It's actually not really clearly stated in the standard (RFC 3986) whether a percent-encoded version of .
or ..
is supposed to have the same this-folder/up-a-folder meaning as the unescaped version. Section 3.3 only talks about “The path segments .
and ..
”, without clarifying whether they match .
and ..
before or after pct-encoding.
Personally I find Firefox's interpretation that %2E
does not mean .
most practical, but unfortunately all the other browsers disagree. This would mean that you can't have a path component containing only .
or ..
.
I think the only possible suggestion is “don't do that”! There are other path components that are troublesome too, typically due to server limitations: %2F
, %00
and %5C
sequences in paths may also be blocked by some web servers, and the empty path segment can also cause problems. So in general it's not possible to fit all possible byte sequences into a path component.
I found that this works and seems more readable:
switch($someString)
{
{ @("y", "yes") -contains $_ } { "You entered Yes." }
default { "You entered No." }
}
The "-contains" operator performs a non-case sensitive search, so you don't need to use "ToLower()". If you do want it to be case sensitive, you can use "-ccontains" instead.
you can also use:
docker system prune
or for just volumes:
docker volume prune
As far as I know the for loop uses the iter function and you should not mess with a structure while iterating over it.
Does it have to be a dictionary? If you use a list something like this might work:
while len(my_list) > 0:
#get last item from list
key, value = my_list.pop()
#do something with key and value
#maybe
my_list.append((key, value))
Note that my_list is a list of the tuple (key, value). The only disadvantage is that you cannot access by key.
EDIT: Nevermind, the answer above is mostly the same.
For example, if you want the date format to be "03.11.2017"
if (String.valueOf(DateEdit.getText()).matches("([1-9]{1}|[0]{1}[1-9]{1}|[1]{1}[0-9]{1}|[2]{1}[0-9]{1}|[3]{1}[0-1]{1})" +
"([.]{1})" +
"([0]{1}[1-9]{1}|[1]{1}[0-2]{1}|[1-9]{1})" +
"([.]{1})" +
"([20]{2}[0-9]{2})"))
checkFormat=true;
else
checkFormat=false;
if (!checkFormat) {
Toast.makeText(getApplicationContext(), "incorrect date format! Ex.23.06.2016", Toast.LENGTH_SHORT).show();
}
In addition to kus answer.
There are some changes in Xcode 8.0
Step 1:
Change scheme destination to Generic IOS device
.
Step 2:
Click Product
> Archive
> once this is complete open up the Organiser and click the latest version.
Step 3:
Click on Export...
option from right side of organiser window.
Step 4: Select a method for export > Choose correct signing > Save to Destination.
Xcode 10.0
Step 3: From Right Side Panel Click on Distribute App.
Step 4: Select Method of distribution and click next.
Step 5: It Opens up distribution option window. Select All compatible device variants and click next.
Step 6: Choose signing certificate.
Step 7: It will open up Preparing archive for distribution window. it takes few min.
Step 8: It will open up Archives window. Click on export and save it.
swift 3
let date : Date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
let todaysDate = dateFormatter.string(from: date)
I found I needed to enable the SSL module in Apache (obviously prefix commands with sudo
if you are not running as root):
a2enmod ssl
then restart Apache:
/etc/init.d/apache2 restart
More details of SSL in Apache for Ubuntu / Debian here.
"WORKSPACE" environment variable works for the latest version of Jenkins Pipeline. You can use this in your Jenkins file: "${env.WORKSPACE}"
Sample use below:
def files = findFiles glob: '**/reports/*.json'
for (def i=0; i<files.length; i++) {
jsonFilePath = "${files[i].path}"
jsonPath = "${env.WORKSPACE}" + "/" + jsonFilePath
echo jsonPath
hope that helps!!
As a workaround, I tried running the Visual Studio 2010 as an administrator, and it worked for me.
I hope this helps.
Default methods in Java Interface are to be used more for providing dummy implementation of a function thus saving any implementing class of that interface from the pain of declaring all the abstract methods even if they want to deal with only one. Default methods in interface are thus in a way more a replacement for the concept of adapter classes.
The methods in abstract class are however supposed to give a meaningful implementation which any child class should override only if needed to override a common functionality.
You can use Stack
to make the image stretch to the full screen.
Stack(
children: <Widget>
[
Positioned.fill( //
child: Image(
image: AssetImage('assets/placeholder.png'),
fit : BoxFit.fill,
),
),
...... // other children widgets of Stack
..........
.............
]
);
Note: Optionally if are using a Scaffold
, you can put the Stack
inside the Scaffold
with or without AppBar
according to your needs.
What about WebMatrix: http://www.microsoft.com/web/webmatrix/ ?
Another more versatile way is to use find
:
sed -i 's/asd/dsg/g' $(find . -type f -name 'xa*')
For whoever still looking for a copy + paste solution in nano editor
Note: If you want to copy the whole line, no need to mark just move the cursor to the line
Assuming the original date is in cell A1:
=A1-180
Works in at least Excel 2003 and 2010.
I create a method to simplify this:
public static void drawCenterText(String text, RectF rectF, Canvas canvas, Paint paint) {
Paint.Align align = paint.getTextAlign();
float x;
float y;
//x
if (align == Paint.Align.LEFT) {
x = rectF.centerX() - paint.measureText(text) / 2;
} else if (align == Paint.Align.CENTER) {
x = rectF.centerX();
} else {
x = rectF.centerX() + paint.measureText(text) / 2;
}
//y
metrics = paint.getFontMetrics();
float acent = Math.abs(metrics.ascent);
float descent = Math.abs(metrics.descent);
y = rectF.centerY() + (acent - descent) / 2f;
canvas.drawText(text, x, y, paint);
Log.e("ghui", "top:" + metrics.top + ",ascent:" + metrics.ascent
+ ",dscent:" + metrics.descent + ",leading:" + metrics.leading + ",bottom" + metrics.bottom);
}
rectF is the area you want draw the text,That's it. Details
It's simple--tostring()
accepts a parameter with this format...
DateTime.ToString("dd/MM/yyyy");
3 Steps you can follow
chmod -R 775 <repo path>
---> change permissions of repository
chown -R apache:apache <repo path>
---> change owner of svn repository
chcon -R -t httpd_sys_content_t <repo path>
----> change SELinux security context of the svn repository
Following on from Sergey's answer, I think this more generic version is more in line with Fowler's Range
idea, and resolves some of the issues with that answer such as being able to have the Includes
methods within a generic class by constraining T
as IComparable<T>
. It's also immutable like what you would expect with types that extend the functionality of other value types like DateTime
.
public struct Range<T> where T : IComparable<T>
{
public Range(T start, T end)
{
Start = start;
End = end;
}
public T Start { get; }
public T End { get; }
public bool Includes(T value) => Start.CompareTo(value) <= 0 && End.CompareTo(value) >= 0;
public bool Includes(Range<T> range) => Start.CompareTo(range.Start) <= 0 && End.CompareTo(range.End) >= 0;
}
You can always use the plot()
function like so:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
ys = [i+x+(i*x)**2 for i in range(10)]
plt.figure()
for y in ys:
plt.plot(x, y, 'o')
plt.show()
If you wish to convert a Pandas DataFrame
to a table (list of lists) and include the header column this should work:
import pandas as pd
def dfToTable(df:pd.DataFrame) -> list:
return [list(df.columns)] + df.values.tolist()
Usage (in REPL):
>>> df = pd.DataFrame(
[["r1c1","r1c2","r1c3"],["r2c1","r2c2","r3c3"]]
, columns=["c1", "c2", "c3"])
>>> df
c1 c2 c3
0 r1c1 r1c2 r1c3
1 r2c1 r2c2 r3c3
>>> dfToTable(df)
[['c1', 'c2', 'c3'], ['r1c1', 'r1c2', 'r1c3'], ['r2c1', 'r2c2', 'r3c3']]
Create a procedure which just does your lock and install it into a different user, who is "trusted" with dbms_lock ( USERA ), grant USERA access to dbms_lock.
Then just grant USERB access to this function. They then wont need to be able to access DBMS_LOCK
( make sure you don't have usera and userb in your system before running this )
Connect as a user with grant privs for dbms_lock, and can create users
drop user usera cascade;
drop user userb cascade;
create user usera default tablespace users identified by abc123;
grant create session to usera;
grant resource to usera;
grant execute on dbms_lock to usera;
create user userb default tablespace users identified by abc123;
grant create session to userb;
grant resource to useb
connect usera/abc123;
create or replace function usera.f_sleep( in_time number ) return number is
begin
dbms_lock.sleep(in_time);
return 1;
end;
/
grant execute on usera.f_sleep to userb;
connect userb/abc123;
/* About to sleep as userb */
select usera.f_sleep(5) from dual;
/* Finished sleeping as userb */
/* Attempt to access dbms_lock as userb.. Should fail */
begin
dbms_lock.sleep(5);
end;
/
/* Finished */
I understand the accepted answer, and have up-voted it but thought I'd dump my laymen's answer here...
Creating a hash
Checking a password against a hash
To check a password that a user inputs.
The Hash
Under the covers the hash is generated using the SHA1 hash function (https://en.wikipedia.org/wiki/SHA-1). This function is iteratively called 1000 times (In the default Identity implementation)
Why is this secure
If you have the .a file of your shared library (.so) you can simply include it with its full path as if it was an object file, like this:
This generates main.o by just compiling:
gcc -c main.c
This links that object file with the corresponding static library and creates the executable (named "main"):
gcc main.o mylibrary.a -o main
Or in a single command:
gcc main.c mylibrary.a -o main
It could also be an absolute or relative path:
gcc main.c /usr/local/mylibs/mylibrary.a -o main
if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
"nd"
else
totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')
The above logic should be what you are looking for.
rake tmp:cache:clear
might be what you're looking for.
When getting "File not found", my problem was that there was no symlink in the folder where was pointing this line in ngix config:
root /var/www/claims/web;
In addition to the Javascript solutions above, you can also use an HTML 5 solution by marking the radio buttons as required in the markup. This will eliminate the need for any Javascript and let the browser do the work for you.
See HTML5: How to use the "required" attribute with a "radio" input field for more information on how to do this well.
R doesn't have these operations because (most) objects in R are immutable. They do not change. Typically, when it looks like you're modifying an object, you're actually modifying a copy.
uint32_t
is defined in the standard, in
<cstdint>
synopsis [cstdint.syn]namespace std {
//...
typedef unsigned integer type uint32_t; // optional
//...
}
uint32
is not, it's a shortcut provided by some compilers (probably as typedef uint32_t uint32
) for ease of use.
A database is the computerized logical representation of a conceptual (or business) model, consisting of a set of informal business rules. These rules are the user-understood meaning of the data. Because computers comprehend only formal representations, business rules cannot be represented directly in a database. They must be mapped to a formal representation, a logical model, which consists of a set of integrity constraints. These constraints — the database schema — are the logical representation in the database of the business rules and, therefore, are the DBMS-understood meaning of the data. It follows that if the DBMS is unaware of and/or does not enforce the full set of constraints representing the business rules, it has an incomplete understanding of what the data means and, therefore, cannot guarantee (a) its integrity by preventing corruption, (b) the integrity of inferences it makes from it (that is, query results) — this is another way of saying that the DBMS is, at best, incomplete.
Note: The DBMS-“understood” meaning — integrity constraints — is not identical to the user-understood meaning — business rules — but, the loss of some meaning notwithstanding, we gain the ability to mechanize logical inferences from the data.
"An Old Class of Errors" by Fabian Pascal
If the number is stored in a string (which it would be if typed by a user), you can use atoi()
to convert it to an integer.
An integer can be assigned directly to a character. A character is different mostly just because how it is interpreted and used.
char c = atoi("61");
First, add a data conversion block into your data flow diagram.
Open the data conversion block and tick the column for which the error is showing. Below change its data type to unicode string(DT_WSTR) or whatever datatype is expected and save.
Go to the destination block. Go to mapping in it and map the newly created element to its corresponding address and save.
Right click your project in the solution explorer.select properties. Select configuration properties and select debugging in it. In this, set the Run64BitRunTime option to false (as excel does not handle the 64 bit application very well).
Choosing older simulator versions is not obvious in Xcode 3.2.5. Older Xcodes had separate lists of "iOS Device SDKs" and "iOS Simulator SDKs" in the "Base SDK" build setting popup menu, but in Xcode 3.2.5 these have been replaced with a single "iOS SDKs" list that only offers 4.2 and "latest".
If you create a new default iOS project, it defaults to 4.2 for both Base SDK and Deployment Target, and in the "Overview" popup in the project's top-left corner, only the 4.2 Simulator is available.
To run an older iOS simulator, you must choose an older iOS version in the "iOS Deployment Target" build setting popup. Only then will the "Overview" popup offer older Simulators: back to 4.0 for iPhone and to 3.2 for iPad.
Great question, and it's odd that the Swing toolkit doesn't include this functionality natively for JTextFields. But, here's a great answer from my Udemy.com course "Learn Java Like a Kid":
txtGuess = new JTextField();
txtGuess.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (txtGuess.getText().length() >= 3 ) // limit textfield to 3 characters
e.consume();
}
});
This limits the number of characters in a guessing game text field to 3 characters, by overriding the keyTyped event and checking to see if the textfield already has 3 characters - if so, you're "consuming" the key event (e) so that it doesn't get processed like normal.
You need the key in dict
idiom for that.
if key in my_dict and not (my_dict[key] is None):
# do something
else:
# do something else
However, you should probably consider using defaultdict
(as dF suggested).
You can center any number of child in a FrameLayout
.
<FrameLayout
>
<child1
....
android:layout_gravity="center"
.....
/>
<Child2
....
android:layout_gravity="center"
/>
</FrameLayout>
So the key is
adding
android:layout_gravity="center"
in the child views.
I centered a CustomView and a TextView on a FrameLayout
like this
Code:
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<com.airbnb.lottie.LottieAnimationView
android:layout_width="180dp"
android:layout_height="180dp"
android:layout_gravity="center"
app:lottie_fileName="red_scan.json"
app:lottie_autoPlay="true"
app:lottie_loop="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#ffffff"
android:textSize="10dp"
android:textStyle="bold"
android:padding="10dp"
android:text="Networks Available: 1\n click to see all"
android:gravity="center" />
</FrameLayout>
Result:
If you don't have access to sysjobs table (someone elses server etc) you might be have or be allowed access to sysjobs_view
SELECT *
from msdb..sysjobs_view s
left join master.sys.syslogins l on s.owner_sid = l.sid
or
SELECT *, SUSER_SNAME(s.owner_sid) AS owner
from msdb..sysjobs_view s
Also, for simulating a slow connection on some *nixes, you can try using ipfw. More information is provided by Ben Newman's answer on this Quora question
You can use list.reverse()
to reverse the list, then list.pop()
to remove the last element, for example:
l = [0, 1, 2, 3, 4]
l.reverse()
print l
[4, 3, 2, 1, 0]
l.pop()
0
l.pop()
1
l.pop()
2
l.pop()
3
l.pop()
4
An example:
use strict;
for (1 .. 2){
# Both variables are lexically scoped to the block.
our ($o); # Belongs to 'main' package.
my ($m); # Does not belong to a package.
# The variables differ with respect to newness.
$o ++;
$m ++;
print __PACKAGE__, " >> o=$o m=$m\n"; # $m is always 1.
# The package has changed, but we still have direct,
# unqualified access to both variables, because the
# lexical scope has not changed.
package Fubb;
print __PACKAGE__, " >> o=$o m=$m\n";
}
# The our() and my() variables differ with respect to privacy.
# We can still access the variable declared with our(), provided
# that we fully qualify its name, but the variable declared
# with my() is unavailable.
print __PACKAGE__, " >> main::o=$main::o\n"; # 2
print __PACKAGE__, " >> main::m=$main::m\n"; # Undefined.
# Attempts to access the variables directly won't compile.
# print __PACKAGE__, " >> o=$o\n";
# print __PACKAGE__, " >> m=$m\n";
# Variables declared with use vars() are like those declared
# with our(): belong to a package; not private; and not new.
# However, their scoping is package-based rather than lexical.
for (1 .. 9){
use vars qw($uv);
$uv ++;
}
# Even though we are outside the lexical scope where the
# use vars() variable was declared, we have direct access
# because the package has not changed.
print __PACKAGE__, " >> uv=$uv\n";
# And we can access it from another package.
package Bubb;
print __PACKAGE__, " >> main::uv=$main::uv\n";
If I want to find where anything I want to search is, I use this:
DECLARE @search_string varchar(200)
SET @search_string = '%myString%'
SELECT DISTINCT
o.name AS Object_Name,
o.type_desc,
m.definition
FROM sys.sql_modules m
INNER JOIN
sys.objects o
ON m.object_id = o.object_id
WHERE m.definition Like @search_string;
I hope this will help you
Create table :
create table users (id int,first_name varchar(10),last_name varchar(10));
Insert values into the table :
insert into users (id,first_name,last_name) values(1,'Abhishek','Anand');
var input = {"document":
{"people":[
{"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
{"name":["hermione granger"],"age":["18"],"gender":["Female"]},
]}
}
var keys = [];
for(var i = 0;i<input.document.people.length;i++)
{
Object.keys(input.document.people[i]).forEach(function(key){
if(keys.indexOf(key) == -1)
{
keys.push(key);
}
});
}
console.log(keys);
HTML
<div id="myDiv" style="display:none;" class="answer_list" >WELCOME</div>
<input type="button" name="answer" onclick="ShowDiv()" />
JavaScript
function ShowDiv() {
document.getElementById("myDiv").style.display = "";
}
Or if you wanted to use jQuery with a nice little animation:
<input id="myButton" type="button" name="answer" />
$('#myButton').click(function() {
$('#myDiv').toggle('slow', function() {
// Animation complete.
});
});
Which method is used to check if SESSION exists or not? Answer:
isset($_SESSION['variable_name'])
Example:
isset($_SESSION['id'])
echo "You are running $0"
Try this one:
$('body').tooltip({
selector: '[rel=tooltip]'
});
In JSF 2.2 it's possible to use passthrough elements:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:jsf="http://xmlns.jcp.org/jsf">
...
<div jsf:id="id1" />
...
</html>
The requirement is to have at least one attribute in the element using jsf namespace.
python doc strings are free-form, you can document it in any way you like.
Examples:
def mymethod(self, foo, bars):
"""
Does neat stuff!
Parameters:
foo - a foo of type FooType to bar with.
bars - The list of bars
"""
Now, there are some conventions, but python doesn't enforce any of them. Some projects have their own conventions. Some tools to work with docstrings also follow specific conventions.
In C \0
is a character literal constant store into an int
data type that represent the character with value of 0.
Since Objective-C is a strict superset of C this constant is retained.
Convert INT to hex:
SELECT CONVERT(VARBINARY(8), 16777215)
Convert hex to INT:
SELECT CONVERT(INT, 0xFFFFFF)
The above example has the limitation that it only works when the HEX value is given as an integer literal. For completeness, if the value to convert is a hexadecimal string (such as found in a varchar column) use:
-- If the '0x' marker is present:
SELECT CONVERT(INT, CONVERT(VARBINARY, '0x1FFFFF', 1))
-- If the '0x' marker is NOT present:
SELECT CONVERT(INT, CONVERT(VARBINARY, '1FFFFF', 2))
Note: The string must contain an even number of hex digits. An odd number of digits will yield an error.
More details can be found in the "Binary Styles" section of CAST and CONVERT (Transact-SQL). I believe SQL Server 2008 or later is required.
Also you can use ss utility to dump sockets statistics.
To dump summary:
ss -s
Total: 91 (kernel 0)
TCP: 18 (estab 11, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 0
Transport Total IP IPv6
* 0 - -
RAW 0 0 0
UDP 4 2 2
TCP 18 16 2
INET 22 18 4
FRAG 0 0 0
To display all sockets:
ss -a
To display UDP sockets:
ss -u -a
To display TCP sockets:
ss -t -a
Here you can read ss man: ss
You should sort the list:
mylist.sort()
After this, iterate through it like this:
doubles = []
for i, elem in enumerate(mylist):
if i != 0:
if elem == old:
doubles.append(elem)
old = None
continue
old = elem
I think I got the reason for the above error. It is the corporate proxy(virtual private network) provided in order to work in the client network. Without that connection I frequently faced the same problem be it maven build or npm install.
You can't do this with a UNIQUE
constraint, but you can do this in a trigger.
CREATE TRIGGER [dbo].[OnInsertMyTableTrigger]
ON [dbo].[MyTable]
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Column1 INT;
DECLARE @Column2 INT; -- allow nulls on this column
SELECT @Column1=Column1, @Column2=Column2 FROM inserted;
-- Check if an existing record already exists, if not allow the insert.
IF NOT EXISTS(SELECT * FROM dbo.MyTable WHERE Column1=@Column1 AND Column2=@Column2 @Column2 IS NOT NULL)
BEGIN
INSERT INTO dbo.MyTable (Column1, Column2)
SELECT @Column2, @Column2;
END
ELSE
BEGIN
RAISERROR('The unique constraint applies on Column1 %d, AND Column2 %d, unless Column2 is NULL.', 16, 1, @Column1, @Column2);
ROLLBACK TRANSACTION;
END
END
Deleting nodes from XML
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");
for (int i = nodes.Count - 1; i >= 0; i--)
{
nodes[i].ParentNode.RemoveChild(nodes[i]);
}
doc.Save(path);
Adding attribute to Nodes in XML
XmlDocument originalXml = new XmlDocument();
originalXml.Load(path);
XmlNode menu = originalXml.SelectSingleNode("//Settings");
XmlNode newSub = originalXml.CreateNode(XmlNodeType.Element, "Setting", null);
XmlAttribute xa = originalXml.CreateAttribute("name");
xa.Value = "qwerty";
XmlAttribute xb = originalXml.CreateAttribute("value");
xb.Value = "555";
newSub.Attributes.Append(xa);
newSub.Attributes.Append(xb);
menu.AppendChild(newSub);
originalXml.Save(path);
I wrote a function what works fine with every instance of Objects (Arrays are those).
Object.prototype.toArray = function()
{
if(!this)
{
return null;
}
var c = [];
for (var key in this)
{
if ( ( this instanceof Array && this.constructor === Array && key === 'length' ) || !this.hasOwnProperty(key) )
{
continue;
}
c.push(this[key]);
}
return c;
};
Usage:
var a = [ 1, 2, 3 ];
a[11] = 4;
a["js"] = 5;
console.log(a.toArray());
var b = { one: 1, two: 2, three: 3, f: function() { return 4; }, five: 5 };
b[7] = 7;
console.log(b.toArray());
Output:
> [ 1, 2, 3, 4, 5 ]
> [ 7, 1, 2, 3, function () { return 4; }, 5 ]
It may be useful for anyone.
Hint: actively refused
sounds like somewhat deeper technical trouble, but...
...actually, this response (and also specifically errno:10061
) is also given, if one calls the bin/mongo executable and the mongodb service is simply not running on the target machine. This even applies to local machine instances (all happening on localhost).
? Always rule out for this trivial possibility first, i.e. simply by using the command line client to access your db.
The best way to do it From Android O preview release is this way:
It works only if you have android studio-2.4 or above
R.font.dancing_script
, R.font.la_la
, and R.font.ba_ba
.Next we must create a font family:
Enclose each font file, style, and weight attribute in the font tag element. The following XML illustrates adding font-related attributes in the font resource XML:
Adding fonts to a TextView:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/hey_fontfamily"/>
As from the documentation
All the steps are correct.
Output the images in a lossless format such as PNG:
ffmpeg.exe -i 10fps.h264 -r 10 -f image2 10fps.h264_%03d.png
Edit/Update: Not quite sure why I originally gave a strange filename example (with a possibly made-up extension).
I have since found that
-vsync 0
is simpler than-r 10
because it avoids needing to know the frame rate.This is something like what I currently use:
mkdir stills ffmpeg -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png
To extract only the key frames (which are likely to be of higher quality post-edit):
ffmpeg -skip_frame nokey -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png
Then use another program (where you can more precisely specify quality, subsampling and DCT method – e.g. GIMP) to convert the PNGs you want to JPEG.
It is possible to obtain slightly sharper images in JPEG format this way than is possible with -qmin 1 -q:v 1
and outputting as JPEG directly from ffmpeg
.
try
console.log($("#"+d));
your solution is passing the double quotes as part of the string.
You can use axis
:
> axis(side=1, at=c(0:23))
That is, something like this:
plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()
There is charts4j which is a charts and graphs API. It enables developers to programmatically create the charts available in the Google Chart API through a straightforward and intuitive Java API.
Disclaimer: I wrote charts4j. We will be doing another major release in the next few weeks.
Use the property TextWrapping
of the TextBlock
element:
<TextBlock Text="StackOverflow Forum"
Width="100"
TextWrapping="WrapWithOverflow"/>
Add new column and fill it with ascending numbers. Then filter by ([column] mod 7 = 0) or something like that (don't have Excel in front of me to actually try this);
If you can't filter by formula, add one more column and use the formula =MOD([column; 7]) in it then filter zeros and you'll get all seventh rows.
Also from Java 8 you can write Dan Cruz answer as:
Thread t = new Thread(()->{
System.out.println("Sleeping ...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted.");
}
System.out.println("Throwing exception ...");
throw new RuntimeException(); });
t.setUncaughtExceptionHandler((th, ex)-> log(String.format("Exception in thread %d id: %s", th.getId(), ex)));
t.start();
I am answering this question late but hope it will help the other candidate facing same problem.
I have used two methods to load thumbnail for videos list the first was
Bitmap bmThumbnail;
bmThumbnail = ThumbnailUtils.createVideoThumbnail(FILE_PATH
+ videoList.get(position),
MediaStore.Video.Thumbnails.MINI_KIND);
if (bmThumbnail != null) {
Log.d("VideoAdapter","video thumbnail found");
holder.imgVideo.setImageBitmap(bmThumbnail);
} else {
Log.d("VideoAdapter","video thumbnail not found");
}
its look good but there was a problem with this solution because when i scroll video list it will freeze some time due to its large processing.
so after this i found another solution which works perfectly by using Glide Library.
Glide
.with( mContext )
.load( Uri.fromFile( new File( FILE_PATH+videoList.get(position) ) ) )
.into( holder.imgVideo );
I recommended the later solution for showing thumbnail with video list . thanks
If it has been staged and committed, then the following will reset the file:
git reset COMMIT_HASH file_path
git checkout COMMIT_HASH file_path
git add file_path
This will work for a deletion that occurred several commits previous.
You could also do
result = ([ a for a,b in original ], [ b for a,b in original ])
It should scale better. Especially if Python makes good on not expanding the list comprehensions unless needed.
(Incidentally, it makes a 2-tuple (pair) of lists, rather than a list of tuples, like zip
does.)
If generators instead of actual lists are ok, this would do that:
result = (( a for a,b in original ), ( b for a,b in original ))
The generators don't munch through the list until you ask for each element, but on the other hand, they do keep references to the original list.
Look at SignalR Tests for the feature.
Test "SendToUser" takes automatically the user identity passed by using a regular owin authentication library.
The scenario is you have a user who has connected from multiple devices/browsers and you want to push a message to all his active connections.
If you have date as a datetime.datetime
(or a datetime.date
) instance and want to combine it via a time from a datetime.time
instance, then you can use the classmethod datetime.datetime.combine
:
import datetime
dt = datetime.datetime(2020, 7, 1)
t = datetime.time(12, 34)
combined = datetime.datetime.combine(dt.date(), t)
Here's an Immutable version of recursive dictionary merge in case anybody needs it.
Based upon @Alex Martelli's answer.
Python 3.x:
import collections
from copy import deepcopy
def merge(dict1, dict2):
''' Return a new dictionary by merging two dictionaries recursively. '''
result = deepcopy(dict1)
for key, value in dict2.items():
if isinstance(value, collections.Mapping):
result[key] = merge(result.get(key, {}), value)
else:
result[key] = deepcopy(dict2[key])
return result
Python 2.x:
import collections
from copy import deepcopy
def merge(dict1, dict2):
''' Return a new dictionary by merging two dictionaries recursively. '''
result = deepcopy(dict1)
for key, value in dict2.iteritems():
if isinstance(value, collections.Mapping):
result[key] = merge(result.get(key, {}), value)
else:
result[key] = deepcopy(dict2[key])
return result
You can do
display/i $pc
and every time GDB stops, it will display the disassembly of the next instruction.
GDB-7.0
also supports set disassemble-next-line on
, which will disassemble the entire next line, and give you more of the disassembly context.
You can have this if you are trying to manifest your application that it has a dependancy on the Microsoft.Windows.Common-Controls assembly. You do this when you want to load Version 6 of the common controls library - so that visual styles are applied to common controls.
You probably followed Microsoft's original documentation way back from Windows XP days, and added the following to your application's manifest:
<!-- Dependancy on Common Controls version 6 -->
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="X86"
publicKeyToken="6595b64144ccf1df"
language="*"/>
</dependentAssembly>
</dependency>
Windows XP is no longer the OS, and you're no longer a 32-bit application. In the intervening 17 years Microsoft updated their documentation; now it's time for you to update your manifest:
<!-- Dependancy on Common Controls version 6 -->
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"/>
</dependentAssembly>
</dependency>
Raymond Chen has a lovely history of the Common Controls:
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
You can either create a new Stage
, add your controls into it or if you require the POPUP as Dialog
box, then you may consider using DialogsFX or ControlsFX(Requires JavaFX8)
For creating a new Stage, you can use the following snippet
@Override
public void start(final Stage primaryStage) {
Button btn = new Button();
btn.setText("Open Dialog");
btn.setOnAction(
new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
final Stage dialog = new Stage();
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.initOwner(primaryStage);
VBox dialogVbox = new VBox(20);
dialogVbox.getChildren().add(new Text("This is a Dialog"));
Scene dialogScene = new Scene(dialogVbox, 300, 200);
dialog.setScene(dialogScene);
dialog.show();
}
});
}
If you don't want it to be modal
(block other windows), use:
dialog.initModality(Modality.NONE);
`You can do it by simple loop using Math.trunc() function. if in interview interviewer ask to do it without converting it into string`
let num = 555194154234 ;
let len = 0 ;
const numLen = (num) => {
for(let i = 0; i < num || num == 1 ; i++){
num = Math.trunc(num/10);
len++ ;
}
return len + 1 ;
}
console.log(numLen(num));
As described in the API of java.sql.PreparedStatement.setBinaryStream()
it is available since 1.6 so it is a JDBC 4.0 API! You use a JDBC 3 Driver so this method is not available!
You have to use image
.listStyle {
list-style: none;
background: url(bullet.jpg) no-repeat left center;
padding-left: 40px;
}
static void Main()
{
// A.
// Example strings with multiple whitespaces.
string s1 = "He saw a cute\tdog.";
string s2 = "There\n\twas another sentence.";
// B.
// Create the Regex.
Regex r = new Regex(@"\s+");
// C.
// Strip multiple spaces.
string s3 = r.Replace(s1, @" ");
Console.WriteLine(s3);
// D.
// Strip multiple spaces.
string s4 = r.Replace(s2, @" ");
Console.WriteLine(s4);
Console.ReadLine();
}
OUTPUT:
He saw a cute dog. There was another sentence. He saw a cute dog.
Some diagrams might help:
Forward proxy
Reverse proxy
Anyone mentioned Jshon or JSON.sh?
https://github.com/keenerd/jshon
pipe json to it, and it traverses the json objects and prints out the path to the current object (as a JSON array) and then the object, without whitespace.
http://kmkeen.com/jshon/
Jshon loads json text from stdin, performs actions, then displays the last action on stdout and also was made to be part of the usual text processing pipeline.
Use android:descendantFocusability
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="80dip"
android:background="@color/light_green"
android:descendantFocusability="blocksDescendants" >
Add above in root layout
SELECT
resultIn the Navigator, right click on the table > Table Data Export Wizard
All columns and rows are included by default, so click on Next.
Select File Path, type, Field Separator (by default it is ;
, not ,
!!!) and click on Next.
Click Next > Next > Finish and the file is created in the specified location
In the case where you simply want to delete a project from the head revision, so that it no longer shows up in your repo when you run svn list file:///path/to/repo/
just run:
svn delete file:///path/to/repo/project
However, if you need to delete all record of it in the repo, use another method.
I suspect that the SelectedItem property of the ComboBox does not change until the control has been validated (which occurs when the control loses focus), whereas the SelectedValue property changes whenever the user selects an item.
Here is a reference to the focus events that occur on controls:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validated.aspx
The problem is very simple
jQuery.get('wokab.json', function(data) {
var glacier = JSON.parse(data);
});
You're parsing it twice. get
uses the dataType='json'
, so data is already in json format.
Use $.ajax({ dataType: 'json' ...
to specifically set the returned data type!
strtok
:Since one of the suggested solutions uses strtok
, unfortunately it doesn't point out a potential memory issue (though it claims to be memory efficient). When using strtok
according to the manual, the:
Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string.
It does this by loading the file into memory. If you're using large files, you need to flush them if you're done looping through the file.
<?php
function process($str) {
$line = strtok($str, PHP_EOL);
/*do something with the first line here...*/
while ($line !== FALSE) {
// get the next line
$line = strtok(PHP_EOL);
/*do something with the rest of the lines here...*/
}
//the bit that frees up memory
strtok('', '');
}
According to the manual, for the file upload part you can use the file
command:
//Create the array
$lines = file( $some_file );
foreach ( $lines as $line ) {
//do something here.
}
If you have several specific properties that you want to transition in the same way (because you also have some properties you specifically don't want to transition, say opacity
), another option is to do something like this (prefixes omitted for brevity):
.myclass {
transition: all 200ms ease;
transition-property: box-shadow, height, width, background, font-size;
}
The second declaration overrides the all
in the shorthand declaration above it and makes for (occasionally) more concise code.
/* prefixes omitted for brevity */_x000D_
.box {_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
background: red;_x000D_
box-shadow: red 0 0 5px 1px;_x000D_
transition: all 500ms ease;_x000D_
/*note: not transitioning width */_x000D_
transition-property: height, background, box-shadow;_x000D_
}_x000D_
_x000D_
.box:hover {_x000D_
height: 50px;_x000D_
width: 50px;_x000D_
box-shadow: blue 0 0 10px 3px;_x000D_
background: blue;_x000D_
}
_x000D_
<p>Hover box for demo</p>_x000D_
<div class="box"></div>
_x000D_
You could use the ceiling
function; this portion of SQL code :
select ceiling(45.01), ceiling(45.49), ceiling(45.99);
will get you "46" each time.
For your update, so, I'd say :
Update product SET price = ceiling(45.01)
BTW : On MySQL, ceil
is an alias to ceiling
; not sure about other DB systems, so you might have to use one or the other, depending on the DB you are using...
Quoting the documentation :
CEILING(X)
Returns the smallest integer value not less than X.
And the given example :
mysql> SELECT CEILING(1.23);
-> 2
mysql> SELECT CEILING(-1.23);
-> -1
Add new column to Table
ALTER TABLE [table]
ADD Column1 Datatype
E.g
ALTER TABLE [test]
ADD ID Int
If User wants to make it auto incremented then
ALTER TABLE [test]
ADD ID Int IDENTITY(1,1) NOT NULL
That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).
You can get this error in the context of, e.g. a Travis build that, by default, checks code out with git clone --depth=50 --branch=master
. To the best of my knowledge, you can control --depth
via .travis.yml
but not the --branch
. Since that results in only a single branch being tracked by the remote, you need to independently update the remote to track the desired remote's refs.
Before:
$ git branch -a
* master
remotes/origin/HEAD -> origin/master
remotes/origin/master
The fix:
$ git remote set-branches --add origin branch-1
$ git remote set-branches --add origin branch-2
$ git fetch
After:
$ git branch -a
* master
remotes/origin/HEAD -> origin/master
remotes/origin/branch-1
remotes/origin/branch-2
remotes/origin/master
Had the same issue that the client_max_body_size
directive was ignored.
My silly error was, that I put a file inside /etc/nginx/conf.d
which did not end with .conf
. Nginx will not load these by default.
malloc()
and calloc()
are functions from the C standard library that allow dynamic memory allocation, meaning that they both allow memory allocation during runtime.
Their prototypes are as follows:
void *malloc( size_t n);
void *calloc( size_t n, size_t t)
There are mainly two differences between the two:
Behavior: malloc()
allocates a memory block, without initializing it, and reading the contents from this block will result in garbage values. calloc()
, on the other hand, allocates a memory block and initializes it to zeros, and obviously reading the content of this block will result in zeros.
Syntax: malloc()
takes 1 argument (the size to be allocated), and calloc()
takes two arguments (number of blocks to be allocated and size of each block).
The return value from both is a pointer to the allocated block of memory, if successful. Otherwise, NULL will be returned indicating the memory allocation failure.
Example:
int *arr;
// allocate memory for 10 integers with garbage values
arr = (int *)malloc(10 * sizeof(int));
// allocate memory for 10 integers and sets all of them to 0
arr = (int *)calloc(10, sizeof(int));
The same functionality as calloc()
can be achieved using malloc()
and memset()
:
// allocate memory for 10 integers with garbage values
arr= (int *)malloc(10 * sizeof(int));
// set all of them to 0
memset(arr, 0, 10 * sizeof(int));
Note that malloc()
is preferably used over calloc()
since it's faster. If zero-initializing the values is wanted, use calloc()
instead.
i suggest PDFMerger from github.com, so easy like ::
include 'PDFMerger.php';
$pdf = new PDFMerger;
$pdf->addPDF('samplepdfs/one.pdf', '1, 3, 4')
->addPDF('samplepdfs/two.pdf', '1-2')
->addPDF('samplepdfs/three.pdf', 'all')
->merge('file', 'samplepdfs/TEST2.pdf'); // REPLACE 'file' WITH 'browser', 'download', 'string', or 'file' for output options
If your search is over several years, and you still want to group monthly, I suggest:
version #1:
SELECT SQL_NO_CACHE YEAR(record_date), MONTH(record_date), COUNT(*)
FROM stats
GROUP BY DATE_FORMAT(record_date, '%Y%m')
version #2 (more efficient):
SELECT SQL_NO_CACHE YEAR(record_date), MONTH(record_date), COUNT(*)
FROM stats
GROUP BY YEAR(record_date)*100 + MONTH(record_date)
I compared these versions on a big table with 1,357,918 rows (innodb), and the 2nd version appears to have better results.
version1 (average of 10 executes): 1.404 seconds
version2 (average of 10 executes): 0.780 seconds
(SQL_NO_CACHE
key added to prevent MySQL from CACHING to queries.)
this worked for me
sudo yarn install
Need to specify two attributes, table-layout:fixed
on table
and white-space:nowrap;
on the cells. You also need to move the overflow:hidden;
to the cells too
table { width:250px;table-layout:fixed; }
table tr { height:1em; }
td { overflow:hidden;white-space:nowrap; }
Here's a Demo . Tested in Firefox 3.5.3 and IE 7
I just spent the last 4 hours with the same issue. What I did was to simply make sure the constraints had unique names.
You can rename the constraints. I appended a number to mine so I could easily trace the number of occurrences.
Example
If a constraint in a table is named boy with a foreign key X The next constraint with the foreign key X can be called boy1
I'm sure you'd figure out better names than I did.
the solustion when we use routes like this:
Route::get('/', function () {
return view('welcome');
});
laravel call them Closure so you cant optimize routes uses as Closures you must route to controller to use php artisan optimize
Such a thing probably does not exist "as-is". It doesn't really exist on Linux or other UNIX-like operating systems either though.
ncurses is only a library that helps you manage interactions with the underlying terminal environment. But it doesn't provide a terminal emulator itself.
The thing that actually displays stuff on the screen (which in your requirement is listed as "native resizable win32 windows") is usually called a Terminal Emulator. If you don't like the one that comes with Windows (you aren't alone; no person on Earth does) there are a few alternatives. There is Console, which in my experience works sometimes and appears to just wrap an underlying Windows terminal emulator (I don't know for sure, but I'm guessing, since there is a menu option to actually get access to that underlying terminal emulator, and sure enough an old crusty Windows/DOS box appears which mirrors everything in the Console window).
A better option
Another option, which may be more appealing is puttycyg. It hooks in to Putty (which, coming from a Linux background, is pretty close to what I'm used to, and free) but actually accesses an underlying cygwin instead of the Windows command interpreter (CMD.EXE
). So you get all the benefits of Putty's awesome terminal emulator, as well as nice ncurses
(and many other) libraries provided by cygwin. Add a couple command line arguments to the Shortcut that launches Putty (or the Batch file) and your app can be automatically launched without going through Putty's UI.
Set the [Console]::OuputEncoding
as encoding whatever you want, and print out with [Console]::WriteLine
.
If powershell ouput method has a problem, then don't use it. It feels bit bad, but works like a charm :)
Both are 0-based, but the start is inclusive and the end is exclusive. This ensures the resulting string is of length start - end
.
To make life easier for substring
operation, imagine that characters are between indexes.
0 1 2 3 4 5 6 7 8 9 10 <- available indexes for substring
u n i v E R S i t y
? ?
start end --> range of "E R S"
Quoting the docs:
The substring begins at the specified
beginIndex
and extends to the character at indexendIndex - 1
. Thus the length of the substring isendIndex-beginIndex
.
If you just want to show label below the marker, then you can extend google maps Marker to add a setter method for label and you can define the label object by extending google maps overlayView like this..
<script type="text/javascript">
var point = { lat: 22.5667, lng: 88.3667 };
var markerSize = { x: 22, y: 40 };
google.maps.Marker.prototype.setLabel = function(label){
this.label = new MarkerLabel({
map: this.map,
marker: this,
text: label
});
this.label.bindTo('position', this, 'position');
};
var MarkerLabel = function(options) {
this.setValues(options);
this.span = document.createElement('span');
this.span.className = 'map-marker-label';
};
MarkerLabel.prototype = $.extend(new google.maps.OverlayView(), {
onAdd: function() {
this.getPanes().overlayImage.appendChild(this.span);
var self = this;
this.listeners = [
google.maps.event.addListener(this, 'position_changed', function() { self.draw(); })];
},
draw: function() {
var text = String(this.get('text'));
var position = this.getProjection().fromLatLngToDivPixel(this.get('position'));
this.span.innerHTML = text;
this.span.style.left = (position.x - (markerSize.x / 2)) - (text.length * 3) + 10 + 'px';
this.span.style.top = (position.y - markerSize.y + 40) + 'px';
}
});
function initialize(){
var myLatLng = new google.maps.LatLng(point.lat, point.lng);
var gmap = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
map: gmap,
position: myLatLng,
label: 'Hello World!',
draggable: true
});
}
</script>
<style>
.map-marker-label{
position: absolute;
color: blue;
font-size: 16px;
font-weight: bold;
}
</style>
This will work.
In real life where you encounter systems already written and adding indexes to tables then drastically slows down the data loading of a 14gig data table, you are sometime forced to used WITH NOLOCK on your reports and end of month proessing so that the aggregate funtions (sum, count etc) do not do row, page, table locking and deteriate the overall performance. Easy to say in a new system never use WITH NOLOCK and use indexes - but adding indexes severly downgrades data loading, and when I'm then told, well, alter the code base to delete indexes, then bulk load then recreate the indexes - which is all well and good, if you are developing a new system. But Not when you have a system already in place.
Please check if the python version you are using is also 64 bit. If not then that could be the issue. You would be using a 32 bit python version and would have installed a 64 bit binaries for the OPENCV library.
In my case, after a long search I found that PyCharm in your Django settings (Settings > Languages & Frameworks > Django) had the configuration file field undefined. You should make this field point to your project's settings file. Then, you must open the Run / Debug settings and remove the environment variable DJANGO_SETTINGS_MODULE = existing path.
This happens because the Django plugin in PyCharm forces the configuration of the framework. So there is no point in configuring any os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')
You could do that:
KeyValuePair<TKey, TValue>
's in the dictionary (which will be a sizable performance hit if you have a number of entries in the dictionary) Use Method 1 if performance is not a consideration, use Method 2 if memory is not a consideration.
Also, all keys must be unique, but the values are not required to be unique. You may have more than one key with the specified value.
Is there any reason you can't reverse the key-value relationship?
One way you could do it in SQL Server would be to return the table content as XML (for XML raw), convert the result to a string and then replace the tags with ", ".
try:
parts = ip.split('.')
return len(parts) == 4 and all(0 <= int(part) < 256 for part in parts)
except ValueError:
return False # one of the 'parts' not convertible to integer
except (AttributeError, TypeError):
return False # `ip` isn't even a string
This is of course subjective and an academic question. Some people argue whether an OO language has to implement classes and inheritance, others write programs that change your life. ;-)
(But really, why should an OO language have to implement classes? I'd think objects were the key components. How you create and then use them is another matter.)
The difference is this:
Int32.Parse()
and Int32.TryParse()
can only convert strings. Convert.ToInt32()
can take any class that implements IConvertible
. If you pass it a string, then they are equivalent, except that you get extra overhead for type comparisons, etc. If you are converting strings, then TryParse()
is probably the better option.
How about head ?
echo alonglineoftext | head -c 9
Store it anywhere in an accessible location except of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to Uploaded image only available after refreshing the page:
Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called "publishing"). This is the main cause of the problem you're seeing.
In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.
Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.
It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you do not ever use getRealPath()
method. Using that method is in any case alarming.
The path to the storage location can in turn be definied in many ways. You have to do it all by yourself. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that @MultipartConfig(location)
does not specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.
So, the path to the final storage location can be definied in either of the following ways:
Hardcoded:
File uploads = new File("/path/to/uploads");
Environment variable via SET UPLOAD_LOCATION=/path/to/uploads
:
File uploads = new File(System.getenv("UPLOAD_LOCATION"));
VM argument during server startup via -Dupload.location="/path/to/uploads"
:
File uploads = new File(System.getProperty("upload.location"));
*.properties
file entry as upload.location=/path/to/uploads
:
File uploads = new File(properties.getProperty("upload.location"));
web.xml
<context-param>
with name upload.location
and value /path/to/uploads
:
File uploads = new File(getServletContext().getInitParameter("upload.location"));
If any, use the server-provided location, e.g. in JBoss AS/WildFly:
File uploads = new File(System.getProperty("jboss.server.data.dir"), "uploads");
Either way, you can easily reference and save the file as follows:
File file = new File(uploads, "somefilename.ext");
try (InputStream input = part.getInputStream()) {
Files.copy(input, file.toPath());
}
Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:
File file = File.createTempFile("somefilename-", ".ext", uploads);
try (InputStream input = part.getInputStream()) {
Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
How to obtain part
in JSP/Servlet is answered in How to upload files to server using JSP/Servlet? and how to obtain part
in JSF is answered in How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?
Note: do not use Part#write()
as it interprets the path relative to the temporary storage location defined in @MultipartConfig(location)
.
For VB and anonymous/lambda:
query.GroupBy(Function(x) New With {Key x.Field1, Key x.Field2, Key x.FieldN })
If you want to toggle text with a toggle button.
HTMLfile which is using bootstrap:
<input class="btn" (click)="muteStream()" type="button"
[ngClass]="status ? 'btn-success' : 'btn-danger'"
[value]="status ? 'unmute' : 'mute'"/>
TS file:
muteStream() {
this.status = !this.status;
}
public class Test1 {
public static void main(String[] args) {
int[] x = { 1, 2, 3, 4, 5, 6 };
Test1 test = new Test1();
x = test.shiftArray(x, 2);
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
}
public int[] pushFirstElementToLast(int[] x, int position) {
int temp = x[0];
for (int i = 0; i < x.length - 1; i++) {
x[i] = x[i + 1];
}
x[x.length - 1] = temp;
return x;
}
public int[] shiftArray(int[] x, int position) {
for (int i = position - 1; i >= 0; i--) {
x = pushFirstElementToLast(x, position);
}
return x;
}
}
Well you could either add <a></a>
tags and place the div inside it, adding an href if you want the div to act as a link. Or else just use Javascript and define an 'OnClick' function. But from the limited information provided, it's a bit hard to determine what the context of your problem is.
Cents? If you're calculationg money values you really shouldn't use float values. Money is actually countable values. The cents or pennys etc. could be considered the two (or whatever) least significant digits of an integer. You could store, and calculate money values as integers and divide by 100 (e.g. place dot or comma two before the two last digits). Using float's can lead to strange rounding errors...
Anyway, if your epsilon is supposed to define the accuracy, it looks a bit too small (too accurate)...
I believe those installers make changes to the path. Did you try closing and re-opening the CMD window after running them and before the last attempt to install the gem that wants devkit present?
Also, be sure you are using the right devkit installer for your version of Ruby. The documentation at devkit wiki page has a requirements note saying:
For RubyInstaller versions 1.8.7, 1.9.2, and 1.9.3 use the DevKit 4.5.2
5 x faster reduce variant but more sophisticated
>>> l = [5, 6, 6, 1, 1, 2, 2, 3, 4]
>>> reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, l, ([], set()))[0]
[5, 6, 1, 2, 3, 4]
Explanation:
default = (list(), set())
# use list to keep order
# use set to make lookup faster
def reducer(result, item):
if item not in result[1]:
result[0].append(item)
result[1].add(item)
return result
>>> reduce(reducer, l, default)[0]
[5, 6, 1, 2, 3, 4]
Technically yes. But only on certain instances. If for example you have the code page up and you hit git checkout, and you realize that you accidently checked out the wrong page or something. Go to the page and click undo. (for me, command + z), and it will go back to exactly where you were before you hit the good old git checkout.
This will not work if your page has been closed, and then you hit git checkout. It only works if the actual code page is open
The linefeed character \n
is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n
instead, then it'll both see the line-break with only \n
and \r\n
, I've never had any problems using it.
Also, you should look into using a StringBuilder
instead of concatenating the String
in the while-loop at BookCatalog.toString()
, it is a lot more effective. For instance:
public String toString() {
BookNode current = front;
StringBuilder sb = new StringBuilder();
while (current!=null){
sb.append(current.getData().toString()+"\r\n ");
current = current.getNext();
}
return sb.toString();
}
You can use anonymous types for example:
var empData = from res in _db.EMPLOYEEs
where res.EMAIL == givenInfo || res.USER_NAME == givenInfo
select new { res.EMAIL, res.USER_NAME };
img{display: flex; max-width: 80%; margin: auto;}
This is working for me. You can also use display: table in this case. Moreover, if you don't want to stick to this approach you can use the following:
img{position: relative; left: 50%;}
I found a solution of my own. I know that Andras answer is probably the most consistent with MSTEST, but I didn't feel like refactoring my code.
[TestMethod]
public void OneIsOne()
{
using (ConsoleRedirector cr = new ConsoleRedirector())
{
Assert.IsFalse(cr.ToString().Contains("New text"));
/* call some method that writes "New text" to stdout */
Assert.IsTrue(cr.ToString().Contains("New text"));
}
}
The disposable ConsoleRedirector
is defined as:
internal class ConsoleRedirector : IDisposable
{
private StringWriter _consoleOutput = new StringWriter();
private TextWriter _originalConsoleOutput;
public ConsoleRedirector()
{
this._originalConsoleOutput = Console.Out;
Console.SetOut(_consoleOutput);
}
public void Dispose()
{
Console.SetOut(_originalConsoleOutput);
Console.Write(this.ToString());
this._consoleOutput.Dispose();
}
public override string ToString()
{
return this._consoleOutput.ToString();
}
}
This is because your <h1>
is the width of the centercol. Specify a width on the <h1>
and use margin: 0 auto;
if you want it centered.
Or, alternatively, you could float the <h1>
, which would make it only exactly as wide as the text.
If you use PHP7, use Throwable in catch
for catching user exceptions and fatal errors.
For example:
DB::beginTransaction();
try {
DB::insert(...);
DB::commit();
} catch (\Throwable $e) {
DB::rollback();
throw $e;
}
If your code must be compartable with PHP5, use Exception
and Throwable
:
DB::beginTransaction();
try {
DB::insert(...);
DB::commit();
} catch (\Exception $e) {
DB::rollback();
throw $e;
} catch (\Throwable $e) {
DB::rollback();
throw $e;
}
Apparently the only reliable and accepted solution would be to do feature detection like this:
browser_treats_urls_like_safari_does = false;
var last_location_hash = location.hash;
location.hash = '"blah"';
if (location.hash == '#%22blah%22')
browser_treats_urls_like_safari_does = true;
location.hash = last_location_hash;
Just set
webView.mediaPlaybackRequiresUserAction = NO;
The autoplay works for me on iOS.
I was surprised to read section 3.3.2 about rejecting cookies:
http://tools.ietf.org/html/rfc2965
That says that a browser should reject a cookie from x.y.z.com with domain .z.com, because 'x.y' contains a dot. So, unless I am misinterpreting the RFC and/or the questions above, there could be questions added:
Will a cookie for .example.com be available for www.yyy.example.com? No.
Will a cookie set by origin server www.yyy.example.com, with domain .example.com, have it's value sent by the user agent to xxx.example.com? No.
Update for XAMPP 7.3.*
If you get into same problem for phpmyadmin in the newest XAMPP, as I had.
The solution is written inside the official documentation located in [XAMPP IP]/dashboard/docs/access-phpmyadmin-remotely.html
To enable remote access to phpMyAdmin from other hosts, follow these steps:
- Launch the stack manager by double-clicking the XAMPP icon in the mounted disk image.
- Ensure that Apache and MySQL services are running in the "Services" tab of the stack manager (or start them as needed).
- Open a new terminal from the "General" tab of the stack manager.
- Edit the /opt/lampp/etc/extra/httpd-xampp.conf file.
- Within this file, find the block
<Directory "/opt/lampp/phpmyadmin">
Update this block and replace
Require local
withRequire all granted
,
- Save the file and restart the Apache service using the stack manager.
Note for section (4) To edit this file make sure you have vim installed.
Note for section (5) Instead of allowing access to all, which is highly insecure, if your computer is connected to a network. A safer approach is to limit the access to only set of IPs as suggested by @Gunnar Bernstein.
In my case I did:
<Directory "/opt/lampp/phpmyadmin">
AllowOverride AuthConfig Limit
Require local
Require ip 192.168
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>
"var" means the compiler will determine the explicit type of the variable, based on usage. For example,
var myVar = new Connection();
would give you a variable of type Connection.
You have to put a g
at the end, it stands for "global":
echo dog dog dos | sed -r 's:dog:log:g'
^
Your questions:
Q 1.) I would like to know why it returns all the texts that following the div?
It should not and I think in will not. It returns all div with 'id' attribute value equal 'containter' (and all children of this). But you are printing the results with ele.getText()
Where getText will return all text content of all children of your result.
Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.
Returns:
The innerText of this element.
Q 2.) how should I modify the code so it just return first or first few nodes that follow the parent note
This is not really clear what you are looking for.
Example:
<p1> <div/> </p1 <p2/>
The following to parent of the div is p2. This would be:
//div[@id='container'][1]/parent::*/following-sibling::*
or shorter
//div[@id='container'][1]/../following-sibling::*
If you are only looking for the first one extent the expression with an "predicate"
(e.g [1]
- for the first one. or [position() < 4]
for the first three)
If your are looking for the first child of the first div:
//div[@id='container'][1]/*[1]
If there is only one div with id an you are looking for the first child:
//div[@id='container']/*[1]
and so on.
Just use gnome, just type in the address and away you go!
Why not check if for nothing?
if not inputbox("bleh") = nothing then
'Code
else
' Error
end if
This is what i typically use, because its a little easier to read.
If the data is in an UTF-8 compatible format, you can convert the bytes to a string.
>>> import curses
>>> print(str(curses.version, "utf-8"))
2.2
Optionally convert to hex first, if the data is not already UTF-8 compatible. E.g. when the data are actual raw bytes.
from binascii import hexlify
from codecs import encode # alternative
>>> print(hexlify(b"\x13\x37"))
b'1337'
>>> print(str(hexlify(b"\x13\x37"), "utf-8"))
1337
>>>> print(str(encode(b"\x13\x37", "hex"), "utf-8"))
1337
Someone asked about adding attributes (specifically, 'rows' and 'cols'). If you're using Razor, you could just do this:
@Html.TextAreaFor(model => model.Text, new { cols = 35, @rows = 3 })
That works for me. The '@' is used to escape keywords so they are treated as variables/properties.
I use SimplePie to parse a Google Reader feed and it works pretty well and has a decent feature set.
Of course, I haven't tested it with non-well-formed RSS / Atom feeds so I don't know how it copes with those, I'm assuming Google's are fairly standards compliant! :)
As a general rule, converting a Web Forms or MVC5 application to ASP.NET Core will require a significant amount of refactoring.
HttpContext.Current
was removed in ASP.NET Core. Accessing the current HTTP context from a separate class library is the type of messy architecture that ASP.NET Core tries to avoid. There are a few ways to re-architect this in ASP.NET Core.
You can access the current HTTP context via the HttpContext
property on any controller. The closest thing to your original code sample would be to pass HttpContext
into the method you are calling:
public class HomeController : Controller
{
public IActionResult Index()
{
MyMethod(HttpContext);
// Other code
}
}
public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
var host = $"{context.Request.Scheme}://{context.Request.Host}";
// Other code
}
If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext
is passed into your Invoke
method automatically:
public Task Invoke(HttpContext context)
{
// Do something with the current HTTP context...
}
Finally, you can use the IHttpContextAccessor
helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.
Request this interface in your constructor:
public MyMiddleware(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
You can then access the current HTTP context in a safe way:
var context = _httpContextAccessor.HttpContext;
// Do something with the current HTTP context...
IHttpContextAccessor
isn't always added to the service container by default, so register it in ConfigureServices
just to be safe:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
// if < .NET Core 2.2 use this
//services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Other code...
}
The -std=c++14
flag is not supported on GCC 4.8. If you want to use C++14 features you need to compile with -std=c++1y
. Using godbolt.org it appears that the earilest version to support -std=c++14
is GCC 4.9.0 or Clang 3.5.0
I don't think that's your problem. Script loading is synchronous by default, so unless you're using the defer
attribute or loading jQuery itself via another AJAX request, your problem is probably something more like a 404. Can you show your markup, and let us know if you see anything suspicious in firebug or web inspector?
caution : It is not recommended to remove the default Python from Ubuntu, it may cause GDM(Graphical Display Manager, that provide graphical login capabilities) failed.
To completely uninstall Python2.x.x and everything depends on it. use this command:
sudo apt purge python2.x-minimal
As there are still a lot of packages that depend on Python2.x.x. So you should have a close look at the packages that apt wants to remove before you let it proceed.
Thanks, I hope it will be helpful for you.
In 3.0, there's now an easier way - hook into the new motion events.
The main trick is that you need to have some UIView (not UIViewController) that you want as firstResponder to receive the shake event messages. Here's the code that you can use in any UIView to get shake events:
@implementation ShakingView
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if ( event.subtype == UIEventSubtypeMotionShake )
{
// Put in code here to handle shake
}
if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] )
[super motionEnded:motion withEvent:event];
}
- (BOOL)canBecomeFirstResponder
{ return YES; }
@end
You can easily transform any UIView (even system views) into a view that can get the shake event simply by subclassing the view with only these methods (and then selecting this new type instead of the base type in IB, or using it when allocating a view).
In the view controller, you want to set this view to become first responder:
- (void) viewWillAppear:(BOOL)animated
{
[shakeView becomeFirstResponder];
[super viewWillAppear:animated];
}
- (void) viewWillDisappear:(BOOL)animated
{
[shakeView resignFirstResponder];
[super viewWillDisappear:animated];
}
Don't forget that if you have other views that become first responder from user actions (like a search bar or text entry field) you'll also need to restore the shaking view first responder status when the other view resigns!
This method works even if you set applicationSupportsShakeToEdit to NO.
You need to use the await keyword when use async and your function return type should be generic Here is an example with return value:
public async Task<object> MethodName()
{
return await Task.FromResult<object>(null);
}
Here is an example with no return value:
public async Task MethodName()
{
await Task.CompletedTask;
}
Read these:
TPL: http://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx and Tasks: http://msdn.microsoft.com/en-us/library/system.threading.tasks(v=vs.110).aspx
Async: http://msdn.microsoft.com/en-us/library/hh156513.aspx Await: http://msdn.microsoft.com/en-us/library/hh156528.aspx
the problem is because you have got the query over multiple lines using the " " that PHP is actually sending all the white spaces in to MySQL which is causing it to error out.
Either put it on one line or append on each line :o)
Sqlyog must be trimming white spaces on each line which explains why its working.
Example:
$qr2="INSERT INTO wp_bp_activity
(
user_id,
(this stuff)component,
(is) `type`,
(a) `action`,
(problem) content,
primary_link,
item_id,....
You need Ajax to make it happen. Something like this:
$(document).ready(function(){
$("#myform").on('submit', function(){
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var contact = $("#contact").val();
var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
if(name=='' || email=='' || password=='' || contact=='')
{
alert("Please fill in all fields");
}
else
{
// Ajax code to submit form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
Here's a simple way
for (i in 1:10) {
skip_to_next <- FALSE
# Note that print(b) fails since b doesn't exist
tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
if(skip_to_next) { next }
}
Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b)
with any code you want. You can also wrap many lines of code in {
and }
if you have more than one line of code inside the tryCatch
I had the same issue (same error on heroku, working on local machine) and I tried all the solutions listed here including
heroku run rails console
which ran without error messages. I tried heroku run rake db:migrate
and heroku run rake db:migrate:reset
a few times. None of this solved the problem. On going through some files that are used in production but not in dev environment, I found some whitespace in the puma.rb file to be the culprit. Hope this helps someone who has the same issue.
Changing this made it work
ActiveRecord::Base.establish_connection
End
to
ActiveRecord::Base.establish_connection
end
curl -X PUT -T "/path/to/file" "http://myputserver.com/puturl.tmp"
If you need an algorithm, try this: Convert the color from RGB space to HSV space (Hue, Saturation, Value). If your UI framework can't do it, check this article: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
Hue is in [0,360). To find the "opposite" color (think colorwheel), just add 180 degrees:
h = (h + 180) % 360;
For saturation and value, invert them:
l = 1.0 - l;
v = 1.0 - v;
Convert back to RGB. This should always give you a high contrast even though most combinations will look ugly.
If you want to avoid the "ugly" part, build a table with several "good" combinations, find the one with the least difference
def q(x):
return x*x
def diff(col1, col2):
return math.sqrt(q(col1.r-col2.r) + q(col1.g-col2.g) + q(col1.b-col2.b))
and use that.
SELECT table_name as Table_Name, row_cnt as Row_Count, SUM(mb) as Size_MB
FROM
(SELECT in_tbl.table_name, to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from ' ||ut.table_name)),'/ROWSET/ROW/C')) AS row_cnt , mb
FROM
(SELECT CASE WHEN lob_tables IS NULL THEN table_name WHEN lob_tables IS NOT NULL THEN lob_tables END AS table_name , mb
FROM (SELECT ul.table_name AS lob_tables, us.segment_name AS table_name , us.bytes/1024/1024 MB FROM user_segments us
LEFT JOIN user_lobs ul ON us.segment_name = ul.segment_name ) ) in_tbl INNER JOIN user_tables ut ON in_tbl.table_name = ut.table_name ) GROUP BY table_name, row_cnt ORDER BY 3 DESC;``
Above query will give, Table_name, Row_count, Size_in_MB(includes lob column size) of specific user.
I managed to do it with
var html_string= "content";
document.getElementById('output_iframe1').src = "data:text/html;charset=utf-8," + escape(html_string);
<song>
<title>Song Tigle</title>
<lyrics>
<line>The is the very first line</line>
<line>Number two and I'm still feeling fine</line>
<line>Number three and a pattern begins</line>
<line>Add lines like this and everyone wins!</line>
</lyrics>
</song>
(Sung to the tune of Home on the Range)
If it was mine I'd wrap the choruses and verses in XML elements as well.
I think the best symptom of correct code coverage is that amount of concrete problems unit tests help to fix is reasonably corresponds to size of unit tests code you created.
there are four types of strings available in php. They are single quotes ('), double quotes (") and Nowdoc (<<<'EOD')
and heredoc(<<<EOD)
strings
you can use both single quotes and double quotes inside heredoc string. Variables will be expanded just as double quotes.
nowdoc strings will not expand variables just like single quotes.
ref: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
The best and recommended way is to use Qt Style Sheet.
To change the text color and background color of a QLabel
, here is what I would do :
QLabel* pLabel = new QLabel;
pLabel->setStyleSheet("QLabel { background-color : red; color : blue; }");
You could also avoid using Qt Style Sheets and change the QPalette
colors of your QLabel
, but you might get different results on different platforms and/or styles.
As Qt documentation states :
Using a QPalette isn't guaranteed to work for all styles, because style authors are restricted by the different platforms' guidelines and by the native theme engine.
But you could do something like this :
QPalette palette = ui->pLabel->palette();
palette.setColor(ui->pLabel->backgroundRole(), Qt::yellow);
palette.setColor(ui->pLabel->foregroundRole(), Qt::yellow);
ui->pLabel->setPalette(palette);
But as I said, I strongly suggest not to use the palette and go for Qt Style Sheet.
Board.setPreferredSize(new Dimension(x, y));
.
.
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);
Main.pack();
Main.setVisible(true);
You are looking for serialize(). Here is an example:
$array = array('foo', 'bar');
//Array to String
$string = serialize($array);
//String to array
$array = unserialize($string);
I modified @Silmaril's answer to extend Alamofire's Manager. This solution uses EVReflection to serialize an object directly:
//Extend Alamofire so it can do POSTs with a JSON body from passed object
extension Alamofire.Manager {
public class func request(
method: Alamofire.Method,
_ URLString: URLStringConvertible,
bodyObject: EVObject)
-> Request
{
return Manager.sharedInstance.request(
method,
URLString,
parameters: [:],
encoding: .Custom({ (convertible, params) in
let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
mutableRequest.HTTPBody = bodyObject.toJsonString().dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
return (mutableRequest, nil)
})
)
}
}
Then you can use it like this:
Alamofire.Manager.request(.POST, endpointUrlString, bodyObject: myObjectToPost)
VB.net 4.0 framework Code :
Threading.Thread.Sleep(5000)
The integer is in miliseconds ( 1 sec = 1000 miliseconds)
I did test it and it works
Mostly you don't see a difference, unless you are using set -u
:
/home/user1> var=""
/home/user1> echo $var
/home/user1> set -u
/home/user1> echo $var
/home/user1> unset var
/home/user1> echo $var
-bash: var: unbound variable
So really, it depends on how you are going to test the variable.
I will add that my preferred way of testing if it is set is:
[[ -n $var ]] # True if the length of $var is non-zero
or
[[ -z $var ]] # True if zero length
app.component.html
<select [(ngModel)]='nrSelect' class='form-control'>
<option value='47'>47</option>
<option value='46'>46</option>
<option value='45'>45</option>
</select>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
nrSelect = 47
}
This is a simple html file "demo.htm" stored in the same folder as the node.js file.
<!DOCTYPE html>
<html>
<body>
<h1>Heading</h1>
<p>Paragraph.</p>
</body>
</html>
Below is the node.js file to call this html file.
var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, resp){
// Print the name of the file for which request is made.
console.log("Request for demo file received.");
fs.readFile("Documents/nodejs/demo.html",function(error, data){
if (error) {
resp.writeHead(404);
resp.write('Contents you are looking for-not found');
resp.end();
} else {
resp.writeHead(200, {
'Content-Type': 'text/html'
});
resp.write(data.toString());
resp.end();
}
});
});
server.listen(8081, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8081/');
Intiate the above nodejs file in command prompt and the message "Server running at http://127.0.0.1:8081/" is displayed.Now in your browser type "http://127.0.0.1:8081/demo.html".
Basically, you get connections in the Sleep state when :
So, you generally end up with many processes in a Sleep state when you have a lot of PHP processes that stay connected, without actually doing anything on the database-side.
A basic idea, so : make sure you don't have PHP processes that run for too long -- or force them to disconnect as soon as they don't need to access the database anymore.
Another thing, that I often see when there is some load on the server :
A solution that can help is to reduce the time your queries take -- optimizing the longest ones.
Follow these steps to run your application on the device connected.
1. Change directories to the root of your Android project and execute:
ant debug
2. Make sure the Android SDK platform-tools/
directory is included in your PATH
environment variable, then execute: adb install bin/<*your app name*>-debug.apk
On your device, locate <*your app name*>
and open it.
Refer Running App
If you simply need to check whether the variable is of type X, or that it conforms to some protocol, then you can use is
, or as?
as in the following:
var unknownTypeVariable = …
if unknownTypeVariable is <ClassName> {
//the variable is of type <ClassName>
} else {
//variable is not of type <ClassName>
}
This is equivalent of isKindOfClass
in Obj-C.
And this is equivalent of conformsToProtocol
, or isMemberOfClass
var unknownTypeVariable = …
if let myClass = unknownTypeVariable as? <ClassName or ProtocolName> {
//unknownTypeVarible is of type <ClassName or ProtocolName>
} else {
//unknownTypeVariable is not of type <ClassName or ProtocolName>
}
I guess this is what you want:
l = range(100)
index = 0
for i in l:
print i,
try:
print l.pop(index+1),
print l.pop(index+1)
except:
pass
index += 1
It is quite handy to code when the number of item to be popped is a run time decision. But it runs with very a bad efficiency and the code is hard to maintain.
You can also check for bootstrap datatable plugin as well for above issue.
It will have a large column table scrollable feature with lot of other options
$(document).ready(function() {
$('#example').dataTable( {
"scrollX": true
} );
} );
for more info with example please check out this link
One can both fix the warning and use the timezone specified in settings.py, which might be different from UTC.
For example in my settings.py I have:
USE_TZ = True
TIME_ZONE = 'Europe/Paris'
Here is a solution; the advantage is that str(mydate)
gives the correct time:
>>> from datetime import datetime
>>> from django.utils.timezone import get_current_timezone
>>> mydate = datetime.now(tz=get_current_timezone())
>>> mydate
datetime.datetime(2019, 3, 10, 11, 16, 9, 184106,
tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>)
>>> str(mydate)
'2019-03-10 11:16:09.184106+01:00'
Another equivalent method is using make_aware
, see dmrz post.
You have to fetch that one record, it will contain the result of Count()
$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];
Not quite, the AND has to be lower-case.
<xsl:when test="4 < 5 and 1 < 2">
<!-- do something -->
</xsl:when>
For me the problem happens if I simply create an empty matplotlibrc
file under ~/.matplotlib
on macOS. Adding "backend: macosx" in it fixes the problem.
I think it is a bug: if backend
is not specified in my matplotlibrc
it should take the default value.
The backslash \
is the escape character for regular expressions. Therefore a double backslash would indeed mean a single, literal backslash.
\ (backslash) followed by any of [\^$.|?*+(){} escapes the special character to suppress its special meaning.
As per Where is Maven Installed on Ubuntu it will first create your settings.xml on /usr/share/maven2/, then you can copy to your home folder as jens mentioned
$ cp /usr/share/maven3/conf/settings.xml ~/.m2/settings.xml
<xsl:if test="xpath-expression">...</xsl:if>
so for example
<xsl:if test="/html/body">body node exists</xsl:if>
<xsl:if test="not(/html/body)">body node missing</xsl:if>
OQ asked about static string
vs const
. Both have different use cases (although both are treated as static).
Use const only for truly constant values (e.g. speed of light - but even this varies depending on medium). The reason for this strict guideline is that the const value is substituted into the uses of the const in assemblies that reference it, meaning you can have versioning issues should the const change in its place of definition (i.e. it shouldn't have been a constant after all). Note this even affects private const
fields because you might have base and subclass in different assemblies and private fields are inherited.
Static fields are tied to the type they are declared within. They are used for representing values that need to be the same for all instances of a given type. These fields can be written to as many times as you like (unless specified readonly).
If you meant static readonly
vs const
, then I'd recommend static readonly
for almost all cases because it is more future proof.
You can use the ThenBy and ThenByDescending extension methods:
foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
try this package, works wonders, and was made for date/time...
library(lubridate)
Portfolio$Date2 <- mdy(Portfolio.all$Date2)
A filter argument with a trailing * can be evaluated almost instantaneously via an index lookup. A leading * implies a sequential search through the index, so it is O(N). It will take ages.
I suggest you reconsider the requirement.
The error is caused by constrains automatically created from autoresizing mask, they are created because UIView property translatesAutoresizingMaskIntoConstraints is true by default.
Consider using BoxView to get rid of all manual constraint creation boilerplate, and make your code concize and readable. To make layout in question with BoxView is very easy:
boxView.items = [
new_view.boxed.centerX().centerY().relativeWidth(1.0).relativeHeight(1.0)
]
Although it is not recommended method but still it works
[7-Zip Software is needed]
Procedure to get jar from java files:
It is possible to SSH to Travis CI environment via a bounce host. The feature isn't built in Travis CI, but it can be achieved by the following steps.
travis
user and ensure that you can SSH to it.Put these lines in the script:
section of your .travis.yml
(e.g. at the end).
- echo travis:$sshpassword | sudo chpasswd
- sudo sed -i 's/ChallengeResponseAuthentication no/ChallengeResponseAuthentication yes/' /etc/ssh/sshd_config
- sudo service ssh restart
- sudo apt-get install sshpass
- sshpass -p $sshpassword ssh -R 9999:localhost:22 -o StrictHostKeyChecking=no travis@$bouncehostip
Where $bouncehostip
is the IP/host of your bounce host, and $sshpassword
is your defined SSH password. These variables can be added as encrypted variables.
Push the changes. You should be able to make an SSH connection to your bounce host.
Source: Shell into Travis CI Build Environment.
Here is the full example:
# use the new container infrastructure
sudo: required
dist: trusty
language: python
python: "2.7"
script:
- echo travis:$sshpassword | sudo chpasswd
- sudo sed -i 's/ChallengeResponseAuthentication no/ChallengeResponseAuthentication yes/' /etc/ssh/sshd_config
- sudo service ssh restart
- sudo apt-get install sshpass
- sshpass -p $sshpassword ssh -R 9999:localhost:22 -o StrictHostKeyChecking=no travisci@$bouncehostip
See: c-mart/travis-shell
at GitHub.
See also: How to reproduce a travis-ci build environment for debugging
Alternatively, signum() can be used:
if (price.signum() == 0) {
return true;
}
Here is a dplyr
based option:
newV = df %>% slice(1) %>% unlist(use.names = FALSE)
# or slightly different:
newV = df %>% slice(1) %>% unlist() %>% unname()
It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with ""
and your variable will be hidden.
So, you could define the variable with:
{{f = forecast[day.iso]; ""}}
One additional comment regarding Vineet Reynolds answer.
I found out that I had to set -XX:+UseParallelGC
in eclipse.ini
I setup the virtual machine (vm) arguments as follows
-vmargs
-Dosgi.requiredJavaVersion=1.7
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M
that solved the issue.
Bootstrap-theme.css is the additional CSS file, which is optional for you to use. It gives 3D effects on the buttons and some other elements.
In the accepted answer
public Node(T data, Node<T> parent) {
this.data = data;
this.parent = parent;
}
should be
public Node(T data, Node<T> parent) {
this.data = data;
this.setParent(parent);
}
otherwise the parent does not have the child in its children list
Just the same way as you would do in normal Java code.
for (Map.Entry<String, String> entry : countries.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// ...
}
However, scriptlets (raw Java code in JSP files, those <% %>
things) are considered a poor practice. I recommend to install JSTL (just drop the JAR file in /WEB-INF/lib
and declare the needed taglibs in top of JSP). It has a <c:forEach>
tag which can iterate over among others Map
s. Every iteration will give you a Map.Entry
back which in turn has getKey()
and getValue()
methods.
Here's a basic example:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach items="${map}" var="entry">
Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>
Thus your particular issue can be solved as follows:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<select name="country">
<c:forEach items="${countries}" var="country">
<option value="${country.key}">${country.value}</option>
</c:forEach>
</select>
You need a Servlet
or a ServletContextListener
to place the ${countries}
in the desired scope. If this list is supposed to be request-based, then use the Servlet
's doGet()
:
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
Map<String, String> countries = MainUtils.getCountries();
request.setAttribute("countries", countries);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}
Or if this list is supposed to be an application-wide constant, then use ServletContextListener
's contextInitialized()
so that it will be loaded only once and kept in memory:
public void contextInitialized(ServletContextEvent event) {
Map<String, String> countries = MainUtils.getCountries();
event.getServletContext().setAttribute("countries", countries);
}
In both cases the countries
will be available in EL by ${countries}
.
Hope this helps.
Heres a pure CSS solution. Put the visible image in the img tag, put the second image as a background in the css, then hide the image on hover.
.buttons{
width:90%;
margin-left:5%;
margin-right:5%;
margin-top:2%;
}
.buttons ul{}
.buttons ul li{
display:inline-block;
width:22%;
margin:1%;
position:relative;
}
.buttons ul li a p{
position:absolute;
top:40%;
text-align:center;
}
.but1{
background:url('scales.jpg') center no-repeat;
background-size:cover;
}
.but1 a:hover img{
visibility:hidden;
}
.but2{
background:url('scales.jpg') center no-repeat;
background-size:cover;
}
.but2 a:hover img{
visibility:hidden;
}
.but3{
background:url('scales.jpg') center no-repeat;
background-size:cover;
}
.but3 a:hover img{
visibility:hidden;
}
.but4{
background:url('scales.jpg') center no-repeat;
background-size:cover;
}
.but4 a:hover img{
visibility:hidden;
}
<div class='buttons'>
<ul>
<li class='but1'><a href='#'><img src='scalesb.jpg' height='300' width='300' alt='' /><p>Blog</p></a></li>
<li class='but2'><a href='#'><img src='scalesb.jpg' height='300' width='300' alt='' /> <p>Herrero</p></a></li>
<li class='but3'><a href='#'><img src='scalesb.jpg' height='300' width='300' alt='' /><p>Loftin</p></a></li>
<li class='but4'><a href='#'><img src='scalesb.jpg' height='300' width='300' alt='' /><p>Contact</p></a></li>
</ul>
</div>