If you wish to create a pdf from php, pdflib will help you (as some others suggested).
Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.
So, the options I know are:
DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.
HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.
Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:
wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.
htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.
Starting with IPython 5.0 and matplotlib 2.0 you can avoid the use of IPython’s specific magic and use
matplotlib.pyplot.ion()/matplotlib.pyplot.ioff()
which have the advantages of working outside of IPython as well.
If you want the value you are assigning in the constructor, you need to add a method in the enum definition to return that value.
If you want a unique number that represent the enum value, you can use ordinal()
.
Got a solution to above problem in a different way where in although i would read entire csv file, but would tweek the display part to show only the content which is desired.
import pandas as pd
df = pd.read_csv('data.csv', skipinitialspace=True)
print df[['star_name', 'ra']]
This one could help in some of the scenario's in learning basics and filtering data on the basis of columns in dataframe.
def safeget(_dct, *_keys):
if not isinstance(_dct, dict): raise TypeError("Is not instance of dict")
def foo(dct, *keys):
if len(keys) == 0: return dct
elif not isinstance(_dct, dict): return None
else: return foo(dct.get(keys[0], None), *keys[1:])
return foo(_dct, *_keys)
assert safeget(dict()) == dict()
assert safeget(dict(), "test") == None
assert safeget(dict([["a", 1],["b", 2]]),"a", "d") == None
assert safeget(dict([["a", 1],["b", 2]]),"a") == 1
assert safeget({"a":{"b":{"c": 2}},"d":1}, "a", "b")["c"] == 2
To animate your 3D object, use the code:
<script>
$(document).ready(function(){
var x = 100;
var y = 0;
setInterval(function(){
x += 1;
y += 1;
var element = document.getElementById('cube');
element.style.webkitTransform = "translateZ(-100px) rotateY("+x+"deg) rotateX("+y+"deg)"; //for safari and chrome
element.style.MozTransform = "translateZ(-100px) rotateY("+x+"deg) rotateX("+y+"deg)"; //for firefox
},50);
//for other browsers use: "msTransform", "OTransform", "transform"
});
</script>
It is not good to use this method but if you really want to split it with regex
<primaryAddress.*>((.|\n)*?)<\/primaryAddress>
the verified answer returns the tags but this just return the value between tags.
Have you added this gem to your gemfile?
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
move that gem out of assets group and then run bundle again, I hope that would help!
I prefer to use the @ symbol so I see the query exactly as I can copy and paste into a query file:
string name = "Joe";
string gender = "M";
string query = String.Format(@"
SELECT
*
FROM
tableA
WHERE
Name = '{0}' AND
Gender = '{1}'", name, gender);
It's really great with long complex queries. Nice thing is it keeps tabs and line feeds so pasting into a query browser retains the nice formatting
Why don't you just save/serve the CSS file as UTF-8?
nav a:hover:after {
content: "?";
}
If that's not good enough, and you want to keep it all-ASCII:
nav a:hover:after {
content: "\2193";
}
The general format for a Unicode character inside a string is \000000
to \FFFFFF
– a backslash followed by six hexadecimal digits. You can leave out leading 0
digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.
Relevant part of the CSS2 spec:
Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:
- with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
- by providing exactly 6 hexadecimal digits: "\000026B" ("&B")
In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.
If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).
- Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
The identifier "te\st" is exactly the same identifier as "test".
Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).
The function takes an int
and returns the number of Ones in binary representation
public static int findOnes(int number)
{
if(number < 2)
{
if(number == 1)
{
count ++;
}
else
{
return 0;
}
}
value = number % 2;
if(number != 1 && value == 1)
count ++;
number /= 2;
findOnes(number);
return count;
}
You'll find debugging errors like this a lot easier if you catch any errors thrown from the execSQL call. eg:
try
{
db.execSQL(Create_CashBook);
}
catch (Exception e)
{
Log.e("ERROR", e.toString());
}
I found it's simple to do this via the svn cat
command so that you don't even have to specify a revision.
svn cat mydir/myfile > mydir/myfile
This probably won't role back the inode (metadata) data such as timestamps.
While @ajv-jsy's answer works most of the time, I had the same problem as @MarioVilas. If one of the strings to be compared contains a double quote ("), the variable expansion throws an error.
Example:
@echo off
SetLocal
set Lhs="
set Rhs="
if "%Lhs%" == "%Rhs%" echo Equal
Error:
echo was unexpected at this time.
Enable delayed expansion and use ! instead of %.
@echo off
SetLocal EnableDelayedExpansion
set Lhs="
set Rhs="
if !Lhs! == !Rhs! echo Equal
:: Surrounding with double quotes also works but appears (is?) unnecessary.
if "!Lhs!" == "!Rhs!" echo Equal
I have not been able to break it so far using this technique. It works with empty strings and all the symbols I threw at it.
Test:
@echo off
SetLocal EnableDelayedExpansion
:: Test empty string
set Lhs=
set Rhs=
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.
:: Test symbols
set Lhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
set Rhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.
no problem doing it with asp.... it's most natural to do so with MVC, but can be done with standard asp as well.
The MVC framework has all sorts of helper classes for JSON, if you can, I'd suggest sussing in some MVC-love, if not, you can probably easily just get the JSON helper classes used by MVC in and use them in the context of asp.net.
edit:
here's an example of how to return JSON data with MVC. This would be in your controller class. This is out of the box functionality with MVC--when you crate a new MVC project this stuff gets auto-created so it's nothing special. The only thing that I"m doing is returning an actionResult that is JSON. The JSON method I'm calling is a method on the Controller class. This is all very basic, default MVC stuff:
public ActionResult GetData()
{
var data = new { Name="kevin", Age=40 };
return Json(data, JsonRequestBehavior.AllowGet);
}
This return data could be called via JQuery as an ajax call thusly:
$.get("/Reader/GetData/", function(data) { someJavacriptMethodOnData(data); });
To get the text from this cell-
<table>
<tr id="somerow">
<td>some text</td>
</tr>
</table>
You can use this -
var Row = document.getElementById("somerow");
var Cells = Row.getElementsByTagName("td");
alert(Cells[0].innerText);
in my case, I got the same exception because the user that I configured in the app did not existed in the DB, creating the user and granting needed permissions solved the problem.
@POST
@Path ("Employee")
@Consumes("application/json")
@Produces("application/json")
public JSONObject postEmployee(JSONObject jsonObject)throws Exception{
return jsonObject;
}
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
INSERT INTO action_2_members (campaign_id, mobile, vote, vote_date)
SELECT campaign_id, from_number, received_msg, date_received
FROM `received_txts`
WHERE `campaign_id` = '8'
Here is how to use telnet in bash shell/expect
#!/usr/bin/expect
# just do a chmod 755 one the script
# ./YOUR_SCRIPT_NAME.sh $YOUHOST $PORT
# if you get "Escape character is '^]'" as the output it means got connected otherwise it has failed
set ip [lindex $argv 0]
set port [lindex $argv 1]
set timeout 5
spawn telnet $ip $port
expect "'^]'."
Dictionaries do not have any inherent order. Or, rather, their inherent order is "arbitrary but not random", so it doesn't do you any good.
In different terms, your d
and your e
would be exactly equivalent dictionaries.
What you can do here is to use an OrderedDict
:
from collections import OrderedDict
d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
'124': { 'key1': 6, 'key2': 56, 'key3': 6 },
'125': { 'key1': 7, 'key2': 44, 'key3': 9 },
}
d_ascending = OrderedDict(sorted(d.items(), key=lambda kv: kv[1]['key3']))
d_descending = OrderedDict(sorted(d.items(),
key=lambda kv: kv[1]['key3'], reverse=True))
The original d
has some arbitrary order. d_ascending
has the order you thought you had in your original d
, but didn't. And d_descending
has the order you want for your e
.
If you don't really need to use e
as a dictionary, but you just want to be able to iterate over the elements of d
in a particular order, you can simplify this:
for key, value in sorted(d.items(), key=lambda kv: kv[1]['key3'], reverse=True):
do_something_with(key, value)
If you want to maintain a dictionary in sorted order across any changes, instead of an OrderedDict
, you want some kind of sorted dictionary. There are a number of options available that you can find on PyPI, some implemented on top of trees, others on top of an OrderedDict
that re-sorts itself as necessary, etc.
Not sure about solutions but a temporary workaround is to ask eslint to ignore it by adding the following on top of the problem line.
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
@ryenus, You need to loop through the result. This is how I'd do it in vbscript;
Set xmlDoc = CreateObject("Msxml2.DOMDocument")
xmlDoc.setProperty "SelectionLanguage", "XPath"
xmlDoc.load("kids.xml")
'Remove the id=1 attribute on Parent to return all child names for all Parent nodes
For Each c In xmlDoc.selectNodes ("//Parent[@id='1']/Children/child/@name")
Wscript.Echo c.text
Next
A nice option is to use tar -tvvf <filePath>
which adds a line that reports the kind of file.
Example in a valid .tar file:
> tar -tvvf filename.tar
drwxr-xr-x 0 diegoreymendez staff 0 Jul 31 12:46 ./testfolder2/
-rw-r--r-- 0 diegoreymendez staff 82 Jul 31 12:46 ./testfolder2/._.DS_Store
-rw-r--r-- 0 diegoreymendez staff 6148 Jul 31 12:46 ./testfolder2/.DS_Store
drwxr-xr-x 0 diegoreymendez staff 0 Jul 31 12:42 ./testfolder2/testfolder/
-rw-r--r-- 0 diegoreymendez staff 82 Jul 31 12:42 ./testfolder2/testfolder/._.DS_Store
-rw-r--r-- 0 diegoreymendez staff 6148 Jul 31 12:42 ./testfolder2/testfolder/.DS_Store
-rw-r--r-- 0 diegoreymendez staff 325377 Jul 5 09:50 ./testfolder2/testfolder/Scala.pages
Archive Format: POSIX ustar format, Compression: none
Corrupted .tar file:
> tar -tvvf corrupted.tar
tar: Unrecognized archive format
Archive Format: (null), Compression: none
tar: Error exit delayed from previous errors.
A good reason, which you have sort of touched on, is that once the CSRF cookie has been received, it is then available for use throughout the application in client script for use in both regular forms and AJAX POSTs. This will make sense in a JavaScript heavy application such as one employed by AngularJS (using AngularJS doesn't require that the application will be a single page app, so it would be useful where state needs to flow between different page requests where the CSRF value cannot normally persist in the browser).
Consider the following scenarios and processes in a typical application for some pros and cons of each approach you describe. These are based on the Synchronizer Token Pattern.
Advantages:
Disadvantages:
Advantages:
Disadvantages:
Advantages:
Disadvantages:
Advantages:
Disadvantages:
Advantages:
Disadvantages:
So the cookie approach is fairly dynamic offering an easy way to retrieve the cookie value (any HTTP request) and to use it (JS can add the value to any form automatically and it can be employed in AJAX requests either as a header or as a form value). Once the CSRF token has been received for the session, there is no need to regenerate it as an attacker employing a CSRF exploit has no method of retrieving this token. If a malicious user tries to read the user's CSRF token in any of the above methods then this will be prevented by the Same Origin Policy. If a malicious user tries to retrieve the CSRF token server side (e.g. via curl
) then this token will not be associated to the same user account as the victim's auth session cookie will be missing from the request (it would be the attacker's - therefore it won't be associated server side with the victim's session).
As well as the Synchronizer Token Pattern there is also the Double Submit Cookie CSRF prevention method, which of course uses cookies to store a type of CSRF token. This is easier to implement as it does not require any server side state for the CSRF token. The CSRF token in fact could be the standard authentication cookie when using this method, and this value is submitted via cookies as usual with the request, but the value is also repeated in either a hidden field or header, of which an attacker cannot replicate as they cannot read the value in the first place. It would be recommended to choose another cookie however, other than the authentication cookie so that the authentication cookie can be secured by being marked HttpOnly. So this is another common reason why you'd find CSRF prevention using a cookie based method.
You say you've had problems with Navicat. For the record, I use Navicat and I haven't experienced the issue you describe. You might want to dig around, see if there's a reason for your problem and/or a solution, because given the question asked, my first recommendation would have been Navicat.
But if you want alternative suggestions, here are a few that I know of and have used:
MySQL has its own tool which you can download for free, called MySQL Workbench. Download it from here: http://wb.mysql.com/. My experience is that it's powerful, but I didn't really like the UI. But that's just my personal taste.
Another free program you might want to try is HeidiSQL. It's more similar to Navicat than MySQL Workbench. A colleague of mine loves it.
(interesting to note, by the way, that MariaDB (the forked version of MySQL) is currently shipped with HeidiSQL as its GUI tool)
Finally, if you're running a web server on your machine, there's always the option of a browser-based tool like PHPMyAdmin. It's actually a surprisingly powerful piece of software.
$ PATH=$PATH:/Library/PostgreSQL/9.1/bin sudo gem install pg
replace the 9.1 for the version installed on your system.
If it's WPF, there is a collection of colors in the static class Brushes
.
TextBox.Background = Brushes.Red;
Of course, you can create your own brush if you want.
LinearGradientBrush myBrush = new LinearGradientBrush();
myBrush.GradientStops.Add(new GradientStop(Colors.Yellow, 0.0));
myBrush.GradientStops.Add(new GradientStop(Colors.Orange, 0.5));
myBrush.GradientStops.Add(new GradientStop(Colors.Red, 1.0));
TextBox.Background = myBrush;
pip won't install binary packages and isn't well tested on Windows.
As Windows doesn't come with a compiler by default pip often can't be used there. easy_install can install binary packages for Windows.
A shorter version of the accepted answer using Guava:
.getMap(Iterables.toArray(locations, WorldLocation.class));
can be shortened further by statically importing toArray:
import static com.google.common.collect.toArray;
// ...
.getMap(toArray(locations, WorldLocation.class));
As Richard said, StringWriter
is the way forward. There's one snag, however: by default, StringWriter
will advertise itself as being in UTF-16. Usually XML is in UTF-8. You can fix this by subclassing StringWriter;
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
}
This will affect the declaration written by XmlWriter
. Of course, if you then write the string out elsewhere in binary form, make sure you use an encoding which matches whichever encoding you fix for the StringWriter
. (The above code always assumes UTF-8; it's trivial to make a more general version which accepts an encoding in the constructor.)
You'd then use:
using (TextWriter writer = new Utf8StringWriter())
{
using (XmlWriter xmlWriter = XmlWriter.Create(writer))
{
...
}
return writer.ToString();
}
Sorry for awakening an old question like this. But I think what the original author wanted as an answer was:
You need to force your program to make the graphic update after you make the change to the textbox1. You can do that by invoking Update();
textBox1.Text += "\r\nThread Sleeps!";
textBox1.Update();
System.Threading.Thread.Sleep(4000);
textBox1.Text += "\r\nThread awakens!";
textBox1.Update();
Normally this will be done automatically when the thread is done.
Ex, you press a button, changes are made to the text, thread dies, and then .Update()
is fired and you see the changes.
(I'm not an expert so I cant really tell you when its fired, but its something similar to this any way.)
In this case, you make a change, pause the thread, and then change the text again, and when the thread finally dies the .Update()
is fired. This resulting in you only seeing the last change made to the text.
You would experience the same issue if you had a long execution between the text changes.
The easiest and most intuitive solution for me was to combine the column names using get_level_values. This prevents duplicate column names when you do more than one aggregation on the same column:
level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
df.columns = level_one + level_two
If you want a separator between columns, you can do this. This will return the same thing as Seiji Armstrong's comment on the accepted answer that only includes underscores for columns with values in both index levels:
level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
column_separator = ['_' if x != '' else '' for x in level_two]
df.columns = level_one + column_separator + level_two
I know this does the same thing as Andy Hayden's great answer above, but I think it is a bit more intuitive this way and is easier to remember (so I don't have to keep referring to this thread), especially for novice pandas users.
This method is also more extensible in the case where you may have 3 column levels.
level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
level_three = df.columns.get_level_values(2).astype(str)
df.columns = level_one + level_two + level_three
Using Powershell you can do this:
# Checks for updates and changes in working copy.
# Regex: Excludes unmodified (first 7 columns blank). To exclude more add criteria to negative look ahead.
# -u: svn gets updates
$regex = '^(?!\s{7}).{7}\s+(.+)';
svn status -u | %{ if($_ -match $regex){ $_ } };
This will include property changes. These show in column 2. It will also catch other differences in files that show in columns 3-7.
Sources:
svn status: http://svnbook.red-bean.com/en/1.8/svn.ref.svn.c.status.html
Regex to match results of svn status: Using powershell and svn to delete unversioned files
When I got this error I wasn't even trying to sign the app. I was writing a test app and didn't care about signing. In order to get rid of this message I had to select "Don't Code Sign" from Build Settings under Code Signing.
If you're using Weebly, start by viewing the published site and right-clicking the image to Copy Image Address. Then in Weebly, go to Edit Site, Pages, click the page you wish to use, SEO Settings, under Header Code enter the code from Shef's answer:
<meta property="og:image" content="/uploads/..." />
just replacing /uploads/... with the copied image address. Click Publish to apply the change.
You can skip the part of Shef's answer about namespace, because that's already set by default in Weebly.
Using the arrow package:
>>> import arrow
>>> arrow.get(2010, 12, 31).timestamp
1293753600
>>> time.gmtime(1293753600)
time.struct_time(tm_year=2010, tm_mon=12, tm_mday=31,
tm_hour=0, tm_min=0, tm_sec=0,
tm_wday=4, tm_yday=365, tm_isdst=0)
Internet Explorer 9 and lower : You could use conditional comments to load an IE-specific stylesheet for any version (or combination of versions) that you wanted to specifically target.like below using external stylesheet.
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="all-ie-only.css" />
<![endif]-->
However, beginning in version 10, conditional comments are no longer supported in IE.
Internet Explorer 10 & 11 : Create a media query using -ms-high-contrast, in which you place your IE 10 and 11-specific CSS styles. Because -ms-high-contrast is Microsoft-specific (and only available in IE 10+), it will only be parsed in Internet Explorer 10 and greater.
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
/* IE10+ CSS styles go here */
}
Microsoft Edge 12 : Can use the @supports rule Here is a link with all the info about this rule
@supports (-ms-accelerator:true) {
/* IE Edge 12+ CSS styles go here */
}
Inline rule IE8 detection
I have 1 more option but it is only detect IE8 and below version.
/* For IE css hack */
margin-top: 10px\9 /* apply to all ie from 8 and below */
*margin-top:10px; /* apply to ie 7 and below */
_margin-top:10px; /* apply to ie 6 and below */
As you specefied for embeded stylesheet. I think you need to use media query and condition comment for below version.
Jacob's reply to John T works perfectly to delete the whole line, and you can Find in Files with that. Make sure to check "Regular expression" at bottom.
Solution: ^.*#region.*$
If what you need is UPDATE from SELECT statement you can do something like this:
UPDATE suppliers
SET city = (SELECT customers.city FROM customers
WHERE customers.customer_name = suppliers.supplier_name)
Another way to get only the numbers in a regex string is as shown below:
$output = preg_replace("/\D+/", "", $input);
For me, it was all about setting up my web server to use the latest-and-greatest tech to support my ASP.NET 5 application!
The following URL gave me all the tips I needed:
https://docs.asp.net/en/1.0.0-rc1/publishing/iis-with-msdeploy.html
Hope this helps :)
JDBC is the predecessor of JPA.
JDBC is a bridge between the Java world and the databases world. In JDBC you need to expose all dirty details needed for CRUD operations, such as table names, column names, while in JPA (which is using JDBC underneath), you also specify those details of database metadata, but with the use of Java annotations.
So JPA creates update queries for you and manages the entities that you looked up or created/updated (it does more as well).
If you want to do JPA without a Java EE container, then Spring and its libraries may be used with the very same Java annotations.
Or just click View, ToolBars, Edit. Then you can select a block of code and then click the Comment or Uncomment toolbar button to do everything in one click.
As an aside, you can Tab/Shift+Tab a block of selected text also. When I was a noobie, I didn't know that for a long time and would do them one line at a time.
Good Luck!
Usually you hear Task is a higher level concept than thread... and that's what this phrase means:
You can't use Abort/ThreadAbortedException, you should support
cancel event in your "business code" periodically testing token.IsCancellationRequested
flag (also avoid long or timeoutless connections e.g. to db, otherwise you will never get a chance to test this flag). By the similar reason Thread.Sleep(delay)
call should be replaced with Task.Delay(delay, token)
call (passing token inside to have possibility to interrupt delay).
There are no thread's Suspend
and Resume
methods functionality with tasks. Instance of task can't be reused either.
But you get two new tools:
a) continuations
// continuation with ContinueWhenAll - execute the delegate, when ALL
// tasks[] had been finished; other option is ContinueWhenAny
Task.Factory.ContinueWhenAll(
tasks,
() => {
int answer = tasks[0].Result + tasks[1].Result;
Console.WriteLine("The answer is {0}", answer);
}
);
b) nested/child tasks
//StartNew - starts task immediately, parent ends whith child
var parent = Task.Factory.StartNew
(() => {
var child = Task.Factory.StartNew(() =>
{
//...
});
},
TaskCreationOptions.AttachedToParent
);
So system thread is completely hidden from task, but still task's code is executed in the concrete system thread. System threads are resources for tasks and ofcourse there is still thread pool under the hood of task's parallel execution. There can be different strategies how thread get new tasks to execute. Another shared resource TaskScheduler cares about it. Some problems that TaskScheduler solves 1) prefer to execute task and its conitnuation in the same thread minimizing switching cost - aka inline execution) 2) prefer execute tasks in an order they were started - aka PreferFairness 3) more effective distribution of tasks between inactive threads depending on "prior knowledge of tasks activity" - aka Work Stealing. Important: in general "async" is not same as "parallel". Playing with TaskScheduler options you can setup async tasks be executed in one thread synchronously. To express parallel code execution higher abstractions (than Tasks) could be used: Parallel.ForEach
, PLINQ
, Dataflow
.
Tasks are integrated with C# async/await features aka Promise Model, e.g there requestButton.Clicked += async (o, e) => ProcessResponce(await client.RequestAsync(e.ResourceName));
the execution of client.RequestAsync
will not block UI thread. Important: under the hood Clicked
delegate call is absolutely regular (all threading is done by compiler).
That is enough to make a choice. If you need to support Cancel functionality of calling legacy API that tends to hang (e.g. timeoutless connection) and for this case supports Thread.Abort(), or if you are creating multithread background calculations and want to optimize switching between threads using Suspend/Resume, that means to manage parallel execution manually - stay with Thread. Otherwise go to Tasks because of they will give you easy manipulate on groups of them, are integrated into the language and make developers more productive - Task Parallel Library (TPL) .
Here is the python example of calling another lambda function and gets its response. There is two invocation type 'RequestResponse' and 'Event'. Use 'RequestResponse' if you want to get the response of lambda function and use 'Event' to invoke lambda function asynchronously. So both ways asynchronous and synchronous are available.
lambda_response = lambda_client.invoke(
FunctionName = lambda_name,
InvocationType = 'RequestResponse',
Payload = json.dumps(input)
)
resp_str = lambda_response['Payload'].read()
response = json.loads(resp_str)
Here is the answer for those of you who need a Boostrap 3 solution.
In bootstrap 3 use 'shown.bs.tab' instead of 'shown' in the next line
// tab
$('#rowTab a:first').tab('show');
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
//show selected tab / active
console.log ( $(e.target).attr('id') );
});
/dev/tty
is a synonym for the controlling terminal (if any) of the current process. As jtl999 says, it's a character special file; that's what the c
in the ls -l
output means.
man 4 tty
or man -s 4 tty
should give you more information, or you can read the man page online here.
Incidentally, pwd > /dev/tty
doesn't necessarily print to the shell's stdout (though it is the pwd
command's standard output). If the shell's standard output has been redirected to something other than the terminal, /dev/tty
still refers to the terminal.
You can also read from /dev/tty
, which will normally read from the keyboard.
While jball's answer is an excellent description of content insets, it doesn't answer the question of when to use it. I'll borrow from his diagrams:
_|?_cW_?_|_?_
| |
---------------
|content| ?
? |content| contentInset.top
cH |content|
? |content| contentInset.bottom
|content| ?
---------------
|content|
-------------?-
That's what you get when you do it, but the usefulness of it only shows when you scroll:
_|?_cW_?_|_?_
|content| ? content is still visible
---------------
|content| ?
? |content| contentInset.top
cH |content|
? |content| contentInset.bottom
|content| ?
---------------
_|_______|___
?
That top row of content will still be visible because it's still inside the frame of the scroll view. One way to think of the top offset is "how much to shift the content down the scroll view when we're scrolled all the way to the top"
To see a place where this is actually used, look at the build-in Photos app on the iphone. The Navigation bar and status bar are transparent, and the contents of the scroll view are visible underneath. That's because the scroll view's frame extends out that far. But if it wasn't for the content inset, you would never be able to have the top of the content clear that transparent navigation bar when you go all the way to the top.
Readonly will not "grayout" the textbox and will still submit the value on a postback.
As of Django 1.10, the patterns
module has been removed (it had been deprecated since 1.8).
Luckily, it should be a simple edit to remove the offending code, since the urlpatterns
should now be stored in a plain-old list:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
# ... your url patterns
]
Below code is very useful to hide default browse button and use custom instead:
(function($) {_x000D_
$('input[type="file"]').bind('change', function() {_x000D_
$("#img_text").html($('input[type="file"]').val());_x000D_
});_x000D_
})(jQuery)
_x000D_
.file-input-wrapper {_x000D_
height: 30px;_x000D_
margin: 2px;_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
width: 118px;_x000D_
background-color: #fff;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.file-input-wrapper>input[type="file"] {_x000D_
font-size: 40px;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 0;_x000D_
opacity: 0;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.file-input-wrapper>.btn-file-input {_x000D_
background-color: #494949;_x000D_
border-radius: 4px;_x000D_
color: #fff;_x000D_
display: inline-block;_x000D_
height: 34px;_x000D_
margin: 0 0 0 -1px;_x000D_
padding-left: 0;_x000D_
width: 121px;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.file-input-wrapper:hover>.btn-file-input {_x000D_
//background-color: #494949;_x000D_
}_x000D_
_x000D_
#img_text {_x000D_
float: right;_x000D_
margin-right: -80px;_x000D_
margin-top: -14px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
<div class="file-input-wrapper">_x000D_
<button class="btn-file-input">SELECT FILES</button>_x000D_
<input type="file" name="image" id="image" value="" />_x000D_
</div>_x000D_
<span id="img_text"></span>_x000D_
</body>
_x000D_
Well try ini_set('memory_limit', '256M');
134217728 bytes = 128 MB
Or rewrite the code to consume less memory.
An actual JSON request would look like this:
data: '{"command":"on"}',
Where you're sending an actual JSON string. For a more general solution, use JSON.stringify()
to serialize an object to JSON, like this:
data: JSON.stringify({ "command": "on" }),
To support older browsers that don't have the JSON
object, use json2.js which will add it in.
What's currently happening is since you have processData: false
, it's basically sending this: ({"command":"on"}).toString()
which is [object Object]
...what you see in your request.
You corrupted your designer. ReAdd your Installer Component. It should have a serviceInstaller and a serviceProcessInstaller. The serviceInstaller with property Startup Method set to Automatic will startup when installed and after each reboot.
In my program, I use some logic to judge if it was onload: watching it's network request, if there was no new request on past 200ms, I treat it onload.
Use this, after onLoadFinish().
function onLoadComplete(page, callback){
var waiting = []; // request id
var interval = 200; //ms time waiting new request
var timer = setTimeout( timeout, interval);
var max_retry = 3; //
var counter_retry = 0;
function timeout(){
if(waiting.length && counter_retry < max_retry){
timer = setTimeout( timeout, interval);
counter_retry++;
return;
}else{
try{
callback(null, page);
}catch(e){}
}
}
//for debug, log time cost
var tlogger = {};
bindEvent(page, 'request', function(req){
waiting.push(req.id);
});
bindEvent(page, 'receive', function (res) {
var cT = res.contentType;
if(!cT){
console.log('[contentType] ', cT, ' [url] ', res.url);
}
if(!cT) return remove(res.id);
if(cT.indexOf('application') * cT.indexOf('text') != 0) return remove(res.id);
if (res.stage === 'start') {
console.log('!!received start: ', res.id);
//console.log( JSON.stringify(res) );
tlogger[res.id] = new Date();
}else if (res.stage === 'end') {
console.log('!!received end: ', res.id, (new Date() - tlogger[res.id]) );
//console.log( JSON.stringify(res) );
remove(res.id);
clearTimeout(timer);
timer = setTimeout(timeout, interval);
}
});
bindEvent(page, 'error', function(err){
remove(err.id);
if(waiting.length === 0){
counter_retry = 0;
}
});
function remove(id){
var i = waiting.indexOf( id );
if(i < 0){
return;
}else{
waiting.splice(i,1);
}
}
function bindEvent(page, evt, cb){
switch(evt){
case 'request':
page.onResourceRequested = cb;
break;
case 'receive':
page.onResourceReceived = cb;
break;
case 'error':
page.onResourceError = cb;
break;
case 'timeout':
page.onResourceTimeout = cb;
break;
}
}
}
Resize image with high quality:
private static InputStream resizeImage(InputStream uploadedInputStream, String fileName, int width, int height) {
try {
BufferedImage image = ImageIO.read(uploadedInputStream);
Image originalImage= image.getScaledInstance(width, height, Image.SCALE_DEFAULT);
int type = ((image.getType() == 0) ? BufferedImage.TYPE_INT_ARGB : image.getType());
BufferedImage resizedImage = new BufferedImage(width, height, type);
Graphics2D g2d = resizedImage.createGraphics();
g2d.drawImage(originalImage, 0, 0, width, height, null);
g2d.dispose();
g2d.setComposite(AlphaComposite.Src);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(resizedImage, fileName.split("\\.")[1], byteArrayOutputStream);
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
} catch (IOException e) {
// Something is going wrong while resizing image
return uploadedInputStream;
}
}
In my case i just went through following steps in windows 10.
OracelServeceXE
, OracleXEClrAgeng
, OracleXETNSListener
Start
/Restart
For C, at least, per C11 6.7.5:
A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:
for an object, causes storage to be reserved for that object;
for a function, includes the function body;
for an enumeration constant, is the (only) declaration of the identifier;
for a typedef name, is the first (or only) declaration of the identifier.
Per C11 6.7.9.8-10:
An initializer specifies the initial value stored in an object ... if an object that has automatic storage is not initialized explicitly, its value is indeterminate.
So, broadly speaking, a declaration introduces an identifier and provides information about it. For a variable, a definition is a declaration which allocates storage for that variable.
Initialization is the specification of the initial value to be stored in an object, which is not necessarily the same as the first time you explicitly assign a value to it. A variable has a value when you define it, whether or not you explicitly give it a value. If you don't explicitly give it a value, and the variable has automatic storage, it will have an initial value, but that value will be indeterminate. If it has static storage, it will be initialized implicitly depending on the type (e.g. pointer types get initialized to null pointers, arithmetic types get initialized to zero, and so on).
So, if you define an automatic variable without specifying an initial value for it, such as:
int myfunc(void) {
int myvar;
...
You are defining it (and therefore also declaring it, since definitions are declarations), but not initializing it. Therefore, definition does not equal declaration plus initialization.
I know I come late, but only recently I was able to implement such "addHeader" to the Adapter. In my FlexibleAdapter project you can call setHeader
on a Sectionable item, then you call showAllHeaders
. If you need only 1 header then the first item should have the header. If you delete this item, then the header is automatically linked to the next one.
Unfortunately footers are not covered (yet).
The FlexibleAdapter allows you to do much more than create headers/sections. You really should have a look: https://github.com/davideas/FlexibleAdapter.
Please do not do that, it is very annoying.
The right menu is there for a reason, and it should be left there. Many browser extensions add entries to the right click menu and the user should be able to use it in any page he visits.
Moreover you can use all of the functionality of the right click menu in other ways (keyboard shortcuts, browser menu etc etc etc) so blocking the right click menu has the only effect of annoying the user.
PS: If really you cannot resist the urge to block it at least do not put a popup saying "no right click allowed".
There seems to be a really easy solution when dealing with data type issues.
Basically, at the end of Excel connection string, add ;IMEX=1;"
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\YOURSERVER\shared\Client Projects\FOLDER\Data\FILE.xls;Extended Properties="EXCEL 8.0;HDR=YES;IMEX=1";
This will resolve data type issues such as columns where values are mixed with text and numbers.
To get to connection property, right click on Excel connection manager below control flow and hit properties. It'll be to the right under solution explorer. Hope that helps.
This example selects a new Range
of Cells
defined by the current cell to a cell 5 to the right.
Note that .Offset
takes arguments of Offset(row, columns)
and can be quite useful.
Sub testForStackOverflow()
Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub
Have a look at at File comparison tools, from which I am using WinMerge. It has an ability to compare XML documents (you may wish to enable DisplayXMLFiles
prefilter).
DisplayXMLFiles.dll - This plugin pretty-prints XML files nicely by inserting tabs and line breaks. This is useful for XML files that do not have line returns in convenient locations.
See also my feature comparison table.
This is excellent practice.
By creating variables inside loops, you ensure their scope is restricted to inside the loop. It cannot be referenced nor called outside of the loop.
This way:
If the name of the variable is a bit "generic" (like "i"), there is no risk to mix it with another variable of same name somewhere later in your code (can also be mitigated using the -Wshadow
warning instruction on GCC)
The compiler knows that the variable scope is limited to inside the loop, and therefore will issue a proper error message if the variable is by mistake referenced elsewhere.
Last but not least, some dedicated optimization can be performed more efficiently by the compiler (most importantly register allocation), since it knows that the variable cannot be used outside of the loop. For example, no need to store the result for later re-use.
In short, you are right to do it.
Note however that the variable is not supposed to retain its value between each loop. In such case, you may need to initialize it every time. You can also create a larger block, encompassing the loop, whose sole purpose is to declare variables which must retain their value from one loop to another. This typically includes the loop counter itself.
{
int i, retainValue;
for (i=0; i<N; i++)
{
int tmpValue;
/* tmpValue is uninitialized */
/* retainValue still has its previous value from previous loop */
/* Do some stuff here */
}
/* Here, retainValue is still valid; tmpValue no longer */
}
For question #2: The variable is allocated once, when the function is called. In fact, from an allocation perspective, it is (nearly) the same as declaring the variable at the beginning of the function. The only difference is the scope: the variable cannot be used outside of the loop. It may even be possible that the variable is not allocated, just re-using some free slot (from other variable whose scope has ended).
With restricted and more precise scope come more accurate optimizations. But more importantly, it makes your code safer, with less states (i.e. variables) to worry about when reading other parts of the code.
This is true even outside of an if(){...}
block. Typically, instead of :
int result;
(...)
result = f1();
if (result) then { (...) }
(...)
result = f2();
if (result) then { (...) }
it's safer to write :
(...)
{
int const result = f1();
if (result) then { (...) }
}
(...)
{
int const result = f2();
if (result) then { (...) }
}
The difference may seem minor, especially on such a small example.
But on a larger code base, it will help : now there is no risk to transport some result
value from f1()
to f2()
block. Each result
is strictly limited to its own scope, making its role more accurate. From a reviewer perspective, it's much nicer, since he has less long range state variables to worry about and track.
Even the compiler will help better : assuming that, in the future, after some erroneous change of code, result
is not properly initialized with f2()
. The second version will simply refuse to work, stating a clear error message at compile time (way better than run time). The first version will not spot anything, the result of f1()
will simply be tested a second time, being confused for the result of f2()
.
The open-source tool CppCheck (a static analysis tool for C/C++ code) provides some excellent hints regarding optimal scope of variables.
In response to comment on allocation: The above rule is true in C, but might not be for some C++ classes.
For standard types and structures, the size of variable is known at compilation time. There is no such thing as "construction" in C, so the space for the variable will simply be allocated into the stack (without any initialization), when the function is called. That's why there is a "zero" cost when declaring the variable inside a loop.
However, for C++ classes, there is this constructor thing which I know much less about. I guess allocation is probably not going to be the issue, since the compiler shall be clever enough to reuse the same space, but the initialization is likely to take place at each loop iteration.
Access-Engine does not support
SELECT count(DISTINCT....) FROM ...
You have to do it like this:
SELECT count(*)
FROM
(SELECT DISTINCT Name FROM table1)
Its a little workaround... you're counting a DISTINCT selection.
"s" is not a "char*", it's a "char[4]". And so, "&s" is not a "char**", but actually "a pointer to an array of 4 characater". Your compiler may treat "&s" as if you had written "&s[0]", which is roughly the same thing, but is a "char*".
When you write "char** p = &s;" you are trying to say "I want p to be set to the address of the thing which currently points to "asd". But currently there is nothing which points to "asd". There is just an array which holds "asd";
char s[] = "asd";
char *p = &s[0]; // alternately you could use the shorthand char*p = s;
char **pp = &p;
You can simplify your code down to
url = "http://worldcup.kimonolabs.com/api/players?apikey=xxx"
json_obj = urllib2.urlopen(url).read
player_json_list = json.loads(json_obj)
for player in readable_json_list:
print player['firstName']
You were trying to access a list element using dictionary syntax. the equivalent of
foo = [1, 2, 3, 4]
foo["1"]
It can be confusing when you have lists of dictionaries and keeping the nesting in order.
Seems to be identical just in case that SQL server will not try to read data which is not required for the query, the optimizer is clever enough
It can have sense when join on complex query (i.e which have joings, groupings etc itself) then, yes, it is better to specify required fields.
But there is one more point. If the query is simple there is no difference but EVERY extra action even which is supposed to improve performance makes optimizer works harder and optimizer can fail to get the best plan in time and will run not optimal query. So extras select can be a such action which can even decrease performance
As @David Heffeman indicates the recommendation is to use .yaml
when possible, and the recommendation has been that way since September 2006.
That some projects use .yml
is mostly because of ignorance of the implementers/documenters: they wanted to use YAML because of readability, or some other feature not available in other formats, were not familiar with the recommendation and and just implemented what worked, maybe after looking at some other project/library (without questioning whether what was done is correct).
The best way to approach this is to be rigorous when creating new files (i.e. use .yaml
) and be permissive when accepting input (i.e. allow .yml
when you encounter it), possible automatically upgrading/correcting these errors when possible.
The other recommendation I have is to document the argument(s) why you have to use .yml
, when you think you have to. That way you don't look like an ignoramus, and give others the opportunity to understand your reasoning. Of course "everybody else is doing it" and "On Google .yml
has more pages than .yaml
" are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a .yml
extension instead of the correct .yaml
, but I think you will be hard pressed to do so.
Some projects realize (too late) that they use the incorrect extension (e.g. originally docker-compose
used .yml
, but in later versions started to use .yaml
, although they still support .yml
). Others still seem ignorant about the correct extension, like AppVeyor early 2019, but allow you to specify the configuration file for a project, including extension. This allows you to get the configuration file out of your face as well as giving it the proper extension: I use .appveyor.yaml
instead of appveyor.yml
for building the windows wheels of my YAML parser for Python).
On the other hand:
The Yaml (sic!) component of Symfony2 implements a selected subset of features defined in the YAML 1.2 version specification.
So it seems fitting that they also use a subset of the recommended extension.
AutoPostBack = true
permits control to post back to the server. It is associated with an Event.
Example:
<asp:DropDownList id="id" runat="server" AutoPostBack="true" OnSelectIndexChanged="..."/>
The aspx page with the above drop down list does not need an asp:button
to do the post back. When you change an option in the drop down list, the page gets posted back to the server.
Default value of AutoPostBack
on control is false.
Since JavaScript FileList is readonly and cannot be manipulated directly,
BEST METHOD
You will have to loop through the input.files
while comparing it with the index
of the file you want to remove. At the same time, you will use new DataTransfer()
to set a new list of files excluding the file you want to remove from the file list.
With this approach, the value of the input.files
itself is changed.
removeFileFromFileList(index) {
const dt = new DataTransfer()
const input = document.getElementById('files')
const { files } = input
for (let i = 0; i < files.length; i++) {
const file = files[i]
if (index !== i) dt.items.add(file) // here you exclude the file. thus removing it.
input.files = dt.files
}
}
ALTERNATIVE METHOD
Another simple method is to convert the FileList into an array and then splice it.
But this approach will not change the input.files
const input = document.getElementById('files')
// as an array, u have more freedom to transform the file list using array functions.
const fileListArr = Array.from(input.files)
fileListArr.splice(index, 1) // here u remove the file
console.log(fileListArr)
This is how I solved it on Windows. I have git installed separately, and Idea just picks git's options automatically (Default Idea config, as I would get from clean installer).
Open the project in the command line. Make some changes there. And commit and push files via git which is installed on my machine. During push it will open a windows asking me to enter username and password. After that, when I make a commit-push from idea, it will simply work.
I installed the Role plugin under Jenkins-3.5, but it does not show the "Manage Roles" option under "Manage Jenkins", and when one follows the security install page from the wiki, all users are locked out instantly. I had to manually shutdown Jenkins on the server, restore the correct configuration settings (/me is happy to do proper backups) and restart Jenkins.
I didn't have high hopes, as that plugin was last updated in 2011
Since strings are lists of characters in Python, we can concatenate strings the same way we concatenate lists (with the + sign):
{{ var1 + '-' + var2 + '-' + var3 }}
If you want to pipe the resulting string to some filter, make sure you enclose the bits in parentheses:
e.g. To concatenate our 3 vars, and get a sha512 hash:
{{ (var1 + var2 + var3) | hash('sha512') }}
Note: this works on Ansible 2.3. I haven't tested it on earlier versions.
My MySQL says "Incorrect table definition; there can be only one auto column and it must be defined as a key" So when I added primary key as below it started working:
CREATE TABLE book (
id INT AUTO_INCREMENT NOT NULL,
accepted_terms BIT(1) NOT NULL,
accepted_privacy BIT(1) NOT NULL,
primary key (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Use dictionary views:
if x in d.viewvalues():
dosomething()..
You do realize that format has nothing to do with how SQL Server stores datetime, right?
You can use set dateformat
for each session. There is no setting for database only.
If you use parameters for data insert or update or where filtering you won't have any problems with that.
You can't clone it, and how you are going to solve your problem depends on what the source of the data is.
One solution is to read all data from the InputStream into a byte array, and then create a ByteArrayInputStream around that byte array, and pass that input stream into your method.
Edit 1: That is, if the other method also needs to read the same data. I.e you want to "reset" the stream.
Difference between synchronized block and synchronized method are following:
synchronized block:
synchronized(this){}
synchronized method:
public synchronized void fun(){}
Throwing code should make clear whether the error message is appropriate for display to end users or is only intended for developer debugging. To indicate a description is displayable to the user, I use a struct DisplayableError
that implements the LocalizedError
protocol.
struct DisplayableError: Error, LocalizedError {
let errorDescription: String?
init(_ description: String) {
errorDescription = description
}
}
Usage for throwing:
throw DisplayableError("Out of pixie dust.")
Usage for display:
let messageToDisplay = error.localizedDescription
I ran into the same problem. I had a PNG file in a Java package and it wasn't exported in the final JAR along with the sources, which caused the app to crash upon start (file not found).
None of the answers above solved my problem but I found the solution on the Gradle forums. I added the following to my build.gradle
file :
sourceSets.main.resources.srcDirs = [ "src/" ]
sourceSets.main.resources.includes = [ "**/*.png" ]
It tells Gradle to look for resources in the src
folder, and ask it to include only PNG files.
EDIT: Beware that if you're using Eclipse, this will break your run configurations and you'll get a main class not found
error when trying to run your program. To fix that, the only solution I've found is to move the image(s) to another directory, res/
for example, and to set it as srcDirs
instead of src/
.
According to many c compilers:
<<
is an arithmetic left shift or bitwise left shift.>>
is an arithmetic right shiftor bitwise right shift.I'm developing an application that needs currency conversion, and been using Open Exchange Rates because I wouldn't be paying since the app is in testing. But as of September 2012 Open Exchange Rates is gonna be paid for non-personal, so I checked out that they were using the Yahoo Finance Webservice (the one that "doesn't exist") and looking for documentation on it got here, and opted to use YQL.
Using YQL with the Yahoo Finance table (yahoo.finance.quotes) linked by NT3RP, currencies appear with symbol="ISOCODE=X", for example: "ARS=X" for Argentine Peso, "AUD=X" for Australian Dollar. "USD=X" doesn't exist, but it would be 1, since the rest are rates against USD.
The "price" value on the OP API is in the field "LastTradePriceOnly" of the table. For my application I used the "Ask" field.
Might sound unbelivable, but Windows 1903 finally allows to name files in Explorer with a leading dot :-)
Make sure you are sending the proper parameters too. This happened to me after switching to UI-Router.
To fix it, I changed $routeParams to use $stateParams in my controller. The main issue was that $stateParams was no longer sending a proper parameter to the resource.
You can simply use .toString()
.
var result = require('child_process').execSync('rsync -avAXz --info=progress2 "/src" "/dest"').toString();
console.log(result);
This has been tested on Node v8.5.0
, I'm not sure about previous versions. According to @etov, it doesn't work on v6.3.1
- I'm not sure about in-between.
Edit: Looking back on this, I've realised that it doesn't actually answer the specific question because it doesn't show the output to you 'live' — only once the command has finished running.
However, I'm leaving this answer here because I know quite a few people come across this question just looking for how to print the result of the command after execution.
I believe that you are looking for the java.lang.BigDecimal class.
If the user should select only one option at once, just remove the "multiple" - make a normal select:
<select name="mySelect" size="3">
<option>Foo</option>
<option>Bar</option>
<option>Foo Bar</option>
<option>Bar Foo</option>
</select>
One of the reasons of your problem could be the password policy you are using.
And if there is no such policy of yours then check your settings for the password properties in the DEFAULT
profile with the following query:
SELECT resource_name, limit
FROM dba_profiles
WHERE profile = 'DEFAULT'
AND resource_type = 'PASSWORD';
And If required, you just need to change the PASSWORD_LIFE_TIME
to unlimited
with the following query:
ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;
And this Link might be helpful for your problem.
It bewilders me that we encourage one-off custom methods whenever a perfectly good, well used library like Apache Commons has solved the problem already. Though the solution is trivial if not absurd, it is irresponsible to encourage such a behavior due to long term maintenance and accessibility.
Just go with Apache Commons
You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);
, you just need to get rid of default sum(max_count)
. No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL
as the value for every cell in that column.
So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.
You also have the option to always COALESCE
the column to your desired default and leave it NULL
for now. This option fails when you want NULL
to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE
.
If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.
This helped me to call API that was using cookie authentication. I have passed authorization in header like this:
request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));
complete code:
// utility method to read the cookie value:
public static string ReadCookie(string cookieName)
{
var cookies = HttpContext.Current.Request.Cookies;
var cookie = cookies.Get(cookieName);
if (cookie != null)
return cookie.Value;
return null;
}
// using statements where you are creating your webclient
using System.Web.Script.Serialization;
using System.Net;
using System.IO;
// WebClient:
var requestUrl = "<API_url>";
var postRequest = new ClassRoom { name = "kushal seth" };
using (var webClient = new WebClient()) {
JavaScriptSerializer serializer = new JavaScriptSerializer();
byte[] requestData = Encoding.ASCII.GetBytes(serializer.Serialize(postRequest));
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = requestData.Length;
request.ContentType = "application/json";
request.Expect = "application/json";
request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));
request.GetRequestStream().Write(requestData, 0, requestData.Length);
using (var response = (HttpWebResponse)request.GetResponse()) {
var reader = new StreamReader(response.GetResponseStream());
var objText = reader.ReadToEnd(); // objText will have the value
}
}
Through Configuration, you can do this:
Model1
{
int fk_one,
int fk_two
}
Model2
{
int pk_one,
int pk_two,
}
then in the context config
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Model1>()
.HasRequired(e => e.Model2)
.WithMany(e => e.Model1s)
.HasForeignKey(e => new { e.fk_one, e.fk_two })
.WillCascadeOnDelete(false);
}
}
If you use Java and spring MVC you just need to add the following annotation to your method returning your page :
@CrossOrigin(origins = "*")
"*" is to allow your page to be accessible from anywhere. See https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Access-Control-Allow-Origin for more details about that.
You can test for the presence of a key in a dictionary, using the in keyword:
d = {'a': 1, 'b': 2}
'a' in d # <== evaluates to True
'c' in d # <== evaluates to False
A common use for checking the existence of a key in a dictionary before mutating it is to default-initialize the value (e.g. if your values are lists, for example, and you want to ensure that there is an empty list to which you can append when inserting the first value for a key). In cases such as those, you may find the collections.defaultdict()
type to be of interest.
In older code, you may also find some uses of has_key()
, a deprecated method for checking the existence of keys in dictionaries (just use key_name in dict_name
, instead).
If you are using Visual S2019, Create a new local branch as shown in following, and then push the changes to the repo.
Let's say that your time value is in cell A1
then in A2
you can put:
=A1*1000*60*60*24
or simply:
=A1*86400000
What I am doing is taking the decimal value of the time and multiply it by 1000 (milliseconds) and 60 (seconds) and 60 (minutes) and 24 (hours).
You will then need to format cell A2
as General for it to be in milliseconds format.
If your time is a text value then use:
=TIMEVALUE(A1)*86400000
UPDATE
Per @dandfra's comment this solution may not work in the Italian version of Excel.
To get RHEL 7 64-bit to compile gcc 4.8 32-bit programs, you'll need to do two things.
Make sure all the 32-bit gcc 4.8 development tools are completely installed:
sudo yum install glibc-devel.i686 libgcc.i686 libstdc++-devel.i686 ncurses-devel.i686
Compile programs using the -m32 flag
gcc pgm.c -m32 -o pgm
stolen from here : How to Compile 32-bit Apps on 64-bit RHEL? - I only had to do step 1.
Using
$("a").attr("href", "http://www.google.com/")
will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. "anchor") anchor tags:
<a name="MyLinks"></a>
<a href="http://www.codeproject.com/">The CodeProject</a>
...Then you probably don't want to accidentally add href
attributes to them. For safety then, we can specify that our selector will only match <a>
tags with an existing href
attribute:
$("a[href]") //...
Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing href
, you might use something like this:
$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')
This will find links where the href
exactly matches the string http://www.google.com/
. A more involved task might be matching, then updating only part of the href
:
$("a[href^='http://stackoverflow.com']")
.each(function()
{
this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/,
"http://stackoverflow.com");
});
The first part selects only links where the href starts with http://stackoverflow.com
. Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.
Make sure that your min/targetSdkVersions are the same in build.gradle and manifest (if exist). Also check for buildToolsVersion in all your modules - it must be the same.
Your string is invalid, but assuming it was valid, you'd have to do:
var finalData = str.replace(/\\/g, "");
When you want to replace all the occurences with .replace
, the first parameter must be a regex, if you supply a string, only the first occurrence will be replaced, that's why your replace wouldn't work.
Cheers
configfiles = glob.glob('C:/Users/sam/Desktop/**/*.txt")
Doesn't works for all cases, instead use glob2
configfiles = glob2.glob('C:/Users/sam/Desktop/**/*.txt")
It's undefined behavior as far as I know. Run a larger program with that and it will crash somewhere along the way. Bounds checking is not a part of raw arrays (or even std::vector).
Use std::vector with std::vector::iterator
's instead so you don't have to worry about it.
Edit:
Just for fun, run this and see how long until you crash:
int main()
{
int array[1];
for (int i = 0; i != 100000; i++)
{
array[i] = i;
}
return 0; //will be lucky to ever reach this
}
Edit2:
Don't run that.
Edit3:
OK, here is a quick lesson on arrays and their relationships with pointers:
When you use array indexing, you are really using a pointer in disguise (called a "reference"), that is automatically dereferenced. This is why instead of *(array[1]), array[1] automatically returns the value at that value.
When you have a pointer to an array, like this:
int array[5];
int *ptr = array;
Then the "array" in the second declaration is really decaying to a pointer to the first array. This is equivalent behavior to this:
int *ptr = &array[0];
When you try to access beyond what you allocated, you are really just using a pointer to other memory (which C++ won't complain about). Taking my example program above, that is equivalent to this:
int main()
{
int array[1];
int *ptr = array;
for (int i = 0; i != 100000; i++, ptr++)
{
*ptr++ = i;
}
return 0; //will be lucky to ever reach this
}
The compiler won't complain because in programming, you often have to communicate with other programs, especially the operating system. This is done with pointers quite a bit.
Create custom TextWatcher subclass:
public class CustomWatcher implements TextWatcher {
private boolean mWasEdited = false;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (mWasEdited){
mWasEdited = false;
return;
}
// get entered value (if required)
String enteredValue = s.toString();
String newValue = "new value";
// don't get trap into infinite loop
mWasEdited = true;
// just replace entered value with whatever you want
s.replace(0, s.length(), newValue);
}
}
Set listener for your EditText:
mTargetEditText.addTextChangedListener(new CustomWatcher());
This is for the icon in the browser (most of the sites omit the type):
<link rel="icon" type="image/vnd.microsoft.icon"
href="http://example.com/favicon.ico" />
or
<link rel="icon" type="image/png"
href="http://example.com/image.png" />
or
<link rel="apple-touch-icon"
href="http://example.com//apple-touch-icon.png">
for the shortcut icon:
<link rel="shortcut icon"
href="http://example.com/favicon.ico" />
Place them in the <head></head>
section.
Edit may 2019 some additional examples from MDN
You can also use the matrix
command, to create a matrix with n lines and m columns, filled with zeros.
matrix(0, n, m)
You can also fit a set of a data to whatever function you like using curve_fit
from scipy.optimize
. For example if you want to fit an exponential function (from the documentation):
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b, c):
return a * np.exp(-b * x) + c
x = np.linspace(0,4,50)
y = func(x, 2.5, 1.3, 0.5)
yn = y + 0.2*np.random.normal(size=len(x))
popt, pcov = curve_fit(func, x, yn)
And then if you want to plot, you could do:
plt.figure()
plt.plot(x, yn, 'ko', label="Original Noised Data")
plt.plot(x, func(x, *popt), 'r-', label="Fitted Curve")
plt.legend()
plt.show()
(Note: the *
in front of popt
when you plot will expand out the terms into the a
, b
, and c
that func
is expecting.)
** -> "xampp->mysql->data" cut all files from data folder and paste to another folder
-> now restart mysql
-> paste all folders from your folder to myslq->data folder
and also paste ib_logfile0.ib_logfile1 , ibdata1 into data folder from your folder.
your database and your data is now available in phpmyadmin..**
Another use case is when using the SQL Server 2016+ functionality of AT TIME ZONE
The below statement will return a date converted to GMT
SELECT
CONVERT(DATETIME, SWITCHOFFSET([ColumnA], DATEPART(TZOFFSET, [ColumnA] AT TIME ZONE 'GMT Standard Time')))
If you want to pass the time zone as a variable, say:
SELECT
CONVERT(DATETIME, SWITCHOFFSET([ColumnA], DATEPART(TZOFFSET, [ColumnA] AT TIME ZONE @TimeZone)))
then that variable needs to be of the type sysname
(declaring it as varchar
will cause an error).
Try dragging a UIView
onto the screen in IB. From there you can drag a UIImageView
and UILabel
into the view you just created. Set the image of the UIImageView
in the properties inspector as the custom bullet image (which you will have to add to your project by dragging it into the navigation pane) and you can write some text in the label.
Try changing
git checkout -- a
to
git checkout -- `git ls-files -m -- a`
Since version 1.7.0, Git's ls-files
honors the skip-worktree flag.
Running your test script (with some minor tweaks changing git commit
... to git commit -q
and git status
to git status --short
) outputs:
Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
D a/a/aa
D a/b/ab
M b/a/ba
After checkout:
M b/a/ba
a/a/aa
a/c/ac
a/b/ab
b/a/ba
Running your test script with the proposed checkout
change outputs:
Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
D a/a/aa
D a/b/ab
M b/a/ba
After checkout:
M b/a/ba
a/a/aa
a/b/ab
b/a/ba
Status 422 (RFC 4918, Section 11.2) comes to mind:
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
Right-click on the widget and choose "center" -> "horizontally". Then choose "center"->"vertically".
You said :
Maybe my data.frame is not in a good format?
Yes this is true. Your data is in the wide format You need to put it in the long format. Generally speaking, long format is better for variables comparison.
Using reshape2
for example , you do this using melt
:
dat.m <- melt(dat,id.vars = "Rank") ## just melt(dat) should work
Then you get your barplot:
ggplot(dat.m, aes(x = Rank, y = value,fill=variable)) +
geom_bar(stat='identity')
But using lattice
and barchart
smart formula notation , you don't need to reshape your data , just do this:
barchart(F1+F2+F3~Rank,data=dat)
Use:
sb.AppendLine();
sb.Append("\t");
for better portability. Environment.NewLine
may not necessarily be \n
; Windows uses \r\n
, for example.
stoi is available "since C++11". Make sure your compiler is up to date.
You can try atoi(hours0.c_str()) instead.
Angular 2, 4 and Angular 5 compatible!
You have provided so few details, so I'll try to answer your question without them.
You can use Interpolation:
<img src={{imagePath}} />
Or you can use a template expression:
<img [src]="imagePath" />
In a ngFor loop it might look like this:
<div *ngFor="let student of students">
<img src={{student.ImagePath}} />
</div>
I guess its better to do this in Java
:
boolean isRotation(String s1,String s2) {
return (s1.length() == s2.length()) && (s1+s1).contains(s2);
}
In Perl I would do:
sub isRotation {
my($string1,$string2) = @_;
return length($string1) == length($string2) && ($string1.$string1)=~/$string2/;
}
or even better using the index function instead of the regex:
sub isRotation {
my($string1,$string2) = @_;
return length($string1) == length($string2) && index($string2,$string1.$string1) != -1;
}
To add some flexibility here, you can achieve more fine-grained control over the level of logging by writing a function that filters out messages however you like:
logging.getLogger('tensorflow').addFilter(my_filter_func)
where my_filter_func
accepts a LogRecord
object as input [LogRecord
docs] and
returns zero if you want the message thrown out; nonzero otherwise.
Here's an example filter that only keeps every nth info message (Python 3 due
to the use of nonlocal
here):
def keep_every_nth_info(n):
i = -1
def filter_record(record):
nonlocal i
i += 1
return int(record.levelname != 'INFO' or i % n == 0)
return filter_record
# Example usage for TensorFlow:
logging.getLogger('tensorflow').addFilter(keep_every_nth_info(5))
All of the above has assumed that TensorFlow has set up its logging state already. You can ensure this without side effects by calling tf.logging.get_verbosity()
before adding a filter.
Anon's answer works great for me, but I just need to modify the statement for days
from:
days = dates - dates.astype('datetime64[M]') + 1
to:
days = dates.astype('datetime64[D]') - dates.astype('datetime64[M]') + 1
Am I doing that right, as far as iterating through the Arraylist goes?
No: by calling iterator
twice in each iteration, you're getting new iterators all the time.
The easiest way to write this loop is using the for-each construct:
for (String s : arrayList)
if (s.equals(value))
// ...
As for
java.lang.ArrayIndexOutOfBoundsException: -1
You just tried to get element number -1
from an array. Counting starts at zero.
You are printing the wrong value. Instead if the string you print the scanners object. Try this
Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);
length
and dbms_lob.getlength
return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength
will return the number of bytes, which may differ from the number of characters in a multi-byte character set.
As the documentation doesn't specify what happens when you apply length
on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength
.
checkout this article :http://www.morgantechspace.com/2013/08/convert-object-to-byte-array-and-vice.html
Use the below code
// Convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
{
if(obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
// Convert a byte array to an Object
private Object ByteArrayToObject(byte[] arrBytes)
{
MemoryStream memStream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
Object obj = (Object) binForm.Deserialize(memStream);
return obj;
}
By default, unlike an exception, a warning doesn't interrupt.
After import warnings
, it is possible to specify a Warnings class when generating a warning. If one is not specified, it is literally UserWarning
by default.
>>> warnings.warn('This is a default warning.')
<string>:1: UserWarning: This is a default warning.
To simply use a preexisting class instead, e.g. DeprecationWarning
:
>>> warnings.warn('This is a particular warning.', DeprecationWarning)
<string>:1: DeprecationWarning: This is a particular warning.
Creating a custom warning class is similar to creating a custom exception class:
>>> class MyCustomWarning(UserWarning):
... pass
...
... warnings.warn('This is my custom warning.', MyCustomWarning)
<string>:1: MyCustomWarning: This is my custom warning.
For testing, consider assertWarns
or assertWarnsRegex
.
As an alternative, especially for standalone applications, consider the logging
module. It can log messages having a level of debug, info, warning, error, etc. Log messages having a level of warning or higher are by default printed to stderr.
The OG thumbnail does not seem to refresh even if passing the fbrefresh variable. To update this without waiting for automated clearing you'll need to change the filename of the thumbnail associated meta tag value and refresh.
Also, to complete what @claudio said, when cherry-picking you can also use a merging strategy.
So you could something like this git cherry-pick --strategy=recursive -X theirs commit
or git cherry-pick --strategy=recursive -X ours commit
Perhaps you need to know how urls are mapped too, since I suffered 404
for hours. There are two kinds of handlers handling requests. BeanNameUrlHandlerMapping
and SimpleUrlHandlerMapping
. When we defined a servlet-mapping
, we are using SimpleUrlHandlerMapping
. One thing we need to know is these two handlers share a common property called alwaysUseFullPath
which defaults to false
.
false
here means Spring will not use the full path to mapp a url to a controller. What does it mean? It means when you define a servlet-mapping
:
<servlet-mapping>
<servlet-name>viewServlet</servlet-name>
<url-pattern>/perfix/*</url-pattern>
</servlet-mapping>
the handler will actually use the *
part to find the controller. For example, the following controller will face a 404
error when you request it using /perfix/api/feature/doSomething
@Controller()
@RequestMapping("/perfix/api/feature")
public class MyController {
@RequestMapping(value = "/doSomething", method = RequestMethod.GET)
@ResponseBody
public String doSomething(HttpServletRequest request) {
....
}
}
It is a perfect match, right? But why 404
. As mentioned before, default value of alwaysUseFullPath
is false, which means in your request, only /api/feature/doSomething
is used to find a corresponding Controller, but there is no Controller cares about that path. You need to either change your url to /perfix/perfix/api/feature/doSomething
or remove perfix
from MyController base @RequestingMapping
.
Some collections assume that null
is rejected using NullPointerException
rather than IllegalArgumentException
. For example, if you compare a set containing null
to a set that rejects null
, the first set will call containsAll
on the other and catch its NullPointerException
-- but not IllegalArgumentException
. (I'm looking at the implementation of AbstractSet.equals
.)
You could reasonably argue that using unchecked exceptions in this way is an antipattern, that comparing collections that contain null
to collections that can't contain null
is a likely bug that really should produce an exception, or that putting null
in a collection at all is a bad idea. Nevertheless, unless you're willing to say that equals
should throw an exception in such a case, you're stuck remembering that NullPointerException
is required in certain circumstances but not in others. ("IAE before NPE except after 'c'...")
There is a helper library for this.
Swift 5
pod 'DeviceKit', '~> 2.0'
Swift 4.0 - Swift 4.2
pod 'DeviceKit', '~> 1.3'
if you just want to determine the model and make something accordingly.
You can use like that :
let isIphoneX = Device().isOneOf([.iPhoneX, .simulator(.iPhoneX)])
In a function :
func isItIPhoneX() -> Bool {
let device = Device()
let check = device.isOneOf([.iPhoneX, .iPhoneXr , .iPhoneXs , .iPhoneXsMax ,
.simulator(.iPhoneX), .simulator(.iPhoneXr) , .simulator(.iPhoneXs) , .simulator(.iPhoneXsMax) ])
return check
}
Try the following :
try
{
var fromEmailAddress = ConfigurationManager.AppSettings["FromEmailAddress"].ToString();
var fromEmailDisplayName = ConfigurationManager.AppSettings["FromEmailDisplayName"].ToString();
var fromEmailPassword = ConfigurationManager.AppSettings["FromEmailPassword"].ToString();
var smtpHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
var smtpPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();
string body = "Your registration has been done successfully. Thank you.";
MailMessage message = new MailMessage(new MailAddress(fromEmailAddress, fromEmailDisplayName), new MailAddress(ud.LoginId, ud.FullName));
message.Subject = "Thank You For Your Registration";
message.IsBodyHtml = true;
message.Body = body;
var client = new SmtpClient();
client.Credentials = new NetworkCredential(fromEmailAddress, fromEmailPassword);
client.Host = smtpHost;
client.EnableSsl = true;
client.Port = !string.IsNullOrEmpty(smtpPort) ? Convert.ToInt32(smtpPort) : 0;
client.Send(message);
}
catch (Exception ex)
{
throw (new Exception("Mail send failed to loginId " + ud.LoginId + ", though registration done."));
}
And then in you web.config add the following in between
<!--Email Config-->
<add key="FromEmailAddress" value="sender emailaddress"/>
<add key="FromEmailDisplayName" value="Display Name"/>
<add key="FromEmailPassword" value="sender Password"/>
<add key="SMTPHost" value="smtp-proxy.tm.net.my"/>
<add key="SMTPPort" value="smptp Port"/>
A real problem often exists because any variables set inside will not be exported when that batch file finishes. So its not possible to export, which caused us issues. As a result, I just set the registry to ALWAYS used delayed expansion (I don't know why it's not the default, could be speed or legacy compatibility issue.)
Yes there is
int temp;
int.TryParse("141241", out temp) = true
int.TryParse("232a23", out temp) = false
int.TryParse("12412a", out temp) = false
Hope this helps.
Currently ng2-search-filter simplify this works.
By directive
<tr *ngFor="let item of items | filter:searchText">
<td>{{item.name}}</td>
</tr>
Or programmatically
let itemsFiltered = new Ng2SearchPipe().transform(items, searchText);
Practical example: https://angular-search-filter.stackblitz.io
pg_dump the_db_name > the_backup.sql
Then copy the backup to your development server, restore with:
psql the_new_dev_db < the_backup.sql
Using a list comprehension:
from datetime import date, timedelta
d1 = date(2008,8,15)
d2 = date(2008,9,15)
# this will give you a list containing all of the dates
dd = [d1 + timedelta(days=x) for x in range((d2-d1).days + 1)]
for d in dd:
print d
# you can't join dates, so if you want to use join, you need to
# cast to a string in the list comprehension:
ddd = [str(d1 + timedelta(days=x)) for x in range((d2-d1).days + 1)]
# now you can join
print "\n".join(ddd)
Here's a toggleClass to toggle/add/remove a class on an element:
// If newState is provided add/remove theClass accordingly, otherwise toggle theClass
function toggleClass(elem, theClass, newState) {
var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');
var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null));
elem.className=elem.className.replace(matchRegExp, ''); // clear all
if (add) elem.className += ' ' + theClass;
}
see jsfiddle
also see my answer here for creating a new class dynamically
Use sqlcmd instead of osql if it's a 2005 database
I'm working on an app and face issue of killing my service by on app kill. I researched on google and found that I have to make it foreground. following is the code:
public class UpdateLocationAndPrayerTimes extends Service {
Context context;
@Override
public void onCreate() {
super.onCreate();
context = this;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
StartForground();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void StartForground() {
LocationChangeDetector locationChangeDetector = new LocationChangeDetector(context);
locationChangeDetector.getLatAndLong();
Notification notification = new NotificationCompat.Builder(this)
.setOngoing(false)
.setSmallIcon(android.R.color.transparent)
//.setSmallIcon(R.drawable.picture)
.build();
startForeground(101, notification);
}
}
hops that it may helps!!!!
The answer is on the MSDN site:
The Save (Not Permitted) dialog box warns you that saving changes is not permitted because the changes you have made require the listed tables to be dropped and re-created.
The following actions might require a table to be re-created:
- Adding a new column to the middle of the table
- Dropping a column
- Changing column nullability
- Changing the order of the columns
- Changing the data type of a column
EDIT 1:
Additional useful informations from here:
To change the Prevent saving changes that require the table re-creation option, follow these steps:
- Open SQL Server Management Studio (SSMS).
- On the Tools menu, click Options.
- In the navigation pane of the Options window, click Designers.
- Select or clear the Prevent saving changes that require the table re-creation check box, and then click OK.
Note If you disable this option, you are not warned when you save the table that the changes that you made have changed the metadata structure of the table. In this case, data loss may occur when you save the table.
Risk of turning off the "Prevent saving changes that require table re-creation" option
Although turning off this option can help you avoid re-creating a table, it can also lead to changes being lost. For example, suppose that you enable the Change Tracking feature in SQL Server 2008 to track changes to the table. When you perform an operation that causes the table to be re-created, you receive the error message that is mentioned in the "Symptoms" section. However, if you turn off this option, the existing change tracking information is deleted when the table is re-created. Therefore, we recommend that you do not work around this problem by turning off the option.
First initialize permission request code
public static final int PERMISSIONS_MULTIPLE_REQUEST = 123;
Check android version
private void checkAndroidVersion() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkPermission();
} else {
// write your logic here
}
}
check multiple permission code
private void checkPermission() {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.READ_EXTERNAL_STORAGE) + ContextCompat
.checkSelfPermission(getActivity(),
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale
(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) ||
ActivityCompat.shouldShowRequestPermissionRationale
(getActivity(), Manifest.permission.CAMERA)) {
Snackbar.make(getActivity().findViewById(android.R.id.content),
"Please Grant Permissions to upload profile photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
} else {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
PERMISSIONS_MULTIPLE_REQUEST);
}
} else {
// write your logic code if permission already granted
}
}
call back method after grant permission by user
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_MULTIPLE_REQUEST:
if (grantResults.length > 0) {
boolean cameraPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean readExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if(cameraPermission && readExternalFile)
{
// write your logic here
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content),
"Please Grant Permissions to upload profile photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
}
}
break;
}
}
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
business_key
values to a temporary tableThe group by
could be executed like:
business key
in a hashtableThe first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
Also remember that you can pass a second argument to the .forEach()
function specifying the object to use as the this
keyword.
// myOjbect is the object you want to iterate.
// Notice the second argument (secondArg) we passed to .forEach.
Object.keys(myObject).forEach(function(element, key, _array) {
// element is the name of the key.
// key is just a numerical value for the array
// _array is the array of all the keys
// this keyword = secondArg
this.foo;
this.bar();
}, secondArg);
One clean way to do this is to inject VirtualTime. It allows you to control time. First install VirtualTime
Install-Package VirtualTime
That allows to, for example, make time that moves 5 times faster on all calls to DateTime.Now or UtcNow
var DateTime = DateTime.Now.ToVirtualTime(5);
To make time move slower , eg 5 times slower do
var DateTime = DateTime.Now.ToVirtualTime(0.5);
To make time stand still do
var DateTime = DateTime.Now.ToVirtualTime(0);
Moving backwards in time is not tested yet
Here are a sample test:
[TestMethod]
public void it_should_make_time_move_faster()
{
int speedOfTimePerMs = 1000;
int timeToPassMs = 3000;
int expectedElapsedVirtualTime = speedOfTimePerMs * timeToPassMs;
DateTime whenTimeStarts = DateTime.Now;
ITime time = whenTimeStarts.ToVirtualTime(speedOfTimePerMs);
Thread.Sleep(timeToPassMs);
DateTime expectedTime = DateTime.Now.AddMilliseconds(expectedElapsedVirtualTime - timeToPassMs);
DateTime virtualTime = time.Now;
Assert.IsTrue(TestHelper.AreEqualWithinMarginOfError(expectedTime, virtualTime, MarginOfErrorMs));
}
You can check out more tests here:
What DateTime.Now.ToVirtualTime extension gives you is an instance of ITime which you pass to a method / class that depends on ITime. some DateTime.Now.ToVirtualTime is setup in the DI container of your choice
Here is another example injecting into a class contrustor
public class AlarmClock
{
private ITime DateTime;
public AlarmClock(ITime dateTime, int numberOfHours)
{
DateTime = dateTime;
SetTime = DateTime.UtcNow.AddHours(numberOfHours);
Task.Run(() =>
{
while (!IsAlarmOn)
{
IsAlarmOn = (SetTime - DateTime.UtcNow).TotalMilliseconds < 0;
}
});
}
public DateTime SetTime { get; set; }
public bool IsAlarmOn { get; set; }
}
[TestMethod]
public void it_can_be_injected_as_a_dependency()
{
//virtual time has to be 1000*3.75 faster to get to an hour
//in 1000 ms real time
var dateTime = DateTime.Now.ToVirtualTime(1000 * 3.75);
var numberOfHoursBeforeAlarmSounds = 1;
var alarmClock = new AlarmClock(dateTime, numberOfHoursBeforeAlarmSounds);
Assert.IsFalse(alarmClock.IsAlarmOn);
System.Threading.Thread.Sleep(1000);
Assert.IsTrue(alarmClock.IsAlarmOn);
}
You can do it using only the shell, no need for tr
or sed
$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test
You could compile and link in one command:
gcc file1.c file2.c -o myprogram
And run with:
./myprogram
But to answer the question as asked, simply pass the object files to gcc
:
gcc file1.o file2.o -o myprogram
echo ($result ->vocation == 1) ? 'Sorcerer'
: ($result->vocation == 2) ? 'Druid'
: ($result->vocation == 3) ? 'Paladin'
....
;
It’s kind of ugly. You should stick with normal if
statements.
If you have the option of using fetchAll() then if there are no rows returned it will just be and empty array.
count($sql->fetchAll(PDO::FETCH_ASSOC))
will return the number of rows returned.
In Java adding a .0 will make it a double...
int total = (int) Math.ceil(157.0 / 32.0);
I think you can use the TimeZoneInfo....to convert the datetime....
static void Main(string[] args)
{
long time = 1310522400000;
DateTime dt_1970 = new DateTime(1970, 1, 1);
long tricks_1970 = dt_1970.Ticks;
long time_tricks = tricks_1970 + time * 10000;
DateTime dt = new DateTime(time_tricks);
Console.WriteLine(dt.ToShortDateString()); // result : 7/13
dt = TimeZoneInfo.ConvertTimeToUtc(dt);
Console.WriteLine(dt.ToShortDateString()); // result : 7/12
Console.Read();
}
<table style="border:2px solid #ddedde">
<tr>
<td style="border:2px solid #ddedde;width:50%">a</td>
<td style="border:2px solid #ddedde;width:20%">b</td>
<td style="border:2px solid #ddedde;width:30%">c</td>
</tr>
<tr>
<td style="border:2px solid #ddedde;width:50%">a</td>
<td style="border:2px solid #ddedde;width:20%">b</td>
<td style="border:2px solid #ddedde;width:30%">c</td>
</tr>
</table>
Check this below code, it works
#define MAX_BYTE_RANGE 255
template <typename T>
class string
{
public:
typedef char *pointer;
typedef const char *const_pointer;
typedef __gnu_cxx::__normal_iterator<pointer, string> iterator;
typedef __gnu_cxx::__normal_iterator<const_pointer, string> const_iterator;
string() : length(0)
{
}
size_t size() const
{
return length;
}
void operator=(const_pointer value)
{
if (value == nullptr)
throw std::invalid_argument("value cannot be null");
auto count = strlen(value);
if (count > 0)
_M_copy(value, count);
}
void operator=(const string &value)
{
if (value.length != 0)
_M_copy(value.buf, value.length);
}
iterator begin()
{
return iterator(buf);
}
iterator end()
{
return iterator(buf + length);
}
const_iterator begin() const
{
return const_iterator(buf);
}
const_iterator end() const
{
return const_iterator(buf + length);
}
const_pointer c_str() const
{
return buf;
}
~string()
{
}
private:
unsigned char length;
T buf[MAX_BYTE_RANGE];
void _M_copy(const_pointer value, size_t count)
{
memcpy(buf, value, count);
length = count;
}
};
Although I'm not answering the original question concering the no-op command, many (if not most) problems when one may think "in this branch I have to do nothing" can be bypassed by simply restructuring the logic so that this branch won't occur.
I try to give a general rule by using the OPs example
do nothing when $a is greater than "10", print "1" if $a is less than "5", otherwise, print "2"
we have to avoid a branch where $a
gets more than 10, so $a < 10
as a general condition can be applied to every other, following condition.
In general terms, when you say do nothing when X, then rephrase it as avoid a branch where X. Usually you can make the avoidance happen by simply negating X and applying it to all other conditions.
So the OPs example with the rule applied may be restructured as:
if [ "$a" -lt 10 ] && [ "$a" -le 5 ]
then
echo "1"
elif [ "$a" -lt 10 ]
then
echo "2"
fi
Just a variation of the above, enclosing everything in the $a < 10
condition:
if [ "$a" -lt 10 ]
then
if [ "$a" -le 5 ]
then
echo "1"
else
echo "2"
fi
fi
(For this specific example @Flimzys restructuring is certainly better, but I wanted to give a general rule for all the people searching how to do nothing.)
on Ubuntu 12.04 and the packaged version of NodeJs is too old to install Bower using the PPA
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get -y install nodejs
When this has installed, check the version:
npm --version
1.4.3
Now install Bower:
sudo npm install -g bower
This will fetch and install Bower globally.
Assert.Throws
returns the exception that's thrown which lets you assert on the exception.
var ex = Assert.Throws<Exception>(() => user.MakeUserActive());
Assert.That(ex.Message, Is.EqualTo("Actual exception message"));
So if no exception is thrown, or an exception of the wrong type is thrown, the first Assert.Throws
assertion will fail. However if an exception of the correct type is thrown then you can now assert on the actual exception that you've saved in the variable.
By using this pattern you can assert on other things than the exception message, e.g. in the case of ArgumentException
and derivatives, you can assert that the parameter name is correct:
var ex = Assert.Throws<ArgumentNullException>(() => foo.Bar(null));
Assert.That(ex.ParamName, Is.EqualTo("bar"));
You can also use the fluent API for doing these asserts:
Assert.That(() => foo.Bar(null),
Throws.Exception
.TypeOf<ArgumentNullException>()
.With.Property("ParamName")
.EqualTo("bar"));
or alternatively
Assert.That(
Assert.Throws<ArgumentNullException>(() =>
foo.Bar(null)
.ParamName,
Is.EqualTo("bar"));
A little tip when asserting on exception messages is to decorate the test method with the SetCultureAttribute
to make sure that the thrown message is using the expected culture. This comes into play if you store your exception messages as resources to allow for localization.
I have come up with a solution that is relatively accurate at evaluating when the angular initialisation is complete.
The directive is:
.directive('initialisation',['$rootScope',function($rootScope) {
return {
restrict: 'A',
link: function($scope) {
var to;
var listener = $scope.$watch(function() {
clearTimeout(to);
to = setTimeout(function () {
console.log('initialised');
listener();
$rootScope.$broadcast('initialised');
}, 50);
});
}
};
}]);
That can then just be added as an attribute to the body
element and then listened for using $scope.$on('initialised', fn)
It works by assuming that the application is initialised when there are no more $digest cycles. $watch is called every digest cycle and so a timer is started (setTimeout not $timeout so a new digest cycle is not triggered). If a digest cycle does not occur within the timeout then the application is assumed to have initialised.
It is obviously not as accurate as satchmoruns solution (as it is possible a digest cycle takes longer than the timeout) but my solution doesn't need you to keep track of the modules which makes it that much easier to manage (particularly for larger projects). Anyway, seems to be accurate enough for my requirements. Hope it helps.
Based on the discussion in the comments (particularly from BalusC), it's probably not worth doing anything more complicated than this:
<script>var ctx = "${pageContext.request.contextPath}"</script>
you should use a /d before path as below :
cd /d e:\
I recently bumped into the same problem. Tried to find a cheaper solution so came up with this.
<LinearLayout
android:id="@+id/linearButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/selector_button_translucent_ab_color"
android:clickable="true"
android:descendantFocusability="blocksDescendants"
android:gravity="center"
android:orientation="horizontal" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/app_name"
android:src="@drawable/ic_launcher" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:textColor="@android:color/white" />
</LinearLayout>
Then just call the OnClickListener
on LinearLayout
.
Hope this helps someone as it seems like a very common problem. :)
But for any future bypassers you could mention that df = df[df.line_race != 0]
doesn't do anything when trying to filter for None
/missing values.
Does work:
df = df[df.line_race != 0]
Doesn't do anything:
df = df[df.line_race != None]
Does work:
df = df[df.line_race.notnull()]
In postgres simply : TO_CHAR(timestamp_column, 'DD/MM/YYYY') as submission_date
I had precisely this problem, but I needed sequential plots to have highly contrasting color. I was also doing plots with a common sub-plot containing reference data, so I wanted the color sequence to be consistently repeatable.
I initially tried simply generating colors randomly, reseeding the RNG before each plot. This worked OK (commented-out in code below), but could generate nearly indistinguishable colors. I wanted highly contrasting colors, ideally sampled from a colormap containing all colors.
I could have as many as 31 data series in a single plot, so I chopped the colormap into that many steps. Then I walked the steps in an order that ensured I wouldn't return to the neighborhood of a given color very soon.
My data is in a highly irregular time series, so I wanted to see the points and the lines, with the point having the 'opposite' color of the line.
Given all the above, it was easiest to generate a dictionary with the relevant parameters for plotting the individual series, then expand it as part of the call.
Here's my code. Perhaps not pretty, but functional.
from matplotlib import cm
cmap = cm.get_cmap('gist_rainbow') #('hsv') #('nipy_spectral')
max_colors = 31 # Constant, max mumber of series in any plot. Ideally prime.
color_number = 0 # Variable, incremented for each series.
def restart_colors():
global color_number
color_number = 0
#np.random.seed(1)
def next_color():
global color_number
color_number += 1
#color = tuple(np.random.uniform(0.0, 0.5, 3))
color = cmap( ((5 * color_number) % max_colors) / max_colors )
return color
def plot_args(): # Invoked for each plot in a series as: '**(plot_args())'
mkr = next_color()
clr = (1 - mkr[0], 1 - mkr[1], 1 - mkr[2], mkr[3]) # Give line inverse of marker color
return {
"marker": "o",
"color": clr,
"mfc": mkr,
"mec": mkr,
"markersize": 0.5,
"linewidth": 1,
}
My context is JupyterLab and Pandas, so here's sample plot code:
restart_colors() # Repeatable color sequence for every plot
fig, axs = plt.subplots(figsize=(15, 8))
plt.title("%s + T-meter"%name)
# Plot reference temperatures:
axs.set_ylabel("°C", rotation=0)
for s in ["T1", "T2", "T3", "T4"]:
df_tmeter.plot(ax=axs, x="Timestamp", y=s, label="T-meter:%s" % s, **(plot_args()))
# Other series gets their own axis labels
ax2 = axs.twinx()
ax2.set_ylabel(units)
for c in df_uptime_sensors:
df_uptime[df_uptime["UUID"] == c].plot(
ax=ax2, x="Timestamp", y=units, label="%s - %s" % (units, c), **(plot_args())
)
fig.tight_layout()
plt.show()
The resulting plot may not be the best example, but it becomes more relevant when interactively zoomed in.
https://stackoverflow.com/a/42234988/9536897 it's not work on mobile mode.
than you can try:
// returns true if the element or one of its parents has the class classname
hasSomeParentTheClass(element, classname) {
if(element.target)
element=element.target;
if (element.className&& element.className.split(" ").indexOf(classname) >= 0) return true;
return (
element.parentNode &&
this.hasSomeParentTheClass(element.parentNode, classname)
);
}
componentDidMount() {
const fthis = this;
$(window).click(function (element) {
if (!fthis.hasSomeParentTheClass(element, "myClass"))
fthis.setState({ pharmacyFocus: null });
});
}
I had this error 2 times. Each time it was solved by changing the ajax type. Either GET to POST or POST to GET.
$.ajax({
type:'GET', // or 'POST'
url: "file.cfm?action=get_table&varb=" + varb
});
Sometimes if there's no any application associated with geo: protocal , you could use try-catch to get the ActivityNotFoundException to handle it.
It happens when you use some emulator like androVM which is not installed google map by default.
The important part is this:
Cannot find class [com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl] for bean with name 'MemberPointSummaryDAOImpl' defined in ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml];
due to:
nested exception is java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
According to this log, Spring could not find your MemberPointSummaryDAOImpl
class.
You can do
display/i $pc
and every time GDB stops, it will display the disassembly of the next instruction.
GDB-7.0
also supports set disassemble-next-line on
, which will disassemble the entire next line, and give you more of the disassembly context.
If you like it short simply use a RegExp:
var streetAddress = /[^,]*/.exec(addy)[0];
package javaapplication4;
import java.text.*;
import java.util.*;
/**
*
* @author Stefan Wendelmann
*/
public class JavaApplication4
{
private static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws ParseException
{
SimpleDateFormat parser = new SimpleDateFormat("dd.MM.YYYY HH:mm:ss.SSS");
Date before = parser.parse("01.10.1990 07:00:00.000");
Date base = parser.parse("01.10.1990 08:00:00.000");
Date after = parser.parse("01.10.1990 09:00:00.000");
printCompare(base, base, "==");
printCompare(base, before, "==");
printCompare(base, before, "<");
printCompare(base, after, "<");
printCompare(base, after, ">");
printCompare(base, before, ">");
printCompare(base, before, "<=");
printCompare(base, base, "<=");
printCompare(base, after, "<=");
printCompare(base, after, ">=");
printCompare(base, base, ">=");
printCompare(base, before, ">=");
}
private static void printCompare (Date a, Date b, String operator){
System.out.println(sdf.format(b)+"\t"+operator+"\t"+sdf.format(a)+"\t"+compareTime(a, b, operator));
}
protected static boolean compareTime(Date a, Date b, String operator)
{
if (a == null)
{
return false;
}
try
{
//Zeit aus Datum holen
// The Magic happens here i only get the Time out of the Date Object
SimpleDateFormat parser = new SimpleDateFormat("HH:mm:ss.SSS");
a = parser.parse(parser.format(a));
b = parser.parse(parser.format(b));
}
catch (ParseException ex)
{
System.err.println(ex);
}
switch (operator)
{
case "==":
return b.compareTo(a) == 0;
case "<":
return b.compareTo(a) < 0;
case ">":
return b.compareTo(a) > 0;
case "<=":
return b.compareTo(a) <= 0;
case ">=":
return b.compareTo(a) >= 0;
default:
throw new IllegalArgumentException("Operator " + operator + " wird für Feldart Time nicht unterstützt!");
}
}
}
run:
08:00:00.000 == 08:00:00.000 true
07:00:00.000 == 08:00:00.000 false
07:00:00.000 < 08:00:00.000 true
09:00:00.000 < 08:00:00.000 false
09:00:00.000 > 08:00:00.000 true
07:00:00.000 > 08:00:00.000 false
07:00:00.000 <= 08:00:00.000 true
08:00:00.000 <= 08:00:00.000 true
09:00:00.000 <= 08:00:00.000 false
09:00:00.000 >= 08:00:00.000 true
08:00:00.000 >= 08:00:00.000 true
07:00:00.000 >= 08:00:00.000 false
BUILD SUCCESSFUL (total time: 0 seconds)
Beside the methods described in previous answers, you can also use a free execution plan viewer and query optimization tool ApexSQL Plan (which I’ve recently bumped into).
You can install and integrate ApexSQL Plan into SQL Server Management Studio, so execution plans can be viewed from SSMS directly.
Viewing Estimated execution plans in ApexSQL Plan
Viewing Actual execution plans in ApexSQL Plan
To view the Actual execution plan of a query, continue from the 2nd step mentioned previously, but now, once the Estimated plan is shown, click the “Actual” button from the main ribbon bar in ApexSQL Plan.
Once the “Actual” button is clicked, the Actual execution plan will be shown with detailed preview of the cost parameters along with other execution plan data.
More information about viewing execution plans can be found by following this link.
Did you try something like:
body {background: url('[url to your image]') no-repeat right bottom;}
You need to open the file in binary b
mode to take care of blank lines in Python 2. This isn't required in Python 3.
So, change open('test.csv', 'w')
to open('test.csv', 'wb')
.
I was just looking at a similar answer-- it's able to be done with a Stroke and the following override:
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
Paint strokePaint = new Paint();
strokePaint.setARGB(255, 0, 0, 0);
strokePaint.setTextAlign(Paint.Align.CENTER);
strokePaint.setTextSize(16);
strokePaint.setTypeface(Typeface.DEFAULT_BOLD);
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setStrokeWidth(2);
Paint textPaint = new Paint();
textPaint.setARGB(255, 255, 255, 255);
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.setTextSize(16);
textPaint.setTypeface(Typeface.DEFAULT_BOLD);
canvas.drawText("Some Text", 100, 100, strokePaint);
canvas.drawText("Some Text", 100, 100, textPaint);
super.draw(canvas, mapView, shadow);
}
as a complementary answer to @Navid_pdp11, which will enable to select the first visible item and work on document load as well. put the following below your body tag
<script>
$('#mainCat').on('change', function() {
let selected = $(this).val();
$("#expertCat option").each(function(){
let element = $(this) ;
if (element.data("tag") != selected){
element.removeClass('visible');
element.addClass('hidden');
element.hide() ;
}else{
element.removeClass('hidden');
element.addClass('visible');
element.show();
}
});
let expertCat = $('#expertCat');
expertCat.prop('selectedIndex',expertCat.find("option.visible:eq(0)").index());
}).triggerHandler('change');
</script>
Everybody seems to refer to date being a column in the table.
I dont think this is good practice. The word date might just be a keyword in some coding language (maybe Oracle) so please change the columnname date to maybe JDate.
So will the following work better:
SELECT * FROM jokes WHERE JDate >= CURRENT_DATE() ORDER BY JScore DESC;
So we have a table called Jokes with columns JScore and JDate.
It appears that tkFileDialog.askdirectory
should work. documentation
I always write a default method "findByIdOrError" in widely used CrudRepository repos/interfaces.
@Repository
public interface RequestRepository extends CrudRepository<Request, Integer> {
default Request findByIdOrError(Integer id) {
return findById(id).orElseThrow(EntityNotFoundException::new);
}
}
Here is another good article that you may check out on Domain Driven Design. if your application is anything serious than college assignment. The basic premise is structure everything around your entities and have a strong domain model. Differentiate between services that provide infrastructure related things (like sending email, persisting data) and services that actually do things that are your core business requirments.
Hope that helps.
Here is the simplest thing I've found
-- Midnight floor of current date
SELECT Convert(DateTime, DATEDIFF(DAY, 0, GETDATE()))
The DATEDIFF returns the integer number of days before or since 1900-1-1, and the Convert Datetime obligingly brings it back to that date at midnight.
Since DateDiff returns an integer you can use add or subtract days to get the right offset.
SELECT Convert(DateTime, DATEDIFF(DAY, 0, GETDATE()) + @dayOffset)
This isn't rounding this is truncating...But I think that is what is being asked. (To round add one and truncate...and that's not rounding either, that the ceiling, but again most likely what you want. To really round add .5 (does that work?) and truncate.
It turns out you can add .5 to GetDate() and it works as expected.
-- Round Current time to midnight today or midnight tomorrow
SELECT Convert(DateTime, DATEDIFF(DAY, 0, GETDATE() + .5))
I did all my trials on SQL Server 2008, but I think these functions apply to 2005 as well.
or select Edit Scheme
from Product
> Scheme
Menu
select Enable Zombie Objects
form the Diagnostics
tab
As alternative, if you prefer .xcconfig
files you can read this article https://therealbnut.wordpress.com/2012/01/01/setting-xcode-4-0-environment-variables-from-a-script/
I'm using Django 1.9, SQLite3 and DjangoCMS 3.2 and had the same issue. I solved it by running python manage.py makemigrations
. This was followed by a prompt stating that the database contained non-null value types but did not have a default value set. It gave me two options: 1) select a one off value now or 2) exit and change the default setting in models.py. I selected the first option and gave the default value of 1. Repeated this four or five times until the prompt said it was finished. I then ran python manage.py migrate
. Now it works just fine. Remember, by running python manage.py makemigrations
first, a revised copy of the database is created (mine was 0004) and you can always revert back to a previous database state.
junit4
require that test classname should be use Test
as suffix.
// Change the way body-parser is used
const bodyParser = require('body-parser');
var rawBodySaver = function (req, res, buf, encoding) {
if (buf && buf.length) {
req.rawBody = buf.toString(encoding || 'utf8');
}
}
app.use(bodyParser.json({ verify: rawBodySaver, extended: true }));
// Now we can access raw-body any where in out application as follows
request.rawBody;
My solution to your problem would be to either:
1 - use int instead of enums: Declare your ints in an anonymous namespace in your CPP file (not in the header):
namespace
{
const int FUNCTIONALITY_NORMAL = 0 ;
const int FUNCTIONALITY_RESTRICTED = 1 ;
const int FUNCTIONALITY_FOR_PROJECT_X = 2 ;
}
As your methods are private, no one will mess with the data. You could even go further to test if someone sends you an invalid data:
namespace
{
const int FUNCTIONALITY_begin = 0 ;
const int FUNCTIONALITY_NORMAL = 0 ;
const int FUNCTIONALITY_RESTRICTED = 1 ;
const int FUNCTIONALITY_FOR_PROJECT_X = 2 ;
const int FUNCTIONALITY_end = 3 ;
bool isFunctionalityCorrect(int i)
{
return (i >= FUNCTIONALITY_begin) && (i < FUNCTIONALITY_end) ;
}
}
2 : create a full class with limited const instantiations, like done in Java. Forward declare the class, and then define it in the CPP file, and instanciate only the enum-like values. I did something like that in C++, and the result was not as satisfying as desired, as it needed some code to simulate an enum (copy construction, operator =, etc.).
3 : As proposed before, use the privately declared enum. Despite the fact an user will see its full definition, it won't be able to use it, nor use the private methods. So you'll usually be able to modify the enum and the content of the existing methods without needing recompiling of code using your class.
My guess would be either the solution 3 or 1.
Assuming you've got access to a standard Unix shell and/or cygwin environment:
tr -s ' ' '\n' < yourfile | sort | uniq -d -c
^--space char
Basically: convert all space characters to linebreaks, then sort the tranlsated output and feed that to uniq and count duplicate lines.
Here's a simple way, using the new array literal syntax:
NSString * s = [@[@"one ", @"two ", @"three"] componentsJoinedByString:@""];
^^^^^^^ create array ^^^^^
^^^^^^^ concatenate ^^^^^
It's possible, as addressed in Issue #7396:
When you do want to insert a
<br />
break tag using Markdown, you end a line with two or more spaces, then type return or Enter.
put at the end it will reopen your console
start cmd
NOTICE: This is never a recommended use of git. This will overwrite changes on the remote. Only do this if you know 100% that your local changes should be pushed to the remote master.
Try this: git push -f origin master
while(something.hasnext())
do something...
if(contains something to process){
do something...
break;
}
}
Just use the break statement;
For eg:this just prints "Breaking..."
while (true) {
if (true) {
System.out.println("Breaking...");
break;
}
System.out.println("Did this print?");
}
When installing Python 3.4 the "Add python.exe to Path" came up unselected. Re-installed with this selected and problem resolved.
Ok, since my attempt to post my solution in a comment failed, here's what I was trying to say. I could do exactly what I wanted from native Python (on Windows, not anywhere else though) with the following code:
import msvcrt
def kbfunc():
x = msvcrt.kbhit()
if x:
ret = ord(msvcrt.getch())
else:
ret = 0
return ret
In PL/SQL, A cursor is a pointer to this context area. It contains all the information needed for processing the statement.
Implicit Cursors: Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it.
Explicit Cursors: Explicit cursors are programmer-defined cursors for gaining more control over the context area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is:
CURSOR cursor_name IS select_statement;
The old fashion emacs bindings can still work in iterm2 and os x terminal:
Preferences -> Profiles -> Keys (sub tab in profiles)
Left/Right option <kbd>?</kbd> key acts as +Esc
(similar in os x terminal)This should enable alt-f and alt-b for moving words by words. (Still ctrl-a and ctrl-e always work as usual)
If set as meta
those old bindings will work while some iterm2 bindings unavailable.