Open Outlook 2013 > File > Office account > About Outlook > click large "? About Outlook" button > read popup description
OnClick is triggered when the user releases the button. But if you still want to use the TouchListener you need to add it in code. It's just:
myView.setOnTouchListener(new View.OnTouchListener()
{
// Implementation;
});
Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("HTML from an external file:");
request.getRequestDispatcher("/pathToFile/fragment.html")
.include(request, response);
out.close();
}
Modern browsers today seem to block (by default) these autoplay features. They are somewhat treated as pop-ops. Very intrusive. So yeah, users now have the complete control on when the sounds are played. [1,2,3]
<audio controls autoplay loop hidden>
<source src="audio.mp3" type="audio/mpeg">
</audio>
<embed src="audio.mp3" style="visibility:hidden" />
Some options:
You can use the Execute Package Utility to change your datasource, before running the package.
You can run your package using DTEXEC, and change your connection by passing in a /CONNECTION parameter. Probably save it as a batch so next time you don't need to type the whole thing and just change the datasource as required.
You can use the SSIS XML package configuration file. Here is a walk through.
You can save your configrations in a database table.
enter code hereif you are using linux you have to edit the
`/etc/apache2/sites-available/000-default.conf`
under the Documentroot . add the following code
`<Directory /var/www/>
AllowOverride all
Require all granted
</Directory>`
then ,
`sudo service apache2 restart`
and you have to enable the apache mod rewrite
`sudo a2enmod rewrite`
Try this CSS:
body {
margin: 0;
padding: 0;
}
.logo {
float: left;
}
/* ~~ Top Navigation Bar ~~ */
#navigation-container {
width: 1200px;
margin: 0 auto;
height: 70px;
}
.navigation-bar {
background-color: #352d2f;
height: 70px;
width: 100%;
}
#navigation-container img {
float: left;
}
#navigation-container ul {
padding: 0px;
margin: 0px;
text-align: center;
display:inline-block;
}
#navigation-container li {
list-style-type: none;
padding: 0px;
height: 24px;
margin-top: 4px;
margin-bottom: 4px;
display: inline;
}
#navigation-container li a {
color: white;
font-size: 16px;
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
text-decoration: none;
line-height: 70px;
padding: 5px 15px;
opacity: 0.7;
}
#menu {
float: right;
}
I know this has been said earlier, but jQuery Autocomplete will do exactly what you need. You should check out the docs as the autocomplete is very customizable. If you are familiar with javascript then you should be able to work this out. If not I can give you a few pointers, as I have done this once before, but beware I am not well versed in javascript myself either, so bear with me on this.
I think the first thing you should do is just get a simple autocomplete text field working on your page, and then you can customize it from there.
The autocomplete widget accepts JSON data as it's 'source:' option. So you should set-up your app to produce the 20 top level categories, and subcategories in JSON format.
The next thing to know is that when the user types into your textfield, the autocomplete widget will send the typed values in a parameter called "term".
So let's say you first set-up your site to deliver the JSON data from a URL like this:
/categories.json
Then your autocomplete source: option would be 'source: /categories.json'.
When a user types into the textfield, such as 'first-cata...' the autocomplete widget will start sending the value in the 'term' parameter like this:
/categories.json?term=first-cata
This will return JSON data back to the widget filtered by anything that matches 'first-cata', and this is displayed as an autocomplete suggestion.
I am not sure what you are programming in, but you can specify how the 'term' parameter finds a match. So you can customize this, so that the term finds a match in the middle of a word if you want. Example, if the user types 'or' you code could make a match on 'sports'.
Lastly, you made a comment that you want to be able to select a category name but have the autocomplete widget submit the category ID not the name.
This can easily be done with a hidden field. This is what is shown in the jQuery autocomplete docs.
When a user selects a category, your JavaScript should update a hidden field with the ID.
I know this answer is not very detailed, but that is mainly because I am not sure what you are programming in, but the above should point you in the right direction. The thing to know is that you can do practically any customizing you want with this widget, if you are willing to spend the time to learn it.
These are the broad strokes, but you can look here for some notes I made when I implemented something similar to what you want in a Rails app.
Hope this helped.
TLDR: use theString = theString.replace("\\", "\\\\");
instead.
replaceAll(target, replacement)
uses regular expression (regex) syntax for target
and partially for replacement
.
Problem is that \
is special character in regex (it can be used like \d
to represents digit) and in String literal (it can be used like "\n"
to represent line separator or \"
to escape double quote symbol which normally would represent end of string literal).
In both these cases to create \
symbol we can escape it (make it literal instead of special character) by placing additional \
before it (like we escape "
in string literals via \"
).
So to target
regex representing \
symbol will need to hold \\
, and string literal representing such text will need to look like "\\\\"
.
So we escaped \
twice:
\\
"\\\\"
(each \
is represented as "\\"
). In case of replacement
\
is also special there. It allows us to escape other special character $
which via $x
notation, allows us to use portion of data matched by regex and held by capturing group indexed as x
, like "012".replaceAll("(\\d)", "$1$1")
will match each digit, place it in capturing group 1 and $1$1
will replace it with its two copies (it will duplicate it) resulting in "001122"
.
So again, to let replacement
represent \
literal we need to escape it with additional \
which means that:
\\
\\
looks like "\\\\"
BUT since we want replacement
to hold two backslashes we will need "\\\\\\\\"
(each \
represented by one "\\\\"
).
So version with replaceAll
can look like
replaceAll("\\\\", "\\\\\\\\");
To make out life easier Java provides tools to automatically escape text into target
and replacement
parts. So now we can focus only on strings, and forget about regex syntax:
replaceAll(Pattern.quote(target), Matcher.quoteReplacement(replacement))
which in our case can look like
replaceAll(Pattern.quote("\\"), Matcher.quoteReplacement("\\\\"))
If we don't really need regex syntax support lets not involve replaceAll
at all. Instead lets use replace
. Both methods will replace all target
s, but replace
doesn't involve regex syntax. So you could simply write
theString = theString.replace("\\", "\\\\");
When you are working with fixed
or absolute
values,
it's good idea to set top
or bottom
and left
or right
(or combination of them) properties.
Also don't set the height
of main
element (let browser set the height of it with setting top
and bottom
properties).
.header{
position: fixed;
background-color: #f00;
height: 100px;
top: 0;
left: 0;
right: 0;
}
.main{
background-color: #ff0;
position: fixed;
bottom: 120px;
left: 0;
right: 0;
top: 100px;
overflow: auto;
}
.footer{
position: fixed;
bottom: 0;
background-color: #f0f;
height: 120px;
bottom: 0;
left: 0;
right: 0;
}
Well, the method in this asnwer method did not work for me. I don't know, maybe this is a Python3 (I am using the 3.4 version) or gmail related issue, but after some tries, the solution that worked for me, was the line
s.send_message(msg)
instead of
s.sendmail(sender, recipients, msg.as_string())
Nothing worked for me until I found iisexpress-proxy.
Open command prompt as administrator, then run
npm install -g iisexpress-proxy
then
iisexpress-proxy 51123 to 81
assuming your Visual Studio project opens on localhost:51123 and you want to access on external IP address x.x.x.x:81
Edit: I am currently using ngrok
This is a Python3 function for converting any text file into the one with UTF-8 encoding. (without using unnecessary packages)
def correctSubtitleEncoding(filename, newFilename, encoding_from, encoding_to='UTF-8'):
with open(filename, 'r', encoding=encoding_from) as fr:
with open(newFilename, 'w', encoding=encoding_to) as fw:
for line in fr:
fw.write(line[:-1]+'\r\n')
You can use it easily in a loop to convert a list of files.
I got this error(classNotFoundException for main class), I actually changed pom version , so did maven install again and then error vanished.
I agree with John on wrapping the sleep function. You could also use this wrapped sleep function to implement a pause function in lua (which would simply sleep then check to see if a certain condition has changed every so often). An alternative is to use hooks.
I'm not exactly sure what you mean with your third bulletpoint (don't commands usually complete before the next is executed?) but hooks may be able to help with this also.
See: Question: How can I end a Lua thread cleanly? for an example of using hooks.
Instead of
background-repeat-x: no-repeat;
background-repeat-y: no-repeat;
which is not correct, use
background-repeat: no-repeat;
Since version 5.7 TCPDF includes support for CSS borders. Margins, padding and float are not yet supported. Check the TCPDF website at http://www.tcpdf.org and consult the official forum for further information.
For those coming here to find the item count of something that is already a jQuery object:
.length is what you are looking for:
Example:
len = $('#divID').length;
alert(len);
Here a .NET C# similar implementation of a timespan class that supports days, hours, minutes and seconds. This implementation also supports negative timespans.
const MILLIS_PER_SECOND = 1000;
const MILLIS_PER_MINUTE = MILLIS_PER_SECOND * 60; // 60,000
const MILLIS_PER_HOUR = MILLIS_PER_MINUTE * 60; // 3,600,000
const MILLIS_PER_DAY = MILLIS_PER_HOUR * 24; // 86,400,000
export class TimeSpan {
private _millis: number;
private static interval(value: number, scale: number): TimeSpan {
if (Number.isNaN(value)) {
throw new Error("value can't be NaN");
}
const tmp = value * scale;
const millis = TimeSpan.round(tmp + (value >= 0 ? 0.5 : -0.5));
if ((millis > TimeSpan.maxValue.totalMilliseconds) || (millis < TimeSpan.minValue.totalMilliseconds)) {
throw new TimeSpanOverflowError("TimeSpanTooLong");
}
return new TimeSpan(millis);
}
private static round(n: number): number {
if (n < 0) {
return Math.ceil(n);
} else if (n > 0) {
return Math.floor(n);
}
return 0;
}
private static timeToMilliseconds(hour: number, minute: number, second: number): number {
const totalSeconds = (hour * 3600) + (minute * 60) + second;
if (totalSeconds > TimeSpan.maxValue.totalSeconds || totalSeconds < TimeSpan.minValue.totalSeconds) {
throw new TimeSpanOverflowError("TimeSpanTooLong");
}
return totalSeconds * MILLIS_PER_SECOND;
}
public static get zero(): TimeSpan {
return new TimeSpan(0);
}
public static get maxValue(): TimeSpan {
return new TimeSpan(Number.MAX_SAFE_INTEGER);
}
public static get minValue(): TimeSpan {
return new TimeSpan(Number.MIN_SAFE_INTEGER);
}
public static fromDays(value: number): TimeSpan {
return TimeSpan.interval(value, MILLIS_PER_DAY);
}
public static fromHours(value: number): TimeSpan {
return TimeSpan.interval(value, MILLIS_PER_HOUR);
}
public static fromMilliseconds(value: number): TimeSpan {
return TimeSpan.interval(value, 1);
}
public static fromMinutes(value: number): TimeSpan {
return TimeSpan.interval(value, MILLIS_PER_MINUTE);
}
public static fromSeconds(value: number): TimeSpan {
return TimeSpan.interval(value, MILLIS_PER_SECOND);
}
public static fromTime(hours: number, minutes: number, seconds: number): TimeSpan;
public static fromTime(days: number, hours: number, minutes: number, seconds: number, milliseconds: number): TimeSpan;
public static fromTime(daysOrHours: number, hoursOrMinutes: number, minutesOrSeconds: number, seconds?: number, milliseconds?: number): TimeSpan {
if (milliseconds != undefined) {
return this.fromTimeStartingFromDays(daysOrHours, hoursOrMinutes, minutesOrSeconds, seconds, milliseconds);
} else {
return this.fromTimeStartingFromHours(daysOrHours, hoursOrMinutes, minutesOrSeconds);
}
}
private static fromTimeStartingFromHours(hours: number, minutes: number, seconds: number): TimeSpan {
const millis = TimeSpan.timeToMilliseconds(hours, minutes, seconds);
return new TimeSpan(millis);
}
private static fromTimeStartingFromDays(days: number, hours: number, minutes: number, seconds: number, milliseconds: number): TimeSpan {
const totalMilliSeconds = (days * MILLIS_PER_DAY) +
(hours * MILLIS_PER_HOUR) +
(minutes * MILLIS_PER_MINUTE) +
(seconds * MILLIS_PER_SECOND) +
milliseconds;
if (totalMilliSeconds > TimeSpan.maxValue.totalMilliseconds || totalMilliSeconds < TimeSpan.minValue.totalMilliseconds) {
throw new TimeSpanOverflowError("TimeSpanTooLong");
}
return new TimeSpan(totalMilliSeconds);
}
constructor(millis: number) {
this._millis = millis;
}
public get days(): number {
return TimeSpan.round(this._millis / MILLIS_PER_DAY);
}
public get hours(): number {
return TimeSpan.round((this._millis / MILLIS_PER_HOUR) % 24);
}
public get minutes(): number {
return TimeSpan.round((this._millis / MILLIS_PER_MINUTE) % 60);
}
public get seconds(): number {
return TimeSpan.round((this._millis / MILLIS_PER_SECOND) % 60);
}
public get milliseconds(): number {
return TimeSpan.round(this._millis % 1000);
}
public get totalDays(): number {
return this._millis / MILLIS_PER_DAY;
}
public get totalHours(): number {
return this._millis / MILLIS_PER_HOUR;
}
public get totalMinutes(): number {
return this._millis / MILLIS_PER_MINUTE;
}
public get totalSeconds(): number {
return this._millis / MILLIS_PER_SECOND;
}
public get totalMilliseconds(): number {
return this._millis;
}
public add(ts: TimeSpan): TimeSpan {
const result = this._millis + ts.totalMilliseconds;
return new TimeSpan(result);
}
public subtract(ts: TimeSpan): TimeSpan {
const result = this._millis - ts.totalMilliseconds;
return new TimeSpan(result);
}
}
const ts = TimeSpan.zero;
From milliseconds
const milliseconds = 10000; // 1 second
// by using the constructor
const ts1 = new TimeSpan(milliseconds);
// or as an alternative you can use the static factory method
const ts2 = TimeSpan.fromMilliseconds(milliseconds);
From seconds
const seconds = 86400; // 1 day
const ts = TimeSpan.fromSeconds(seconds);
From minutes
const minutes = 1440; // 1 day
const ts = TimeSpan.fromMinutes(minutes);
From hours
const hours = 24; // 1 day
const ts = TimeSpan.fromHours(hours);
From days
const days = 1; // 1 day
const ts = TimeSpan.fromDays(days);
From time with given hours, minutes and seconds
const hours = 1;
const minutes = 1;
const seconds = 1;
const ts = TimeSpan.fromTime(hours, minutes, seconds);
From time2 with given days, hours, minutes, seconds and milliseconds
const days = 1;
const hours = 1;
const minutes = 1;
const seconds = 1;
const milliseconds = 1;
const ts = TimeSpan.fromTime(days, hours, minutes, seconds, milliseconds);
From maximal safe integer
const ts = TimeSpan.maxValue;
From minimal safe integer
const ts = TimeSpan.minValue;
From minimal safe integer
const ts = TimeSpan.minValue;
Add
const ts1 = TimeSpan.fromDays(1);
const ts2 = TimeSpan.fromHours(1);
const ts = ts1.add(ts2);
console.log(ts.days); // 1
console.log(ts.hours); // 1
console.log(ts.minutes); // 0
console.log(ts.seconds); // 0
console.log(ts.milliseconds); // 0
Subtract
const ts1 = TimeSpan.fromDays(1);
const ts2 = TimeSpan.fromHours(1);
const ts = ts1.subtract(ts2);
console.log(ts.days); // 0
console.log(ts.hours); // 23
console.log(ts.minutes); // 0
console.log(ts.seconds); // 0
console.log(ts.milliseconds); // 0
Getting the intervals
const days = 1;
const hours = 1;
const minutes = 1;
const seconds = 1;
const milliseconds = 1;
const ts = TimeSpan.fromTime2(days, hours, minutes, seconds, milliseconds);
console.log(ts.days); // 1
console.log(ts.hours); // 1
console.log(ts.minutes); // 1
console.log(ts.seconds); // 1
console.log(ts.milliseconds); // 1
console.log(ts.totalDays) // 1.0423726967592593;
console.log(ts.totalHours) // 25.016944722222224;
console.log(ts.totalMinutes) // 1501.0166833333333;
console.log(ts.totalSeconds) // 90061.001;
console.log(ts.totalMilliseconds); // 90061001;
See also here: https://github.com/erdas/timespan
The following code works fine:
@using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
and generates as expected:
<form action="/Upload/Upload" enctype="multipart/form-data" method="post">
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
</form>
On the other hand if you are writing this code inside the context of other server side construct such as an if
or foreach
you should remove the @
before the using
. For example:
@if (SomeCondition)
{
using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
}
As far as your server side code is concerned, here's how to proceed:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Upload");
}
You can loop through the columns collection of the datatable.
VB
Dim dt As New DataTable()
For Each column As DataColumn In dt.Columns
Console.WriteLine(column.ColumnName)
Next
C#
DataTable dt = new DataTable();
foreach (DataColumn column in dt.Columns)
{
Console.WriteLine(column.ColumnName);
}
Hope this helps!
In your test code your are trying to pass App
to the spyOn function, but spyOn will only work with objects, not classes. Generally you need to use one of two approaches here:
1) Where the click handler calls a function passed as a prop, e.g.
class App extends Component {
myClickFunc = () => {
console.log('clickity clickcty');
this.props.someCallback();
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now pass in a spy function as a prop to the component, and assert that it is called:
describe('my sweet test', () => {
it('clicks it', () => {
const spy = jest.fn();
const app = shallow(<App someCallback={spy} />)
const p = app.find('.App-intro')
p.simulate('click')
expect(spy).toHaveBeenCalled()
})
})
2) Where the click handler sets some state on the component, e.g.
class App extends Component {
state = {
aProperty: 'first'
}
myClickFunc = () => {
console.log('clickity clickcty');
this.setState({
aProperty: 'second'
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now make assertions about the state of the component, i.e.
describe('my sweet test', () => {
it('clicks it', () => {
const app = shallow(<App />)
const p = app.find('.App-intro')
p.simulate('click')
expect(app.state('aProperty')).toEqual('second');
})
})
This would work
setInterval(function(){$("#myButtonId").click();}, 1000);
.dmp files are dumps of oracle databases created with the "exp" command. You can import them using the "imp" command.
If you have an oracle client intalled on your machine, you can executed the command
imp help=y
to find out how it works. What will definitely help is knowing from wich schema the data was exported and what the oracle version was.
Inline tag is used to add another src of document to the current html element.
In your case an video of a youtube and we need to specify the html type(4 or 5) to the browser externally to the link
so add ?html=5 to the end of the link.. :)
E:\>mysql -u root -p
Enter password: *******
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1026
Server version: 5.6.34-log MySQL Community Server (GPL)
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> select @@version;
+------------+
| @@version |
+------------+
| 5.6.34-log |
+------------+
1 row in set (0.00 sec)
Sometimes you will get lots of compiler outputs with many warnings and no line of output that says "error: you did something wrong here" but there was still an error. An example of this is a missing header file - the compiler says something like "no such file" but not "error: no such file", then it exits with non-zero exit code some time later (perhaps after many more warnings). Make will bomb out with an error message in these cases!
All you need is width:100%
somewhere that applies to the tag as shown by the various answers here.
Using col-xs-12:
<!-- adds float:left, which is usually not a problem -->
<img class='img-responsive col-xs-12' />
Or inline CSS:
<img class='img-responsive' style='width:100%;' />
Or, in your own CSS file, add an additional definition for .img-responsive
.img-responsive {
width:100%;
}
THE ROOT OF THE PROBLEM
This is a known FF bug that <fieldset>
does not respect overflow rules:
https://bugzilla.mozilla.org/show_bug.cgi?id=261037
A CSS "FIX" to fix the FireFox bug would be to make the <fieldset>
display:table-column
. However, doing so, according to the following link, will cause the display of the fieldset to fail in Opera:
https://github.com/TryGhost/Ghost/issues/789
So, just set your tag to 100% width as described in one of the solutions above.
TO search a column name use the below query if you know the column name accurately:
select owner,table_name from all_tab_columns where upper(column_name) =upper('keyword');
TO search a column name if you dont know the accurate column use below:
select owner,table_name from all_tab_columns where upper(column_name) like upper('%keyword%');
If your problem is like the following while using Google Chrome:
[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]
Then create a batch file by following these steps:
Open notepad in Desktop.
start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit
This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.
Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.
This is another way of solving this problem.
$data = array(
1,
4,
'a' => 'b',
'c' => 'd'
);
$query = http_build_query(array('aParam' => $data));
A full example with Zebra_Image library, that I think is so easy and useful. There are a lot of code, but if you read it, there are a lot of comments too so you can make copy and paste to use it quickly.
This example validates image format, size and replace image size with custom resolution. There is Zebra library and documentation (download only Zebra_Image.php file).
Explanation:
Main function
private function uploadImage() {
$target_file = "../img/blog/";
//this function could be in the same PHP file or class. I use a Helper (see bellow)
if(UsersUtils::uploadFile($target_file, $this->selectedBlog->getId())) {
//This function is at same Helper class.
//The image will be returned allways if there isn't errors uploading it, for this reason there aren't validations here.
$blogPhotoPath = UsersUtils::getUserFile($target_file, $this->selectedBlog->getId());
// create a new instance of the class
$imageHelper = new Zebra_Image();
// indicate a source image
$imageHelper->source_path = $blogPhotoPath;
// indicate a target image
$imageHelper->target_path = $blogPhotoPath;
// since in this example we're going to have a jpeg file, let's set the output
// image's quality
$imageHelper->jpeg_quality = 100;
// some additional properties that can be set
// read about them in the documentation
$imageHelper->preserve_aspect_ratio = true;
$imageHelper->enlarge_smaller_images = true;
$imageHelper->preserve_time = true;
$imageHelper->handle_exif_orientation_tag = true;
// resize
// and if there is an error, show the error message
if (!$imageHelper->resize(450, 310, ZEBRA_IMAGE_CROP_CENTER)) {
// if there was an error, let's see what the error is about
switch ($imageHelper->error) {
case 1:
echo 'Source file could not be found!';
break;
case 2:
echo 'Source file is not readable!';
break;
case 3:
echo 'Could not write target file!';
break;
case 4:
echo 'Unsupported source file format!';
break;
case 5:
echo 'Unsupported target file format!';
break;
case 6:
echo 'GD library version does not support target file format!';
break;
case 7:
echo 'GD library is not installed!';
break;
case 8:
echo '"chmod" command is disabled via configuration!';
break;
case 9:
echo '"exif_read_data" function is not available';
break;
}
} else {
echo 'Image uploaded with new size without erros');
}
}
}
External functions or use at same PHP file removing public static qualifiers.
public static function uploadFile($targetDir, $fileName) {
// File upload path
$fileUploaded = $_FILES["input-file"];
$fileType = pathinfo(basename($fileUploaded["name"]),PATHINFO_EXTENSION);
$targetFilePath = $targetDir . $fileName .'.'.$fileType;
if(empty($fileName)){
echo 'Error: any file found inside this path';
return false;
}
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf');
if(in_array($fileType, $allowTypes)){
//Max buffer length 8M
var_dump(ob_get_length());
if(ob_get_length() > 8388608) {
echo 'Error: Max size available 8MB';
return false;
}
// Upload file to server
if(move_uploaded_file($fileUploaded["tmp_name"], $targetFilePath)){
return true;
}else{
echo 'Error: error_uploading_image.';
}
}else{
echo 'Error: Only files JPG, JPEG, PNG, GIF y PDF types are allowed';
}
return false;
}
public static function getUserFile($targetDir, $userId) {
$userImages = glob($targetDir.$userId.'.*');
return !empty($userImages) ? $userImages[0] : null;
}
Implement Comparable interface to Fruit.
public class Fruit implements Comparable<Fruit> {
It implements the method
@Override
public int compareTo(Fruit fruit) {
//write code here for compare name
}
Then do call sort method
Collections.sort(fruitList);
I hope this clarifies those two:
x | 2
0001 //x
0010 //2
0011 //result = 3
x & 1
0001 //x
0001 //1
0001 //result = 1
Just throw any RuntimeException
from a method marked as @Transactional
.
By default all RuntimeException
s rollback transaction whereas checked exceptions don't. This is an EJB legacy. You can configure this by using rollbackFor()
and noRollbackFor()
annotation parameters:
@Transactional(rollbackFor=Exception.class)
This will rollback transaction after throwing any exception.
For all , this , there exists a better method (EASIEST METHOD) :
1 ) A plugin for Android studio exits , called Android wifi ADB
2) Go to file -> settings -> Plugins -> Browse Repositories
3) Look for Android WiFi ADB , click on INSTALL , and then restart on prompt
4) You will see a new icon , which is your new plugin .
Now to make this work :
5) Go to your phone's developer option and enable DEBUGGING (must)
6) Also enable , ALLOW DEBUG OVER TCP/NETWORK
7) Attach your phone via USB , and make sure , both phone and your pc/laptop are connected to the same network (either hotspot or wifi)
8) CLICK ON THE NEW ICON (ie your ANDROID Wifi ABD)
9) Your phone get's detected and get's connected over wifi/hotspot , and hence now you may disconnect the usb . This is a one time process , hence you may not need to keep phone connected over usb .
This will save your phone from irregular charges and also , a remedy for short length usb cables .
Another solution without chaining grep
:
egrep '(^|[^g])loom' ~/projects/**/trunk/src/**/*.@(h|cpp)
Between brackets, you exclude the character g
before any occurrence of loom
, unless loom
is the first chars of the line.
Another thing that can cause Maven to not find the tests if if the module's packaging is not declared correctly.
In a recent case, someone had <packaging>pom</packaging>
and my tests never ran. I changed it to <packaging>jar</packaging>
and now it works fine.
Simple:
btn.setBackground(Color.red);
To use RGB values:
btn[i].setBackground(Color.RGBtoHSB(int, int, int, float[]));
In C++11, use std::stoi
as:
std::string s = "10";
int i = std::stoi(s);
Note that std::stoi
will throw exception of type std::invalid_argument
if the conversion cannot be performed, or std::out_of_range
if the conversion results in overflow(i.e when the string value is too big for int
type). You can use std::stol
or std:stoll
though in case int
seems too small for the input string.
In C++03/98, any of the following can be used:
std::string s = "10";
int i;
//approach one
std::istringstream(s) >> i; //i is 10 after this
//approach two
sscanf(s.c_str(), "%d", &i); //i is 10 after this
Note that the above two approaches would fail for input s = "10jh"
. They will return 10 instead of notifying error. So the safe and robust approach is to write your own function that parses the input string, and verify each character to check if it is digit or not, and then work accordingly. Here is one robust implemtation (untested though):
int to_int(char const *s)
{
if ( s == NULL || *s == '\0' )
throw std::invalid_argument("null or empty string argument");
bool negate = (s[0] == '-');
if ( *s == '+' || *s == '-' )
++s;
if ( *s == '\0')
throw std::invalid_argument("sign character only.");
int result = 0;
while(*s)
{
if ( *s < '0' || *s > '9' )
throw std::invalid_argument("invalid input string");
result = result * 10 - (*s - '0'); //assume negative number
++s;
}
return negate ? result : -result; //-result is positive!
}
This solution is slightly modified version of my another solution.
Try the following command:
mysqladmin -h[hostname/localhost] -u[username] -p[password] drop [database]
In my case this code did'n work until I move apply plugin: 'kotlin-android'
from bottom to top.
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
android {
...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}
The approach you're looking for is FillDown
. Another way so you don't have to kick your head off every time is to store formulas in an array of strings. Combining them gives you a powerful method of inputting formulas by the multitude. Code follows:
Sub FillDown()
Dim strFormulas(1 To 3) As Variant
With ThisWorkbook.Sheets("Sheet1")
strFormulas(1) = "=SUM(A2:B2)"
strFormulas(2) = "=PRODUCT(A2:B2)"
strFormulas(3) = "=A2/B2"
.Range("C2:E2").Formula = strFormulas
.Range("C2:E11").FillDown
End With
End Sub
Screenshots:
Result as of line: .Range("C2:E2").Formula = strFormulas
:
Result as of line: .Range("C2:E11").FillDown
:
Of course, you can make it dynamic by storing the last row into a variable and turning it to something like .Range("C2:E" & LRow).FillDown
, much like what you did.
Hope this helps!
According to the Wordpress documentation, you should use wp_localize_script()
in your functions.php file. This will create a Javascript Object in the header, which will be available to your scripts at runtime.
See Codex
Example:
<?php wp_localize_script('mylib', 'WPURLS', array( 'siteurl' => get_option('siteurl') )); ?>
To access this variable within in Javascript, you would simply do:
<script type="text/javascript">
var url = WPURLS.siteurl;
</script>
You can usee the following code:
week_start = str(datetime.today() - timedelta(days=datetime.today().weekday() % 7)).split(' ')[0]
Try this one:
HTML:
<div id="para1"></div>
JavaScript:
document.getElementById("para1").innerHTML = formatAMPM();
function formatAMPM() {
var d = new Date(),
minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(),
ampm = d.getHours() >= 12 ? 'pm' : 'am',
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
return days[d.getDay()]+' '+months[d.getMonth()]+' '+d.getDate()+' '+d.getFullYear()+' '+hours+':'+minutes+ampm;
}
Result:
Mon Sep 18 2017 12:40pm
The JSON spec says you CAN escape forward slash, but you don't have to.
Try:
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children:children...)
Use This code to find exact X and Y cordinates :
int[] array = new int[2];
ViewForWhichLocationIsToBeFound.getLocationOnScreen(array);
if (AppConstants.DEBUG)
Log.d(AppConstants.TAG, "array X = " + array[0] + ", Y = " + array[1]);
ViewWhichToBeMovedOnFoundLocation.setTranslationX(array[0] + 21);
ViewWhichToBeMovedOnFoundLocation.setTranslationY(array[1] - 165);
I have added/subtracted some values to adjust my view. Please do these lines only after whole view has been inflated.
For File Open only, the syntax is
,"one\n
two",...
The critical thing is that there is no space after the first ",". Normally spaces are fine, and trimmed if the string is not quoted. But otherwise nasty. Took me a while to figure that out.
It does not seem to matter if the line is ended \n or \c\n.
Make sure you expand the formula bar so you can actually see the text in the cell (got me after a long day...)
Now of course, File Open will not support UTF-8 Properly (unless one uses tricks).
Excel > Data > Get External Data > From Text
Can be set into UTF-8 mode (it is way down the list of fonts). However, in that case the new lines do not seem to work and I know no way to fix that.
(One might thing that after 30 years MS would get this stuff right.)
I'm using intelliJ 15 community edition and I'm able to right click a file and select 'add to .gitignore'
LayoutInflater
is used to generate dynamic views of the XML for the ListView
item or in onCreateView
of the fragment.
ConvertView
is basically used to recycle the views which are not in the view currently. Say you have a scrollable ListView
. On scrolling down or up, the convertView
gives the view which was scrolled. This reusage saves memory.
The parent parameter of the getView()
method gives a reference to the parent layout which has the listView. Say you want to get the Id of any item in the parent XML you can use:
ViewParent nv = parent.getParent();
while (nv != null) {
if (View.class.isInstance(nv)) {
final View button = ((View) nv).findViewById(R.id.remove);
if (button != null) {
// FOUND IT!
// do something, then break;
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("Remove", "Remove clicked");
((Button) button).setText("Hi");
}
});
}
break;
}
}
I would suggest using the new mixins approach described there: https://blogs.msdn.microsoft.com/typescript/2017/02/22/announcing-typescript-2-2/
This approach is better, than the "applyMixins" approach described by Fenton, because the autocompiler would help you and show all the methods / properties from the both base and 2nd inheritance classes.
This approach might be checked on the TS Playground site.
Here is the implementation:
class MainClass {
testMainClass() {
alert("testMainClass");
}
}
const addSecondInheritance = (BaseClass: { new(...args) }) => {
return class extends BaseClass {
testSecondInheritance() {
alert("testSecondInheritance");
}
}
}
// Prepare the new class, which "inherits" 2 classes (MainClass and the cass declared in the addSecondInheritance method)
const SecondInheritanceClass = addSecondInheritance(MainClass);
// Create object from the new prepared class
const secondInheritanceObj = new SecondInheritanceClass();
secondInheritanceObj.testMainClass();
secondInheritanceObj.testSecondInheritance();
How about this
$FQDN=[System.Net.Dns]::GetHostByName($VM).Hostname.Split('.')
[int]$i = 1
[int]$x = 0
[string]$Domain = $null
do {
$x = $i-$FQDN.Count
$Domain = $Domain+$FQDN[$x]+"."
$i = $i + 1
} until ( $i -eq $FQDN.Count )
$Domain = $Domain.TrimEnd(".")
As mentioned in my earlier answer, you can use RegExp.exec()
to iterate over all matches and count each occurrence; the advantage is limited to memory only, because on the whole it's about 20% slower than using String.match()
.
var re = /\s/g,
count = 0;
while (re.exec(text) !== null) {
++count;
}
return count;
Just an alternative to the code by rkosegi,
BEGIN
.. Declare statements ..
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
.. set any flags etc eg. SET @flag = 0; ..
ROLLBACK;
END;
START TRANSACTION;
.. Query 1 ..
.. Query 2 ..
.. Query 3 ..
COMMIT;
.. eg. SET @flag = 1; ..
END
I know this is an old question, but I'd like to suggest an NPM package I've created called smart-circular, which works differently from the other ways proposed. It's specially useful if you're using big and deep objects.
Some features are:
Replacing circular references or simply repeated structures inside the object by the path leading to its first occurrence (not just the string [circular]);
By looking for circularities in a breadth-first search, the package ensures this path is as small as possible, which is important when dealing with very big and deep objects, where the paths can get annoyingly long and difficult to follow (the custom replacement in JSON.stringify does a DFS);
Allows personalised replacements, handy to simplify or ignore less important parts of the object;
Finally, the paths are written exactly in the way necessary to access the field referenced, which can help you debugging.
.align {_x000D_
display: flex;_x000D_
width: 400px;_x000D_
height: 400px;_x000D_
border: solid 1px black;_x000D_
align-items: center;_x000D_
justify-content: space-around;_x000D_
}_x000D_
.align div:first-child {_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
background-color: red;_x000D_
position: absolute; _x000D_
}_x000D_
.align div {_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
background-color: blue;_x000D_
}
_x000D_
<div class='align'>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
</div>
_x000D_
First child will be aligned vertically and horizontally at center
Using ES6 syntax in React does not bind this
to user-defined functions however it will bind this
to the component lifecycle methods.
So the function that you declared will not have the same context as the class and trying to access this
will not give you what you are expecting.
For getting the context of class you have to bind the context of class to the function or use arrow functions.
Method 1 to bind the context:
class MyContainer extends Component {
constructor(props) {
super(props);
this.onMove = this.onMove.bind(this);
this.testVarible= "this is a test";
}
onMove() {
console.log(this.testVarible);
}
}
Method 2 to bind the context:
class MyContainer extends Component {
constructor(props) {
super(props);
this.testVarible= "this is a test";
}
onMove = () => {
console.log(this.testVarible);
}
}
Method 2 is my preferred way but you are free to choose your own.
Update: You can also create the properties on class without constructor:
class MyContainer extends Component {
testVarible= "this is a test";
onMove = () => {
console.log(this.testVarible);
}
}
Note If you want to update the view as well, you should use state
and setState
method when you set or change the value.
Example:
class MyContainer extends Component {
state = { testVarible: "this is a test" };
onMove = () => {
console.log(this.state.testVarible);
this.setState({ testVarible: "new value" });
}
}
here's the one that works for me:
from sqlalchemy import create_engine
import urllib
conn_str = (
r'Driver=ODBC Driver 13 for SQL Server;'
r'Server=DefinitelyNotProd;'
r'Database=PlayPen;'
r'Trusted_Connection=Yes;')
quoted_conn_str = urllib.parse.quote_plus(conn_str)
engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted_conn_str))
No one told what could cause this error, in case of migration from one host to another, remember about checking hostname in sudoers file:
So this is my /etc/sudoers config
User_Alias POWERUSER = user_name
Cmnd_Alias SKILL = /root/bin/sudo_auth_wrapper.sh
POWERUSER hostname=(root:root) NOPASSWD: SKILL
if it doesn't match
uname -a
Linux other_hostname 3.10.17 #1 SMP Wed Oct 23 16:28:33 CDT 2013 x86_64 Intel(R) Core(TM) i3-4130T CPU @ 2.90GHz GenuineIntel GNU/Linux
it will pop up this error:
no tty present and no askpass program specified
this will also work, if you like
xcopy C:\Test\Log "c:\Test\Backup-%date:~4,2%-%date:~7,2%-%date:~10,4%_%time:~0,2%%time:~3,2%" /s /i
del C:\Test\Log
You can get your code to work by just swapping the two terms:
if ($(target).parents('div#hello').length) {
You had the child and parent round the wrong way.
SP is the stack register a shortcut for typing r13. LR is the link register a shortcut for r14. And PC is the program counter a shortcut for typing r15.
When you perform a call, called a branch link instruction, bl, the return address is placed in r14, the link register. the program counter pc is changed to the address you are branching to.
There are a few stack pointers in the traditional ARM cores (the cortex-m series being an exception) when you hit an interrupt for example you are using a different stack than when running in the foreground, you dont have to change your code just use sp or r13 as normal the hardware has done the switch for you and uses the correct one when it decodes the instructions.
The traditional ARM instruction set (not thumb) gives you the freedom to use the stack in a grows up from lower addresses to higher addresses or grows down from high address to low addresses. the compilers and most folks set the stack pointer high and have it grow down from high addresses to lower addresses. For example maybe you have ram from 0x20000000 to 0x20008000 you set your linker script to build your program to run/use 0x20000000 and set your stack pointer to 0x20008000 in your startup code, at least the system/user stack pointer, you have to divide up the memory for other stacks if you need/use them.
Stack is just memory. Processors normally have special memory read/write instructions that are PC based and some that are stack based. The stack ones at a minimum are usually named push and pop but dont have to be (as with the traditional arm instructions).
If you go to http://github.com/lsasim I created a teaching processor and have an assembly language tutorial. Somewhere in there I go through a discussion about stacks. It is NOT an arm processor but the story is the same it should translate directly to what you are trying to understand on the arm or most other processors.
Say for example you have 20 variables you need in your program but only 16 registers minus at least three of them (sp, lr, pc) that are special purpose. You are going to have to keep some of your variables in ram. Lets say that r5 holds a variable that you use often enough that you dont want to keep it in ram, but there is one section of code where you really need another register to do something and r5 is not being used, you can save r5 on the stack with minimal effort while you reuse r5 for something else, then later, easily, restore it.
Traditional (well not all the way back to the beginning) arm syntax:
...
stmdb r13!,{r5}
...temporarily use r5 for something else...
ldmia r13!,{r5}
...
stm is store multiple you can save more than one register at a time, up to all of them in one instruction.
db means decrement before, this is a downward moving stack from high addresses to lower addresses.
You can use r13 or sp here to indicate the stack pointer. This particular instruction is not limited to stack operations, can be used for other things.
The ! means update the r13 register with the new address after it completes, here again stm can be used for non-stack operations so you might not want to change the base address register, leave the ! off in that case.
Then in the brackets { } list the registers you want to save, comma separated.
ldmia is the reverse, ldm means load multiple. ia means increment after and the rest is the same as stm
So if your stack pointer were at 0x20008000 when you hit the stmdb instruction seeing as there is one 32 bit register in the list it will decrement before it uses it the value in r13 so 0x20007FFC then it writes r5 to 0x20007FFC in memory and saves the value 0x20007FFC in r13. Later, assuming you have no bugs when you get to the ldmia instruction r13 has 0x20007FFC in it there is a single register in the list r5. So it reads memory at 0x20007FFC puts that value in r5, ia means increment after so 0x20007FFC increments one register size to 0x20008000 and the ! means write that number to r13 to complete the instruction.
Why would you use the stack instead of just a fixed memory location? Well the beauty of the above is that r13 can be anywhere it could be 0x20007654 when you run that code or 0x20002000 or whatever and the code still functions, even better if you use that code in a loop or with recursion it works and for each level of recursion you go you save a new copy of r5, you might have 30 saved copies depending on where you are in that loop. and as it unrolls it puts all the copies back as desired. with a single fixed memory location that doesnt work. This translates directly to C code as an example:
void myfun ( void )
{
int somedata;
}
In a C program like that the variable somedata lives on the stack, if you called myfun recursively you would have multiple copies of the value for somedata depending on how deep in the recursion. Also since that variable is only used within the function and is not needed elsewhere then you perhaps dont want to burn an amount of system memory for that variable for the life of the program you only want those bytes when in that function and free that memory when not in that function. that is what a stack is used for.
A global variable would not be found on the stack.
Going back...
Say you wanted to implement and call that function you would have some code/function you are in when you call the myfun function. The myfun function wants to use r5 and r6 when it is operating on something but it doesnt want to trash whatever someone called it was using r5 and r6 for so for the duration of myfun() you would want to save those registers on the stack. Likewise if you look into the branch link instruction (bl) and the link register lr (r14) there is only one link register, if you call a function from a function you will need to save the link register on each call otherwise you cant return.
...
bl myfun
<--- the return from my fun returns here
...
myfun:
stmdb sp!,{r5,r6,lr}
sub sp,#4 <--- make room for the somedata variable
...
some code here that uses r5 and r6
bl more_fun <-- this modifies lr, if we didnt save lr we wouldnt be able to return from myfun
<---- more_fun() returns here
...
add sp,#4 <-- take back the stack memory we allocated for the somedata variable
ldmia sp!,{r5,r6,lr}
mov pc,lr <---- return to whomever called myfun.
So hopefully you can see both the stack usage and link register. Other processors do the same kinds of things in a different way. for example some will put the return value on the stack and when you execute the return function it knows where to return to by pulling a value off of the stack. Compilers C/C++, etc will normally have a "calling convention" or application interface (ABI and EABI are names for the ones ARM has defined). if every function follows the calling convention, puts parameters it is passing to functions being called in the right registers or on the stack per the convention. And each function follows the rules as to what registers it does not have to preserve the contents of and what registers it has to preserve the contents of then you can have functions call functions call functions and do recursion and all kinds of things, so long as the stack does not go so deep that it runs into the memory used for globals and the heap and such, you can call functions and return from them all day long. The above implementation of myfun is very similar to what you would see a compiler produce.
ARM has many cores now and a few instruction sets the cortex-m series works a little differently as far as not having a bunch of modes and different stack pointers. And when executing thumb instructions in thumb mode you use the push and pop instructions which do not give you the freedom to use any register like stm it only uses r13 (sp) and you cannot save all the registers only a specific subset of them. the popular arm assemblers allow you to use
push {r5,r6}
...
pop {r5,r6}
in arm code as well as thumb code. For the arm code it encodes the proper stmdb and ldmia. (in thumb mode you also dont have the choice as to when and where you use db, decrement before, and ia, increment after).
No you absolutly do not have to use the same registers and you dont have to pair up the same number of registers.
push {r5,r6,r7}
...
pop {r2,r3}
...
pop {r1}
assuming there is no other stack pointer modifications in between those instructions if you remember the sp is going to be decremented 12 bytes for the push lets say from 0x1000 to 0x0FF4, r5 will be written to 0xFF4, r6 to 0xFF8 and r7 to 0xFFC the stack pointer will change to 0x0FF4. the first pop will take the value at 0x0FF4 and put that in r2 then the value at 0x0FF8 and put that in r3 the stack pointer gets the value 0x0FFC. later the last pop, the sp is 0x0FFC that is read and the value placed in r1, the stack pointer then gets the value 0x1000, where it started.
The ARM ARM, ARM Architectural Reference Manual (infocenter.arm.com, reference manuals, find the one for ARMv5 and download it, this is the traditional ARM ARM with ARM and thumb instructions) contains pseudo code for the ldm and stm ARM istructions for the complete picture as to how these are used. Likewise well the whole book is about the arm and how to program it. Up front the programmers model chapter walks you through all of the registers in all of the modes, etc.
If you are programming an ARM processor you should start by determining (the chip vendor should tell you, ARM does not make chips it makes cores that chip vendors put in their chips) exactly which core you have. Then go to the arm website and find the ARM ARM for that family and find the TRM (technical reference manual) for the specific core including revision if the vendor has supplied that (r2p0 means revision 2.0 (two point zero, 2p0)), even if there is a newer rev, use the manual that goes with the one the vendor used in their design. Not every core supports every instruction or mode the TRM tells you the modes and instructions supported the ARM ARM throws a blanket over the features for the whole family of processors that that core lives in. Note that the ARM7TDMI is an ARMv4 NOT an ARMv7 likewise the ARM9 is not an ARMv9. ARMvNUMBER is the family name ARM7, ARM11 without a v is the core name. The newer cores have names like Cortex and mpcore instead of the ARMNUMBER thing, which reduces confusion. Of course they had to add the confusion back by making an ARMv7-m (cortex-MNUMBER) and the ARMv7-a (Cortex-ANUMBER) which are very different families, one is for heavy loads, desktops, laptops, etc the other is for microcontrollers, clocks and blinking lights on a coffee maker and things like that. google beagleboard (Cortex-A) and the stm32 value line discovery board (Cortex-M) to get a feel for the differences. Or even the open-rd.org board which uses multiple cores at more than a gigahertz or the newer tegra 2 from nvidia, same deal super scaler, muti core, multi gigahertz. A cortex-m barely brakes the 100MHz barrier and has memory measured in kbytes although it probably runs of a battery for months if you wanted it to where a cortex-a not so much.
sorry for the very long post, hope it is useful.
Also you might want to log in via browser and get the command with all headers including cookies:
Open the Network tab of Developer Tools, log in, navigate to the needed page, use "Copy as cURL".
ReSharper does a great job of finding unused code.
In the VS IDE, you can right click on the definition and choose 'Find All References', although this only works at the solution level.
I tried some of the other answers here, but originalEvent was also undefined. Upon inspection, found a TouchList classed property (as suggested by another poster) and managed to get to pageX/Y this way:
var x = e.changedTouches[0].pageX;
Abstract example with clearer table and column names:
UPDATE tableName t1
INNER JOIN tableName t2 ON t2.ref_column = t1.ref_column
SET t1.column_to_update = t2.column_desired_value
As suggested by @Nico
Hope this help someone.
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
If you're using lodash and in the mood for a too-cute-for-its-own-good one-liner:
_.map(_.words('123, 124, 234,252'), _.add.bind(1, 1));
It's surprisingly robust thanks to lodash's powerful parsing capabilities.
If you want one that will also clean non-digit characters out of the string (and is easier to follow...and not quite so cutesy):
_.chain('123, 124, 234,252, n301')
.replace(/[^\d,]/g, '')
.words()
.map(_.partial(_.add, 1))
.value();
2017 edit:
I no longer recommend my previous solution. Besides being overkill and already easy to do without a third-party library, it makes use of _.chain, which has a variety of issues. Here's the solution I would now recommend:
const str = '123, 124, 234,252';
const arr = str.split(',').map(n => parseInt(n, 10) + 1);
My old answer is still correct, so I'll leave it for the record, but there's no need to use it nowadays.
Windows imposes a memory limit per process, you can see what it is for each version here
See:
User-mode virtual address space for each 64-bit process;
With IMAGE_FILE_LARGE_ADDRESS_AWARE set (default):
x64: 8 TB
Intel IPF: 7 TB
2 GB with IMAGE_FILE_LARGE_ADDRESS_AWARE cleared
I already said that I was new to exec()
function. After doing some more digging, I came upon 2>&1
which needs to be added at the end of command in exec()
.
Thanks @mattosmat
for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.
So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.
For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.
exec('some_command 2>&1', $output);
print_r($output); // to see the response to your command
Thanks for all the help guys, I appreciate it ;)
Just import in this way, WORKS perfectly:
// Import HttpModule from @angular/http
import {HttpModule} from '@angular/http';
@NgModule({
declarations: [
MyApp,
HelloIonicPage,
ItemDetailsPage,
ListPage
],
imports: [
BrowserModule,
HttpModule,
IonicModule.forRoot(MyApp),
],
bootstrap: [...],
entryComponents: [...],
providers: [... ]
})
and then you contruct in the service.ts like this:
constructor(private http: Http) { }
getmyClass(): Promise<myClass[]> {
return this.http.get(URL)
.toPromise()
.then(response => response.json().data as myClass[])
.catch(this.handleError);
}
This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.
old way to achieve the same thing was:
var functionCaller = this.member;
if (functionCaller!= null)
functionCaller.someFunction(var someParam);
and now it has been made much easier with just:
member?.someFunction(var someParam);
I strongly recommend this doc page.
Python's sets (and dictionaries) will iterate and print out in some order, but exactly what that order will be is arbitrary, and not guaranteed to remain the same after additions and removals.
Here's an example of a set changing order after a lot of values are added and then removed:
>>> s = set([1,6,8])
>>> print(s)
{8, 1, 6}
>>> s.update(range(10,100000))
>>> for v in range(10, 100000):
s.remove(v)
>>> print(s)
{1, 6, 8}
This is implementation dependent though, and so you should not rely upon it.
Just set the frame property of the tableHeaderView.
I followed everything from here: https://cloud.google.com/compute/docs/instances/connecting-to-instance#generatesshkeypair
But still there was an error and SSH keys in my instance metadata wasn't getting recognized.
Solution: Check if your ssh key has any new-line. When I copied my public key using cat, it added into-lines into the key, thus breaking the key. Had to manually check any line-breaks and correct it.
VB Code:
Dim ListItem1 As New ListItem()
ListItem1.Text = "put anything here"
ListItem1.Value = "0"
drpTag.DataBind()
drpTag.Items.Insert(0, ListItem1)
View:
<asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="CompareValidator" ControlToValidate="drpTag"
ValueToCompare="0">
</asp:CompareValidator>
You can use $http.get()
method to fetch your JSON
file. Then assign response data to a $scope
object. In HTML
to create table use ng-repeat for $scope object. ng-repeat
will loop the rows in-side this loop you can bind data to columns dynamically.
I have checked your code and you have created static table
<table>
<tr>
<th>Name</th>
<th>Relationship</th>
</tr>
<tr ng-repeat="indivisual in members">
<td>{{ indivisual.Name }}</td>
<td>{{ indivisual.Relation }}</td>
</tr>
</table>
so better your can go to my code to create dynamic table as per data you column and row will be increase or decrease..
I would say "Yes". As "Matz" had said something like this in one of his talks, "Ruby objects have no types." Not all of it but the part that he is trying to get across to us. Why would anyone have said "Everything is an Object" then? To add he said "Data has Types not objects".
So we might enjoy this.
https://www.youtube.com/watch?v=1l3U1X3z0CE
But Ruby doesn't care to much about the type of object just the class. We use classes not types. All data then has a class.
12345.class
'my string'.class
They may also have ancestors
Object.ancestors
They also have meta classes but I'll save you the details on that.
Once you know the class then you'll be able to lookup what methods you may use for it. That's where the "data type" is needed. If you really want to get into details the look up...
"The Ruby Object Model"
This is the term used for how Ruby handles objects. It's all internal so you don't really see much of this but it's nice to know. But that's another topic.
Yes! The class is the data type. Objects have classes and data has types. So if you know about data bases then you know there are only a finite set of types.
text blocks numbers
Found an addendum to this question:
If you want to change the visibility of your menu items on the go you just need to set a member variable in your activity to remember that you want to hide the menu and call invalidateOptionsMenu()
and hide the items in your overridden onCreateOptionsMenu(...)
method.
//anywhere in your code
...
mState = HIDE_MENU; // setting state
invalidateOptionsMenu(); // now onCreateOptionsMenu(...) is called again
...
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// inflate menu from xml
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.settings, menu);
if (mState == HIDE_MENU)
{
for (int i = 0; i < menu.size(); i++)
menu.getItem(i).setVisible(false);
}
}
In my example I've hidden all items.
By definition dictionaries are unordered, and therefore cannot be indexed. For that kind of functionality use an ordered dictionary. Python Ordered Dictionary
in Macbooks, you can use shift + cmd + 7 to comment a previously highlighted block
This may have changed since the question was asked, but there is a difference between stopping an instance and terminating an instance.
If your instance is EBS-based, it can be stopped. It will remain in your account, but you will not be charged for it (you will continue to be charged for EBS storage associated with the instance and unused Elastic IP addresses). You can re-start the instance at any time.
If the instance is terminated, it will be deleted from your account. You’ll be charged for any remaining EBS volumes, but by default the associated EBS volume will be deleted. This can be configured when you create the instance using the command-line EC2 API Tools.
you certainly won't succeed with
tail -f /var/log/foo.log |grep --line-buffered string2search
when you use "colortail" as an alias for tail, eg. in bash
alias tail='colortail -n 30'
you can check by
type alias
if this outputs something like
tail isan alias of colortail -n 30
.
then you have your culprit :)
Solution:
remove the alias with
unalias tail
ensure that you're using the 'real' tail binary by this command
type tail
which should output something like:
tail is /usr/bin/tail
and then you can run your command
tail -f foo.log |grep --line-buffered something
Good luck.
HTML:
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
jQuery
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
Try this:
div{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
background: red;
}
Here div is html tag. You wrote a html tag followed by a dot that is wrong.Only a class is written followed by dot.
Do you want to chain the Task
s, or can they be invoked in a parallel manner?
For chaining
Just do something like
Task.Run(...).ContinueWith(...).ContinueWith(...).ContinueWith(...);
Task.Factory.StartNew(...).ContinueWith(...).ContinueWith(...).ContinueWith(...);
and don't forget to check the previous Task
instance in each ContinueWith
as it might be faulted.
For the parallel manner
The most simple method I came across: Parallel.Invoke
Otherwise there's Task.WaitAll
or you can even use WaitHandle
s for doing a countdown to zero actions left (wait, there's a new class: CountdownEvent
), or ...
Just define:
#define M_PI acos(-1.0)
It should give you exact PI number that math functions are working with. So if they change PI value they are working with in tangent or cosine or sine, then your program should be always up-to-dated ;)
This is the solution but you have to set:
echo 1 > /proc/sys/vm/overcommit_memory
Put the date in single quotes and move the parenthesis (after the 'yes'
) to the end:
INSERT INTO custorder
VALUES ('Kevin', 'yes' , STR_TO_DATE('1-01-2012', '%d-%m-%Y') ) ;
^ ^
---parenthesis removed--| and added here ------|
But you can always use dates without STR_TO_DATE()
function, just use the (Y-m-d) '20120101'
or '2012-01-01'
format. Check the MySQL docs: Date and Time Literals
INSERT INTO custorder
VALUES ('Kevin', 'yes', '2012-01-01') ;
often this is due to missing permissions. The windows account the local IIS Application Pool is running with may not have the permission to write to the applications directory. You could create a directory somewhere, give everyone permission to write in it and point your log4net config to that directory. If then a log file is created there, you can modify the permissions for your desired log directory so that the app pool can write to it.
Another reason could be an uninitialized log4net. In a winforms app, you usually configure log4net upon application start. In a web app, you can do this either dynamically (in your logging component, check if you can create a specific Ilog logger using its name, if not -> call configure()) or again upon application start in global.asax.cs.
This worked for me
textview.setTypeface(textview.getTypeface(), Typeface.BOLD);
or
textview.setTypeface(Typeface.DEFAULT_BOLD);
There has been some major changes in ms 2008 -> Might be worth considering the following article when making a decisions on what data type to use. http://msdn.microsoft.com/en-us/library/ms143432.aspx
Bytes per
In the current version of Sublime Text 2 (Build: 2139), you can set the syntax for all files of a certain file extension using an option in the menu bar. Open a file with the extension you want to set a default for and navigate through the following menus: View -> Syntax -> Open all with current extension as... ->[your syntax choice]
.
Updated 2012-06-28: Recent builds of Sublime Text 2 (at least since Build 2181) have allowed the syntax to be set by clicking the current syntax type in the lower right corner of the window. This will open the syntax selection menu with the option to Open all with current extension as...
at the top of the menu.
Updated 2016-04-19: As of now, this also works for Sublime Text 3.
Why not use the JPDA and attach to the launched process from a separate debugger process ? You should be able to specify the appropriate options in Maven to launch your process with the debugging hooks enabled. This article has more information.
It is possible to reference an intellij 'Path Variable' in an intellij 'Run Configuration'.
In 'Path Variables' create a variable for example ANALYTICS_VERSION
.
In a 'Run Configuration' under 'Environment Variables' add for example the following:
ANALYTICS_LOAD_LOCATION=$MAVEN_REPOSITORY$\com\my\company\analytics\$ANALYTICS_VERSION$\bin
To answer the original question you would need to add an APP_HOME
environment variable to your run configuration which references the path variable:
APP_HOME=$APP_HOME$
Alternatively you can use a Docker image which already has ping installed, e.g. busybox:
docker run --rm busybox ping SERVER_NAME -c 2
If your server is Ubuntu and Apache version is 2.4
Server version: Apache/2.4.29 (Ubuntu)
Then you export variables in "/etc/apache2/envvars" location.
Just like this below line, you need to add an extra line in "/etc/apache2/envvars" export GOROOT=/usr/local/go
For those who have the similar problem trying to connect to local db and trying like
con = psycopg2.connect(database="my_db", user="my_name", password="admin")
, try to pass the additional parameter, so the following saved me a day:
con = psycopg2.connect(database="my_db", user="my_name", password="admin", host="localhost")
Rather than using a DisplayFilter you could use a very simple CaptureFilter like
port 53
See the "Capture only DNS (port 53) traffic" example on the CaptureFilters wiki.
Only second approach will work. You can modify collection during iteration using iterator.remove()
only. All other attempts will cause ConcurrentModificationException
.
I believe we can start from basic to achieve desired result.
For example, I had a situation to extract data after "/". The given excel field had a value of 2rko6xyda14gdl7/VEERABABU%20MATCHA%20IN131621.jpg . I simply wanted to extract the text from "I5" cell after slash symbol. So firstly I want to find where "/" symbol is (FIND("/",I5). This gives me the position of "/". Then I should know the length of text, which i can get by LEN(I5).so total length minus the position of "/" . which is LEN(I5)-(FIND("/",I5)) . This will first find the "/" position and then get me the total text that needs to be extracted. The RIGHT function is RIGHT(I5,12) will simply extract all the values of last 12 digits starting from right most character. So I will replace the above function "LEN(I5)-(FIND("/",I5))" for 12 number in the RIGHT function to get me dynamically the number of characters I need to extract in any given cell and my solution is presented as given below
The approach was
=RIGHT(I5,LEN(I5)-(FIND("/",I5))) will give me out as VEERABABU%20MATCHA%20IN131621.jpg . I think I am clear.
Assuming SQL Server:
e.g. if you class special characters as anything NOT alphanumeric:
DECLARE @MyString VARCHAR(100)
SET @MyString = 'adgkjb$'
IF (@MyString LIKE '%[^a-zA-Z0-9]%')
PRINT 'Contains "special" characters'
ELSE
PRINT 'Does not contain "special" characters'
Just add to other characters you don't class as special, inside the square brackets
Here is a pretty easy way to do it.
val data = List("it", "was", "the", "best", "of", "times", "it", "was",
"the", "worst", "of", "times")
data.foldLeft(Map[String,Int]().withDefaultValue(0)){
case (acc, letter) =>
acc + (letter -> (1 + acc(letter)))
}
// => Map(worst -> 1, best -> 1, it -> 2, was -> 2, times -> 2, of -> 2, the -> 2)
Like explained in other answers you need to provide a comparison function. If
you would like to keep the definition of that function close to the sort
call (e.g. if it only makes sense for this sort) you can define it right there
with boost::lambda
. Use boost::lambda::bind
to call the member function.
To e.g. sort by member variable or function data1
:
#include <algorithm>
#include <vector>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
using boost::lambda::bind;
using boost::lambda::_1;
using boost::lambda::_2;
std::vector<myclass> object(10000);
std::sort(object.begin(), object.end(),
bind(&myclass::data1, _1) < bind(&myclass::data1, _2));
100,000 should be fine.
I have (anecdotally) seen people having problems with many millions of files and I have had problems myself with Explorer just not having a clue how to count past 60-something thousand files, but NTFS should be good for the volumes you're talking.
In case you're wondering, the technical (and I hope theoretical) maximum number of files is: 4,294,967,295
A complete solution in swift, in your view controller
// you can use your own logic to determine if you need to hide status bar
// I just put a var here for now
var hideStatusBar = false
override func preferStatusBarHidden() -> Bool {
return hideStatus
}
// in other method to manually toggle status bar
func updateUI() {
hideStatusBar = true
// call this method to update status bar
prefersStatusBarHidden()
}
You can't put a border on a tr element. This worked for me in firefox and IE 11:
<td style='border-bottom:1pt solid black'>
In addition, you can change Eclipse shortcut in Windows -> Preferences -> General -> Keys
var strUser = e.options[e.selectedIndex].value;
This is correct and should give you the value. Is it the text you're after?
var strUser = e.options[e.selectedIndex].text;
So you're clear on the terminology:
<select>
<option value="hello">Hello World</option>
</select>
This option has:
For API level 23 (Marshmallow) and later, additional to uses-permission in manifest, pop up permission should also be implemented, and user needs to grant it while using the app in run-time.
Below, there is an example to save hello world!
as content of myFile.txt
file in Test
directory inside picture directory.
In the manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Where you want to create the file:
int permission = ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (permission != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,PERMISSIONS_STORAGE, 1);
}
File myDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Test");
myDir.mkdirs();
try
{
String FILENAME = "myFile.txt";
File file = new File (myDir, FILENAME);
String string = "hello world!";
FileOutputStream fos = new FileOutputStream(file);
fos.write(string.getBytes());
fos.close();
}
catch (IOException e) {
e.printStackTrace();
}
Use the ajaxStop
event.
For example, let's say you have a loading ... message while fetching 100 ajax requests and you want to hide that message once loaded.
From the jQuery doc:
$("#loading").ajaxStop(function() {
$(this).hide();
});
Do note that it will wait for all ajax requests being done on that page.
For GitLab users I've put up a gist on how I migrated from SVN here:
https://gist.github.com/leftclickben/322b7a3042cbe97ed2af
svn.domain.com.au
.http
(other protocols should work).git.domain.com.au
and:
dev-team
.ssh [email protected]
).favourite-project
is created in the dev-team
namespace.users.txt
contains the relevant user details, one user per line, of the form username = First Last <[email protected]>
, where username
is the username given in SVN logs. (See first link in References section for details, in particular answer by user Casey).bash
git svn clone --stdlayout --no-metadata -A users.txt
http://svn.domain.com.au/svn/repository/favourite-project
cd favourite-project
git remote add gitlab [email protected]:dev-team/favourite-project.git
git push --set-upstream gitlab master
That's it! Reload the project page in GitLab web UI and you will see all commits and files now listed.
git svn clone
command will stop, in which case, update users.txt
, cd favourite-project
and git svn fetch
will continue from where it stopped.trunk
-tags
-branches
layout for SVN repository is required.git svn clone
command stops at the level immediately above trunk/
, tags/
and branches/
.git svn clone
command produces a lot of output, including some warnings at the top; I ignored the warnings.Judging by the desktop folder location you are using Windows. The command in Windows would be:
adb pull /sdcard/log.txt %USERPROFILE%\Desktop\
Use map.panTo();
does not do anything if the point is in the current view. Use map.setView()
instead.
I had a polyline and I had to center map to a new point in polyline at every second. Check the code : GOOD: https://jsfiddle.net/nstudor/xcmdwfjk/
mymap.setView(point, 11, { animation: true });
BAD: https://jsfiddle.net/nstudor/Lgahv905/
mymap.panTo(point);
mymap.setZoom(11);
\n
must be in double quotes!
echo "hello\nworld";
Output
hello
world
A nice way around this is to use PHP as a more of a templating language
<p>
Hello <span><?php echo $world ?></span>
</p>
Output
<p>
Hello <span>Planet Earth</span>
</p>
Notice, all newlines are kept in tact!
In case someone doesn't fix the problem use methods above. I fixed mine by surrounding the async func by an arrow function. As in:
describe("Profile Tab Exists and Clickable: /settings/user", () => {
test(`Assert that you can click the profile tab`, (() => {
async () => {
await page.waitForSelector(PROFILE.TAB)
await page.click(PROFILE.TAB)
}
})(), 30000);
});
From the core javascript reference
===
Returnstrue
if the operands are strictly equal (see above) with no type conversion.
svn move
— Move a file or directory.
In addition to what the other answers have said, note that the '/' character in "dd/MM/yyyy" is not a literal character: it represents the date separator of the current user's culture. Therefore, if the current culture uses yyyy-MM-dd dates, then when you call toString it will give you a date such as "31-12-2016" (using dashes instead of slashes). To force it to use slashes, you need to escape that character:
DateTime.Now.ToString("dd/MM/yyyy") --> "19-12-2016" for a Japanese user
DateTime.Now.ToString("dd/MM/yyyy") --> "19/12/2016" for a UK user
DateTime.Now.ToString("dd\\/MM\\/yyyy") --> "19/12/2016" independent of region
I had faced the same problem while accessing any hard drive directory. Then I solved it in this way.
import os
os.startfile("D:\folder_name\file_name") #running shortcut
os.startfile("F:") #accessing directory
The picture above shows an error and resolved output.
You need then a wrapping element with the bg image and in it the content element with the bg color:
<div id="Wrapper">
<div id="Content">
<!-- content here -->
</div>
</div>
and the css:
#Wrapper{
background:url(../img/bg/diagonalnoise.png);
width:300px;
height:300px;
}
#Content{
background-color:rgba(248,247,216,0.7);
width:100%;
height:100%;
}
Using [name=elementName]{}
without tag before will work too.
It will affect all elements with this name.
For example:
[name=test] {_x000D_
width: 100px;_x000D_
}
_x000D_
<input type=text name=test>_x000D_
<div name=test></div>
_x000D_
If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:
Dictionary<string, ArrayList> result = target.GetComponents()
.ToDictionary(x => x.Key, x => x.Value);
There's no such thing as an IEnumerable<T1, T2>
but a KeyValuePair<TKey, TValue>
is fine.
you can try this
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
It will remove all the data from the model and reset it.
one more approach to use.
first, define the following somewhere on the page:
<div id="valueHolderId">${someValue}</div>
then in JS, just do something similar to
var someValue = $('#valueHolderId').html();
it works great for the cases when all scripts are inside .js files and obviously there is no jstl available
Whereas the most prevalent practice are RESTful apis where plurals are used e.g. /api/resources/123
, there is one special case where I find use of a singular name more appropriate/expressive than plural names. It is the case of one-to-one relationships. Specifically if the target item is a value object(in Domain-driven-design paradigm).
Let us assume every resource has a one-to-one accessLog
which could be modeled as a value object i.e not an entity therefore no ID. It could be expressed as /api/resources/123/accessLog
. The usual verbs (POST, PUT, DELETE, GET) would appropriately express the intent and also the fact that the relationship is indeed one-to-one.
In the service project do the following:
Now you need to make a setup project. The best thing to do is use the setup wizard.
Right click on your solution and add a new project: Add > New Project > Setup and Deployment Projects > Setup Wizard
a. This could vary slightly for different versions of Visual Studio. b. Visual Studio 2010 it is located in: Install Templates > Other Project Types > Setup and Deployment > Visual Studio Installer
On the second step select "Create a Setup for a Windows Application."
On the 3rd step, select "Primary output from..."
Click through to Finish.
Next edit your installer to make sure the correct output is included.
You can edit the installer output name by right clicking the Installer project in your solution and select Properties. Change the 'Output file name:' to whatever you want. By selecting the installer project as well and looking at the properties windows, you can edit the Product Name
, Title
, Manufacturer
, etc...
Next build your installer and it will produce an MSI and a setup.exe. Choose whichever you want to use to deploy your service.
pd.wide_to_long
You can add a prefix to your year columns and then feed directly to pd.wide_to_long
. I won't pretend this is efficient, but it may in certain situations be more convenient than pd.melt
, e.g. when your columns already have an appropriate prefix.
df.columns = np.hstack((df.columns[:2], df.columns[2:].map(lambda x: f'Value{x}')))
res = pd.wide_to_long(df, stubnames=['Value'], i='name', j='Date').reset_index()\
.sort_values(['location', 'name'])
print(res)
name Date location Value
0 test Jan-2010 A 12
2 test Feb-2010 A 20
4 test March-2010 A 30
1 foo Jan-2010 B 18
3 foo Feb-2010 B 20
5 foo March-2010 B 25
npm has a few packages, but none have reached 1.0 yet. Best picks from npm list mail
:
[email protected]
[email protected]
[email protected]
You can also use redirect()
method like this:-
return redirect('https://stackoverflow.com/');
As already recommended, you can use tree
. But for using it together with restructured text some additional parameters were required.
The standard tree
output will not be printed if your're using pandoc
to produce pdf.
tree --dirsfirst --charset=ascii /path/to/directory
will produce a nice ASCII
tree that can be integrated into your document like this:
.. code::
.
|-- ContentStore
| |-- de-DE
| | |-- art.mshc
| | |-- artnoloc.mshc
| | |-- clientserver.mshc
| | |-- noarm.mshc
| | |-- resources.mshc
| | `-- windowsclient.mshc
| `-- en-US
| |-- art.mshc
| |-- artnoloc.mshc
| |-- clientserver.mshc
| |-- noarm.mshc
| |-- resources.mshc
| `-- windowsclient.mshc
`-- IndexStore
|-- de-DE
| |-- art.mshi
| |-- artnoloc.mshi
| |-- clientserver.mshi
| |-- noarm.mshi
| |-- resources.mshi
| `-- windowsclient.mshi
`-- en-US
|-- art.mshi
|-- artnoloc.mshi
|-- clientserver.mshi
|-- noarm.mshi
|-- resources.mshi
`-- windowsclient.mshi
In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using
<encoder>
<pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern>
</encoder>
the %ex in pattern is what makes the difference
The easiest way to do it is:
vector<int> ints = {10, 20, 30};
Actually link to .well-know
is on the first tab of your realm settings - but link doesn't look like link, but as value of text box... bad ui design.
Screenshot of Realm's General Tab
Try this Script:
function addclassName(){
setTimeout(function(){
var c = document.querySelectorAll(".modal-backdrop");
for (var i = 0; i < c.length; i++) {
c[i].style.zIndex = 1040 + i * 20 ;
}
var d = document.querySelectorAll(".modal.fade");
for(var i = 0; i<d.length; i++){
d[i].style.zIndex = 1050 + i * 20;
}
}, 10);
}
Below solution tested and its working, hope it will support in your project.
HTML code:
<input type="file" name="asgnmnt_file" id="asgnmnt_file" class="span8"
style="display:none;" onchange="fileSelected(this)">
<br><br>
<img id="asgnmnt_file_img" src="uploads/assignments/abc.jpg" width="150" height="150"
onclick="passFileUrl()" style="cursor:pointer;">
JavaScript code:
function passFileUrl(){
document.getElementById('asgnmnt_file').click();
}
function fileSelected(inputData){
document.getElementById('asgnmnt_file_img').src = window.URL.createObjectURL(inputData.files[0])
}
Does c# have its own version of the java "synchronized" keyword?
No. In C#, you explicitly lock
resources that you want to work on synchronously across asynchronous threads. lock
opens a block; it doesn't work on method level.
However, the underlying mechanism is similar since lock
works by invoking Monitor.Enter
(and subsequently Monitor.Exit
) on the runtime. Java works the same way, according to the Sun documentation.
When you say
(a['x']==1) and (a['y']==10)
You are implicitly asking Python to convert (a['x']==1)
and (a['y']==10)
to boolean values.
NumPy arrays (of length greater than 1) and Pandas objects such as Series do not have a boolean value -- in other words, they raise
ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
when used as a boolean value. That's because its unclear when it should be True or False. Some users might assume they are True if they have non-zero length, like a Python list. Others might desire for it to be True only if all its elements are True. Others might want it to be True if any of its elements are True.
Because there are so many conflicting expectations, the designers of NumPy and Pandas refuse to guess, and instead raise a ValueError.
Instead, you must be explicit, by calling the empty()
, all()
or any()
method to indicate which behavior you desire.
In this case, however, it looks like you do not want boolean evaluation, you want element-wise logical-and. That is what the &
binary operator performs:
(a['x']==1) & (a['y']==10)
returns a boolean array.
By the way, as alexpmil notes,
the parentheses are mandatory since &
has a higher operator precedence than ==
.
Without the parentheses, a['x']==1 & a['y']==10
would be evaluated as a['x'] == (1 & a['y']) == 10
which would in turn be equivalent to the chained comparison (a['x'] == (1 & a['y'])) and ((1 & a['y']) == 10)
. That is an expression of the form Series and Series
.
The use of and
with two Series would again trigger the same ValueError
as above. That's why the parentheses are mandatory.
In Swift 3 there is addingPercentEncoding
let originalString = "test/test"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
print(escapedString!)
Output:
test%2Ftest
In iOS 7 and above there is stringByAddingPercentEncodingWithAllowedCharacters
var originalString = "test/test"
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
println("escapedString: \(escapedString)")
Output:
test%2Ftest
The following are useful (inverted) character sets:
URLFragmentAllowedCharacterSet "#%<>[\]^`{|}
URLHostAllowedCharacterSet "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet "#%<>[\]^`{|}
URLUserAllowedCharacterSet "#%/:<>?@[\]^`
If you want a different set of characters to be escaped create a set:
Example with added "=" character:
var originalString = "test/test=42"
var customAllowedSet = NSCharacterSet(charactersInString:"=\"#%/<>?@\\^`{|}").invertedSet
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
println("escapedString: \(escapedString)")
Output:
test%2Ftest%3D42
Example to verify ascii characters not in the set:
func printCharactersInSet(set: NSCharacterSet) {
var characters = ""
let iSet = set.invertedSet
for i: UInt32 in 32..<127 {
let c = Character(UnicodeScalar(i))
if iSet.longCharacterIsMember(i) {
characters = characters + String(c)
}
}
print("characters not in set: \'\(characters)\'")
}
You will find multiple different methods that people use and they each have there own place.
<?php if($first_condition): ?>
/*$first_condition is true*/
<?php elseif ($second_condition): ?>
/*$first_condition is false and $second_condition is true*/
<?php else: ?>
/*$first_condition and $second_condition are false*/
<?php endif; ?>
If in your php.ini attribute short_open_tag = true
(this is normally found on line 141
of the default php.ini file) you can replace your php open tag from <?php
to <?
. This is not advised as most live server environments have this turned off (including many CMS's like Drupal, WordPress and Joomla). I have already tested short hand open tags in Drupal and confirmed that it will break your site, so stick with <?php
. short_open_tag
is not on by default in all server configurations and must not be assumed as such when developing for unknown server configurations. Many hosting companies have short_open_tag
turned off.
A quick search of short_open_tag
in stackExchange shows 830 results. https://stackoverflow.com/search?q=short_open_tag
That's a lot of people having problems with something they should just not play with.
with some server environments and applications, short hand php open tags will still crash your code even with short_open_tag
set to true
.
short_open_tag
will be removed in PHP6 so don't use short hand tags.
all future PHP versions will be dropping short_open_tag
"It's been recommended for several years that you not use the short tag "short cut" and instead to use the full tag combination. With the wide spread use of XML and use of these tags by other languages, the server can become easily confused and end up parsing the wrong code in the wrong context. But because this short cut has been a feature for such a long time, it's currently still supported for backwards compatibility, but we recommend you don't use them." – Jelmer Sep 25 '12 at 9:00 php: "short_open_tag = On" not working
and
Normally you write PHP like so: . However if allow_short_tags directive is enabled you're able to use: . Also sort tags provides extra syntax: which is equal to .
Short tags might seem cool but they're not. They causes only more problems. Oh... and IIRC they'll be removed from PHP6. Crozin answered Aug 24 '10 at 22:12 php short_open_tag problem
and
To answer the why part, I'd quote Zend PHP 5 certification guide: "Short tags were, for a time, the standard in the PHP world; however, they do have the major drawback of conflicting with XML headers and, therefore, have somewhat fallen by the wayside." – Fluffy Apr 13 '11 at 14:40 Are PHP short tags acceptable to use?
You may also see people use the following example:
<?php if($first_condition){ ?>
/*$first_condition is true*/
<?php }else if ($second_condition){ ?>
/*$first_condition is false and $second_condition is true*/
<?php }else{ ?>
/*$first_condition and $second_condition are false*/
<?php } ?>
This will work but it is highly frowned upon as it's not considered as legible and is not what you would use this format for. If you had a PHP file where you had a block of PHP code that didn't have embedded tags inside, then you would use the bracket format.
The following example shows when to use the bracket method
<?php
if($first_condition){
/*$first_condition is true*/
}else if ($second_condition){
/*$first_condition is false and $second_condition is true*/
}else{
/*$first_condition and $second_condition are false*/
}
?>
If you're doing this code for yourself you can do what you like, but if your working with a team at a job it is advised to use the correct format for the correct circumstance. If you use brackets in embedded html/php scripts that is a good way to get fired, as no one will want to clean up your code after you. IT bosses will care about code legibility and college professors grade on legibility.
UPDATE
based on comments from duskwuff its still unclear if shorthand is discouraged (by the php standards) or not. I'll update this answer as I get more information. But based on many documents found on the web about shorthand being bad for portability. I would still personally not use it as it gives no advantage and you must rely on a setting being on that is not on for every web host.
@jonrsharpe has an excellent explanation of what's going on. I thought I'd just show the difference in time when running each of the 3 options 10,000,000 times (enough for a slight difference to show).
Code used:
def a(x):
if x != 'val':
pass
def b(x):
if not x == 'val':
pass
def c(x):
if x == 'val':
pass
else:
pass
x = 1
for i in range(10000000):
a(x)
b(x)
c(x)
And the cProfile profiler results:
So we can see that there is a very minute difference of ~0.7% between if not x == 'val':
and if x != 'val':
. Of these, if x != 'val':
is the fastest.
However, most surprisingly, we can see that
if x == 'val':
pass
else:
is in fact the fastest, and beats if x != 'val':
by ~0.3%. This isn't very readable, but I guess if you wanted a negligible performance improvement, one could go down this route.
The logic here is not quite correct, you need to check every letter to determine if the word is a palindrome. Currently, you print multiple times. What about doing something like:
function checkPalindrome(word) {
var l = word.length;
for (var i = 0; i < l / 2; i++) {
if (word.charAt(i) !== word.charAt(l - 1 - i)) {
return false;
}
}
return true;
}
if (checkPalindrome("1122332211")) {
document.write("The word is a palindrome");
} else {
document.write("The word is NOT a palindrome");
}
Which should print that it IS indeed a palindrome.
MySQL example:
import MySQLdb as db
from pandas import DataFrame
from pandas.io.sql import frame_query
database = db.connect('localhost','username','password','database')
data = frame_query("SELECT * FROM data", database)
If, like me, you are trying to use GETDATE()
within an expression and have the seemingly unreasonable requirement (SSIS/SSDT seems very much a work in progress to me, and not a polished offering) of wanting that date to get inserted into SQL Server as a valid date (type = datetime
), then I found this expression to work:
@[User::someVar] = (DT_WSTR,4)YEAR(GETDATE()) + "-" + RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()), 2) + "-" + RIGHT("0" + (DT_WSTR,2)DAY( GETDATE()), 2) + " " + RIGHT("0" + (DT_WSTR,2)DATEPART("hh", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("mi", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("ss", GETDATE()), 2)
I found this code snippet HERE
it sometimes occurs when we use a custom adapter in any activity of fragment . and we return null object i.e null view so the activity gets confused which view to load , so that is why this exception occurs
When the workbook first opens, execute this code:
alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"
Then just have a macro in the workbook called "EventMacro" that will repeat it.
Public Sub EventMacro()
'... Execute your actions here'
alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"
End Sub
You also could use simpler regex designed for your case like (.*)\/(([^\?\n\r])*)
where $2
match what you want.
Based on link you've provided, right answer should be
Math.floor(Math.random()*899999+100000);
Math.random() returns float between 0 and 1, so minimum number will be 100000, max - 999999. Exactly 6 digits, as you wanted :)
You simply use this in one row.
$query = $this->db->get_where('mytable',array('id'=>'3'));
I've used it in the case where something may have gone awry in my @Before method.
public Object obj;
@Before
public void setUp() {
// Do some set up
obj = new Object();
}
@Test
public void testObjectManipulation() {
if(obj == null) {
fail("obj should not be null");
}
// Do some other valuable testing
}
If you are not root user then, use following commands:
There are two ways to do it -
1.
sudo vi path_to_file/file_name
Press Esc and then type below respectively
:wq //save and exit :q! //exit without saving
When using nano: after you finish editing press ctrl+x then it will ask save Y/N.
If you want to save press Y, if not press N. And press enter to exit the editor.
use the timeIntervalSince1970 function of the NSDate class like below:
double start = [startDate timeIntervalSince1970];
double end = [endDate timeIntervalSince1970];
double difference = end - start;
basically, this is what i use to compare the difference in seconds between 2 different dates. also check this link here
ES6 modules support in Node.js is fairly recent; even in the bleeding-edge versions, it is still experimental. With Node.js 10, you can start Node.js with the --experimental-modules
flag, and it will likely work.
To import on older Node.js versions - or standard Node.js 10 - use CommonJS syntax:
const fs = require('fs');
Probably is the use of the "on" event that Bootstrap use a lot and was inserted at jQuery 1.7 http://api.jquery.com/on/
If the bandwidth is far higher than the bitrate, I would recommend TCP for unicast live video streaming.
Case 1: Consecutive packets are lost for a duration of several seconds. => live video will stop on the client side whatever the transport layer is (TCP or UDP). When the network recovers: - if TCP is used, client video player can choose to restart the stream at the first packet lost (timeshift) OR to drop all late packets and to restart the video stream with no timeshift. - if UDP is used, there is no choice on the client side, video restart live without any timeshift. => TCP equal or better.
Case 2: some packets are randomly and often lost on the network. - if TCP is used, these packets will be immediately retransmitted and with a correct jitter buffer, there will be no impact on the video stream quality/latency. - if UDP is used, video quality will be poor. => TCP much better
Unfortunately, this is not currently possible in the latest version of DataContractJsonSerializer. See: http://connect.microsoft.com/VisualStudio/feedback/details/558686/datacontractjsonserializer-should-serialize-dictionary-k-v-as-a-json-associative-array
The current suggested workaround is to use the JavaScriptSerializer as Mark suggested above.
Good luck!
I think if you have something that structured and complex, you might consider something other than a single drop-down box.
The shorthand for an if else structure works as expected in JSX
this.props.hasImage ? <MyImage /> : <SomeotherElement>
You can find other options on this blogpost of DevNacho, but it's more common to do it with the shorthand. If you need to have a bigger if clause you should write a function that returns or component A or component B.
for example:
this.setState({overlayHovered: true});
renderComponentByState({overlayHovered}){
if(overlayHovered) {
return <overlayHoveredComponent />
}else{
return <overlayNotHoveredComponent />
}
}
You can destructure your overlayHovered from this.state if you give it as parameter. Then execute that function in your render() method:
renderComponentByState(this.state)
I was able to find my version of Xcode on maxOS Sierra using this command:
pkgutil --pkg-info=com.apple.pkg.CLTools_Executables | grep version
as per this answer.
Having seen your fiddle in the comments the issue is quite easy to fix. You just need to add overflow:auto
or set a specific height to your div
. Live example: http://jsfiddle.net/tw16/xRcXL/3/
.Tab{
overflow:auto; /* add this */
border:solid 1px #faa62a;
border-bottom:none;
padding:7px 10px;
background:-moz-linear-gradient(center top , #FAD59F, #FA9907) repeat scroll 0 0 transparent;
background:-webkit-gradient(linear, left top, left bottom, from(#fad59f), to(#fa9907));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907)";
}
If you need to get multiple values from inputs and you're using []'s to define the inputs with multiple values, you can use the following:
$('#contentform').find('input, textarea, select').each(function(x, field) {
if (field.name) {
if (field.name.indexOf('[]')>0) {
if (!$.isArray(data[field.name])) {
data[field.name]=new Array();
}
data[field.name].push(field.value);
} else {
data[field.name]=field.value;
}
}
});
If you're using IIS 7 do something like this:
I spent way too much time on this and the solution was super simple. I had to use my "MX" as the host and port 25.
var sClient = new SmtpClient("domain-com.mail.protection.outlook.com");
var message = new MailMessage();
sClient.Port = 25;
sClient.EnableSsl = true;
sClient.Credentials = new NetworkCredential("user", "password");
sClient.UseDefaultCredentials = false;
message.Body = "Test";
message.From = new MailAddress("[email protected]");
message.Subject = "Test";
message.CC.Add(new MailAddress("[email protected]"));
sClient.Send(message);
In my case, I needed to copy the google-play-services_lib FOLDER in the same DRIVE of the source codes of my apps
In VBA, the !=
operator is the Not
operator, like this:
If Not strTest = "" Then ...
Let's start with a quote from the virtual machine spec:
Loading of a class or interface that contains a String literal may create a new String object (§2.4.8) to represent that literal. This may not occur if the a String object has already been created to represent a previous occurrence of that literal, or if the String.intern method has been invoked on a String object representing the same string as the literal.
This may not occur - This is a hint, that there's something special about String
objects. Usually, invoking a constructor will always create a new instance of the class. This is not the case with Strings, especially when String objects are 'created' with literals. Those Strings are stored in a global store (pool) - or at least the references are kept in a pool, and whenever a new instance of an already known Strings is needed, the vm returns a reference to the object from the pool. In pseudo code, it may go like that:
1: a := "one"
--> if(pool[hash("one")] == null) // true
pool[hash("one") --> "one"]
return pool[hash("one")]
2: b := "one"
--> if(pool[hash("one")] == null) // false, "one" already in pool
pool[hash("one") --> "one"]
return pool[hash("one")]
So in this case, variables a
and b
hold references to the same object. IN this case, we have (a == b) && (a.equals(b)) == true
.
This is not the case if we use the constructor:
1: a := "one"
2: b := new String("one")
Again, "one"
is created on the pool but then we create a new instance from the same literal, and in this case, it leads to (a == b) && (a.equals(b)) == false
So why do we have a String pool? Strings and especially String literals are widely used in typical Java code. And they are immutable. And being immutable allowed to cache String to save memory and increase performance (less effort for creation, less garbage to be collected).
As programmers we don't have to care much about the String pool, as long as we keep in mind:
(a == b) && (a.equals(b))
may be true
or false
(always use equals
to compare Strings)char[]
of a String (as you don't know who is actualling using that String)This issue could be because of wrong entity framework reference or sometimes the Class name not matching the entity name in database. Make sure the Table name matches with class name.
Two likely definitions:
getActivity()
in a Fragment
returns the Activity
the Fragment
is currently associated with. (see http://developer.android.com/reference/android/app/Fragment.html#getActivity()).getActivity()
is user-defined.Also, you can try (for Windows 10 Pro)
Run Powershell as administrator and type ssh-keygen -t rsa -b 4096 -C "[email protected]"
The basic problem while migrating from MySQL I faced was, I thought of the term database
to be same in PostgreSQL also, but it is not. So if we are going to switch the database from our application or pgAdmin
, the result would not be as expected.
As in my case, we have separate schemas (Considering PostgreSQL terminology here.) for each customer and separate admin schema. So in application, I have to switch between schemas.
For this, we can use the SET search_path
command. This does switch the current schema to the specified schema name for the current session.
example:
SET search_path = different_schema_name;
This changes the current_schema to the specified schema for the session. To change it permanently, we have to make changes in postgresql.conf
file.
The answer of @PeterOlson may be worked back in the day but it looks like
Object.create
is changed. I would go for the copy-constructor way like @user166390 said in the comments.
The reason I necromanced this post is because I needed such implementation.
Nowadays we can use Object.assign
(credits to @SayanPal solution) & ES6 syntax:
class Person {
constructor(obj) {
obj && Object.assign(this, obj);
}
getFullName() {
return `${this.lastName} ${this.firstName}`;
}
}
Usage:
const newPerson = new Person(person1)
newPerson.getFullName() // -> Freeman Gordon
ES5 answer below
function Person(obj) {
for(var prop in obj){
// for safety you can use the hasOwnProperty function
this[prop] = obj[prop];
}
}
Usage:
var newPerson = new Person(person1);
console.log(newPerson.getFullName()); // -> Freeman Gordon
Using a shorter version, 1.5 liner:
function Person(){
if(arguments[0]) for(var prop in arguments[0]) this[prop] = arguments[0][prop];
}
You should probably use either DateTime.ParseExact
or DateTime.TryParseExact
instead. They allow you to specify specific formats. I personally prefer the Try
-versions since I think they produce nicer code for the error cases.
Important to note with elementFormDefault is that it applies to locally defined elements, typically named elements inside a complexType block, as opposed to global elements defined on the top-level of the schema. With elementFormDefault="qualified" you can address local elements in the schema from within the xml document using the schema's target namespace as the document's default namespace.
In practice, use elementFormDefault="qualified" to be able to declare elements in nested blocks, otherwise you'll have to declare all elements on the top level and refer to them in the schema in nested elements using the ref attribute, resulting in a much less compact schema.
This bit in the XML Schema Primer talks about it: http://www.w3.org/TR/xmlschema-0/#NS
The answer seems to be just no.
Although there are many good other answers, they either just hide the uglyness (which I did not ask for) or introduce new problems (edge cases).
Since version 3.8.2 of SQLite, an alternative to explicit NOT NULL specifications is the "WITHOUT ROWID" specification: [1]
NOT NULL is enforced on every column of the PRIMARY KEY
in a WITHOUT ROWID table.
"WITHOUT ROWID" tables have potential efficiency advantages, so a less verbose alternative to consider is:
CREATE TABLE t (
c1,
c2,
c3,
PRIMARY KEY (c1, c2)
) WITHOUT ROWID;
For example, at the sqlite3 prompt:
sqlite> insert into t values(1,null,3);
Error: NOT NULL constraint failed: t.c2
Instead of you manual adding the tracing enabling bit into web.config you can also try using the WCF configuration editor which comes with VS SDK to enable tracing
This's simple and works like a charm :) just declare your enum like this and you can use it on HTML template
statusEnum: typeof StatusEnum = StatusEnum;
read -r -p "Wait 5 seconds or press any key to continue immediately" -t 5 -n 1 -s
To continue when you press any one button
I know this has been answered with previous entries, but for anyone else that comes to this question, I did find a way that did not require having use the "ping" process in windows and then scrubbing the output.
What I did was use JNA to invoke Window's IP helper library to do an ICMP echo
This Stack Overflow quesion is the current top Google result for "random string Python". The current top answer is:
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
This is an excellent method, but the PRNG in random is not cryptographically secure. I assume many people researching this question will want to generate random strings for encryption or passwords. You can do this securely by making a small change in the above code:
''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
Using random.SystemRandom()
instead of just random uses /dev/urandom on *nix machines and CryptGenRandom()
in Windows. These are cryptographically secure PRNGs. Using random.choice
instead of random.SystemRandom().choice
in an application that requires a secure PRNG could be potentially devastating, and given the popularity of this question, I bet that mistake has been made many times already.
If you're using python3.6 or above, you can use the new secrets module as mentioned in MSeifert's answer:
''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(N))
The module docs also discuss convenient ways to generate secure tokens and best practices.
It should be possible changing setting the JAVA_HOME environment variable differently for specific applications.
When starting from the command line or from a batch script you can use set JAVA_HOME=C:\...\j2dskXXX
to change the JAVA_HOME environment.
It is possible that you also need to change the PATH
environment variable to use the correct java binary. To do this you can use set PATH=%JAVA_HOME%\bin;%PATH%
.
There are 3 problems.
1) Incorrect decimal separator
Different cultures use different decimal separators (namely ,
and .
).
If you replace .
with ,
it should work as expected:
Console.WriteLine(Convert.ToDouble("52,8725945"));
You can parse your doubles using overloaded method which takes culture as a second parameter. In this case you can use InvariantCulture
(What is the invariant culture) e.g. using double.Parse
:
double.Parse("52.8725945", System.Globalization.CultureInfo.InvariantCulture);
You should also take a look at double.TryParse
, you can use it with many options and it is especially useful to check wheter or not your string is a valid double
.
2) You have an incorrect double
One of your values is incorrect, because it contains two dots:
15.5859949000000662452.23862099999999
3) Your array has an empty value at the end, which is an incorrect double
You can use overloaded Split
which removes empty values:
string[] someArray = a.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
There is an alternative solution to this problem which also deals with duplicate matches.
We start with 2 lists of equal length: emails
, otherarray
. The objective is to remove items from both lists for each index i
where emails[i] == '[email protected]'
.
This can be achieved using a list comprehension and then splitting via zip
:
emails = ['[email protected]', '[email protected]', '[email protected]']
otherarray = ['some', 'other', 'details']
from operator import itemgetter
res = [(i, j) for i, j in zip(emails, otherarray) if i!= '[email protected]']
emails, otherarray = map(list, map(itemgetter(0, 1), zip(*res)))
print(emails) # ['[email protected]', '[email protected]']
print(otherarray) # ['some', 'details']
Use an interval:
select some_date_column + interval '1' hour
from your_table;
To avoid confusion, paraphrasing both question and answer. I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump
, this method dumped all its content in one line. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:
with g as outfile:
json.dump(hostDict, outfile,indent=2)
Using indent = 2
helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.
Based on the fact that the request isn't sent on the default port 80/443 this Ajax call is automatically considered a cross-origin resource (CORS) request, which in other words means that the request automatically issues an OPTIONS request which checks for CORS headers on the server's/servlet's side.
This happens even if you set
crossOrigin: false;
or even if you ommit it.
The reason is simply that localhost != localhost:57124
. Try sending it only to localhost
without the port - it will fail, because the requested target won't be reachable, however notice that if the domain names are equal the request is sent without the OPTIONS request before POST.
using (SqlConnection connection = new SqlConnection("Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True"))
{
SqlCommand command =
new SqlCommand("select * from Pending_Tasks WHERE CustomerId=...", connection);
connection.Open();
SqlDataReader read= command.ExecuteReader();
while (read.Read())
{
CustID.Text = (read["Customer_ID"].ToString());
CustName.Text = (read["Customer_Name"].ToString());
Add1.Text = (read["Address_1"].ToString());
Add2.Text = (read["Address_2"].ToString());
PostBox.Text = (read["Postcode"].ToString());
PassBox.Text = (read["Password"].ToString());
DatBox.Text = (read["Data_Important"].ToString());
LanNumb.Text = (read["Landline"].ToString());
MobNumber.Text = (read["Mobile"].ToString());
FaultRep.Text = (read["Fault_Report"].ToString());
}
read.Close();
}
Make sure you have data in the query : select * from Pending_Tasks and you are using "using System.Data.SqlClient;"
1.
To_Date(To_Char(MaxDate, 'DD/MM/YYYY')) = REP_DATE
is causing the issue. when you use to_date without the time format, oracle will use the current sessions NLS format to convert, which in your case might not be "DD/MM/YYYY". Check this...
SQL> select sysdate from dual;
SYSDATE
---------
26-SEP-12
Which means my session's setting is DD-Mon-YY
SQL> select to_char(sysdate,'MM/DD/YYYY') from dual;
TO_CHAR(SY
----------
09/26/2012
SQL> select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual;
select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual
*
ERROR at line 1:
ORA-01843: not a valid month
SQL> select to_date(to_char(sysdate,'MM/DD/YYYY'),'MM/DD/YYYY') from dual;
TO_DATE(T
---------
26-SEP-12
2.
More importantly, Why are you converting to char and then to date, instead of directly comparing
MaxDate = REP_DATE
If you want to ignore the time component in MaxDate before comparision, you should use..
trunc(MaxDate ) = rep_date
instead.
==Update : based on updated question.
Rep_Date = 01/04/2009 Rep_Time = 01/01/1753 13:00:00
I think the problem is more complex. if rep_time is intended to be only time, then you cannot store it in the database as a date. It would have to be a string or date to time interval or numerically as seconds (thanks to Alex, see this) . If possible, I would suggest using one column rep_date that has both the date and time and compare it to the max date column directly.
If it is a running system and you have no control over repdate, you could try this.
trunc(rep_date) = trunc(maxdate) and
to_char(rep_date,'HH24:MI:SS') = to_char(maxdate,'HH24:MI:SS')
Either way, the time is being stored incorrectly (as you can tell from the year 1753) and there could be other issues going forward.
You can use native win command:
WMIC /node:ComputerName process call create “cmd.exe /c start.exe”
The WMIC is part of wbem win folder: C:\Windows\System32\wbem
pandas.Series.astype
You can do something like this :
weather["Temp"] = weather.Temp.astype(float)
You can also use pd.to_numeric
that will convert the column from object to float
Example :
s = pd.Series(['apple', '1.0', '2', -3])
print(pd.to_numeric(s, errors='ignore'))
print("=========================")
print(pd.to_numeric(s, errors='coerce'))
Output:
0 apple
1 1.0
2 2
3 -3
=========================
dtype: object
0 NaN
1 1.0
2 2.0
3 -3.0
dtype: float64
In your case you can do something like this:
weather["Temp"] = pd.to_numeric(weather.Temp, errors='coerce')
convert_objects
Example is as follows
>> pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
0 1
1 2
2 3
3 4
4 NaN
dtype: float64
You can use this as follows:
weather["Temp"] = weather.Temp.convert_objects(convert_numeric=True)
NaN
... so be careful while using it.If the above methods are not working for you, you may want to look into changing the encoding
of the csv file
itself.
Using Excel:
csv
file using Excel
CSV (Comma delimited) (*.csv)
optionUnicode (UTF-8)
from Save this document as drop-down listUsing Notepad:
csv file
using notepad.csv
extensionUTF-8
option.By doing this, you should be able to import csv
files without encountering the UnicodeCodeError
.
<?php
class Test {
function MethodA(){
echo __FUNCTION__ ;
}
}
$test = new Test;
echo $test->MethodA();
?>
Result: "MethodA";