Take care to provide only 1 setter and getter for any attribute. The best way to approach is to write down the definition of all the attributes then use eclipse generate setter and getter utility rather than doing it manually. The option comes on right click-> source -> Generate Getter and Setter.
SQL Injection can be done on any input the user can influence that isn't properly escaped before used in a query.
One example would be a get variable like this:
http//www.example.com/user.php?userid=5
Now, if the accompanying PHP code goes something like this:
$query = "SELECT username, password FROM users WHERE userid=" . $_GET['userid'];
// ...
You can easily use SQL injection here too:
http//www.example.com/user.php?userid=5 AND 1=2 UNION SELECT password,username FROM users WHERE usertype='admin'
(of course, the spaces will have to be replaced by %20
, but this is more readable. Additionally, this is just an example making some more assumptions, but the idea should be clear.)
You have to delete Your appname.dll file from your output folder. Cleanup Debug and Release folders. Rebuild and copy to output folder regenerated dll file.
For me, other answers didn't work. I had to go to open Files
and do Invalidate caches and restart
on Intellij. After that, everything worked fine again.
Do you have times associated with your dates? BETWEEN is inclusive, but when you convert 2013-10-18 to a date it becomes 2013-10-18 00:00:000.00. Anything that is logged after the first second of the 18th will not shown using BETWEEN, unless you include a time value.
Try:
SELECT * FROM LOGS WHERE CHECK_IN BETWEEN CONVERT(datetime,'2013-10-17') AND CONVERT(datetime,'2013-10-18 23:59:59:999')
if you want to search the entire day of the 18th.
SQL DATETIME fields have milliseconds. So I added 999 to the field.
This is an odd solution, but it worked for me.
I wanted to uninstall Visual Studio 2015 and do a clean install afterwards, but when I tried to remove it through the Control Panel, it was giving me a generic error.
I fixed it by deleting the Visual Studio 2015 folder in Program Files (x86). After that, the Control Panel uninstall worked fine.
preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);
It's easier using Array.filter
:
var unique = arr.filter(function(elem, index, self) {
return index === self.indexOf(elem);
})
I tried using the solution By @davy-c but had an Exception "System.FormatException: 'Input string was not in a correct format.'", this was due to there still being text past the line number, I modified the code he posted and came up with:
int line = Convert.ToInt32(objErr.ToString().Substring(objErr.ToString().IndexOf("line")).Substring(0, objErr.ToString().Substring(objErr.ToString().IndexOf("line")).ToString().IndexOf("\r\n")).Replace("line ", ""));
This works for me in VS2017 C#.
Make sure that if you have nvarchar(50)in DB row you don't trying to insert more than 50characters in it. Stupid mistake but took me 3 hours to figure it out.
Here is the code I use when I want to preload images before appending them to the page.
It is also important to check if the image is already loaded from the cache (for IE).
//create image to preload:
var imgPreload = new Image();
$(imgPreload).attr({
src: photoUrl
});
//check if the image is already loaded (cached):
if (imgPreload.complete || imgPreload.readyState === 4) {
//image loaded:
//your code here to insert image into page
} else {
//go fetch the image:
$(imgPreload).load(function (response, status, xhr) {
if (status == 'error') {
//image could not be loaded:
} else {
//image loaded:
//your code here to insert image into page
}
});
}
This should do it, let me know if you have trouble with it:
Sub foo()
Dim x As Workbook
Dim y As Workbook
'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")
'Now, copy what you want from x:
x.Sheets("name of copying sheet").Range("A1").Copy
'Now, paste to y worksheet:
y.Sheets("sheetname").Range("A1").PasteSpecial
'Close x:
x.Close
End Sub
Alternatively, you could just:
Sub foo2()
Dim x As Workbook
Dim y As Workbook
'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")
'Now, transfer values from x to y:
y.Sheets("sheetname").Range("A1").Value = x.Sheets("name of copying sheet").Range("A1")
'Close x:
x.Close
End Sub
To extend this to the entire sheet:
With x.Sheets("name of copying sheet").UsedRange
'Now, paste to y worksheet:
y.Sheets("sheet name").Range("A1").Resize( _
.Rows.Count, .Columns.Count) = .Value
End With
And yet another way, store the value as a variable and write the variable to the destination:
Sub foo3()
Dim x As Workbook
Dim y As Workbook
Dim vals as Variant
'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")
'Store the value in a variable:
vals = x.Sheets("name of sheet").Range("A1").Value
'Use the variable to assign a value to the other file/sheet:
y.Sheets("sheetname").Range("A1").Value = vals
'Close x:
x.Close
End Sub
The last method above is usually the fastest for most applications, but do note that for very large datasets (100k rows) it's observed that the Clipboard actually outperforms the array dump:
Copy/PasteSpecial vs Range.Value = Range.Value
That said, there are other considerations than just speed, and it may be the case that the performance hit on a large dataset is worth the tradeoff, to avoid interacting with the Clipboard.
Here is a similar question with some - yet unaccepted - answers. One of them mentions FMJ as a java alternative to JMF.
The best way is to use different database groups. If you want to keep using the master database as usual ($this->db) just turn off persistent connexion configuration option to your secondary database(s). Only master database should work with persistent connexion :
Master database
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "database_name";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
$db['default']['swap_pre'] = "";
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
Secondary database (notice pconnect is set to false)
$db['otherdb']['hostname'] = "localhost";
$db['otherdb']['username'] = "root";
$db['otherdb']['password'] = "";
$db['otherdb']['database'] = "other_database_name";
$db['otherdb']['dbdriver'] = "mysql";
$db['otherdb']['dbprefix'] = "";
$db['otherdb']['pconnect'] = FALSE;
$db['otherdb']['db_debug'] = FALSE;
$db['otherdb']['cache_on'] = FALSE;
$db['otherdb']['cachedir'] = "";
$db['otherdb']['char_set'] = "utf8";
$db['otherdb']['dbcollat'] = "utf8_general_ci";
$db['otherdb']['swap_pre'] = "";
$db['otherdb']['autoinit'] = TRUE;
$db['otherdb']['stricton'] = FALSE;
Then you can use secondary databases as database objects while using master database as usual :
// use master dataabse
$users = $this->db->get('users');
// connect to secondary database
$otherdb = $this->load->database('otherdb', TRUE);
$stuff = $otherdb->get('struff');
$otherdb->insert_batch('users', $users->result_array());
// keep using master database as usual, for example insert stuff from other database
$this->db->insert_batch('stuff', $stuff->result_array());
I know it's kinda too late to reply to this post but since I don't see any clear answer i'd do it anyway...
you might wanna check out the MANIFEST.MF
in META-INF
on your eclipse.
then you might need to add the path of your class files like..
Class-Path: WEB-INF/classes
To compare between latest commit of current branch and a tag:
git log --pretty=oneline HEAD...tag
You could also use a "heredoc":
mongo localhost/db <<EOF
db.dropDatabase()
EOF
Results in output like:
mongo localhost/db <<EOF
db.dropDatabase()
EOF
MongoDB shell version: 2.2.2
connecting to: localhost/db
{ "dropped" : "db", "ok" : 1 }
bye
I like to use heredocs for things like this, in case you want more complex sequence of commands.
Because the glyphicons are now fonts, one can use the contextual classes to apply the appropriate color to the icons.
For example:
<span class="glyphicon glyphicon-info-sign text-info"></span>
adding text-info
to the css will make the icon the info blue color.
<div *ngIf="currentStatus !== ('status1' || 'status2' || 'status3' || 'status4')">
This will allow decimal with exponentiation and upto 2 digits ,
^[+-]?\d+(\.\d{2}([eE](-[1-9]([0-9]*)?|[+]?\d+))?)?$
In order to change date format in the views.py and then assign it to template.
# get the object details
home = Home.objects.get(home_id=homeid)
# get the start date
_startDate = home.home_startdate.strftime('%m/%d/%Y')
# assign it to template
return render_to_response('showme.html'
{'home_startdate':_startDate},
context_instance=RequestContext(request) )
To fix the core question, "how should I detect that these two variables don't have the same value when one of them is null?", I don't like the approach of nvl(my_column, 'some value that will never, ever, ever appear in the data and I can be absolutely sure of that')
because you can't always guarantee that a value won't appear... especially with NUMBERs.
I have used the following:
if (str1 is null) <> (str2 is null) or str1 <> str2 then
dbms_output.put_line('not equal');
end if;
Disclaimer: I am not an Oracle wizard and I came up with this one myself and have not seen it elsewhere, so there may be some subtle reason why it's a bad idea. But it does avoid the trap mentioned by APC, that comparing a null to something else gives neither TRUE nor FALSE but NULL. Because the clauses (str1 is null)
will always return TRUE or FALSE, never null.
(Note that PL/SQL performs short-circuit evaluation, as noted here.)
You missed break statements. Don't forget to use break
-statements even in the default
case.
switch (searchType)
{
case "SearchBooks":
Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
break;
case "SearchAuthors":
Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
break;
default:
Console.WriteLine("Default case handling");
break;
}
For some reason, none of the previous answers worked for me really. This is what worked for me and it works across browsers as well:
.center {
text-align: center;
height: 100%;
/* Safari, Opera, and Chrome */
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-align: center;
/* Firefox */
display: -moz-box;
-moz-box-pack: center;
-moz-box-align: center;
/* Internet Explorer 10 */
display: -ms-flexbox;
-ms-flex-pack: center;
-ms-flex-align: center;
}
This regex is very short and sweet for working.
/^([+]\d{2})?\d{10}$/
Ex: +910123456789 or 0123456789
-> /^ and $/ is for starting and ending
-> The ? mark is used for conditional formatting where before question mark is available or not it will work
-> ([+]\d{2}) this indicates that the + sign with two digits '\d{2}' here you can place digit as per country
-> after the ? mark '\d{10}' this says that the digits must be 10 of length change as per your country mobile number length
This is how this regex for mobile number is working.
+ sign is used for world wide matching of number.
if you want to add the space between than you can use the
[ ]
here the square bracket represents the character sequence and a space is character for searching in regex.
for the space separated digit you can use this regex
/^([+]\d{2}[ ])?\d{10}$/
Ex: +91 0123456789
Thanks ask any question if you have.
color="white"
is not a known attribute to Angular Material.
color attribute can changed to primary
, accent
, and warn
. as said in this doc
your icon inside button works because its parent class button has css class of color:white
, or may be your color="accent"
is white. check the developer tools to find it.
By default, icons will use the current font color
The following is what I use to commit changes on foo
to N=1
days in the past:
git add foo
git commit -m "Update foo"
git commit --amend --date="$(date -v-1d)"
If you want to commit to a even older date, say 3 days back, just change the date
argument: date -v-3d
.
That's really useful when you forget to commit something yesterday, for instance.
UPDATE: --date
also accepts expressions like --date "3 days ago"
or even --date "yesterday"
. So we can reduce it to one line command:
git add foo ; git commit --date "yesterday" -m "Update"
this is just and slice of code, hope works for you
$ch = @curl_init();
@curl_setopt($ch, CURLOPT_URL, 'http://example.com');
@curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
@curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = @curl_exec($ch);
$errno = @curl_errno($ch);
$error = @curl_error($ch);
$response = $response;
$info = @curl_getinfo($ch);
return $info['http_code'];
you should be able to access them from $_POST
variable:
foreach ($_POST as $param_name => $param_val) {
echo "Param: $param_name; Value: $param_val<br />\n";
}
It's of use for everything that has to scale according to the font size.
It's especially useful on browsers which implement zoom by scaling the font size. So if you size all your elements using em
they scale accordingly.
We can concat same column or also other column of the table.
Debian appears to include the following:
I'll test symlinks of each for mpic, etc., and see if that helps the likes of HDF5-openmpi enabled find mpi.h.
Take that back Debian includes symlinks via their alternatives system and it still cannot find the proper paths between HDF5 openmpi packages and mpi.h referenced in the H5public.h header.
Hope the issue is resolved. I just thought to tell my solution.
Map<String, String> env = System.getenv();
new MockUp<System>() {
@Mock
public String getenv(String name)
{
if (name.equalsIgnoreCase( "OUR_OWN_VARIABLE" )) {
return "true";
}
return env.get(name);
}
};
One thing to note, if you are using a freestyle job, you won't be able to access build parameters or the Jenkins JVM's environment UNLESS you are using System Groovy Script build steps. I spent hours googling and researching before gathering enough clues to figure that out.
You can use WebClient.
Or (if you need more fine-grained control over the request) HttpWebRequest
Or, HttpClient in System.Net.Http.dll.
Here's a "translation" to HttpWebRequest (needed rather than WebClient in order to set the referrer). (Uses System.Net and System.IO):
HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create(requestUrl))
http.Referer = referrer;
HttpWebResponse response = (HttpWebResponse )http.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
string responseJson = sr.ReadToEnd();
// more stuff
}
Thanks for the help everyone, rejecting the promise in .catch()
solved my issue:
export function fetchVehicle(id) {
return dispatch => {
return dispatch({
type: 'FETCH_VEHICLE',
payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
.then(status)
.then(res => res.json())
.catch(error => {
return Promise.reject()
})
});
};
}
function status(res) {
if (!res.ok) {
throw new Error(res.statusText);
}
return res;
}
in my case it was not related to the path or filename. If filemtime(), fileatime() or filectime() don't work, try stat().
$filedate = date_create(date("Y-m-d", filectime($file)));
becomes
$stat = stat($directory.$file);
$filedate = date_create(date("Y-m-d", $stat['ctime']));
that worked for me.
Complete snippet for deleting files by number of days:
$directory = $_SERVER['DOCUMENT_ROOT'].'/directory/';
$files = array_slice(scandir($directory), 2);
foreach($files as $file)
{
$extension = substr($file, -3, 3);
if ($extension == 'jpg') // in case you only want specific files deleted
{
$stat = stat($directory.$file);
$filedate = date_create(date("Y-m-d", $stat['ctime']));
$today = date_create(date("Y-m-d"));
$days = date_diff($filedate, $today, true);
if ($days->days > 1)
{
unlink($directory.$file);
}
}
}
If you are just going to verify/validate the entered user name and password, use the Rfc2898DerivedBytes class (also known as Password Based Key Derivation Function 2 or PBKDF2). This is more secure than using encryption like Triple DES or AES because there is no practical way to go from the result of RFC2898DerivedBytes back to the password. You can only go from a password to the result. See Is it ok to use SHA1 hash of password as a salt when deriving encryption key and IV from password string? for an example and discussion for .Net or String encrypt / decrypt with password c# Metro Style for WinRT/Metro.
If you are storing the password for reuse, such as supplying it to a third party, use the Windows Data Protection API (DPAPI). This uses operating system generated and protected keys and the Triple DES encryption algorithm to encrypt and decrypt information. This means your application does not have to worry about generating and protecting the encryption keys, a major concern when using cryptography.
In C#, use the System.Security.Cryptography.ProtectedData class. For example, to encrypt a piece of data, use ProtectedData.Protect()
:
// Data to protect. Convert a string to a byte[] using Encoding.UTF8.GetBytes().
byte[] plaintext;
// Generate additional entropy (will be used as the Initialization vector)
byte[] entropy = new byte[20];
using(RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(entropy);
}
byte[] ciphertext = ProtectedData.Protect(plaintext, entropy,
DataProtectionScope.CurrentUser);
Store the entropy and ciphertext securely, such as in a file or registry key with permissions set so only the current user can read it. To get access to the original data, use ProtectedData.Unprotect()
:
byte[] plaintext= ProtectedData.Unprotect(ciphertext, entropy,
DataProtectionScope.CurrentUser);
Note that there are additional security considerations. For example, avoid storing secrets like passwords as a string
. Strings are immutable, being they cannot be notified in memory so someone looking at the application's memory or a memory dump may see the password. Use SecureString or a byte[] instead and remember to dispose or zero them as soon as the password is no longer needed.
I am on Android Studio. I got this error when min/targetSDKVersion were set to 17. While looking thro this thread, I tried to change the minSDKVersion, voila..problem fixed. Go figure.. :(
android:minSdkVersion="17"
android:targetSdkVersion="17" />
Even I too faced similar issue,
fatal error RC1015: cannot open include file 'afxres.h'. from this code
Replacing afxres.h with Winresrc.h and declaring IDC_STATIC as -1 worked for me. (Using visual studio Premium 2012)
//#include "afxres.h"
#include "WinResrc.h"
#define IDC_STATIC -1
On Webpack 2 I tried all 12 devtool options. The following options link to the original file in the console and preserve line numbers. See the note below re: lines only.
https://webpack.js.org/configuration/devtool
devtool best dev options
build rebuild quality look
eval-source-map slow pretty fast original source worst
inline-source-map slow slow original source medium
cheap-module-eval-source-map medium fast original source (lines only) worst
inline-cheap-module-source-map medium pretty slow original source (lines only) best
lines only
Source Maps are simplified to a single mapping per line. This usually means a single mapping per statement (assuming you author is this way). This prevents you from debugging execution on statement level and from settings breakpoints on columns of a line. Combining with minimizing is not possible as minimizers usually only emit a single line.
REVISITING THIS
On a large project I find ... eval-source-map rebuild time is ~3.5s ... inline-source-map rebuild time is ~7s
If you want to compare with a particular date , You can directly write it like :
select * from `table_name` where timestamp >= '2018-07-07';
// here the timestamp is the name of the column having type as timestamp
or
For fetching today date , CURDATE() function is available , so :
select * from `table_name` where timestamp >= CURDATE();
.push() will add elements to the end of an array.
Use .unshift() if need to add some element to the beginning of array i.e:
items.unshift({'id':5});
Demo:
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];_x000D_
items.unshift({'id': 0});_x000D_
console.log(items);
_x000D_
And use .splice() in case you want to add object at a particular index i.e:
items.splice(2, 0, {'id':5});
// ^ Given object will be placed at index 2...
Demo:
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];_x000D_
items.splice(2, 0, {'id': 2.5});_x000D_
console.log(items);
_x000D_
You can just use the method uniq
. Assuming your array is ary
, call:
ary.uniq{|x| x.user_id}
and this will return a set with unique user_id
s.
Until 24 hrs.
As Duration.format
is deprecated, with [email protected]
const seconds = 123;
moment.utc(moment.duration(seconds,'seconds').as('milliseconds')).format('HH:mm:ss');
You can use these kind of programs to emulate an apache web server and run PHP on your computer:
Just for completeness here's the solution involving my StreamEx library:
String[] names = {"Sam","Pamela", "Dave", "Pascal", "Erik"};
EntryStream.of(names)
.filterKeyValue((idx, str) -> str.length() <= idx+1)
.values().toList();
Here we create an EntryStream<Integer, String>
which extends Stream<Entry<Integer, String>>
and adds some specific operations like filterKeyValue
or values
. Also toList()
shortcut is used.
this does not disable the spam checking
div.g-recaptcha > div.grecaptcha-badge {
width:0 !important;
}
Add:
display: inline-block;
to the style of your td
.
Add:
display: inline-block;
word-break: break-word;
to the style of your td
.
Note:
Mind that, as for now, break-word
is not part of the standard specification for webkit; therefore, you might be interested in employing the break-all
instead. This alternative value provides a undoubtedly drastic solution; however, it conforms to the standard.
Add:
display: inline-block;
word-break: break-word;
to the style of your td
.
The previous paragraph applies to Opera in a similar way.
Had an issue while uploading an image and couldn't delete it and found a solution. gl hf
//C# .NET
var image = Image.FromFile(filePath);
image.Dispose(); // this removes all resources
//later...
File.Delete(filePath); //now works
According to the MDN reference page, includes
is not supported on Internet Explorer. The simplest alternative is to use indexOf
, like this:
if(window.location.hash.indexOf("?") >= 0) {
...
}
td.setAttribute('rowspan',x);
Instead of Windows PowerShell
, find the item in the Start Menu called SharePoint 2013 Management Shell
:
struct Rect
{
Rect(int x1, int x2, int y1, int y2)
: x1(x1), x2(x2), y1(y1), y2(y2)
{
assert(x1 < x2);
assert(y1 < y2);
}
int x1, x2, y1, y2;
};
//some area of the r1 overlaps r2
bool overlap(const Rect &r1, const Rect &r2)
{
return r1.x1 < r2.x2 && r2.x1 < r1.x2 &&
r1.y1 < r2.y2 && r2.x1 < r1.y2;
}
//either the rectangles overlap or the edges touch
bool touch(const Rect &r1, const Rect &r2)
{
return r1.x1 <= r2.x2 && r2.x1 <= r1.x2 &&
r1.y1 <= r2.y2 && r2.x1 <= r1.y2;
}
If your object looks like this:
obj = {
"_id":"5078c3a803ff4197dc81fbfb",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 1"
}
Probably the simplest method in JavaScript is:
obj.id = obj._id
del object['_id']
As a result, you will get:
obj = {
"id":"5078c3a803ff4197dc81fbfb",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 1"
}
Think the class should be defined as:
- (void) myTestWithSomeString:(NSString *) astring{
NSLog(@"hi, %s", astring);
}
You only have a single parameter so you should only have a single :
You might want to consider using %@ in your NSLog also - it is just a good habit to get into - will then write out any object - not just strings.
Here is the one of the better solutions.
DECLARE @i int
DECLARE @curren_val int
DECLARE @numrows int
create table #Practitioner (idx int IDENTITY(1,1), PractitionerId int)
INSERT INTO #Practitioner (PractitionerId) values (10),(20),(30)
SET @i = 1
SET @numrows = (SELECT COUNT(*) FROM #Practitioner)
IF @numrows > 0
WHILE (@i <= (SELECT MAX(idx) FROM #Practitioner))
BEGIN
SET @curren_val = (SELECT PractitionerId FROM #Practitioner WHERE idx = @i)
--Do something with Id here
PRINT @curren_val
SET @i = @i + 1
END
Here i've add some values in the table beacuse, initially it is empty.
We can access or we can do anything in the body of the loop and we can access the idx by defining it inside the table definition.
BEGIN
SET @curren_val = (SELECT PractitionerId FROM #Practitioner WHERE idx = @i)
--Do something with Id here
PRINT @curren_val
SET @i = @i + 1
END
I made two examples from what I think your question might be:
Check this out for storing additional values. It uses data attributes to store the other value:
PUT and PATCH methods are similar in nature, but there is a key difference.
PUT - in PUT request, the enclosed entity would be considered as the modified version of a resource which residing on server and it would be replaced by this modified entity.
PATCH - in PATCH request, enclosed entity contains the set of instructions that how the entity which residing on server, would be modified to produce a newer version.
Instead Of using find(), One of the easy way is the Use of 'in' as above.
if 'substring' is present in 'str' then if part will execute otherwise else part will execute.
Complementing the previous answers, one big difference between both is that Visual Studio Code comes in a so called "portable" version that does not require full administrative permissions to run on Windows and can be placed in a removable drive for convenience.
Somewhere in that mess, the non-breaking spaces from the HTML template (the s) are encoding as ISO-8859-1 so that they show up incorrectly as an "Â" character
That'd be encoding to UTF-8 then, not ISO-8859-1. The non-breaking space character is byte 0xA0 in ISO-8859-1; when encoded to UTF-8 it'd be 0xC2,0xA0, which, if you (incorrectly) view it as ISO-8859-1 comes out as "Â "
. That includes a trailing nbsp which you might not be noticing; if that byte isn't there, then something else has mauled your document and we need to see further up to find out what.
What's the regexp, how does the templating work? There would seem to be a proper HTML parser involved somewhere if your
strings are (correctly) being turned into U+00A0 NON-BREAKING SPACE characters. If so, you could just process your template natively in the DOM, and ask it to serialise using the ASCII encoding to keep non-ASCII characters as character references. That would also stop you having to do regex post-processing on the HTML itself, which is always a highly dodgy business.
Well anyway, for now you can add one of the following to your document's <head>
and see if that makes it look right in the browser:
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta charset="utf-8">
If you've done that, then any remaining problem is ActivePDF's fault.
In your AVD advanced settings, you should be able to set front and back cameras to Webcam()
or Emulated
.
I met this issue right on when I first install the Heroku's POSTGRES.app thing. After one morning trial and error i think this one line of code solved problem. As describe earlier, this is because postgresql does not have default role the first time it is set up. And we need to set that.
sovanlandy=# CREATE ROLE postgres LOGIN;
You must log in to your respective psql console to use this psql command.
Also noted that, if you already created the role 'postgre' but still get permission errors, you need to alter with command:
sovanlandy=# ALTER ROLE postgres LOGIN;
Hope it helps!
in order to Removing The Dotted Outline href link you can write in your css file:
a {
outline: 0;
}
I have used a temporary file to do this in the past, like this below.
DIR /B *.DAT | FIND.EXE /C /V "" > COUNT.TXT
FOR /F "tokens=1" %%f IN (COUNT.TXT) DO (
IF NOT %%f==6 SET _MSG=File count is %%f, and 6 were expected. & DEL COUNT.TXT & ECHO #### ERROR - FILE COUNT WAS %%f AND 6 WERE EXPECTED. #### >> %_LOGFILE% & GOTO SENDMAIL
)
The best and easiest way to clear a JLIST is:
myJlist.setListData(new String[0]);
Have a look at this answer, it discusses internally routing HTTP through direct Objective-C calls to an HTTP-capable layer/embedded web server (let's assume that the HTTP server code is within the same application that wishes to display the HTML within a web widget).
This has the advantage of being slightly more secure (and possibly faster) as no port(s) should be exposed.
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
If I understand you need following code. (passing expression lambda by parameter) The Method
public static void Method(Expression<Func<int, bool>> predicate) {
int[] number={1,2,3,4,5,6,7,8,9,10};
var newList = from x in number
.Where(predicate.Compile()) //here compile your clausuly
select x;
newList.ToList();//return a new list
}
Calling method
Method(v => v.Equals(1));
You can do the same in their class, see this is example.
public string Name {get;set;}
public static List<Class> GetList(Expression<Func<Class, bool>> predicate)
{
List<Class> c = new List<Class>();
c.Add(new Class("name1"));
c.Add(new Class("name2"));
var f = from g in c.
Where (predicate.Compile())
select g;
f.ToList();
return f;
}
Calling method
Class.GetList(c=>c.Name=="yourname");
I hope this is useful
For development purpose https://mailtrap.io/ provides you with all the settings that needs to be added in .env file. Eg:
Host: mailtrap.io
Port: 25 or 465 or 2525
Username: cb1d1475bc6cce
Password: 7a330479c15f99
Auth: PLAIN, LOGIN and CRAM-MD5
TLS: Optional
Otherwise for implementation purpose you can get the smtp credentials to be added in .env file from the mail (like gmail n all)
After addition make sure to restart the server
May I suggest you to have a look at the tool Jenv
This will allow you to switch at any time between your installed JVMs.
Simply as:
jenv global oracle-1.7
then later for test purpose:
jenv global oracle-1.6
And you have much more commands available.
If your jar file already has an absolute pathname as shown, it is particularly easy:
cd /where/you/want/it; jar xf /path/to/jarfile.jar
That is, you have the shell executed by Python change directory for you and then run the extraction.
If your jar file does not already have an absolute pathname, then you have to convert the relative name to absolute (by prefixing it with the path of the current directory) so that jar
can find it after the change of directory.
The only issues left to worry about are things like blanks in the path names.
The problem is caused because the code you are running was created in an older API level, And your present SDK Manager doesn't support running them. So do try the following; 1.Install the SDK Manager that support API level 23. Go to >SDK Manager, >Android SDK , then select API 23 and install. 2.second alternative is to update your build.grade app module to change compileSdkVersion,compile,and other numbers to your currently supported API level.
Note:please ensure to check the API and Revision numbers and change them exactly. otherwise Your project won't synchronize
I just inherited an old VB.NET console application and needed to set up a Global Exception Handler. Since this question mentions VB.NET a few times and is tagged with VB.NET, but all the other answers here are in C#, I thought I would add the exact syntax for a VB.NET application as well.
Public Sub Main()
REM Set up Global Unhandled Exception Handler.
AddHandler System.AppDomain.CurrentDomain.UnhandledException, AddressOf MyUnhandledExceptionEvent
REM Do other stuff
End Sub
Public Sub MyUnhandledExceptionEvent(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
REM Log Exception here and do whatever else is needed
End Sub
I used the REM
comment marker instead of the single quote here because Stack Overflow seemed to handle the syntax highlighting a bit better with REM
.
Bit heavy because of using pandas but works:
import pandas as pd
pd.to_datetime(msec_from_java, unit='ms').to_pydatetime()
private String getColumn(int c) {
String s = "";
do {
s = (char)('A' + (c % 26)) + s;
c /= 26;
} while (c-- > 0);
return s;
}
Its not exactly base 26, there is no 0 in the system. If there was, 'Z' would be followed by 'BA' not by 'AA'.
To answer the question more generaly how to redirect standard output to a variable ?
do the following :
from io import StringIO
import sys
result = StringIO()
sys.stdout = result
result_string = result.getvalue()
If you need to do that only in some function do the following :
old_stdout = sys.stdout
# your function containing the previous lines
my_function()
sys.stdout = old_stdout
A simple way of looking at HTTP 301 vs. 302 redirects is:
Suppose you have a bookmark to "http://sample.com/sample". You use a browser to go there.
A 302 redirect to a different URL at this point would mean that you should keep your bookmark to "http://sample.com/sample". This is because the destination URL may change in the future.
A 301 redirect to a different URL would mean that your bookmark should change to point to the new URL as it is a permanent redirect.
JNZ is short for "Jump if not zero (ZF = 0)", and NOT "Jump if the ZF is set".
If it's any easier to remember, consider that JNZ and JNE (jump if not equal) are equivalent. Therefore, when you're doing cmp al, 47
and the content of AL
is equal to 47, the ZF is set, ergo the jump (if Not Equal - JNE) should not be taken.
If you are doing Unity Project. You can get this error.
Command PhaseScriptExecution failed with a nonzero exit code
The solution is very simple
https://forum.unity.com/threads/error-on-build.561706/
Pre-requisites: Have cocoapods installed
Not Needed: 1. Install "cocoapods"
for installing run following line in your terminal: $sudo gem install cocoapods
chmod +x MapFileParser.sh
chmod +x process_symbols.sh
It worked for me)
I think that installing "cocoapods" is not necessary, only step 3 and 4 enough to solve, but it does not work, you can try it.
I've come across this problem myself. In my case, resetting IE was the quickest solution to the problem:
Install Python opencv
pip install opencv-python
and instead of using ..
cv2.SIFT()
Use
cv2.SIFT_create()
working code using opencv-python below
import cv2
img1 = cv2.imread('yourimg.png',0)
sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1,None) #keypoint and descriptors
...
you can also install "opencv-contrib-python" and use "cv2.xfeatures2d.SIFT_create()" but that is secondary and up to you.. working code using the python package opencv-contrib-python
import cv2
img1 = cv2.imread('yourimg.png',0)
sift = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1,None) #keypoint and descriptors
Thanks
Any answer didn't help in my case.
What eventually helped was removing bower
and gulp
(I use both of them in my project):
npm remove -g bower
npm remove -g gulp
After that I installed them again:
npm install -g bower
npm install -g gulp
Now it works just fine.
Sub Scrape()
Dim Browser As InternetExplorer
Dim Document As htmlDocument
Dim Elements As IHTMLElementCollection
Dim Element As IHTMLElement
Set Browser = New InternetExplorer
Browser.Visible = True
Browser.navigate "http://www.stackoverflow.com"
Do While Browser.Busy And Not Browser.readyState = READYSTATE_COMPLETE
DoEvents
Loop
Set Document = Browser.Document
Set Elements = Document.getElementById("hmenus").getElementsByTagName("li")
For Each Element In Elements
Debug.Print Element.innerText
'Questions
'Tags
'Users
'Badges
'Unanswered
'Ask Question
Next Element
Set Document = Nothing
Set Browser = Nothing
End Sub
First at the beginning of an Update to a huge object:
/*General note to all who tread in the <ObjectName>() code...
* The SetOriginals() method from the BaseEntity class should be called (and only called) right after the Get() method
* call as seen above. Calling the SetOriginals method elsewhere will result in bugs and all kinds of other nasty suprises.
*/
Then after some 200 lines of logic to update the object:
//Attempt to explain this confusing mess of code:
//First time you save an actual absence this is what happens:
//0. The first save saves to the <TableName> table (among other things). (Fig. A)
//1. The <CalculationMethod> method is called next which inserts to the <OtherTableName> table.
//(This is the table that keeps track of credits to the case.) (Fig. B)
//2. So then you have to call <UpdateCalculations> to move the <TableName> records to the <ThirdTableName> table. (Fig. C)
//3. Then you go back and run calculations since you have the debits table (<ThirdTableName>) populated. (Fig D.)
//4. Then a final save to save the calculations back to the case. (Fig. E)
//Yeah, I know what you're thinking: this sucks. 10/01/07 XXX
And the developer was right... This sucked HARD!
list_ = list(range(9)) print(list_[1::2])
// Pass in function expiration date to check token
function checkToken(exp) {
if (Date.now() <= exp * 1000) {
console.log(true, 'token is not expired')
} else {
console.log(false, 'token is expired')
}
}
Set content type. Look at this method.
message.setContent("<h1>Hello</h1>", "text/html");
I know I'm late to the party, but try this...
SELECT
`Train`,
`Dest`,
SUBSTRING_INDEX(GROUP_CONCAT(`Time` ORDER BY `Time` DESC), ",", 1) AS `Time`
FROM TrainTable
GROUP BY Train;
Src: Group Concat Documentation
Edit: fixed sql syntax
More detail on Mr Dredel's answer and tuinstoel's comment. The data in the column will be stored in its specific case, but you can change your session's case-sensitivity for matching.
You can change either the session or the database to use linguistic or case insensitive searching. You can also set up indexes to use particular sort orders.
eg
ALTER SESSION SET NLS_SORT=BINARY_CI;
Once you start getting into non-english languages, with accents and so on, there's additional support for accent-insensitive. Some of the capabilities vary by version, so check out the Globablization document for your particular version of Oracle. The latest (11g) is here
If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py
with
import camelot
tables = camelot.read_pdf('foo.pdf')
You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.
tables.export('foo.csv', f='csv', compress=False)
Edit: tabula-py
appears roughly 6 times faster than camelot-py
so that should be used instead.
import camelot
import cProfile
import pstats
import tabula
cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt
cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt
print(time_tabula, time_camelot, time_camelot/time_tabula)
gave
1.8495559890000015 11.057014036000016 5.978199147125147
Yes there is a major difference between the two methods Use delete_all if you want records to be deleted quickly without model callbacks being called
If you care about your models callbacks then use destroy_all
From the official docs
http://apidock.com/rails/ActiveRecord/Base/destroy_all/class
destroy_all(conditions = nil) public
Destroys the records matching conditions by instantiating each record and calling its destroy method. Each object’s callbacks are executed (including :dependent association options and before_destroy/after_destroy Observer methods). Returns the collection of objects that were destroyed; each will be frozen, to reflect that no changes should be made (since they can’t be persisted).
Note: Instantiation, callback execution, and deletion of each record can be time consuming when you’re removing many records at once. It generates at least one SQL DELETE query per record (or possibly more, to enforce your callbacks). If you want to delete many rows quickly, without concern for their associations or callbacks, use delete_all instead.
From the command line:
psql my_database -c 'SHOW SERVER_ENCODING'
From within psql
, an SQL IDE or an API:
SHOW SERVER_ENCODING
For SQL Server 2008, the command is:
ALTER DATABASE ExampleDB SET RECOVERY SIMPLE
DBCC SHRINKFILE('ExampleDB_log', 0, TRUNCATEONLY)
ALTER DATABASE ExampleDB SET RECOVERY FULL
This reduced my 14GB log file down to 1MB.
For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.
Not always. NaN is a counterexample. But usually, identity (is
) implies equality (==
). The converse is not true: Two distinct objects can have the same value.
Also, is it generally considered better to just use '==' by default, even when comparing int or Boolean values?
You use ==
when comparing values and is
when comparing identities.
When comparing ints (or immutable types in general), you pretty much always want the former. There's an optimization that allows small integers to be compared with is
, but don't rely on it.
For boolean values, you shouldn't be doing comparisons at all. Instead of:
if x == True:
# do something
write:
if x:
# do something
For comparing against None
, is None
is preferred over == None
.
I've always liked to use 'is' because I find it more aesthetically pleasing and pythonic (which is how I fell into this trap...), but I wonder if it's intended to just be reserved for when you care about finding two objects with the same id.
Yes, that's exactly what it's for.
//for normal state:
btnSecurite.setTitle("TextHear", for: .normal)
I did it using this command:
syntax: adb push filename.extension /sdcard/0/
example: adb push UPDATE-SuperSU-v2.01.zip /sdcard/0/
With ES6+ you can just do [${variable}
]
NSURL *url= [NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"userId=2323";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
Watch again:
char dest[5];
char src[5] = "test";
printf("String: %s\n", do_something(dest, src));
Focus on this line:
printf("String: %s\n", do_something(dest, src));
You can clearly see that the do_something function is not declared!
If you look a little further,
printf("String: %s\n", do_something(dest, src));
char *do_something(char *dest, const char *src)
{
return dest;
}
you will see that you declare the function after you use it.
You will need to modify this part with this code:
char *do_something(char *dest, const char *src)
{
return dest;
}
printf("String: %s\n", do_something(dest, src));
Cheers ;)
For Firefox use
iframewin.print()
for IE use
iframedocument.execCommand('print', false, null);
see also Unable to print an iframe on IE using JavaScript, prints parent page instead
DateTimeFormatter.ISO_INSTANT.format(Instant.now())
This saves you from having to convert to UTC. However, some other language's time frameworks may not support the milliseconds so you should do
DateTimeFormatter.ISO_INSTANT.format(Instant.now().truncatedTo(ChronoUnit.SECONDS))
For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.
However, if you had multiple rules like this:
#foo > ul > li > ul > li > a:nth-child(3n+1) {
color: red;
}
#foo > ul > li > ul > li > a:nth-child(3n+2) {
color: green;
}
#foo > ul > li > ul > li > a:nth-child(3n+3) {
color: blue;
}
You could condense them to one of the following:
/* Sass */
#foo > ul > li > ul > li
> a:nth-child(3n+1)
color: red
> a:nth-child(3n+2)
color: green
> a:nth-child(3n+3)
color: blue
/* SCSS */
#foo > ul > li > ul > li {
> a:nth-child(3n+1) { color: red; }
> a:nth-child(3n+2) { color: green; }
> a:nth-child(3n+3) { color: blue; }
}
In Swift 1.2:
@IBAction func openLink {
let pth = "http://www.google.com"
if let url = NSURL(string: pth){
UIApplication.sharedApplication().openURL(url)
}
Using the mysqli PHP driver, you can't get the insert_id after you commit.
The real solution is this:
function add_post($post_data){
$this->db->trans_begin();
$this->db->insert('posts',$post_data);
$item_id = $this->db->insert_id();
if( $this->db->trans_status() === FALSE )
{
$this->db->trans_rollback();
return( 0 );
}
else
{
$this->db->trans_commit();
return( $item_id );
}
}
Source for code structure: https://codeigniter.com/user_guide/database/transactions.html#running-transactions-manually
You can not put
$connection = sqlite_open("[path]/data/users.sqlite", 0666);
outside the class construction. You have to put that line inside a function or the constructor but you can not place it where you have now.
The nil pointer dereference is in line 65 which is the defer in
res, err := client.Do(req)
defer res.Body.Close()
if err != nil {
return nil, err
}
If err!= nil then res==nil and res.Body panics. Handle err before defering the res.Body.Close().
In static class, if you are getting information from xml or reg, class tries to initialize all properties. therefore, you should control if the config variable is there otherwise properties will not initialize so the class.
Check xml referance variable is there, Check reg referance variable is is there, Make sure you handle if they are not there.
$username = filter_input(INPUT_POST, 'userName', FILTER_SANITIZE_STRING);
if ($username == '') {$username = 'Anonymous';}
Best practice - always filter inputs, sanitize string is ok, but you're better off using a custom callback function to really filter out what's not acceptable. Then check the now-safe variable if it is null/empty and if it is, set to Anonymous. Does not require 'else' statement as it was set if it existed on the first line.
No built-in function. It depends what you mean by week of month. You might mean whether it's in the first 7 days (week 1), the second 7 days (week 2), etc. In that case it would just be
(DATEPART(day,@Date)-1)/7 + 1
If you want to use the same week numbering as is used with DATEPART(week,), you could use the difference between the week numbers of the first of the month and the date in question (+1):
(DATEPART(week,@Date)- DATEPART(week,DATEADD(m, DATEDIFF(m, 0, @Date), 0))) + 1
Or, you might need something else, depending on what you mean by the week number.
IE is picky about the window name argument. It doesn't like spaces, dashes, or other punctuation.
An alternative, you can also use fopen
$params = array('http' => array(
'method' => 'POST',
'content' => 'toto=1&tata=2'
));
$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
throw new Exception("Problem with $sUrl, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false)
{
throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
It seems me there was a network issue. On your side, or on Maven side, or anywhere in the middle. Just try again later.
If the error is permanent, check your network settings. If you are behind a proxy, you need the following in you ~/.m2/settings.xml:
<proxies>
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>proxyuser</username>
<password>proxypass</password>
<host>proxy.host.net</host>
<port>80</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
</proxies>
Oracle SQL Developer > View > DBA > Select your connection > Expand > Security > Users > Right click your user > Create like > Fill in fields > Copy SQL script > Close
If your user has object privileges, do this also
Oracle SQL Developer > View > DBA > Select your connection > Expand > Security > Users > Double click your user > Object Privs > Select all data > Right click > Export > Export as text file
Edit that text file to grant object privileges to your user.
Use a foreach loop, it loops through all the key=>value pairs:
foreach($array as $key=>$value){
print "$key holds $value\n";
}
Or to answer your question completely:
foreach($array as $value){
print $value."\n";
}
//create the url
$profile_pic = "http://graph.facebook.com/".$uid."/picture";
//echo the image out
echo "<img src=\"" . $profile_pic . "\" />";
Works fine for me
Based on the answer of gengkev, I created functions for both ways, because BlobBuilder can handle String and ArrayBuffer:
function string2ArrayBuffer(string, callback) {
var bb = new BlobBuilder();
bb.append(string);
var f = new FileReader();
f.onload = function(e) {
callback(e.target.result);
}
f.readAsArrayBuffer(bb.getBlob());
}
and
function arrayBuffer2String(buf, callback) {
var bb = new BlobBuilder();
bb.append(buf);
var f = new FileReader();
f.onload = function(e) {
callback(e.target.result)
}
f.readAsText(bb.getBlob());
}
A simple test:
string2ArrayBuffer("abc",
function (buf) {
var uInt8 = new Uint8Array(buf);
console.log(uInt8); // Returns `Uint8Array { 0=97, 1=98, 2=99}`
arrayBuffer2String(buf,
function (string) {
console.log(string); // returns "abc"
}
)
}
)
The document says that you can use values to group the queryset .
class Travel(models.Model):
interest = models.ForeignKey(Interest)
user = models.ForeignKey(User)
time = models.DateTimeField(auto_now_add=True)
# Find the travel and group by the interest:
>>> Travel.objects.values('interest').annotate(Count('user'))
<QuerySet [{'interest': 5, 'user__count': 2}, {'interest': 6, 'user__count': 1}]>
# the interest(id=5) had been visited for 2 times,
# and the interest(id=6) had only been visited for 1 time.
>>> Travel.objects.values('interest').annotate(Count('user', distinct=True))
<QuerySet [{'interest': 5, 'user__count': 1}, {'interest': 6, 'user__count': 1}]>
# the interest(id=5) had been visited by only one person (but this person had
# visited the interest for 2 times
You can find all the books and group them by name using this code:
Book.objects.values('name').annotate(Count('id')).order_by() # ensure you add the order_by()
You can watch some cheet sheet here.
There many cases where script Manager may give problem like that. you Try This First add Script Manager in appropriate Placeholder or any place Holder which appears before the content in which Ajax Control is used.
We need to add ScriptManager while using any AJAX Control not only update Panel.
<asp:ScriptManager ID="ScriptManger1" runat="Server" />
If you are using Latest Ajax Control Toolkit (I am not sure about version 4.0 or 4.5) you need to use that Particular ToolkitScriptManager and not ScriptManager from default Ajax Extensions.
You can use only one ScriptManager or ToolKitScriptManager on page, If you have added it on Master Page you no need to add it again on Web Page.
The problem mentioned here may because of ContentPlaceHolder Please Check how many content place holders you have on your master page. Lets take an example if you have 2 content Placeholders "Head" and "ContentPlaceHolder1" on Master Page and ContentPlaceHolder1 is your Content Page.please check below code I added here my ScriptManager on Second Placeholder just below there is update panel.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder id="MainContent" runat="server">
<asp:ScriptManager ID="ScriptManger1" runat="Server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
Most of us make mistake while designing web form when we choose masterpage by default on web page there are equal number of placeholders as of MasterPage.
<%@ Page Title="" Language="C#" MasterPageFile="~/Master Pages/Home.master" AutoEventWireup="true" CodeFile="frmCompanyLogin.aspx.cs" Inherits="Authentication_frmCompanyLogin" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
</asp:Content>
We no need to remove any PlaceHolder it is guiding structure but you must have to add the web form Contents in Same PlaceHolder where you added your ScriptManager(on Master Page) or add Script Manager in appropriate Placeholder or any place Holder which appears before the content in which Ajax Control is used.
Query for just a single known column:
session.query(MyTable.col1).count()
My problem was that I wanted all the columns in a row to have the same background. I grouped both by row and by column, and with the top two solutions here I got all the rows in column 1 with a colored background, all the rows in column 2 with a white background, all the rows in column 3 with a colored background, and so on. It's as if RowNumber
and bOddRow
(of Catch22's solution) pay attention to my column group instead of ignoring that and only alternating with a new row.
What I wanted is for all the columns in row 1 to have a white background, then all the columns in row 2 to have a colored background, then all the columns in row 3 to have a white background, and so on. I got this effect by using the selected answer but instead of passing Nothing
to RowNumber
, I passed the name of my column group, e.g.
=IIf(RowNumber("MyColumnGroupName") Mod 2 = 0, "AliceBlue", "Transparent")
Thought this might be useful to someone else.
You can put it like this
assertTrue("your fail message ",Long.parseLong(previousTokenValues[1]) > Long.parseLong(currentTokenValues[1]));
Here's how to do with cv2 in Python:
# Create a blank 300x300 black image
image = np.zeros((300, 300, 3), np.uint8)
# Fill image with red color(set each pixel to red)
image[:] = (0, 0, 255)
Here's more complete example how to create new blank image filled with a certain RGB color
import cv2
import numpy as np
def create_blank(width, height, rgb_color=(0, 0, 0)):
"""Create new image(numpy array) filled with certain color in RGB"""
# Create black blank image
image = np.zeros((height, width, 3), np.uint8)
# Since OpenCV uses BGR, convert the color first
color = tuple(reversed(rgb_color))
# Fill image with color
image[:] = color
return image
# Create new blank 300x300 red image
width, height = 300, 300
red = (255, 0, 0)
image = create_blank(width, height, rgb_color=red)
cv2.imwrite('red.jpg', image)
It is better to process HTML as a template than to build nodes via JavaScript (HTML is not XML after all.) You can keep your IFRAME's HTML syntax clean by using a template and then appending the template's contents into another DIV.
<div id="placeholder"></div>
<script id="iframeTemplate" type="text/html">
<iframe src="...">
<!-- replace this line with alternate content -->
</iframe>
</script>
<script type="text/javascript">
var element,
html,
template;
element = document.getElementById("placeholder");
template = document.getElementById("iframeTemplate");
html = template.innerHTML;
element.innerHTML = html;
</script>
I have made some researches on this subject recently. The way to implement it has to be different if the field is a TEXT field, a non unique field.
I have made some tests with a TEXT field. Considering the fact that we have a table with 1M entries. 37 entries are equal to 'something':
SELECT * FROM test WHERE text LIKE '%something%' LIMIT 1
with
mysql_num_rows()
: 0.039061069488525s. (FASTER)SELECT count(*) as count FROM test WHERE text LIKE '%something%
:
16.028197050095s.SELECT EXISTS(SELECT 1 FROM test WHERE text LIKE '%something%')
:
0.87045907974243s.SELECT EXISTS(SELECT 1 FROM test WHERE text LIKE '%something%' LIMIT 1)
: 0.044898986816406s.But now, with a BIGINT PK field, only one entry is equal to '321321' :
SELECT * FROM test2 WHERE id ='321321' LIMIT 1
with
mysql_num_rows()
: 0.0089840888977051s.SELECT count(*) as count FROM test2 WHERE id ='321321'
: 0.00033879280090332s.SELECT EXISTS(SELECT 1 FROM test2 WHERE id ='321321')
: 0.00023889541625977s.SELECT EXISTS(SELECT 1 FROM test2 WHERE id ='321321' LIMIT 1)
: 0.00020313262939453s. (FASTER)Have you tried this (using HttpClient version 4):
String encoding = Base64Encoder.encode(user + ":" + pwd);
HttpPost httpPost = new HttpPost("http://host:post/test/login");
httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoding);
System.out.println("executing request " + httpPost.getRequestLine());
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
just check out if you have this problem "vt-x is disabled in bios"
in this case you need to enable virtualization technology bios
Use below code to generate files on fly..
<? //Generate text file on the fly
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=savethis.txt");
// do your Db stuff here to get the content into $content
print "This is some text...\n";
print $content;
?>
I believe the async library will provide you a very elegant way to do this. While promises and callbacks can get a little hard to juggle with, async can give neat patterns to streamline your thought process. To run functions in serial, you would need to put them in an async waterfall. In async lingo, every function is called a task
that takes some arguments and a callback
; which is the next function in the sequence. The basic structure would look something like:
async.waterfall([
// A list of functions
function(callback){
// Function no. 1 in sequence
callback(null, arg);
},
function(arg, callback){
// Function no. 2 in sequence
callback(null);
}
],
function(err, results){
// Optional final callback will get results for all prior functions
});
I've just tried to briefly explain the structure here. Read through the waterfall guide for more information, it's pretty well written.
With a simple for
loop:
for _, v := range myconfig {
if v.Key == "key1" {
// Found!
}
}
Note that since element type of the slice is a struct
(not a pointer), this may be inefficient if the struct type is "big" as the loop will copy each visited element into the loop variable.
It would be faster to use a range
loop just on the index, this avoids copying the elements:
for i := range myconfig {
if myconfig[i].Key == "key1" {
// Found!
}
}
Notes:
It depends on your case whether multiple configs may exist with the same key
, but if not, you should break
out of the loop if a match is found (to avoid searching for others).
for i := range myconfig {
if myconfig[i].Key == "key1" {
// Found!
break
}
}
Also if this is a frequent operation, you should consider building a map
from it which you can simply index, e.g.
// Build a config map:
confMap := map[string]string{}
for _, v := range myconfig {
confMap[v.Key] = v.Value
}
// And then to find values by key:
if v, ok := confMap["key1"]; ok {
// Found
}
I have wasted 3 days
ultimately solved a graph question
used for
finding shortest distance
using BFS
Want to share the experience.
When the (undirected for me) graph has
fixed distance (1, 6, etc.) for edges
#1
We can use BFS to find shortest path simply by traversing it
then, if required, multiply with fixed distance (1, 6, etc.)
#2
As noted above
with BFS
the very 1st time an adjacent node is reached, it is shortest path
#3
It does not matter what queue you use
deque/queue(c++) or
your own queue implementation (in c language)
A circular queue is unnecessary
#4
Number of elements required for queue is N+1 at most, which I used
(dint check if N works)
here, N is V, number of vertices.
#5
Wikipedia BFS will work, and is sufficient.
https://en.wikipedia.org/wiki/Breadth-first_search#Pseudocode
I have lost 3 days trying all above alternatives, verifying & re-verifying again and again above
they are not the issue.
(Try to spend time looking for other issues, if you dint find any issues with above 5).
More explanation from the comment below:
A
/ \
B C
/\ /\
D E F G
Assume above is your graph
graph goes downwards
For A, the adjacents are B & C
For B, the adjacents are D & E
For C, the adjacents are F & G
say, start node is A
when you reach A, to, B & C the shortest distance to B & C from A is 1
when you reach D or E, thru B, the shortest distance to A & D is 2 (A->B->D)
similarly, A->E is 2 (A->B->E)
also, A->F & A->G is 2
So, now instead of 1 distance between nodes, if it is 6, then just multiply the answer by 6
example,
if distance between each is 1, then A->E is 2 (A->B->E = 1+1)
if distance between each is 6, then A->E is 12 (A->B->E = 6+6)
yes, bfs may take any path
but we are calculating for all paths
if you have to go from A to Z, then we travel all paths from A to an intermediate I, and since there will be many paths we discard all but shortest path till I, then continue with shortest path ahead to next node J
again if there are multiple paths from I to J, we only take shortest one
example,
assume,
A -> I we have distance 5
(STEP) assume, I -> J we have multiple paths, of distances 7 & 8, since 7 is shortest
we take A -> J as 5 (A->I shortest) + 8 (shortest now) = 13
so A->J is now 13
we repeat now above (STEP) for J -> K and so on, till we get to Z
Read this part, 2 or 3 times, and draw on paper, you will surely get what i am saying, best of luck
In this case I would use a definition list as so:
<dl>
<dt>Fruits I like:</dt>
<dd>Apples</dd>
<dd>Bananas</dd>
<dd>Oranges</dd>
</dl>
A reference to an element will never look "falsy", so leaving off the explicit null check is safe.
Javascript will treat references to some values in a boolean context as false
: undefined, null, numeric zero and NaN
, and empty strings. But what getElementById
returns will either be an element reference, or null. Thus if the element is in the DOM, the return value will be an object reference, and all object references are true
in an if ()
test. If the element is not in the DOM, the return value would be null
, and null
is always false
in an if ()
test.
It's harmless to include the comparison, but personally I prefer to keep out bits of code that don't do anything because I figure every time my finger hits the keyboard I might be introducing a bug :)
Note that those using jQuery should not do this:
if ($('#something')) { /* ... */ }
because the jQuery function will always return something "truthy" — even if no element is found, jQuery returns an object reference. Instead:
if ($('#something').length) { /* ... */ }
edit — as to checking the value of an element, no, you can't do that at the same time as you're checking for the existence of the element itself directly with DOM methods. Again, most frameworks make that relatively simple and clean, as others have noted in their answers.
you need to take out the quotes:
soda = a + b
(You want to refer to the variables a
and b
, not the strings "a" and "b")
Why use LEN so you have 2 string functions? All you need is character 5 on...
...SUBSTRING (Code1, 5, 8000)...
Try this :
$obj = @{
SomeProp = "Hello"
}
Write-Host "Property Value is $($obj."SomeProp")"
Option 1. you can do this using single cmd where D is my xampp or wampp install folder so i use this where mysql.exe install and second option database name and last is sql file so replace it as your then run this
D:\xampp\mysql\bin\mysql.exe -u root -p databse_name < D:\yoursqlfile.sql
Option 1 for wampp
D:\wamp64\bin\mysql\mysql5.7.14\bin\mysql.exe -u root -p databse_name< D:\yoursqlfile.sql
change your folder and mysql version
Option 2 Suppose your current path is which is showing command prompt
C:\Users\shafiq;
then change directory using cd..
then goto your mysql directory where your xampp installed. Then cd..
for change directory. then go to bin folder.
C:\xampp\mysql\bin;
C:\xampp\mysql\bin\mysql -u {username} -p {database password}
.then please enter when you see enter password in command prompt.
choose database using
mysql->use test (where database name test)
then put in source sql in bin folder.
then last command will be
mysql-> source test.sql (where test.sql is file name which need to import)
then press enter
This is full command
C:\Users\shafiq;
C:\xampp\mysql\bin
C:\xampp\mysql\bin\mysql -u {username} -p {database password}
mysql-> use test
mysql->source test.sql
The tool that richardtz suggests is excellent.
Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.
You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge
Please have a look here
Either you can use rails tag Or use plain HTML tags
Rails tag
<%= select("Contact", "email_provider", Contact::PROVIDERS, {:include_blank => true}) %>
*above line of code would become HTML code(HTML Tag), find it below *
HTML tag
<select name="Contact[email_provider]">
<option></option>
<option>yahoo</option>
<option>gmail</option>
<option>msn</option>
</select>
To add exact fontsize you can use following. Worked for me since in my case predefined ranges (Large, tiny) are not match with the font size required to me.
\fontsize{10}{12}\selectfont This is the text you need to be in 10px
More info: https://tug.org/TUGboat/tb33-3/tb105thurnherr.pdf
I had a similar problem using axes. The class parameter is frameon
but the kwarg is frame_on
. axes_api
>>> plt.gca().set(frameon=False)
AttributeError: Unknown property frameon
frame_on
data = range(100)
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(data)
#ax.set(frameon=False) # Old
ax.set(frame_on=False) # New
plt.show()
I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.
//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
"ln": {c.ln},
"ip": {c.ip},
"ua": {c.ua}})
//okay, moving on...
if err != nil {
//handle postform error
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
//handle read response error
}
fmt.Printf("%s\n", string(body))
The resolution is 480 dpi, the launcher icon is 144*144px all is scaled 3x respect to mdpi (so called "base", "baseline" or "normal") sizes.
My experience is that the new version of Filezilla has this problem, but not the old versions. I was using Filezilla and everything was OK. After I upgraded to version 3.10, I faced this problem and I couldn't solve it. I uninstalled version 3.10 and reinstalled version 3.8 and the problem was gone! Now I am using version 3.8 and everything is OK. I prefer to face no problems even if I have to use old versions. ;)
Try installing the old version and do not upgrade, however odd that may sound.
even after installing anaconda i got the same error and entering python3 showed this:
$ python3
Python 3.6.9 (default, Nov 7 2019, 10:44:02)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
enter this command: source ~/.bashrc
(it is kind of restarting the terminal) after running the command enter python3
again:
$ python3
Python 3.7.4 (default, Aug 13 2019, 20:35:49)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
this means anaconda is added. now import pandas
will work.
I tested all the answers here, but for me, none worked. So I studied a bit the problem, and finally I found the connection string needed. To get this string, you do:
1. in you project name:
a. right click the project name,
b. click Add,
c. select SQL Server Database (obviously you can rename it as you wish).
Now the new desired database will be added to your project.
2. The database is visible in the Server Explorer window.
3. Left click the database name in the Server Explorer window; now check the Solution Explorer window, and you will find the "Connection String", along side with Provider, State, Type, Version.
4. Copy the connection string provided, and put it in the Page_Load method:
string source = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\x\x\documents\visual studio 2013\Projects\WebApplication3\WebApplication3\App_Data\Product.mdf;Integrated Security=True";
SqlConnection conn = new SqlConnection(source);
conn.Open();
//your code here;
conn.Close();
I renamed my database as Product. Also, in the "AttachDbFilename", you must replace "c:\x\x\documents\" with your path to the phisical address of the .mdf file.
It worked for me, but I must mention this method works for VS2012 and VS2013. Don't know about other versions.
Select
A.maskid
, A.maskname
, A.schoolid
, B.schoolname
, STUFF((
SELECT ',' + T.maskdetail
FROM dbo.maskdetails T
WHERE A.maskid = T.maskid
FOR XML PATH('')), 1, 1, '') as maskdetail
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid
Group by A.maskid
, A.maskname
, A.schoolid
, B.schoolname
To get just the string value within the spinner use the following:
spinner.getSelectedItem().toString();
Just use TO_DATE()
function to convert string to DATE
.
For Example:
create table Customer(
CustId int primary key,
CustName varchar(20),
DOB date);
insert into Customer values(1,'Vishnu', TO_DATE('1994/12/16 12:00:00', 'yyyy/mm/dd hh:mi:ss'));
This is what I'm teaching my students tomorrow. After years of looking at this stuff... ie all of the documentation above http://www.cpearson.com/excel/errorhandling.htm comes to mind as an excellent one...
I hope this summarizes it for others. There is an Err
object and an active (or inactive) ErrorHandler
. Both need to be handled and reset for new errors.
Paste this into a workbook and step through it with F8.
Sub ErrorHandlingDemonstration()
On Error GoTo ErrorHandler
'this will error
Debug.Print (1 / 0)
'this will also error
dummy = Application.WorksheetFunction.VLookup("not gonna find me", Range("A1:B2"), 2, True)
'silly error
Dummy2 = "string" * 50
Exit Sub
zeroDivisionErrorBlock:
maybeWe = "did some cleanup on variables that shouldnt have been divided!"
' moves the code execution to the line AFTER the one that errored
Resume Next
vlookupFailedErrorBlock:
maybeThisTime = "we made sure the value we were looking for was in the range!"
' moves the code execution to the line AFTER the one that errored
Resume Next
catchAllUnhandledErrors:
MsgBox(thisErrorsDescription)
Exit Sub
ErrorHandler:
thisErrorsNumberBeforeReset = Err.Number
thisErrorsDescription = Err.Description
'this will reset the error object and error handling
On Error GoTo 0
'this will tell vba where to go for new errors, ie the new ErrorHandler that was previous just reset!
On Error GoTo ErrorHandler
' 11 is the err.number for division by 0
If thisErrorsNumberBeforeReset = 11 Then
GoTo zeroDivisionErrorBlock
' 1004 is the err.number for vlookup failing
ElseIf thisErrorsNumberBeforeReset = 1004 Then
GoTo vlookupFailedErrorBlock
Else
GoTo catchAllUnhandledErrors
End If
End Sub
Seems like you can't iterate through JSONArray
with a for each
. You can loop through your JSONArray
like this:
for (int i=0; i < arr.length(); i++) {
arr.getJSONObject(i);
}
Also you can do join:
var qwe = new List<int> {5, 2, 3, 8};
Console.WriteLine(string.Join("\t", qwe));
Here is a working sample.
<html>_x000D_
<script type="text/javascript">_x000D_
var canvas, ctx, flag = false,_x000D_
prevX = 0,_x000D_
currX = 0,_x000D_
prevY = 0,_x000D_
currY = 0,_x000D_
dot_flag = false;_x000D_
_x000D_
var x = "black",_x000D_
y = 2;_x000D_
_x000D_
function init() {_x000D_
canvas = document.getElementById('can');_x000D_
ctx = canvas.getContext("2d");_x000D_
w = canvas.width;_x000D_
h = canvas.height;_x000D_
_x000D_
canvas.addEventListener("mousemove", function (e) {_x000D_
findxy('move', e)_x000D_
}, false);_x000D_
canvas.addEventListener("mousedown", function (e) {_x000D_
findxy('down', e)_x000D_
}, false);_x000D_
canvas.addEventListener("mouseup", function (e) {_x000D_
findxy('up', e)_x000D_
}, false);_x000D_
canvas.addEventListener("mouseout", function (e) {_x000D_
findxy('out', e)_x000D_
}, false);_x000D_
}_x000D_
_x000D_
function color(obj) {_x000D_
switch (obj.id) {_x000D_
case "green":_x000D_
x = "green";_x000D_
break;_x000D_
case "blue":_x000D_
x = "blue";_x000D_
break;_x000D_
case "red":_x000D_
x = "red";_x000D_
break;_x000D_
case "yellow":_x000D_
x = "yellow";_x000D_
break;_x000D_
case "orange":_x000D_
x = "orange";_x000D_
break;_x000D_
case "black":_x000D_
x = "black";_x000D_
break;_x000D_
case "white":_x000D_
x = "white";_x000D_
break;_x000D_
}_x000D_
if (x == "white") y = 14;_x000D_
else y = 2;_x000D_
_x000D_
}_x000D_
_x000D_
function draw() {_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(prevX, prevY);_x000D_
ctx.lineTo(currX, currY);_x000D_
ctx.strokeStyle = x;_x000D_
ctx.lineWidth = y;_x000D_
ctx.stroke();_x000D_
ctx.closePath();_x000D_
}_x000D_
_x000D_
function erase() {_x000D_
var m = confirm("Want to clear");_x000D_
if (m) {_x000D_
ctx.clearRect(0, 0, w, h);_x000D_
document.getElementById("canvasimg").style.display = "none";_x000D_
}_x000D_
}_x000D_
_x000D_
function save() {_x000D_
document.getElementById("canvasimg").style.border = "2px solid";_x000D_
var dataURL = canvas.toDataURL();_x000D_
document.getElementById("canvasimg").src = dataURL;_x000D_
document.getElementById("canvasimg").style.display = "inline";_x000D_
}_x000D_
_x000D_
function findxy(res, e) {_x000D_
if (res == 'down') {_x000D_
prevX = currX;_x000D_
prevY = currY;_x000D_
currX = e.clientX - canvas.offsetLeft;_x000D_
currY = e.clientY - canvas.offsetTop;_x000D_
_x000D_
flag = true;_x000D_
dot_flag = true;_x000D_
if (dot_flag) {_x000D_
ctx.beginPath();_x000D_
ctx.fillStyle = x;_x000D_
ctx.fillRect(currX, currY, 2, 2);_x000D_
ctx.closePath();_x000D_
dot_flag = false;_x000D_
}_x000D_
}_x000D_
if (res == 'up' || res == "out") {_x000D_
flag = false;_x000D_
}_x000D_
if (res == 'move') {_x000D_
if (flag) {_x000D_
prevX = currX;_x000D_
prevY = currY;_x000D_
currX = e.clientX - canvas.offsetLeft;_x000D_
currY = e.clientY - canvas.offsetTop;_x000D_
draw();_x000D_
}_x000D_
}_x000D_
}_x000D_
</script>_x000D_
<body onload="init()">_x000D_
<canvas id="can" width="400" height="400" style="position:absolute;top:10%;left:10%;border:2px solid;"></canvas>_x000D_
<div style="position:absolute;top:12%;left:43%;">Choose Color</div>_x000D_
<div style="position:absolute;top:15%;left:45%;width:10px;height:10px;background:green;" id="green" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:15%;left:46%;width:10px;height:10px;background:blue;" id="blue" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:15%;left:47%;width:10px;height:10px;background:red;" id="red" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:17%;left:45%;width:10px;height:10px;background:yellow;" id="yellow" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:17%;left:46%;width:10px;height:10px;background:orange;" id="orange" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:17%;left:47%;width:10px;height:10px;background:black;" id="black" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:20%;left:43%;">Eraser</div>_x000D_
<div style="position:absolute;top:22%;left:45%;width:15px;height:15px;background:white;border:2px solid;" id="white" onclick="color(this)"></div>_x000D_
<img id="canvasimg" style="position:absolute;top:10%;left:52%;" style="display:none;">_x000D_
<input type="button" value="save" id="btn" size="30" onclick="save()" style="position:absolute;top:55%;left:10%;">_x000D_
<input type="button" value="clear" id="clr" size="23" onclick="erase()" style="position:absolute;top:55%;left:15%;">_x000D_
</body>_x000D_
</html>
_x000D_
I found the solution at: Passing data to a bootstrap modal
So simply use:
$(e.relatedTarget).data('book-id');
with 'book-id
' is a attribute of modal with pre-fix 'data-
'
Since this question was originally asked and answered, some of the inner-workings of Elasticsearch have changed, particularly around timestamps. Here is a full example showing how to query for single latest record. Tested on ES 6/7.
1) Tell Elasticsearch to treat timestamp
field as the timestamp
curl -XPUT "localhost:9200/my_index?pretty" -H 'Content-Type: application/json' -d '{"mappings":{"message":{"properties":{"timestamp":{"type":"date"}}}}}'
2) Put some test data into the index
curl -XPOST "localhost:9200/my_index/message/1" -H 'Content-Type: application/json' -d '{ "timestamp" : "2019-08-02T03:00:00Z", "message" : "hello world" }'
curl -XPOST "localhost:9200/my_index/message/2" -H 'Content-Type: application/json' -d '{ "timestamp" : "2019-08-02T04:00:00Z", "message" : "bye world" }'
3) Query for the latest record
curl -X POST "localhost:9200/my_index/_search" -H 'Content-Type: application/json' -d '{"query": {"match_all": {}},"size": 1,"sort": [{"timestamp": {"order": "desc"}}]}'
4) Expected results
{
"took":0,
"timed_out":false,
"_shards":{
"total":5,
"successful":5,
"skipped":0,
"failed":0
},
"hits":{
"total":2,
"max_score":null,
"hits":[
{
"_index":"my_index",
"_type":"message",
"_id":"2",
"_score":null,
"_source":{
"timestamp":"2019-08-02T04:00:00Z",
"message":"bye world"
},
"sort":[
1564718400000
]
}
]
}
}
Just add
xAxis: {
...
lineWidth: 0,
minorGridLineWidth: 0,
lineColor: 'transparent',
...
labels: {
enabled: false
},
minorTickLength: 0,
tickLength: 0
}
to the xAxis definition.
Since Version 4.1.9 you can simply use the axis attribute visible
:
xAxis: {
visible: false,
}
There's a section on Bringing Up a Popup Menu in the How to Use Menus article of The Java Tutorials which explains how to use the JPopupMenu
class.
The example code in the tutorial shows how to add MouseListener
s to the components which should display a pop-up menu, and displays the menu accordingly.
(The method you describe is fairly similar to the way the tutorial presents the way to show a pop-up menu on a component.)
bar
is deprecated. Please check ogp.me for the current docs.
As the other answers have noted, static and class methods are easily accomplished using the built-in decorators:
class Test(object):
# regular instance method:
def MyMethod(self):
pass
# class method:
@classmethod
def MyClassMethod(klass):
pass
# static method:
@staticmethod
def MyStaticMethod():
pass
As usual, the first argument to MyMethod()
is bound to the class instance object. In contrast, the first argument to MyClassMethod()
is bound to the class object itself (e.g., in this case, Test
). For MyStaticMethod()
, none of the arguments are bound, and having arguments at all is optional.
However, implementing "static variables" (well, mutable static variables, anyway, if that's not a contradiction in terms...) is not as straight forward. As millerdev pointed out in his answer, the problem is that Python's class attributes are not truly "static variables". Consider:
class Test(object):
i = 3 # This is a class attribute
x = Test()
x.i = 12 # Attempt to change the value of the class attribute using x instance
assert x.i == Test.i # ERROR
assert Test.i == 3 # Test.i was not affected
assert x.i == 12 # x.i is a different object than Test.i
This is because the line x.i = 12
has added a new instance attribute i
to x
instead of changing the value of the Test
class i
attribute.
Partial expected static variable behavior, i.e., syncing of the attribute between multiple instances (but not with the class itself; see "gotcha" below), can be achieved by turning the class attribute into a property:
class Test(object):
_i = 3
@property
def i(self):
return type(self)._i
@i.setter
def i(self,val):
type(self)._i = val
## ALTERNATIVE IMPLEMENTATION - FUNCTIONALLY EQUIVALENT TO ABOVE ##
## (except with separate methods for getting and setting i) ##
class Test(object):
_i = 3
def get_i(self):
return type(self)._i
def set_i(self,val):
type(self)._i = val
i = property(get_i, set_i)
Now you can do:
x1 = Test()
x2 = Test()
x1.i = 50
assert x2.i == x1.i # no error
assert x2.i == 50 # the property is synced
The static variable will now remain in sync between all class instances.
(NOTE: That is, unless a class instance decides to define its own version of _i
! But if someone decides to do THAT, they deserve what they get, don't they???)
Note that technically speaking, i
is still not a 'static variable' at all; it is a property
, which is a special type of descriptor. However, the property
behavior is now equivalent to a (mutable) static variable synced across all class instances.
For immutable static variable behavior, simply omit the property
setter:
class Test(object):
_i = 3
@property
def i(self):
return type(self)._i
## ALTERNATIVE IMPLEMENTATION - FUNCTIONALLY EQUIVALENT TO ABOVE ##
## (except with separate methods for getting i) ##
class Test(object):
_i = 3
def get_i(self):
return type(self)._i
i = property(get_i)
Now attempting to set the instance i
attribute will return an AttributeError
:
x = Test()
assert x.i == 3 # success
x.i = 12 # ERROR
Note that the above methods only work with instances of your class - they will not work when using the class itself. So for example:
x = Test()
assert x.i == Test.i # ERROR
# x.i and Test.i are two different objects:
type(Test.i) # class 'property'
type(x.i) # class 'int'
The line assert Test.i == x.i
produces an error, because the i
attribute of Test
and x
are two different objects.
Many people will find this surprising. However, it should not be. If we go back and inspect our Test
class definition (the second version), we take note of this line:
i = property(get_i)
Clearly, the member i
of Test
must be a property
object, which is the type of object returned from the property
function.
If you find the above confusing, you are most likely still thinking about it from the perspective of other languages (e.g. Java or c++). You should go study the property
object, about the order in which Python attributes are returned, the descriptor protocol, and the method resolution order (MRO).
I present a solution to the above 'gotcha' below; however I would suggest - strenuously - that you do not try to do something like the following until - at minimum - you thoroughly understand why assert Test.i = x.i
causes an error.
Test.i == x.i
I present the (Python 3) solution below for informational purposes only. I am not endorsing it as a "good solution". I have my doubts as to whether emulating the static variable behavior of other languages in Python is ever actually necessary. However, regardless as to whether it is actually useful, the below should help further understanding of how Python works.
UPDATE: this attempt is really pretty awful; if you insist on doing something like this (hint: please don't; Python is a very elegant language and shoe-horning it into behaving like another language is just not necessary), use the code in Ethan Furman's answer instead.
Emulating static variable behavior of other languages using a metaclass
A metaclass is the class of a class. The default metaclass for all classes in Python (i.e., the "new style" classes post Python 2.3 I believe) is type
. For example:
type(int) # class 'type'
type(str) # class 'type'
class Test(): pass
type(Test) # class 'type'
However, you can define your own metaclass like this:
class MyMeta(type): pass
And apply it to your own class like this (Python 3 only):
class MyClass(metaclass = MyMeta):
pass
type(MyClass) # class MyMeta
Below is a metaclass I have created which attempts to emulate "static variable" behavior of other languages. It basically works by replacing the default getter, setter, and deleter with versions which check to see if the attribute being requested is a "static variable".
A catalog of the "static variables" is stored in the StaticVarMeta.statics
attribute. All attribute requests are initially attempted to be resolved using a substitute resolution order. I have dubbed this the "static resolution order", or "SRO". This is done by looking for the requested attribute in the set of "static variables" for a given class (or its parent classes). If the attribute does not appear in the "SRO", the class will fall back on the default attribute get/set/delete behavior (i.e., "MRO").
from functools import wraps
class StaticVarsMeta(type):
'''A metaclass for creating classes that emulate the "static variable" behavior
of other languages. I do not advise actually using this for anything!!!
Behavior is intended to be similar to classes that use __slots__. However, "normal"
attributes and __statics___ can coexist (unlike with __slots__).
Example usage:
class MyBaseClass(metaclass = StaticVarsMeta):
__statics__ = {'a','b','c'}
i = 0 # regular attribute
a = 1 # static var defined (optional)
class MyParentClass(MyBaseClass):
__statics__ = {'d','e','f'}
j = 2 # regular attribute
d, e, f = 3, 4, 5 # Static vars
a, b, c = 6, 7, 8 # Static vars (inherited from MyBaseClass, defined/re-defined here)
class MyChildClass(MyParentClass):
__statics__ = {'a','b','c'}
j = 2 # regular attribute (redefines j from MyParentClass)
d, e, f = 9, 10, 11 # Static vars (inherited from MyParentClass, redefined here)
a, b, c = 12, 13, 14 # Static vars (overriding previous definition in MyParentClass here)'''
statics = {}
def __new__(mcls, name, bases, namespace):
# Get the class object
cls = super().__new__(mcls, name, bases, namespace)
# Establish the "statics resolution order"
cls.__sro__ = tuple(c for c in cls.__mro__ if isinstance(c,mcls))
# Replace class getter, setter, and deleter for instance attributes
cls.__getattribute__ = StaticVarsMeta.__inst_getattribute__(cls, cls.__getattribute__)
cls.__setattr__ = StaticVarsMeta.__inst_setattr__(cls, cls.__setattr__)
cls.__delattr__ = StaticVarsMeta.__inst_delattr__(cls, cls.__delattr__)
# Store the list of static variables for the class object
# This list is permanent and cannot be changed, similar to __slots__
try:
mcls.statics[cls] = getattr(cls,'__statics__')
except AttributeError:
mcls.statics[cls] = namespace['__statics__'] = set() # No static vars provided
# Check and make sure the statics var names are strings
if any(not isinstance(static,str) for static in mcls.statics[cls]):
typ = dict(zip((not isinstance(static,str) for static in mcls.statics[cls]), map(type,mcls.statics[cls])))[True].__name__
raise TypeError('__statics__ items must be strings, not {0}'.format(typ))
# Move any previously existing, not overridden statics to the static var parent class(es)
if len(cls.__sro__) > 1:
for attr,value in namespace.items():
if attr not in StaticVarsMeta.statics[cls] and attr != ['__statics__']:
for c in cls.__sro__[1:]:
if attr in StaticVarsMeta.statics[c]:
setattr(c,attr,value)
delattr(cls,attr)
return cls
def __inst_getattribute__(self, orig_getattribute):
'''Replaces the class __getattribute__'''
@wraps(orig_getattribute)
def wrapper(self, attr):
if StaticVarsMeta.is_static(type(self),attr):
return StaticVarsMeta.__getstatic__(type(self),attr)
else:
return orig_getattribute(self, attr)
return wrapper
def __inst_setattr__(self, orig_setattribute):
'''Replaces the class __setattr__'''
@wraps(orig_setattribute)
def wrapper(self, attr, value):
if StaticVarsMeta.is_static(type(self),attr):
StaticVarsMeta.__setstatic__(type(self),attr, value)
else:
orig_setattribute(self, attr, value)
return wrapper
def __inst_delattr__(self, orig_delattribute):
'''Replaces the class __delattr__'''
@wraps(orig_delattribute)
def wrapper(self, attr):
if StaticVarsMeta.is_static(type(self),attr):
StaticVarsMeta.__delstatic__(type(self),attr)
else:
orig_delattribute(self, attr)
return wrapper
def __getstatic__(cls,attr):
'''Static variable getter'''
for c in cls.__sro__:
if attr in StaticVarsMeta.statics[c]:
try:
return getattr(c,attr)
except AttributeError:
pass
raise AttributeError(cls.__name__ + " object has no attribute '{0}'".format(attr))
def __setstatic__(cls,attr,value):
'''Static variable setter'''
for c in cls.__sro__:
if attr in StaticVarsMeta.statics[c]:
setattr(c,attr,value)
break
def __delstatic__(cls,attr):
'''Static variable deleter'''
for c in cls.__sro__:
if attr in StaticVarsMeta.statics[c]:
try:
delattr(c,attr)
break
except AttributeError:
pass
raise AttributeError(cls.__name__ + " object has no attribute '{0}'".format(attr))
def __delattr__(cls,attr):
'''Prevent __sro__ attribute from deletion'''
if attr == '__sro__':
raise AttributeError('readonly attribute')
super().__delattr__(attr)
def is_static(cls,attr):
'''Returns True if an attribute is a static variable of any class in the __sro__'''
if any(attr in StaticVarsMeta.statics[c] for c in cls.__sro__):
return True
return False
// root-app_x000D_
const rootApp = angular.module('root-app', ['app1', 'app2E']);_x000D_
_x000D_
// app1_x000D_
const app11aa = angular.module('app1', []);_x000D_
app11aa.controller('main', function($scope) {_x000D_
$scope.msg = 'App 1';_x000D_
});_x000D_
_x000D_
// app2_x000D_
const app2 = angular.module('app2E', []);_x000D_
app2.controller('mainB', function($scope) {_x000D_
$scope.msg = 'App 2';_x000D_
});_x000D_
_x000D_
// bootstrap_x000D_
angular.bootstrap(document.querySelector('#app1a'), ['app1']);_x000D_
angular.bootstrap(document.querySelector('#app2b'), ['app2E']);
_x000D_
<!-- [email protected] -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.0/angular.min.js"></script>_x000D_
_x000D_
<!-- root-app -->_x000D_
<div ng-app="root-app">_x000D_
_x000D_
<!-- app1 -->_x000D_
<div id="app1a">_x000D_
<div ng-controller="main">_x000D_
{{msg}}_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<!-- app2 -->_x000D_
<div id="app2b">_x000D_
<div ng-controller="mainB">_x000D_
{{msg}}_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
In 5.0 Lollipop, Google added an official method, WebChromeClient.onShowFileChooser. They even provide a way to automatically generate the file chooser intent so that it uses the input accept mime types.
public class MyWebChromeClient extends WebChromeClient {
// reference to activity instance. May be unnecessary if your web chrome client is member class.
private MyActivity activity;
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
// make sure there is no existing message
if (myActivity.uploadMessage != null) {
myActivity.uploadMessage.onReceiveValue(null);
myActivity.uploadMessage = null;
}
myActivity.uploadMessage = filePathCallback;
Intent intent = fileChooserParams.createIntent();
try {
myActivity.startActivityForResult(intent, MyActivity.REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e) {
myActivity.uploadMessage = null;
Toast.makeText(myActivity, "Cannot open file chooser", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
}
public class MyActivity extends ... {
public static final int REQUEST_SELECT_FILE = 100;
public ValueCallback<Uri[]> uploadMessage;
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == REQUEST_SELECT_FILE) {
if (uploadMessage == null) return;
uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
uploadMessage = null;
}
}
}
}
For Android versions before KitKat, the private methods mentioned in the other answers work. I have not found a good workaround for KitKat (4.4).
When you pass a pointer by a non-const
reference, you are telling the compiler that you are going to modify that pointer's value. Your code does not do that, but the compiler thinks that it does, or plans to do it in the future.
To fix this error, either declare x
constant
// This tells the compiler that you are not planning to modify the pointer
// passed by reference
void test(float * const &x){
*x = 1000;
}
or make a variable to which you assign a pointer to nKByte
before calling test
:
float nKByte = 100.0;
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr
float *nKBytePtr = &nKByte;
test(nKBytePtr);
For anybody coming here looking for a getTickCount() implementation for iOS, here is mine after putting various sources together.
Previously I had a bug in this code (I divided by 1000000 first) which was causing some quantisation of the output on my iPhone 6 (perhaps this was not an issue on iPhone 4/etc or I just never noticed it). Note that by not performing that division first, there is some risk of overflow if the numerator of the timebase is quite large. If anybody is curious, there is a link with much more information here: https://stackoverflow.com/a/23378064/588476
In light of that information, maybe it is safer to use Apple's function CACurrentMediaTime
!
I also benchmarked the mach_timebase_info
call and it takes approximately 19ns on my iPhone 6, so I removed the (not threadsafe) code which was caching the output of that call.
#include <mach/mach.h>
#include <mach/mach_time.h>
uint64_t getTickCount(void)
{
mach_timebase_info_data_t sTimebaseInfo;
uint64_t machTime = mach_absolute_time();
// Convert to milliseconds
mach_timebase_info(&sTimebaseInfo);
machTime *= sTimebaseInfo.numer;
machTime /= sTimebaseInfo.denom;
machTime /= 1000000; // convert from nanoseconds to milliseconds
return machTime;
}
Do be aware of the potential risk of overflow depending on the output of the timebase call. I suspect (but do not know) that it might be a constant for each model of iPhone. on my iPhone 6 it was 125/3
.
The solution using CACurrentMediaTime()
is quite trivial:
uint64_t getTickCount(void)
{
double ret = CACurrentMediaTime();
return ret * 1000;
}
I see that if you paste csv delimited text in Excel and do a "Text to Columns", it asks you for a "text qualifier". It's defaulted to a double quote so that it treats text within double quotes as literal. I imagine that Excel implements this by going one character at a time, if it encounters a "text qualifier", it keeps going to the next "qualifier". You can probably implement this yourself with a for loop and a boolean to denote if you're inside literal text.
public string[] CsvParser(string csvText)
{
List<string> tokens = new List<string>();
int last = -1;
int current = 0;
bool inText = false;
while(current < csvText.Length)
{
switch(csvText[current])
{
case '"':
inText = !inText; break;
case ',':
if (!inText)
{
tokens.Add(csvText.Substring(last + 1, (current - last)).Trim(' ', ','));
last = current;
}
break;
default:
break;
}
current++;
}
if (last != csvText.Length - 1)
{
tokens.Add(csvText.Substring(last+1).Trim());
}
return tokens.ToArray();
}
All you need to do is to override getParams method in Request class. I had the same problem and I searched through the answers but I could not find a proper one. The problem is unlike get request, post parameters being redirected by the servers may be dropped. For instance, read this. So, don't risk your requests to be redirected by webserver. If you are targeting http://example/myapp , then mention the exact address of your service, that is http://example.com/myapp/index.php.
Volley is OK and works perfectly, the problem stems from somewhere else.
You can do this alike here but with your package. In my case, it was lsb_release
Run: yum whatprovides lsb_release
Response:
redhat-lsb-core-4.1-24.el7.i686 : LSB Core module support
Repo : rhel-7-server-rpms
Matched from:
Filename : /usr/bin/lsb_release
redhat-lsb-core-4.1-24.el7.x86_64 : LSB Core module support
Repo : rhel-7-server-rpms
Matched from:
Filename : /usr/bin/lsb_release
redhat-lsb-core-4.1-27.el7.i686 : LSB Core module support
Repo : rhel-7-server-rpms
Matched from:
Filename : /usr/bin/lsb_release
redhat-lsb-core-4.1-27.el7.x86_64 : LSB Core module support
Repo : rhel-7-server-rpms
Matched from:
Filename : /usr/bin/lsb_release`
Run to install: yum install redhat-lsb-core
The package name SHOULD be without number and system type so yum packager can choose what is best for him.
Stack:
Heap:
delete
, delete[]
, or free
.new
or malloc
respectively.Example:
int foo()
{
char *pBuffer; //<--nothing allocated yet (excluding the pointer itself, which is allocated here on the stack).
bool b = true; // Allocated on the stack.
if(b)
{
//Create 500 bytes on the stack
char buffer[500];
//Create 500 bytes on the heap
pBuffer = new char[500];
}//<-- buffer is deallocated here, pBuffer is not
}//<--- oops there's a memory leak, I should have called delete[] pBuffer;
Running VS Code on Android is not possible, at least until Android support is implemented in Electron. This has been rejected by the Electron team in the past, see electron#562
Visual Studio Codespaces and GitHub Codespaces an upcoming services that enables running VS Code in a browser. Since everything runs in a browser, it seems likely that mobile OS' will be supported.
In my case, using MAC OS X 10.11 and Android 2.0, and by doing exactly what Aqib Mumtaz has explained.
But, each time, I had this message : "A problem occurred configuring project ':app'. > Cannot evaluate module xxx : Configuration with name 'default' not found."
I found that the reason of this message is that Android 2.0 doesn't allow to create a library directly. So, I have decided first to create an app projet and then to modify the build.gradle in order to transform it as a library.
This solution doesn't work, because a Library project is very different than an app project.
So, I have resolved my problem like this :
Then continue with the solution proposed by Aqib Mumtaz.
As a result, your library source will be shared without needing to duplicate source files each time (it was an heresy for me!)
Hoping that this help you.
You just need this:
$(".hidden").attr("placeholder", "Type here to search");
classList
is used for manipulating classes and not attributes.
This works wonderfully for me:
CREATE FUNCTION [dbo].[StartOfWeek] ( @INPUTDATE DATETIME ) RETURNS DATETIME AS BEGIN -- THIS does not work in function. -- SET DATEFIRST 1 -- set monday to be the first day of week. DECLARE @DOW INT -- to store day of week SET @INPUTDATE = CONVERT(VARCHAR(10), @INPUTDATE, 111) SET @DOW = DATEPART(DW, @INPUTDATE) -- Magic convertion of monday to 1, tuesday to 2, etc. -- irrespect what SQL server thinks about start of the week. -- But here we have sunday marked as 0, but we fix this later. SET @DOW = (@DOW + @@DATEFIRST - 1) %7 IF @DOW = 0 SET @DOW = 7 -- fix for sunday RETURN DATEADD(DD, 1 - @DOW,@INPUTDATE) END
Try Find out divs height and setting div height (Similar to the one Matt posted but using a loop)
You can use redial package for prefetching data on the server before attempting to render
As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)
EDIT 1:
Following your comment, I run a test table:
mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)
Insertion:
mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)
EDIT 2:
So, aparently you want to insert a NULL value to pdd
field as your comment states ?
You can do that in 2 ways like this:
Method 1:
mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)
Method 2:
mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)
EDIT 3:
You failed to change the default value of pdd
field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)
mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3 Duplicates: 0 Warnings: 1
7 years later and this code has helped me. However, my times still were not showing up correctly.
Using Matplotlib 2.0.0 and I had to add the following bit of code from Editing the date formatting of x-axis tick labels in matplotlib by Paul H.
import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)
I changed the format to (%H:%M) and the time displayed correctly.
All thanks to the community.
You can do it by manipulating the timecode or by using strtotime(). Here's an example using strtotime.
$data['created'] = date('Y-m-d H:i:s', strtotime("+1 week"));
Suppose you want to add those flags (better to declare them in a constant):
SET(GCC_COVERAGE_COMPILE_FLAGS "-fprofile-arcs -ftest-coverage")
SET(GCC_COVERAGE_LINK_FLAGS "-lgcov")
There are several ways to add them:
The easiest one (not clean, but easy and convenient, and works only for compile flags, C & C++ at once):
add_definitions(${GCC_COVERAGE_COMPILE_FLAGS})
Appending to corresponding CMake variables:
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}")
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS}")
Using target properties, cf. doc CMake compile flag target property and need to know the target name.
get_target_property(TEMP ${THE_TARGET} COMPILE_FLAGS)
if(TEMP STREQUAL "TEMP-NOTFOUND")
SET(TEMP "") # Set to empty string
else()
SET(TEMP "${TEMP} ") # A space to cleanly separate from existing content
endif()
# Append our values
SET(TEMP "${TEMP}${GCC_COVERAGE_COMPILE_FLAGS}" )
set_target_properties(${THE_TARGET} PROPERTIES COMPILE_FLAGS ${TEMP} )
Right now I use method 2.
Try this code
Convert ArrayList to Collection
ArrayList<User> usersArrayList = new ArrayList<User>();
Collection<User> userCollection = new HashSet<User>(usersArrayList);
Convert Collection to ArrayList
Collection<User> userCollection = new HashSet<User>(usersArrayList);
List<User> userList = new ArrayList<User>(userCollection );
Simplest way is to use the dot operator in place of source, which is the sh equivalent of the bash source
command:
Instead of:
RUN source /usr/local/bin/virtualenvwrapper.sh
Use:
RUN . /usr/local/bin/virtualenvwrapper.sh
In general, I/O means Input or Output. Those methods throw the IOException
whenever an input or output operation is failed or interpreted. Note that this won't be thrown for reading or writing to memory as Java will be handling it automatically.
Here are some cases which result in IOException
.
I should like to provide the modern answer.
You shouldn’t really want to convert a date and time from a string at one GMT offset to a string at a different GMT offset and with in a different format. Rather in your program keep an instant (a point in time) as a proper date-time object. Only when you need to give string output, format your object into the desired string.
Parsing input
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.toFormatter();
String dateTimeString = "2011-10-06 03:35:05";
Instant instant = LocalDateTime.parse(dateTimeString, formatter)
.atOffset(ZoneOffset.UTC)
.toInstant();
For most purposes Instant
is a good choice for storing a point in time. If you needed to make it explicit that the date and time came from GMT, use an OffsetDateTime
instead.
Converting, formatting and printing output
ZoneId desiredZone = ZoneId.of("Pacific/Auckland");
Locale desiredeLocale = Locale.forLanguageTag("en-NZ");
DateTimeFormatter desiredFormatter = DateTimeFormatter.ofPattern(
"dd MMM uuuu HH:mm:ss OOOO", desiredeLocale);
ZonedDateTime desiredDateTime = instant.atZone(desiredZone);
String result = desiredDateTime.format(desiredFormatter);
System.out.println(result);
This printed:
06 Oct 2011 16:35:05 GMT+13:00
I specified time zone Pacific/Auckland rather than the offset you mentioned, +13:00. I understood that you wanted New Zealand time, and Pacific/Auckland better tells the reader this. The time zone also takes summer time (DST) into account so you don’t need to take this into account in your own code (for most purposes).
Since Oct
is in English, it’s a good idea to give the formatter an explicit locale. GMT
might be localized too, but I think that it just prints GMT
in all locales.
OOOO
in the format patterns string is one way of printing the offset, which may be a better idea than printing the time zone abbreviation you would get from z
since time zone abbreviations are often ambiguous. If you want NZDT
(for New Zealand Daylight Time), just put z
there instead.
Your questions
I will answer your numbered questions in relation to the modern classes in java.time.
Is possible to:
- Set the time on an object
No, the modern classes are immutable. You need to create an object that has the desired date and time from the outset (this has a number of advantages including thread safety).
- (Possibly) Set the TimeZone of the initial time stamp
The atZone
method that I use in the code returns a ZonedDateTime
with the specified time zone. Other date-time classes have a similar method, sometimes called atZoneSameInstant
or other names.
- Format the time stamp with a new TimeZone
With java.time converting to a new time zone and formatting are two distinct steps as shown.
- Return a string with new time zone time.
Yes, convert to the desired time zone as shown and format as shown.
I found that anytime I try to set the time like this:
calendar.setTime(new Date(1317816735000L));
the local machine's TimeZone is used. Why is that?
It’s not the way you think, which goes nicely to show just a couple of the (many) design problems with the old classes.
Date
hasn’t got a time zone. Only when you print it, its toString
method grabs your local time zone and uses it for rendering the string. This is true for new Date()
too. This behaviour has confused many, many programmers over the last 25 years.Calender
has got a time zone. It doesn’t change when you do calendar.setTime(new Date(1317816735000L));
.Oracle tutorial: Date Time explaining how to use java.time.
try this instead $(".video-divs.focused")
. This works if you are looking for video-divs that are focused.
My answer is "neither one".
I believe the most "Pythonic" way to do things is to NOT check beforehand if the key is in a dictionary and instead just write code that assumes it's there and catch any KeyErrors that get raised because it wasn't.
This is usually done with enclosing the code in a try...except
clause and is a well-known idiom usually expressed as "It's easier to ask forgiveness than permission" or with the acronym EAFP, which basically means it is better to try something and catch the errors instead for making sure everything's OK before doing anything. Why validate what doesn't need to be validated when you can handle exceptions gracefully instead of trying to avoid them? Because it's often more readable and the code tends to be faster if the probability is low that the key won't be there (or whatever preconditions there may be).
Of course, this isn't appropriate in all situations and not everyone agrees with the philosophy, so you'll need to decide for yourself on a case-by-case basis. Not surprisingly the opposite of this is called LBYL for "Look Before You Leap".
As a trivial example consider:
if 'name' in dct:
value = dct['name'] * 3
else:
logerror('"%s" not found in dictionary, using default' % name)
value = 42
vs
try:
value = dct['name'] * 3
except KeyError:
logerror('"%s" not found in dictionary, using default' % name)
value = 42
Although in the case it's almost exactly the same amount of code, the second doesn't spend time checking first and is probably slightly faster because of it (try...except block isn't totally free though, so it probably doesn't make that much difference here).
Generally speaking, testing in advance can often be much more involved and the savings gain from not doing it can be significant. That said, if 'name' in dict:
is better for the reasons stated in the other answers.
If you're interested in the topic, this message titled "EAFP vs LBYL (was Re: A little disappointed so far)" from the Python mailing list archive probably explains the difference between the two approached better than I have here. There's also a good discussion about the two approaches in the book Python in a Nutshell, 2nd Ed by Alex Martelli in chapter 6 on Exceptions titled Error-Checking Strategies. (I see there's now a newer 3rd edition, publish in 2017, which covers both Python 2.7 and 3.x).
Just turn the LIKE around
SELECT * FROM customers
WHERE 'Robert Bob Smith III, PhD.' LIKE CONCAT('%',name,'%')
Basically the answer lies in what really happens when a module is required via require
statement. Assuming this is the first time the module is being required.
For example:
var x = require('file1.js');
contents of file1.js:
module.exports = '123';
When the above statement is executed, a Module
object is created. Its constructor function is:
function Module(id, parent) {
this.id = id;
this.exports = {};
this.parent = parent;
if (parent && parent.children) {
parent.children.push(this);
}
this.filename = null;
this.loaded = false;
this.children = [];
}
As you see each module object has a property with name exports
. This is what is eventually returned as part of require
.
Next step of require is to wrap the contents of file1.js into an anonymous function like below:
(function (exports, require, module, __filename, __dirname) {
//contents from file1.js
module.exports = '123;
});
And this anonymous function is invoked the following way, module
here refers to the Module
Object created earlier.
(function (exports, require, module, __filename, __dirname) {
//contents from file1.js
module.exports = '123;
}) (module.exports,require, module, "path_to_file1.js","directory of the file1.js");
As we can see inside the function, exports
formal argument refers to module.exports
. In essence it's a convenience provided to the module programmer.
However this convenience need to be exercised with care. In any case if trying to assign a new object to exports ensure we do it this way.
exports = module.exports = {};
If we do it following way wrong way, module.exports
will still be pointing to the object created as part of module instance.
exports = {};
As as result adding anything to the above exports object will have no effect to module.exports object and nothing will be exported or returned as part of require.
We all have our preferred coding styles. This is what I did:
var pictures = new[]
{
new { id = Guid.NewGuid(), type = "image/jpeg", tag = "justme", path = @"C:\Pictures\JustMe.jpg" },
new { id = Guid.NewGuid(), type = "image/jpeg", tag = "justme-bw", path = @"C:\Pictures\JustMe-BW.jpg" }
}.ToList();
var content = $@"
<style type=""text/css"">
body {{ font-family: Arial; font-size: 10pt; }}
</style>
<body>
<h4>{DateTime.Now:dddd, MMMM d, yyyy h:mm:ss tt}</h4>
<p>Some pictures</p>
<div>
<p>Color Picture</p>
<img src=cid:{{justme}} />
</div>
<div>
<p>Black and White Picture</p>
<img src=cid:{{justme-bw}} />
</div>
<div>
<p>Color Picture repeated</p>
<img src=cid:{{justme}} />
</div>
</body>
";
// Update content with picture guid
pictures.ForEach(p => content = content.Replace($"{{{p.tag}}}", $"{p.id}"));
// Create Alternate View
var view = AlternateView.CreateAlternateViewFromString(content, Encoding.UTF8, MediaTypeNames.Text.Html);
// Add the resources
pictures.ForEach(p => view.LinkedResources.Add(new LinkedResource(p.path, p.type) { ContentId = p.id.ToString() }));
using (var client = new SmtpClient()) // Set properties as needed or use config file
using (MailMessage message = new MailMessage()
{
IsBodyHtml = true,
BodyEncoding = Encoding.UTF8,
Subject = "Picture Email",
SubjectEncoding = Encoding.UTF8,
})
{
message.AlternateViews.Add(view);
message.From = new MailAddress("[email protected]");
message.To.Add(new MailAddress("[email protected]"));
client.Send(message);
}
You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:
var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
if(!pattern.test(userinput))
{
alert('not a valid e-mail address');
}?
Default Colors:
android:textColorHint="@android:color/holo_blue_dark"
For Color code:
android:textColorHint="#33b5e5"
If you are using angular
and ie 9, 10
or edge
use :
myModule.config(['$httpProvider', function($httpProvider) {
//initialize get if not there
if (!$httpProvider.defaults.headers.get) {
$httpProvider.defaults.headers.get = {};
}
// Answer edited to include suggestions from comments
// because previous version of code introduced browser-related errors
//disable IE ajax request caching
$httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
// extra
$httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
$httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
}]);
To completely disable cache
.
@Günter's answer is correct. I just wanted to propose yet another method.
You could also add the host-binding inside the @Component()
-decorator. You can put the event and desired function call in the host-metadata-property like so:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
host: {
'(window:resize)': 'onResize($event)'
}
})
export class AppComponent{
onResize(event){
event.target.innerWidth; // window width
}
}
In my case Win 10. the file applicationHost.config is corrupted by VS 2012. And you can get the copy the history of this file under C:\inetpub\history. Then restart IIS and it works properly.
Have you already tried like
var open_link = window.open('','_blank');
open_link.location="somepage.html";
From the matplotlib docs on scatter 1:
cmap is only used if c is an array of floats
So colorlist needs to be a list of floats rather than a list of tuples as you have it now. plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns. vmin and vmax can then control the limits of your colorbar. Things outside vmin/vmax get the colors of the endpoints.
How does this work for you?
import matplotlib.pyplot as plt
cm = plt.cm.get_cmap('RdYlBu')
xy = range(20)
z = xy
sc = plt.scatter(xy, xy, c=z, vmin=0, vmax=20, s=35, cmap=cm)
plt.colorbar(sc)
plt.show()
JavaScript
If you want to return matched letters:
('Example 123').match(/[A-Z]/gi)
// Result: ["E", "x", "a", "m", "p", "l", "e"]
If you want to replace matched letters with stars ('*') for example:
('Example 123').replace(/[A-Z]/gi, '*')
//Result: "****** 123"*
Here is a pure JavaScript example of picking an image file, displaying it, looping through the image properties, and then re-sizing the image from the canvas into an IMG tag and explicitly setting the re-sized image type to jpeg.
If you right click the top image, in the canvas tag, and choose Save File As, it will default to a PNG format. If you right click, and Save File as the lower image, it will default to a JPEG format. Any file over 400px in width is reduced to 400px in width, and a height proportional to the original file.
<form class='frmUpload'>
<input name="picOneUpload" type="file" accept="image/*" onchange="picUpload(this.files[0])" >
</form>
<canvas id="cnvsForFormat" width="400" height="266" style="border:1px solid #c3c3c3"></canvas>
<div id='allImgProperties' style="display:inline"></div>
<div id='imgTwoForJPG'></div>
<script>
window.picUpload = function(frmData) {
console.log("picUpload ran: " + frmData);
var allObjtProperties = '';
for (objProprty in frmData) {
console.log(objProprty + " : " + frmData[objProprty]);
allObjtProperties = allObjtProperties + "<span>" + objProprty + ": " + frmData[objProprty] + ", </span>";
};
document.getElementById('allImgProperties').innerHTML = allObjtProperties;
var cnvs=document.getElementById("cnvsForFormat");
console.log("cnvs: " + cnvs);
var ctx=cnvs.getContext("2d");
var img = new Image;
img.src = URL.createObjectURL(frmData);
console.log('img: ' + img);
img.onload = function() {
var picWidth = this.width;
var picHeight = this.height;
var wdthHghtRatio = picHeight/picWidth;
console.log('wdthHghtRatio: ' + wdthHghtRatio);
if (Number(picWidth) > 400) {
var newHeight = Math.round(Number(400) * wdthHghtRatio);
} else {
return false;
};
document.getElementById('cnvsForFormat').height = newHeight;
console.log('width: 400 h: ' + newHeight);
//You must change the width and height settings in order to decrease the image size, but
//it needs to be proportional to the original dimensions.
console.log('This is BEFORE the DRAW IMAGE');
ctx.drawImage(img,0,0, 400, newHeight);
console.log('THIS IS AFTER THE DRAW IMAGE!');
//Even if original image is jpeg, getting data out of the canvas will default to png if not specified
var canvasToDtaUrl = cnvs.toDataURL("image/jpeg");
//The type and size of the image in this new IMG tag will be JPEG, and possibly much smaller in size
document.getElementById('imgTwoForJPG').innerHTML = "<img src='" + canvasToDtaUrl + "'>";
};
};
</script>
Here is a jsFiddle:
jsFiddle Pick, display, get properties, and Re-size an image file
In jsFiddle, right clicking the top image, which is a canvas, won't give you the same save options as right clicking the bottom image in an IMG tag.
If you want to modify an older commit, not the last one, you will need to use rebase
command as explained in here,Github help page , on the Amending the message of older or multiple commit messages section
Here is the solution which worked for me after MySQL 8.0 Installation on Windows 10.
Suppose MySQL username is root
and password is admin
Open command prompt and enter the following commands:
cd C:\Program Files\MySQL\MySQL Server 8.0\bin
mysql_upgrade -uroot -padmin
mysql -uroot -padmin
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'admin'