There is no standard, so there is no guarantee. With that said, its common for the sitemap to be self labeled and on the root, like this:
example.com/sitemap.xml
Case is sensitive on some servers, so keep that in mind. If its not there, look in the robots file on the root:
example.com/robots.txt
If you don't see it listed in the robots file head to Google and search this:
site:example.com filetype:xml
This will limit the results to XML files on your target domain. At this point its trial-and-error and based on the specifics of the website you are working with. If you get several pages of results from the Google search phrase above then try to limit the results further:
filetype:xml site:example.com inurl:sitemap
or
filetype:xml site:example.com inurl:products
If you still can't find it you can right-click > "View Source"
and do a search (aka: "control find" or Ctrl + F
) for .xml
to see if there is a reference to it in the code.
According to the official documentation on sitemaps.org it needs to be a full URL:
You can specify the location of the Sitemap using a robots.txt file. To do this, simply add the following line including the full URL to the sitemap:
Sitemap: http://www.example.com/sitemap.xml
Other answers here address the general question of what the proper Content-Type
for an XML response is, and conclude (as with What's the difference between text/xml vs application/xml for webservice response) that both text/xml
and application/xml
are permissible. However, none address whether there are any rules specific to sitemaps.
Answer: there aren't. The sitemap spec is https://www.sitemaps.org, and using Google site:
searches you can confirm that it does not contain the words or phrases mime, mimetype, content-type, application/xml, or text/xml anywhere. In other words, it is entirely silent on the topic of what Content-Type
should be used for serving sitemaps.
In the absence of any commentary in the sitemap spec directly addressing this question, we can safely assume that the same rules apply as when choosing the Content-Type
of any other XML document - i.e. that it may be either text/xml
or application/xml
.
There is a package random_word could implement this request very conveniently:
$ pip install random-word
from random_word import RandomWords
r = RandomWords()
# Return a single random word
r.get_random_word()
# Return list of Random words
r.get_random_words()
# Return Word of the day
r.word_of_the_day()
Easiest way to get text from the user:
EditText Variable1 = findViewById(R.id.enter_name);
String Variable2 = Variable1.getText().toString();
The important thing to note here is that the mime type is not the same as the file extension. Sometimes, however, they have the same value.
https://www.iana.org/assignments/media-types/media-types.xhtml includes a list of registered Mime types, though there is nothing stopping you from making up your own, as long as you are at both the sending and the receiving end. Here is where Microsoft comes in to the picture.
Where there is a lot of confusion is the fact that operating systems have their own way of identifying file types by using the tail end of the file name, referred to as the extension. In modern operating systems, the whole name is one long string, but in more primitive operating systems, it is treated as a separate attribute.
The OS which caused the confusion is MSDOS, which had limited the extension to 3 characters. This limitation is inherited to this day in devices, such as SD cards, which still store data in the same way.
One side effect of this limitation is that some file extensions, such as .gif
match their Mime Type, image/gif
, while others are compromised. This includes image/jpeg
whose extension is shortened to .jpg
. Even in modern Windows, where the limitation is lifted, Microsoft never let the past go, and so the file extension is still the shortened version.
Given that that:
The short answer is:
image/jpg
, so the answer is
that it is not the same as image/jpeg
While we’re at it …
Legacy versions of Internet Explorer took the liberty of uploading jpeg
files with the Mime Type of image/pjpeg
, which, of course, just means more work for everybody else. They also uploaded png
files as image/x-png
.
For future reference, you can get help for any command by using the /?
switch, which should explain what switches do what.
According to the set /?
screen, the format for set /p
is SET /P variable=[promptString]
which would indicate that the p in /p
is "prompt." It just prints in your example because <nul
passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.
/L
in for /L
generates a List of numbers.
From ping /?
:
Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
[-r count] [-s count] [[-j host-list] | [-k host-list]]
[-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name
Options:
-t Ping the specified host until stopped.
To see statistics and continue - type Control-Break;
To stop - type Control-C.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-l size Send buffer size.
-f Set Don't Fragment flag in packet (IPv4-only).
-i TTL Time To Live.
-v TOS Type Of Service (IPv4-only. This setting has been deprecated
and has no effect on the type of service field in the IP Header).
-r count Record route for count hops (IPv4-only).
-s count Timestamp for count hops (IPv4-only).
-j host-list Loose source route along host-list (IPv4-only).
-k host-list Strict source route along host-list (IPv4-only).
-w timeout Timeout in milliseconds to wait for each reply.
-R Use routing header to test reverse route also (IPv6-only).
-S srcaddr Source address to use.
-4 Force using IPv4.
-6 Force using IPv6.
In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal.
In case of entity framework FK in dependent must also be its PK so in your case you should use:
public class Boo
{
[Key, ForeignKey("Foo")]
public string BooId{get;set;}
public Foo Foo{get;set;}
}
Or fluent mapping
modelBuilder.Entity<Foo>()
.HasOptional(f => f.Boo)
.WithRequired(s => s.Foo);
even shorter using the dot:
#!/bin/bash
. CONFIG_FILE
sudo -u wwwrun svn up /srv/www/htdocs/$production
sudo -u wwwrun svn up /srv/www/htdocs/$playschool
Previously posted solutions did not work for me. cell.getRawValue()
returned the same formula as stated in the cell. The following function worked for me:
public void readFormula() throws IOException {
FileInputStream fis = new FileInputStream("Path of your file");
Workbook wb = new XSSFWorkbook(fis);
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
CellReference cellReference = new CellReference("C2"); // pass the cell which contains the formula
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
CellValue cellValue = evaluator.evaluate(cell);
switch (cellValue.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cellValue.getBooleanValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cellValue.getNumberValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cellValue.getStringValue());
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
break;
// CELL_TYPE_FORMULA will never happen
case Cell.CELL_TYPE_FORMULA:
break;
}
}
What you are trying to do can be simplified down to this.
$('input:text').bind('focus blur', function() {_x000D_
$(this).toggleClass('red');_x000D_
});
_x000D_
input{_x000D_
background:#FFFFEE;_x000D_
}_x000D_
.red{_x000D_
background-color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<form>_x000D_
<input class="calc_input" type="text" name="start_date" id="start_date" />_x000D_
<input class="calc_input" type="text" name="end_date" id="end_date" />_x000D_
<input class="calc_input" size="8" type="text" name="leap_year" id="leap_year" />_x000D_
</form>
_x000D_
If you are trying to delete empty spaces , try using =''
instead of is null
. Hence , if your row contains empty spaces , is null
will not capture those records. Empty space is not null and null is not empty space.
Dec Hex Binary Char-acter Description
0 00 00000000 NUL null
32 20 00100000 Space space
So I recommend:
delete from foo_table where bar = ''
#or
delete from foo_table where bar = '' or bar is null
#or even better ,
delete from foo_table where rtrim(ltrim(isnull(bar,'')))='';
There is no semicolon at the end of that instruction causing the error.
EDIT
Like RiverC pointed out, there is no semicolon at the end of the previous line!
require ("scripts/connect.php")
EDIT
It seems you have no-semicolons whatsoever.
http://php.net/manual/en/language.basic-syntax.instruction-separation.php
As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement.
To test if the POST variable has an element called 'userID' you would be better off using array_key_exists .. which actually tests for the existence of the array key not whether its value has been set .. a subtle and probably only semantic difference, but it does improve readability.
and right now your $uid is being set to a boolean value depending whether $__POST['userID'] is set or not ... If I recall from memory you might want to try ...
$uid = (array_key_exists('userID', $_POST)?$_POST['userID']:'guest';
Then you can use an identifiable 'guest' user and render your code that much more readable :)
Another point re isset() even though it is unlikely to apply in this scenario, it's worth remembering if you don't want to get caught out later ... an array element can be legitimately set to NULL ... i.e. it can exist, but be as yet unpopulated, and this could be a valid, acceptable, and testable condition. but :
a = array('one'=>1, 'two'=>null, 'three'=>3);
isset(a['one']) == true
isset(a['two']) == false
array_key_exists(a['one']) == true
array_key_exists(a['two']) == true
Bw sure you know which function you want to use for which purpose.
You can use Bootstrap's tabs with bootstrap-verticaltabs
. This modifies Bootstrap's Tabs to provide an alternative vertical styling. That way you can use the built in tabs in bootstrap and get the vertical menu you are looking for.
cURL is a library that lets you make HTTP requests in PHP. Everything you need to know about it (and most other extensions) can be found in the PHP manual.
In order to use PHP's cURL functions you need to install the » libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.
You can make HTTP requests without cURL, too, though it requires allow_url_fopen
to be enabled in your php.ini
file.
// Make a HTTP GET request and print it (requires allow_url_fopen to be enabled)
print file_get_contents('http://www.example.com/');
WORKING Method { if there is no problem other than configuration }
By Default Appache is not restricting access from ipv4. (common external ip)
What may restrict is the configurations in 'httpd.conf' (or 'apache2.conf' depending on your apache configuration)
Solution:
Replace all:
<Directory />
AllowOverride none
Require all denied
</Directory>
with
<Directory />
AllowOverride none
# Require all denied
</Directory>
hence removing out all restriction given to Apache
Replace Require local
with Require all granted
at C:/wamp/www/
directory
<Directory "c:/wamp/www/">
Options Indexes FollowSymLinks
AllowOverride all
Require all granted
# Require local
</Directory>
That's the job that GNU's automake/autoconf are designed to solve. You might want to investigate them.
Alternatively you can set environment variables on your different platforms and make you Makefile conditional against them.
Edit: Looks like everyone else beat me to it haha
Found the answer.
ISNULL()
determines what to do when you have a null value.
In this case my function returns a null value so I needed specify a 0 to be returned instead.
SELECT ISNULL(SUM(Price), 0) AS TotalPrice
FROM Inventory
WHERE (DateAdded
BETWEEN @StartDate AND @EndDate)
For 'Hello' at the start of the string:
SELECT STUFF('Hello World', 1, 6, '')
This will work for 'Hello' anywhere in the string:
SELECT REPLACE('Hello World', 'Hello ', '')
A rather roundabout way, just for completeness:
for /f "delims=" %i in ('type CON') do set inp=%i
Of course that requires ^Z as a terminator, and so the Johannes answer is better in all practical ways.
This was answered by a few others but I found a solution that worked really well for me.
System.out.println(CvType.typeToString(yourMat.type()));
You cannot 'alter' the property syntax this way. What you can do is this:
class Foo
{
string MyProperty { get; set; } // auto-property with inaccessible backing field
}
and a generic version would look like this:
class Foo<T>
{
T MyProperty { get; set; }
}
The lack of abstraction is what makes C faster. If you write an output statement you know exactly what is happening. If you write an output statement in java it is getting compiled to a class file which then gets run on a virtual machine introducing a layor of abstraction. The lack of object oriented features as a part of the language also increases it's speed do to less code being generated. If you use C as an object oriented language then you are doing all the coding for things such as classes, inharitence, etc. This means rather then make something generalized enough for everyone with the amount of code and the performance penelty that requires you only write what you need to get the job done.
Hello this is my first time posting so please be patient: my answer was to create a simple property:
public bool Checked { get; set; }
Then to set the data context of the Checkbox (called cb1):
cb1.DataContext = this;
Then to bind the IsChecked proerty of it in the xaml
IsChecked="{Binding Checked}"
The code is like this:
XAML
<CheckBox x:Name="cb1"
HorizontalAlignment="Left"
Margin="439,81,0,0"
VerticalAlignment="Top"
Height="35" Width="96"
IsChecked="{Binding Checked}"/>
Code behind
public partial class MainWindow : Window
{
public bool Checked { get; set; }
public MainWindow()
{
InitializeComponent();
cb1.DataContext = this;
}
private void myyButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(Checked.ToString());
}
}
Something like this will work:
>>> import os
>>> path = '/usr/share/cups/charmaps'
>>> text_files = [f for f in os.listdir(path) if f.endswith('.txt')]
>>> text_files
['euc-cn.txt', 'euc-jp.txt', 'euc-kr.txt', 'euc-tw.txt', ... 'windows-950.txt']
I realise this is old, but an array filter may do what you need:
var arr = [0, 1, 2].filter(function (count) {
return count < 1;
});
You can then run arr.forEach
and other array functions.
I realise that if you intend to cut down on loop operations altogether, this will probably not do what you want. For that you best use while
.
In my case, it simply because the disk is full. Just clear some disk space and restart and everything is fine.
The library has a section in the readme about escaping. It's Javascript-native, so I do not suggest switching to node-mysql-native. The documentation states these guidelines for escaping:
Edit: node-mysql-native is also a pure-Javascript solution.
true
/ false
stringsYYYY-mm-dd HH:ii:ss
stringsX'0fa5'
['a', 'b']
turns into 'a', 'b'
[['a', 'b'], ['c', 'd']]
turns into ('a', 'b'), ('c', 'd')
key = 'val'
pairs. Nested objects are cast to strings.undefined
/ null
are converted to NULL
NaN
/ Infinity
are left as-is. MySQL does not support these, and trying to insert them as values will trigger MySQL errors until they implement support.This allows for you to do things like so:
var userId = 5;
var query = connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
//query.sql returns SELECT * FROM users WHERE id = '5'
});
As well as this:
var post = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
//query.sql returns INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
});
Aside from those functions, you can also use the escape functions:
connection.escape(query);
mysql.escape(query);
To escape query identifiers:
mysql.escapeId(identifier);
And as a response to your comment on prepared statements:
From a usability perspective, the module is great, but it has not yet implemented something akin to PHP's Prepared Statements.
The prepared statements are on the todo list for this connector, but this module at least allows you to specify custom formats that can be very similar to prepared statements. Here's an example from the readme:
connection.config.queryFormat = function (query, values) {
if (!values) return query;
return query.replace(/\:(\w+)/g, function (txt, key) {
if (values.hasOwnProperty(key)) {
return this.escape(values[key]);
}
return txt;
}.bind(this));
};
This changes the query format of the connection so you can use queries like this:
connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
//equivalent to
connection.query("UPDATE posts SET title = " + mysql.escape("Hello MySQL");
A solution with flexbox (working on IE11): (or view on jsfiddle)
<html>
<style>
html, body {
height: 100%; /* fix for IE11, not needed for chrome/ff */
margin: 0; /* CSS-reset for chrome */
}
</style>
<body style="display: flex;">
<div style="background-color: black; flex: 1; margin: 25px;"></div>
</body>
</html>
(The CSS-reset is not necessarily important for the actual problem.)
The important part is flex: 1
(In combination with display: flex
at the parent). Funnily enough, the most plausible explanation I know for how the Flex property works comes from a react-native documentation, so I refer to it anyway:
(...) flex: 1, which tells a component to fill all available space, shared evenly amongst other components with the same parent
I had the same problem, and the little star means that the kernel is still working. So the program is trapped in an endless while loop. So you only have to the rewrite the code
foreach my $key (keys %$ad_grp_ref) {
...
}
Perl::Critic
and daxim recommend the style
foreach my $key (keys %{ $ad_grp_ref }) {
...
}
out of concerns for readability and maintenance (so that you don't need to think hard about what to change when you need to use %{ $ad_grp_obj[3]->get_ref() }
instead of %{ $ad_grp_ref }
)
About prototype bean(s) :
The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding. To get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-processor, which holds a reference to beans that need to be cleaned up.
From the spring boot docs https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
YAML lists are represented as property keys with [index] dereferencers, for example this YAML:
my:
servers:
- dev.bar.com
- foo.bar.com
Would be transformed into these properties:
my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com
To bind to properties like that using the Spring DataBinder utilities (which is what @ConfigurationProperties
does) you need to have a property in the target bean of type java.util.List
and you either need to provide a setter, or initialize it with a mutable value, e.g. this will bind to the properties above. Here is what the question's code would look like.
@ConfigurationProperties(prefix="ignore")
public class Filenames {
private List<String> ignoredFilenames = new ArrayList<String>();
public List<String> getFilenames() {
return this.ignoredFilenames;
}
}
Install PAR::Packer from CPAN (it is free) and use pp utility.
I actually think that's not the good way to parse it. It's not clean or it's a bit out of subject ...
I'd do something like ...
if ($pos_get = strpos($app_uri, '?')) $app_uri = substr($app_uri, 0, $pos_get);
Considering $app_uri as the URI/URL of my website.
I don't know if I got you right, but, as I understand, you could use an additional hidden field with the value "add tag" and let the button have the desired text.
Using Console to read input (usable only outside of an IDE):
System.out.print("Enter something:");
String input = System.console().readLine();
Another way (works everywhere):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String");
String s = br.readLine();
System.out.print("Enter Integer:");
try {
int i = Integer.parseInt(br.readLine());
} catch(NumberFormatException nfe) {
System.err.println("Invalid Format!");
}
}
}
System.console() returns null in an IDE.
So if you really need to use System.console()
, read this solution from McDowell.
The easiest solution for your case - change the first line, let it do just the opposite thing:
String lower = Name.toUpperCase ();
Of course, it's worth to change its name too.
The one liner "no imports" version
a = [0,88,26,3,48,85,65,16,97,83,91]
ind_pos = [1,5,7]
[ a[i] for i in ind_pos ]
var currentDate = new Date(),
currentDay = currentDate.getDate() < 10
? '0' + currentDate.getDate()
: currentDate.getDate(),
currentMonth = currentDate.getMonth() < 9
? '0' + (currentDate.getMonth() + 1)
: (currentDate.getMonth() + 1);
document.getElementById("date").innerHTML = currentDay + '/' + currentMonth + '/' + currentDate.getFullYear();
You can read more about Date object
in function
def handleUpload():
if 'photo' in request.files:
photo = request.files['photo']
if photo.filename != '':
image = request.files['photo']
image_string = base64.b64encode(image.read())
image_string = image_string.decode('utf-8')
#use this to remove b'...' to get raw string
return render_template('handleUpload.html',filestring = image_string)
return render_template('upload.html')
in html file
<html>
<head>
<title>Simple file upload using Python Flask</title>
</head>
<body>
{% if filestring %}
<h1>Raw image:</h1>
<h1>{{filestring}}</h1>
<img src="data:image/png;base64, {{filestring}}" alt="alternate" />.
{% else %}
<h1></h1>
{% endif %}
</body>
By Restarting NPF, I can see the interfaces with wireshark 1.6.5
Open a Command Prompt with administrative privileges.
That's it.
In reply to ""Why do they appear all of a sudden? I used to use this script for years and I've never had any problem."
It is very common for most sites to operate under the "default" error reporting of "Show all errors, but not 'notices' and 'deprecated'". This will be set in php.ini and apply to all sites on the server. This means that those "notices" used in the examples will be suppressed (hidden) while other errors, considered more critical, will be shown/recorded.
The other critical setting is the errors can be hidden (i.e. display_errors
set to "off" or "syslog").
What will have happened in this case is that either the error_reporting
was changed to also show notices (as per examples) and/or that the settings were changed to display_errors
on screen (as opposed to suppressing them/logging them).
Why have they changed?
The obvious/simplest answer is that someone adjusted either of these settings in php.ini, or an upgraded version of PHP is now using a different php.ini from before. That's the first place to look.
However it is also possible to override these settings in
and any of these could also have been changed.
There is also the added complication that the web server configuration can enable/disable .htaccess directives, so if you have directives in .htaccess that suddenly start/stop working then you need to check for that.
(.htconf / .htaccess assume you're running as apache. If running command line this won't apply; if running IIS or other webserver then you'll need to check those configs accordingly)
Summary
error_reporting
and display_errors
php directives in php.ini has not changed, or that you're not using a different php.ini from before.error_reporting
and display_errors
php directives in .htconf (or vhosts etc) have not changederror_reporting
and display_errors
php directives in .htaccess have not changederror_reporting
and display_errors
php directives have been set there.Good Solution is to get Nearest Round Number is
var=2.5
echo $var | awk '{print int($1+0.5)}'
Logic is simple if the var decimal value is less then .5 then closest value taken is integer value. Well if decimal value is more than .5 then next integer value gets added and since awk then takes only integer part. Issue solved
column_obj != None
will produce a IS NOT NULL
constraint:
In a column context, produces the clause
a != b
. If the target isNone
, produces aIS NOT NULL
.
or use isnot()
(new in 0.7.9):
Implement the
IS NOT
operator.Normally,
IS NOT
is generated automatically when comparing to a value ofNone
, which resolves toNULL
. However, explicit usage ofIS NOT
may be desirable if comparing to boolean values on certain platforms.
Demo:
>>> from sqlalchemy.sql import column
>>> column('YourColumn') != None
<sqlalchemy.sql.elements.BinaryExpression object at 0x10c8d8b90>
>>> str(column('YourColumn') != None)
'"YourColumn" IS NOT NULL'
>>> column('YourColumn').isnot(None)
<sqlalchemy.sql.elements.BinaryExpression object at 0x104603850>
>>> str(column('YourColumn').isnot(None))
'"YourColumn" IS NOT NULL'
Use UploadStringAsync
method:
WebClient webClient = new WebClient();
webClient.UploadStringCompleted += (s, e) =>
{
if (e.Error != null)
{
//handle your error here
}
else
{
//post was successful, so do what you need to do here
}
};
webClient.UploadStringAsync(new Uri(yourUri), UriKind.Absolute), "POST", yourParameters);
The align-items
, or respectively align-content
attribute controls this behaviour.
align-items
defines the items' positioning perpendicularly to flex-direction
.
The default flex-direction
is row
, therfore vertical placement can be controlled with align-items
.
There is also the align-self
attribute to control the alignment on a per item basis.
#a {_x000D_
display:flex;_x000D_
_x000D_
align-items:flex-start;_x000D_
align-content:flex-start;_x000D_
}_x000D_
_x000D_
#a > div {_x000D_
_x000D_
background-color:red;_x000D_
padding:5px;_x000D_
margin:2px;_x000D_
}_x000D_
#a > #c {_x000D_
align-self:stretch;_x000D_
}
_x000D_
<div id="a">_x000D_
_x000D_
<div id="b">left</div>_x000D_
<div id="c">middle</div>_x000D_
<div>right<br>right<br>right<br>right<br>right<br></div>_x000D_
_x000D_
</div>
_x000D_
css-tricks has an excellent article on the topic. I recommend reading it a couple of times.
I followed tim peterson's instructions but I created a local branch for my changes. However, after pushing I was not seeing the new branch in GitHub. The solution was to add -u to the push command:
git push -u origin <branch>
The not straightforward way of doing it would be granting select on each table of the database:
postgres=# grant select on db_name.table_name to read_only_user;
You could automate that by generating your grant statements from the database metadata.
i think right now is Firefox 3.6.2, but when internet explorer 9 launched, it will support HTML5
I do not think that is possible you have to set all the values individualling (like the first example you provided.)
The Second example you gave, will only Initialize the last varuable to "" and not the others.
This is a mix of the two previous answers:
PreparedStatement ps = c.prepareStatement("INSERT INTO employees VALUES (?, ?)");
ps.setString(1, "John");
ps.setString(2,"Doe");
ps.addBatch();
ps.clearParameters();
ps.setString(1, "Dave");
ps.setString(2,"Smith");
ps.addBatch();
ps.clearParameters();
int[] results = ps.executeBatch();
This is a two-step process:
you need to create a login to SQL Server for that user, based on its Windows account
CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
you need to grant this login permission to access a database:
USE (your database)
CREATE USER (username) FOR LOGIN (your login name)
Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader
database role to read all tables.
USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'
function scrollToBottom() {
$("#mContainer").animate({ scrollTop: $("#mContainer")[0].scrollHeight }, 1000);
}
This is the solution work from me and you find, I'm sure
I needed something I could run as one command, instead of having to write docker ps
and copying over each Container ID and running the command multiple times. I've adapted BMitch's answer and thought I'd share in case someone else may find this useful.
Mixing xargs
seems to pull off what I need here:
docker ps --format='{{.ID}}' | \
xargs -I {} sh -c 'echo > $(docker inspect --format="{{.LogPath}}" {})'
This grabs each Container ID listed by docker ps
(will erase your logs for any container on that list!), pipes it into xargs
and then echoes a blank string to replace the log path of the container.
Even if it s late i hope i can help someone. if dropdown menu or submenu is on the right side of screen it's open on the left side, if menu or submenu is on the left it's open on the right side.
$(".dropdown-toggle").on("click", function(event){//"show.bs.dropdown"
var liparent=$(this.parentElement);
var ulChild=liparent.find('ul');
var xOffset=liparent.offset().left;
var alignRight=($(document).width()-xOffset)<xOffset;
if (liparent.hasClass("dropdown-submenu"))
{
ulChild.css("left",alignRight?"-101%":"");
}
else
{
ulChild.toggleClass("dropdown-menu-right",alignRight);
}
});
To detect vertical position you can also add
$( document ).ready(function() {
var liparent=$(".dropdown");
var yOffset=liparent.offset().top;
var toTop=($(document).height()-yOffset)<yOffset;
liparent.toggleClass("dropup",toTop);
});
As of BS3 there's a .center-block
helper class. From the docs:
// Classes
.center-block {
display: block;
margin-left: auto;
margin-right: auto;
}
// Usage as mixins
.element {
.center-block();
}
There is hidden complexity in this seemingly simple problem. All the answers given have some issues.
Create .col-centred
class, but there is a major gotcha.
.col-centred {
float: none !important;
margin: 0 auto;
}
<!-- Bootstrap 3 -->
<div class="col-lg-6 col-centred">
Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 col-centred">
Centred content.
</div>
The Gotcha
Bootstrap requires columns add up to 12. If they do not they will overlap, which is a problem. In this case the centred column will overlap the column above it. Visually the page may look the same, but mouse events will not work on the column being overlapped (you can't hover or click links, for example). This is because mouse events are registering on the centred column that's overlapping the elements you try to click.
The Fixes
You can resolve this issue by using a clearfix
element. Using z-index
to bring the centred column to the bottom will not work because it will be overlapped itself, and consequently mouse events will work on it.
<div class="row">
<div class="col-lg-12">
I get overlapped by `col-lg-7 centered` unless there's a clearfix.
</div>
<div class="clearfix"></div>
<div class="col-lg-7 centred">
</div>
</div>
Or you can isolate the centred column in its own row.
<div class="row">
<div class="col-lg-12">
</div>
</div>
<div class="row">
<div class="col-lg-7 centred">
Look I am in my own row.
</div>
</div>
<!-- Bootstrap 3 -->
<div class="col-lg-6 col-lg-offset-3">
Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 span-offset-3">
Centred content.
</div>
The first problem is that your centred column must be an even number because the offset value must divide evenly by 2 for the layout to be centered (left/right).
Secondly, as some have commented, using offsets is a bad idea. This is because when the browser resizes the offset will turn into blank space, pushing the actual content down the page.
This is the best solution in my opinion. No hacking required and you don't mess around with the grid, which could cause unintended consequences, as per solutions 1 and 2.
.col-centred {
margin: 0 auto;
}
<div class="row">
<div class="col-lg-12">
<div class="centred">
Look I am in my own row.
</div>
</div>
</div>
What? In your validation function, just put
document.onlyform.upload.value="";
Assuming upload is the name:
<input type="file" name="upload" id="csv_doc"/>
I'm using JSP, not sure if that makes a difference...
Works for me, and I think it's way easier.
Whose special characters you want to remove from a string, prepare a list of them and then user javascript replace function to remove all special characters.
var str = 'abc'de#;:sfjkewr47239847duifyh';
alert(str.replace("'","").replace("#","").replace(";","").replace(":",""));
or you can run loop for a whole string and compare single single character with the ASCII code and regenerate a new string.
As hinted at by this post Error in chrome: Content-Type is not allowed by Access-Control-Allow-Headers just add the additional header to your web.config like so...
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
We can easily setup a Nodejs app by Nginx acting as a reverse proxy.
The following configuration assumes the NodeJS application is running on 127.0.0.1:8080,
server{
server_name domain.com sub.domain.com; # multiple domains
location /{
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_pass_request_headers on;
}
location /static/{
alias /absolute/path/to/static/files; # nginx will handle js/css
}
}
in above setup your Nodejs app will,
HTTP_HOST
header where you can apply domain specific logic to serve the response. 'Your Application must be managed by a process manager like pm2 or supervisor for handling situations/reusing sockets or resources etc.
Setup an error reporting service for getting production errors like sentry or rollbar
NOTE: you can setup logic for handing domain specific request routes, create a middleware for expressjs application
Add this CSS reset to your CSS code: (From here)
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
It'll reset the CSS effectively, getting rid of the padding and margins.
see my answer here:
How can I get the current date and time in UTC or GMT in Java?
I've fully tested it by changing the timezones on the emulator
Use the std::getline()
from <string>
.
istream & getline(istream & is,std::string& str)
So, for your case it would be:
std::getline(read,x);
Here are a few ways:
1) sub
sub(".*:", "", string)
## [1] "E001" "E002" "E003"
2) strsplit
sapply(strsplit(string, ":"), "[", 2)
## [1] "E001" "E002" "E003"
3) read.table
read.table(text = string, sep = ":", as.is = TRUE)$V2
## [1] "E001" "E002" "E003"
4) substring
This assumes second portion always starts at 4th character (which is the case in the example in the question):
substring(string, 4)
## [1] "E001" "E002" "E003"
4a) substring/regex
If the colon were not always in a known position we could modify (4) by searching for it:
substring(string, regexpr(":", string) + 1)
5) strapplyc
strapplyc
returns the parenthesized portion:
library(gsubfn)
strapplyc(string, ":(.*)", simplify = TRUE)
## [1] "E001" "E002" "E003"
6) read.dcf
This one only works if the substrings prior to the colon are unique (which they are in the example in the question). Also it requires that the separator be colon (which it is in the question). If a different separator were used then we could use sub
to replace it with a colon first. For example, if the separator were _
then string <- sub("_", ":", string)
c(read.dcf(textConnection(string)))
## [1] "E001" "E002" "E003"
7) separate
7a) Using tidyr::separate
we create a data frame with two columns, one for the part before the colon and one for after, and then extract the latter.
library(dplyr)
library(tidyr)
library(purrr)
DF <- data.frame(string)
DF %>%
separate(string, into = c("pre", "post")) %>%
pull("post")
## [1] "E001" "E002" "E003"
7b) Alternately separate
can be used to just create the post
column and then unlist
and unname
the resulting data frame:
library(dplyr)
library(tidyr)
DF %>%
separate(string, into = c(NA, "post")) %>%
unlist %>%
unname
## [1] "E001" "E002" "E003"
8) trimws We can use trimws
to trim word characters off the left and then use it again to trim the colon.
trimws(trimws(string, "left", "\\w"), "left", ":")
## [1] "E001" "E002" "E003"
The input string
is assumed to be:
string <- c("G1:E001", "G2:E002", "G3:E003")
You can store images in MySQL as blobs. However, this is problematic for a couple of reasons:
Instead, consider updating your table to add an image_path field. For example:
ALTER TABLE `your_table`
ADD COLUMN `image_path` varchar(1024)
Then store your images on disk, and update the table with the image path. When you need to use the images, retrieve them from disk using the path specified.
An advantageous side-effect of this approach is that the images do not necessarily be stored on disk; you could just as easily store a URL instead of an image path, and retrieve images from any internet-connected location.
As Peter already pointed out:
In [1]: import requests
In [2]: r = requests.get('https://api.github.com/events')
In [3]: type(r)
Out[3]: requests.models.Response
In [4]: type(r.content)
Out[4]: str
You may also want to check r.text
.
Also: https://2.python-requests.org/en/latest/user/quickstart/
The accepted answer is correct but it doesn't tell you how to use it. This is how you use indexOf and substring functions together.
String filename = "abc.def.ghi"; // full file name
int iend = filename.indexOf("."); //this finds the first occurrence of "."
//in string thus giving you the index of where it is in the string
// Now iend can be -1, if lets say the string had no "." at all in it i.e. no "." is found.
//So check and account for it.
String subString;
if (iend != -1)
{
subString= filename.substring(0 , iend); //this will give abc
}
Put this at the end of your app module build.gradle:
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
if (!requested.name.startsWith("multidex")) {
details.useVersion '25.3.0'
}
}
}}
Specify the keyword args linestyle
and/or marker
in your call to plot
.
For example, using a dashed line and blue circle markers:
plt.plot(range(10), linestyle='--', marker='o', color='b')
A shortcut call for the same thing:
plt.plot(range(10), '--bo')
Here is a list of the possible line and marker styles:
================ ===============================
character description
================ ===============================
- solid line style
-- dashed line style
-. dash-dot line style
: dotted line style
. point marker
, pixel marker
o circle marker
v triangle_down marker
^ triangle_up marker
< triangle_left marker
> triangle_right marker
1 tri_down marker
2 tri_up marker
3 tri_left marker
4 tri_right marker
s square marker
p pentagon marker
* star marker
h hexagon1 marker
H hexagon2 marker
+ plus marker
x x marker
D diamond marker
d thin_diamond marker
| vline marker
_ hline marker
================ ===============================
edit: with an example of marking an arbitrary subset of points, as requested in the comments:
import numpy as np
import matplotlib.pyplot as plt
xs = np.linspace(-np.pi, np.pi, 30)
ys = np.sin(xs)
markers_on = [12, 17, 18, 19]
plt.plot(xs, ys, '-gD', markevery=markers_on)
plt.show()
This last example using the markevery
kwarg is possible in since 1.4+, due to the merge of this feature branch. If you are stuck on an older version of matplotlib, you can still achieve the result by overlaying a scatterplot on the line plot. See the edit history for more details.
@ECHO OFF
SETLOCAL
set file=C:\Users\l72rugschiri\Desktop\fs.cfg
FOR %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)
Not really sure what you mean by no "function"
Obviously, change ECHO
to SET
to set the variables rather thon ECHOing them...
See for
documentation for a full list.
ceztko's test case (for reference)
@ECHO OFF
SETLOCAL
set file="C:\Users\ l72rugschiri\Desktop\fs.cfg"
FOR /F "delims=" %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)
Comment : please see comments.
Create an anchor:
<a name="anchor" id="anchor"></a>
then link to it:
<a href="http://server/page.html#anchor">Link text</a>
def my_func(mandatory_arg, optional_arg=100):
print(mandatory_arg, optional_arg)
http://docs.python.org/2/tutorial/controlflow.html#default-argument-values
I find this more readable than using **kwargs
.
To determine if an argument was passed at all, I use a custom utility object as the default value:
MISSING = object()
def func(arg=MISSING):
if arg is MISSING:
...
This issue occurs due to openssl and extension director so uncomment below extensions in php.ini
file
extension=php_openssl.dll
extension_dir = "ext"
Its works on my machine.
First things first, you need to loop to < a.length
rather than a.length - 1
. As this is strictly less than you need to include the upper bound.
So, to check all pairs of elements you can do:
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] != a[k]) {
//do stuff
}
}
}
But this will compare, for example a[2]
to a[3]
and then a[3]
to a[2]
. Given that you are checking !=
this seems wasteful.
A better approach would be to compare each element i
to the rest of the array:
for (int i = 0; i < a.length; i++) {
for (int k = i + 1; k < a.length; k++) {
if (a[i] != a[k]) {
//do stuff
}
}
}
So if you have the indices [1...5] the comparison would go
1 -> 2
1 -> 3
1 -> 4
1 -> 5
2 -> 3
2 -> 4
2 -> 5
3 -> 4
3 -> 5
4 -> 5
So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.
Do you really need to keep the session (do you have data in it?) or is it enough to fake this by reinstantiating the session when a request comes in? If the first, use the method above. If the second, try something like using the Session_End event handler.
If you have Forms Authentication, then you get something in the Global.asax.cs like
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(formsCookie.Value);
if (ticket.Expired)
{
Request.Cookies.Remove(FormsAuthentication.FormsCookieName);
FormsAuthentication.SignOut();
...
}
else
{ ...
// renew ticket if old
ticket = FormsAuthentication.RenewTicketIfOld(ticket);
...
}
And you set the ticket lifetime much longer than the session lifetime. If you're not authenticating, or using a different authentication method, there are similar tricks. Microsoft TFS web interface and SharePoint seem to use these - the give away is that if you click a link on a stale page, you get authentication prompts in the popup window, but if you just use a command, it works.
You can try:
int sum = startingNumber;
for (int i=0; i < positiveInteger; i++) {
sum += i;
}
cout << sum;
But much easier is to note that the sum 1+2+...+n = n*(n+1) / 2
, so you do not need a loop at all, just use the formula n*(n+1)/2
.
deck = []
for rank in ranks:
for suit in suits:
deck.append(('%s%s')%(rank, suit))
This can be achieved using list comprehension:
[deck.append((rank,suit)) for suit in suits for rank in ranks ]
It could be related to log4j.
Do you have log4j.jar file in the websphere java classpath (as defined in the startup file) as well as the application classpath ?
If you do make sure that the log4j.jar file is in the java classpath and that it is NOT in the web-inf/lib directory of your webapp.
It can also be related with the ant version (may be not your case, but I do put it here for reference):
You have a .class file in your class path (i.e. not a directory or a .jar file). Starting with ant 1.6, ant will open the files in the classpath checking for manifest entries. This attempted opening will fail with the error "java.util.zip.ZipException"
The problem does not exist with ant 1.5 as it does not try to open the files. - so make sure that your classpath's do not contain .class files.
On a side note, did you consider having separate jars ?
You could in the manifest of your main jar, refer to the other jars with this attribute:
Class-Path: one.jar two.jar three.jar
Then, place all of your jars in the same folder.
Again, may be not valid for your case, but still there for reference.
function handleFileSelect(evt) {_x000D_
var files = evt.target.files;_x000D_
_x000D_
// Loop through the FileList and render image files as thumbnails._x000D_
for (var i = 0, f; f = files[i]; i++) {_x000D_
_x000D_
// Only process image files._x000D_
if (!f.type.match('image.*')) {_x000D_
continue;_x000D_
}_x000D_
_x000D_
var reader = new FileReader();_x000D_
_x000D_
// Closure to capture the file information._x000D_
reader.onload = (function(theFile) {_x000D_
return function(e) {_x000D_
// Render thumbnail._x000D_
var span = document.createElement('span');_x000D_
span.innerHTML = _x000D_
[_x000D_
'<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', _x000D_
e.target.result,_x000D_
'" title="', escape(theFile.name), _x000D_
'"/>'_x000D_
].join('');_x000D_
_x000D_
document.getElementById('list').insertBefore(span, null);_x000D_
};_x000D_
})(f);_x000D_
_x000D_
// Read in the image file as a data URL._x000D_
reader.readAsDataURL(f);_x000D_
}_x000D_
}_x000D_
_x000D_
document.getElementById('files').addEventListener('change', handleFileSelect, false);
_x000D_
<input type="file" id="files" multiple />_x000D_
<output id="list"></output>
_x000D_
Just tried on my machine compiling this :
int a = ...;
int b = a * 10;
When disassembling it produces output :
MOV EAX,DWORD PTR SS:[ESP+1C] ; Move a into EAX
LEA EAX,DWORD PTR DS:[EAX+EAX*4] ; Multiply by 5 without shift !
SHL EAX, 1 ; Multiply by 2 using shift
This version is faster than your hand-optimized code with pure shifting and addition.
You really never know what the compiler is going to come up with, so it's better to simply write a normal multiplication and let him optimize the way he wants to, except in very precise cases where you know the compiler cannot optimize.
<input type="password"id="har">
<input type="submit"value="get password"onclick="har()">
<script>
function har() {
var txt_val;
txt_val = document.getElementById("har").value;
alert(txt_val);
}
</script>
I found some elegant solution on MSDN
System.Console.Write('\uXXXX') //XXXX is hex Unicode for character
This simple program writes ? right on the screen.
using System;
public class Test
{
public static void Main()
{
Console.Write('\u2103'); //? character code
}
}
use http://www.php.net/manual/en/datetime.add.php like
$date = date_create('2000-01-01');
date_add($date, date_interval_create_from_date_string('1 days'));
echo date_format($date, 'Y-m-d');
output
2000-01-2
In the .service file under the [Unit] section:
[Unit]
Description=My Website
After=syslog.target network.target mongodb.service
The important part is the mongodb.service
The manpage describes it however due to formatting it's not as clear on first sight
You need to either provide the absolute path to data.csv, or run your script in the same directory as data.csv.
If you are like me and you have the same application.properties
in src/main/resources
and src/test/resources
, and you are wondering why the application.properties
in your test folder is not overriding the application.properties
in your main resources, read on...
If you have application.properties
under src/main/resources
and the same application.properties
under src/test/resources
, which application.properties
gets picked up, depends on how you are running your tests. The folder structure src/main/resources
and src/test/resources
, is a Maven architectural convention, so if you run your test like mvnw test
or even gradlew test
, the application.properties
in src/test/resources
will get picked up, as test classpath will precede main classpath. But, if you run your test like Run as JUnit Test
in Eclipse/STS, the application.properties
in src/main/resources
will get picked up, as main classpath precedes test classpath.
You can check it out by opening the menu bar Run > Run Configurations > JUnit > *your_run_configuration* > Click on "Show Command Line"
.
You will see something like this:
XXXbin\javaw.exe -ea -Dfile.encoding=UTF-8 -classpath
XXX\workspace-spring-tool-suite-4-4.5.1.RELEASE\project_name\bin\main;
XXX\workspace-spring-tool-suite-4-4.5.1.RELEASE\project_name\bin\test;
Do you see that classpath xxx\main comes first, and then xxx\test? Right, it's all about classpath :-)
Side-note: Be mindful that properties overridden in the Launch Configuration(In Spring Tool Suite IDE, for example) takes priority over application.properties.
matches
tries to match the expression against the entire string and implicitly add a ^
at the start and $
at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:
public static void main(String[] args) throws ParseException {
Pattern p = Pattern.compile("\\d\\d\\d");
Matcher m = p.matcher("a123b");
System.out.println(m.find());
System.out.println(m.matches());
p = Pattern.compile("^\\d\\d\\d$");
m = p.matcher("123");
System.out.println(m.find());
System.out.println(m.matches());
}
/* output:
true
false
true
true
*/
123
is a substring of a123b
so the find()
method outputs true. matches()
only 'sees' a123b
which is not the same as 123
and thus outputs false.
If you mean by newline the newline character it is \n and \r is the carrier return character, but if you mean by newline the line ending then it depends on the operating system: DOS uses carriage return and line feed ("\r\n") as a line ending, which Unix uses just line feed ("\n")
I think here "inflating a view" means fetching the layout.xml file drawing a view specified in that xml file and POPULATING ( = inflating ) the parent viewGroup with the created View.
I believe the WAVE module does not support recording, just processing existing files. You might want to look at PyAudio for actually recording. WAV is about the world's simplest file format. In paInt16 you just get a signed integer representing a level, and closer to 0 is quieter. I can't remember if WAV files are high byte first or low byte, but something like this ought to work (sorry, I'm not really a python programmer:
from array import array
# you'll probably want to experiment on threshold
# depends how noisy the signal
threshold = 10
max_value = 0
as_ints = array('h', data)
max_value = max(as_ints)
if max_value > threshold:
# not silence
PyAudio code for recording kept for reference:
import pyaudio
import sys
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
frames_per_buffer=chunk)
print "* recording"
for i in range(0, 44100 / chunk * RECORD_SECONDS):
data = stream.read(chunk)
# check for silence here by comparing the level with 0 (or some threshold) for
# the contents of data.
# then write data or not to a file
print "* done"
stream.stop_stream()
stream.close()
p.terminate()
In my case, similar to this solution, I ended up using the following x-forwarded-for approach:
let ip = (req.headers['x-forwarded-for'] || '').split(',')[0];
x-forwarded-for
header will keep on adding the route of the IP from the origin all the way to the final destination server, thus if you need to retrieve the origin client's IP, this would be the first item of the array.
$(".reset").click(function() {
$(this).closest('form').find("input[type=text], textarea").val("");
});
if you are using any mobile suit like mobogenie or something that might also will make this issue. try killing that too from the task manager.
Note : i faced the same issue, tried the above solution. That didn't work, finally found out this solution.May useful for someone else!..
Have a look at Rancher.com - it can manage multiple Docker hosts and much more.
Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.
The following res:
(resource) references need to point to your model.
<add name="Entities" connectionString="metadata=
res://*/Models.WraithNath.co.uk.csdl|
res://*/Models.WraithNath.co.uk.ssdl|
res://*/Models.WraithNath.co.uk.msl;
Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).
It also may help to specify the assembly rather than using "//*/".
Worst case, you can check everything (a bit slower but should always find the resource) by using
<add name="Entities" connectionString="metadata=
res://*/;provider= <!-- ... -->
As Kris mentions, you can use the $resource
service to interact with the server, but I get the impression you are beginning your journey with Angular - I was there last week - so I recommend to start experimenting directly with the $http
service. In this case you can call its get
method.
If you have the following JSON
[{ "text":"learn angular", "done":true },
{ "text":"build an angular app", "done":false},
{ "text":"something", "done":false },
{ "text":"another todo", "done":true }]
You can load it like this
var App = angular.module('App', []);
App.controller('TodoCtrl', function($scope, $http) {
$http.get('todos.json')
.then(function(res){
$scope.todos = res.data;
});
});
The get
method returns a promise object which
first argument is a success callback and the second an error
callback.
When you add $http
as a parameter of a function Angular does it magic
and injects the $http
resource into your controller.
I've put some examples here
This is really just an expansion of BBB's answer which lead to to get my experiment working.
This script will simply create a file /tmp/testfile when you click on the button that says "Open Script".
This requires 3 files.
The File Tree:
root@test:/var/www/html# tree testscript/
testscript/
+-- index.html
+-- testexec.php
+-- test.sh
1. The main WebPage:
root@test:/var/www/html# cat testscript/index.html
<form action="/testscript/testexec.php">
<input type="submit" value="Open Script">
</form>
2. The PHP Page that runs the script and redirects back to the main page:
root@test:/var/www/html# cat testscript/testexec.php
<?php
shell_exec("/var/www/html/testscript/test.sh");
header('Location: http://192.168.1.222/testscript/index.html?success=true');
?>
3. The Script :
root@test:/var/www/html# cat testscript/test.sh
#!/bin/bash
touch /tmp/testfile
.png files are nice, but .ico files provide alpha-channel transparency, too, plus they give you backwards compatibility.
Have a look at which type StackOverflow uses for example (note that it's transparent):
<link rel="shortcut icon" href="http://sstatic.net/so/favicon.ico">
<link rel="apple-touch-icon" href="http://sstatic.net/so/apple-touch-icon.png">
The apple-itouch thingy is for iphone users that make a shortcut to a website.
A SELECT
in SQL Server will place a shared lock on a table row - and a second SELECT
would also require a shared lock, and those are compatible with one another.
So no - one SELECT
cannot block another SELECT
.
What the WITH (NOLOCK)
query hint is used for is to be able to read data that's in the process of being inserted (by another connection) and that hasn't been committed yet.
Without that query hint, a SELECT
might be blocked reading a table by an ongoing INSERT
(or UPDATE
) statement that places an exclusive lock on rows (or possibly a whole table), until that operation's transaction has been committed (or rolled back).
Problem of the WITH (NOLOCK)
hint is: you might be reading data rows that aren't going to be inserted at all, in the end (if the INSERT
transaction is rolled back) - so your e.g. report might show data that's never really been committed to the database.
There's another query hint that might be useful - WITH (READPAST)
. This instructs the SELECT
command to just skip any rows that it attempts to read and that are locked exclusively. The SELECT
will not block, and it will not read any "dirty" un-committed data - but it might skip some rows, e.g. not show all your rows in the table.
Why not just
private double translateSlider(int sliderval) {
if(sliderval > 4 || sliderval < 0)
return 1.0d;
return (1.0d - ((double)sliderval/10.0d));
}
Or similar?
That error usually occurs when you try to subtract an interval from DateTime.MinValue
or you want to add something to DateTime.MaxValue
(or you try to instantiate a date outside this min-max interval). Are you sure you're not assigning MinValue
somewhere?
You can use below script for reading child of the above xml. It will work with IE and Mozila Firefox both.
<script type="text/javascript">
function readXml(xmlFile){
var xmlDoc;
if(typeof window.DOMParser != "undefined") {
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",xmlFile,false);
if (xmlhttp.overrideMimeType){
xmlhttp.overrideMimeType('text/xml');
}
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
}
else{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.load(xmlFile);
}
var tagObj=xmlDoc.getElementsByTagName("marker");
var typeValue = tagObj[0].getElementsByTagName("type")[0].childNodes[0].nodeValue;
var titleValue = tagObj[0].getElementsByTagName("title")[0].childNodes[0].nodeValue;
}
</script>
There are a number of different solutions for finding running median from streamed data, I will briefly talk about them at the very end of the answer.
The question is about the details of the a specific solution (max heap/min heap solution), and how heap based solution works is explained below:
For the first two elements add smaller one to the maxHeap on the left, and bigger one to the minHeap on the right. Then process stream data one by one,
Step 1: Add next item to one of the heaps
if next item is smaller than maxHeap root add it to maxHeap,
else add it to minHeap
Step 2: Balance the heaps (after this step heaps will be either balanced or
one of them will contain 1 more item)
if number of elements in one of the heaps is greater than the other by
more than 1, remove the root element from the one containing more elements and
add to the other one
Then at any given time you can calculate median like this:
If the heaps contain equal amount of elements;
median = (root of maxHeap + root of minHeap)/2
Else
median = root of the heap with more elements
Now I will talk about the problem in general as promised in the beginning of the answer. Finding running median from a stream of data is a tough problem, and finding an exact solution with memory constraints efficiently is probably impossible for the general case. On the other hand, if the data has some characteristics we can exploit, we can develop efficient specialized solutions. For example, if we know that the data is an integral type, then we can use counting sort, which can give you a constant memory constant time algorithm. Heap based solution is a more general solution because it can be used for other data types (doubles) as well. And finally, if the exact median is not required and an approximation is enough, you can just try to estimate a probability density function for the data and estimate median using that.
This is the answer in 2017. urllib3
not a part of requests
anymore
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
Why docker container exits immediately?
If you want to force the image to hang around (in order to debug something or examine state of the file system) you can override the entry point to change it to a shell:
docker run -it --entrypoint=/bin/bash myimagename
Yeah that can be quite complicated since the *
is used for many different purposes in C/C++.
If *
appears in front of an already declared variable/function, it means either that:
*
gives access to the value of that variable (if the type of that variable is a pointer type, or overloaded the *
operator).*
has the meaning of the multiply operator, in that case, there has to be another variable to the left of the *
If *
appears in a variable or function declaration it means that that variable is a pointer:
int int_value = 1;
int * int_ptr; //can point to another int variable
int int_array1[10]; //can contain up to 10 int values, basically int_array1 is an pointer as well which points to the first int of the array
//int int_array2[]; //illegal, without initializer list..
int int_array3[] = {1,2,3,4,5}; // these two
int int_array4[5] = {1,2,3,4,5}; // are identical
void func_takes_int_ptr1(int *int_ptr){} // these two are identical
void func_takes_int_ptr2(int int_ptr[]){}// and legal
If &
appears in a variable or function declaration, it generally means that that variable is a reference to a variable of that type.
If &
appears in front of an already declared variable, it returns the address of that variable
Additionally you should know, that when passing an array to a function, you will always have to pass the array size of that array as well, except when the array is something like a 0-terminated cstring (char array).
One of the way you can achieve this is:
Now your java program can be opened in a fancy way just like any other MSWindows apps.! :)
This article http://technet.microsoft.com/en-us/library/ee198810.aspx led me to the solution. The only change is the placement of the exclamation mark.
(!manager=*)
It seems to be working just as wanted.
Use a timer with an interval set to 2–3 seconds.
You have three different options to choose from, depending on which type of application you're writing:
Don't use Thread.Sleep
if your application need to process any inputs on that thread at the same time (WinForms, WPF), as Sleep
will completely lock up the thread and prevent it from processing other messages. Assuming a single-threaded application (as most are), your entire application will stop responding, rather than just delaying an operation as you probably intended. Note that it may be fine to use Sleep in pure console application as there are no "events" to handle or on separate thread (also Task.Delay
is better option).
In addition to timers and Sleep
you can use Task.Delay
which is asynchronous version of Sleep
that does not block thread from processing events (if used properly - don't turn it into infinite sleep with .Wait()
).
public async void ClickHandler(...)
{
// whatever you need to do before delay goes here
await Task.Delay(2000);
// whatever you need to do after delay.
}
The same await Task.Delay(2000)
can be used in a Main
method of a console application if you use C# 7.1 (Async main on MSDN blogs).
Note: delaying operation with Sleep
has benefit of avoiding race conditions that comes from potentially starting multiple operations with timers/Delay
. Unfortunately freezing UI-based application is not acceptable so you need to think about what will happen if you start multiple delays (i.e. if it is triggered by a button click) - consider disabling such button, or canceling the timer/task or making sure delayed operation can be done multiple times safely.
Didn't find the voted solutions satisfactory. So I wrote something thats is kind of generic and works both first and last part of your text (something like substr but for words). Also you can set if you'd like the spaces to be left out in the char-count.
function chopTxtMinMax(txt, firstChar, lastChar=0){
var wordsArr = txt.split(" ");
var newWordsArr = [];
var totalIteratedChars = 0;
var inclSpacesCount = true;
for(var wordIndx in wordsArr){
totalIteratedChars += wordsArr[wordIndx].length + (inclSpacesCount ? 1 : 0);
if(totalIteratedChars >= firstChar && (totalIteratedChars <= lastChar || lastChar==0)){
newWordsArr.push(wordsArr[wordIndx]);
}
}
txt = newWordsArr.join(" ");
return txt;
}
math.fabs()
converts its argument to float if it can (if it can't, it throws an exception). It then takes the absolute value, and returns the result as a float.
In addition to floats, abs()
also works with integers and complex numbers. Its return type depends on the type of its argument.
In [7]: type(abs(-2))
Out[7]: int
In [8]: type(abs(-2.0))
Out[8]: float
In [9]: type(abs(3+4j))
Out[9]: float
In [10]: type(math.fabs(-2))
Out[10]: float
In [11]: type(math.fabs(-2.0))
Out[11]: float
In [12]: type(math.fabs(3+4j))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/npe/<ipython-input-12-8368761369da> in <module>()
----> 1 type(math.fabs(3+4j))
TypeError: can't convert complex to float
Another way to phrase the question is "What is the nearest commit that resides on a branch other than the current branch, and which branch is that?"
You can find it with a little bit of command line magic
git show-branch \
| sed "s/].*//" \
| grep "\*" \
| grep -v "$(git rev-parse --abbrev-ref HEAD)" \
| head -n1 \
| sed "s/^.*\[//"
With awk:
git show-branch -a \
| grep '\*' \
| grep -v `git rev-parse --abbrev-ref HEAD` \
| head -n1 \
| sed 's/[^\[]*//' \
| awk 'match($0, /\[[a-zA-Z0-9\/-]+\]/) { print substr( $0, RSTART+1, RLENGTH-2 )}'
Running the above code on
A---B---D <-master
\
\
C---E---I <-develop
\
\
F---G---H <-topic
Will give you develop
if you run it from H and master
if you run it from I.
For ListFragment use
getListView().setDivider(null)
after the list has been obtained.
You can also try this. Credits to the original author who has since removed the script
/mobile.class.php
<?php
/*
=====================================================
Mobile version detection
-----------------------------------------------------
compliments of http://www.buchfelder.biz/
=====================================================
*/
$mobile = "http://www.stepforth.mobi";
$text = $_SERVER['HTTP_USER_AGENT'];
$var[0] = 'Mozilla/4.';
$var[1] = 'Mozilla/3.0';
$var[2] = 'AvantGo';
$var[3] = 'ProxiNet';
$var[4] = 'Danger hiptop 1.0';
$var[5] = 'DoCoMo/';
$var[6] = 'Google CHTML Proxy/';
$var[7] = 'UP.Browser/';
$var[8] = 'SEMC-Browser/';
$var[9] = 'J-PHONE/';
$var[10] = 'PDXGW/';
$var[11] = 'ASTEL/';
$var[12] = 'Mozilla/1.22';
$var[13] = 'Handspring';
$var[14] = 'Windows CE';
$var[15] = 'PPC';
$var[16] = 'Mozilla/2.0';
$var[17] = 'Blazer/';
$var[18] = 'Palm';
$var[19] = 'WebPro/';
$var[20] = 'EPOC32-WTL/';
$var[21] = 'Tungsten';
$var[22] = 'Netfront/';
$var[23] = 'Mobile Content Viewer/';
$var[24] = 'PDA';
$var[25] = 'MMP/2.0';
$var[26] = 'Embedix/';
$var[27] = 'Qtopia/';
$var[28] = 'Xiino/';
$var[29] = 'BlackBerry';
$var[30] = 'Gecko/20031007';
$var[31] = 'MOT-';
$var[32] = 'UP.Link/';
$var[33] = 'Smartphone';
$var[34] = 'portalmmm/';
$var[35] = 'Nokia';
$var[36] = 'Symbian';
$var[37] = 'AppleWebKit/413';
$var[38] = 'UPG1 UP/';
$var[39] = 'RegKing';
$var[40] = 'STNC-WTL/';
$var[41] = 'J2ME';
$var[42] = 'Opera Mini/';
$var[43] = 'SEC-';
$var[44] = 'ReqwirelessWeb/';
$var[45] = 'AU-MIC/';
$var[46] = 'Sharp';
$var[47] = 'SIE-';
$var[48] = 'SonyEricsson';
$var[49] = 'Elaine/';
$var[50] = 'SAMSUNG-';
$var[51] = 'Panasonic';
$var[52] = 'Siemens';
$var[53] = 'Sony';
$var[54] = 'Verizon';
$var[55] = 'Cingular';
$var[56] = 'Sprint';
$var[57] = 'AT&T;';
$var[58] = 'Nextel';
$var[59] = 'Pocket PC';
$var[60] = 'T-Mobile';
$var[61] = 'Orange';
$var[62] = 'Casio';
$var[63] = 'HTC';
$var[64] = 'Motorola';
$var[65] = 'Samsung';
$var[66] = 'NEC';
$result = count($var);
for ($i=0;$i<$result;$i++)
{
$ausg = stristr($text, $var[$i]);
if(strlen($ausg)>0)
{
header("location: $mobile");
exit;
}
}
?>
Just edit the $mobile = "http://www.stepforth.mobi";
You can always encrypt data on the client side. Please note that not all of the data have to be encrypted because it has a performance issue.
Good answers but I see most of them has some problems: First of all I think a good answer should work for complete file names which have their path headings, also it should work for linux or windows or as mentioned it should be cross platform. For most of answers; file names with no extension but a path with a folder name including dot, the function will fail to return the correct extension: examples of some test cases could be as follow:
const char filename1 = {"C:\\init.d\\doc"}; // => No extention
const char filename2 = {"..\\doc"}; //relative path name => No extention
const char filename3 = {""}; //emputy file name => No extention
const char filename4 = {"testing"}; //only single name => No extention
const char filename5 = {"tested/k.doc"}; // normal file name => doc
const char filename6 = {".."}; // parent folder => No extention
const char filename7 = {"/"}; // linux root => No extention
const char filename8 = {"/bin/test.d.config/lx.wize.str"}; // ordinary path! => str
"brian newman" suggestion will fail for filename1 and filename4. and most of other answers which are based on reverse find will fail for filename1. I suggest including the following method in your source: which is function returning index of first character of extension or the length of given string if not found.
size_t find_ext_idx(const char* fileName)
{
size_t len = strlen(fileName);
size_t idx = len-1;
for(size_t i = 0; *(fileName+i); i++) {
if (*(fileName+i) == '.') {
idx = i;
} else if (*(fileName + i) == '/' || *(fileName + i) == '\\') {
idx = len - 1;
}
}
return idx+1;
}
you could use the above code in your c++ application like below:
std::string get_file_ext(const char* fileName)
{
return std::string(fileName).substr(find_ext_idx(fileName));
}
The last point in some cases the a folder is given to file name as argument and includes a dot in the folder name the function will return folder's dot trailing so better first to user check that the given name is a filename and not folder name.
I don't think you need to remove "#" from href. Following works with Angularjs 1.2.10
<a href="#/" ng-click="logout()">Logout</a>
hey all everyone is over thinking this all you need to do is wrap the nav in a like below:
csscode:
#navwrap {
height: 100px; (change dependant on hight of nav)
width: 100%;
margin: 0;
padding-top: 5px;
}
HTML:
<div id="navwrap">
nav code inside
</div>
you can achieve that using Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously.
Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. reference
When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance.
DatabaseMetaData.supportsBatchUpdates()
method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.executeBatch()
is used to start the execution of all the statements grouped together.addBatch()
method. However, you cannot selectively choose which statement to remove.EXAMPLE:
import java.sql.*;
public class jdbcConn {
public static void main(String[] args) throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","name","pass");
Statement stmt = con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String insertEmp1 = "insert into emp values
(10,'jay','trainee')";
String insertEmp2 = "insert into emp values
(11,'jayes','trainee')";
String insertEmp3 = "insert into emp values
(12,'shail','trainee')";
con.setAutoCommit(false);
stmt.addBatch(insertEmp1);//inserting Query in stmt
stmt.addBatch(insertEmp2);
stmt.addBatch(insertEmp3);
ResultSet rs = stmt.executeQuery("select * from emp");
rs.last();
System.out.println("rows before batch execution= "
+ rs.getRow());
stmt.executeBatch();
con.commit();
System.out.println("Batch executed");
rs = stmt.executeQuery("select * from emp");
rs.last();
System.out.println("rows after batch execution= "
+ rs.getRow());
}
}
refer http://www.tutorialspoint.com/javaexamples/jdbc_executebatch.htm
I believe your problem is this: in your while loop, n is divided by 2, but never cast as an integer again, so it becomes a float at some point. It is then added onto y, which is then a float too, and that gives you the warning.
Assuming you want to add this path for all users on the system, add the following line to your /etc/profile.d/play.sh
(and possibly play.csh
, etc):
PATH=$PATH:/home/me/play
export PATH
import React, {Component} from 'react';
export default class ChatOutPut extends Component {
constructor(props) {
super(props);
this.state = {
messages: props.chatmessages
};
}
componentDidUpdate = (previousProps, previousState) => {
if (this.refs.chatoutput != null) {
this.refs.chatoutput.scrollTop = this.refs.chatoutput.scrollHeight;
}
}
renderMessage(data) {
return (
<div key={data.key}>
{data.message}
</div>
);
}
render() {
return (
<div ref='chatoutput' className={classes.chatoutputcontainer}>
{this.state.messages.map(this.renderMessage, this)}
</div>
);
}
}
This answer is pretty similar to Oz.'s, using <chrono>
for C++ -- I didn't grab it from Oz. though...
I picked up the original snippet at the bottom of this page, and slightly modified it to be a complete console app. I love using this lil' ol' thing. It's fantastic if you do a lot of scripting and need a reliable tool in Windows to get the epoch in actual milliseconds without resorting to using VB, or some less modern, less reader-friendly code.
#include <chrono>
#include <iostream>
int main() {
unsigned __int64 now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
std::cout << now << std::endl;
return 0;
}
purrr::flatten_*()
is also a good option. the flatten_*
functions add thin sanity checks and ensure type safety.
myList <- list('A'=1, 'B'=2, 'C'=3)
purrr::flatten_dbl(myList)
## [1] 1 2 3
Right from the PHP Docs: PHP 5.3 Windows binaries uses the static version of the MCrypt library, no DLL are needed.
http://php.net/manual/en/mcrypt.requirements.php
But if you really want to download it, just go to the mcrypt sourceforge page
Since the accepted answer does not allow more edits, I'm going to summarize it with a single copy-paste command (Replace 3.2.1 with the latest version available in the first line):
version="3.2.1" && \
wget "https://github.com/glfw/glfw/releases/download/${version}/glfw-${version}.zip" && \
unzip glfw-${version}.zip && \
cd glfw-${version} && \
sudo apt-get install cmake xorg-dev libglu1-mesa-dev && \
sudo cmake -G "Unix Makefiles" && \
sudo make && \
sudo make install
If you want to compile a program use the following commands:
g++ -std=c++11 -c main.cpp && \
g++ main.o -o main.exec -lGL -lGLU -lglfw3 -lX11 -lXxf86vm -lXrandr -lpthread -lXi -ldl -lXinerama -lXcursor
If you are following the learnopengl.com tutorial you may have to set up GLAD as well. In such case click on this link
and then click on the "Generate" button at the bottom right corner of the website and download the zip file. Extract it and compile the sources with the following command:
g++ glad/src/glad.c -c -Iglad/include
Now, the commands to compile your program become like this:
g++ -std=c++11 -c main.cpp -Iglad/include && \
g++ main.o glad.o -o main.exec -lGL -lGLU -lglfw3 -lX11 -lXxf86vm -lXrandr -lpthread -lXi -ldl -lXinerama -lXcursor
Jenkins has a link to their REST API in the bottom right of each page. This link appears on every page of Jenkins and points you to an API output for the exact page you are browsing. That should provide some understanding into how to build the API URls.
You can additionally use some wrapper, like I do, in Python, using http://jenkinsapi.readthedocs.io/en/latest/
Here is their website: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API
Try this:
setlocal EnableDelayedExpansion
...
for /F "tokens=*" %%a in ('type %FileName%') do (
set z=%%a
echo !z!
echo %%a
)
Try to use WebConfigurationManager
instead of ConfigurationManager
Apparently, it is possible. From the manual:
You can specify multiple tables in a DELETE statement to delete rows from one or more tables depending on the particular condition in the WHERE clause. However, you cannot use ORDER BY or LIMIT in a multiple-table DELETE. The table_references clause lists the tables involved in the join. Its syntax is described in Section 12.2.8.1, “JOIN Syntax”.
The example in the manual is:
DELETE t1, t2 FROM t1 INNER JOIN t2 INNER JOIN t3
WHERE t1.id=t2.id AND t2.id=t3.id;
should be applicable 1:1.
I create the tag like this and then I push it to GitHub:
git tag -a v1.1 -m "Version 1.1 is waiting for review"
git push --tags
Counting objects: 1, done.
Writing objects: 100% (1/1), 180 bytes, done.
Total 1 (delta 0), reused 0 (delta 0)
To [email protected]:neoneye/triangle_draw.git
* [new tag] v1.1 -> v1.1
If this is UNIX:
sort -k 2 file.txt
You can use multiple -k
flags to sort on more than one column. For example, to sort by family name then first name as a tie breaker:
sort -k 2,2 -k 1,1 file.txt
Relevant options from "man sort":
-k, --key=POS1[,POS2]
start a key at POS1, end it at POS2 (origin 1)
POS is F[.C][OPTS], where F is the field number and C the character position in the field. OPTS is one or more single-letter ordering options, which override global ordering options for that key. If no key is given, use the entire line as the key.
-t, --field-separator=SEP
use SEP instead of non-blank to blank transition
The pop-up window does not have any close event that you can listen to.
On the other hand, there is a closed property that is set to true when the window gets closed.
You can set a timer to check that closed property and do it like this:
var win = window.open('foo.html', 'windowName',"width=200,height=200,scrollbars=no");
var timer = setInterval(function() {
if(win.closed) {
clearInterval(timer);
alert('closed');
}
}, 1000);
See this working Fiddle example!
If you're using fs-extra, you can skip the JSON.stringify
part with the writeJson function:
const fsExtra = require('fs-extra');
fsExtra.writeJson('./package.json', {name: 'fs-extra'})
.then(() => {
console.log('success!')
})
.catch(err => {
console.error(err)
})
Run Spring Boot app using Maven
You can also use Maven plugin to run your Spring Boot app. Use the below example to run your Spring Boot app with Maven plugin:
mvn spring-boot:run
Run Spring Boot App with Gradle
And if you use Gradle you can run the Spring Boot app with the following command:
gradle bootRun
I like Alex FTPS Client which is written by a Microsoft MVP name Alex Pilotti. It's a C# library you can use in Console apps, Windows Forms, PowerShell, ASP.NET (in any .NET language). If you have a multithreaded app you will have to configure the library to run syncronously, but overall a good client that will most likely get you what you need.
def _GetHtmlPage(self, addr):
headers = { 'User-Agent' : self.userAgent,
' Cookie' : self.cookies}
req = urllib2.Request(addr)
response = urllib2.urlopen(req)
print "ResponseInfo="
print response.info()
resultsHtml = unicode(response.read(), self.encoding)
return resultsHtml
char *s does not have some memory allocated . You need to allocate it manually in your case . You can do it as follows
s = (char *)malloc(100) ;
This would not lead to segmentation fault error as you will not be refering to an unknown location anymore
I found this problem continued even when setting the BODY MARGIN to zero.
However it turns out there is an easy fix. All you need to do is give your HEADER tag a 1px border, aswell as setting the BODY MARGIN to zero, as shown below.
body { margin:0px; }
header { border:1px black solid; }
You may also need to change the MARGIN to zero for any H1, H2, etc. elements you have within your HEADER div. This will get rid of any extra space which may show around the text.
Not sure why this works, but I use Chrome browser. Obviously you can also change the colour of the border to match your header colour.
Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal (i.e. the first is greater or smaller than the second) then that's the result of the comparison, else the second item is considered, then the third and so on.
See Common Sequence Operations:
Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.
Also Value Comparisons for further details:
Lexicographical comparison between built-in collections works as follows:
- For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example,
[1,2] == (1,2)
is false because the type is not the same).- Collections that support order comparison are ordered the same as their first unequal elements (for example,
[1,2,x] <= [1,2,y]
has the same value asx <= y
). If a corresponding element does not exist, the shorter collection is ordered first (for example,[1,2] < [1,2,3]
is true).
If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is considered smaller (for example, [1,2] < [1,2,3] returns True).
Note 1: <
and >
do not mean "smaller than" and "greater than" but "is before" and "is after": so (0, 1) "is before" (1, 0).
Note 2: tuples must not be considered as vectors in a n-dimensional space, compared according to their length.
Note 3: referring to question https://stackoverflow.com/questions/36911617/python-2-tuple-comparison: do not think that a tuple is "greater" than another only if any element of the first is greater than the corresponding one in the second.
EDIT: between other options there's a nice library that could solve your issue: https://github.com/daimajia/AndroidSwipeLayout
Alpine Linux does not have any default location at all. The file /etc/nginx/conf.d/default.conf
says:
# Everything is a 404
location / {
return 404;
}
# You may need this to prevent return 404 recursion.
location = /404.html {
internal;
}
Replace those with a line like root /var/www/localhost/htdocs
to point to the directory you want. Then sudo service nginx restart
to restart.
As per dart 2.6
The optional onError
parameter of int.parse
is deprecated. Therefore, you should use int.tryParse
instead.
Note:
The same applies to double.parse
. Therefore, use double.tryParse
instead.
/**
* ...
*
* The [onError] parameter is deprecated and will be removed.
* Instead of `int.parse(string, onError: (string) => ...)`,
* you should use `int.tryParse(string) ?? (...)`.
*
* ...
*/
external static int parse(String source, {int radix, @deprecated int onError(String source)});
The difference is that int.tryParse
returns null
if the source string is invalid.
/**
* Parse [source] as a, possibly signed, integer literal and return its value.
*
* Like [parse] except that this function returns `null` where a
* similar call to [parse] would throw a [FormatException],
* and the [source] must still not be `null`.
*/
external static int tryParse(String source, {int radix});
So, in your case it should look like:
// Valid source value
int parsedValue1 = int.tryParse('12345');
print(parsedValue1); // 12345
// Error handling
int parsedValue2 = int.tryParse('');
if (parsedValue2 == null) {
print(parsedValue2); // null
//
// handle the error here ...
//
}
SELECT character_set_name
FROM information_schema.character_sets
;
information_schema
From the SQL-standard schema information_schema
present in every database/catalog, use the defined view named character_sets
. This approach should be portable across all standard database systems.
SELECT *
FROM information_schema.character_sets
;
Despite the name being plural, it shows only a single row, reporting on the current database/catalog.
The third column is character_set_name
:
Name of the character set, currently implemented as showing the name of the database encoding
You can also use SugarJS in NodeJS.
They have a very clean clone feature: http://sugarjs.com/api/Object/clone
You can use the following code when your processor runs on .NET or uses MSXML (as opposed to Java-based or other native processors). It uses msxsl:script
.
Make sure to add the namespace xmlns:msxsl="urn:schemas-microsoft-com:xslt"
to your root xsl:stylesheet
or xsl:transform
element.
In addition, bind outlet
to any namespace you like, for instance xmlns:outlet = "http://my.functions"
.
<msxsl:script implements-prefix="outlet" language="javascript">
function replace_str(str_text,str_replace,str_by)
{
return str_text.replace(str_replace,str_by);
}
</msxsl:script>
<xsl:variable name="newtext" select="outlet:replace_str(string(@oldstring),'me','you')" />
argc
is the number of arguments being passed into your program from the command line and argv
is the array of arguments.
You can loop through the arguments knowing the number of them like:
for(int i = 0; i < argc; i++)
{
// argv[i] is the argument at index i
}
window.location.href
returns the location of the current page.
top.location.href
(which is an alias of window.top.location.href
) returns the location of the topmost window in the window hierarchy. If a window has no parent, top
is a reference to itself (in other words, window
=== window.top
).
top
is useful both when you're dealing with frames and when dealing with windows which have been opened by other pages. For example, if you have a page called test.html
with the following script:
var newWin=window.open('about:blank','test','width=100,height=100');
newWin.document.write('<script>alert(top.location.href);</script>');
The resulting alert will have the full path to test.html – not about:blank, which is what window.location.href
would return.
To answer your question about redirecting, go with window.location.assign(url);
Essentially:
<?php
//somewhere set a value
$var = "a value";
?>
<script>
// then echo it into the js/html stream
// and assign to a js variable
spge = '<?php echo $var ;?>';
// then
alert(spge);
</script>
I know this is an old post but I had a lot of issues trying to solve this and I finally did so I wanted to share.
My issue was that I was adding an event listener within the ontouchstart and removing it in the ontouchend functions - something like this
function onTouchStart() {
window.addEventListener("touchmove", handleTouchMove, {
passive: false
});
}
function onTouchEnd() {
window.removeEventListener("touchmove", handleTouchMove, {
passive: true
});
}
function handleTouchMove(e) {
e.preventDefault();
}
For some reason adding it removing it like this was causing this issue of the event randomly not being cancelable. So to solve this I kept the listener active and toggled a boolean on whether or not it should prevent the event - something like this:
let stopScrolling = false;
window.addEventListener("touchmove", handleTouchMove, {
passive: false
});
function handleTouchMove(e) {
if (!stopScrolling) {
return;
}
e.preventDefault();
}
function onTouchStart() {
stopScrolling = true;
}
function onTouchEnd() {
stopScrolling = false;
}
I was actually using React so my solution involved setting state, but I've simplified it for a more generic solution. Hopefully this helps someone!
Java will not throw an exception if you divide by float zero. It will detect a run-time error only if you divide by integer zero not double zero.
If you divide by 0.0, the result will be INFINITY.
It's perfectly valid to use break
- as others have pointed out, it's nowhere in the same league as goto
.
Although you might want to use the vFound
variable when you want to check outside the loop whether the value was found in the array. Also from a maintainability point of view, having a common flag signalling the exit criteria might be useful.
edit the file /etc/eclipse.ini
, so as to contain entry as;
-Duser.name=myname
Restart the "eclipse" and now, on creation of any new file, with wizard (c/c++/java), it will use "myname" in place of ${user}.
In SQL Plus:
SQL> var r refcursor
SQL> set autoprint on
SQL> exec :r := function_returning_refcursor();
Replace the last line with a call to your procedure / function and the contents of the refcursor will be displayed
You actually can do this you can basically listen for this pop up to happen and then confirm true before it ever "pops up",
if(window.alert){
return true
}
If you are ok to do transformation, you may try this.
DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());
As of Vista, cacls
is deprecated. Here's the first couple of help lines:
C:\>cacls
NOTE: Cacls is now deprecated, please use Icacls.
Displays or modifies access control lists (ACLs) of files
You should use icacls
instead. This is how you grant John full control over D:\test
folder and all its subfolders:
C:\>icacls "D:\test" /grant John:(OI)(CI)F /T
According do MS documentation:
F
= Full ControlCI
= Container Inherit - This flag indicates that subordinate containers will inherit this ACE.OI
= Object Inherit - This flag indicates that subordinate files will inherit the ACE./T
= Apply recursively to existing files and sub-folders. (OI
and CI
only apply to new files and sub-folders). Credit: comment by @AlexSpence.For complete documentation, you may run "icacls
" with no arguments or see the Microsoft documentation here and here
/* Important part */
.modal-dialog{
overflow-y: initial !important
}
.modal-body{
max-height: calc(100vh - 200px);
overflow-y: auto;
}
This works for Bootstrap 3 without JS code and is responsive.
1.We are using Hadoop for storing Large data (i.e.structure,Unstructure and Semistructure data ) in the form file format like txt,csv.
2.If We want columnar Updations in our data then we are using Hbase tool
3.In case of Hive , we are storing Big data which is in structured format and in addition to that we are providing Analysis on that data.
4.Pig is tool which is using Pig latin language to analyze data which is in any format(structure,semistructure and unstructure).
As Joshua M pointed out, the zoom function isn't supported only in Firefox, but you can simply fix this as shown:
div.zoom {
zoom: 2; /* all browsers */
-moz-transform: scale(2); /* Firefox */
}
I prefer to use double quotes , as single quptes are very powerful as we used them if dont able to change anything inside it or can invoke the variable substituion .
so use double quotes instaed.
echo $LINE | sed -e "s/12345678/$replace/g"
Controller:
public JsonResult GetProductsData()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:5136/api/");
//HTTP GET
var responseTask = client.GetAsync("product");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<IList<product>>();
readTask.Wait();
var alldata = readTask.Result;
var rsproduct = from x in alldata
select new[]
{
Convert.ToString(x.pid),
Convert.ToString(x.pname),
Convert.ToString(x.pprice),
};
return Json(new
{
aaData = rsproduct
},
JsonRequestBehavior.AllowGet);
}
else //web api sent error response
{
//log response status here..
var pro = Enumerable.Empty<product>();
return Json(new
{
aaData = pro
},
JsonRequestBehavior.AllowGet);
}
}
}
public JsonResult InupProduct(string id,string pname, string pprice)
{
try
{
product obj = new product
{
pid = Convert.ToInt32(id),
pname = pname,
pprice = Convert.ToDecimal(pprice)
};
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:5136/api/product");
if(id=="0")
{
//insert........
//HTTP POST
var postTask = client.PostAsJsonAsync<product>("product", obj);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
return Json(1, JsonRequestBehavior.AllowGet);
}
else
{
return Json(0, JsonRequestBehavior.AllowGet);
}
}
else
{
//update........
//HTTP POST
var postTask = client.PutAsJsonAsync<product>("product", obj);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
return Json(1, JsonRequestBehavior.AllowGet);
}
else
{
return Json(0, JsonRequestBehavior.AllowGet);
}
}
}
/*context.InUPProduct(Convert.ToInt32(id),pname,Convert.ToDecimal(pprice));
return Json(1, JsonRequestBehavior.AllowGet);*/
}
catch (Exception ex)
{
return Json(0, JsonRequestBehavior.AllowGet);
}
}
public JsonResult deleteRecord(int ID)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:5136/api/product");
//HTTP DELETE
var deleteTask = client.DeleteAsync("product/" + ID);
deleteTask.Wait();
var result = deleteTask.Result;
if (result.IsSuccessStatusCode)
{
return Json(1, JsonRequestBehavior.AllowGet);
}
else
{
return Json(0, JsonRequestBehavior.AllowGet);
}
}
/* var data = context.products.Where(x => x.pid == ID).FirstOrDefault();
context.products.Remove(data);
context.SaveChanges();
return Json(1, JsonRequestBehavior.AllowGet);*/
}
catch (Exception ex)
{
return Json(0, JsonRequestBehavior.AllowGet);
}
}
If you need for check your string for Is All char is 0 :
static public bool IsAllZero (this string input)
{
if(string.IsNullOrEmpty(input))
return true;
foreach (char ch in input)
{
if(ch != '0')
return false;
}
return true;
}
Nvm Nvm is a script-based node version manager. You can install it easily with a curl and bash one-liner as described in the documentation. It's also available on Homebrew.
Assuming you have successfully installed nvm. The following will install the latest version of node.
nvm install node --reinstall-packages-from=node
The last option installs all global npm packages over to your new version. This way packages like mocha and node-inspector keep working.
N
N is an npm-based node version manager. You can install it by installing first some version of node and then running npm install -g n
.
Assuming you have successfully installed n. The following will install the latest version of node.
sudo n latest
Homebrew Homebrew is one of the two popular package managers for Mac. Assuming you have previously installed node with brew install node. You can get up-to-date with formulae and upgrade to the latest Node.js version with the following.
1 brew update
2 brew upgrade node
MacPorts MacPorts is the another package manager for Mac. The following will update the local ports tree to get access to updated versions. Then it will install the latest version of Node.js. This works even if you have previous version of the package installed.
1 sudo port selfupdate
2 sudo port install nodejs-devel
The nextInt()
method leaves the \n
(end line) symbol and is picked up immediately by nextLine()
, skipping over the next input. What you want to do is use nextLine()
for everything, and parse it later:
String nextIntString = keyboard.nextLine(); //get the number as a single line
int nextInt = Integer.parseInt(nextIntString); //convert the string to an int
This is by far the easiest way to avoid problems--don't mix your "next" methods. Use only nextLine()
and then parse int
s or separate words afterwards.
Also, make sure you use only one Scanner
if your are only using one terminal for input. That could be another reason for the exception.
Last note: compare a String
with the .equals()
function, not the ==
operator.
if (playAgain == "yes"); // Causes problems
if (playAgain.equals("yes")); // Works every time
I never tried, but doing a google search, Jailcoder looks like a solution. The problem is the device need to be jailbroken. If anyone try this, please comment and let us know how it worked.
I have used this very often in neural networks. It is well known that when we start training a neural network we randomly initialise the weights. The model is trained on these weights on a particular dataset. After number of epochs you get trained set of weights.
Now suppose you want to again train from scratch or you want to pass the model to others to reproduce your results, the weights will be again initialised to a random numbers which mostly will be different from earlier ones. The obtained trained weights after same number of epochs ( keeping same data and other parameters ) as earlier one will differ. The problem is your model is no more reproducible that is every time you train your model from scratch it provides you different sets of weights. This is because the model is being initialized by different random numbers every time.
What if every time you start training from scratch the model is initialised to the same set of random initialise weights? In this case your model could become reproducible. This is achieved by numpy.random.seed(0). By mentioning seed() to a particular number, you are hanging on to same set of random numbers always.
Most of the time you can just npm update (or yarn upgrade) a module to get the latest non breaking changes (respecting the semver specified in your package.json) (<-- read that last part again).
npm update browser-sync
-------
yarn upgrade browser-sync
- Use
npm|yarn outdated
to see which modules have newer versions- Use
npm update|yarn upgrade
(without a package name) to update all modules- Include
--save-dev|--dev
if you want to save the newer version numbers to your package.json. (NOTE: as of npm v5.0 this is only necessary fordevDependencies
).
Major version upgrades:
In your case, it looks like you want the next major version (v2.x.x), which is likely to have breaking changes and you will need to update your app to accommodate those changes. You can install/save the latest 2.x.x
by doing:
npm install browser-sync@2 --save-dev
-------
yarn add browser-sync@2 --dev
...or the latest 2.1.x
by doing:
npm install [email protected] --save-dev
-------
yarn add [email protected] --dev
...or the latest and greatest by doing:
npm install browser-sync@latest --save-dev
-------
yarn add browser-sync@latest --dev
Note: the last one is no different than doing this:
npm uninstall browser-sync --save-dev npm install browser-sync --save-dev ------- yarn remove browser-sync --dev yarn add browser-sync --dev
The
--save-dev
part is important. This will uninstall it, remove the value from your package.json, and then reinstall the latest version and save the new value to your package.json.
That you are running Windows. Read:
http://en.wikipedia.org/wiki/Sudo
It basically allows you to execute an application with elevated privileges. If you want to achieve a similar effect under Windows, open an administrative prompt and execute your command from there. Under Vista, this is easily done by opening the shortcut while holding Ctrl+Shift at the same time.
That being said, it might very well be possible that your account already has sufficient privileges, depending on how your OS is setup, and the Windows version used.
You can use an enum like in this example:
public class MainClass {
enum Choice { Choice1, Choice2, Choice3 }
public static void main(String[] args) {
Choice ch = Choice.Choice1;
switch(ch) {
case Choice1:
System.out.println("Choice1 selected");
break;
case Choice2:
System.out.println("Choice2 selected");
break;
case Choice3:
System.out.println("Choice3 selected");
break;
}
}
}
Source: Switch statement with enum
from sklearn.metrics import mean_squared_error
rmse = mean_squared_error(y_actual, y_predicted, squared=False)
or
import math
from sklearn.metrics import mean_squared_error
rmse = math.sqrt(mean_squared_error(y_actual, y_predicted))
You could use a Comparator with Java's built-in methods for sorting and binary search. Suppose you have a class like this, where a and b are the fields you want to use for sorting:
class Thing { String a, b, c, d; }
You would define your Comparator:
Comparator<Thing> comparator = new Comparator<Thing>() {
public int compare(Thing o1, Thing o2) {
if (o1.a.equals(o2.a)) {
return o1.b.compareTo(o2.b);
}
return o1.a.compareTo(o2.a);
}
};
Then sort your list:
Collections.sort(list, comparator);
And finally do the binary search:
int i = Collections.binarySearch(list, thingToFind, comparator);
The terms "background page", "popup", "content script" are still confusing you; I strongly suggest a more in-depth look at the Google Chrome Extensions Documentation.
Regarding your question if content scripts or background pages are the way to go:
Content scripts: Definitely
Content scripts are the only component of an extension that has access to the web-page's DOM.
Background page / Popup: Maybe (probably max. 1 of the two)
You may need to have the content script pass the DOM content to either a background page or the popup for further processing.
Let me repeat that I strongly recommend a more careful study of the available documentation!
That said, here is a sample extension that retrieves the DOM content on StackOverflow pages and sends it to the background page, which in turn prints it in the console:
background.js:
// Regex-pattern to check URLs against.
// It matches URLs like: http[s]://[...]stackoverflow.com[...]
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.com/;
// A function to use as callback
function doStuffWithDom(domContent) {
console.log('I received the following DOM content:\n' + domContent);
}
// When the browser-action button is clicked...
chrome.browserAction.onClicked.addListener(function (tab) {
// ...check the URL of the active tab against our pattern and...
if (urlRegex.test(tab.url)) {
// ...if it matches, send a message specifying a callback too
chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
}
});
content.js:
// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
// If the received message has the expected format...
if (msg.text === 'report_back') {
// Call the specified callback, passing
// the web-page's DOM content as argument
sendResponse(document.all[0].outerHTML);
}
});
manifest.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
...
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["*://*.stackoverflow.com/*"],
"js": ["content.js"]
}],
"browser_action": {
"default_title": "Test Extension"
},
"permissions": ["activeTab"]
}
Bottom up with O(n) space solution
#include <stdio.h>
void print_all_subset(int *A, int len, int *B, int len2, int index)
{
if (index >= len)
{
for (int i = 0; i < len2; ++i)
{
printf("%d ", B[i]);
}
printf("\n");
return;
}
print_all_subset(A, len, B, len2, index+1);
B[len2] = A[index];
print_all_subset(A, len, B, len2+1, index+1);
}
int main()
{
int A[] = {1, 2, 3, 4, 5, 6, 7};
int B[7] = {0};
print_all_subset(A, 7, B, 0, 0);
}
You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model
Post.objects.all().delete()
and to delete any Post with a future publication date
Post.objects.filter(pub_date__gt=datetime.now()).delete()
You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.
EDIT:
Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForm
s and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.
I know the question is from 2012, but I found the easiest way ever, and I wanted to share.
HTML:
<div id="parent">
<div id="child">Content here</div>
</div>
and CSS:
#parent{
height: 100%;
display: table;
}
#child {
display: table-cell;
vertical-align: middle;
}
This is how I solved my problem:
List<User> list = GetAllUsers(); //Private Method
if (!sortAscending)
{
list = list
.OrderBy(r => r.GetType().GetProperty(sortBy).GetValue(r,null))
.ToList();
}
else
{
list = list
.OrderByDescending(r => r.GetType().GetProperty(sortBy).GetValue(r,null))
.ToList();
}
For Windows, I've created a build.cmd
file:
(replace the keystore path and alias)
For Cordova:
@echo off
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%
And for Ionic:
@echo off
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && ionic build --prod && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%
Save it in the ptoject's directory, you can double click or open it with cmd.
add this to your css:
html, body{height: 100%}
and change the max-height of #block12
to height
Explanation:
Basically #wrap
was 100% height (relative measure) but when you use relative measures it looks for its parent element's measure, and it's normally undefined because it's also relative. The only element(s) being able to use a relative heights are body
and or html
themselves depending on the browser, the rest of the elements need a parent element with absolute height.
But be careful, it's tricky playing around with relative heights, you have to calculate properly your header's height so you can substract it from the other element's percentages.
string result = System.Text.Encoding.UTF8.GetString(fs.ToArray());
I think TrungTN and anon's answer is okay, but MartinStettner's way of implementing the hex() function is not really simple, and too dark, considering hex << (int)mychar is already a workaround.
here is my solution to make "<<" operator easier:
#include <sstream>
#include <iomanip>
string uchar2hex(unsigned char inchar)
{
ostringstream oss (ostringstream::out);
oss << setw(2) << setfill('0') << hex << (int)(inchar);
return oss.str();
}
int main()
{
unsigned char a = 131;
std::cout << uchar2hex(a) << std::endl;
}
It's just not worthy implementing a stream operator :-)
Yes, you just forgot the quotes ...
$('<form/>').attr('action','form2.html').submit();
Do it like this
if (typeof $(this).attr("checked") == "undefined" )
// To check if checkbox is checked
if( $(this).attr("checked")=="checked")
My suggestion is to manage docker, with docker compose. Is an easy to way to manage all the docker's containers for your project, you can map the versions and link different containers to work together.
The docs are very simple to understand, better than docker's docs.
Best
Whilst this an old question, I ran into this problem myself recently and some of the answers here are now deprecated (as the comments point out). So for the benefit of others who may have stumbled here:
A term
query can be used to find the exact term specified in the reverse index:
{
"query": {
"term" : { "tags" : "a" }
}
From the documenation https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html
Alternatively you can use a terms
query, which will match all documents with any of the items specified in the given array:
{
"query": {
"terms" : { "tags" : ["a", "c"]}
}
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html
One gotcha to be aware of (which caught me out) - how you define the document also makes a difference. If the field you're searching in has been indexed as a text
type then Elasticsearch will perform a full text search (i.e using an analyzed
string).
If you've indexed the field as a keyword
then a keyword search using a 'non-analyzed' string is performed. This can have a massive practical impact as Analyzed strings are pre-processed (lowercased, punctuation dropped etc.) See (https://www.elastic.co/guide/en/elasticsearch/guide/master/term-vs-full-text.html)
To avoid these issues, the string field has split into two new types: text, which should be used for full-text search, and keyword, which should be used for keyword search. (https://www.elastic.co/blog/strings-are-dead-long-live-strings)
Both Activity
and Service
actually extend
Context
so you can simply use this
as your Context
within your Service
.
NotificationManager notificationManager =
(NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
Notification notification = new Notification(/* your notification */);
PendingIntent pendingIntent = /* your intent */;
notification.setLatestEventInfo(this, /* your content */, pendingIntent);
notificationManager.notify(/* id */, notification);
I have a Web Application with several other referenced Projects in the Solution. I've deployed successfully with a single Publish configuration many times in the past. I changed the Project Configuration from Debug to Release for a Project that had been missed in the past. The next time I attempted to deploy I got these symptoms, where the Publish just quietly fails - it does nothing and says it succeeded:
1>------ Build started: Project: Project, Configuration: DeployProduction Any CPU ------
1>
2>Publishing folder /...
========== Build: 1 succeeded, 0 failed, 9 up-to-date, 0 skipped ==========
========== Publish: 1 succeeded, 0 failed, 0 skipped ==========
The only way to recover it was to wipe out the Publish profile, close Visual Studio to force it to save the deletion, reopen it, and recreate the Publish profile from scratch. Once I did that I could Publish fine again.
Win8 VS2012, crappy laptop.
Swift 4.0, 4.1 & 4.2 First, I created mutable array of type imageFile() as shown below
var arr = [imageFile]()
Create mutable object image of type imageFile() and assign value to properties as shown below
var image = imageFile()
image.fileId = 14
image.fileName = "A"
Now, append this object to array arr
arr.append(image)
Now, assign the different properties to same mutable object i.e image
image = imageFile()
image.fileId = 13
image.fileName = "B"
Now, again append image object to array arr
arr.append(image)
Now, we will apply Ascending order on fileId property in array arr objects. Use < symbol for Ascending order
arr = arr.sorted(by: {$0.fileId < $1.fileId}) // arr has all objects in Ascending order
print("sorted array is",arr[0].fileId)// sorted array is 13
print("sorted array is",arr[1].fileId)//sorted array is 14
Now, we will apply Descending order on on fileId property in array arr objects. Use > symbol for Descending order
arr = arr.sorted(by: {$0.fileId > $1.fileId}) // arr has all objects in Descending order
print("Unsorted array is",arr[0].fileId)// Unsorted array is 14
print("Unsorted array is",arr[1].fileId)// Unsorted array is 13
In Swift 4.1. & 4.2 For sorted order use
let sortedArr = arr.sorted { (id1, id2) -> Bool in
return id1.fileId < id2.fileId // Use > for Descending order
}
You will need to know something about the URLs, like do they have a specific directory or some query string element because you have to match for something. Otherwise you will have to redirect on the 404. If this is what is required then do something like this in your .htaccess:
ErrorDocument 404 /index.php
An error page redirect must be relative to root so you cannot use www.mydomain.com.
If you have a pattern to match too then use 301 instead of 302 because 301 is permanent and 302 is temporary. A 301 will get the old URLs removed from the search engines and the 302 will not.
Mod Rewrite Reference: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html
Using Java 8
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
String encoded = DatatypeConverter.printHexBinary(hash);
System.out.println(encoded.toLowerCase());
Try this
npm uninstall angular-cli
npm install @angular/cli --save-dev
If you need to work a lot with database in your code and you know the structure of your table, I suggest you do it as follow:
First of all you can define a class which will help you to make objects capable of keeping your table rows data. For example in my project I created a class named Document.java to keep data of a single document from my database and I made an array list of these objects to keep data of my table which is gain by a query.
package financialdocuments;
import java.lang.*;
import java.util.HashMap;
/**
*
* @author Administrator
*/
public class Document {
private int document_number;
private boolean document_type;
private boolean document_status;
private StringBuilder document_date;
private StringBuilder document_statement;
private int document_code_number;
private int document_employee_number;
private int document_client_number;
private String document_employee_name;
private String document_client_name;
private long document_amount;
private long document_payment_amount;
HashMap<Integer,Activity> document_activity_hashmap;
public Document(int dn,boolean dt,boolean ds,String dd,String dst,int dcon,int den,int dcln,long da,String dena,String dcna){
document_date = new StringBuilder(dd);
document_date.setLength(10);
document_date.setCharAt(4, '.');
document_date.setCharAt(7, '.');
document_statement = new StringBuilder(dst);
document_statement.setLength(50);
document_number = dn;
document_type = dt;
document_status = ds;
document_code_number = dcon;
document_employee_number = den;
document_client_number = dcln;
document_amount = da;
document_employee_name = dena;
document_client_name = dcna;
document_payment_amount = 0;
document_activity_hashmap = new HashMap<>();
}
public Document(int dn,boolean dt,boolean ds, long dpa){
document_number = dn;
document_type = dt;
document_status = ds;
document_payment_amount = dpa;
document_activity_hashmap = new HashMap<>();
}
// Print document information
public void printDocumentInformation (){
System.out.println("Document Number:" + document_number);
System.out.println("Document Date:" + document_date);
System.out.println("Document Type:" + document_type);
System.out.println("Document Status:" + document_status);
System.out.println("Document Statement:" + document_statement);
System.out.println("Document Code Number:" + document_code_number);
System.out.println("Document Client Number:" + document_client_number);
System.out.println("Document Employee Number:" + document_employee_number);
System.out.println("Document Amount:" + document_amount);
System.out.println("Document Payment Amount:" + document_payment_amount);
System.out.println("Document Employee Name:" + document_employee_name);
System.out.println("Document Client Name:" + document_client_name);
}
}
Second of all, you can define a class to handle your database needs. For example I defined a class named DataBase.java which handles my connections to the database and my needed queries. And I instantiated an objected of it in my main class.
package financialdocuments;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Administrator
*/
public class DataBase {
/**
*
* Defining parameters and strings that are going to be used
*
*/
//Connection connect;
// Tables which their datas are extracted at the beginning
HashMap<Integer,String> code_table;
HashMap<Integer,String> activity_table;
HashMap<Integer,String> client_table;
HashMap<Integer,String> employee_table;
// Resultset Returned by queries
private ResultSet result;
// Strings needed to set connection
String url = "jdbc:mysql://localhost:3306/financial_documents?useUnicode=yes&characterEncoding=UTF-8";
String dbName = "financial_documents";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
public DataBase(){
code_table = new HashMap<>();
activity_table = new HashMap<>();
client_table = new HashMap<>();
employee_table = new HashMap<>();
Initialize();
}
/**
* Set variables and objects for this class.
*/
private void Initialize(){
System.out.println("Loading driver...");
try {
Class.forName(driver);
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
System.out.println("Connecting database...");
try (Connection connect = DriverManager.getConnection(url,userName,password)) {
System.out.println("Database connected!");
//Get tables' information
selectCodeTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printCodeTableQueryArray();
selectActivityTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printActivityTableQueryArray();
selectClientTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printClientTableQueryArray();
selectEmployeeTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printEmployeeTableQueryArray();
connect.close();
}catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
}
/**
* Write Queries
* @param s
* @return
*/
public boolean insertQuery(String s){
boolean ret = false;
System.out.println("Loading driver...");
try {
Class.forName(driver);
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
System.out.println("Connecting database...");
try (Connection connect = DriverManager.getConnection(url,userName,password)) {
System.out.println("Database connected!");
//Set tables' information
try {
Statement st = connect.createStatement();
int val = st.executeUpdate(s);
if(val==1){
System.out.print("Successfully inserted value");
ret = true;
}
else{
System.out.print("Unsuccessful insertion");
ret = false;
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
connect.close();
}catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
return ret;
}
/**
* Query needed to get code table's data
* @param c
* @return
*/
private void selectCodeTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM code;");
while (res.next()) {
int id = res.getInt("code_number");
String msg = res.getString("code_statement");
code_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printCodeTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : code_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get activity table's data
* @param c
* @return
*/
private void selectActivityTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM activity;");
while (res.next()) {
int id = res.getInt("activity_number");
String msg = res.getString("activity_statement");
activity_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printActivityTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : activity_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get client table's data
* @param c
* @return
*/
private void selectClientTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM client;");
while (res.next()) {
int id = res.getInt("client_number");
String msg = res.getString("client_full_name");
client_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printClientTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : client_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get activity table's data
* @param c
* @return
*/
private void selectEmployeeTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM employee;");
while (res.next()) {
int id = res.getInt("employee_number");
String msg = res.getString("employee_full_name");
employee_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printEmployeeTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : employee_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
}
I hope this could be a little help.
r = list(qs[:1])
if r:
return r[0]
return None
You can create a function:
function changeInputType(oldObj, oTyp, nValue) {
var newObject = document.createElement('input');
newObject.type = oTyp;
if(oldObj.size) newObject.size = oldObj.size;
if(oldObj.value) newObject.value = nValue;
if(oldObj.name) newObject.name = oldObj.name;
if(oldObj.id) newObject.id = oldObj.id;
if(oldObj.className) newObject.className = oldObj.className;
oldObj.parentNode.replaceChild(newObject,oldObj);
return newObject;
}
And you do a call like:
changeInputType(document.getElementById('DATE_RANGE_VALUE'), 'checkbox', 7);
The URL file://[servername]/[sharename]
should open an explorer window to the shared folder on the network.
Authentication is a property of a thread in server environment in the same way as it is a property of a process in OS. Having a bean instance for accessing authentication information would be inconvenient configuration and wiring overhead without any benefit.
Regarding test authentication there are several ways how you can make your life easier. My favourite is to make a custom annotation @Authenticated
and test execution listener, which manages it. Check DirtiesContextTestExecutionListener
for inspiration.
I believe that all the previously proposed solutions (apart from those that require specific implementations) result in the comments being included in the output HTML, even if they are not displayed.
If you want a comment that is strictly for yourself (readers of the converted document should not be able to see it, even with "view source") you could (ab)use the link labels (for use with reference style links) that are available in the core Markdown specification:
http://daringfireball.net/projects/markdown/syntax#link
That is:
[comment]: <> (This is a comment, it will not be included)
[comment]: <> (in the output file unless you use it in)
[comment]: <> (a reference style link.)
Or you could go further:
[//]: <> (This is also a comment.)
To improve platform compatibility (and to save one keystroke) it is also possible to use #
(which is a legitimate hyperlink target) instead of <>
:
[//]: # (This may be the most platform independent comment)
For maximum portability it is important to insert a blank line before and after this type of comments, because some Markdown parsers do not work correctly when definitions brush up against regular text. The most recent research with Babelmark shows that blank lines before and after are both important. Some parsers will output the comment if there is no blank line before, and some parsers will exclude the following line if there is no blank line after.
In general, this approach should work with most Markdown parsers, since it's part of the core specification. (even if the behavior when multiple links are defined, or when a link is defined but never used, is not strictly specified).
setInterval
sets up a recurring timer. It returns a handle that you can pass into clearInterval
to stop it from firing:
var handle = setInterval(drawAll, 20);
// When you want to cancel it:
clearInterval(handle);
handle = 0; // I just do this so I know I've cleared the interval
On browsers, the handle is guaranteed to be a number that isn't equal to 0
; therefore, 0
makes a handy flag value for "no timer set". (Other platforms may return other values; NodeJS's timer functions return an object, for instance.)
To schedule a function to only fire once, use setTimeout
instead. It won't keep firing. (It also returns a handle you can use to cancel it via clearTimeout
before it fires that one time if appropriate.)
setTimeout(drawAll, 20);