If you use Bitnami installer for wampstack, go to:
c:/Bitnami/wampstack-5.6.24-0/apache/conf (of course your version number may be different)
Open the file: httpd.conf in a text editor like Visual Studio code or Notepad ++
Do a search for "DocumentRoot". See image.
You will be able to change the directory in this file.
For me it was on line 183, but it only works after you reboot your computer. I wish there was a way to quickly change it without having to reboot each time, but for now that's the only way I know how.
Using the ArrayObject from Std or building your own
(new \ArrayObject($existingStdClass))
you can use the build in method on the new class:
getArrayCopy()
or pass the new object to
iterator_to_array
Here is some help if you do the download through a server (this way you can name/convert/post-process/etc your file):
-Post data using toDataURL
-Set the headers
$filename = "test.jpg"; //or png
header('Content-Description: File Transfer');
if($msie = !strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false)
header("Content-type: application/force-download");else
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Transfer-Encoding: binary");
header("Expires: 0"); header("Cache-Control: must-revalidate");
header("Pragma: public");
-create image
$data = $_POST['data'];
$img = imagecreatefromstring(base64_decode(substr($data,strpos($data,',')+1)));
-export image as JPEG
$width = imagesx($img);
$height = imagesy($img);
$output = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($output, 255, 255, 255);
imagefilledrectangle($output, 0, 0, $width, $height, $white);
imagecopy($output, $img, 0, 0, 0, 0, $width, $height);
imagejpeg($output);
exit();
imagesavealpha($img, true);
imagepng($img);
die($img);
Found my solution on Apache/2.2.15 (Unix).
And Thanks for answer from @QuantumHive:
First: I finded all
Order allow,deny
Deny from all
instead of
Order allow,deny
Allow from all
and then:
I setted
#
# Control access to UserDir directories. The following is an example
# for a site where these directories are restricted to read-only.
#
#<Directory /var/www/html>
# AllowOverride FileInfo AuthConfig Limit
# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
# <Limit GET POST OPTIONS>
# Order allow,deny
# Allow from all
# </Limit>
# <LimitExcept GET POST OPTIONS>
# Order deny,allow
# Deny from all
# </LimitExcept>
#</Directory>
Remove the previous "#" annotation to
#
# Control access to UserDir directories. The following is an example
# for a site where these directories are restricted to read-only.
#
<Directory /var/www/html>
AllowOverride FileInfo AuthConfig Limit
Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
<Limit GET POST OPTIONS>
Order allow,deny
Allow from all
</Limit>
<LimitExcept GET POST OPTIONS>
Order deny,allow
Deny from all
</LimitExcept>
</Directory>
ps. my WebDir is: /var/www/html
This way is comparatively more easy
SELECT doc_id,serial_number,status FROM date_time ORDER BY date_time DESC LIMIT 0,1;
Simply use this to get date before 300 days, replace 300 with your days:
Date date = new Date(); // Or where ever you get it from
Date daysAgo = new DateTime(date).minusDays(300).toDate();
Here,
DateTime
is org.joda.time.DateTime;
Date
is java.util.Date
Scrolling div on click of button.
Html Code:-
<div id="textBody" style="height:200px; width:600px; overflow:auto;">
<!------Your content---->
</div>
JQuery code for scrolling div:-
$(function() {
$( "#upBtn" ).click(function(){
$('#textBody').scrollTop($('#textBody').scrollTop()-20);
});
$( "#downBtn" ).click(function(){
$('#textBody').scrollTop($('#textBody').scrollTop()+20);;
});
});
Constraints are part of a database schema definition.
A constraint is usually associated with a table and is created with a CREATE CONSTRAINT
or CREATE ASSERTION
SQL statement.
They define certain properties that data in a database must comply with. They can apply to a column, a whole table, more than one table or an entire schema. A reliable database system ensures that constraints hold at all times (except possibly inside a transaction, for so called deferred constraints).
Common kinds of constraints are:
I found that simply setting the line-height and height to the same pixel quantity produced the most consistent result. By "most consistent" I mean optimally consistent but of course it is not 100% "pixel-perfect" across browsers. Additionally I found that Firefox (v. 17.x) tends to crowd the option text to the right against the drop-down arrow; I alleviated this with a small amount of padding-right set on the OPTION element only. This setting does not affect appearance in IE 7-9.
My result:
select, option {
font-size:10px;
height:19px;
line-height: 19px;
padding:0;
margin:0;
}
option {
padding-right:6px; /* Firefox */
}
NOTE -- my SELECT element uses a smaller font, 10px. Obviously you will need to adjust proportions accordingly for your specific UI context.
This is merely an educated guess without seeing the rest of your HTML/CSS:
Have you applied display: block
or display: inline-block
to li a
? If not, try it.
Otherwise, try applying the CSS3 transform rules to li
instead.
Use isinstance
, nothing else:
if isinstance(x, pd.DataFrame):
... # do something
PEP8 says explicitly that isinstance
is the preferred way to check types
No: type(x) is pd.DataFrame
No: type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)
And don't even think about
if obj.__class__.__name__ = 'DataFrame':
expect_problems_some_day()
isinstance
handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str
or unicode
), because they derive from basestring
)
if isinstance(obj, basestring):
i_am_string(obj)
Specifically for pandas
DataFrame
objects:
import pandas as pd
isinstance(var, pd.DataFrame)
With the Hub command-line wrapper you can link it to git and then you can do
git pull-request
From the man page of hub:
git pull-request [-f] [TITLE|-i ISSUE|ISSUE-URL] [-b BASE] [-h HEAD]
Opens a pull request on GitHub for the project that the "origin" remote points to. The default head of the pull request is the current branch. Both base and head of the pull request can be explicitly given in one of the following formats: "branch", "owner:branch",
"owner/repo:branch". This command will abort operation if it detects that the current topic branch has local commits that are not yet pushed to its upstream branch on the remote. To skip this check, use -f.
If TITLE is omitted, a text editor will open in which title and body of the pull request can be entered in the same manner as git commit message.
If instead of normal TITLE an issue number is given with -i, the pull request will be attached to an existing GitHub issue. Alternatively, instead of title you can paste a full URL to an issue on GitHub.
Pure Python2 w/o dep:
def relpath(cwd, path):
"""Create a relative path for path from cwd, if possible"""
if sys.platform == "win32":
cwd = cwd.lower()
path = path.lower()
_cwd = os.path.abspath(cwd).split(os.path.sep)
_path = os.path.abspath(path).split(os.path.sep)
eq_until_pos = None
for i in xrange(min(len(_cwd), len(_path))):
if _cwd[i] == _path[i]:
eq_until_pos = i
else:
break
if eq_until_pos is None:
return path
newpath = [".." for i in xrange(len(_cwd[eq_until_pos+1:]))]
newpath.extend(_path[eq_until_pos+1:])
return os.path.join(*newpath) if newpath else "."
Simplest Way that i have tried Just now
from datetime import datetime
from django.utils import timezone
current = timezone.now()
if current.month == 1:
month = 12
else:
month = current.month - 1
current = datetime(current.year, month, current.day)
HashTable is synchronized, if you are using it in a single thread you can use HashMap, which is an unsynchronized version. Unsynchronized objects are often a little more performant. By the way if multiple threads access a HashMap concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. Youn can wrap a unsynchronized map in a synchronized one using :
Map m = Collections.synchronizedMap(new HashMap(...));
HashTable can only contain non-null object as a key or as a value. HashMap can contain one null key and null values.
The iterators returned by Map are fail-fast, if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException
. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Whereas the Enumerations returned by Hashtable's keys and elements methods are not fail-fast.
HashTable and HashMap are member of the Java Collections Framework (since Java 2 platform v1.2, HashTable was retrofitted to implement the Map interface).
HashTable is considered legacy code, the documentation advise to use ConcurrentHashMap in place of Hashtable if a thread-safe highly-concurrent implementation is desired.
HashMap doesn't guarantee the order in which elements are returned. For HashTable I guess it's the same but I'm not entirely sure, I don't find ressource that clearly state that.
As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.
It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.
library(grid)
library(gridExtra)
library(plyr)
# create a new column with proportions
prop <- function(x) x/sum(x)
Data <- ddply(Data,"Year",transform,Share=prop(Frequency))
# create the component graphics
totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") +
xlab("") + labs(title = "Frequency totals in given Year")
proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category))
+ geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") +
labs(title = "Proportion of total Frequency accounted by each Category in given Year")
# bring them together
grid.arrange(totals,proportion)
This will give you a 2 panel display like this:
If you want to add Frequency values a table is the best format.
ExecuteNonQuery method will return number of rows effected with INSERT, DELETE or UPDATE operations. This ExecuteNonQuery method will be used only for insert, update and delete, Create, and SET statements. (Read More)
ExecuteScalar will return single row single column value i.e. single value, on execution of SQL Query or Stored procedure using command object. It’s very fast to retrieve single values from database. (Read More)
ExecuteReader will be used to return the set of rows, on execution of SQL Query or Stored procedure using command object. This one is forward only retrieval of records and it is used to read the table values from first to last. (Read More)
This worked for me:
$("#element1").droppable(
{
drop: function(event, ui)
{
var currentPos = ui.helper.position();
alert("left="+parseInt(currentPos.left)+" top="+parseInt(currentPos.top));
}
});
You can use the Logical NOT !
operator:
if (!$(this).parent().next().is('ul')){
Or equivalently (see comments below):
if (! ($(this).parent().next().is('ul'))){
For more information, see the Logical Operators section of the MDN docs.
You could also use lambda
. Useful if you're using django.utils.timezone.now
date = models.DateField(_("Date"), default=lambda: now().date())
@user1417684 and @chris-foster are right!
excerpt from working code (without error handling):
var SubItemModel = mongoose.model('subitems', SubItemSchema);
var ItemModel = mongoose.model('items', ItemSchema);
var new_sub_item_model = new SubItemModel(new_sub_item_plain);
new_sub_item_model.save(function (error, new_sub_item) {
var new_item = new ItemModel(new_item);
new_item.subitem = new_sub_item._id;
new_item.save(function (error, new_item) {
// so this is a valid way to populate via the Model
// as documented in comments above (here @stack overflow):
ItemModel.populate(new_item, { path: 'subitem', model: 'subitems' }, function(error, new_item) {
callback(new_item.toObject());
});
// or populate directly on the result object
new_item.populate('subitem', function(error, new_item) {
callback(new_item.toObject());
});
});
});
First, start the code block with <%# instead of <%= :
<head id="head1" runat="server">
<title>My Page</title>
<link href="css/common.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%# ResolveUrl("~/javascript/leesUtils.js") %>"></script>
</head>
This changes the code block from a Response.Write code block to a databinding expression.
Since <%# ... %>
databinding expressions aren't code blocks, the CLR won't complain. Then in the code for the master page, you'd add the following:
protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();
}
The rest of answers are pretty good, but just wanted to add some extra information in case someone comes here looking for a solution to replace/update a multiline echo.
So I would like to share an example with you all. The following script was tried on a CentOS system and uses "timedatectl" command which basically prints some detailed time information of your system.
I decided to use that command as its output contains multiple lines and works perfectly for the example below:
#!/bin/bash
while true; do
COMMAND=$(timedatectl) #Save command result in a var.
echo "$COMMAND" #Print command result, including new lines.
sleep 3 #Keep above's output on screen during 3 seconds before clearing it
#Following code clears previously printed lines
LINES=$(echo "$COMMAND" | wc -l) #Calculate number of lines for the output previously printed
for (( i=1; i <= $(($LINES)); i++ ));do #For each line printed as a result of "timedatectl"
tput cuu1 #Move cursor up by one line
tput el #Clear the line
done
done
The above will print the result of "timedatectl
" forever and will replace the previous echo with updated results.
I have to mention that this code is only an example, but maybe not the best solution for you depending on your needs.
A similar command that would do almost the same (at least visually) is "watch -n 3 timedatectl
".
But that's a different story. :)
Hope that helps!
You forgot to print
the result. What you get is the P
in RE(P)L
and not the actual printed result.
In Py2.x you should so something like
>>> print "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines
and in Py3.X, print is a function, so you should do
print("\n".join(['I', 'would', 'expect', 'multiple', 'lines']))
Now that was the short answer. Your Python Interpreter, which is actually a REPL, always displays the representation of the string rather than the actual displayed output. Representation is what you would get with the repr
statement
>>> print repr("\n".join(['I', 'would', 'expect', 'multiple', 'lines']))
'I\nwould\nexpect\nmultiple\nlines'
If you store the padding in resource files, you can simply call
int padding = getResources().getDimensionPixelOffset(R.dimen.padding);
It does the conversion for you.
From your shell run:
pip2 install unicodecsv
And (unlike the original question) presuming you're using Python's built in csv
module, turn
import csv
into
import unicodecsv as csv
in your code.
Maybe something like this:
SELECT count(*) FROM user_tab_columns WHERE table_name = 'FOO'
this will count number of columns in a the table FOO
You can also just
select count(*) from all_tab_columns where owner='BAR' and table_name='FOO';
where the owner is schema and note that Table Names are upper case
When it comes to inserting a picture, r2evans's suggestion of ![Caption for the picture.](/path/to/image.png)
can be problematic if PDF output is required.
The knitr function include_graphics
knitr::include_graphics('/path/to/image.png')
is a more portable alternative
that will generate, on your behalf, the markdown that is most appropriate to the output format that you are generating.
This feature helps not only delaying expensive calculations, but is also useful to construct mutual dependent or cyclic structures. E.g. this leads to an stack overflow:
trait Foo { val foo: Foo }
case class Fee extends Foo { val foo = Faa() }
case class Faa extends Foo { val foo = Fee() }
println(Fee().foo)
//StackOverflowException
But with lazy vals it works fine
trait Foo { val foo: Foo }
case class Fee extends Foo { lazy val foo = Faa() }
case class Faa extends Foo { lazy val foo = Fee() }
println(Fee().foo)
//Faa()
Vectors and matrices can only be of a single type and cbind
and rbind
on vectors will give matrices. In these cases, the numeric values will be promoted to character values since that type will hold all the values.
(Note that in your rbind
example, the promotion happens within the c
call:
> c(10, "[]", "[[1,2]]")
[1] "10" "[]" "[[1,2]]"
If you want a rectangular structure where the columns can be different types, you want a data.frame
. Any of the following should get you what you want:
> x = data.frame(v1=c(10, 20), v2=c("[]", "[]"), v3=c("[[1,2]]","[[1,3]]"))
> x
v1 v2 v3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ v1: num 10 20
$ v2: Factor w/ 1 level "[]": 1 1
$ v3: Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
or (using specifically the data.frame
version of cbind
)
> x = cbind.data.frame(c(10, 20), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
c(10, 20) c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ c(10, 20) : num 10 20
$ c("[]", "[]") : Factor w/ 1 level "[]": 1 1
$ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
or (using cbind
, but making the first a data.frame
so that it combines as data.frames do):
> x = cbind(data.frame(c(10, 20)), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
c.10..20. c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ c.10..20. : num 10 20
$ c("[]", "[]") : Factor w/ 1 level "[]": 1 1
$ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
To find out if a path is a valid directory try:
file.info(cacheDir)[1,"isdir"]
file.info
does not care about a slash on the end.
file.exists
on Windows will fail for a directory if it ends in a slash, and succeeds without it. So this cannot be used to determine if a path is a directory.
file.exists("R:/data/CCAM/CCAMC160b_echam5_A2-ct-uf.-5t05N.190to240E_level1000/cache/")
[1] FALSE
file.exists("R:/data/CCAM/CCAMC160b_echam5_A2-ct-uf.-5t05N.190to240E_level1000/cache")
[1] TRUE
file.info(cacheDir)["isdir"]
The difference between the two is best brought in what seems a necessary and sufficient definition of the dependencyManagement element available in Maven website docs:
dependencyManagement
"Default dependency information for projects that inherit from this one. The dependencies in this section are not immediately resolved. Instead, when a POM derived from this one declares a dependency described by a matching groupId and artifactId, the version and other values from this section are used for that dependency if they were not already specified." [ https://maven.apache.org/ref/3.6.1/maven-model/maven.html ]
It should be read along with some more information available on a different page:
“..the minimal set of information for matching a dependency reference against a dependencyManagement section is actually {groupId, artifactId, type, classifier}. In many cases, these dependencies will refer to jar artifacts with no classifier. This allows us to shorthand the identity set to {groupId, artifactId}, since the default for the type field is jar, and the default classifier is null.” [https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html ]
Thus, all the sub-elements (scope, exclusions etc.,) of a dependency element--other than groupId, artifactId, type, classifier, not just version--are available for lockdown/default at the point (and thus inherited from there onward) you specify the dependency within a dependencyElement. If you’d specified a dependency with the type and classifier sub-elements (see the first-cited webpage to check all sub-elements) as not jar and not null respectively, you’d need {groupId, artifactId, classifier, type} to reference (resolve) that dependency at any point in an inheritance originating from the dependencyManagement element. Else, {groupId, artifactId} would suffice if you do not intend to override the defaults for classifier and type (jar and null respectively). So default is a good keyword in that definition; any sub-element(s) (other than groupId, artifactId, classifier and type, of course) explicitly assigned value(s) at the point you reference a dependency override the defaults in the dependencyManagement element.
So, any dependency element outside of dependencyManagement, whether as a reference to some dependencyManagement element or as a standalone is immediately resolved (i.e. installed to the local repository and available for classpaths).
For the sake of ease of use and understandability.
You can simply put a Tooltip anywhere on your form (from toolbox). You will then be given an options in the Properties of everything else in your form to determine what is displayed in that Tooltip (it reads something like "ToolTip on toolTip1"). Anytime you hover on an object, the text in that property will be displayed as a tooltip.
This does not cover custom on-the-fly tooltips like the original question is asking for. But I am leaving this here for others that do not need
Here's an example:
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
int main() {
const char* const list[] = {"zip", "zam", "bam"};
const size_t len = sizeof(list) / sizeof(list[0]);
for (size_t i = 0; i < len; ++i)
std::cout << list[i] << "\n";
const std::vector<string> v(list, list + len);
std::copy(v.begin(), v.end(), std::ostream_iterator<string>(std::cout, "\n"));
}
new AsyncRoute({path: '/demo/:demoKey1/:demoKey2', loader: () => {
return System.import('app/modules/demo/demo').then(m =>m.demoComponent);
}, name: 'demoPage'}),
export class demoComponent {
onClick(){
this._router.navigate( ['/demoPage', {demoKey1: "123", demoKey2: "234"}]);
}
}
Here is a short example, the C++ way using rdbuf
. I got this from the web. I can't find my original source on this:
#include <fstream>
#include <iostream>
int main ()
{
std::ifstream f1 ("C:\\me.txt",std::fstream::binary);
std::ofstream f2 ("C:\\me2.doc",std::fstream::trunc|std::fstream::binary);
f2<<f1.rdbuf();
return 0;
}
It’s easy; just do the following:
rvm implode
or
rm -rf ~/.rvm
And don’t forget to remove the script calls in the following files:
~/.bashrc
~/.bash_profile
~/.profile
And maybe others depending on whatever shell you’re using.
If you don't really need the button element, just move the classes to a regular link:
<div class="btn-group">
<a href="/save/1" class="btn btn-primary active">
<i class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></i> Save
</a>
<a href="/cancel/1" class="btn btn-default">Cancel</a>
</div>
Conversely, you can also change a button to appear like a link:
<button type="button" class="btn btn-link">Link</button>
The most straigh forward way I found using VisualStudio 2019 to debug an external library to which you are referencing in NuGet, is by taking the following steps:
Tools > Options > Debugging > General > Untick 'Enable Just My Code'
Type the NuGet package name you want to debug in the search field & click 'OK'
From the Assembly Explorer, right-click on the assembly imported and select 'Generate Pdb'
Select a custom path where you want to save the .PDB file and the framework you want this to be generated for
Copy the .PDB file from the folder generated to your Debug folder and you can now set breakpoints on this assembly's library code
Try:
select
id,
StartDate,
CASE WHEN StartDate IS NULL
THEN 'Awaiting'
ELSE 'Approved' END AS StartDateStatus
FROM myTable
You code would have been doing a When StartDate = NULL, I think.
NULL
is never equal to NULL
(as NULL is the absence of a value). NULL
is also never not equal to NULL
. The syntax noted above is ANSI SQL standard and the converse would be StartDate IS NOT NULL
.
You can run the following:
SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison
And this returns:
EqualityCheck = 0
InEqualityCheck = 0
NullComparison = 1
For completeness, in SQL Server you can:
SET ANSI_NULLS OFF;
Which would result in your equals comparisons working differently:
SET ANSI_NULLS OFF
SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison
Which returns:
EqualityCheck = 1
InEqualityCheck = 0
NullComparison = 1
But I would highly recommend against doing this. People subsequently maintaining your code might be compelled to hunt you down and hurt you...
Also, it will no longer work in upcoming versions of SQL server:
DECLARE @min INT = 3;
DECLARE @max INT = 6;
SELECT @min + ROUND(RAND() * (@max - @min), 0);
Step by step
DECLARE @min INT = 3;
DECLARE @max INT = 6;
DECLARE @rand DECIMAL(19,4) = RAND();
DECLARE @difference INT = @max - @min;
DECLARE @chunk INT = ROUND(@rand * @difference, 0);
DECLARE @result INT = @min + @chunk;
SELECT @result;
Note that a user-defined function thus not allow the use of RAND(). A workaround for this (source: http://blog.sqlauthority.com/2012/11/20/sql-server-using-rand-in-user-defined-functions-udf/) is to create a view first.
CREATE VIEW [dbo].[vw_RandomSeed]
AS
SELECT RAND() AS seed
and then create the random function
CREATE FUNCTION udf_RandomNumberBetween
(
@min INT,
@max INT
)
RETURNS INT
AS
BEGIN
RETURN @min + ROUND((SELECT TOP 1 seed FROM vw_RandomSeed) * (@max - @min), 0);
END
The Java code given by Dommer above gives slightly incorrect results but the small errors add up if you are processing say a GPS track. Here is an implementation of the Haversine method in Java which also takes into account height differences between two points.
/**
* Calculate distance between two points in latitude and longitude taking
* into account height difference. If you are not interested in height
* difference pass 0.0. Uses Haversine method as its base.
*
* lat1, lon1 Start point lat2, lon2 End point el1 Start altitude in meters
* el2 End altitude in meters
* @returns Distance in Meters
*/
public static double distance(double lat1, double lat2, double lon1,
double lon2, double el1, double el2) {
final int R = 6371; // Radius of the earth
double latDistance = Math.toRadians(lat2 - lat1);
double lonDistance = Math.toRadians(lon2 - lon1);
double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = R * c * 1000; // convert to meters
double height = el1 - el2;
distance = Math.pow(distance, 2) + Math.pow(height, 2);
return Math.sqrt(distance);
}
This code reads csv to DataTable:
public static DataTable ReadCsv(string path)
{
DataTable result = new DataTable("SomeData");
using (TextFieldParser parser = new TextFieldParser(path))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
bool isFirstRow = true;
//IList<string> headers = new List<string>();
while (!parser.EndOfData)
{
string[] fields = parser.ReadFields();
if (isFirstRow)
{
foreach (string field in fields)
{
result.Columns.Add(new DataColumn(field, typeof(string)));
}
isFirstRow = false;
}
else
{
int i = 0;
DataRow row = result.NewRow();
foreach (string field in fields)
{
row[i++] = field;
}
result.Rows.Add(row);
}
}
}
return result;
}
Well, the JVM memory model works something like this: values are stored on one pile of memory stack and objects are stored on another pile of memory called the heap. The garbage collector looks for garbage by looking at a list of objects you've made and seeing which ones aren't pointed at by anything. This is where setting an object to null
comes in; all nonprimitive (think of classes) variables are really references that point to the object on the stack, so by setting the reference you have to null
the garbage collector can see that there's nothing else pointing at the object and it can decide to garbage collect it. All Java objects are stored on the heap so they can be seen and collected by the garbage collector.
Nonprimitive (int
s, char
s, double
s, those sort of things) values, however, aren't stored on the heap. They're created and stored temporarily as they're needed and there's not much you can do there, but thankfully the compilers nowadays are really efficient and will avoid needed to store them on the JVM stack unless they absolutely need to.
On a bytecode level, that's basically how it works. The JVM is based on a stack-based machine, with a couple instructions to create allocate objects on the heap as well, and a ton of instructions to manipulate, push and pop values, off the stack. Local variables are stored on the stack, allocated variables on the heap.* These are the heap and the stack I'm referring to above. Here's a pretty good starting point if you want to get into the nitty gritty details.
In the resulting compiled code, there's a bit of leeway in terms of implementing the heap and stack. Allocation's implemented as allocation, there's really not a way around doing so. Thus the virtual machine heap becomes an actual heap, and allocations in the bytecode are allocations in actual memory. But you can get around using a stack to some extent, since instead of storing the values on a stack (and accessing a ton of memory), you can stored them on registers on the CPU which can be up to a hundred times (maybe even a thousand) faster than storing it on memory. But there's cases where this isn't possible (look up register spilling for one example of when this may happen), and using a stack to implement a stack kind of makes a lot of sense.
And quite frankly in your case a few integers probably won't matter. The compiler will probably optimize them out by itself in this case anyways. Optimization should always happen after you get it running and notice it's a tad slower than you'd prefer it to be. Worry about making simple, elegant, working code first then later make it fast (and hopefully) simple, elegant, working code.
Java's actually very nicely made so that you shouldn't have to worry about null
ing variables very often. Whenever you stop needing to use something, it will usually incidentally be disappearing from the scope of your program (and thus becoming eligible for garbage collection). So I guess the real lesson here is to use local variables as often as you can.
*There's also a constant pool, a local variable pool, and a couple other things in memory but you have close to no control over the size of those things and I want to keep this fairly simple.
Just go to vmvare edit->preferences->shared vms. Click on change settings and disable sharing.click on OK.xampp will work fine.
Fail module works great! Thanks.
I had to define my fact before checking it, otherwise I'd get an undefined variable error.
And I had issues when doing setting the fact with quotes and without spaces.
This worked:
set_fact: flag="failed"
This threw errors:
set_fact: flag = failed
$("#id").change(function(){
//does some stuff;
});
Source: https://github.com/webcaetano/mongo-mysql
10 rows
mysql insert: 1702ms
mysql select: 11ms
mongo insert: 47ms
mongo select: 12ms
100 rows
mysql insert: 8171ms
mysql select: 10ms
mongo insert: 167ms
mongo select: 60ms
1000 rows
mysql insert: 94813ms (1.58 minutes)
mysql select: 13ms
mongo insert: 1013ms
mongo select: 677ms
10.000 rows
mysql insert: 924695ms (15.41 minutes)
mysql select: 144ms
mongo insert: 9956ms (9.95 seconds)
mongo select: 4539ms (4.539 seconds)
I know I am late to the party, but this should work no matter how you start the script and uses builtins exclusively:
DIR="${BASH_SOURCE%/*}"
if [[ ! -d "$DIR" ]]; then DIR="$PWD"; fi
. "$DIR/incl.sh"
. "$DIR/main.sh"
.
(dot) command is an alias to source
, $PWD
is the Path for the Working Directory, BASH_SOURCE
is an array variable whose members are the source filenames, ${string%substring}
strips shortest match of $substring from back of $string
This guide is oriented to developers who already have an application in the Play Store. If you are starting with a new app the process it's much easier and you can follow the guidelines of paragraph "New apps" from here
Prerequisites that 99% of developers already have :
Android Studio
JDK 8 and after installation you need to setup an environment variable in your user space to simplify terminal commands. In Windows x64 you need to add this : C:\Program Files\Java\{JDK_VERSION}\bin
to the Path
environment variable. (If you don't know how to do this you can read my guide to add a folder to the Windows 10 Path
environment variable).
Step 0: Open Google Play developer console, then go to Release Management -> App Signing.
Accept the App Signing TOS.
Step 1: Download PEPK Tool clicking the button identical to the image below
Step 2: Open a terminal and type:
java -jar PATH_TO_PEPK --keystore=PATH_TO_KEYSTORE --alias=ALIAS_YOU_USE_TO_SIGN_APK --output=PATH_TO_OUTPUT_FILE --encryptionkey=GOOGLE_ENCRYPTION_KEY
Legend:
C:\Users\YourName\Downloads\pepk.jar
for Windows users.C:\Android\mykeystore
or C:\Android\mykeystore.keystore
etc...C:\Android\private_key.pem
eb10fe8f7c7c9df715022017b00c6471f8ba8170b13049a11e6c09ffe3056a104a3bbe4ac5a955f4ba4fe93fc8cef27558a3eb9d2a529a2092761fb833b656cd48b9de6a
Example:
java -jar "C:\Users\YourName\Downloads\pepk.jar" --keystore="C:\Android\mykeystore" --alias=myalias --output="C:\Android\private_key.pem" --encryptionkey=eb10fe8f7c7c9df715022017b00c6471f8ba8170b13049a11e6c09ffe3056a104a3bbe4ac5a955f4ba4fe93fc8cef27558a3eb9d2a529a2092761fb833b656cd48b9de6a
Press Enter and you will need to provide in order:
If everything has gone OK, you now will have a file in PATH_TO_OUTPUT_FILE folder called private_key.pem
.
Step 3: Upload the private_key.pem file clicking the button identical to the image below
Step 4: Create a new keystore file using Android Studio.
YOU WILL NEED THIS KEYSTORE IN THE FUTURE TO SIGN THE NEXT RELEASES OF YOUR APP, DON'T FORGET THE PASSWORDS
Open one of your Android projects (choose one at random). Go to Build -> Generate Signed APK and press Create new.
Now you should fill the required fields.
Key store path represent the new keystore you will create, choose a folder and a name using the 3 dots icon on the right, i choosed
C:\Android\upload_key.jks
(.jks extension will be added automatically)NOTE: I used
upload
as the new alias name but if you previously used the same keystore with different aliases to sign different apps, you should choose the same aliases name you had previously in the original keystore.
Press OK when finished, and now you will have a new upload_key.jks
keystore. You can close Android Studio now.
Step 5: We need to extract the upload certificate from the newly created upload_key.jks
keystore.
Open a terminal and type:
keytool -export -rfc -keystore UPLOAD_KEYSTORE_PATH -alias UPLOAD_KEYSTORE_ALIAS -file PATH_TO_OUTPUT_FILE
Legend:
C:\Android\upload_key.jks
.upload
.C:\Android\upload_key_public_certificate.pem
.Example:
keytool -export -rfc -keystore "C:\Android\upload_key.jks" -alias upload -file "C:\Android\upload_key_public_certificate.pem"
Press Enter and you will need to provide the keystore password.
Now if everything has gone OK, you will have a file in the folder PATH_TO_OUTPUT_FILE called upload_key_public_certificate.pem
.
Step 6: Upload the upload_key_public_certificate.pem
file clicking the button identical to the image below
Step 7: Click ENROLL button at the end of the App Signing page.
Now every new release APK must be signed with the upload_key.jks
keystore and aliases created in Step 4, prior to be uploaded in the Google Play Developer console.
More Resources:
Q: When i upload the APK signed with the new upload_key keystore, Google Play show an error like : You uploaded an unsigned APK. You need to create a signed APK.
A: Check to sign the APK with both signatures (V1 and V2) while building the release APK. Read here for more details.
The step 4,5,6 are to create upload key which is optional for existing apps
"Upload key (optional for existing apps): A new key you generate during your enrollment in the program. You will use the upload key to sign all future APKs prior to uploading them to the Play Console." https://support.google.com/googleplay/android-developer/answer/7384423
My answer provides a ways to run a subset of test in different scenarios.
pytest
To run all the tests from one directory, use the directory as a parameter to
pytest
:
pytest tests/my-directory
To run a file full of tests, list the file with the relative path as a parameter to pytest
:
pytest tests/my-directory/test_demo.py
To run a single test function, add ::
and the test function name:
pytest -v tests/my-directory/test_demo.py::test_specific_function
-v
is used so you can see which function was run.
To run just a class, do like we did with functions and add ::
, then the class name to the file parameter:
pytest -v tests/my-directory/test_demo.py::TestClassName
If you don't want to run all of a test class, just one method, just add
another ::
and the method name:
pytest -v tests/my-directory/test_demo.py::TestClassName::test_specific_method
The -k
option enables you to pass in an expression to run tests that have
certain names specified by the expression as a substring of the test name.
It is possible to use and, or, and not to create complex expressions.
For example, to run all of the functions that have _raises in their name:
pytest -v -k _raises
I usually use
DATE_ADD(CURDATE(), INTERVAL - 1 MONTH)
Which is almost same as Pekka's but this way you can control your INTERVAL to be negative or positive...
Try this:
new SimpleDateFormat("MM/dd/yyyy")
MM
is "month" (not mm
)dd
is "day" (not DD
)It's all in the javadoc for SimpleDateFormat
FYI, the reason your format is still a valid date format is that:
mm
is "minutes"DD
is "day in year"Also, you don't need the cast to Date
... it already is a Date
(or it explodes):
public static void main(String[] args) throws ParseException {
System.out.println(new SimpleDateFormat("MM/dd/yyyy").parse("08/16/2011"));
}
Output:
Tue Aug 16 00:00:00 EST 2011
Voila!
Another alternative, not sure if this applies to your particular problem but to some it may be applicable is to use UnaryOperator
in java.util.function library.
where it returns same type you specify, so you put all your variables in one class and is it as a parameter:
public class FunctionsLibraryUse {
public static void main(String[] args){
UnaryOperator<People> personsBirthday = (p) ->{
System.out.println("it's " + p.getName() + " birthday!");
p.setAge(p.getAge() + 1);
return p;
};
People mel = new People();
mel.setName("mel");
mel.setAge(27);
mel = personsBirthday.apply(mel);
System.out.println("he is now : " + mel.getAge());
}
}
class People{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
So the class you have, in this case Person
, can have numerous instance variables and won't have to change the parameter of your lambda expression.
For those interested, I've written notes on how to use java.util.function library: http://sysdotoutdotprint.com/index.php/2017/04/28/java-util-function-library/
To create a patch with both modified & new files (staged) you can run:
git diff HEAD > file_name.patch
I highly recommend the reading of a lecture in SciPy-lectures organization:
https://scipy-lectures.org/intro/language/reusing_code.html
It explains all the commented doubts.
But, new paths can be easily added and avoiding duplication with the following code:
import sys
new_path = 'insert here the new path'
if new_path not in sys.path:
sys.path.append(new_path)
import funcoes_python #Useful python functions saved in a different script
This works very well.
ArrayList<String[]> a = new ArrayList<String[]>();
a.add(new String[3]);
a.get(0)[0] = "Zubair";
a.get(0)[1] = "Borkala";
a.get(0)[2] = "Kerala";
System.out.println(a.get(0)[1]);
Result will be
Borkala
You can use one and more echo statement inside href
<a href="profile.php?usr=<?php echo $_SESSION['firstname']."&email=". $_SESSION['email']; ?> ">Link</a>
link : "/profile.php?usr=firstname&email=email"
This problem is quite annoying. I usually have Chinese character in my filename and file content. Please note that I am using Windows 10, here is my solution:
To display the file name, such as dir
or ls
if you installed Ubuntu bash on Windows 10
Set the region to support non-utf 8 character.
After that, console's font will be changed to the font of that locale, and it also changes the encoding of the console.
After you have done previous steps, in order to display the file content of a UTF-8 file using command line tool
chcp 65001
type
command to peek the file content, or cat
if you installed Ubuntu bash on Windows 10The laziest solution: Just use a console emulator such as http://cmder.net/
You want the %c
conversion specifier, which just reads a sequence of characters without special handling for whitespace.
Note that you need to fill the buffer with zeroes first, because the %c
specifier doesn't write a nul-terminator. You also need to specify the number of characters to read (otherwise it defaults to only 1):
memset(buffer, 0, 200);
sscanf("19 cool kid", "%d %199c", &age, buffer);
In fact I would not use any REDIM, nor a loop for transferring data from sheet to array:
dim arOne()
arOne = range("A2:F1000")
or even
arOne = range("A2").CurrentRegion
and that's it, your array is filled much faster then with a loop, no redim.
For posterity's sake, I've decided to throw my hat into the ring :)
Recently I've been seeing more and more restructuring away from the target
/selector
paradigm, in favor of things such as protocols, blocks, etc. However, there is one drop-in replacement for performSelector
that I've used a few times now:
[NSApp sendAction: NSSelectorFromString(@"someMethod") to: _controller from: nil];
These seem to be a clean, ARC-safe, and nearly identical replacement for performSelector
without having to much about with objc_msgSend()
.
Though, I have no idea if there is an analog available on iOS.
This happens when you forget to start the database before connecting to it:
mysql.server start
then
mysql -u root -p -h 127.0.0.1
Use setInverseBackgroundForced(true)
on the alert dialog builder to invert the background.
- (void)viewDidLoad {
[super viewDidLoad];
arr=[[NSArray alloc]initWithObjects:@"ABC",@"XYZ", nil];
tableview = [[UITableView alloc]initWithFrame:tableFrame style:UITableViewStylePlain];
tableview.delegate = self;
tableview.dataSource = self;
[self.view addSubview:tableview];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyCell"];
}
cell.textLabel.text=[arr objectAtIndex:indexPath.row];
return cell;
}
There is a mistake in your insert statement chage it to below and try :
String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";
~ $ hciconfig noauth
This should do the trick (I'm using bluez 5.23 and there's no more simple-egent and blue-utils). However, I'm trying to look for a way to make changes hciconfig permanent because after power out and then power on, authentication is needed again. So far, the changes in hciconfig still stays the same when you reboot it. it reverts back only when power out. If anybody has found a way to make hciconfig permanent, do let me know!
def dt2ts(dt, utc=False):
if utc:
return calendar.timegm(dt.timetuple())
if dt.tzinfo is None:
return int(time.mktime(dt.timetuple()))
utc_dt = dt.astimezone(tz.tzutc()).timetuple()
return calendar.timegm(utc_dt)
If you want UTC timestamp :time.mktime
just for local dt .Use calendar.timegm
is safe but dt must the utc zone so change the zone to utc. If dt in UTC just use calendar.timegm
.
You can use either HttpClient
or RestSharp
. Since I do not know what your code is, here is an example using HttpClient
:
using (var client = new HttpClient())
{
// This would be the like http://www.uber.com
client.BaseAddress = new Uri("Base Address/URL Address");
// serialize your json using newtonsoft json serializer then add it to the StringContent
var content = new StringContent(YourJson, Encoding.UTF8, "application/json")
// method address would be like api/callUber:SomePort for example
var result = await client.PostAsync("Method Address", content);
string resultContent = await result.Content.ReadAsStringAsync();
}
Typescript version:
export class Utility {
public static convertModelToFormData(model: any, form: FormData = null, namespace = ''): FormData {
let formData = form || new FormData();
let formKey;
for (let propertyName in model) {
if (!model.hasOwnProperty(propertyName) || !model[propertyName]) continue;
let formKey = namespace ? `${namespace}[${propertyName}]` : propertyName;
if (model[propertyName] instanceof Date)
formData.append(formKey, model[propertyName].toISOString());
else if (model[propertyName] instanceof Array) {
model[propertyName].forEach((element, index) => {
const tempFormKey = `${formKey}[${index}]`;
this.convertModelToFormData(element, formData, tempFormKey);
});
}
else if (typeof model[propertyName] === 'object' && !(model[propertyName] instanceof File))
this.convertModelToFormData(model[propertyName], formData, formKey);
else
formData.append(formKey, model[propertyName].toString());
}
return formData;
}
}
Using:
let formData = Utility.convertModelToFormData(model);
Warning: this way is not a safe way, but is very easy to use. Use it wisely.
Use the eval function.
print eval('2 + 4')
Output:
6
You can even use variables or regular python code.
a = 5
print eval('a + 4')
Output:
9
You also can get return values:
d = eval('4 + 5')
print d
Output:
9
Or call functions:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
a = 20
b = 10
print eval('add(a, b)')
print eval('subtract(a, b)')
Output:
30
10
In case you want to write a parser, maybe instead you can built a python code generator if that is easier and use eval to run the code. With eval you can execute any Python evalution.
Why eval is unsafe?
Since you can put literally anything in the eval, e.g. if the input argument is:
os.system(‘rm -rf /’)
It will remove all files on your system (at least on Linux/Unix). So only use eval when you trust the input.
just change the extension to .bmp.
Do this:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.PNG, 40, bytes);
//you can create a new file name "test.BMP" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.bmp")
It'll sound that I'm just fooling around, but try it once and it'll get saved in BMP
format. Cheers!
Just wanted to thank KM for his valuable solution. I implemented it myself to reduce the amount of lines in a shrinkdatabase request on SQLServer. Here is my SQL request if it can help anyone :
-- Declare the variable to be used
DECLARE @Query varchar (1000)
DECLARE @MyDBN varchar(11);
-- Initializing the @MyDBN variable (possible values : db1, db2, db3, ...)
SET @MyDBN = 'db1';
-- Creating the request to execute
SET @Query='use '+ @MyDBN +'; ALTER DATABASE '+ @MyDBN +' SET RECOVERY SIMPLE WITH NO_WAIT; DBCC SHRINKDATABASE ('+ @MyDBN +', 1, TRUNCATEONLY); ALTER DATABASE '+ @MyDBN +' SET RECOVERY FULL WITH NO_WAIT'
--
EXEC (@Query)
You might also want to check out some of the suggestions in this blog post: My new little friend, Enum<T>
The post describes a way to create a very simple generic helper class which enables you to avoid the ugly casting syntax inherent with Enum.Parse
- instead you end up writing something like this in your code:
MyColours colour = Enum<MyColours>.Parse(stringValue);
Or check out some of the comments in the same post which talk about using an extension method to achieve similar.
Without hitting db we can fetch all months name.
WITH CTE_Sample1 AS
(
Select 0 as MonthNumber
UNION ALL
select MonthNumber+1 FROM CTE_Sample1
WHERE MonthNumber+1<12
)
Select DateName( month , DateAdd( month , MonthNumber ,0 ) ) from CTE_Sample1
If you want to check the current device whether its iPad or iPhone then you can use these line of code :
if(UIDevice.currentDevice().userInterfaceIdiom == .Pad){
}else if(UIDevice.currentDevice().userInterfaceIdiom == .Phone){
}
Writing a decorator that works with and without parameter is a challenge because Python expects completely different behavior in these two cases! Many answers have tried to work around this and below is an improvement of answer by @norok2. Specifically, this variation eliminates the use of locals()
.
Following the same example as given by @norok2:
import functools
def multiplying(f_py=None, factor=1):
assert callable(f_py) or f_py is None
def _decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return factor * func(*args, **kwargs)
return wrapper
return _decorator(f_py) if callable(f_py) else _decorator
@multiplying
def summing(x): return sum(x)
print(summing(range(10)))
# 45
@multiplying()
def summing(x): return sum(x)
print(summing(range(10)))
# 45
@multiplying(factor=10)
def summing(x): return sum(x)
print(summing(range(10)))
# 450
The catch is that the user must supply key,value pairs of parameters instead of positional parameters and the first parameter is reserved.
Considering the typical top-level class. Only public and no modifier access modifiers may be used at the top level so you'll either see public or you won't see any access modifier at all.
`static`` is used because you may not have a need to create an actual object at the top level (but sometimes you will want to so you may not always see/use static. There are other reasons why you wouldn't include static too but this is the typical one at the top level.)
void
is used because usually you're not going to be returning a value from the top level (class). (sometimes you'll want to return a value other than NULL
so void may not always be used either especially in the case when you have declared, initialized an object at the top level that you are assigning some value to).
Disclaimer: I'm a newbie myself so if this answer is wrong in any way please don't hang me. By day I'm a tech recruiter not a developer; coding is my hobby. Also, I'm always open to constructive criticism and love to learn so please feel free to point out any errors.
As per my understanding data structure is any data residing in memory of any electronic system that can be efficiently managed. Many times it is a game of memory or faster accessibility of data. In terms of memory again, there are tradeoffs done with the management of data based on cost to the company of that end product. Efficiently managed tells us how best the data can be accessed based on the primary requirement of the end product. This is a very high level explanation but data structures is a vast subjects. Most of the interviewers dive into data structures that they can afford to discuss in the interviews depending on the time they have, which are linked lists and related subjects.
Now, these data types can be divided into primitive, abstract, composite, based on the way they are logically constructed and accessed.
I hope this helps you dive in.
I had the same problem: the error was File not found
, while opening HTML
files in chrome, but I resolved it as follows:
BEFORE:
1) I saved a html file abc.html
in a folder name C#
.
2) When I was opening the abc.html
in Google Chrome, it was showing error as "file not found". But it was working fine on Firefox and Internet Explorer.
AFTER:
3) What I did then is, I simply changed the folder name C#
to csharp
without space and re opened it in Chrome. It worked.
4) The moral is: Make sure you don't give any space in a folder name as some browsers don't support it.
For PowerShell 3.0
$PSCommandPath
Contains the full path and file name of the script that is being run.
This variable is valid in all scripts.
The function is then:
function Get-ScriptDirectory {
Split-Path -Parent $PSCommandPath
}
I use __dict__
Example:
class MyObj(object):
def __init__(self):
self.name = 'Chuck Norris'
self.phone = '+6661'
obj = MyObj()
print(obj.__dict__)
# Output:
# {'phone': '+6661', 'name': 'Chuck Norris'}
ddList.Items.FindByText("oldValue").Selected = false;
ddList.Items.FindByText("newValue").Selected = true;
You cannot decrypt this password again but there is another method named "pwdcompare". Here is a example how to use it with SQL syntax:
USE TEMPDB
GO
declare @hash varbinary (255)
CREATE TABLE tempdb..h (id_num int, hash varbinary (255))
SET @hash = pwdencrypt('123') -- encryption
INSERT INTO tempdb..h (id_num,hash) VALUES (1,@hash)
SET @hash = pwdencrypt('123')
INSERT INTO tempdb..h (id_num,hash) VALUES (2,@hash)
SELECT TOP 1 @hash = hash FROM tempdb..h WHERE id_num = 2
SELECT pwdcompare ('123', @hash) AS [Success of check] -- Comparison
SELECT * FROM tempdb..h
INSERT INTO tempdb..h (id_num,hash)
VALUES (3,CONVERT(varbinary (255),
0x01002D60BA07FE612C8DE537DF3BFCFA49CD9968324481C1A8A8FE612C8DE537DF3BFCFA49CD9968324481C1A8A8))
SELECT TOP 1 @hash = hash FROM tempdb..h WHERE id_num = 3
SELECT pwdcompare ('123', @hash) AS [Success of check] -- Comparison
SELECT * FROM tempdb..h
DROP TABLE tempdb..h
GO
For Laravel 5.x / 6.x / 7.x use:
return redirect()->away('https://www.google.com');
as stated in the docs:
Sometimes you may need to redirect to a domain outside of your application. You may do so by calling the away method, which creates a RedirectResponse without any additional URL encoding, validation, or verification:
For anyone who is still running into this issue. I had a similar problem where I could see my device from adb on the command line using adb devices
but Android Studio would not recognize when I had a device attached and would throw either:
Unable to locate adb within SDK
orUnable to obtain result of 'adb version'
I had tried start/stops of adb, uninstalls, of platform-tools, and more. What I found was that inside my C:\Users\<UserName>\AppData\Local\Android
folder I had multiple sdk folders. I performed the following:
platform-tools\
directories within each C:\Users\<UserName>\AppData\Local\Android\sdk*
directoryHope this helps someone someday with their issue.
You may have this issue as well if you have environment variable GCC_ROOT pointing to a wrong location. Probably simplest fix could be (on *nix like system):
unset GCC_ROOT
in more complicated cases you may need to repoint it to proper location
The data received in your serialPort1_DataReceived
method is coming from another thread context than the UI thread, and that's the reason you see this error.
To remedy this, you will have to use a dispatcher as descibed in the MSDN article:
How to: Make Thread-Safe Calls to Windows Forms Controls
So instead of setting the text property directly in the serialport1_DataReceived
method, use this pattern:
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
}
So in your case:
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
txt += serialPort1.ReadExisting().ToString();
SetText(txt.ToString());
}
Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.
To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.
Yes, but it relies on an ES5 feature of JavaScript. This means it will not work in IE8 or older.
var result = objArray.map(function(a) {return a.foo;});
On ES6 compatible JS interpreters you can use an arrow function for brevity:
var result = objArray.map(a => a.foo);
You can use round function
round("10.221",2);
Will return 10.22
If you can't use $timeout due to external resources and cant use a directive due to a specific issue with timing, use broadcast.
Add $scope.$broadcast("variable_name_here");
after the desired external resource or long running controller/directive has completed.
Then add the below after your external resource has loaded.
$scope.$on("variable_name_here", function(){
// DOM manipulation here
jQuery('selector').height();
}
For example in the promise of a deferred HTTP request.
MyHttpService.then(function(data){
$scope.MyHttpReturnedImage = data.image;
$scope.$broadcast("imageLoaded");
});
$scope.$on("imageLoaded", function(){
jQuery('img').height(80).width(80);
}
//This c# method will check for even and odd lengh palindrome string
public static bool IsPalenDrome(string palendromeString)
{
bool isPalenDrome = false;
try
{
int halfLength = palendromeString.Length / 2;
string leftHalfString = palendromeString.Substring(0,halfLength);
char[] reversedArray = palendromeString.ToCharArray();
Array.Reverse(reversedArray);
string reversedString = new string(reversedArray);
string rightHalfStringReversed = reversedString.Substring(0, halfLength);
isPalenDrome = leftHalfString == rightHalfStringReversed ? true : false;
}
catch (Exception ex)
{
throw ex;
}
return isPalenDrome;
}
Surely you just need:
double seconds = milliseconds / 1000.0;
There's no need to manually do the two parts separately - you just need floating point arithmetic, which the use of 1000.0
(as a double
literal) forces. (I'm assuming your milliseconds
value is an integer of some form.)
Note that as usual with double
, you may not be able to represent the result exactly. Consider using BigDecimal
if you want to represent 100ms as 0.1 seconds exactly. (Given that it's a physical quantity, and the 100ms wouldn't be exact in the first place, a double
is probably appropriate, but...)
The first one is invalid syntax. You cannot have object properties inside a plain array. The second one is right although it is not strict JSON. It's a relaxed form of JSON wherein quotes in string keys are omitted.
This tutorial by Patrick Hunlock, may help to learn about JSON and this site may help to validate JSON.
You have to close that application first. There is no way to delete it, if it's used by some application.
UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.
There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.
Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.
I had a special requirement wherein I already had a dataframe but given a certain condition I had to return an empty dataframe so I returned df.limit(0)
instead.
I just ran into this.
If you're not seeing curl in the list (see ibaralf's screenshot), then you may have out-of-date cygwin sources. In one of the screens in cygwin's setup.exe wizard, you have the option to "Install from Internet" or "Install from Local Directory". If you have the "Install from Local Directory" option enabled, then you may not see curl in the list. Switch to "Install from Internet" and select a mirror and then you should see curl.
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
string fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
//OR
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
//etc
}
If you get this error message from the browser:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access
when you're trying to do an Ajax POST/GET request to a remote server which is out of your control, please forget about this simple fix:
<?php header('Access-Control-Allow-Origin: *'); ?>
What you really need to do, especially if you only use JavaScript to do the Ajax request, is an internal proxy who takes your query and send it through to the remote server.
First in your JavaScript, do an Ajax call to your own server, something like:
$.ajax({
url: yourserver.com/controller/proxy.php,
async:false,
type: "POST",
dataType: "json",
data: data,
success: function (result) {
JSON.parse(result);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
Then, create a simple PHP file called proxy.php to wrap your POST data and append them to the remote URL server as a parameters. I give you an example of how I bypass this problem with the Expedia Hotel search API:
if (isset($_POST)) {
$apiKey = $_POST['apiKey'];
$cid = $_POST['cid'];
$minorRev = 99;
$url = 'http://api.ean.com/ean-services/rs/hotel/v3/list?' . 'cid='. $cid . '&' . 'minorRev=' . $minorRev . '&' . 'apiKey=' . $apiKey;
echo json_encode(file_get_contents($url));
}
By doing:
echo json_encode(file_get_contents($url));
You are just doing the same query but on the server side and after that, it should works fine.
I've found none of the suggestions to really work. Here's a more robust one that normalizes spacing when finding classes.
//Inside closure so that the inner functions don't need regeneration on every call.
const getCssClasses = (function () {
function normalize(str) {
if (!str) return '';
str = String(str).replace(/\s*([>~+])\s*/g, ' $1 '); //Normalize symbol spacing.
return str.replace(/(\s+)/g, ' ').trim(); //Normalize whitespace
}
function split(str, on) { //Split, Trim, and remove empty elements
return str.split(on).map(x => x.trim()).filter(x => x);
}
function containsAny(selText, ors) {
return selText ? ors.some(x => selText.indexOf(x) >= 0) : false;
}
return function (selector) {
const logicalORs = split(normalize(selector), ',');
const sheets = Array.from(window.document.styleSheets);
const ruleArrays = sheets.map((x) => Array.from(x.rules || x.cssRules || []));
const allRules = ruleArrays.reduce((all, x) => all.concat(x), []);
return allRules.filter((x) => containsAny(normalize(x.selectorText), logicalORs));
};
})();
Here's it in action from the Chrome console.
I believe Mica's way deserves the rank of answer, since is not visible enough as a comment:
\begin{tikzpicture}[font=\small]
These are the installation i had to run in order to make it work on fedora 22 :-
glibc-2.21-7.fc22.i686
alsa-lib-1.0.29-1.fc22.i686
qt3-3.3.8b-64.fc22.i686
libusb-1:0.1.5-5.fc22.i686
The core of the answer lies on finding the next element:
function findNextTabStop(el) {
var universe = document.querySelectorAll('input, button, select, textarea, a[href]');
var list = Array.prototype.filter.call(universe, function(item) {return item.tabIndex >= "0"});
var index = list.indexOf(el);
return list[index + 1] || list[0];
}
Usage:
var nextEl = findNextTabStop(element);
nextEl.focus();
Notice I don't care about prioritizing tabIndex
.
A quicker workaround is to use .asfreq()
. This doesn't require creation of a new index to call within .reindex()
.
# "broken" (staggered) dates
dates = pd.Index([pd.Timestamp('2012-05-01'),
pd.Timestamp('2012-05-04'),
pd.Timestamp('2012-05-06')])
s = pd.Series([1, 2, 3], dates)
print(s.asfreq('D'))
2012-05-01 1.0
2012-05-02 NaN
2012-05-03 NaN
2012-05-04 2.0
2012-05-05 NaN
2012-05-06 3.0
Freq: D, dtype: float64
for me that issue happened because i generated .jks file on my laptop with 1.8.0_251 and i copied it on server witch had java 1.8.0_45 and when I used that .jks file in my code i got java.io.IOException: Invalid Keystore format.
to solve this issue i generated .jks file directly on the server instead of copy there from my laptop which had different java version.
You can also use:
sdiff file1 file2
To display differences side by side within your terminal!
You're correct, in that example the throws
is superfluous. It's possible that it was left there from some previous implementation - perhaps the exception was originally thrown instead of caught in the catch block.
Add this code in your view controller
UIView *myView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 300, 30)];
UIBarButtonItem *btnL = [[UIBarButtonItem alloc]initWithCustomView:myView];
self.navigationItem.leftBarButtonItem = btnL;
Be aware of number of digits in epoch time. Usually they are ten (1534936923) ,then use:
=(A1 / 86400) + 25569
For thirteen digits (1534936923000) of epoch time adjust the formula:
=(LEFT(A1,LEN(A1)-3) / 86400) + 25569
to avoid
###################################
Dates or times that are negative or too large display as ######
See more on https://www.epochconverter.com/
Go to Project> Properties> C/C++ Build> Environment. You will see three fields, choose PATH. See if the folder containing make.exe is appended to the path or not. Sometimes the change to the System PATH variable (made from My Computer> Properties> Advanced System Settings...) is NOT reflected in Eclipse. This solved the problem for me, hope it helps you too!
You can annotate the specific property in your POJO with @JsonIgnore.
When your activity is recreated after it was previously destroyed, you can recover your saved state from the Bundle that the system passes your activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.
Because the onCreate() method is called whether the system is creating a new instance of your activity or recreating a previous one, you must check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed.
static final String STATE_USER = "user";
private String mUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mUser = savedInstanceState.getString(STATE_USER);
} else {
// Probably initialize members with default values for a new instance
mUser = "NewUser";
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(STATE_USER, mUser);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
I had the same issue when trying to install a package for Node.js. After some extensive googeling I found this walktrough: https://github.com/TooTallNate/node-gyp/wiki/Visual-Studio-2010-Setup
When I had followed these steps I could use "npm install" without any issues.
To return the whole table at once you could change the SELECT to:
SELECT ...
BULK COLLECT INTO T
FROM ...
This is only advisable for results that aren't excessively large, since they all have to be accumulated in memory before being returned; otherwise consider the pipelined function as suggested by Charles, or returning a REF CURSOR.
The currently accepted answer is incorrect. It is NOT required to set maxBufferSize
and maxReceivedMessageSize
on the client and the server binding. It depends!
If your request is too large (i.e., method parameters of the service operation are memory intensive) set the properties on the server-side, if the response is too large (i.e., the method return value of the service operation is memory intensive) set the values on the client-side.
For the difference between maxBufferSize
and maxReceivedMessageSize
see MaxBufferSize property?.
You can just validate your pipeline to find out syntax issues. Jenkis has nice API for Jenkisfile validation - https://jenkins_url/pipeline-model-converter/validate
Using curl and passing your .Jenkinsfile, you will get syntax check instantly
curl --user username:password -X POST -F "jenkinsfile=<jenkinsfile" https://jenkins_url/pipeline-model-converter/validate
You can add this workflow to editors:
uint32_t
is standard, uint32
is not. That is, if you include <inttypes.h>
or <stdint.h>
, you will get a definition of uint32_t
. uint32
is a typedef in some local code base, but you should not expect it to exist unless you define it yourself. And defining it yourself is a bad idea.
Typically, your help output should include:
[options]
to indicate where the options goarg_name
for a required, singular arg[arg_name]
for an optional, singular argarg_name...
for a required arg of which there can be many (this is rare)[arg_name...]
for an arg for which any number can be suppliedarg_name
should be a descriptive, short name, in lower, snake case-l
) or a long form (e.g. --list
), include them together on the same line, as their descriptions will be the sameGREP_OPTS
Note further that it's good form to accept both -h
and --help
to trigger this message and that you should show this message if the user messes up the command-line syntax, e.g. omits a required argument.
You need to use the TO_DATE
function.
SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;
Use this
DELETE FROM `articles`, `comments`
USING `articles`,`comments`
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4
or
DELETE `articles`, `comments`
FROM `articles`, `comments`
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4
cat filename | sort | uniq -c | awk -F" " '$1<2 {print $2}'
Deletes the duplicate lines using awk.
There is a quick method to set the syntax:
Ctrl
+Shift
+P
,then type in the input box
ss + (which type you want set)
eg: ss html +Enter
and ss means "set syntax"
it is really quicker than check in the menu's checkbox.
You can do this by AWS S3 Cognito try this link here :
http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/browser-examples.html#Amazon_S3
Also try this code
Just change Region, IdentityPoolId and Your bucket name
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>AWS S3 File Upload</title>_x000D_
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.12.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<input type="file" id="file-chooser" />_x000D_
<button id="upload-button">Upload to S3</button>_x000D_
<div id="results"></div>_x000D_
<script type="text/javascript">_x000D_
AWS.config.region = 'your-region'; // 1. Enter your region_x000D_
_x000D_
AWS.config.credentials = new AWS.CognitoIdentityCredentials({_x000D_
IdentityPoolId: 'your-IdentityPoolId' // 2. Enter your identity pool_x000D_
});_x000D_
_x000D_
AWS.config.credentials.get(function(err) {_x000D_
if (err) alert(err);_x000D_
console.log(AWS.config.credentials);_x000D_
});_x000D_
_x000D_
var bucketName = 'your-bucket'; // Enter your bucket name_x000D_
var bucket = new AWS.S3({_x000D_
params: {_x000D_
Bucket: bucketName_x000D_
}_x000D_
});_x000D_
_x000D_
var fileChooser = document.getElementById('file-chooser');_x000D_
var button = document.getElementById('upload-button');_x000D_
var results = document.getElementById('results');_x000D_
button.addEventListener('click', function() {_x000D_
_x000D_
var file = fileChooser.files[0];_x000D_
_x000D_
if (file) {_x000D_
_x000D_
results.innerHTML = '';_x000D_
var objKey = 'testing/' + file.name;_x000D_
var params = {_x000D_
Key: objKey,_x000D_
ContentType: file.type,_x000D_
Body: file,_x000D_
ACL: 'public-read'_x000D_
};_x000D_
_x000D_
bucket.putObject(params, function(err, data) {_x000D_
if (err) {_x000D_
results.innerHTML = 'ERROR: ' + err;_x000D_
} else {_x000D_
listObjs();_x000D_
}_x000D_
});_x000D_
} else {_x000D_
results.innerHTML = 'Nothing to upload.';_x000D_
}_x000D_
}, false);_x000D_
function listObjs() {_x000D_
var prefix = 'testing';_x000D_
bucket.listObjects({_x000D_
Prefix: prefix_x000D_
}, function(err, data) {_x000D_
if (err) {_x000D_
results.innerHTML = 'ERROR: ' + err;_x000D_
} else {_x000D_
var objKeys = "";_x000D_
data.Contents.forEach(function(obj) {_x000D_
objKeys += obj.Key + "<br>";_x000D_
});_x000D_
results.innerHTML = objKeys;_x000D_
}_x000D_
});_x000D_
}_x000D_
</script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
In swift 3, you can use this
var enumValue = Customer.Physics
var str = String(describing: enumValue)
ThreadPoolExecutor
also has beforeExecute
and afterExecute
hook methods that you can override and make use of. Here is the description from ThreadPoolExecutor
's Javadocs.
Hook methods
This class provides protected overridable
beforeExecute(java.lang.Thread, java.lang.Runnable)
andafterExecute(java.lang.Runnable, java.lang.Throwable)
methods that are called before and after execution of each task. These can be used to manipulate the execution environment; for example, reinitializingThreadLocals
, gathering statistics, or adding log entries. Additionally, methodterminated()
can be overridden to perform any special processing that needs to be done once theExecutor
has fully terminated. If hook or callback methods throw exceptions, internal worker threads may in turn fail and abruptly terminate.
Use config something like this:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>user-webservice</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
and then you'll need three files:
The *-servlet.xml
files are used automatically and each creates an application context for that servlet.
From the Spring documentation, 13.2. The DispatcherServlet:
The framework will, on initialization of a
DispatcherServlet
, look for a file named [servlet-name]-servlet.xml in theWEB-INF
directory of your web application and create the beans defined there (overriding the definitions of any beans defined with the same name in the global scope).
If you want to update it later, once "this" no longer references it, I had some luck with assigning a variable to point to the main form.
static Form f0;
public OrdUpdate()
{
InitializeComponent();
f0=this;
}
// then later you can say
f0.Text="New text";
What is the current approach to make a custom AuthorizeAttribute
Easy: don't create your own AuthorizeAttribute
.
For pure authorization scenarios (like restricting access to specific users only), the recommended approach is to use the new authorization block: https://github.com/aspnet/MusicStore/blob/1c0aeb08bb1ebd846726232226279bbe001782e1/samples/MusicStore/Startup.cs#L84-L92
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AuthorizationOptions>(options =>
{
options.AddPolicy("ManageStore", policy => policy.RequireClaim("Action", "ManageStore"));
});
}
}
public class StoreController : Controller
{
[Authorize(Policy = "ManageStore"), HttpGet]
public async Task<IActionResult> Manage() { ... }
}
For authentication, it's best handled at the middleware level.
What are you trying to achieve exactly?
Well, the only thing I can make it work is like so:
servers: >
dev.example.com,
another.example.com
@Value("${servers}")
private String[] array;
And dont forget the @Configuration above your class....
Without the "," separation, no such luck...
Works too (boot 1.5.8 versie)
servers:
dev.example.com,
another.example.com
when we run application in eclipse apk generate is sign by default Keystore which is provided by android .
But if you want to upload your application on play store you need to create your own keystore. Eclipse already provides GUI interface to create new keystore. And you also can create keystore through command line.
default alias is
androiddebugkey
Consider:
int[] myArray = new int[10];
String myString = "hello world!";
List<int> myList = new ArrayList<int>();
myArray.length // Gives the length of the array
myString.length() // Gives the length of the string
myList.size() // Gives the length of the list
It's very likely that strings and arrays were designed at different times and hence ended up using different conventions. One justification is that since Strings use arrays internally, a method, length()
, was used to avoid duplication of the same information. Another is that using a method length()
helps emphasize the immutability of strings, even though the size of an array is also unchangeable.
Ultimately this is just an inconsistency that evolved that would definitely be fixed if the language were ever redesigned from the ground up. As far as I know no other languages (C#, Python, Scala, etc.) do the same thing, so this is likely just a slight flaw that ended up as part of the language.
You'll get an error if you use the wrong one anyway.
Why not use a generator instead?
private IEnumerable<string> ReadLogLines(string logPath) {
using(StreamReader reader = File.OpenText(logPath)) {
string line = "";
while((line = reader.ReadLine()) != null) {
yield return line;
}
}
}
Then you can use it like you would use the list:
var logFile = ReadLogLines(LOG_PATH);
foreach(var s in logFile) {
// Do whatever you need
}
Of course, if you need to have a List<string>
, then you will need to keep the entire file contents in memory. There's really no way around that.
Use an HTML line break (<br />
) to force a line break within a table cell:
|Something|Something else<br />that's rather long|Something else|
Hi you can use icon as SVG and set colors. See this code
/*_x000D_
* declare map and places as a global variable_x000D_
*/_x000D_
var map;_x000D_
var places = [_x000D_
['Place 1', "<h1>Title 1</h1>", -0.690542, -76.174856,"red"],_x000D_
['Place 2', "<h1>Title 2</h1>", -5.028249, -57.659052,"blue"],_x000D_
['Place 3', "<h1>Title 3</h1>", -0.028249, -77.757507,"green"],_x000D_
['Place 4', "<h1>Title 4</h1>", -0.800101286, -76.78747820,"orange"],_x000D_
['Place 5', "<h1>Title 5</h1>", -0.950198, -78.959302,"#FF33AA"]_x000D_
];_x000D_
/*_x000D_
* use google maps api built-in mechanism to attach dom events_x000D_
*/_x000D_
google.maps.event.addDomListener(window, "load", function () {_x000D_
_x000D_
/*_x000D_
* create map_x000D_
*/_x000D_
var map = new google.maps.Map(document.getElementById("map_div"), {_x000D_
mapTypeId: google.maps.MapTypeId.ROADMAP,_x000D_
});_x000D_
_x000D_
/*_x000D_
* create infowindow (which will be used by markers)_x000D_
*/_x000D_
var infoWindow = new google.maps.InfoWindow();_x000D_
/*_x000D_
* create bounds (which will be used auto zoom map)_x000D_
*/_x000D_
var bounds = new google.maps.LatLngBounds();_x000D_
_x000D_
/*_x000D_
* marker creater function (acts as a closure for html parameter)_x000D_
*/_x000D_
function createMarker(options, html) {_x000D_
var marker = new google.maps.Marker(options);_x000D_
bounds.extend(options.position);_x000D_
if (html) {_x000D_
google.maps.event.addListener(marker, "click", function () {_x000D_
infoWindow.setContent(html);_x000D_
infoWindow.open(options.map, this);_x000D_
map.setZoom(map.getZoom() + 1)_x000D_
map.setCenter(marker.getPosition());_x000D_
});_x000D_
}_x000D_
return marker;_x000D_
}_x000D_
_x000D_
/*_x000D_
* add markers to map_x000D_
*/_x000D_
for (var i = 0; i < places.length; i++) {_x000D_
var point = places[i];_x000D_
createMarker({_x000D_
position: new google.maps.LatLng(point[2], point[3]),_x000D_
map: map,_x000D_
icon: {_x000D_
path: "M27.648 -41.399q0 -3.816 -2.7 -6.516t-6.516 -2.7 -6.516 2.7 -2.7 6.516 2.7 6.516 6.516 2.7 6.516 -2.7 2.7 -6.516zm9.216 0q0 3.924 -1.188 6.444l-13.104 27.864q-0.576 1.188 -1.71 1.872t-2.43 0.684 -2.43 -0.684 -1.674 -1.872l-13.14 -27.864q-1.188 -2.52 -1.188 -6.444 0 -7.632 5.4 -13.032t13.032 -5.4 13.032 5.4 5.4 13.032z",_x000D_
scale: 0.6,_x000D_
strokeWeight: 0.2,_x000D_
strokeColor: 'black',_x000D_
strokeOpacity: 1,_x000D_
fillColor: point[4],_x000D_
fillOpacity: 0.85,_x000D_
},_x000D_
}, point[1]);_x000D_
};_x000D_
map.fitBounds(bounds);_x000D_
});
_x000D_
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3"></script>_x000D_
<div id="map_div" style="height: 400px;"></div>
_x000D_
Depending on what document type you want you can use XmlDocument.LoadXml
or XDocument.Load
.
Something like:
>>> bytes.fromhex('4a4b4c').decode('utf-8')
'JKL'
Just put the actual encoding you are using.
Python 3.3 and later now uses the 2010 compiler. To best way to solve the issue is to just install Visual C++ Express 2010 for free.
Now comes the harder part for 64 bit users and to be honest I just moved to 32 bit but 2010 express doesn't come with a 64 bit compiler (you get a new error, ValueError: ['path'] ) so you have to install Microsoft SDK 7.1 and follow the directions here to get the 64 bit compiler working with python: Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7
It may just be easier for you to use the 32 bit version for now. In addition to getting the compiler working, you can bypass the need to compile many modules by getting the binary wheel file from this locaiton http://www.lfd.uci.edu/~gohlke/pythonlibs/
Just download the .whl file you need, shift + right click the download folder and select "open command window here" and run
pip install module-name.whl
I used that method on 64 bit 3.4.3 before I broke down and decided to just get a working compiler for pip compiles modules from source by default, which is why the binary wheel files work and having pip build from source doesn't.
People getting this (vcvarsall.bat) error on Python 2.7 can instead install "Microsoft Visual C++ Compiler for Python 2.7"
If you want some flexibility, create a class that watches the size of the list.
Here's a simple example. You would need to override all the methods that change the state of the list.
public class LimitedArrayList<T> extends ArrayList<T>{
private int limit;
public LimitedArrayList(int limit){
this.limit = limit;
}
@Override
public void add(T item){
if (this.size() > limit)
throw new ListTooLargeException();
super.add(item);
}
// ... similarly for other methods that may add new elements ...
Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:
sudo apt-get install bison flex
There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.
Note that Date.getDate
only returns the day of the month. You can add a day by calling Date.setDate
and appending 1.
// Create new Date instance
var date = new Date()
// Add a day
date.setDate(date.getDate() + 1)
JavaScript will automatically update the month and year for you.
EDIT:
Here's a link to a page where you can find all the cool stuff about the built-in Date object, and see what's possible: Date.
How about calling a function from within your callback instead of returning a value in sync_call()?
function sync_call(input) {
var value;
// Assume the async call always succeed
async_call(input, function(result) {
value = result;
use_value(value);
} );
}
If you want to have a simple Line in your Layout to separate two views you can use a generic View with the height and width you want the line to have and a set background color.
With this approach you don't need to override a View or use a Canvas yourself just simple and clean add the line in xml.
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@android:color/black" />
The example code I provided will generate a line that fills the screen in width and has a height of one dp.
If you have problems with the drawing of the line on small screens consider to change the height of the line to px. The problem is that on a ldpi screen the line will be 0.75 pixel high. Sometimes this may result in a rounding that makes the line vanish. If this is a problem for your layout define the width of the line a ressource file and create a separate ressource file for small screens that sets the value to 1px instead of 1dp.
This approach is only usable if you want horizontal or vertical lines that are used to divide layout elements. If you want to achieve something like a cross that is drawn into an image my approach will not work.
To return the queryset you retrieved with queryset = Users.objects.all(),
you first need to serialize them.
Serialization is the process of converting one data structure to another. Using Class-Based Views, you could return JSON like this.
from django.core.serializers import serialize
from django.http import JsonResponse
from django.views.generic import View
class JSONListView(View):
def get(self, request, *args, **kwargs):
qs = User.objects.all()
data = serialize("json", qs)
return JsonResponse(data)
This will output a list of JSON. For more detail on how this works, check out my blog article How to return a JSON Response with Django. It goes into more detail on how you would go about this.
MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);
SUBSTITUTE()
in a string can be nasty, however, it's always possible to arrange it: I started off using the community wiki answer, but realised that it wasn't detecting alt-tab events in Chrome. This is because it uses the first available event source, and in this case it's the page visibility API, which in Chrome seems to not track alt-tabbing.
I decided to modify the script a bit to keep track of all possible events for page focus changes. Here's a function you can drop in:
function onVisibilityChange(callback) {
var visible = true;
if (!callback) {
throw new Error('no callback given');
}
function focused() {
if (!visible) {
callback(visible = true);
}
}
function unfocused() {
if (visible) {
callback(visible = false);
}
}
// Standards:
if ('hidden' in document) {
document.addEventListener('visibilitychange',
function() {(document.hidden ? unfocused : focused)()});
}
if ('mozHidden' in document) {
document.addEventListener('mozvisibilitychange',
function() {(document.mozHidden ? unfocused : focused)()});
}
if ('webkitHidden' in document) {
document.addEventListener('webkitvisibilitychange',
function() {(document.webkitHidden ? unfocused : focused)()});
}
if ('msHidden' in document) {
document.addEventListener('msvisibilitychange',
function() {(document.msHidden ? unfocused : focused)()});
}
// IE 9 and lower:
if ('onfocusin' in document) {
document.onfocusin = focused;
document.onfocusout = unfocused;
}
// All others:
window.onpageshow = window.onfocus = focused;
window.onpagehide = window.onblur = unfocused;
};
Use it like this:
onVisibilityChange(function(visible) {
console.log('the page is now', visible ? 'focused' : 'unfocused');
});
This version listens for all the different visibility events and fires a callback if any of them causes a change. The focused
and unfocused
handlers make sure that the callback isn't called multiple times if multiple APIs catch the same visibility change.
maybe your script tab has some problem.
if you set type, must type="application/javascript".
<!DOCTYPE html>
<html>
<head>
<title>
Hello
</title>
</head>
<body>
<div onclick="showMsg('Hello')">
Click me show message
</div>
<script type="application/javascript">
function showMsg(item) {
alert(item);
}
</script>
</body>
</html>
I have a use case where I have to iterate through the dict to get the key, value pair, also the index indicating where I am. This is how I do it:
d = {'x': 1, 'y': 2, 'z': 3}
for i, (key, value) in enumerate(d.items()):
print(i, key, value)
Note that the parentheses around the key, value are important, without them, you'd get an ValueError
"not enough values to unpack".
I know I'm late to the party, but to specifically answer the two questions:
"I just want to disable specific clicky-things so that:
How hard can this be?"
They stop clicking
1. For buttons like <button>
or <input type="button">
you add the attribute: disabled
.
<button type="submit" disabled>Register</button>
<input type="button" value="Register" disabled>
2. For links, ANY link... actually, any HTML element, you can use CSS3 pointer events.
.selector { pointer-events:none; }
Browser support for pointer events is awesome by today's state of the art (5/12/14). But we usually have to support legacy browsers in the IE realm, so IE10 and below DO NOT support pointer events: http://caniuse.com/pointer-events. So using one of the JavaScript solutions mentioned by others here may be the way to go for legacy browsers.
More info about pointer events:
They look disabled
Obviously this a CSS answer, so:
1. For buttons like <button>
or <input type="button">
use the [attribute]
selector:
button[disabled] { ... }
input[type=button][disabled] { ... }
--
Here's a basic demo with the stuff I mentioned here: http://jsfiddle.net/bXm5B/4/
Hope this helps.
If you are using Bootstrap, look at padding
of your td
s.
The following creates a generic function, taking an array of any size and of any type by reference:
template<typename T, std::size_t S>
void my_func(T (&arr)[S]) {
// do stuff
}
You didn't do what you're being asked to do.
What is asked:
I have to execute ../gradlew build
What you do
cd ..
gradlew build
That's not the same thing.
The first one will use the gradlew command found in the ..
directory (mdeinum...
), and look for the build file to execute in the current directory, which is (for example) chapter1-bookstore
.
The second one will execute the gradlew command found in the current directory (mdeinum...
), and look for the build file to execute in the current directory, which is mdeinum...
.
So the build file executed is not the same.
Here is a very simple and easy to follow example.
private int CalculateAge()
{
//get birthdate
DateTime dtBirth = Convert.ToDateTime(BirthDatePicker.Value);
int byear = dtBirth.Year;
int bmonth = dtBirth.Month;
int bday = dtBirth.Day;
DateTime dtToday = DateTime.Now;
int tYear = dtToday.Year;
int tmonth = dtToday.Month;
int tday = dtToday.Day;
int age = tYear - byear;
if (bmonth < tmonth)
age--;
else if (bmonth == tmonth && bday>tday)
{
age--;
}
return age;
}
I ended up using Jsch- it was pretty straightforward, and seemed to scale up pretty well (I was grabbing a few thousand files every few minutes).
Just in case you want to see all of the gory details in human readable form, you can use:
import platform;
print(platform.sys.version);
Output for my system:
3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
[GCC 7.2.0]
Something very detailed but machine parsable would be to get the version_info
object from platform.sys
, instead, and then use its properties to take a predetermined course of action. For example:
import platform;
print(platform.sys.version_info)
Output on my system:
sys.version_info(major=3, minor=6, micro=5, releaselevel='final', serial=0)
Followed by @Andy's answer, you can do following to solve your second question:
In [56]: df.groupby(['col5','col2']).size().reset_index().groupby('col2')[[0]].max()
Out[56]:
0
col2
A 3
B 2
C 1
D 3
For MACOS users
if you see credentials failed but you are sure that is is working previously then:
probably you made a software update to the system. System uses git bundled with xcode. its better to open Xcode and click install extra components on startup of xcode. it will say installing components. when you accept the license agreement if will start working again.
in short:
open Xcode, install additional ompoenents. accept user licence agreement
Password Strength Algorithm:
Password Length:
5 Points: Less than 4 characters
10 Points: 5 to 7 characters
25 Points: 8 or more
Letters:
0 Points: No letters
10 Points: Letters are all lower case
20 Points: Letters are upper case and lower case
Numbers:
0 Points: No numbers
10 Points: 1 number
20 Points: 3 or more numbers
Characters:
0 Points: No characters
10 Points: 1 character
25 Points: More than 1 character
Bonus:
2 Points: Letters and numbers
3 Points: Letters, numbers, and characters
5 Points: Mixed case letters, numbers, and characters
Password Text Range:
>= 90: Very Secure
>= 80: Secure
>= 70: Very Strong
>= 60: Strong
>= 50: Average
>= 25: Weak
>= 0: Very Weak
Settings Toggle to true or false, if you want to change what is checked in the password
var m_strUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var m_strLowerCase = "abcdefghijklmnopqrstuvwxyz";
var m_strNumber = "0123456789";
var m_strCharacters = "!@#$%^&*?_~"
Check password
function checkPassword(strPassword)
{
// Reset combination count
var nScore = 0;
// Password length
// -- Less than 4 characters
if (strPassword.length < 5)
{
nScore += 5;
}
// -- 5 to 7 characters
else if (strPassword.length > 4 && strPassword.length < 8)
{
nScore += 10;
}
// -- 8 or more
else if (strPassword.length > 7)
{
nScore += 25;
}
// Letters
var nUpperCount = countContain(strPassword, m_strUpperCase);
var nLowerCount = countContain(strPassword, m_strLowerCase);
var nLowerUpperCount = nUpperCount + nLowerCount;
// -- Letters are all lower case
if (nUpperCount == 0 && nLowerCount != 0)
{
nScore += 10;
}
// -- Letters are upper case and lower case
else if (nUpperCount != 0 && nLowerCount != 0)
{
nScore += 20;
}
// Numbers
var nNumberCount = countContain(strPassword, m_strNumber);
// -- 1 number
if (nNumberCount == 1)
{
nScore += 10;
}
// -- 3 or more numbers
if (nNumberCount >= 3)
{
nScore += 20;
}
// Characters
var nCharacterCount = countContain(strPassword, m_strCharacters);
// -- 1 character
if (nCharacterCount == 1)
{
nScore += 10;
}
// -- More than 1 character
if (nCharacterCount > 1)
{
nScore += 25;
}
// Bonus
// -- Letters and numbers
if (nNumberCount != 0 && nLowerUpperCount != 0)
{
nScore += 2;
}
// -- Letters, numbers, and characters
if (nNumberCount != 0 && nLowerUpperCount != 0 && nCharacterCount != 0)
{
nScore += 3;
}
// -- Mixed case letters, numbers, and characters
if (nNumberCount != 0 && nUpperCount != 0 && nLowerCount != 0 && nCharacterCount != 0)
{
nScore += 5;
}
return nScore;
}
// Runs password through check and then updates GUI
function runPassword(strPassword, strFieldID)
{
// Check password
var nScore = checkPassword(strPassword);
// Get controls
var ctlBar = document.getElementById(strFieldID + "_bar");
var ctlText = document.getElementById(strFieldID + "_text");
if (!ctlBar || !ctlText)
return;
// Set new width
ctlBar.style.width = (nScore*1.25>100)?100:nScore*1.25 + "%";
// Color and text
// -- Very Secure
/*if (nScore >= 90)
{
var strText = "Very Secure";
var strColor = "#0ca908";
}
// -- Secure
else if (nScore >= 80)
{
var strText = "Secure";
vstrColor = "#7ff67c";
}
// -- Very Strong
else
*/
if (nScore >= 80)
{
var strText = "Very Strong";
var strColor = "#008000";
}
// -- Strong
else if (nScore >= 60)
{
var strText = "Strong";
var strColor = "#006000";
}
// -- Average
else if (nScore >= 40)
{
var strText = "Average";
var strColor = "#e3cb00";
}
// -- Weak
else if (nScore >= 20)
{
var strText = "Weak";
var strColor = "#Fe3d1a";
}
// -- Very Weak
else
{
var strText = "Very Weak";
var strColor = "#e71a1a";
}
if(strPassword.length == 0)
{
ctlBar.style.backgroundColor = "";
ctlText.innerHTML = "";
}
else
{
ctlBar.style.backgroundColor = strColor;
ctlText.innerHTML = strText;
}
}
// Checks a string for a list of characters
function countContain(strPassword, strCheck)
{
// Declare variables
var nCount = 0;
for (i = 0; i < strPassword.length; i++)
{
if (strCheck.indexOf(strPassword.charAt(i)) > -1)
{
nCount++;
}
}
return nCount;
}
You can customize by yourself according to your requirement.
I built a custom class that extends TextView
and solves this problem... Check out my answer here =)
As @MeBigFatGuy says, except you can make your static {...}
block use a loop over the values()
collection:
static {
for (PcapLinkType type : PcapLinkType.values()) {
intToTypeMap.put(type.getValue(), type);
}
}
My solution is a class to sort listView items when you click on column header.
You can specify the type of each column.
listView.ListViewItemSorter = new ListViewColumnSorter();
listView.ListViewItemSorter.ColumnsTypeComparer.Add(0, DateTime);
listView.ListViewItemSorter.ColumnsTypeComparer.Add(1, int);
That's it !
The C# class :
using System.Collections;
using System.Collections.Generic;
using EDV;
namespace System.Windows.Forms
{
/// <summary>
/// Cette classe est une implémentation de l'interface 'IComparer' pour le tri des items de ListView. Adapté de http://support.microsoft.com/kb/319401.
/// </summary>
/// <remarks>Intégré par EDVariables.</remarks>
public class ListViewColumnSorter : IComparer
{
/// <summary>
/// Spécifie la colonne à trier
/// </summary>
private int ColumnToSort;
/// <summary>
/// Spécifie l'ordre de tri (en d'autres termes 'Croissant').
/// </summary>
private SortOrder OrderOfSort;
/// <summary>
/// Objet de comparaison ne respectant pas les majuscules et minuscules
/// </summary>
private CaseInsensitiveComparer ObjectCompare;
/// <summary>
/// Constructeur de classe. Initialise la colonne sur '0' et aucun tri
/// </summary>
public ListViewColumnSorter()
: this(0, SortOrder.None) { }
/// <summary>
/// Constructeur de classe. Initializes various elements
/// <param name="columnToSort">Spécifie la colonne à trier</param>
/// <param name="orderOfSort">Spécifie l'ordre de tri</param>
/// </summary>
public ListViewColumnSorter(int columnToSort, SortOrder orderOfSort)
{
// Initialise la colonne
ColumnToSort = columnToSort;
// Initialise l'ordre de tri
OrderOfSort = orderOfSort;
// Initialise l'objet CaseInsensitiveComparer
ObjectCompare = new CaseInsensitiveComparer();
// Dictionnaire de comparateurs
ColumnsComparer = new Dictionary<int, IComparer>();
ColumnsTypeComparer = new Dictionary<int, Type>();
}
/// <summary>
/// Cette méthode est héritée de l'interface IComparer. Il compare les deux objets passés en effectuant une comparaison
///qui ne tient pas compte des majuscules et des minuscules.
/// <br/>Si le comparateur n'existe pas dans ColumnsComparer, CaseInsensitiveComparer est utilisé.
/// </summary>
/// <param name="x">Premier objet à comparer</param>
/// <param name="x">Deuxième objet à comparer</param>
/// <returns>Le résultat de la comparaison. "0" si équivalent, négatif si 'x' est inférieur à 'y'
///et positif si 'x' est supérieur à 'y'</returns>
public int Compare(object x, object y)
{
int compareResult;
ListViewItem listviewX, listviewY;
// Envoit les objets à comparer aux objets ListViewItem
listviewX = (ListViewItem)x;
listviewY = (ListViewItem)y;
if (listviewX.SubItems.Count < ColumnToSort + 1 || listviewY.SubItems.Count < ColumnToSort + 1)
return 0;
IComparer objectComparer = null;
Type comparableType = null;
if (ColumnsComparer == null || !ColumnsComparer.TryGetValue(ColumnToSort, out objectComparer))
if (ColumnsTypeComparer == null || !ColumnsTypeComparer.TryGetValue(ColumnToSort, out comparableType))
objectComparer = ObjectCompare;
// Compare les deux éléments
if (comparableType != null) {
//Conversion du type
object valueX = listviewX.SubItems[ColumnToSort].Text;
object valueY = listviewY.SubItems[ColumnToSort].Text;
if (!edvTools.TryParse(ref valueX, comparableType) || !edvTools.TryParse(ref valueY, comparableType))
return 0;
compareResult = (valueX as IComparable).CompareTo(valueY);
}
else
compareResult = objectComparer.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);
// Calcule la valeur correcte d'après la comparaison d'objets
if (OrderOfSort == SortOrder.Ascending) {
// Le tri croissant est sélectionné, renvoie des résultats normaux de comparaison
return compareResult;
}
else if (OrderOfSort == SortOrder.Descending) {
// Le tri décroissant est sélectionné, renvoie des résultats négatifs de comparaison
return (-compareResult);
}
else {
// Renvoie '0' pour indiquer qu'ils sont égaux
return 0;
}
}
/// <summary>
/// Obtient ou définit le numéro de la colonne à laquelle appliquer l'opération de tri (par défaut sur '0').
/// </summary>
public int SortColumn
{
set
{
ColumnToSort = value;
}
get
{
return ColumnToSort;
}
}
/// <summary>
/// Obtient ou définit l'ordre de tri à appliquer (par exemple, 'croissant' ou 'décroissant').
/// </summary>
public SortOrder Order
{
set
{
OrderOfSort = value;
}
get
{
return OrderOfSort;
}
}
/// <summary>
/// Dictionnaire de comparateurs par colonne.
/// <br/>Pendant le tri, si le comparateur n'existe pas dans ColumnsComparer, CaseInsensitiveComparer est utilisé.
/// </summary>
public Dictionary<int, IComparer> ColumnsComparer { get; set; }
/// <summary>
/// Dictionnaire de comparateurs par colonne.
/// <br/>Pendant le tri, si le comparateur n'existe pas dans ColumnsTypeComparer, CaseInsensitiveComparer est utilisé.
/// </summary>
public Dictionary<int, Type> ColumnsTypeComparer { get; set; }
}
}
Initializing a ListView :
<var>Visual.WIN.ctrlListView.OnShown</var> :
eventSender.Columns.Clear();
eventSender.SmallImageList = edvWinForm.ImageList16;
eventSender.ListViewItemSorter = new ListViewColumnSorter();
var col = eventSender.Columns.Add("Répertoire");
col.Width = 160;
col.ImageKey = "Domain";
col = eventSender.Columns.Add("Fichier");
col.Width = 180;
col.ImageKey = "File";
col = eventSender.Columns.Add("Date");
col.Width = 120;
col.ImageKey = "DateTime";
eventSender.ListViewItemSorter.ColumnsTypeComparer.Add(col.Index, DateTime);
col = eventSender.Columns.Add("Position");
col.TextAlign = HorizontalAlignment.Right;
col.Width = 80;
col.ImageKey = "Num";
eventSender.ListViewItemSorter.ColumnsTypeComparer.Add(col.Index, Int32);
Fill a ListView :
<var>Visual.WIN.cmdSearch.OnClick</var> :
//non récursif et sans fonction
..ctrlListView:Items.Clear();
..ctrlListView:Sorting = SortOrder.None;
var group = ..ctrlListView:Groups.Add(DateTime.Now.ToString()
, Path.Combine(..cboDir:Text, ..ctrlPattern1:Text) + " contenant " + ..ctrlSearch1:Text);
var perf = Environment.TickCount;
var files = new DirectoryInfo(..cboDir:Text).GetFiles(..ctrlPattern1:Text)
var search = ..ctrlSearch1:Text;
var ignoreCase = ..Search.IgnoreCase;
//var result = new StringBuilder();
var dirLength : int = ..cboDir:Text.Length;
var position : int;
var added : int = 0;
for(var i : int = 0; i < files.Length; i++){
var file = files[i];
if(search == ""
|| (position = File.ReadAllText(file.FullName).IndexOf(String(search)
, StringComparison(ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture))) > =0) {
// result.AppendLine(file.FullName.Substring(dirLength) + "\tPos : " + pkvFile.Value);
var item = ..ctrlListView:Items.Add(file.FullName.Substring(dirLength));
item.SubItems.Add(file.Name);
item.SubItems.Add(File.GetLastWriteTime(file.FullName).ToString());
item.SubItems.Add(position.ToString("# ### ##0"));
item.Group = group;
++added;
}
}
group.Header += " : " + added + "/" + files.Length + " fichier(s)"
+ " en " + (Environment.TickCount - perf).ToString("# ##0 msec");
On ListView column click :
<var>Visual.WIN.ctrlListView.OnColumnClick</var> :
// Déterminer si la colonne sélectionnée est déjà la colonne triée.
var sorter = eventSender.ListViewItemSorter;
if ( eventArgs.Column == sorter .SortColumn )
{
// Inverser le sens de tri en cours pour cette colonne.
if (sorter.Order == SortOrder.Ascending)
{
sorter.Order = SortOrder.Descending;
}
else
{
sorter.Order = SortOrder.Ascending;
}
}
else
{
// Définir le numéro de colonne à trier ; par défaut sur croissant.
sorter.SortColumn = eventArgs.Column;
sorter.Order = SortOrder.Ascending;
}
// Procéder au tri avec les nouvelles options.
eventSender.Sort();
Function edvTools.TryParse used above
class edvTools {
/// <summary>
/// Tente la conversion d'une valeur suivant un type EDVType
/// </summary>
/// <param name="pValue">Référence de la valeur à convertir</param>
/// <param name="pType">Type EDV en sortie</param>
/// <returns></returns>
public static bool TryParse(ref object pValue, System.Type pType)
{
int lIParsed;
double lDParsed;
string lsValue;
if (pValue == null) return false;
if (pType.Equals(typeof(bool))) {
bool lBParsed;
if (pValue is bool) return true;
if (double.TryParse(pValue.ToString(), out lDParsed)) {
pValue = lDParsed != 0D;
return true;
}
if (bool.TryParse(pValue.ToString(), out lBParsed)) {
pValue = lBParsed;
return true;
}
else
return false;
}
if (pType.Equals(typeof(Double))) {
if (pValue is Double) return true;
if (double.TryParse(pValue.ToString(), out lDParsed)
|| double.TryParse(pValue.ToString().Replace(NumberDecimalSeparatorNOT, NumberDecimalSeparator), out lDParsed)) {
pValue = lDParsed;
return true;
}
else
return false;
}
if (pType.Equals(typeof(int))) {
if (pValue is int) return true;
if (Int32.TryParse(pValue.ToString(), out lIParsed)) {
pValue = lIParsed;
return true;
}
else if (double.TryParse(pValue.ToString(), out lDParsed)) {
pValue = (int)lDParsed;
return true;
}
else
return false;
}
if (pType.Equals(typeof(Byte))) {
if (pValue is byte) return true;
byte lByte;
if (Byte.TryParse(pValue.ToString(), out lByte)) {
pValue = lByte;
return true;
}
else if (double.TryParse(pValue.ToString(), out lDParsed)) {
pValue = (byte)lDParsed;
return true;
}
else
return false;
}
if (pType.Equals(typeof(long))) {
long lLParsed;
if (pValue is long) return true;
if (long.TryParse(pValue.ToString(), out lLParsed)) {
pValue = lLParsed;
return true;
}
else if (double.TryParse(pValue.ToString(), out lDParsed)) {
pValue = (long)lDParsed;
return true;
}
else
return false;
}
if (pType.Equals(typeof(Single))) {
if (pValue is float) return true;
Single lSParsed;
if (Single.TryParse(pValue.ToString(), out lSParsed)
|| Single.TryParse(pValue.ToString().Replace(NumberDecimalSeparatorNOT, NumberDecimalSeparator), out lSParsed)) {
pValue = lSParsed;
return true;
}
else
return false;
}
if (pType.Equals(typeof(DateTime))) {
if (pValue is DateTime) return true;
DateTime lDTParsed;
if (DateTime.TryParse(pValue.ToString(), out lDTParsed)) {
pValue = lDTParsed;
return true;
}
else if (pValue.ToString().Contains("UTC")) //Date venant de JScript
{
if (_MonthsUTC == null) InitMonthsUTC();
string[] lDateParts = pValue.ToString().Split(' ');
lDTParsed = new DateTime(int.Parse(lDateParts[5]), _MonthsUTC[lDateParts[1]], int.Parse(lDateParts[2]));
lDateParts = lDateParts[3].ToString().Split(':');
pValue = lDTParsed.AddSeconds(int.Parse(lDateParts[0]) * 3600 + int.Parse(lDateParts[1]) * 60 + int.Parse(lDateParts[2]));
return true;
}
else
return false;
}
if (pType.Equals(typeof(Array))) {
if (pValue is System.Collections.ICollection || pValue is System.Collections.ArrayList)
return true;
return pValue is System.Data.DataTable
|| pValue is string && (pValue as string).StartsWith("<");
}
if (pType.Equals(typeof(DataTable))) {
return pValue is System.Data.DataTable
|| pValue is string && (pValue as string).StartsWith("<");
}
if (pType.Equals(typeof(System.Drawing.Bitmap))) {
return pValue is System.Drawing.Image || pValue is byte[];
}
if (pType.Equals(typeof(System.Drawing.Image))) {
return pValue is System.Drawing.Image || pValue is byte[];
}
if (pType.Equals(typeof(System.Drawing.Color))) {
if (pValue is System.Drawing.Color) return true;
if (pValue is System.Drawing.KnownColor) {
pValue = System.Drawing.Color.FromKnownColor((System.Drawing.KnownColor)pValue);
return true;
}
int lARGB;
if (!int.TryParse(lsValue = pValue.ToString(), out lARGB)) {
if (lsValue.StartsWith("Color [A=", StringComparison.InvariantCulture)) {
foreach (string lsARGB in lsValue.Substring("Color [".Length, lsValue.Length - "Color []".Length).Split(','))
switch (lsARGB.TrimStart().Substring(0, 1)) {
case "A":
lARGB = int.Parse(lsARGB.Substring(2)) * 0x1000000;
break;
case "R":
lARGB += int.Parse(lsARGB.TrimStart().Substring(2)) * 0x10000;
break;
case "G":
lARGB += int.Parse(lsARGB.TrimStart().Substring(2)) * 0x100;
break;
case "B":
lARGB += int.Parse(lsARGB.TrimStart().Substring(2));
break;
default:
break;
}
pValue = System.Drawing.Color.FromArgb(lARGB);
return true;
}
if (lsValue.StartsWith("Color [", StringComparison.InvariantCulture)) {
pValue = System.Drawing.Color.FromName(lsValue.Substring("Color [".Length, lsValue.Length - "Color []".Length));
return true;
}
return false;
}
pValue = System.Drawing.Color.FromArgb(lARGB);
return true;
}
if (pType.IsEnum) {
try {
if (pValue == null) return false;
if (pValue is int || pValue is byte || pValue is ulong || pValue is long || pValue is double)
pValue = Enum.ToObject(pType, pValue);
else
pValue = Enum.Parse(pType, pValue.ToString());
}
catch {
return false;
}
}
return true;
}
}
It's called correlated subquery. It has it's uses.
setTimeout(function(){
}, 500);
Place your code inside of the { }
500
= 0.5 seconds
2200
= 2.2 seconds
etc.
<input type="text" style="width:50px;"/>
There is a straightforward solution without messing with matplotlib: just pandas.
Tweaking the original example:
table = sql.read_frame(query,connection)
ax = table[0].plot(color=colors[0],ylim=(0,100))
ax2 = table[1].plot(secondary_y=True,color=colors[1], ax=ax)
ax.set_ylabel('Left axes label')
ax2.set_ylabel('Right axes label')
Basically, when the secondary_y=True
option is given (eventhough ax=ax
is passed too) pandas.plot
returns a different axes which we use to set the labels.
I know this was answered long ago, but I think this approach worths it.
this nsdate
used different format:
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MMM dd, yyyy HH:mm"];
NSDate *now = [[NSDate alloc] init];
NSString *dateString = [format stringFromDate:now];
NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];
[inFormat setDateFormat:@"MMM dd, yyyy"];
NSDate *parsed = [inFormat dateFromString:dateString];
You could also try bitpocket: https://github.com/sickill/bitpocket
It is not strange for me that none of the solutions above came up, but I saw how the igd installation removed the new version and installed the old one, for the solution I downloaded this archive:https://pypi.org/project/igd/#files
and changed the recommended version of the new version: 'lxml==4.3.0' in setup.py It works!
The zero value for time.Time is 0001-01-01 00:00:00 +0000 UTC
See http://play.golang.org/p/vTidOlmb9P
cmd.exe is located in different locations in different versions of Windows. To avoid needing the location of cmd.exe, you can use the command moogs wrote without calling "cmd.exe /C".
Here's an example that worked for me:
So the final step will look something like this in Command Prompt:
C:\Projects\MyProject\bin\Debug>runas /user:domain\username Application.exe
Note: the domain name was required in my situation.
Update: In an effort to answer my own question, here is what I've been able to uncover so far. If anyone else out there has something, I'd still be interested to find out more.
Based on JSON Schema
Commercial (No endorsement intended or implied, may or may not meet requirement)
jQuery
YAML
See Also
This shows the licence type and number of licences:
SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')
I had to use the \COPY because I received the error message:
ERROR: could not open file "/filepath/places.csv" for writing: Permission denied
So I used:
\Copy (Select address, zip From manjadata) To '/filepath/places.csv' With CSV;
and it is functioning
from the pandas doc http://pandas.pydata.org/pandas-docs/stable/dsintro.html Series is a one-dimensional labeled array capable of holding any data type. To read data in form of panda Series:
import pandas as pd
ds = pd.Series(data, index=index)
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types.
import pandas as pd
df = pd.DataFrame(data, index=index)
In both of the above index is list
for example: I have a csv file with following data:
,country,popuplation,area,capital
BR,Brazil,10210,12015,Brasile
RU,Russia,1025,457,Moscow
IN,India,10458,457787,New Delhi
To read above data as series and data frame:
import pandas as pd
file_data = pd.read_csv("file_path", index_col=0)
d = pd.Series(file_data.country, index=['BR','RU','IN'] or index = file_data.index)
output:
>>> d
BR Brazil
RU Russia
IN India
df = pd.DataFrame(file_data.area, index=['BR','RU','IN'] or index = file_data.index )
output:
>>> df
area
BR 12015
RU 457
IN 457787
In my case $(document).ready(function() was missing. Try this.
$(document).ready(function(){
("#table tr").click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:first').html();
alert(value);
});
$('.ok').on('click', function(e){
alert($("#table tr.selected td:first").html());
});
});
Don't use in-line JavaScript, separate your behaviour from your data and it gets much easier to handle. I'd suggest the following:
var table = document.getElementById('tableID'),
cells = table.getElementsByTagName('td');
for (var i=0,len=cells.length; i<len; i++){
cells[i].onclick = function(){
console.log(this.innerHTML);
/* if you know it's going to be numeric:
console.log(parseInt(this.innerHTML),10);
*/
}
}
var table = document.getElementById('tableID'),_x000D_
cells = table.getElementsByTagName('td');_x000D_
_x000D_
for (var i = 0, len = cells.length; i < len; i++) {_x000D_
cells[i].onclick = function() {_x000D_
console.log(this.innerHTML);_x000D_
};_x000D_
}
_x000D_
th,_x000D_
td {_x000D_
border: 1px solid #000;_x000D_
padding: 0.2em 0.3em 0.1em 0.3em;_x000D_
}
_x000D_
<table id="tableID">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Column heading 1</th>_x000D_
<th>Column heading 2</th>_x000D_
<th>Column heading 3</th>_x000D_
<th>Column heading 4</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>43</td>_x000D_
<td>23</td>_x000D_
<td>89</td>_x000D_
<td>5</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>4</td>_x000D_
<td>3</td>_x000D_
<td>0</td>_x000D_
<td>98</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>10</td>_x000D_
<td>32</td>_x000D_
<td>7</td>_x000D_
<td>2</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
A revised approach, in response to the comment (below):
You're missing a semicolon. Also, don't make functions within a loop.
This revision binds a (single) named function as the click
event-handler of the multiple <td>
elements, and avoids the unnecessary overhead of creating multiple anonymous functions within a loop (which is poor practice due to repetition and the impact on performance, due to memory usage):
function logText() {
// 'this' is automatically passed to the named
// function via the use of addEventListener()
// (later):
console.log(this.textContent);
}
// using a CSS Selector, with document.querySelectorAll()
// to get a NodeList of <td> elements within the #tableID element:
var cells = document.querySelectorAll('#tableID td');
// iterating over the array-like NodeList, using
// Array.prototype.forEach() and Function.prototype.call():
Array.prototype.forEach.call(cells, function(td) {
// the first argument of the anonymous function (here: 'td')
// is the element of the array over which we're iterating.
// adding an event-handler (the function logText) to handle
// the click events on the <td> elements:
td.addEventListener('click', logText);
});
function logText() {_x000D_
console.log(this.textContent);_x000D_
}_x000D_
_x000D_
var cells = document.querySelectorAll('#tableID td');_x000D_
_x000D_
Array.prototype.forEach.call(cells, function(td) {_x000D_
td.addEventListener('click', logText);_x000D_
});
_x000D_
th,_x000D_
td {_x000D_
border: 1px solid #000;_x000D_
padding: 0.2em 0.3em 0.1em 0.3em;_x000D_
}
_x000D_
<table id="tableID">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Column heading 1</th>_x000D_
<th>Column heading 2</th>_x000D_
<th>Column heading 3</th>_x000D_
<th>Column heading 4</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>43</td>_x000D_
<td>23</td>_x000D_
<td>89</td>_x000D_
<td>5</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>4</td>_x000D_
<td>3</td>_x000D_
<td>0</td>_x000D_
<td>98</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>10</td>_x000D_
<td>32</td>_x000D_
<td>7</td>_x000D_
<td>2</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
References:
Try Below Simple Ruby Magics :)
(1..x).each { |n| puts n }
x.times { |n| puts n }
1.upto(x) { |n| print n }
I think a cleaner approach is to inherit the vertical alignment:
In html:
<div class="shortcut"><a href="#">Download</a></div>
And in css:
.shortcut {
vertical-align: middle;
}
.shortcut > a:after {
vertical-align: inherit;
{
This way the icon will align properly in any resolution/font-size combination. Great for use with icon fonts.
The documentation is hear https://laravel.com/docs/5.4/views#view-composers but i will break it down
Look for the directory app\Providers in the root directory of your application and create the file ComposerServiceProvider.php and copy and past the text below into it and save it.
<?php
namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container.
*
* @return void
*/
public function boot()
{
// Using class based composers...
View::composer(
'profile', 'App\Http\ViewComposers\ProfileComposer'
);
// Using Closure based composers...
View::composer('dashboard', function ($view) {
//
});
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
}
From the root of your application open Config/app.php and look for the Providers section in the file and copy and past this 'App\Providers\ComposerServiceProvider', to the array.
By doing this, we have created the Composer Service Provider. When you run your application with the view Profile like so http://yourdomain/something/profile, the service provider ComposerServiceProvider is called and the class App\Http\ViewComposers\ProfileComposer is instantiated calling the method Composer due to the code below inside the boot method or function.
// Using class based composers...
View::composer(
'profile', 'App\Http\ViewComposers\ProfileComposer'
);
Go to the directory path app/Http
Create the directory called ViewComposers
Create the file ProfileComposer.php.
class ProfileComposer
{
/**
* The user repository implementation.
*
* @var UserRepository
*/
protected $users;
/**
* Create a new profile composer.
*
* @param UserRepository $users
* @return void
*/
public function __construct(UserRepository $users)
{
// Dependencies automatically resolved by service container...
$this->users = $users;
}
/**
* Bind data to the view.
*
* @param View $view
* @return void
*/
public function compose(View $view)
{
$view->with('count', $this->users->count());
}
}
Now go to your view or in this case Profile.blade.php and add
{{ $count }}
and that will show the count of users on the profile page.
To show the count on all pages change
// Using class based composers...
View::composer(
'profile', 'App\Http\ViewComposers\ProfileComposer'
);
To
// Using class based composers...
View::composer(
'*', 'App\Http\ViewComposers\ProfileComposer'
);
I came across this today, when I was playing around with someone else's website.
I realized I could attach a break-point in the debugger to some line of code before what I wanted to dynamically edit. And since break-points stay even after a reload of the page, I was able to edit the changes I wanted while paused at break-point and then continued to let the page load.
So as a quick work around, and if it works with your situation:
You need to install a plugin, There is a free one from the eclipse foundation called the Web Tools Platform. It has all the development functionality that you'll need.
You can get the Java EE Edition of eclipse with has it pre-installed.
To create and run your first servlet:
doGet()
method.That should do it for you. You can use ant to build here if that's what you'd like but eclipse will actually do the build and automatically deploy the changes to the server. With Tomcat you might have to restart it every now and again depending on the change.
One case which hasn't been covered is how to handle cancellation inside of an async method. Take for example a simple case where you need to upload some data to a service get it to calculate something and then return some results.
public async Task<Results> ProcessDataAsync(MyData data)
{
var client = await GetClientAsync();
await client.UploadDataAsync(data);
await client.CalculateAsync();
return await client.GetResultsAsync();
}
If you want to support cancellation then the easiest way would be to pass in a token and check if it has been cancelled between each async method call (or using ContinueWith). If they are very long running calls though you could be waiting a while to cancel. I created a little helper method to instead fail as soon as canceled.
public static class TaskExtensions
{
public static async Task<T> WaitOrCancel<T>(this Task<T> task, CancellationToken token)
{
token.ThrowIfCancellationRequested();
await Task.WhenAny(task, token.WhenCanceled());
token.ThrowIfCancellationRequested();
return await task;
}
public static Task WhenCanceled(this CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).SetResult(true), tcs);
return tcs.Task;
}
}
So to use it then just add .WaitOrCancel(token)
to any async call:
public async Task<Results> ProcessDataAsync(MyData data, CancellationToken token)
{
Client client;
try
{
client = await GetClientAsync().WaitOrCancel(token);
await client.UploadDataAsync(data).WaitOrCancel(token);
await client.CalculateAsync().WaitOrCancel(token);
return await client.GetResultsAsync().WaitOrCancel(token);
}
catch (OperationCanceledException)
{
if (client != null)
await client.CancelAsync();
throw;
}
}
Note that this will not stop the Task you were waiting for and it will continue running. You'll need to use a different mechanism to stop it, such as the CancelAsync
call in the example, or better yet pass in the same CancellationToken
to the Task
so that it can handle the cancellation eventually. Trying to abort the thread isn't recommended.
I realize this question is ancient and there is an accepted and an alternate answer. I also realize that my answer will only answer half of the question, but for anyone wanting to round to the nearest minute and still have a datetime compatible value using only a single function:
CAST(YourValueHere as smalldatetime);
For hours or seconds, use Jeff Ogata's answer (the accepted answer) above.
It depends on the host, but you probably simply can't (you can't on my shared host on Rackspace Cloud Sites - I asked them).
What you can do is set up an environment on your dev machine that roughly matches your shared host, and do all of your management through the command line locally. Then when everything is set (you've pulled in all the dependencies, updated, managed with git, etc.) you can "push" that to your shared host over (s)FTP.
Check out the pack URI syntax. You want something like this:
<ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Subfolder/YourResourceFile.xaml"/>
I got this exception when I set url in query like "example.com/files/text.txt". Ive changed url to "http://example.com/files/text.txt" and this exception dissapeared.
http://martinfowler.com/articles/microservice-testing/
Martin Fowler's blog post speaks about strategies to test code (Especially in a micro-services architecture) but most of it applies to any application.
I'll quote from his summary slide:
- Unit tests - exercise the smallest pieces of testable software in the application to determine whether they behave as expected.
- Integration tests - verify the communication paths and interactions between components to detect interface defects.
- Component tests - limit the scope of the exercised software to a portion of the system under test, manipulating the system through internal code interfaces and using test doubles to isolate the code under test from other components.
- Contract tests - verify interactions at the boundary of an external service asserting that it meets the contract expected by a consuming service.
- End-To-End tests - verify that a system meets external requirements and achieves its goals, testing the entire system, from end to end.
To see the devices I was interested in, I had replace Win32_USBHub
by Win32_PnPEntity
in Adel Hazzah's code, based on this post. This works for me:
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.Management; // need to add System.Management to your project references.
class Program
{
static void Main(string[] args)
{
var usbDevices = GetUSBDevices();
foreach (var usbDevice in usbDevices)
{
Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
}
Console.Read();
}
static List<USBDeviceInfo> GetUSBDevices()
{
List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
ManagementObjectCollection collection;
using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_PnPEntity"))
collection = searcher.Get();
foreach (var device in collection)
{
devices.Add(new USBDeviceInfo(
(string)device.GetPropertyValue("DeviceID"),
(string)device.GetPropertyValue("PNPDeviceID"),
(string)device.GetPropertyValue("Description")
));
}
collection.Dispose();
return devices;
}
}
class USBDeviceInfo
{
public USBDeviceInfo(string deviceID, string pnpDeviceID, string description)
{
this.DeviceID = deviceID;
this.PnpDeviceID = pnpDeviceID;
this.Description = description;
}
public string DeviceID { get; private set; }
public string PnpDeviceID { get; private set; }
public string Description { get; private set; }
}
}
If you have an SMTP service running, you can outfile to the drop directory. If you have high volume, you may result with duplicate file names, but there are ways to avoid that.
Otherwise, you will need to create a UDF.
Here's a sample trigger solution:
CREATE TRIGGER test.autosendfromdrop BEFORE INSERT ON test.emaildrop
FOR EACH ROW BEGIN
/* START THE WRITING OF THE EMAIL FILE HERE*/
SELECT concat("To: ",NEW.To),
concat("From: ",NEW.From),
concat("Subject: ",NEW.Subject),
NEW.Body
INTO OUTFILE
"C:\\inetpub\\mailroot\\pickup\\mail.txt"
FIELDS TERMINATED by '\r\n' ESCAPED BY '';
END;
To markup the message body you will need something like this...
CREATE FUNCTION `HTMLBody`(Msg varchar(8192))
RETURNS varchar(17408) CHARSET latin1 DETERMINISTIC
BEGIN
declare tmpMsg varchar(17408);
set tmpMsg = cast(concat(
'Date: ',date_format(NOW(),'%e %b %Y %H:%i:%S -0600'),'\r\n',
'MIME-Version: 1.0','\r\n',
'Content-Type: multipart/alternative;','\r\n',
' boundary=\"----=_NextPart_000_0000_01CA4B3F.8C263EE0\"','\r\n',
'Content-Class: urn:content-classes:message','\r\n',
'Importance: normal','\r\n',
'Priority: normal','\r\n','','\r\n','','\r\n',
'This is a multi-part message in MIME format.','\r\n','','\r\n',
'------=_NextPart_000_0000_01CA4B3F.8C263EE0','\r\n',
'Content-Type: text/plain;','\r\n',
' charset=\"iso-8859-1\"','\r\n',
'Content-Transfer-Encoding: 7bit','\r\n','','\r\n','','\r\n',
Msg,
'\r\n','','\r\n','','\r\n',
'------=_NextPart_000_0000_01CA4B3F.8C263EE0','\r\n',
'Content-Type: text/html','\r\n',
'Content-Transfer-Encoding: 7bit','\r\n','','\r\n',
Msg,
'\r\n','------=_NextPart_000_0000_01CA4B3F.8C263EE0--'
) as char);
RETURN tmpMsg;
END ;
Easiest method is
<TD>
<xsl:value-of select="concat(//author/first-name,' ',//author/last-name)"/>
</TD>
when the XML Structure is
<title>The Confidence Man</title>
<author>
<first-name>Herman</first-name>
<last-name>Melville</last-name>
</author>
<price>11.99</price>
If HTML and use bootstrap they have a helper class.
<span class="text-nowrap">1-866-566-7233</span>
We see this a lot with OAuth2 integrations. We provide API services to our Customers, and they'll naively try to put their private key into an AJAX call. This is really poor security. And well-coded API Gateways, backends for frontend, and other such proxies, do not allow this. You should get this error.
I will quote @aspillers comment and change a single word: "Access-Control-Allow-Origin
is a header sent in a server response which indicates IF the client is allowed to see the contents of a result".
ISSUE: The problem is that a developer is trying to include their private key inside a client-side (browser) JavaScript request. They will get an error, and this is because they are exposing their client secret.
SOLUTION: Have the JavaScript web application talk to a backend service that holds the client secret securely. That backend service can authenticate the web app to the OAuth2 provider, and get an access token. Then the web application can make the AJAX call.
My opinion,
Task.Delay()
is asynchronous. It doesn't block the current thread. You can still do other operations within current thread. It returns a Task return type (Thread.Sleep()
doesn't return anything ). You can check if this task is completed(use Task.IsCompleted
property) later after another time-consuming process.
Thread.Sleep()
doesn't have a return type. It's synchronous. In the thread, you can't really do anything other than waiting for the delay to finish.
As for real-life usage, I have been programming for 15 years. I have never used Thread.Sleep()
in production code. I couldn't find any use case for it.
Maybe that's because I mostly do web application development.
It might help you!
AngularJs Code-sample
var app = angular.module('urlApp', []);
app.controller('urlCtrl', function ($scope, $log, $window) {
$scope.ClickMeToRedirect = function () {
var url = "http://" + $window.location.host + "/Account/Login";
$log.log(url);
$window.location.href = url;
};
});
HTML Code-sample
<div ng-app="urlApp">
<div ng-controller="urlCtrl">
Redirect to <a href="#" ng-click="ClickMeToRedirect()">Click Me!</a>
</div>
</div>
Be very careful: all of the answers on this page are implicitly taking the decision of where the binning starts - the left-hand edge of the left-most bin, if you like - out of the user's hands. If the user is combining any of these functions for binning data with his/her own decision about where binning starts (as is done on the blog which is linked to above) the functions above are all incorrect. With an arbitrary starting point for binning 'Min', the correct function is:
bin(x) = width*(floor((x-Min)/width)+0.5) + Min
You can see why this is correct sequentially (it helps to draw a few bins and a point somewhere in one of them). Subtract Min from your data point to see how far into the binning range it is. Then divide by binwidth so that you're effectively working in units of 'bins'. Then 'floor' the result to go to the left-hand edge of that bin, add 0.5 to go to the middle of the bin, multiply by the width so that you're no longer working in units of bins but in an absolute scale again, then finally add back on the Min offset you subtracted at the start.
Consider this function in action:
Min = 0.25 # where binning starts
Max = 2.25 # where binning ends
n = 2 # the number of bins
width = (Max-Min)/n # binwidth; evaluates to 1.0
bin(x) = width*(floor((x-Min)/width)+0.5) + Min
e.g. the value 1.1 truly falls in the left bin:
Born2Smile's answer is only correct if the bin boundaries occur at (n+0.5)*binwidth (where n runs over integers). mas90's answer is only correct if the bin boundaries occur at n*binwidth.
Richard Fearn has the right idea, so I wrote up the full class based on his skeleton code. It's hopefully short enough to post here. Copy & paste for enjoyment. I should probably add some magic incantation, too: "This code is released to the public domain"
import org.slf4j.Logger;
public class LogLevel {
/**
* Allowed levels, as an enum. Import using "import [package].LogLevel.Level"
* Every logging implementation has something like this except SLF4J.
*/
public static enum Level {
TRACE, DEBUG, INFO, WARN, ERROR
}
/**
* This class cannot be instantiated, why would you want to?
*/
private LogLevel() {
// Unreachable
}
/**
* Log at the specified level. If the "logger" is null, nothing is logged.
* If the "level" is null, nothing is logged. If the "txt" is null,
* behaviour depends on the SLF4J implementation.
*/
public static void log(Logger logger, Level level, String txt) {
if (logger != null && level != null) {
switch (level) {
case TRACE:
logger.trace(txt);
break;
case DEBUG:
logger.debug(txt);
break;
case INFO:
logger.info(txt);
break;
case WARN:
logger.warn(txt);
break;
case ERROR:
logger.error(txt);
break;
}
}
}
/**
* Log at the specified level. If the "logger" is null, nothing is logged.
* If the "level" is null, nothing is logged. If the "format" or the "argArray"
* are null, behaviour depends on the SLF4J-backing implementation.
*/
public static void log(Logger logger, Level level, String format, Object[] argArray) {
if (logger != null && level != null) {
switch (level) {
case TRACE:
logger.trace(format, argArray);
break;
case DEBUG:
logger.debug(format, argArray);
break;
case INFO:
logger.info(format, argArray);
break;
case WARN:
logger.warn(format, argArray);
break;
case ERROR:
logger.error(format, argArray);
break;
}
}
}
/**
* Log at the specified level, with a Throwable on top. If the "logger" is null,
* nothing is logged. If the "level" is null, nothing is logged. If the "format" or
* the "argArray" or the "throwable" are null, behaviour depends on the SLF4J-backing
* implementation.
*/
public static void log(Logger logger, Level level, String txt, Throwable throwable) {
if (logger != null && level != null) {
switch (level) {
case TRACE:
logger.trace(txt, throwable);
break;
case DEBUG:
logger.debug(txt, throwable);
break;
case INFO:
logger.info(txt, throwable);
break;
case WARN:
logger.warn(txt, throwable);
break;
case ERROR:
logger.error(txt, throwable);
break;
}
}
}
/**
* Check whether a SLF4J logger is enabled for a certain loglevel.
* If the "logger" or the "level" is null, false is returned.
*/
public static boolean isEnabledFor(Logger logger, Level level) {
boolean res = false;
if (logger != null && level != null) {
switch (level) {
case TRACE:
res = logger.isTraceEnabled();
break;
case DEBUG:
res = logger.isDebugEnabled();
break;
case INFO:
res = logger.isInfoEnabled();
break;
case WARN:
res = logger.isWarnEnabled();
break;
case ERROR:
res = logger.isErrorEnabled();
break;
}
}
return res;
}
}
There are many efficient ways to test primality (and this isn't one of them), but the loop you wrote can be concisely rewritten in Python:
def is_prime(a):
return all(a % i for i in xrange(2, a))
That is, a is prime if all numbers between 2 and a (not inclusive) give non-zero remainder when divided into a.
Additionally for gists, it seems you must leave out the username
git remote set-url origin [email protected]:<Project code>
You can also use following query :
DELETE FROM Student, Enrollment USING Student INNER JOIN Enrollment ON Student.studentId = Enrollment.studentId WHERE Student.studentId= 51;