I guess you're using windows 7 with the Orwell Dev CPP
This version of Dev CPP is good for windows 8 only. However on Windows 7 you need the older version of it which is devcpp-4.9.9.2_setup.exe Download it from the link and use it. (Don't forget to uninstall any other version already installed on your pc) Also note that the older version does not work with windows 8.
i think you should link your project in console mode
just press Ctrl+h and in General tab select console.
For pure C++
You can't. C++ doesn't even have the concept of a console.
The program could be printing to a printer, outputting straight to a file, or being redirected to the input of another program for all it cares. Even if you could clear the console in C++, it would make those cases significantly messier.
See this entry in the comp.lang.c++ FAQ:
OS-Specific
If it still makes sense to clear the console in your program, and you are interested in operating system specific solutions, those do exist.
For Windows (as in your tag), check out this link:
Edit: This answer previously mentioned using system("cls");
, because Microsoft said to do that. However it has been pointed out in the comments that this is not a safe thing to do. I have removed the link to the Microsoft article because of this problem.
Libraries (somewhat portable)
ncurses is a library that supports console manipulation:
Eclipse uses it's own internal compiler that can compile to several Java versions.
From Eclipse Help > Java development user guide > Concepts > Java Builder
The Java builder builds Java programs using its own compiler (the Eclipse Compiler for Java) that implements the Java Language Specification.
For Eclipse Mars.1 Release (4.5.1), this can target 1.3 to 1.8 inclusive.
When you configure a project:
[project-name] > Properties > Java Compiler > Compiler compliance level
This configures the Eclipse Java compiler to compile code to the specified Java version, typically 1.8 today.
Host environment variables, eg JAVA_HOME etc, are not used.
The Oracle/Sun JDK compiler is not used.
This is based on another answer, but is just reformated:
Assuming you mean you want the non-numbers stripped out, you should be able to use something like:
'
' Skips all characters in the input string except digits
'
Function GetDigits(ByVal s As String) As String
Dim char As String
Dim i As Integer
GetDigits = ""
For i = 1 To Len(s)
char = Mid(s, i, 1)
If char >= "0" And char <= "9" Then
GetDigits = GetDigits + char
End If
Next i
End Function
Calling this with:
Dim myStr as String
myStr = GetDigits("3d1fgd4g1dg5d9gdg")
Call MsgBox(myStr)
will give you a dialog box containing:
314159
and those first two lines show how you can store it into an arbitrary string variable, to do with as you wish.
Yet another pure CSS solution (i.e. without the use of images, characters or additional fonts), based on @Bansoa is the answer's answer .
I've simplified it and added a bit of Flexbox magic to make it responsive.
Cross in this example automatically scales to any square container, and to change the thickness of its lines one have just to tune height: 4px;
(to make a cross truly responsive, you may want to set the height
in percents or other relative units).
div {_x000D_
position: relative;_x000D_
height: 150px; /* this can be anything */_x000D_
width: 150px; /* ...but maintain 1:1 aspect ratio */_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
justify-content: center;_x000D_
border: 1px solid pink; /* not required, added for better visibility */_x000D_
}_x000D_
_x000D_
div::before,_x000D_
div::after {_x000D_
position: absolute;_x000D_
content: '';_x000D_
width: 100%;_x000D_
height: 4px; /* cross thickness */_x000D_
background-color: black;_x000D_
}_x000D_
_x000D_
div::before {_x000D_
transform: rotate(45deg);_x000D_
}_x000D_
_x000D_
div::after {_x000D_
transform: rotate(-45deg);_x000D_
}
_x000D_
<div></div>
_x000D_
The easiest way that I use is this command on terminal:
docker logs elk > /home/Desktop/output.log
structure is:
docker logs <Container Name> > path/filename.log
Another solution might look like this,
char arr[] = "mom";
std::cout << "hi " << std::string(arr);
which avoids using an extra variable.
empty
is an operator:
The
empty
operator is a prefix operation that can be used to determine whether a value is null or empty.
<c:if test="${empty myObject.featuresList}">
$('td').click(function() {
var myCol = $(this).index();
var $tr = $(this).closest('tr');
var myRow = $tr.index();
});
simply add to your data structure ( mItems ) , and then notify your adapter about dataset change
private void addItem(String item) {
mItems.add(item);
mAdapter.notifyDataSetChanged();
}
addItem("New Item");
I had the exact same problem yesterday working through problem 2-3 in Accelerated C++. The key is to change all variables you will be comparing (using Boolean operators) to compatible types. In this case, that means string::size_type
(or unsigned int
, but since this example is using the former, I will just stick with that even though the two are technically compatible).
Notice that in their original code they did exactly this for the c counter (page 30 in Section 2.5 of the book), as you rightly pointed out.
What makes this example more complicated is that the different padding variables (padsides and padtopbottom), as well as all counters, must also be changed to string::size_type
.
Getting to your example, the code that you posted would end up looking like this:
cout << "Please enter the size of the frame between top and bottom";
string::size_type padtopbottom;
cin >> padtopbottom;
cout << "Please enter size of the frame from each side you would like: ";
string::size_type padsides;
cin >> padsides;
string::size_type c = 0; // definition of c in the program
if (r == padtopbottom + 1 && c == padsides + 1) { // where the error no longer occurs
Notice that in the previous conditional, you would get the error if you didn't initialize variable r as a string::size_type
in the for
loop. So you need to initialize the for loop using something like:
for (string::size_type r=0; r!=rows; ++r) //If r and rows are string::size_type, no error!
So, basically, once you introduce a string::size_type
variable into the mix, any time you want to perform a boolean operation on that item, all operands must have a compatible type for it to compile without warnings.
>>> from datetime import datetime
>>> print(datetime.today().strftime("%H:%M %p"))
15:31 AM
Try replacing %I
with %H
.
another thing that can cause this, even if everything is set up correctly, is running the command from a Makefile. for example, I had a rule:
awssetup:
aws configure
aws s3 sync s3://mybucket.whatever .
when I ran make awssetup
I got the error: fatal error: An error occurred (InvalidAccessKeyId) when calling the ListObjects operation: The AWS Access Key Id you provided does not exist in our records.
. but running it from the command line worked.
EDIT: I would appreciate it if you do not downvote this answer further. This answer is wrong, but I would rather retain it as a historical note. While it is arguable whether the pytz interface is error-prone, it can do things that dateutil.tz cannot do, especially regarding daylight-saving in the past or in the future. I have honestly recorded my experience in an article "Time zones in Python".
If you are on a Unix-like platform, I would suggest you avoid pytz and look just at /usr/share/zoneinfo. dateutil.tz can utilize the information there.
The following piece of code shows the problem pytz can give. I was shocked when I first found it out. (Interestingly enough, the pytz installed by yum on CentOS 7 does not exhibit this problem.)
import pytz
import dateutil.tz
from datetime import datetime
print((datetime(2017,2,13,14,29,29, tzinfo=pytz.timezone('Asia/Shanghai'))
- datetime(2017,2,13,14,29,29, tzinfo=pytz.timezone('UTC')))
.total_seconds())
print((datetime(2017,2,13,14,29,29, tzinfo=dateutil.tz.gettz('Asia/Shanghai'))
- datetime(2017,2,13,14,29,29, tzinfo=dateutil.tz.tzutc()))
.total_seconds())
-29160.0
-28800.0
I.e. the timezone created by pytz is for the true local time, instead of the standard local time people observe. Shanghai conforms to +0800, not +0806 as suggested by pytz:
pytz.timezone('Asia/Shanghai')
<DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>
EDIT: Thanks to Mark Ransom's comment and downvote, now I know I am using pytz the wrong way. In summary, you are not supposed to pass the result of pytz.timezone(…)
to datetime
, but should pass the datetime
to its localize
method.
Despite his argument (and my bad for not reading the pytz documentation more carefully), I am going to keep this answer. I was answering the question in one way (how to enumerate the supported timezones, though not with pytz), because I believed pytz did not provide a correct solution. Though my belief was wrong, this answer is still providing some information, IMHO, which is potentially useful to people interested in this question. Pytz's correct way of doing things is counter-intuitive. Heck, if the tzinfo created by pytz should not be directly used by datetime
, it should be a different type. The pytz interface is simply badly designed. The link provided by Mark shows that many people, not just me, have been misled by the pytz interface.
Different use case, but set your session as the default session did the trick for me:
with sess.as_default():
result = compute_fn([seed_input,1])
This is one of these mistakes that is so obvious, once you have solved it.
My use-case is the following:
1) store keras VGG16 as tensorflow graph
2) load kers VGG16 as a graph
3) run tf function on the graph and get:
FailedPreconditionError: Attempting to use uninitialized value block1_conv2/bias
[[Node: block1_conv2/bias/read = Identity[T=DT_FLOAT, _class=["loc:@block1_conv2/bias"], _device="/job:localhost/replica:0/task:0/device:GPU:0"](block1_conv2/bias)]]
[[Node: predictions/Softmax/_7 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_168_predictions/Softmax", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
just add your <script src="./custom.js"></script>
before </bod>
tag. that is supply time to d3.select(#chart)
detect your #chart
element in html body
put this command in your vimrc file
set ic
always do case insensitive search
You can use set
with the /p
argument:
SET /P variable=[promptString]
The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.
So, simply use something like
set /p Input=Enter some text:
Later you can use that variable as argument to a command:
myCommand %Input%
Be careful though, that if your input might contain spaces it's probably a good idea to quote it:
myCommand "%Input%"
I second the top voted answer, but feel like adding little more details here if anyone finds it useful.
short version:
IIS runs any website you configure in a process named w3wp.exe. IIS Application pool is feature in IIS which allows each website or a part of it to run under a corresponding w3wp.exe process. So you can run 100 websites all in a single w3wp.exe or 100 different w3wp.exe. E.g. run 3 websites in same application pool(same w3wp.exe) to save memory usage. ,run 2 different websites in two different application pools so that each can run under separate user account(called application pool identity). run a website in one application pool and a subsite 'website/app' under a different application pool.
Longer version:
Every website or a part of the website,you can run under an application pool.You can control some basic settings of the website using an application pool.
In the nav go View => Layout => Columns:2
(alt+shift+2
) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py
)
It appears you can also reopen the file using the command File -> New View into File
which will open the current file in a new tab
Solution ( group by like mysql)
grep -ioh "facebook\|xing\|linkedin\|googleplus" access-log.txt | sort | uniq -c | sort -n
Result
3249 googleplus
4211 linkedin
5212 xing
7928 facebook
A single quote is represented using \x27
Like in
awk 'BEGIN {FS=" ";} {printf "\x27%s\x27 ", $1}'
All the answers above about reload()
or imp.reload()
are deprecated.
reload()
is no longer a builtin function in python 3 and imp.reload()
is marked deprecated (see help(imp)
).
It's better to use importlib.reload()
instead.
What you are doing is not working, because you apply the margin: auto to the full-width column.
Wrap it in a div and center that one. E.g:
<div class="i-am-centered">
<div class="row">...</div>
</div>
.
.i-am-centered { margin: auto; max-width: 300px;}
Its a cleaner solution anyway, as it is more expressive and as you usually don't want to mess with the grid.
When I create a root class, whose methods I defined using the arrow functions. When inheriting and overwriting the original function I noticed the same issue.
class C {
x = () => 1;
};
class CC extends C {
x = (foo) => super.x() + foo;
};
let add = new CC;
console.log(add.x(4));
this is solved by defining the method of the parent class without arrow functions
class C {
x() {
return 1;
};
};
class CC extends C {
x = foo => super.x() + foo;
};
let add = new CC;
console.log(add.x(4));
To implement you need use Typeface go through with sample below
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Roboto/Roboto-Regular.ttf");
for (View view : allViews)
{
if (view instanceof TextView)
{
TextView textView = (TextView) view;
textView.setTypeface(typeface);
}
}
}
You can use the str.format
method. Examples:
>>> print('{0:.16f}'.format(1.6))
1.6000000000000001
>>> print('{0:.15f}'.format(1.6))
1.600000000000000
Note the 1
at the end of the first example is rounding error; it happens because exact representation of the decimal number 1.6 requires an infinite number binary digits. Since floating-point numbers have a finite number of bits, the number is rounded to a nearby, but not equal, value.
You can use the "modulo-formatting" syntax (this works for Python 2.6 and 2.7 too):
>>> print '%.16f' % 1.6
1.6000000000000001
>>> print '%.15f' % 1.6
1.600000000000000
You may try indexed-file-reader (Apache License 2.0). The class IndexedFileReader has a method called readLines(int from, int to) which returns a SortedMap whose key is the line number and the value is the line that was read.
Example:
File file = new File("src/test/resources/file.txt");
reader = new IndexedFileReader(file);
lines = reader.readLines(6, 10);
assertNotNull("Null result.", lines);
assertEquals("Incorrect length.", 5, lines.size());
assertTrue("Incorrect value.", lines.get(6).startsWith("[6]"));
assertTrue("Incorrect value.", lines.get(7).startsWith("[7]"));
assertTrue("Incorrect value.", lines.get(8).startsWith("[8]"));
assertTrue("Incorrect value.", lines.get(9).startsWith("[9]"));
assertTrue("Incorrect value.", lines.get(10).startsWith("[10]"));
The above example reads a text file composed of 50 lines in the following format:
[1] The quick brown fox jumped over the lazy dog ODD
[2] The quick brown fox jumped over the lazy dog EVEN
Disclamer: I wrote this library
In iReport 5.5.0, just right click the report base hierarchy in Report Inspector Bloc Window viewer, then click Compile Report
You can now see the result in the console down. If no Errors, you may see something like this.
I use RETURN
here all the time, works in script or Stored Procedure
Make sure you ROLLBACK
the transaction if you are in one, otherwise RETURN
immediately will result in an open uncommitted transaction
You're all thinking too hard. Just use a simple Regular Expression, it's your best friend.
var string1 = "Hi Stack Overflow. I like to eat pizza."
var string2 = "Damn, I fail."
var regex = /(pizza)/g // Insert whatever phrase or character you want to find
string1.test(regex); // => true
string2.test(regex); // => false
Sometimes PostgreSQL fails to make the best choice of indexes for a particular condition. As an example, suppose there is a transactions table with several million rows, of which there are several hundred for any given day, and the table has four indexes: transaction_id, client_id, date, and description. You want to run the following query:
SELECT client_id, SUM(amount)
FROM transactions
WHERE date >= 'yesterday'::timestamp AND date < 'today'::timestamp AND
description = 'Refund'
GROUP BY client_id
PostgreSQL may choose to use the index transactions_description_idx instead of transactions_date_idx, which may lead to the query taking several minutes instead of less than one second. If this is the case, you can force using the index on date by fudging the condition like this:
SELECT client_id, SUM(amount)
FROM transactions
WHERE date >= 'yesterday'::timestamp AND date < 'today'::timestamp AND
description||'' = 'Refund'
GROUP BY client_id
@last-child's answer is a great answer!
However, adding a border to my H2 produced an underline longer than the text.
If you're dynamically writing your CSS, or if like me you're lucky and know what the text will be, you can do the following:
change the content
to something the right length (ie the same
text) set the font color to transparent
(or rgba(0,0,0,0)
)
to underline <h2>Processing</h2>
(for example),
change last-child's code to be:
a {
text-decoration: none;
position: relative;
}
a:after {
content: 'Processing';
color: transparent;
width: 100%;
position: absolute;
left: 0;
bottom: 1px;
border-width: 0 0 1px;
border-style: solid;
}
Try to see if the following code helps you:
Dim iDate As String = "05/05/2005"
Dim oDate As DateTime = Convert.ToDateTime(iDate)
private String convertToRoman(int num) {
String result = "";
while(num > 0){
if(num >= 1000){
result += "M";
num -= 1000;
}else if(num >= 900){
result += "CM";
num -= 900;
}
else if(num >= 500){
result += "D";
num -= 500;
}else if(num >= 400){
result += "CD";
num -= 400;
}else if(num >= 100){
result += "C";
num -= 100;
}else if(num >= 90){
result += "XC";
num -= 90;
}else if(num >= 50){
result += "L";
num -= 50;
}else if(num >= 40){
result += "XL";
num -= 40;
}
else if(num >= 10){
result += "X";
num -= 10;
}else if(num >= 9){
result += "IX";
num -= 9;
}
else if(num >= 5){
result += "V";
num -= 5;
}else if(num >= 4){
result += "IV";
num -= 4;
}else if(num >= 1){
result += "I";
num -= 1;
}
else{
break;
}
}
return result;
}
Use ON DUPLICATE KEY UPDATE ...
,
Negative : because the UPDATE
uses resources for the second action.
Use INSERT IGNORE ...
,
Negative : MySQL will not show any errors if something goes wrong, so you cannot handle the errors. Use it only if you don’t care about the query.
If the goal is to create a grid with equal height rows, where the tallest cell in the grid sets the height for all rows, here's a quick and simple solution:
grid-auto-rows: 1fr
Grid Layout provides a unit for establishing flexible lengths in a grid container. This is the fr
unit. It is designed to distribute free space in the container and is somewhat analogous to the flex-grow
property in flexbox.
If you set all rows in a grid container to 1fr
, let's say like this:
grid-auto-rows: 1fr;
... then all rows will be equal height.
It doesn't really make sense off-the-bat because fr
is supposed to distribute free space. And if several rows have content with different heights, then when the space is distributed, some rows would be proportionally smaller and taller.
Except, buried deep in the grid spec is this little nugget:
7.2.3. Flexible Lengths: the
fr
unit...
When the available space is infinite (which happens when the grid container’s width or height is indefinite), flex-sized (
fr
) grid tracks are sized to their contents while retaining their respective proportions.The used size of each flex-sized grid track is computed by determining the
max-content
size of each flex-sized grid track and dividing that size by the respective flex factor to determine a “hypothetical1fr
size”.The maximum of those is used as the resolved
1fr
length (the flex fraction), which is then multiplied by each grid track’s flex factor to determine its final size.
So, if I'm reading this correctly, when dealing with a dynamically-sized grid (e.g., the height is indefinite), grid tracks (rows, in this case) are sized to their contents.
The height of each row is determined by the tallest (max-content
) grid item.
The maximum height of those rows becomes the length of 1fr
.
That's how 1fr
creates equal height rows in a grid container.
As noted in the question, equal height rows are not possible with flexbox.
Flex items can be equal height on the same row, but not across multiple rows.
This behavior is defined in the flexbox spec:
In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.
In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.
From the definition of height:
Applies to: all elements but non-replaced inline elements, table columns, and column groups
An a
element is, by default an inline element (and it is non-replaced).
You need to change the display (directly with the display property or indirectly, e.g. with float).
DISTINCT
removes rows if all selected values are equal. Apparently, you have entries with the same p.id
but with different pl.nm
(or pl.val
or pl.txt_val
). The answer to your question depends on which one of these values you want to show in the one row with your p.id
(the first? the smallest? any?).
sysname
is a built in datatype limited to 128 Unicode characters that, IIRC, is used primarily to store object names when creating scripts. Its value cannot be NULL
It is basically the same as using nvarchar(128) NOT NULL
EDIT
As mentioned by @Jim in the comments, I don't think there is really a business case where you would use sysname
to be honest. It is mainly used by Microsoft when building the internal sys
tables and stored procedures etc within SQL Server.
For example, by executing Exec sp_help 'sys.tables'
you will see that the column name
is defined as sysname
this is because the value of this is actually an object in itself (a table)
I would worry too much about it.
It's also worth noting that for those people still using SQL Server 6.5 and lower (are there still people using it?) the built in type of sysname
is the equivalent of varchar(30)
Documentation
sysname
is defined with the documentation for nchar
and nvarchar
, in the remarks section:
sysname is a system-supplied user-defined data type that is functionally equivalent to nvarchar(128), except that it is not nullable. sysname is used to reference database object names.
To clarify the above remarks, by default sysname is defined as NOT NULL
it is certainly possible to define it as nullable. It is also important to note that the exact definition can vary between instances of SQL Server.
The sysname data type is used for table columns, variables, and stored procedure parameters that store object names. The exact definition of sysname is related to the rules for identifiers. Therefore, it can vary between instances of SQL Server. sysname is functionally the same as nvarchar(128) except that, by default, sysname is NOT NULL. In earlier versions of SQL Server, sysname is defined as varchar(30).
Some further information about sysname
allowing or disallowing NULL
values can be found here https://stackoverflow.com/a/52290792/300863
Just because it is the default (to be NOT NULL) does not guarantee that it will be!
I have it working in only JavaScript. Firefox won't let you update the keyCode, so all you can do is trap keyCode 13 and force it to focus on the next element by tabIndex as if keyCode 9 was pressed. The tricky part is finding the next tabIndex. I have tested this only on IE8-IE10 and Firefox and it works:
function ModifyEnterKeyPressAsTab(event)
{
var caller;
var key;
if (window.event)
{
caller = window.event.srcElement; //Get the event caller in IE.
key = window.event.keyCode; //Get the keycode in IE.
}
else
{
caller = event.target; //Get the event caller in Firefox.
key = event.which; //Get the keycode in Firefox.
}
if (key == 13) //Enter key was pressed.
{
cTab = caller.tabIndex; //caller tabIndex.
maxTab = 0; //highest tabIndex (start at 0 to change)
minTab = cTab; //lowest tabIndex (this may change, but start at caller)
allById = document.getElementsByTagName("input"); //Get input elements.
allByIndex = []; //Storage for elements by index.
c = 0; //index of the caller in allByIndex (start at 0 to change)
i = 0; //generic indexer for allByIndex;
for (id in allById) //Loop through all the input elements by id.
{
allByIndex[i] = allById[id]; //Set allByIndex.
tab = allByIndex[i].tabIndex;
if (caller == allByIndex[i])
c = i; //Get the index of the caller.
if (tab > maxTab)
maxTab = tab; //Get the highest tabIndex on the page.
if (tab < minTab && tab >= 0)
minTab = tab; //Get the lowest positive tabIndex on the page.
i++;
}
//Loop through tab indexes from caller to highest.
for (tab = cTab; tab <= maxTab; tab++)
{
//Look for this tabIndex from the caller to the end of page.
for (i = c + 1; i < allByIndex.length; i++)
{
if (allByIndex[i].tabIndex == tab)
{
allByIndex[i].focus(); //Move to that element and stop.
return;
}
}
//Look for the next tabIndex from the start of page to the caller.
for (i = 0; i < c; i++)
{
if (allByIndex[i].tabIndex == tab + 1)
{
allByIndex[i].focus(); //Move to that element and stop.
return;
}
}
//Continue searching from the caller for the next tabIndex.
}
//The caller was the last element with the highest tabIndex,
//so find the first element with the lowest tabIndex.
for (i = 0; i < allByIndex.length; i++)
{
if (allByIndex[i].tabIndex == minTab)
{
allByIndex[i].focus(); //Move to that element and stop.
return;
}
}
}
}
To use this code, add it to your html input tag:
<input id="SomeID" onkeydown="ModifyEnterKeyPressAsTab(event);" ... >
Or add it to an element in javascript:
document.getElementById("SomeID").onKeyDown = ModifyEnterKeyPressAsTab;
A couple other notes:
I only needed it to work on my input elements, but you could extend it to other document elements if you need to. For this, getElementsByClassName is very helpful, but that is a whole other topic.
A limitation is that it only tabs between the elements that you have added to your allById array. It does not tab around to the other things that your browser might, like toolbars and menus outside your html document. Perhaps this is a feature instead of a limitation. If you like, trap keyCode 9 and this behavior will work with the tab key too.
There is a possibility that your installation of MYSQL got corrupted. The best thing you can do is to search for MYSQL INSTALLER on your system and then run it again.
It will not download the mysql server again, it will just help you to set it up.
After that, edit your environment variables
path and add the bin folder of your mysql to it.
By now, it should work.
Here is one more option:
public System.String GetRandomString(System.Int32 length)
{
System.Byte[] seedBuffer = new System.Byte[4];
using (var rngCryptoServiceProvider = new System.Security.Cryptography.RNGCryptoServiceProvider())
{
rngCryptoServiceProvider.GetBytes(seedBuffer);
System.String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
System.Random random = new System.Random(System.BitConverter.ToInt32(seedBuffer, 0));
return new System.String(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
}
}
My problem at first was:
Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace.
1) I Right click on my project -> Android Tools -> Add Support Library (Run my app...Didn't work so I keep it going...) 2) Right click on my project again -> Properties -> Android -> Check Android 4.1.2 (16) on Project Build Target (Run the app again...and get this:
Unable to execute dex: Multiple dex files define Landroid/support/v4/app/BackStackState;
3) So I went to the "lib" folder on my project and delete the "old" Android.support.library.jar (Run the app and cross fingers and...)
¡IT WORKS!
Hope it helps someone...Thanks people!
I think, jogojapan gave an very good and exhaustive answer. You definitively should take a look at it before reading my post. However, I'd like to add the following:
unordered_map
separately, instead of using the equality comparison operator (operator==
). This might be helpful, for example, if you want to use the latter for comparing all members of two Node
objects to each other, but only some specific members as key of an unordered_map
.All in all, for your Node
class, the code could be written as follows:
using h = std::hash<int>;
auto hash = [](const Node& n){return ((17 * 31 + h()(n.a)) * 31 + h()(n.b)) * 31 + h()(n.c);};
auto equal = [](const Node& l, const Node& r){return l.a == r.a && l.b == r.b && l.c == r.c;};
std::unordered_map<Node, int, decltype(hash), decltype(equal)> m(8, hash, equal);
Notes:
Be aware that the third parameter (value) in the examples given above: the value is a constant (e.g. 'Z' or c(20,30)).
Defining the third parameter using values from the data frame itself can lead to confusion.
E.g. with a simple data frame such as this (using dplyr::data_frame):
tmp <- data_frame(a=1:10, b=sample(LETTERS[24:26], 10, replace=T))
This will create somthing like this:
a b
(int) (chr)
1 1 X
2 2 Y
3 3 Y
4 4 X
5 5 Z
..etc
Now suppose you want wanted to do, was to multiply the values in column 'a' by 2, but only where column 'b' is "X". My immediate thought would be something like this:
with(tmp, replace(a, b=="X", a*2))
That will not provide the desired outcome, however. The a*2 will defined as a fixed vector rather than a reference to the 'a' column. The vector 'a*2' will thus be
[1] 2 4 6 8 10 12 14 16 18 20
at the start of the 'replace' operation. Thus, the first row where 'b' equals "X", the value in 'a' will be placed by 2. The second time, it will be replaced by 4, etc ... it will not be replaced by two-times-the-value-of-a in that particular row.
I encountered this problem while upgrading from CXF 2.7.0 to 3.0.2. Here is what I did to resolve it:
Included the following in my pom.xml
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.0</version>
</dependency>
and added the following provider
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider" />
</jaxrs:providers>
You've almost done it. However setting flex: 0 0 <basis>
declaration to the columns would prevent them from growing/shrinking; And the <basis>
parameter would define the width of columns.
In addition, you could use CSS3 calc()
expression to specify the height
of columns with the respect to the height of the header.
#productShowcaseTitle {
flex: 0 0 100%; /* Let it fill the entire space horizontally */
height: 100px;
}
#productShowcaseDetail,
#productShowcaseThumbnailContainer {
height: calc(100% - 100px); /* excluding the height of the header */
}
#productShowcaseContainer {_x000D_
display: flex;_x000D_
flex-flow: row wrap;_x000D_
_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
flex: 0 0 100%; /* Let it fill the entire space horizontally */_x000D_
height: 100px;_x000D_
background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
flex: 0 0 66%; /* ~ 2 * 33.33% */_x000D_
height: calc(100% - 100px); /* excluding the height of the header */_x000D_
background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
flex: 0 0 34%; /* ~ 33.33% */_x000D_
height: calc(100% - 100px); /* excluding the height of the header */_x000D_
background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
<div id="productShowcaseTitle"></div>_x000D_
<div id="productShowcaseDetail"></div>_x000D_
<div id="productShowcaseThumbnailContainer"></div>_x000D_
</div>
_x000D_
(Vendor prefixes omitted due to brevity)
Alternatively, if you could change your markup e.g. wrapping the columns by an additional <div>
element, it would be achieved without using calc()
as follows:
<div class="contentContainer"> <!-- Added wrapper -->
<div id="productShowcaseDetail"></div>
<div id="productShowcaseThumbnailContainer"></div>
</div>
#productShowcaseContainer {
display: flex;
flex-direction: column;
height: 600px; width: 580px;
}
.contentContainer { display: flex; flex: 1; }
#productShowcaseDetail { flex: 3; }
#productShowcaseThumbnailContainer { flex: 2; }
#productShowcaseContainer {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
}_x000D_
_x000D_
.contentContainer {_x000D_
display: flex;_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
height: 100px;_x000D_
background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
flex: 3;_x000D_
background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
flex: 2;_x000D_
background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
<div id="productShowcaseTitle"></div>_x000D_
_x000D_
<div class="contentContainer"> <!-- Added wrapper -->_x000D_
<div id="productShowcaseDetail"></div>_x000D_
<div id="productShowcaseThumbnailContainer"></div>_x000D_
</div>_x000D_
</div>
_x000D_
(Vendor prefixes omitted due to brevity)
The simple thing is to put the script below the document, just before your closing </body>
tag:
<body>
<div id="main">
<div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>
<script src="app.js"></script>
</body>
app.js file:
var main = new Vue({
el: '#main',
data: {
currentActivity: 'home'
}
});
I was doing some volume rendering in octave (matlab clone) and building my 3D arrays (ie an array of 2d slices) using
buffer=zeros(1,512*512*512,"uint16");
vol=reshape(buffer,512,512,512);
Memory consumption seemed to be efficient. (can't say the same for the subsequent speed of computations :^)
You can add a class to each of your .row
divs to add some space in between them like so:
.spacer {
margin-top: 40px; /* define margin as you see fit */
}
You can then use it like so:
<div class="row spacer">
<div class="span4">...</div>
<div class="span4">...</div>
<div class="span4">...</div>
</div>
<div class="row spacer">
<div class="span4">...</div>
<div class="span4">...</div>
<div class="span4">...</div>
</div>
I ran into the exact same problem under identical circumstances. I don't have the tnsnames.ora file, and I wanted to use SQL*Plus with Easy Connection Identifier format in command line. I solved this problem as follows.
The SQL*Plus® User's Guide and Reference gives an example:
sqlplus hr@\"sales-server:1521/sales.us.acme.com\"
Pay attention to two important points:
I found these good questions to detect service name via existing connection: 1, 2. Try this query for example:
SELECT value FROM V$SYSTEM_PARAMETER WHERE UPPER(name) = 'SERVICE_NAMES'
Activity
To pass a bitmap between Activites
Intent intent = new Intent(this, Activity.class);
intent.putExtra("bitmap", bitmap);
And in the Activity class
Bitmap bitmap = getIntent().getParcelableExtra("bitmap");
Fragment
To pass a bitmap between Fragments
SecondFragment fragment = new SecondFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap", bitmap);
fragment.setArguments(bundle);
To receive inside the SecondFragment
Bitmap bitmap = getArguments().getParcelable("bitmap");
Transferring large bitmap (Compress bitmap)
If you are getting failed binder transaction, this means you are exceeding the binder transaction buffer by transferring large element from one activity to another activity.
So in that case you have to compress the bitmap as an byte's array and then uncompress it in another activity, like this
In the FirstActivity
Intent intent = new Intent(this, SecondActivity.class);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
byte[] bytes = stream.toByteArray();
intent.putExtra("bitmapbytes",bytes);
And in the SecondActivity
byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
There is an answer by @hexafraction , He had specified the x and y to be top right corner which is wrong, those are top left corner .
I have also provided the source please check it.
public void setBounds(int x,
int y,
int width,
int height)
Moves and resizes this component. The new location of the top-left corner is specified by x and y, and the new size is specified by width and height. This method changes layout-related information, and therefore, invalidates the component hierarchy.
Parameters:
x - the new x-coordinate of this component
y - the new y-coordinate of this component
width - the new width of this component
height - the new height of this component
source:- setBounds
Use a duplicated double quote.
@"this ""word"" is escaped";
outputs:
this "word" is escaped
Simple: In Visual Studio Report designer
1. Open the report in design mode and delete the dataset from the RDLC File
2. Open solution Explorer and delete the actual (corrupted) XSD file
3. Add the dataset back to the RDLC file.
4. The above procedure will create the new XSD file.
5. More detailed is below.
In Visual Studio, Open your RDLC file Report in Design mode. Click on the report and then Select View and then Report Data from the top line menu. Select Datasets and then Right Click and delete the dataset from the report. Next Open Solution Explorer, if it is not already open in your Visual Studio. Locate the XSD file (It should be the same name as the dataset you just deleted from the report). Now go back and right click again on the report data Datasets, and select Add Dataset . This will create a new XSD file and write the dataset properties to the report. Now your error message will be gone and any missing data will now appear in your reports.
No, LINQ doesn't support a manner of mass updating. The only shorter way would be to use a ForEach
extension method - Why there is no ForEach extension method on IEnumerable?
If you want to checkout all the files 'anywhere'
git checkout -- $(git rev-parse --show-toplevel)
Another way is,
mysql > SHOW CREATE TABLE my_db.my_table;
You should get the table name and create table sql
Use
var isEmpty: Bool { get }
Example
let lang = "Swift 5"
if lang.isEmpty {
print("Empty string")
}
If you want to ignore white spaces
if lang.trimmingCharacters(in: .whitespaces).isEmpty {
print("Empty string")
}
OP's solution to his problem, as he says, has dubious output. That code still shows confusion about representations of time. To clear up this confusion, and make code that won't lead to wrong times, consider this extension of what he did:
public static void _testDateFormatting() {
SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfGMT2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
sdfGMT2.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfLocal1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
SimpleDateFormat sdfLocal2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
try {
Date d = new Date();
String s1 = d.toString();
String s2 = sdfLocal1.format(d);
// Store s3 or s4 in database.
String s3 = sdfGMT1.format(d);
String s4 = sdfGMT2.format(d);
// Retrieve s3 or s4 from database, using LOCAL sdf.
String s5 = sdfLocal1.parse(s3).toString();
//EXCEPTION String s6 = sdfLocal2.parse(s3).toString();
String s7 = sdfLocal1.parse(s4).toString();
String s8 = sdfLocal2.parse(s4).toString();
// Retrieve s3 from database, using GMT sdf.
// Note that this is the SAME sdf that created s3.
Date d2 = sdfGMT1.parse(s3);
String s9 = d2.toString();
String s10 = sdfGMT1.format(d2);
String s11 = sdfLocal2.format(d2);
} catch (Exception e) {
e.printStackTrace();
}
}
examining values in a debugger:
s1 "Mon Sep 07 06:11:53 EDT 2015" (id=831698113128)
s2 "2015.09.07 06:11:53" (id=831698114048)
s3 "2015.09.07 10:11:53" (id=831698114968)
s4 "2015.09.07 10:11:53 GMT+00:00" (id=831698116112)
s5 "Mon Sep 07 10:11:53 EDT 2015" (id=831698116944)
s6 -- omitted, gave parse exception
s7 "Mon Sep 07 10:11:53 EDT 2015" (id=831698118680)
s8 "Mon Sep 07 06:11:53 EDT 2015" (id=831698119584)
s9 "Mon Sep 07 06:11:53 EDT 2015" (id=831698120392)
s10 "2015.09.07 10:11:53" (id=831698121312)
s11 "2015.09.07 06:11:53 EDT" (id=831698122256)
sdf2 and sdfLocal2 include time zone, so we can see what is really going on. s1 & s2 are at 06:11:53 in zone EDT. s3 & s4 are at 10:11:53 in zone GMT -- equivalent to the original EDT time. Imagine we save s3 or s4 in a data base, where we are using GMT for consistency, so we can have times from anywhere in the world, without storing different time zones.
s5 parses the GMT time, but treats it as a local time. So it says "10:11:53" -- the GMT time -- but thinks it is 10:11:53 in local time. Not good.
s7 parses the GMT time, but ignores the GMT in the string, so still treats it as a local time.
s8 works, because now we include GMT in the string, and the local zone parser uses it to convert from one time zone to another.
Now suppose you don't want to store the zone, you want to be able to parse s3, but display it as a local time. The answer is to parse using the same time zone it was stored in -- so use the same sdf as it was created in, sdfGMT1. s9, s10, & s11 are all representations of the original time. They are all "correct". That is, d2 == d1. Then it is only a question of how you want to DISPLAY it. If you want to display what is stored in DB -- GMT time -- then you need to format it using a GMT sdf. Ths is s10.
So here is the final solution, if you don't want to explicitly store with " GMT" in the string, and want to display in GMT format:
public static void _testDateFormatting() {
SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
Date d = new Date();
String s3 = sdfGMT1.format(d);
// Store s3 in DB.
// ...
// Retrieve s3 from database, using GMT sdf.
Date d2 = sdfGMT1.parse(s3);
String s10 = sdfGMT1.format(d2);
} catch (Exception e) {
e.printStackTrace();
}
}
fmod
is the standard C function for handling floating-point modulus; I imagine your source was saying that Java handles floating-point modulus the same as C's fmod
function. In Java you can use the %
operator on doubles the same as on integers:
int x = 5 % 3; // x = 2
double y = .5 % .3; // y = .2
For ubuntu 14.04LTS with php 7, issue:
sudo apt-get install php-dev
Then install:
pecl install memcache
If you want an alphanumeric strings with lowercase and uppercase characters ([a-zA-Z0-9]), you can use Convert.ToBase64String() for a fast and simple solution.
As for uniqueness, check out the birthday problem to calculate how likely a collission is given (A) the length of the strings generated and (B) the number of strings generated.
Random random = new Random();
int outputLength = 10;
int byteLength = (int)Math.Ceiling(3f / 4f * outputLength); // Base64 uses 4 characters for every 3 bytes of data; so in random bytes we need only 3/4 of the desired length
byte[] randomBytes = new byte[byteLength];
string output;
do
{
random.NextBytes(randomBytes); // Fill bytes with random data
output = Convert.ToBase64String(randomBytes); // Convert to base64
output = output.Substring(0, outputLength); // Truncate any superfluous characters and/or padding
} while (output.Contains('/') || output.Contains('+')); // Repeat if we contain non-alphanumeric characters (~25% chance if length=10; ~50% chance if length=20; ~35% chance if length=32)
In React or any Javascript modules that internally use Webpack, if the src attribute value of img is given as a path in string format as given below
e.g. <img src={'/src/images/logo.png'} /> or <img src='/src/images/logo.png' />
then during build, the final HTML page built contains src='/src/images/logo.png'. This path is not read during build time, but is read during rendering in browser. At the rendering time, if the logo.png is not found in the /src/images directory, then the image would not render. If you open the console in browser, you can see the 404 error for the image. I believe you meant to use ./src directory instead of /src directory. In that case, the development directory ./src is not available to the browser. When the page is loaded in browser only the files in the 'public' directory are available to the browser. So, the relative path ./src is assumed to be public/src directory and if the logo.png is not found in public/src/images/ directory, it would not render the image.
So, the solution for this problem is either to put your image in the public directory and reference the relative path from public directory or use import
or require
keywords in React or any Javascript module to inform the Webpack to read this path during build phase and include the image in the final build output. The details of both these methods has been elaborated by Dan Abramov in his answer, please refer to it or use the link: https://create-react-app.dev/docs/adding-images-fonts-and-files/
You would need to install pip3.
On Linux, the command would be: sudo apt install python3-pip
On Mac, using brew, first brew install python3
Then brew postinstall python3
Try calling pip3 -V
to see if it worked.
Sorry to jump on this question late in the game but I have an answer for irregular (non-rectangular) shapes. I solved it using SVGs to generate masks of where I want to have the event attached.
The idea is to attach events to inlined SVGs, super cheap and even user friendly because there are plenty of programs for generating SVGs. The SVG can have a layer of the image as a background.
http://jcrogel.com/code/2015/03/18/mapping-images-using-javascript-events/
Whether a string can be parsed as a number is a runtime concern. Typescript does not support this use case as it is focused on compile time (not runtime) safety.
This will work:
#!/usr/bin/expect -f
spawn scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no file1 file2 file3 user@host:/path/
expect "password:"
send "xyz123\r"
expect "*\r"
expect "\r"
interact
Hope you can Successfully remove your project. Happy Coding :)
The JAX-WS way for basic authentication is
Service s = new Service();
Port port = s.getPort();
BindingProvider prov = (BindingProvider)port;
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "myusername");
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "mypassword");
port.call();
I faced same issue, I uploaded ipa via Xcode7 and it get stuck for 48hrs. Number of times I mail to apple support but it won't work so I uploaded ipa multiple times, but no use then I made change in version number e.g. 2.2(33) to 2.3(1) and it works for me. So try at your side may be this will help you.
It's just the required syntax:
void Func(int (&myArray)[100])
^ Pass array of 100 int
by reference the parameters name is myArray
;
void Func(int* myArray)
^ Pass an array. Array decays to a pointer. Thus you lose size information.
void Func(int (*myFunc)(double))
^ Pass a function pointer. The function returns an int
and takes a double
. The parameter name is myFunc
.
After Python 3.5 you can also use:
import subprocess
f = open('test.txt', 'w')
process = subprocess.run(['ls', '-la'], stdout=subprocess.PIPE, universal_newlines=True)
f.write(process.stdout)
f.close()
The execution of the command is blocking and the output will be in process.stdout.
Visual Studio
windows.h
)Visual Studio Code
//use fabs()
double sum_primary_diagonal=0;
double sum_secondary_diagonal=0;
double difference = fabs(sum_primary_diagonal - sum_secondary_diagonal);
Perl was likely the first language to use it. Groovy is another language that supports it. Basically instead of returning 1
(true
) or 0
(false
) depending on whether the arguments are equal or unequal, the spaceship operator will return 1
, 0
, or -1
depending on the value of the left argument relative to the right argument.
a <=> b :=
if a < b then return -1
if a = b then return 0
if a > b then return 1
if a and b are not comparable then return nil
It's useful for sorting an array.
Consider using the Restlet framework, which has great semantics for this sort of thing. It's powerful and flexible.
The code could be as simple as:
Client client = new Client(Protocol.HTTP);
Response response = client.get(url);
if (response.getStatus().isError()) {
// uh oh!
}
The primary flag seems to only work for vagrant ssh
for me.
In the past I have used the following method to hack around the issue.
# stage box intended for configuration closely matching production if ARGV[1] == 'stage' config.vm.define "stage" do |stage| box_setup stage, \ "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml" end end
For Python Run This Command
apt-get install -y python-setuptools
For Python 3.
apt-get install -y python3-setuptools
Nginx prefers prefix-based location matches (not involving regular expression), that's why in your code block, /stash redirects are going to /.
The algorithm used by Nginx to select which location to use is described thoroughly here: https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms#matching-location-blocks
This worked for me as well:
Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"
Eclipse folder has an initialization file which is used by eclipse on launch/Double click it is named as eclipse.ini. Add the following lines in eclipse.ini file. Where the vm defines the path of JVM with which we want eclipse to use.
-vm
C:\Program Files\Java\jdk1.8\bin\javaw.exe
Make sure you have add the above lines separately and above the following line
--launcher.appendVmargs
-vmargs
I solved this problem by switching to root with sudo su.
http://www.unicode.org is the place to look for symbol names.
? BLACK CIRCLE 25CF
? MEDIUM BLACK CIRCLE 26AB
? BLACK LARGE CIRCLE 2B24
or even:
NEW MOON SYMBOL 1F311
Good luck finding a font that supports them all. Only one shows up in Windows 7 with Chrome.
Taking care of whether the array starts at zero or one. Also, when position 0 or 1 is returned by the function, making sure that the same is not confused as True or False returned by the function.
Function array_return_index(arr As Variant, val As Variant, Optional array_start_at_zero As Boolean = True) As Variant
Dim pos
pos = Application.Match(val, arr, False)
If Not IsError(pos) Then
If array_start_at_zero = True Then
pos = pos - 1
'initializing array at 0
End If
array_return_index = pos
Else
array_return_index = False
End If
End Function
Sub array_return_index_test()
Dim pos, arr, val
arr = Array(1, 2, 4, 5)
val = 1
'When array starts at zero
pos = array_return_index(arr, val)
If IsNumeric(pos) Then
MsgBox "Array starting at 0; Value found at : " & pos
Else
MsgBox "Not found"
End If
'When array starts at one
pos = array_return_index(arr, val, False)
If IsNumeric(pos) Then
MsgBox "Array starting at 1; Value found at : " & pos
Else
MsgBox "Not found"
End If
End Sub
The other answers and comments are correct in that to examine the contents of a stream, one must add a terminal operation, thereby "consuming" the stream. However, one can do this and turn the result back into a stream, without buffering up the entire contents of the stream. Here are a couple examples:
static <T> Stream<T> throwIfEmpty(Stream<T> stream) {
Iterator<T> iterator = stream.iterator();
if (iterator.hasNext()) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false);
} else {
throw new NoSuchElementException("empty stream");
}
}
static <T> Stream<T> defaultIfEmpty(Stream<T> stream, Supplier<T> supplier) {
Iterator<T> iterator = stream.iterator();
if (iterator.hasNext()) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false);
} else {
return Stream.of(supplier.get());
}
}
Basically turn the stream into an Iterator
in order to call hasNext()
on it, and if true, turn the Iterator
back into a Stream
. This is inefficient in that all subsequent operations on the stream will go through the Iterator's hasNext()
and next()
methods, which also implies that the stream is effectively processed sequentially (even if it's later turned parallel). However, this does allow you to test the stream without buffering up all of its elements.
There is probably a way to do this using a Spliterator
instead of an Iterator
. This potentially allows the returned stream to have the same characteristics as the input stream, including running in parallel.
There is a better way of checking radios and checkbox; you have to pass an array of values to the val method instead of a raw value
Note: If you simply pass the value by itself (without being inside an array), that will result in all values of "mygroup" being set to the value.
$("input[name=mygroup]").val([5]);
Here is the jQuery doc that explains how it works: http://api.jquery.com/val/#val-value
And .val([...])
also works with form elements like <input type="checkbox">
, <input type="radio">
, and <option>
s inside of a <select>
.
The inputs and the options having a value that matches one of the elements of the array will be checked or selected, while those having a value that don't match one of the elements of the array will be unchecked or unselected
Fiddle demonstrating this working: https://jsfiddle.net/92nekvp3/
Hope here is the exact what we are looking for.
private void button2_Click(object sender, RoutedEventArgs e)
{
UpdateExcel("Sheet3", 4, 7, "Namachi@gmail");
}
private void UpdateExcel(string sheetName, int row, int col, string data)
{
Microsoft.Office.Interop.Excel.Application oXL = null;
Microsoft.Office.Interop.Excel._Workbook oWB = null;
Microsoft.Office.Interop.Excel._Worksheet oSheet = null;
try
{
oXL = new Microsoft.Office.Interop.Excel.Application();
oWB = oXL.Workbooks.Open("d:\\MyExcel.xlsx");
oSheet = String.IsNullOrEmpty(sheetName) ? (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet : (Microsoft.Office.Interop.Excel._Worksheet)oWB.Worksheets[sheetName];
oSheet.Cells[row, col] = data;
oWB.Save();
MessageBox.Show("Done!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
if (oWB != null)
oWB.Close();
}
}
You can upload up to 8 screenshots. Those screenshots must be one of the dimensions (sizes) you listed; you can have multiple screenshots of the same dimensions.
This should also work:
AggregateValues("hello", MyList.ConvertAll(c => c.Name).ToArray())
Here, I am giving you a demo example. See this and customize it according to your need.
public class ShowPopUp extends Activity {
PopupWindow popUp;
boolean click = true;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
popUp = new PopupWindow(this);
LinearLayout layout = new LinearLayout(this);
LinearLayout mainLayout = new LinearLayout(this);
TextView tv = new TextView(this);
Button but = new Button(this);
but.setText("Click Me");
but.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (click) {
popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
popUp.update(50, 50, 300, 80);
click = false;
} else {
popUp.dismiss();
click = true;
}
}
});
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.VERTICAL);
tv.setText("Hi this is a sample text for popup window");
layout.addView(tv, params);
popUp.setContentView(layout);
// popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
mainLayout.addView(but, params);
setContentView(mainLayout);
}
}
Hope this will solve your issue.
var select = document.getElementById("DropList");
var length = select.options.length;
for (i = 0; i < length; i++) {
select.options[i].remove();
}
Hope, this code will helps you
A rect
can't contain a text
element. Instead transform a g
element with the location of text and rectangle, then append both the rectangle and the text to it:
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("rect")
.attr("width", x)
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d) { return x(d) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) { return d; });
http://bl.ocks.org/mbostock/7341714
Multi-line labels are also a little tricky, you might want to check out this wrap function.
I also use ImageView
for icons (in ListView
or settings screen). But I think there is much simpler way to do that.
Use tint
to change the color overlay on your selected icon.
In xml,
android:tint="@color/accent"
android:src="@drawable/ic_event"
works fine since it comes from AppCompat
Can also encode like below.... gathered from https://davidwalsh.name/domdocument-utf8-problem
$profile = '<p>???????????????????????9</p>';
$dom = new DOMDocument();
$dom->loadHTML(mb_convert_encoding($profile, 'HTML-ENTITIES', 'UTF-8'));
echo $dom->saveHTML();
I am surprise, no one here has ans by using simple javascript
and Set
logic to automatically filter the duplicates values, simple example on mongo shellas below:
var allKeys = new Set()
db.collectionName.find().forEach( function (o) {for (key in o ) allKeys.add(key)})
for(let key of allKeys) print(key)
This will print all possible unique keys in the collection name: collectionName.
(Jun-Dec 2016) Most answers here are now out-of-date as: 1) GData APIs are the previous generation of Google APIs, and that's why it was hard for @Josh Brown to find that old GData Docs API documentation. While not all GData APIs have been deprecated, all newer Google APIs do not use the Google Data protocol; and 2) Google released a new Google Sheets API (not GData). In order to use the new API, you need to get the Google APIs Client Library for Python (it's as easy as pip install -U google-api-python-client
[or pip3
for Python 3]) and use the latest Sheets API v4+, which is much more powerful & flexible than older API releases.
Here's one code sample from the official docs to help get you kickstarted. However, here are slightly longer, more "real-world" examples of using the API you can learn from (videos plus blog posts):
The latest Sheets API provides features not available in older releases, namely giving developers programmatic access to a Sheet as if you were using the user interface (create frozen rows, perform cell formatting, resizing rows/columns, adding pivot tables, creating charts, etc.), but NOT as if it was some database that you could perform searches on and get selected rows from. You'd basically have to build a querying layer on top of the API that does this. One alternative is to use the Google Charts Visualization API query language, which does support SQL-like querying. You can also query from within the Sheet itself. Be aware that this functionality existed before the v4 API, and that the security model was updated in Aug 2016. To learn more, check my G+ reshare to a full write-up from a Google Developer Expert.
Also note that the Sheets API is primarily for programmatically accessing spreadsheet operations & functionality as described above, but to perform file-level access such as imports/exports, copy, move, rename, etc., use the Google Drive API instead. Examples of using the Drive API:
(*) - TL;DR: upload plain text file to Drive, import/convert to Google Docs format, then export that Doc as PDF. Post above uses Drive API v2; this follow-up post describes migrating it to Drive API v3, and here's a developer video combining both "poor man's converter" posts.
To learn more about how to use Google APIs with Python in general, check out my blog as well as a variety of Google developer videos (series 1 and series 2) I'm producing.
ps. As far as Google Docs goes, there isn't a REST API available at this time, so the only way to programmatically access a Doc is by using Google Apps Script (which like Node.js is JavaScript outside of the browser, but instead of running on a Node server, these apps run in Google's cloud; also check out my intro video.) With Apps Script, you can build a Docs app or an add-on for Docs (and other things like Sheets & Forms).
UPDATE Jul 2018: The above "ps." is no longer true. The G Suite developer team pre-announced a new Google Docs REST API at Google Cloud NEXT '18. Developers interested in getting into the early access program for the new API should register at https://developers.google.com/docs.
UPDATE Feb 2019: The Docs API launched to preview last July is now available generally to all... read the launch post for more details.
UPDATE Nov 2019: In an effort to bring G Suite and GCP APIs more inline with each other, earlier this year, all G Suite code samples were partially integrated with GCP's newer (lower-level not product) Python client libraries. The way auth is done is similar but (currently) requires a tiny bit more code to manage token storage, meaning rather than our libraries manage storage.json
, you'll store them using pickle
(token.pickle
or whatever name you prefer) instead, or choose your own form of persistent storage. For you readers here, take a look at the updated Python quickstart example.
Use try with resources. this will automatically close the resources.
try (BufferedReader br = new BufferedReader(new FileReader("C:/test.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
}
You must give permission to your app for listening http requests. You can use this command in cmd for this purpose (open cmd Run As Administrator mode)
netsh http add urlacl url=http://+:8000/ user=Everyone
If your app is working other port, for example 9095, this command must be like as below:
netsh http add urlacl url=http://+:9095/ user=Everyone
And re-run your app, it should work. This way working for me.
Just Add AjaxControlToolkit.dll to your Reference folder.
On your Project Solution
Right Click on Reference Folder > Add Reference > browse AjaxControlToolkit.dll .
Then build.
Regards
in ubuntu 14.04 based on your php version : 5.6,7.0,7.1,7.2,7.3
sudo apt-get install php{version}-mcrypt
sudo apt-get install php7.1-mcrypt
sudo phpenmod mcrypt
The value of the certificate comes mostly from the trust of the internet users in the issuer of the certificate. To that end, Verisign is tough to beat. A certificate says to the client that you are who you say you are, and the issuer has verified that to be true.
You can get a free SSL certificate signed, for example, by StartSSL. This is an improvement on self-signed certificates, because your end-users would stop getting warning pop-ups informing them of a suspicious certificate on your end. However, the browser bar is not going to turn green when communicating with your site over https, so this solution is not ideal.
The cheapest SSL certificate that turns the bar green will cost you a few hundred dollars, and you would need to go through a process of proving the identity of your company to the issuer of the certificate by submitting relevant documents.
As it solved the problem, I put it as an answer.
Don't use single and double quotes, especially when you define a raw string with r
in front of it.
The correct call is then
path = r"C:\Apps\CorVu\DATA\Reports\AlliD\Monthly Commission Reports\Output\pdcom1"
or
path = r'C:\Apps\CorVu\DATA\Reports\AlliD\Monthly Commission Reports\Output\pdcom1'
Post.find().sort({updatedAt:1}).exec(function (err, posts){
...
});
The error is here:
hasLetter("a",words[]);
You are passing the first item of words
, instead of the array.
Instead, pass the array to the function:
hasLetter("a",words);
Problem solved!
Here's a breakdown of what the problem was:
I'm guessing in your browser (chrome throws a different error), words[] == words[0]
, so when you call hasLetter("a",words[]);
, you are actually calling hasLetter("a",words[0]);
. So, in essence, you are passing the first item of words to your function, not the array as a whole.
Of course, because words
is just an empty array, words[0]
is undefined
. Therefore, your function call is actually:
hasLetter("a", undefined);
which means that, when you try to access d[ascii]
, you are actually trying to access undefined[0]
, hence the error.
I tried using <%# %>
with no success. Then I changed Page.Header.DataBind();
in my code behind to this.Header.DataBind();
and it worked fine.
Consider this function. It accepts both position number, and strings arguments:
function get_string_between($string, $start = '', $end = ''){
if (empty($start)) {
$start = 0;
}elseif (!is_numeric($start)) {
$start = strpos($string, $start) + strlen($start);
}
if (empty($end)) {
$end = strlen($string);
}elseif (!is_numeric($end)) {
$end = strpos($string, $end);
}
return substr($string, $start, ($end - $start));
}
Results:
echo get_string_between($string); // result = this is my [tag]dog[/tag]
echo get_string_between($string, 0); // result = this is my [tag]dog[/tag]
echo get_string_between($string, ''); // result = this is my [tag]dog[/tag]
echo get_string_between($string, '[tag]'); // result = dog[/tag]
echo get_string_between($string, 0, '[/tag]'); // result = this is my [tag]dog
echo get_string_between($string, '', '[/tag]'); // result = this is my [tag]dog
echo get_string_between($string, '[tag]', '[/tag]'); // result = dog
echo get_string_between($string, '[tag]', strlen($string)); // dog[/tag]
Improve to @inno answer
delimiter //
DROP PROCEDURE IF EXISTS get_product;
CREATE PROCEDURE get_product()
BEGIN
DECLARE i VARCHAR(100);
DECLARE cur1 CURSOR FOR SELECT DISTINCT table_name FROM information_schema.columns WHERE COLUMN_NAME IN ('Product');
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO i;
SELECT i; -- printing table name
SET @s = CONCAT('select * from ', i, ' where Product like %XYZ%');
PREPARE stmt1 FROM @s;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END LOOP read_loop;
CLOSE cur1;
END//
delimiter ;
call get_product();
First style is better. Though you should use better variable name
It is naming convention used when passing callbacks in situations that require serial execution of actions, e.g. scan directory -> read file data -> do something with data. This is in preference to deeply nesting the callbacks. The first three sections of the following article on Tim Caswell's HowToNode blog give a good overview of this:
http://howtonode.org/control-flow
Also see the Sequential Actions section of the second part of that posting:
There is no built-in method that allows what you intend to do.
You have to add a method to your repository, like this:
public function getWhatYouWant()
{
$qb = $this->createQueryBuilder('u');
$qb->where('u.id != :identifier')
->setParameter('identifier', 1);
return $qb->getQuery()
->getResult();
}
Hope this helps.
Using SSMS, I made sure the user had connect permissions on both the database and ReportServer.
On the specific database being queried, under properties, I mapped their credentials and enabled datareader and public permissions. Also, as others have stated-I made sure there were no denyread/denywrite boxes selected.
I did not want to enable db ownership when for their reports since they only needed to have select permissions.
Try this:
@keyframes animationName {
0% { opacity:0; }
50% { opacity:1; }
100% { opacity:0; }
}
@-o-keyframes animationName{
0% { opacity:0; }
50% { opacity:1; }
100% { opacity:0; }
}
@-moz-keyframes animationName{
0% { opacity:0; }
50% { opacity:1; }
100% { opacity:0; }
}
@-webkit-keyframes animationName{
0% { opacity:0; }
50% { opacity:1; }
100% { opacity:0; }
}
.elementToFadeInAndOut {
-webkit-animation: animationName 5s infinite;
-moz-animation: animationName 5s infinite;
-o-animation: animationName 5s infinite;
animation: animationName 5s infinite;
}
I used the following to upgrade git on mac.
hansi$ brew install git
hansi$ git --version
git version 2.19.0
hansi$ brew install git
Warning: git 2.25.1 is already installed, it's just not linked
You can use `brew link git` to link this version.
hansi$ brew link git
Linking /usr/local/Cellar/git/2.25.1...
Error: Could not symlink bin/git
Target /usr/local/bin/git
already exists. You may want to remove it:
rm '/usr/local/bin/git'
To force the link and overwrite all conflicting files:
brew link --overwrite git
To list all files that would be deleted:
brew link --overwrite --dry-run git
hansi$ brew link --overwrite git
Linking /usr/local/Cellar/git/2.25.1... 205 symlinks created
hansi$ git --version
git version 2.25.1
If you using ajax to load modal's body such way and want to be able to reload it's content
<a data-toggle="modal" data-target="#myModal" href="./add">Add</a>
<a data-toggle="modal" data-target="#myModal" href="./edit/id">Modify</a>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<!-- Content will be loaded here -->
</div>
</div>
</div>
use
<script>
$(function() {
$('.modal').on('hidden.bs.modal', function(){
$(this).removeData('bs.modal');
});
});
</script>
If you are working with Android's MediaStore database, here is how to store an image and then display it after it is saved.
on button click write this
Intent in = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
in.putExtra("crop", "true");
in.putExtra("outputX", 100);
in.putExtra("outputY", 100);
in.putExtra("scale", true);
in.putExtra("return-data", true);
startActivityForResult(in, 1);
then do this in your activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Bitmap bmp = (Bitmap) data.getExtras().get("data");
img.setImageBitmap(bmp);
btnadd.requestFocus();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);
byte[] bytarray = Base64.decode(encodedImageString, Base64.DEFAULT);
Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
bytarray.length);
}
}
Add new SSH keys as described in this article on GitHub.
If Git still asks you for username & password, try changing https://github.com/
to [email protected]:
in remote URL:
$ git config remote.origin.url
https://github.com/dir/repo.git
$ git config remote.origin.url "[email protected]:dir/repo.git"
No. Java doesn't support default parameters like C++. You need to define a different method:
public int doSomething()
{
return doSomething(value1, value2);
}
Check if there is already a Node server running on your machine and then close it.
This feature has been added in dplyr v0.3. You can now pass a named character vector to the by
argument in left_join
(and other joining functions) to specify which columns to join on in each data frame. With the example given in the original question, the code would be:
left_join(test_data, kantrowitz, by = c("first_name" = "name"))
If you are using .NET Core or System.Memory for .NET Framework, there is a very efficient marshaling mechanism available via Span<T> and Memory<T> that can effectively reinterpret string memory as a span of bytes. Once you have a span of bytes you are free to marshal back to another type, or copy the span to an array for serialization.
To summarize what others have said:
public static class MarshalExtensions
{
public static ReadOnlySpan<byte> AsBytes(this string value) => MemoryMarshal.AsBytes(value.AsSpan());
public static string AsString(this ReadOnlySpan<byte> value) => new string(MemoryMarshal.Cast<byte, char>(value));
}
static void Main(string[] args)
{
string str1 = "??,??";
ReadOnlySpan<byte> span = str1.AsBytes();
string str2 = span.AsString();
byte[] bytes = span.ToArray();
Debug.Assert(bytes.Length > 0);
Debug.Assert(str1 == str2);
}
In C++ this is roughly equivalent to reinterpret_cast, and C this is roughly equivalent to a cast to the system's word type (char).
In recent versions of the .NET Core Runtime (CoreCLR), operations on spans effectively invoke compiler intrinsics and various optimizations that can sometimes eliminate bounds checking, leading to exceptional performance while preserving memory safety, assuming that your memory was allocated by the CLR and the spans are not derived from pointers from an unmanaged memory allocator.
This uses a mechanism supported by the CLR that returns ReadOnlySpan<char> from a string; Additionally, this span does not necessarily encompass the complete internal string layout. ReadOnlySpan<T> implies that you must create a copy if you need to perform mutation, as strings are immutable.
For AngularJs you have to use "angular-datatables.min.js" file for datatable settings. You will get this from http://l-lin.github.io/angular-datatables/#/welcome.
After that you can write code like below,
<script>
var app = angular.module('AngularWayApp', ['datatables']);
</script>
<div ng-app="AngularWayApp" ng-controller="AngularWayCtrl">
<table id="example" datatable="ng" class="table">
<thead>
<tr>
<th><b>UserID</b></th>
<th><b>Firstname</b></th>
<th><b>Lastname</b></th>
<th><b>Email</b></th>
<th><b>Actions</b></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users" ng-click="testingClick(user)">
<td>
{{user.UserId}}
</td>
<td>
{{user.FirstName}}
</td>
<td>
{{user.Lastname}}
</td>
<td>
{{user.Email}}
</td>
<td>
<span ng-click="editUser(user)" style="color:blue;cursor: pointer; font-weight:500; font-size:15px" class="btnAdd" data-toggle="modal" data-target="#myModal">Edit</span> |
<span ng-click="deleteUser(user)" style="color:red; cursor: pointer; font-weight:500; font-size:15px" class="btnRed">Delete</span>
</td>
</tr>
</tbody>
</table>
</div>
Use following syntax to create new table from old table in SQL server 2008
Select * into new_table from old_table
first get the ObjectID function from the mongodb ObjectId = require(mongodb).ObjectID;
then you can call the _id with the delete function
"_id" : ObjectId("4d5192665777000000005490")
What you could do is something like this (pseudocode):
<container table>
<tr>
<td>
<"300px" table>
<td>
<fixed layout table>
Basically, split up the table into two tables and have it contained by another table.
Why not use an Excel formula to determine the rows? For instance, if you are looking for how many cells contain data in Column A use this:
=COUNTIFS(A:A,"<>")
You can replace <> with any value to get how many rows have that value in it.
=COUNTIFS(A:A,"2008")
This can be used for finding filled cells in a row too.
from datetime import datetime
datetime.strptime(date_string, "%Y-%m-%d")
..this raises a ValueError
if it receives an incompatible format.
..if you're dealing with dates and times a lot (in the sense of datetime objects, as opposed to unix timestamp floats), it's a good idea to look into the pytz module, and for storage/db, store everything in UTC.
According to the Oracle PLSQL language definition, a character literal can contain "any printable character in the character set". https://docs.oracle.com/cd/A97630_01/appdev.920/a96624/02_funds.htm#2876
@Robert Love's answer exhibits a best practice for readable code, but you can also just type in the linefeed character into the code. Here is an example from a Linux terminal using sqlplus
:
SQL> set serveroutput on
SQL> begin
2 dbms_output.put_line( 'hello' || chr(10) || 'world' );
3 end;
4 /
hello
world
PL/SQL procedure successfully completed.
SQL> begin
2 dbms_output.put_line( 'hello
3 world' );
4 end;
5 /
hello
world
PL/SQL procedure successfully completed.
Instead of the CHR( NN ) function you can also use Unicode literal escape sequences like u'\0085'
which I prefer because, well you know we are not living in 1970 anymore. See the equivalent example below:
SQL> begin
2 dbms_output.put_line( 'hello' || u'\000A' || 'world' );
3 end;
4 /
hello
world
PL/SQL procedure successfully completed.
For fair coverage I guess it is worth noting that different operating systems use different characters/character sequences for end of line handling. You've got to have a think about the context in which your program output is going to be viewed or printed, in order to determine whether you are using the right technique.
u'\000D\000A'
u'\000A'
u'\0085'
'<BR>'
'<br />'
Thank Mathias Lin, tested and it works!
In addition, sample implementation of Mathias's method in activity can be as follows.
public class DirectionMapActivity extends MapActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.directionmap);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
String locationProvider = LocationManager.NETWORK_PROVIDER;
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");//from
urlString.append( Double.toString(lastKnownLocation.getLatitude() ));
urlString.append(",");
urlString.append( Double.toString(lastKnownLocation.getLongitude() ));
urlString.append("&daddr=");//to
urlString.append( Double.toString((double)dest[0]/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)dest[1]/1.0E6 ));
urlString.append("&ie=UTF8&0&om=0&output=kml");
try{
// setup the url
URL url = new URL(urlString.toString());
// create the factory
SAXParserFactory factory = SAXParserFactory.newInstance();
// create a parser
SAXParser parser = factory.newSAXParser();
// create the reader (scanner)
XMLReader xmlreader = parser.getXMLReader();
// instantiate our handler
NavigationSaxHandler navSaxHandler = new NavigationSaxHandler();
// assign our handler
xmlreader.setContentHandler(navSaxHandler);
// get our data via the url class
InputSource is = new InputSource(url.openStream());
// perform the synchronous parse
xmlreader.parse(is);
// get the results - should be a fully populated RSSFeed instance, or null on error
NavigationDataSet ds = navSaxHandler.getParsedData();
// draw path
drawPath(ds, Color.parseColor("#add331"), mapView );
// find boundary by using itemized overlay
GeoPoint destPoint = new GeoPoint(dest[0],dest[1]);
GeoPoint currentPoint = new GeoPoint( new Double(lastKnownLocation.getLatitude()*1E6).intValue()
,new Double(lastKnownLocation.getLongitude()*1E6).intValue() );
Drawable dot = this.getResources().getDrawable(R.drawable.pixel);
MapItemizedOverlay bgItemizedOverlay = new MapItemizedOverlay(dot,this);
OverlayItem currentPixel = new OverlayItem(destPoint, null, null );
OverlayItem destPixel = new OverlayItem(currentPoint, null, null );
bgItemizedOverlay.addOverlay(currentPixel);
bgItemizedOverlay.addOverlay(destPixel);
// center and zoom in the map
MapController mc = mapView.getController();
mc.zoomToSpan(bgItemizedOverlay.getLatSpanE6()*2,bgItemizedOverlay.getLonSpanE6()*2);
mc.animateTo(new GeoPoint(
(currentPoint.getLatitudeE6() + destPoint.getLatitudeE6()) / 2
, (currentPoint.getLongitudeE6() + destPoint.getLongitudeE6()) / 2));
} catch(Exception e) {
Log.d("DirectionMap","Exception parsing kml.");
}
}
// and the rest of the methods in activity, e.g. drawPath() etc...
MapItemizedOverlay.java
public class MapItemizedOverlay extends ItemizedOverlay{
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public MapItemizedOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
@Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
@Override
public int size() {
return mOverlays.size();
}
}
if you have a checkbox and you would like to fetch it's value ie true / false in any java file--
Use--
Context mContext;
boolean checkFlag;
checkFlag=PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(KEY,DEFAULT_VALUE);`
Easy code, if 'indexOf' returns '-1' it means that element is not inside the array then the condition '=== -1' retrieve true/false.
The '&&' operator means 'and', so if the first condition is true we push it to the array.
array.indexOf(newItem) === -1 && array.push(newItem);
Getting rJava to work depends heavily on your computers configuration:
If you use 64bit version make sure, that you do not set JAVA_HOME as a enviorment variable. If this variable is set, rJava will not work for whatever reason (at least for me). You can check easily within R is JAVA_HOME is set with
Sys.getenv("JAVA_HOME")
If you need to have JAVA_HOME set (e.g. you need it for maven or something else), you could deactivate it within your R-session with the following code before loading rJava:
if (Sys.getenv("JAVA_HOME")!="")
Sys.setenv(JAVA_HOME="")
library(rJava)
This should do the trick in most cases. Furthermore this will fix issue Using the rJava package on Win7 64 bit with R, too. I borrowed the idea of unsetting the enviorment variable from R: rJava package install failing.
I am the creator of PowerMock so obviously I must recommend that! :-)
PowerMock extends both EasyMock and Mockito with the ability to mock static methods, final and even private methods. The EasyMock support is complete, but the Mockito plugin needs some more work. We are planning to add JMock support as well.
PowerMock is not intended to replace other frameworks, rather it can be used in the tricky situations when other frameworks does't allow mocking. PowerMock also contains other useful features such as suppressing static initializers and constructors.
Use the matplotlib savefig
function with the keyword argument transparent=True
to save the image as a png file.
In [30]: x = np.linspace(0,6,31)
In [31]: y = np.exp(-0.5*x) * np.sin(x)
In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]
In [33]: savefig('demo.png', transparent=True)
Result:
Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display
command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.
Just for the record I would specify the following:
/^[xX]?[0-9a-fA-F]{6}$/
Which differs in that it checks that it has to contain the six valid characters and on lowercase or uppercase x in case we have one.
Thanks to @HBP for paving the way here!
I found this to add a little flexibility to the solution.
The RegEx has been updated to accommodate times before noon.
This solution allows you to pass any string to it. As long as a valid time (in this format 18:00 || 18:00:00 || 3:00 || 3:00:00) is somewhere in that string, you're good to go.
Note: you can use just the militaryToTweleveHourConverter
or take the guts out of the parseTime
variable. However, I'm formatting a date from a database with date-fns
then passing that formatted date to the converter.
Totally works. Hope this helps.
import dateFns from 'date-fns';
//* +---------------------------+
//* Format ex. Sat 1/1/18 1:00pm
//* +---------------------------+
const formatMonthDayYearTime = date =>
militaryToTweleveHourConverter(
dateFns.format(new Date(date), 'ddd M/DD/YY H:mm')
);
//* +-------------------------------+
//* Convert MILITARY TIME to 12 hour
//* +-------------------------------+
const militaryToTweleveHourConverter = time => {
const getTime = time.split(' ');
const parseTime = getTime.map(res => {
// Check for correct time format and split into components or return non-time units unaltered
let timeUnit = res
.toString()
.match(/^([\d]|[0-1]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [res];
console.log('timeUnit', timeUnit);
// If the time format is matched, it will break the components into an array
// ie. ["19:00", "19", ":", "00", undefined]
if (timeUnit.length > 1) {
// Remove full string match value
timeUnit = timeUnit.slice(1);
// Set am/pm and assign it to the last index in the array
timeUnit[5] = timeUnit[0] < 12 ? 'am' : 'pm';
// Adjust hours by subtracting 12 from anything greater than 12 and replace the value in the hours index
timeUnit[0] = timeUnit[0] % 12 || 12;
}
// return adjusted time or original string
return timeUnit.join('');
});
// Re-assemble the array pieces into a string
return parseTime.join(' ');
};
console.log(formatMonthDayYearTime('Sat 9/17/18 18:30'));
// console log returns the following
// Mon 9/17/18 6:30pm
console.log(militaryToTweleveHourConverter('18:30'));
// console log returns the following
// 6:30pm
console.log(militaryToTweleveHourConverter('18:30:09'));
// console log returns the following
// 6:30:09pm
console.log(militaryToTweleveHourConverter('8:30:09'));
// console log returns the following
// 8:30:09am
The postscript()
device allows creation of EPS, but only if you change some of the default values. Read ?postscript
for the details.
Here is an example:
postscript("foo.eps", horizontal = FALSE, onefile = FALSE, paper = "special")
plot(1:10)
dev.off()
I got the same problem, I know I wasn't running any other instances, and I could see it with adb devices
. I just did a restart of eclipse and it worked.
On Ubuntu 16.04
Here's how I fixed this issue: Refer Docker Compose documentation
sudo curl -L https://github.com/docker/compose/releases/download/1.21.0/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
After you do the curl command , it'll put docker-compose into the
/usr/local/bin
which is not on the PATH
.
To fix it, create a symbolic link:
sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
And now if you do:
docker-compose --version
You'll see that docker-compose is now on the PATH
After struggling a lot, I finally found a solution, here we go -
Download the file jtds-1.3.1.jar
and ntlmauth.dll
and save it in Program File -> Java -> JDK -> jre -> bin.
Then use the following code -
String pPSSDBDriverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Class.forName(pPSSDBDriverName);
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://<ur_server:port>;UseNTLMv2=true;Domain=AD;Trusted_Connection=yes");
stmt = conn.createStatement();
String sql = " DELETE FROM <data> where <condition>;
stmt.executeUpdate(sql);
From API level 17 and above, you can call: View.generateViewId()
Then use View.setId(int).
If your app is targeted lower than API level 17, use ViewCompat.generateViewId()
Simply run this command for installing composer globally
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer
Paths specified with a .
are relative to the current working directory, not relative to the script file. So the file might be found if you run node app.js
but not if you run node folder/app.js
. The only exception to this is require('./file')
and that is only possible because require
exists per-module and thus knows what module it is being called from.
To make a path relative to the script, you must use the __dirname
variable.
var path = require('path');
path.join(__dirname, 'path/to/file')
or potentially
path.join(__dirname, 'path', 'to', 'file')
Remove mb4 from charset and collation from config/database.php, then it will execute successfully.
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
Go to Eclipse Menu --> Window ==> Show View ==> Variables
This should bring back your variables window in eclipse
I hit an issue where following an Update, SVN showed a folder as being conflicted. Strangely, this was only visible through the command line - TortoiseSVN thought it was all fine.
#>svn st
! my_dir
! my_dir\sub_dir
svn cleanup
, svn revert
, svn update
and svn resolve
were all unsuccessful at fixing this.
I eventually solved the problem as follows:
Following that, everything was fine.
Note I didn't have any local changes, so I don't know if you'd be at risk if you did. I didn't use the delete / update method suggested by others - I got into this state by trying that on the my_dir/sub_dir/sub_sub_dir directory (which started with the same symptoms) - so I didn't want to risk making things worse again!
Not quite on-topic, but maybe helpful if someone comes across this post as I did.
I had this error today trying to run Django tests because I was using the shorthand from .models import *
syntax in one of my files. The issue was that I had a file structure like so:
apps/
myapp/
models/
__init__.py
foo.py
bar.py
and in models/__init__.py
I was importing my models using the shorthand syntax:
from .foo import *
from .bar import *
In my application I was importing models like so:
from myapp.models import Foo, Bar
This caused the Django model doesn't declare an explicit app_label
when running ./manage.py test
.
To fix the problem, I had to explicitly import from the full path in models/__init__.py
:
from myapp.models.foo import *
from myapp.models.bar import *
That took care of the error.
H/t https://medium.com/@michal.bock/fix-weird-exceptions-when-running-django-tests-f58def71b59a
There is simpler method.
Instead of using setTimeout or working with socket directly,
We can use 'timeout' in the 'options' in client uses
Below is code of both server and client, in 3 parts.
Module and options part:
'use strict';
// Source: https://github.com/nodejs/node/blob/master/test/parallel/test-http-client-timeout-option.js
const assert = require('assert');
const http = require('http');
const options = {
host: '127.0.0.1', // server uses this
port: 3000, // server uses this
method: 'GET', // client uses this
path: '/', // client uses this
timeout: 2000 // client uses this, timesout in 2 seconds if server does not respond in time
};
Server part:
function startServer() {
console.log('startServer');
const server = http.createServer();
server
.listen(options.port, options.host, function () {
console.log('Server listening on http://' + options.host + ':' + options.port);
console.log('');
// server is listening now
// so, let's start the client
startClient();
});
}
Client part:
function startClient() {
console.log('startClient');
const req = http.request(options);
req.on('close', function () {
console.log("got closed!");
});
req.on('timeout', function () {
console.log("timeout! " + (options.timeout / 1000) + " seconds expired");
// Source: https://github.com/nodejs/node/blob/master/test/parallel/test-http-client-timeout-option.js#L27
req.destroy();
});
req.on('error', function (e) {
// Source: https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js#L248
if (req.connection.destroyed) {
console.log("got error, req.destroy() was called!");
return;
}
console.log("got error! ", e);
});
// Finish sending the request
req.end();
}
startServer();
If you put all the above 3 parts in one file, "a.js", and then run:
node a.js
then, output will be:
startServer
Server listening on http://127.0.0.1:3000
startClient
timeout! 2 seconds expired
got closed!
got error, req.destroy() was called!
Hope that helps.
Even though there is a bool (short for boolean) data type in C++. But in C++, any nonzero value is a true value including negative numbers. A 0 (zero) is treated as false. Where as in JAVA there is a separate data type boolean for true and false.
THERE'S an even simpler answer
import java.io.BufferedReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
String myBeautifulScanf = new Scanner(System.in).nextLine();
System.out.println( myBeautifulScanf );
}
}
A simpler version of your code would be:
dict(zip(names, d.values()))
If you want to keep the same structure, you can change it to:
vlst = list(d.values())
{names[i]: vlst[i] for i in range(len(names))}
(You can just as easily put list(d.values())
inside the comprehension instead of vlst
; it's just wasteful to do so since it would be re-generating the list every time).
I recently had to create a button that would download a json file of all values of a large form. I needed this to work with IE/Edge/Chrome. This is what I did:
function download(text, name, type)
{
var file = new Blob([text], {type: type});
var isIE = /*@cc_on!@*/false || !!document.documentMode;
if (isIE)
{
window.navigator.msSaveOrOpenBlob(file, name);
}
else
{
var a = document.createElement('a');
a.href = URL.createObjectURL(file);
a.download = name;
a.click();
}
}
download(jsonData, 'Form_Data_.json','application/json');
There was one issue with filename and extension in edge but at the time of writing this seemed to be a bug with Edge that is due to be fixed.
Hope this helps someone
Local temporary tables: if you create local temporary tables and then open another connection and try the query , you will get the following error.
the temporary tables are only accessible within the session that created them.
Global temporary tables: Sometimes, you may want to create a temporary table that is accessible other connections. In this case, you can use global temporary tables.
Global temporary tables are only destroyed when all the sessions referring to it are closed.
Your submit button doesn't have a name. Add name="submit" to your submit button.
If you view source on the form in the browser, you'll see how it submits to self - the form's action attribute will contain the name of the current script - therefore when the form submits, it submits to itself. Edit for vanity sake!
As it is being mentioned in pir's comment - the .apply(lambda el: scale.fit_transform(el))
method will produce the following warning:
DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
Converting your columns to numpy arrays should do the job (I prefer StandardScaler):
from sklearn.preprocessing import StandardScaler
scale = StandardScaler()
dfTest[['A','B','C']] = scale.fit_transform(dfTest[['A','B','C']].as_matrix())
-- Edit Nov 2018 (Tested for pandas 0.23.4)--
As Rob Murray mentions in the comments, in the current (v0.23.4) version of pandas .as_matrix()
returns FutureWarning
. Therefore, it should be replaced by .values
:
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit_transform(dfTest[['A','B']].values)
-- Edit May 2019 (Tested for pandas 0.24.2)--
As joelostblom mentions in the comments, "Since 0.24.0
, it is recommended to use .to_numpy()
instead of .values
."
Updated example:
import pandas as pd
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
dfTest = pd.DataFrame({
'A':[14.00,90.20,90.95,96.27,91.21],
'B':[103.02,107.26,110.35,114.23,114.68],
'C':['big','small','big','small','small']
})
dfTest[['A', 'B']] = scaler.fit_transform(dfTest[['A','B']].to_numpy())
dfTest
A B C
0 -1.995290 -1.571117 big
1 0.436356 -0.603995 small
2 0.460289 0.100818 big
3 0.630058 0.985826 small
4 0.468586 1.088469 small
If it is an application on the Market, then on app start-up, fire an Intent to open up the Market app hopefully which will cause it to check for updates.
Otherwise implementing and update checker is fairly easy. Here is my code (roughly) for it:
String response = SendNetworkUpdateAppRequest(); // Your code to do the network request
// should send the current version
// to server
if(response.equals("YES")) // Start Intent to download the app user has to manually install it by clicking on the notification
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("URL TO LATEST APK")));
Of course you should rewrite this to do the request on a background thread but you get the idea.
If you like something a little but more complex but allows your app to automatically apply the update see here.
There are two scenarios when this exception could occur. One is mentioned by nandeesh. Other scenario is mentioned here: http://blackriver.to/2012/08/android-annoying-exception-unable-to-add-window-is-your-activity-running/
Make sure you handle both of them
I've faced this issue and the solution was making sure that all the data from the child field are matching the parent field
for example, you want to add foreign key inside (attendance) table to the column (employeeName)
where the parent is (employees) table, (employeeName) column
all the data in attendance.employeeName must be matching employee.employeeName
Go to Menu Tool -> SQL Output, Run the PL/SQL statement, the output will show on SQL Output panel.
You can use the directive v-el
to save an element and then use it later.
<div v-el:my-div></div>
<!-- this.$els.myDiv --->
Edit: This is deprecated in Vue 2, see ??? answer
In the hope that it will be useful to some, you may want to check out my go at it:
While there are a couple of good and well-documented IMAP libraries for .NET available, none of them are free for personal, let alone commercial use...and I was just not all that satisfied with the mostly abandoned free alternatives I found.
S22.Imap supports IMAP IDLE notifications as well as SSL and partial message fetching. I have put some effort into producing documentation and keeping it up to date, because with the projects I found, documentation was often sparse or non-existent.
Feel free to give it a try and let me know if you run into any issues!
You can view any existing index by using the below CURL. Please replace the index-name with your actual name before running and it will run as is.
View the index content
curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name?pretty
And the output will include an index(see settings in output) and its mappings too and it will look like below output -
{
"index_name": {
"aliases": {},
"mappings": {
"collection_name": {
"properties": {
"test_field": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"settings": {
"index": {
"creation_date": "1527377274366",
"number_of_shards": "5",
"number_of_replicas": "1",
"uuid": "6QfKqbbVQ0Gbsqkq7WZJ2g",
"version": {
"created": "6020299"
},
"provided_name": "index_name"
}
}
}
}
View ALL the data under this index
curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name/_search?pretty
an API(Application Programming Interface) is a set of defined functions and methods for interfacing with the underlying operating system or another program or service running on the computer.
It is usually used by establishing a reference to a library in your software or importing a function from a dll.
It is used in one form or another in almost all software, being explicitly called in your program or implicitly called by the compiler.
This has been really helpful. Here is my implementation for any given table:
def sql_replace(self, tableobject, dictargs):
#missing check of table object is valid
primarykeys = [key.name for key in inspect(tableobject).primary_key]
filterargs = []
for primkeys in primarykeys:
if dictargs[primkeys] is not None:
filterargs.append(getattr(db.RT_eqmtvsdata, primkeys) == dictargs[primkeys])
else:
return
query = select([db.RT_eqmtvsdata]).where(and_(*filterargs))
if self.r_ExecuteAndErrorChk2(query)[primarykeys[0]] is not None:
# update
filter = and_(*filterargs)
query = tableobject.__table__.update().values(dictargs).where(filter)
return self.w_ExecuteAndErrorChk2(query)
else:
query = tableobject.__table__.insert().values(dictargs)
return self.w_ExecuteAndErrorChk2(query)
# example usage
inrow = {'eqmtvs_id': eqmtvsid, 'datetime': dtime, 'param_id': paramid}
self.sql_replace(tableobject=db.RT_eqmtvsdata, dictargs=inrow)
If the output of MAX(CreationDate) is not wanted - like in the example of the original question - the only answer is the second statement of Prashant Gupta's answer:
SELECT [Category] FROM [MonitoringJob]
GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC
Explanation: you can't use the ORDER BY clause in an inline function, so the statement in the answer of Prutswonder is not useable in this case, you can't put an outer select around it and discard the MAX(CreationDate) part.
If you cancel and see that run
sp_who2 'active'
(Activity Monitor won't be available on old sql server 2000 FYI )
Spot the SPID you wish to kill e.g. 81
Kill 81
Run the sp_who2 'active'
again and you will probably notice it is sleeping ... rolling back
To get the STATUS run again the KILL
Kill 81
Then you will get a message like this
SPID 81: transaction rollback in progress. Estimated rollback completion: 63%. Estimated time remaining: 992 seconds.
This is what I did:
You could just use window.location.hash
to grab the id.
var id = window.location.hash;
I don't think you will need that much code to achieve this.
You can use assign
(doc) to change the value of perf.a1:
> assign(paste("perf.a", "1", sep=""),5)
> perf.a1
[1] 5
To start things off, the error QApplication: no such file or directory
means your compiler was not able to find this header. It is not related to the linking process as you mentioned in the question.
The -I
flag (uppercase i) is used to specify the include (headers) directory (which is what you need to do), while the -L
flag is used to specify the libraries directory. The -l
flag (lowercase L) is used to link your application with a specified library.
But you can use Qt to your advantage: Qt has a build system named qmake which makes things easier. For instance, when I want to compile main.cpp I create a main.pro file. For educational purposes, let's say this source code is a simple project that uses only QApplication
and QDeclarativeView
. An appropriate .pro file would be:
TEMPLATE += app
QT += gui declarative
SOURCES += main.cpp
Then, execute the qmake
inside that directory to create the Makefile that will be used to compile your application, and finally execute make
to get the job done.
On my system this make
outputs:
g++ -c -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_DECLARATIVE_LIB -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/opt/qt_47x/mkspecs/linux-g++ -I. -I/opt/qt_47x/include/QtCore -I/opt/qt_47x/include/QtGui -I/opt/qt_47x/include/QtDeclarative -I/opt/qt_47x/include -I/usr/X11R6/include -I. -o main.o main.cpp
g++ -Wl,-O1 -Wl,-rpath,/opt/qt_47x/lib -o main main.o -L/opt/qt_47x/lib -L/usr/X11R6/lib -lQtDeclarative -L/opt/qt_47x/lib -lQtScript -lQtSvg -L/usr/X11R6/lib -lQtSql -lQtXmlPatterns -lQtNetwork -lQtGui -lQtCore -lpthread
Note: I installed Qt in another directory --> /opt/qt_47x
Edit: Qt 5.x and later
Add QT += widgets
to the .pro file and solve this problem.
git rm --cached . -r
will "un-add" everything you've added from your current directory recursively
If you are on php 5.4+, it is cleaner to use session_status():
if (session_status() == PHP_SESSION_ACTIVE) {
echo 'Session is active';
}
PHP_SESSION_DISABLED
if sessions are disabled.PHP_SESSION_NONE
if sessions are enabled, but none exists.PHP_SESSION_ACTIVE
if sessions are enabled, and one exists.If changing the name did not work run setup with \layout
argument.
This could better be done as
x="\n"
echo -ne $x
-e option will interpret backslahes for the escape sequence
-n option will remove the trailing newline in the output
PS: the command echo has an effect of always including a trailing newline in the output so -n is required to turn that thing off (and make it less confusing)
According to Listening For and Broadcasting Global Messages, and Setting Alarms in Common Tasks and How to Do Them in Android:
If the receiving class is not registered using in its manifest, you can dynamically instantiate and register a receiver by calling Context.registerReceiver().
Take a look at registerReceiver (BroadcastReceiver receiver, IntentFilter filter) for more info.
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
storageClass
-line from the PersistentVolumeClaimAt creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
if type(varA) == str or type(varB) == str:
print 'string involved'
from EDX - online course MITx: 6.00.1x Introduction to Computer Science and Programming Using Python
From Zvon.org XSLT Reference:
XPath function: boolean contains (string, string)
Hope this helps.
Integer[] arrayInteger = {1,2,3,4,3,2,4,6,7,8,9,9,10};
Set set = new HashSet();
for(Integer i:arrayInteger)
set.add(i);
System.out.println(set);
No, but it's been requested many times.
Enclose Link component inside BrowserRouter component
export default () => (
<div>
<h1>
<BrowserRouter>
<Link to="/">Redux example</Link>
</BrowserRouter>
</h1>
</div>
)
It seems you can just display both dfs using a comma in between in display. I noticed this on some notebooks on github. This code is from Jake VanderPlas's notebook.
class display(object):
"""Display HTML representation of multiple objects"""
template = """<div style="float: left; padding: 10px;">
<p style='font-family:"Courier New", Courier, monospace'>{0}</p>{1}
</div>"""
def __init__(self, *args):
self.args = args
def _repr_html_(self):
return '\n'.join(self.template.format(a, eval(a)._repr_html_())
for a in self.args)
def __repr__(self):
return '\n\n'.join(a + '\n' + repr(eval(a))
for a in self.args)
display('df', "df2")
If anyone came to this question looking for ways to add multiple parameters at the same time (my case), you can use .params
with a MultivalueMap instead of adding each .param
:
LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>()
requestParams.add("id", "1");
requestParams.add("name", "john");
requestParams.add("age", "30");
mockMvc.perform(get("my/endpoint").params(requestParams)).andExpect(status().isOk())
A simple method that only uses RGB is
cR=R1-R2
cG=G1-G2
cB=B1-B2
uR=R1+R2
distance=cR*cR*(2+uR/256) + cG*cG*4 + cB*cB*(2+(255-uR)/256)
I've used this one for a while now, and it works well enough for most purposes.
it is enough to modify something in your text editor and reload localhost. all your connection will be lost nd you have opsibility to ng serve the new project in the console.
left = None
left is None #evaluates to True
You need to check that Session["emp_num"]
is not null
before trying to convert it to a string otherwise you will get a null reference exception.
I'd go with your first example - but you could make it slightly more "elegant".
There are a couple of ways, but the ones that springs to mind are:
if (Session["emp_num"] is string)
{
}
or
if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
}
This will return null if the variable doesn't exist or isn't a string.
I am using WebAPI 3 and was facing the same issue. The issue has resolve as @Rytis added his solution. And I think in WebAPI 3, we don't need to define method RegisterWebApi
.
My change was only in web.config file and is working.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST" />
</customHeaders>
</httpProtocol>
Thanks for you solution @Rytis!
Simply specify the desired framerate in "-r " option before the input file:
ffmpeg -y -r 24 -i seeing_noaudio.mp4 seeing.mp4
Options affect the next file AFTER them. "-r" before an input file forces to reinterpret its header as if the video was encoded at the given framerate. No recompression is necessary. There was a small utility avifrate.exe to patch avi file headers directly to change the framerate. ffmpeg command above essentially does the same, but has to copy the entire file.
This should be what you need.
Javascript:
$(window).scroll(function() {
var hT = $('#circle').offset().top,
hH = $('#circle').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
console.log((hT - wH), wS);
if (wS > (hT + hH - wH)) {
$('.count').each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 900,
easing: 'swing',
step: function(now) {
$(this).text(Math.ceil(now));
}
});
}); {
$('.count').removeClass('count').addClass('counted');
};
}
});
CSS:
#circle
{
width: 100px;
height: 100px;
background: blue;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
float:left;
margin:5px;
}
.count, .counted
{
line-height: 100px;
color:white;
margin-left:30px;
font-size:25px;
}
#talkbubble {
width: 120px;
height: 80px;
background: green;
position: relative;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
float:left;
margin:20px;
}
#talkbubble:before {
content:"";
position: absolute;
right: 100%;
top: 15px;
width: 0;
height: 0;
border-top: 13px solid transparent;
border-right: 20px solid green;
border-bottom: 13px solid transparent;
}
HTML:
<div id="talkbubble"><span class="count">145</span></div>
<div style="clear:both"></div>
<div id="talkbubble"><span class="count">145</span></div>
<div style="clear:both"></div>
<div id="circle"><span class="count">1234</span></div>
Check this bootply: http://www.bootply.com/atin_agarwal2/cJBywxX5Qp
This is a JQuery code for Preventing Submit
$('form').submit(function (e) {
if (radioButtonValue !== "0") {
e.preventDefault();
}
});
May be You are not registering the Controllers. Try below code:
Step 1. Write your own controller factory class ControllerFactory :DefaultControllerFactory by implementing defaultcontrollerfactory in models folder
public class ControllerFactory :DefaultControllerFactory
{
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
try
{
if (controllerType == null)
throw new ArgumentNullException("controllerType");
if (!typeof(IController).IsAssignableFrom(controllerType))
throw new ArgumentException(string.Format(
"Type requested is not a controller: {0}",
controllerType.Name),
"controllerType");
return MvcUnityContainer.Container.Resolve(controllerType) as IController;
}
catch
{
return null;
}
}
public static class MvcUnityContainer
{
public static UnityContainer Container { get; set; }
}
}
Step 2:Regigster it in BootStrap: inBuildUnityContainer method
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
//RegisterTypes(container);
container = new UnityContainer();
container.RegisterType<IProductRepository, ProductRepository>();
MvcUnityContainer.Container = container;
return container;
}
Step 3: In Global Asax.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
Bootstrapper.Initialise();
ControllerBuilder.Current.SetControllerFactory(typeof(ControllerFactory));
}
And you are done
I tried
Document.getElementsByClassName('option0')
Which resulted in the error: Uncaught TypeError: Document.getElementsByClass is not a function
After that I tried:
document.getElementsByClassName('option0')
And it works!
You are encoding the form incorrectly. You should only encode the values:
StringBuilder postData = new StringBuilder();
postData.Append("username=" + HttpUtility.UrlEncode(uname) + "&");
postData.Append("password=" + HttpUtility.UrlEncode(pword) + "&");
postData.Append("url_success=" + HttpUtility.UrlEncode(urlSuccess) + "&");
postData.Append("url_failed=" + HttpUtility.UrlEncode(urlFailed));
edit
I was incorrect. According to RFC1866 section 8.2.1 both names and values should be encoded.
But for the given example, the names do not have any characters that needs to be encoded, so in this case my code example is correct ;)
The code in the question is still incorrect as it would encode the equal sign which is the reason to why the web server cannot decode it.
A more proper way would have been:
StringBuilder postData = new StringBuilder();
postData.AppendUrlEncoded("username", uname);
postData.AppendUrlEncoded("password", pword);
postData.AppendUrlEncoded("url_success", urlSuccess);
postData.AppendUrlEncoded("url_failed", urlFailed);
//in an extension class
public static void AppendUrlEncoded(this StringBuilder sb, string name, string value)
{
if (sb.Length != 0)
sb.Append("&");
sb.Append(HttpUtility.UrlEncode(name));
sb.Append("=");
sb.Append(HttpUtility.UrlEncode(value));
}
As per the documentation, these are just synonyms. size()
is there to be consistent with other STL containers (like vector
, map
, etc.) and length()
is to be consistent with most peoples' intuitive notion of character strings. People usually talk about a word, sentence or paragraph's length, not its size, so length()
is there to make things more readable.
As an alternative, since you know the hostname, resolve the database server IP via hostname from the web server.
You can change or import a theme by using the icon that the "Duplicate Theme" arrow is pointing to in the photo.
Every one sees color differently. Most times a small change in contrast is all you need. Removing the hase from Dracula by changing the Background color to 242527 was perfect for me.
C# is strongly typed so you can't create variables dynamically. You could use an array but a better C# way would be to use a Dictionary as follows. More on C# dictionaries here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuickTest
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> names = new Dictionary<string,int>();
for (int i = 0; i < 10; i++)
{
names.Add(String.Format("name{0}", i.ToString()), i);
}
var xx1 = names["name1"];
var xx2 = names["name2"];
var xx3 = names["name3"];
}
}
}
If this JSON file won't become too big over time, you should try:
Create a JavaScript object with the table array in it
var obj = {
table: []
};
Add some data to it, for example:
obj.table.push({id: 1, square:2});
Convert it from an object to a string with JSON.stringify
var json = JSON.stringify(obj);
Use fs to write the file to disk
var fs = require('fs');
fs.writeFile('myjsonfile.json', json, 'utf8', callback);
If you want to append it, read the JSON file and convert it back to an object
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
obj = JSON.parse(data); //now it an object
obj.table.push({id: 2, square:3}); //add some data
json = JSON.stringify(obj); //convert it back to json
fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
}});
This will work for data that is up to 100 MB effectively. Over this limit, you should use a database engine.
UPDATE:
Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.
For picking just one element of a generator use break
in a for
statement, or list(itertools.islice(gen, 1))
According to your example (literally) you can do something like:
while True:
...
if something:
for my_element in myfunct():
dostuff(my_element)
break
else:
do_generator_empty()
If you want "get just one element from the [once generated] generator whenever I like" (I suppose 50% thats the original intention, and the most common intention) then:
gen = myfunct()
while True:
...
if something:
for my_element in gen:
dostuff(my_element)
break
else:
do_generator_empty()
This way explicit use of generator.next()
can be avoided, and end-of-input handling doesn't require (cryptic) StopIteration
exception handling or extra default value comparisons.
The else:
of for
statement section is only needed if you want do something special in case of end-of-generator.
next()
/ .next()
:In Python3 the .next()
method was renamed to .__next__()
for good reason: its considered low-level (PEP 3114). Before Python 2.6 the builtin function next()
did not exist. And it was even discussed to move next()
to the operator
module (which would have been wise), because of its rare need and questionable inflation of builtin names.
Using next()
without default is still very low-level practice - throwing the cryptic StopIteration
like a bolt out of the blue in normal application code openly. And using next()
with default sentinel - which best should be the only option for a next()
directly in builtins
- is limited and often gives reason to odd non-pythonic logic/readablity.
Bottom line: Using next() should be very rare - like using functions of operator
module. Using for x in iterator
, islice
, list(iterator)
and other functions accepting an iterator seamlessly is the natural way of using iterators on application level - and quite always possible. next()
is low-level, an extra concept, unobvious - as the question of this thread shows. While e.g. using break
in for
is conventional.