Try something like this inside ThisOutlookSession
:
Private Sub Application_NewMail()
Call Your_main_macro
End Sub
My outlook vba just fired when I received an email and had that application event open.
Edit: I just tested a hello world msg box and it ran after being called in the application_newmail
event when an email was received.
The following should work with the latest version of Apache common codec
byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes));
and for encoding
byte[] encodedBytes = Base64.getEncoder().encode(decodedBytes);
System.out.println(new String(encodedBytes));
1 char s[100];
2 s = "hello";
In the example you provided, s is actually initialized at line 1, not line 2. Even though you didn't assign it a value explicitly at this point, the compiler did.
At line 2, you're performing an assignment operation, and you cannot assign one array of characters to another array of characters like this. You'll have to use strcpy()
or some kind of loop to assign each element of the array.
Do not use preg_match()
if you only want to check if one string is contained in another string. Use strpos()
or strstr()
instead as they will be faster. (http://in2.php.net/preg_match)
if (strpos($text, 'string_name') !== false){
echo 'get the string';
}
If you want to pass the data using POST instead of GET, you can do it using a combination of PHP and JavaScript, like this:
function formSubmit(house_number)
{
document.forms[0].house_number.value = house_number;
document.forms[0].submit();
}
Then in PHP you loop through the house-numbers, and create links to the JavaScript function, like this:
<form action="house.php" method="POST">
<input type="hidden" name="house_number" value="-1">
<?php
foreach ($houses as $id => name)
{
echo "<a href=\"javascript:formSubmit($id);\">$name</a>\n";
}
?>
</form>
That way you just have one form whose hidden variable(s) get modified according to which link you click on. Then JavasScript submits the form.
It seems as though there are multiple rows in the DATA.Dim_Member table per SUSP.Susp_Visits row.
To change the Path, you can set a new Path to an Enviroment-Variable named: VAGRANT_HOME
export VAGRANT_HOME=my/new/path/goes/here/
Thats maybe nice if you want to have those vagrant-Images on another HDD.
More Information here in the Documentations: http://docs.vagrantup.com/v2/other/environmental-variables.html
Try this query -
SELECT
t2.company_name,
t2.expose_new,
t2.expose_used,
t1.title,
t1.seller,
t1.status,
CASE status
WHEN 'New' THEN t2.expose_new
WHEN 'Used' THEN t2.expose_used
ELSE NULL
END as 'expose'
FROM
`products` t1
JOIN manufacturers t2
ON
t2.id = t1.seller
WHERE
t1.seller = 4238
What about this. Seems to give better performance.
byte[] bytes = new byte[1000];
StringBuilder x = new StringBuilder();
int numRead = 0;
while ((numRead = is.read(bytes)) >= 0) {
x.append(new String(bytes, 0, numRead));
}
Edit: Actually this sort of encompasses both steelbytes and Maurice Perry's
TO_DATE supports conversion to DATE datatype, which doesn't support milliseconds. If you want millisecond support in Oracle, you should look at TIMESTAMP datatype and TO_TIMESTAMP function.
Hope that helps.
If you use JQuery, you can use:
$("meta[property='video']").attr('content');
Use valueAsNumber
instead of .val()
.
input . valueAsNumber [ = value ]
Returns a number representing the form control's value, if applicable; otherwise, returns null.
Can be set, to change the value.
Throws an INVALID_STATE_ERR exception if the control is neither date- or time-based nor numeric.
Technically slice
is the fastest way. However, it is even faster if you add the 0
begin index.
myArray.slice(0);
is faster than
myArray.slice();
When we create a new RDS DB instance, the default master user is not the root user. But only gets certain privileges for that DB instance. This permission does not include SET permission. Now if your default master user tries to execute mysql SET commands, then you will face this error: Access denied; you need (at least one of) the SUPER or SYSTEM_VARIABLES_ADMIN privilege(s) for this operation
Comment out or remove these lines
SET @MYSQLDUMP_TEMP_LOG_BIN = @@SESSION.SQL_LOG_BIN;
SET @@SESSION.SQL_LOG_BIN= 1;
SET @@GLOBAL.GTID_PURGED=/*!80000 '+'*/ '';
You can also ignore the errors by using the -f option to load the rest of the dump file.
mysql -f <REPLACE_DB_NAME> -u <REPLACE_DB_USER> -h <DB_HOST_HERE> -p < dumpfile.sql
Maybe this helps. You have to refer the @param
/**
* Display a listing of the resource.
*
* @param Illuminate\Http\Request $request
* @return Response
*/
public function index(Request $request)
{
if($request->ajax()){
return "AJAX";
}
return "HTTP";
}
Other answers sort of hint at it, but the problem may arise from expecting a bytes object. In Python 3, decode is valid when you have an object of class bytes. Running encode before decode may "fix" the problem, but it is a useless pair of operations that suggest the problem us upstream.
Actually, the problem here is the use of ReadContentAsObject. Unfortunately, this method does not live up to its expectations; while it should detect the most appropirate type for the value, it actually returns a string, no matter what(this can be verified using Reflector).
However, in your specific case, you already know the type you want to cast to, therefore i would say you are using the wrong method.
Try using ReadContentAs instead, it's exactly what you need.
private static T ReadData<T>(XmlReader reader, string value)
{
reader.MoveToAttribute(value);
object readData = reader.ReadContentAs(typeof(T), null);
return (T)readData;
}
To answer your question about why caching is working, even though the web-server didn't include the headers:
[a date]
[seconds]
The server kindly asked any intermediate proxies to not cache the contents (i.e. the item should only be cached in a private cache, i.e. only on your own local machine):
But the server forgot to include any sort of caching hints:
But they did include a Last-Modified date in the response:
Last-Modified: Tue, 16 Oct 2012 03:13:38 GMT
Because the browser knows the date the file was modified, it can perform a conditional request. It will ask the server for the file, but instruct the server to only send the file if it has been modified since 2012/10/16 3:13:38:
GET / HTTP/1.1
If-Modified-Since: Tue, 16 Oct 2012 03:13:38 GMT
The server receives the request, realizes that the client has the most recent version already. Rather than sending the client 200 OK
, followed by the contents of the page, instead it tells you that your cached version is good:
304 Not Modified
Your browser did have to suffer the delay of sending a request to the server, and wait for a response, but it did save having to re-download the static content.
Because Last-Modified sucks.
Not everything on the server has a date associated with it. If I'm building a page on the fly, there is no date associated with it - it's now. But I'm perfectly willing to let the user cache the homepage for 15 seconds:
200 OK
Cache-Control: max-age=15
If the user hammers F5, they'll keep getting the cached version for 15 seconds. If it's a corporate proxy, then all 67198 users hitting the same page in the same 15-second window will all get the same contents - all served from close cache. Performance win for everyone.
The virtue of adding Cache-Control: max-age
is that the browser doesn't even have to perform a conditional request.
Last-Modified
, the browser has to perform a request If-Modified-Since
, and watch for a 304 Not Modified
responsemax-age
, the browser won't even have to suffer the network round-trip; the content will come right out of the cachesExpires
is a legacy equivalent of the modern (c. 1998) Cache-Control: max-age
header:
Expires
: you specify a date (yuck)max-age
: you specify seconds (goodness)And if both are specified, then the browser uses max-age
:
200 OK
Cache-Control: max-age=60
Expires: 20180403T192837
Any web-site written after 1998 should not use Expires
anymore, and instead use max-age
.
ETag is similar to Last-Modified, except that it doesn't have to be a date - it just has to be a something.
If I'm pulling a list of products out of a database, the server can send the last rowversion
as an ETag, rather than a date:
200 OK
ETag: "247986"
My ETag can be the SHA1 hash of a static resource (e.g. image, js, css, font), or of the cached rendered page (i.e. this is what the Mozilla MDN wiki does; they hash the final markup):
200 OK
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
And exactly like in the case of a conditional request based on Last-Modified:
GET / HTTP/1.1
If-Modified-Since: Tue, 16 Oct 2012 03:13:38 GMT
304 Not Modified
I can perform a conditional request based on the ETag:
GET / HTTP/1.1
If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4"
304 Not Modified
An ETag
is superior to Last-Modified
because it works for things besides files, or things that have a notion of date. It just is
How about:
DELETE guide_category
WHERE id_guide_category IN (
SELECT id_guide_category
FROM guide_category AS gc
LEFT JOIN guide AS g
ON g.id_guide = gc.id_guide
WHERE g.title IS NULL
)
If I ommit begin - end it is error. So for me this is working (nothing else needed):
set serveroutput on;
begin
DBMS_OUTPUT.PUT_LINE('testing');
end;
height:100% works if the parent container has a specified height property else, it won't work
This is not a particularly good answer as it explains how to run your java code n VS Code and not necessarily a Maven
project, but it worked for me because I could not get around to doing the manual configuration myself. I decided to use this method instead since it is easier and faster.
Install VSCode (and for windows, set your environment variables), then install vscode:extension/vscjava.vscode-java-pack
as detailed above, and then install the code runner extension pack, which basically sets up the whole process (in the background) as explained in the accepted answer above and then provides a play button to run your java code when you're ready.
This was all explained in this video.
Again, this is not the best solution, but if you want to cut to the chase, you may find this answer useful.
This shows you how to
DOM
Nodes
with XPath
Nodes
. We will call the code with the following statement
processFilteredXml(xmlIn, xpathExpr,(node) -> {/*Do something...*/;});
In our case we want to print some creatorNames
from a book.xml
using "//book/creators/creator/creatorName"
as xpath to perform a printNode
action on each Node that matches the XPath
.
Full code
@Test
public void printXml() {
try (InputStream in = readFile("book.xml")) {
processFilteredXml(in, "//book/creators/creator/creatorName", (node) -> {
printNode(node, System.out);
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private InputStream readFile(String yourSampleFile) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream(yourSampleFile);
}
private void processFilteredXml(InputStream in, String xpath, Consumer<Node> process) {
Document doc = readXml(in);
NodeList list = filterNodesByXPath(doc, xpath);
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
process.accept(node);
}
}
public Document readXml(InputStream xmlin) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
return db.parse(xmlin);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private NodeList filterNodesByXPath(Document doc, String xpathExpr) {
try {
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
XPathExpression expr = xpath.compile(xpathExpr);
Object eval = expr.evaluate(doc, XPathConstants.NODESET);
return (NodeList) eval;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void printNode(Node node, PrintStream out) {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(node);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
out.println(xmlString);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Prints
<creatorName>Fosmire, Michael</creatorName>
<creatorName>Wertz, Ruth</creatorName>
<creatorName>Purzer, Senay</creatorName>
For book.xml
<book>
<creators>
<creator>
<creatorName>Fosmire, Michael</creatorName>
<givenName>Michael</givenName>
<familyName>Fosmire</familyName>
</creator>
<creator>
<creatorName>Wertz, Ruth</creatorName>
<givenName>Ruth</givenName>
<familyName>Wertz</familyName>
</creator>
<creator>
<creatorName>Purzer, Senay</creatorName>
<givenName>Senay</givenName>
<familyName>Purzer</familyName>
</creator>
</creators>
<titles>
<title>Critical Engineering Literacy Test (CELT)</title>
</titles>
</book>
public boolean FileExists(String fname) {
File file = getBaseContext().getFileStreamPath(fname);
return file.exists();
}
Added this as a comment to accepted answer, but felt it deserved a longer explanation. Starting around April 2015 this will probably be raised a few times.
As of V2 of the graph api the accepted answer no longer works using a username. So now you need the userid first, and you can no longer use a username to get this. To further complicate matters, for privacy reasons, Facebook is now changing userid's per app (see https://developers.facebook.com/docs/graph-api/reference/v2.2/user/ and https://developers.facebook.com/docs/apps/upgrading/#upgrading_v2_0_user_ids ), so you will have to have some kind of proper authentication to retrieve a userid you can use. Technically the profile pic is still public and available at /userid/picture (see docs at https://developers.facebook.com/docs/graph-api/reference/v2.0/user/picture and this example user: http://graph.facebook.com/v2.2/4/picture?redirect=0) however figuring out a user's standard userid seems impossible based just on their profile - your app would need to get them to approve interaction with the app which for my use case (just showing a profile pic next to their FB profile link) is overkill.
If someone has figured out a way to get the profile pic based on username, or alternatively, how to get a userid (even an alternating one) to use to retrieve a profile pic, please share! In the meantime, the old graph url still works until April 2015.
The breakdown of your declaration and its members is somewhat littered:
Remove the typedef
The typedef
is neither required, not desired for class/struct declarations in C++. Your members have no knowledge of the declaration of pos
as-written, which is core to your current compilation failure.
Change this:
typedef struct {....} pos;
To this:
struct pos { ... };
Remove extraneous inlines
You're both declaring and defining your member operators within the class definition itself. The inline
keyword is not needed so long as your implementations remain in their current location (the class definition)
Return references to *this
where appropriate
This is related to an abundance of copy-constructions within your implementation that should not be done without a strong reason for doing so. It is related to the expression ideology of the following:
a = b = c;
This assigns c
to b
, and the resulting value b
is then assigned to a
. This is not equivalent to the following code, contrary to what you may think:
a = c;
b = c;
Therefore, your assignment operator should be implemented as such:
pos& operator =(const pos& a)
{
x = a.x;
y = a.y;
return *this;
}
Even here, this is not needed. The default copy-assignment operator will do the above for you free of charge (and code! woot!)
Note: there are times where the above should be avoided in favor of the copy/swap idiom. Though not needed for this specific case, it may look like this:
pos& operator=(pos a) // by-value param invokes class copy-ctor
{
this->swap(a);
return *this;
}
Then a swap method is implemented:
void pos::swap(pos& obj)
{
// TODO: swap object guts with obj
}
You do this to utilize the class copy-ctor to make a copy, then utilize exception-safe swapping to perform the exchange. The result is the incoming copy departs (and destroys) your object's old guts, while your object assumes ownership of there's. Read more the copy/swap idiom here, along with the pros and cons therein.
Pass objects by const reference when appropriate
All of your input parameters to all of your members are currently making copies of whatever is being passed at invoke. While it may be trivial for code like this, it can be very expensive for larger object types. An exampleis given here:
Change this:
bool operator==(pos a) const{
if(a.x==x && a.y== y)return true;
else return false;
}
To this: (also simplified)
bool operator==(const pos& a) const
{
return (x == a.x && y == a.y);
}
No copies of anything are made, resulting in more efficient code.
Finally, in answering your question, what is the difference between a member function or operator declared as const
and one that is not?
A const
member declares that invoking that member will not modifying the underlying object (mutable declarations not withstanding). Only const
member functions can be invoked against const
objects, or const
references and pointers. For example, your operator +()
does not modify your local object and thus should be declared as const
. Your operator =()
clearly modifies the local object, and therefore the operator should not be const
.
Summary
struct pos
{
int x;
int y;
// default + parameterized constructor
pos(int x=0, int y=0)
: x(x), y(y)
{
}
// assignment operator modifies object, therefore non-const
pos& operator=(const pos& a)
{
x=a.x;
y=a.y;
return *this;
}
// addop. doesn't modify object. therefore const.
pos operator+(const pos& a) const
{
return pos(a.x+x, a.y+y);
}
// equality comparison. doesn't modify object. therefore const.
bool operator==(const pos& a) const
{
return (x == a.x && y == a.y);
}
};
EDIT OP wanted to see how an assignment operator chain works. The following demonstrates how this:
a = b = c;
Is equivalent to this:
b = c;
a = b;
And that this does not always equate to this:
a = c;
b = c;
Sample code:
#include <iostream>
#include <string>
using namespace std;
struct obj
{
std::string name;
int value;
obj(const std::string& name, int value)
: name(name), value(value)
{
}
obj& operator =(const obj& o)
{
cout << name << " = " << o.name << endl;
value = (o.value+1); // note: our value is one more than the rhs.
return *this;
}
};
int main(int argc, char *argv[])
{
obj a("a", 1), b("b", 2), c("c", 3);
a = b = c;
cout << "a.value = " << a.value << endl;
cout << "b.value = " << b.value << endl;
cout << "c.value = " << c.value << endl;
a = c;
b = c;
cout << "a.value = " << a.value << endl;
cout << "b.value = " << b.value << endl;
cout << "c.value = " << c.value << endl;
return 0;
}
Output
b = c
a = b
a.value = 5
b.value = 4
c.value = 3
a = c
b = c
a.value = 4
b.value = 4
c.value = 3
DECLARE @CarList nvarchar(max);
SET @CarList = N'';
SELECT @CarList+=CarName+N','
FROM dbo.CARS;
SELECT LEFT(@CarList,LEN(@CarList)-1);
Thanks are due to whoever on SO showed me the use of accumulating data during a query.
TextView txtview = new TextView(v.getContext());
LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f);
txtview.setLayoutParams(params);
1f is denotes as weight=1; you can give 2f or 3f, views will move accoding to the space
To delete all objects in a list, you can directly write list = []
Here is example:
>>> a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a = []
>>> a
[]
There is TKlerx's Android SQLite browser for Eclipse, and it's fully functional alongside Android Studio. I'll recommend it, because it is immensely practical.
To install it on Device Monitor, just place the JAR file in [Path to Android SDK folder]/sdk/tools/lib/monitor-[...]/plugins
.
This is a paragraph option. Go to Window>Paragraph then a small window will pop up. You will have two buttons on the bottom. One with a arrow on the left of P and one on the right. Select the right one.
Nothing here worked for me, I found this command in another SO answer though and it solved my problem. Just start command prompt as an administrator and run this command:
run->cmd
run "c:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i"
Credit: User Vicxx
This worked for me, no jquery or select wrapper with input class, just material.js and this vanilla js:
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
});
As you can tell I got the materialize css actual style and not the browsers default.
This probably isn't the most elegant way to do it, but it gets the job done.
In[1]: import numpy as np
In[2]: import pandas as pd
In[3]: df = pd.DataFrame(np.genfromtxt('/Users/spencerlyon2/Desktop/test.csv', dtype=str)[1:], columns=['ID'])
In[4]: df
Out[4]:
ID
0 00013007854817840016671868
1 00013007854817840016749251
2 00013007854817840016754630
3 00013007854817840016781876
4 00013007854817840017028824
5 00013007854817840017963235
6 00013007854817840018860166
Just replace '/Users/spencerlyon2/Desktop/test.csv'
with the path to your file
Install pip:
sudo easy_install pip
Install brew:
ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"
Install mysql:
brew install mysql
Install MySQLdb
sudo pip install MySQL-python
If you have compilation problems, try editing the ~/.profile file like in one of the answers here.
If you know the number of sheet you want to reference you can use below function to find out the name. Than you can use it in INDIRECT funcion.
Public Function GETSHEETNAME(address As String, Optional SheetNumber As Integer = 1) As String
Set WS = GetObject(address).Worksheets
GETSHEETNAME = WS(SheetNumber).Name
End Function
This solution doesn't require referenced workbook to be open - Excel gonna open it by itself (but it's gonna be hidden).
I made the following module called unicoder to be able to do the transformation on variables:
import sys
import os
def ustr(string):
string = 'u"%s"'%string
with open('_unicoder.py', 'w') as script:
script.write('# -*- coding: utf-8 -*-\n')
script.write('_ustr = %s'%string)
import _unicoder
value = _unicoder._ustr
del _unicoder
del sys.modules['_unicoder']
os.system('del _unicoder.py')
os.system('del _unicoder.pyc')
return value
Then in your program you could do the following:
# -*- coding: utf-8 -*-
from unicoder import ustr
txt = 'Hello, Unicode World'
txt = ustr(txt)
print type(txt) # <type 'unicode'>
You just needed to update ca-certificates package. Before that just disable all repos with https that are failing. That's why solution with commenting mirrorlist or using http instead https would work also.
For example if you need to disable only epel repo:
yum --disablerepo=epel -y update ca-certificates
This will also help wget, curl, and anything else that uses SSL certificates.
You have to cd to your master directory and then rails s command will work without problems.
But do not forget bundle-install command when you didn't do it before.
You could use strcmp()
:
/* strcmp example */
#include <stdio.h>
#include <string.h>
int main ()
{
char szKey[] = "apple";
char szInput[80];
do {
printf ("Guess my favourite fruit? ");
gets (szInput);
} while (strcmp (szKey,szInput) != 0);
puts ("Correct answer!");
return 0;
}
According to the HTML spec, <span>
is an inline element and <div>
is a block element. Now that can be changed using the display
CSS property but there is one issue: in terms of HTML validation, you can't put block elements inside inline elements so:
<p>...<div>foo</div>...</p>
is not strictly valid even if you change the <div>
to inline
or inline-block
.
So, if your element is inline
or inline-block
use a <span>
. If it's a block
level element, use a <div>
.
I use SLF4J + Logback classic and apply it like this:
trait Logging {
lazy val logger = LoggerFactory.getLogger(getClass)
implicit def logging2Logger(anything: Logging): Logger = anything.logger
}
Then you can use it whichever fits your style better:
class X with Logging {
logger.debug("foo")
debug("bar")
}
but this approach of course uses a logger instance per class instance.
What about -mmin
?
find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
-exec rm -f {} \;
From man find:
-mmin n File's data was last modified n minutes ago.
Also, make sure to test this first!
... -exec echo rm -f '{}' \; ^^^^ Add the 'echo' so you just see the commands that are going to get run instead of actual trying them first.
Just for fun, here is a solution using ed
which does not have the problem of not working on an empty file. You can put it into a shell script just like any other answer to this question.
ed Test <<EOF
a
.
0i
<added text>
.
1,+1 j
$ g/^$/d
wq
EOF
The above script adds the text to insert to the first line, and then joins the first and second line. To avoid ed exiting on error with an invalid join, it first creates a blank line at the end of the file and remove it later if it still exists.
Limitations: This script does not work if <added text>
is exactly equal to a single period.
This will convert "Hello World" to "48656c6c6f20576f726c64" and will store this hex value in str1 and also will convert "48656c6c6f20576f726c64" to "Hello World".
#include <iostream>
#include<sstream>
using namespace std;
int hexCharToInt(char);
string hexToString(string);
int main()
{
std::string str;
std::stringstream str1;
str="Hello World";
for(int i=0;i<str.length();i++){
str1 << std::hex << (int)str.at(i);
}
std::cout << str1.str() <<"\n";
string test = "48656c6c6f20576f726c64";
std::cout << hexToString(test) <<"\n";
return 0;
}
string hexToString(string str){
std::stringstream HexString;
for(int i=0;i<str.length();i++){
char a = str.at(i++);
char b = str.at(i);
int x = hexCharToInt(a);
int y = hexCharToInt(b);
HexString << (char)((16*x)+y);
}
return HexString.str();
}
int hexCharToInt(char a){
if(a>='0' && a<='9')
return(a-48);
else if(a>='A' && a<='Z')
return(a-55);
else
return(a-87);
}
You can use ToString() to convert the first enum to its name, and then Enum.Parse() to convert the string back to the other Enum. This will throw an exception if the value is not supported by the destination enum (i.e. for an "Unknown" value)
If the hour is important, I used str_to_date(date, '%d/%m/%Y %T' )
, the %T
shows the hour in the format hh:mm:ss
.
select top {LIMIT HERE} * from (
select *, ROW_NUMBER() over (order by {ORDER FIELD}) as r_n_n
from {YOUR TABLES} where {OTHER OPTIONAL FILTERS}
) xx where r_n_n >={OFFSET HERE}
A note:
This solution will only work in SQL Server 2005 or above, since this was when ROW_NUMBER()
was implemented.
If you're using #
as an operator, consider defining a new operator for it:
\newcommand{\pound}{\operatornamewithlimits{\#}}
You can then write things like \pound_{n = 1}^N
and get:
I use GET when I'm retrieving information from a URL and POST when I'm sending information to a URL.
For bootstrap 3 datepicker. (Note the capital letters)
$("#datetimepicker").datetimepicker( {
format: "YYYY",
viewMode: "years"
});
FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.
Some references:
Though you can use any other client that allows automation.
You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).
Combine WinSCP scripting capabilities with Windows Scheduler:
A typical WinSCP script for upload (with SFTP) looks like:
open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close
With FTP, just replace the sftp://
with the ftp://
and remove the -hostkey="..."
switch.
Similarly for download: How to schedule an automatic FTP download on Windows?
WinSCP can even generate a script from an imported FileZilla session.
For details, see the guide to FileZilla automation.
(I'm the author of WinSCP)
Another option, if you are using SFTP, is the psftp.exe
client from PuTTY suite.
Without answering the question about how to create and inject Authentication objects, Spring Security 4.0 provides some welcome alternatives when it comes to testing. The @WithMockUser
annotation enables the developer to specify a mock user (with optional authorities, username, password and roles) in a neat way:
@Test
@WithMockUser(username = "admin", authorities = { "ADMIN", "USER" })
public void getMessageWithMockUserCustomAuthorities() {
String message = messageService.getMessage();
...
}
There is also the option to use @WithUserDetails
to emulate a UserDetails
returned from the UserDetailsService
, e.g.
@Test
@WithUserDetails("customUsername")
public void getMessageWithUserDetailsCustomUsername() {
String message = messageService.getMessage();
...
}
More details can be found in the @WithMockUser and the @WithUserDetails chapters in the Spring Security reference docs (from which the above examples were copied)
Clean way which I found useful
git revert --no-commit HEAD~3..
This command reverts last 3 commits with only one commit.
Also doesn't rewrite history.
The ..
helps create a range. Meaning HEAD~3..
is the same as HEAD~3..HEAD
#!/bin/bash
# functiontest.sh a sample to call the function in the shell script
choice="true"
function process_install
{
commands...
}
function process_exit
{
commands...
}
function main
{
if [[ "$choice" == "true" ]]; then
process_install
elif [[ "$choice" == "false" ]]; then
process_exit
fi
}
main "$@"
it will start from the main function
I was able to add the following to my .bash_profile to prevent the error:
export PGHOST=localhost
This works because:
If you omit the host name, psql will connect via a Unix-domain socket to a server on the local host, or via TCP/IP to localhost on machines that don't have Unix-domain sockets.
Your OS supports Unix domain sockets, but PostgreSQL's Unix socket that psql
needs either doesn't exist or is in a different location than it expects.
Specifying a hostname explicitly as localhost
forces psql
to use TCP/IP. Setting an environment variable PGHOST
is one of the ways to achieve that. It's documented in psql's manual.
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
// or SimpleDateFormat sdf = new SimpleDateFormat( "MM/dd/yyyy KK:mm:ss a Z" );
sdf.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
System.out.println( sdf.format( new Date() ) );
Without VBA macro, you can use this tips to get the username from the path :
=MID(INFO("DIRECTORY"),10,LEN(INFO("DIRECTORY"))-LEN(MID(INFO("DIRECTORY"),FIND("\",INFO("DIRECTORY"),10),1000))-LEN("C:\Users\"))
Png files can handle transparency.
So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png
file.
And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?
If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.
If NEW_TABLE already exists then ...
insert into new_table
select * from old_table
/
If you want to create NEW_TABLE based on the records in OLD_TABLE ...
create table new_table as
select * from old_table
/
If the purpose is to create a new but empty table then use a WHERE clause with a condition which can never be true:
create table new_table as
select * from old_table
where 1 = 2
/
Remember that CREATE TABLE ... AS SELECT creates only a table with the same projection as the source table. The new table does not have any constraints, triggers or indexes which the original table might have. Those still have to be added manually (if they are required).
From Oracle docs, Date.toString() method convert Date object to a String of the specific form - do not use toString method on Date object. Try to use:
String stringDate = new SimpleDateFormat(YOUR_STRING_PATTERN).format(yourDateObject);
Next step is parse stringDate to Date:
Date date = new SimpleDateFormat(OUTPUT_PATTERN).parse(stringDate);
Note that, parse method throws ParseException
Although this question is being asked for 5 years ago. I just want to share my answer. Below is how I detect whether someone is clicked cancel and OK button in input box:
Public sName As String
Sub FillName()
sName = InputBox("Who is your name?")
' User is clicked cancel button
If StrPtr(sName) = False Then
MsgBox ("Please fill your name!")
Exit Sub
End If
' User is clicked OK button whether entering any data or without entering any datas
If sName = "" Then
' If sName string is empty
MsgBox ("Please fill your name!")
Else
' When sName string is filled
MsgBox ("Welcome " & sName & " and nice see you!")
End If
End Sub
Make use of jquery toggle function which do the task for you
.toggle() - Display or hide the matched elements.
$('#myelement').click(function(){
$('#another-element').toggle('slow');
});
What about using UIPageViewController
with an array of UICollectionViewControllers
? You'd have to fetch proper number of items in each UICollectionViewController
, but it shouldn't be hard. You'd get exactly the same look as the Springboard has.
I've thought about this and in my opinion you have to set:
self.collectionView.pagingEnabled = YES;
and create your own collection view layout by subclassing UICollectionViewLayout
. From the custom layout object you can access self.collectionView
, so you'll know what is the size of the collection view's frame
, numberOfSections
and numberOfItemsInSection:
. With that information you can calculate cells' frames
(in prepareLayout
) and collectionViewContentSize
. Here're some articles about creating custom layouts:
You can do this (or an approximation of it) without creating the custom layout. Add UIScrollView
in the blank view, set paging enabled in it. In the scroll view add the a collection view. Then add to it a width constraint, check in code how many items you have and set its constant
to the correct value, e.g. (self.view.frame.size.width * numOfScreens)
. Here's how it looks (numbers on cells show the indexPath.row
): https://www.dropbox.com/s/ss4jdbvr511azxz/collection_view.mov If you're not satisfied with the way cells are ordered, then I'm afraid you'd have to go with 1. or 2.
In late 2017 Proxool, BoneCP, C3P0, DBCP are mostly defunct at this time. HikariCP (created in 2012) seems promising, blows the doors off anything else I know of. http://www.baeldung.com/hikaricp
Proxool has a number of issues:
- Under heavy load can exceed max number of connections and not return below max
- Can manage to not return to min connections even after connections expire
- Can lock up the entire pool (and all server/client threads) if it has trouble connecting to the database during HouseKeeper thread (does not use .setQueryTimeout)
- HouseKeeper thread, while having connection pool lock for its process, requests the Prototyper thread to recreate connections (sweep) which can result in race condition/lockup. In these method calls the last parameter should always be sweep:false during the loop, only sweep:true below it.
- HouseKeeper only needs the single PrototypeController sweep at the end and has more [mentioned above]
- HouseKeeper thread checks for testing of connections before seeing what connections may be expired [some risk of testing expired connection that may be broken/terminated through other timeouts to DB in firewall, etc.]
- The project has unfinished code (properties that are defined but not acted upon)
- The Default max connection life if not defined is 4 hours (excessive)
- HouseKeeper thread runs every five seconds per pool (excessive)
You can modify the code and make these improvements. But as it was created in 2003, and updated in 2008, its lacking nearly 10 years of java improvements that solutions like hikaricp utilize.
Answering this just in case if someone else like me stumbles upon this post among many that advise use of JavaScripts for changing iframe height to 100%.
I strongly recommend that you see and try this option specified at How do you give iframe 100% height before resorting to a JavaScript based option. The referenced solution works perfectly for me in all of the testing I have done so far. Hope this helps someone.
As was suggested in a comment above, if the certificate store on the host is compatible with the guest, you can just mount it directly.
On a Debian host (and container), I've successfully done:
docker run -v /etc/ssl/certs:/etc/ssl/certs:ro ...
If you are like me and have certain restrictions in a production environment, you may wish to use a table variable instead of temp table, and an ad-hoc query rather than a create procedure.
Of course depending on your sql server instance, it must support table variables.
I also added a USE statement to narrow the search scope
USE DATABASE_NAME
DECLARE @SearchStr nvarchar(100) = 'SEARCH_TEXT'
DECLARE @Results TABLE (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO @Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM @Results
Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")
Should be:
Date.strptime(updated, '%a, %d %b %Y %H:%M:%S %Z')
Set the columns Width
property to be a proportional width such as *
I encountered this problem as well. I updated everything I could in the Android SDK Manager, uninstalled my device using Device Manager, and now it works correctly. I issues a few "kill-server" and "start-server" along the way...
db.collection.remove(<query>,
{
justOne: <boolean>,
writeConcern: <document>
})
The question is correctly answered here Center a column using Twitter Bootstrap 3
For odd rows: i.e., col-md-7 or col-large-9 use this
Add col-centered to the column you want centered.
<div class="col-lg-11 col-centered">
And add this to your stylesheet:
.col-centered{
float: none;
margin: 0 auto;
}
For even rows: i.e., col-md-6 or col-large-10 use this
Simply use bootstrap 3's offset col class. i.e.,
<div class="col-lg-10 col-lg-offset-1">
Try this
function DisplayLocalSites
{
try{
Set-ExecutionPolicy unrestricted
$list = @()
foreach ($webapp in get-childitem IIS:\Sites\)
{
$name = "IIS:\Sites\" + $webapp.name
$item = @{}
$item.WebAppName = $webapp.name
foreach($Bind in $webapp.Bindings.collection)
{
$item.SiteUrl = $Bind.Protocol +'://'+ $Bind.BindingInformation.Split(":")[-1]
}
$obj = New-Object PSObject -Property $item
$list += $obj
}
$list | Format-Table -a -Property "WebAppName","SiteUrl"
$list | Out-File -filepath C:\websites.txt
Set-ExecutionPolicy restricted
}
catch
{
$ExceptionMessage = "Error in Line: " + $_.Exception.Line + ". " + $_.Exception.GetType().FullName + ": " + $_.Exception.Message + " Stacktrace: " + $_.Exception.StackTrace
$ExceptionMessage
}
}
This is the only solution that worked for me on Ubuntu-18.
Inside the file app.py
, use:
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
The code above will give the same permission error unless sudo
is used to run it:
sudo python3 app.py
For the case where there are 2 getters for the same property, the deserializer fails Refer Link
What I usually do is use clock()
or time()
from the time
library. clock
measures interpreter time, while time
measures system time. Additional caveats can be found in the docs.
For example,
def fn():
st = time()
dostuff()
print 'fn took %.2f seconds' % (time() - st)
Or alternatively, you can use timeit
. I often use the time
approach due to how fast I can bang it out, but if you're timing an isolate-able piece of code, timeit
comes in handy.
From the timeit docs,
def test():
"Stupid test function"
L = []
for i in range(100):
L.append(i)
if __name__=='__main__':
from timeit import Timer
t = Timer("test()", "from __main__ import test")
print t.timeit()
Then to convert to minutes, you can simply divide by 60. If you want the script runtime in an easily readable format, whether it's seconds or days, you can convert to a timedelta
and str
it:
runtime = time() - st
print 'runtime:', timedelta(seconds=runtime)
and that'll print out something of the form [D day[s], ][H]H:MM:SS[.UUUUUU]
. You can check out the timedelta docs.
And finally, if what you're actually after is profiling your code, Python makes available the profile library as well.
When you run the code
listoflists.append((list, list[0]))
You are not (as I think you expect) adding a copy of list
to the end of listoflists
. What you are doing is adding a reference to list
to the end of listoflists
. Thus, every time you update list
, it updates every reference to list
, which in this case, is every item in listoflists
What you could do instead is something like this:
listoflists = []
for i in range(1, 10):
listoflists.append((range(i), 0))
The problem is frequently with 'secure' setup of mountpoints, such as /tmp
If they are mounted noexec
(check with cat /etc/mtab
and or sudo mount
) then there is no permission to execute any binaries or build scripts from within the (temporary) folder.
E.g. to remount temporarily:
sudo mount -o remount,exec /tmp
Or to change permanently, remove noexec
in /etc/fstab
Assuming MySQL supports it, you can easily do this with a standard SQL subquery:
select
(count(*) from league_girl l1 where l2.score > l1.score and l1.id <> l2.id) as position,
username,
score
from league_girl l2
order by score;
For large amounts of displayed results, this will be a bit slow and you will want to switch to a self join instead.
Using jdk7-u221, I was need to install the Java Cryptography Extension (JCE)
unicode_escape
doesn't work in generalIt turns out that the string_escape
or unicode_escape
solution does not work in general -- particularly, it doesn't work in the presence of actual Unicode.
If you can be sure that every non-ASCII character will be escaped (and remember, anything beyond the first 128 characters is non-ASCII), unicode_escape
will do the right thing for you. But if there are any literal non-ASCII characters already in your string, things will go wrong.
unicode_escape
is fundamentally designed to convert bytes into Unicode text. But in many places -- for example, Python source code -- the source data is already Unicode text.
The only way this can work correctly is if you encode the text into bytes first. UTF-8 is the sensible encoding for all text, so that should work, right?
The following examples are in Python 3, so that the string literals are cleaner, but the same problem exists with slightly different manifestations on both Python 2 and 3.
>>> s = 'naïve \\t test'
>>> print(s.encode('utf-8').decode('unicode_escape'))
naïve test
Well, that's wrong.
The new recommended way to use codecs that decode text into text is to call codecs.decode
directly. Does that help?
>>> import codecs
>>> print(codecs.decode(s, 'unicode_escape'))
naïve test
Not at all. (Also, the above is a UnicodeError on Python 2.)
The unicode_escape
codec, despite its name, turns out to assume that all non-ASCII bytes are in the Latin-1 (ISO-8859-1) encoding. So you would have to do it like this:
>>> print(s.encode('latin-1').decode('unicode_escape'))
naïve test
But that's terrible. This limits you to the 256 Latin-1 characters, as if Unicode had never been invented at all!
>>> print('Erno \\t Rubik'.encode('latin-1').decode('unicode_escape'))
UnicodeEncodeError: 'latin-1' codec can't encode character '\u0151'
in position 3: ordinal not in range(256)
(Surprisingly, we do not now have two problems.)
What we need to do is only apply the unicode_escape
decoder to things that we are certain to be ASCII text. In particular, we can make sure only to apply it to valid Python escape sequences, which are guaranteed to be ASCII text.
The plan is, we'll find escape sequences using a regular expression, and use a function as the argument to re.sub
to replace them with their unescaped value.
import re
import codecs
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\U........ # 8-digit hex escapes
| \\u.... # 4-digit hex escapes
| \\x.. # 2-digit hex escapes
| \\[0-7]{1,3} # Octal escapes
| \\N\{[^}]+\} # Unicode characters by name
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
def decode_escapes(s):
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
And with that:
>>> print(decode_escapes('Erno \\t Rubik'))
Erno Rubik
To close this question, what seemed to have worked is indeed running
docker-compose stop
docker-compose rm -f
docker-compose -f docker-compose.yml up -d
I.e. remove the containers before running up
again.
What one needs to keep in mind when doing it like this is that data volume containers are removed as well if you just run rm -f
. In order to prevent that I specify explicitly each container to remove:
docker-compose rm -f application nginx php
As I said in my question, I don't know if this is the correct process. But this seems to work for our use case, so until we find a better solution we'll roll with this one.
Here is one solution with jQuery for browsers that don't support the placeholder attribute.
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
Found here: http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
Regarding 0xCC
and 0xCD
in particular, these are relics from the Intel 8088/8086 processor instruction set back in the 1980s. 0xCC
is a special case of the software interrupt opcode INT
0xCD
. The special single-byte version 0xCC
allows a program to generate interrupt 3.
Although software interrupt numbers are, in principle, arbitrary, INT 3
was traditionally used for the debugger break or breakpoint function, a convention which remains to this day. Whenever a debugger is launched, it installs an interrupt handler for INT 3
such that when that opcode is executed the debugger will be triggered. Typically it will pause the currently running programming and show an interactive prompt.
Normally, the x86 INT
opcode is two bytes: 0xCD
followed by the desired interrupt number from 0-255. Now although you could issue 0xCD 0x03
for INT 3
, Intel decided to add a special version--0xCC
with no additional byte--because an opcode must be only one byte in order to function as a reliable 'fill byte' for unused memory.
The point here is to allow for graceful recovery if the processor mistakenly jumps into memory that does not contain any intended instructions. Multi-byte instructions aren't suited this purpose since an erroneous jump could land at any possible byte offset where it would have to continue with a properly formed instruction stream.
Obviously, one-byte opcodes work trivially for this, but there can also be quirky exceptions: for example, considering the fill sequence 0xCDCDCDCD
(also mentioned on this page), we can see that it's fairly reliable since no matter where the instruction pointer lands (except perhaps the last filled byte), the CPU can resume executing a valid two-byte x86 instruction CD CD
, in this case for generating software interrupt 205 (0xCD).
Weirder still, whereas CD CC CD CC
is 100% interpretable--giving either INT 3
or INT 204
--the sequence CC CD CC CD
is less reliable, only 75% as shown, but generally 99.99% when repeated as an int-sized memory filler.
Well here is a nice script to TRIM all varchar columns on a table dynamically:
--Just change table name
declare @MyTable varchar(100)
set @MyTable = 'MyTable'
--temp table to get column names and a row id
select column_name, ROW_NUMBER() OVER(ORDER BY column_name) as id into #tempcols from INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE IN ('varchar', 'nvarchar') and TABLE_NAME = @MyTable
declare @tri int
select @tri = count(*) from #tempcols
declare @i int
select @i = 0
declare @trimmer nvarchar(max)
declare @comma varchar(1)
set @comma = ', '
--Build Update query
select @trimmer = 'UPDATE [dbo].[' + @MyTable + '] SET '
WHILE @i <= @tri
BEGIN
IF (@i = @tri)
BEGIN
set @comma = ''
END
SELECT @trimmer = @trimmer + CHAR(10)+ '[' + COLUMN_NAME + '] = LTRIM(RTRIM([' + COLUMN_NAME + ']))'+@comma
FROM #tempcols
where id = @i
select @i = @i+1
END
--execute the entire query
EXEC sp_executesql @trimmer
drop table #tempcols
Given an actual JAR file, you can list the contents using JarFile.entries()
. You will need to know the location of the JAR file though - you can't just ask the classloader to list everything it could get at.
You should be able to work out the location of the JAR file based on the URL returned from ThisClassName.class.getResource("ThisClassName.class")
, but it may be a tiny bit fiddly.
DELIMITER $$
CREATE PROCEDURE GenerateRangeDates(IN dateStart DATE, IN dateEnd DATE)
BEGIN
CREATE TEMPORARY TABLE IF NOT EXISTS dates (day DATE);
loopDate: LOOP
INSERT INTO dates(day) VALUES (dateStart);
SET dateStart = DATE_ADD(dateStart, INTERVAL 1 DAY);
IF dateStart <= dateEnd
THEN ITERATE loopDate;
ELSE LEAVE loopDate;
END IF;
END LOOP loopDate;
SELECT day FROM dates;
DROP TEMPORARY TABLE IF EXISTS dates;
END
$$
-- Call procedure
call GenerateRangeDates(
now() - INTERVAL 40 DAY,
now()
);
Yacoby's answer inspires me to write an adaptor for encapsulating the functor boilerplate.
template< class T, bool (*comp)( T const &, T const & ) >
class set_funcomp {
struct ftor {
bool operator()( T const &l, T const &r )
{ return comp( l, r ); }
};
public:
typedef std::set< T, ftor > t;
};
// usage
bool my_comparison( foo const &l, foo const &r );
set_funcomp< foo, my_comparison >::t boo; // just the way you want it!
Wow, I think that was worth the trouble!
In SQL you need to use GETDATE()
:
UPDATE table SET date = GETDATE();
There is no NOW()
function.
To answer your question:
In a large table, since the function is evaluated for each row, you will end up getting different values for the updated field.
So, if your requirement is to set it all to the same date I would do something like this (untested):
DECLARE @currDate DATETIME;
SET @currDate = GETDATE();
UPDATE table SET date = @currDate;
Viewgroup inherits properties of views and does more with other views and viewgroup.
See the Android API: http://developer.android.com/reference/android/view/ViewGroup.html
Without using Collections in Java:
import java.util.Scanner;
public class SortingaString {
public static String Sort(String s1)
{
char ch[]=s1.toCharArray();
String res=" ";
for(int i=0; i<ch.length ; i++)
{
for(int j=i+1;j<ch.length; j++)
{
if(ch[i]>=ch[j])
{
char m=ch[i];
ch[i]=ch[j];
ch[j]=m;
}
}
res=res+ch[i];
}
return res;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("enter the string");
String s1=sc.next();
String ans=Sort( s1);
System.out.println("after sorting=="+ans);
}
}
Output:
enter the string==
sorting
after sorting== ginorst
You can use CommonCrypto from iOS or CryptoSwift as external library. There are implementations with both tools below. That said, CommonCrypto output with AES should be tested, as it is not clear in CC documentation, which mode of AES it uses.
CommonCrypto in Swift 4.2
import CommonCrypto func encrypt(data: Data) -> Data { return cryptCC(data: data, key: key, operation: kCCEncrypt) } func decrypt(data: Data) -> Data { return cryptCC(data: data, key: key, operation: kCCDecrypt) } private func cryptCC(data: Data, key: String operation: Int) -> Data { guard key.count == kCCKeySizeAES128 else { fatalError("Key size failed!") } var ivBytes: [UInt8] var inBytes: [UInt8] var outLength: Int if operation == kCCEncrypt { ivBytes = [UInt8](repeating: 0, count: kCCBlockSizeAES128) guard kCCSuccess == SecRandomCopyBytes(kSecRandomDefault, ivBytes.count, &ivBytes) else { fatalError("IV creation failed!") } inBytes = Array(data) outLength = data.count + kCCBlockSizeAES128 } else { ivBytes = Array(Array(data).dropLast(data.count - kCCBlockSizeAES128)) inBytes = Array(Array(data).dropFirst(kCCBlockSizeAES128)) outLength = inBytes.count } var outBytes = [UInt8](repeating: 0, count: outLength) var bytesMutated = 0 guard kCCSuccess == CCCrypt(CCOperation(operation), CCAlgorithm(kCCAlgorithmAES128), CCOptions(kCCOptionPKCS7Padding), Array(key), kCCKeySizeAES128, &ivBytes, &inBytes, inBytes.count, &outBytes, outLength, &bytesMutated) else { fatalError("Cryptography operation \(operation) failed") } var outData = Data(bytes: &outBytes, count: bytesMutated) if operation == kCCEncrypt { ivBytes.append(contentsOf: Array(outData)) outData = Data(bytes: ivBytes) } return outData }
CryptoSwift v0.14 in Swift 4.2
enum Operation { case encrypt case decrypt } private let keySizeAES128 = 16 private let aesBlockSize = 16 func encrypt(data: Data, key: String) -> Data { return crypt(data: data, key: key, operation: .encrypt) } func decrypt(data: Data, key: String) -> Data { return crypt(data: data, key: key, operation: .decrypt) } private func crypt(data: Data, key: String, operation: Operation) -> Data { guard key.count == keySizeAES128 else { fatalError("Key size failed!") } var outData: Data? = nil if operation == .encrypt { var ivBytes = [UInt8](repeating: 0, count: aesBlockSize) guard 0 == SecRandomCopyBytes(kSecRandomDefault, ivBytes.count, &ivBytes) else { fatalError("IV creation failed!") } do { let aes = try AES(key: Array(key.data(using: .utf8)!), blockMode: CBC(iv: ivBytes)) let encrypted = try aes.encrypt(Array(data)) ivBytes.append(contentsOf: encrypted) outData = Data(bytes: ivBytes) } catch { print("Encryption error: \(error)") } } else { let ivBytes = Array(Array(data).dropLast(data.count - aesBlockSize)) let inBytes = Array(Array(data).dropFirst(aesBlockSize)) do { let aes = try AES(key: Array(key.data(using: .utf8)!), blockMode: CBC(iv: ivBytes)) let decrypted = try aes.decrypt(inBytes) outData = Data(bytes: decrypted) } catch { print("Decryption error: \(error)") } } return outData! }
As a one-liner into vim:
:set tabstop=4 shiftwidth=4
For permanent setup, add these lines to ~/.vimrc:
set tabstop=4
set shiftwidth=4
NOTE: Add set expandtab
if you prefer 4-spaces indentation, instead of a tab indentation.
Try ftp://test.rebex.net/
It is read-only used for testing Rebex components to list directory and download. Allows also to test FTP/SSL and IMAP.
Username is "demo", password is "password"
See https://test.rebex.net/ for more information.
If you only want to replace some characters you could use this:
import re
print re.sub(r'([\.\\\+\*\?\[\^\]\$\(\)\{\}\!\<\>\|\:\-])', r'\\\1', "example string.")
Note : This answer is now out-of-date. This changes the theme in "preview" only as @imjohnking and @john-ktejik pointed out. As @Shahzeb mentioned, theme can modified in res>values>styles
Android Studio 0.8.2 provides a slightly easier way to change the theme. In the preview window, you can select the theme of "Holo.Light.DarkActionBar" by clicking on the theme combo box just above the phone.
Or do a ctrl + click on the @style/AppTheme in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.
When using the Support Library, you must instead use the Theme.AppCompat themes:
Source http://forums.udacity.com/questions/100200635/choosing-theme-in-android-studio-08x
for (Project project : listOfLists) {
String nama_project = project.getNama_project();
if (project.getModelproject().size() > 1) {
for (int i = 1; i < project.getModelproject().size(); i++) {
DataModel model = project.getModelproject().get(i);
int id_laporan = model.getId();
String detail_pekerjaan = model.getAlamat();
}
}
}
Starting with Java 8, the general purpose solution for a primitive array arr
, and a value to search val
, is:
public static int indexOf(char[] arr, char val) {
return IntStream.range(0, arr.length).filter(i -> arr[i] == val).findFirst().orElse(-1);
}
This code creates a stream over the indexes of the array with IntStream.range
, filters the indexes to keep only those where the array's element at that index is equal to the value searched and finally keeps the first one matched with findFirst
. findFirst
returns an OptionalInt
, as it is possible that no matching indexes were found. So we invoke orElse(-1)
to either return the value found or -1
if none were found.
Overloads can be added for int[]
, long[]
, etc. The body of the method will remain the same.
For object arrays, like String[]
, we could use the same idea and have the filtering step using the equals
method, or Objects.equals
to consider two null
elements equal, instead of ==
.
But we can do it in a simpler manner with:
public static <T> int indexOf(T[] arr, T val) {
return Arrays.asList(arr).indexOf(val);
}
This creates a list wrapper for the input array using Arrays.asList
and searches the index of the element with indexOf
.
This solution does not work for primitive arrays, as shown here: a primitive array like int[]
is not an Object[]
but an Object
; as such, invoking asList
on it creates a list of a single element, which is the given array, not a list of the elements of the array.
From .NET 4.5 on, there is the Stream.CopyToAsync
method
input.CopyToAsync(output);
This will return a Task
that can be continued on when completed, like so:
await input.CopyToAsync(output)
// Code from here on will be run in a continuation.
Note that depending on where the call to CopyToAsync
is made, the code that follows may or may not continue on the same thread that called it.
The SynchronizationContext
that was captured when calling await
will determine what thread the continuation will be executed on.
Additionally, this call (and this is an implementation detail subject to change) still sequences reads and writes (it just doesn't waste a threads blocking on I/O completion).
From .NET 4.0 on, there's is the Stream.CopyTo
method
input.CopyTo(output);
For .NET 3.5 and before
There isn't anything baked into the framework to assist with this; you have to copy the content manually, like so:
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write (buffer, 0, read);
}
}
Note 1: This method will allow you to report on progress (x bytes read so far ...)
Note 2: Why use a fixed buffer size and not input.Length
? Because that Length may not be available! From the docs:
If a class derived from Stream does not support seeking, calls to Length, SetLength, Position, and Seek throw a NotSupportedException.
POCO stands for "Plain Old CLR Object".
What I ideally want to do is call LogTable.DeleteItem(user_id) - Without supplying the range, and have it delete everything for me.
An understandable request indeed; I can imagine advanced operations like these might get added over time by the AWS team (they have a history of starting with a limited feature set first and evaluate extensions based on customer feedback), but here is what you should do to avoid the cost of a full scan at least:
Use Query rather than Scan to retrieve all items for user_id
- this works regardless of the combined hash/range primary key in use, because HashKeyValue and RangeKeyCondition are separate parameters in this API and the former only targets the Attribute value of the hash component of the composite primary key..
Primary key of the item from which to continue an earlier query. An earlier query might provide this value as the LastEvaluatedKey if that query operation was interrupted before completing the query; either because of the result set size or the Limit parameter. The LastEvaluatedKey can be passed back in a new query request to continue the operation from that point.
Loop over all returned items and either facilitate DeleteItem as usual
As highlighted by ivant, the BatchWriteItem operation enables you to put or delete several items across multiple tables in a single API call [emphasis mine]:
To upload one item, you can use the PutItem API and to delete one item, you can use the DeleteItem API. However, when you want to upload or delete large amounts of data, such as uploading large amounts of data from Amazon Elastic MapReduce (EMR) or migrate data from another database in to Amazon DynamoDB, this API offers an efficient alternative.
Please note that this still has some relevant limitations, most notably:
Maximum operations in a single request — You can specify a total of up to 25 put or delete operations; however, the total request size cannot exceed 1 MB (the HTTP payload).
Not an atomic operation — Individual operations specified in a BatchWriteItem are atomic; however BatchWriteItem as a whole is a "best-effort" operation and not an atomic operation. That is, in a BatchWriteItem request, some operations might succeed and others might fail. [...]
Nevertheless this obviously offers a potentially significant gain for use cases like the one at hand.
There is no difference at all!
1) git checkout -b branch origin/branch
If there is no --track
and no --no-track
, --track
is assumed as default. The default can be changed with the setting branch.autosetupmerge
.
In effect, 1) behaves like git checkout -b branch --track origin/branch
.
2) git checkout --track origin/branch
“As a convenience”, --track
without -b
implies -b
and the argument to -b
is guessed to be “branch”. The guessing is driven by the configuration variable remote.origin.fetch
.
In effect, 2) behaves like git checkout -b branch --track origin/branch
.
As you can see: no difference.
But it gets even better:
3) git checkout branch
is also equivalent to git checkout -b branch --track origin/branch
if “branch” does not exist yet but “origin/branch” does1.
All three commands set the “upstream” of “branch” to be “origin/branch” (or they fail).
Upstream is used as reference point of argument-less git status
, git push
, git merge
and thus git pull
(if configured like that (which is the default or almost the default)).
E.g. git status
tells you how far behind or ahead you are of upstream, if one is configured.
git push
is configured to push the current branch upstream by default2 since git 2.0.
1 ...and if “origin” is the only remote having “branch”
2 the default (named “simple”) also enforces for both branch names to be equal
only css div you can center content
div{
display:table;
margin:0 auto;
}
You can also run docker build with -f
option
docker build -t ubuntu-test:latest -f Dockerfile.custom .
With the help of the of Guido mail provided by @kindall, we can understand the standard import process as trying to find the module in each member of sys.path
, and file as the result of this lookup (more details in PyMOTW Modules and Imports.). So if the module is located in an absolute path in sys.path
the result is absolute, but if it is located in a relative path in sys.path
the result is relative.
Now the site.py
startup file takes care of delivering only absolute path in sys.path
, except the initial ''
, so if you don't change it by other means than setting the PYTHONPATH (whose path are also made absolute, before prefixing sys.path
), you will get always an absolute path, but when the module is accessed through the current directory.
Now if you trick sys.path in a funny way you can get anything.
As example if you have a sample module foo.py
in /tmp/
with the code:
import sys
print(sys.path)
print (__file__)
If you go in /tmp you get:
>>> import foo
['', '/tmp', '/usr/lib/python3.3', ...]
./foo.py
When in in /home/user
, if you add /tmp
your PYTHONPATH
you get:
>>> import foo
['', '/tmp', '/usr/lib/python3.3', ...]
/tmp/foo.py
Even if you add ../../tmp
, it will be normalized and the result is the same.
But if instead of using PYTHONPATH
you use directly some funny path
you get a result as funny as the cause.
>>> import sys
>>> sys.path.append('../../tmp')
>>> import foo
['', '/usr/lib/python3.3', .... , '../../tmp']
../../tmp/foo.py
Guido explains in the above cited thread, why python do not try to transform all entries in absolute paths:
we don't want to have to call getpwd() on every import .... getpwd() is relatively slow and can sometimes fail outright,
So your path is used as it is.
Technically C# Extension have no equivalent in Java. But if you do want to implement such functions for a cleaner code and maintainability, you have to use Manifold framework.
package extensions.java.lang.String;
import manifold.ext.api.*;
@Extension
public class MyStringExtension {
public static void print(@This String thiz) {
System.out.println(thiz);
}
@Extension
public static String lineSeparator() {
return System.lineSeparator();
}
}
Exits the loop if the line is empty(Improving code).
#include <stdio.h>
#include <string.h>
// The value BUFFERSIZE can be changed to customer's taste . Changes the
// size of the base array (string buffer )
#define BUFFERSIZE 10
int main(void)
{
char buffer[BUFFERSIZE];
char cChar;
printf("Enter a message: \n");
while(*(fgets(buffer, BUFFERSIZE, stdin)) != '\n')
{
// For concatenation
// fgets reads and adds '\n' in the string , replace '\n' by '\0' to
// remove the line break .
/* if(buffer[strlen(buffer) - 1] == '\n')
buffer[strlen(buffer) - 1] = '\0'; */
printf("%s", buffer);
// Corrects the error mentioned by Alain BECKER.
// Checks if the string buffer is full to check and prevent the
// next character read by fgets is '\n' .
if(strlen(buffer) == (BUFFERSIZE - 1) && (buffer[strlen(buffer) - 1] != '\n'))
{
// Prevents end of the line '\n' to be read in the first
// character (Loop Exit) in the next loop. Reads
// the next char in stdin buffer , if '\n' is read and removed, if
// different is returned to stdin
cChar = fgetc(stdin);
if(cChar != '\n')
ungetc(cChar, stdin);
// To print correctly if '\n' is removed.
else
printf("\n");
}
}
return 0;
}
Exit when Enter is pressed.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#define BUFFERSIZE 16
int main(void)
{
char buffer[BUFFERSIZE];
printf("Enter a message: \n");
while(true)
{
assert(fgets(buffer, BUFFERSIZE, stdin) != NULL);
// Verifies that the previous character to the last character in the
// buffer array is '\n' (The last character is '\0') if the
// character is '\n' leaves loop.
if(buffer[strlen(buffer) - 1] == '\n')
{
// fgets reads and adds '\n' in the string, replace '\n' by '\0' to
// remove the line break .
buffer[strlen(buffer) - 1] = '\0';
printf("%s", buffer);
break;
}
printf("%s", buffer);
}
return 0;
}
Concatenation and dinamic allocation(linked list) to a single string.
/* Autor : Tiago Portela
Email : [email protected]
Sobre : Compilado com TDM-GCC 5.10 64-bit e LCC-Win32 64-bit;
Obs : Apenas tentando aprender algoritimos, sozinho, por hobby. */
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#define BUFFERSIZE 8
typedef struct _Node {
char *lpBuffer;
struct _Node *LpProxNode;
} Node_t, *LpNode_t;
int main(void)
{
char acBuffer[BUFFERSIZE] = {0};
LpNode_t lpNode = (LpNode_t)malloc(sizeof(Node_t));
assert(lpNode!=NULL);
LpNode_t lpHeadNode = lpNode;
char* lpBuffer = (char*)calloc(1,sizeof(char));
assert(lpBuffer!=NULL);
char cChar;
printf("Enter a message: \n");
// Exit when Enter is pressed
/* while(true)
{
assert(fgets(acBuffer, BUFFERSIZE, stdin)!=NULL);
lpNode->lpBuffer = (char*)malloc((strlen(acBuffer) + 1) * sizeof(char));
assert(lpNode->lpBuffer!=NULL);
strcpy(lpNode->lpBuffer, acBuffer);
if(lpNode->lpBuffer[strlen(acBuffer) - 1] == '\n')
{
lpNode->lpBuffer[strlen(acBuffer) - 1] = '\0';
lpNode->LpProxNode = NULL;
break;
}
lpNode->LpProxNode = (LpNode_t)malloc(sizeof(Node_t));
lpNode = lpNode->LpProxNode;
assert(lpNode!=NULL);
}*/
// Exits the loop if the line is empty(Improving code).
while(true)
{
assert(fgets(acBuffer, BUFFERSIZE, stdin)!=NULL);
lpNode->lpBuffer = (char*)malloc((strlen(acBuffer) + 1) * sizeof(char));
assert(lpNode->lpBuffer!=NULL);
strcpy(lpNode->lpBuffer, acBuffer);
if(acBuffer[strlen(acBuffer) - 1] == '\n')
lpNode->lpBuffer[strlen(acBuffer) - 1] = '\0';
if(strlen(acBuffer) == (BUFFERSIZE - 1) && (acBuffer[strlen(acBuffer) - 1] != '\n'))
{
cChar = fgetc(stdin);
if(cChar != '\n')
ungetc(cChar, stdin);
}
if(acBuffer[0] == '\n')
{
lpNode->LpProxNode = NULL;
break;
}
lpNode->LpProxNode = (LpNode_t)malloc(sizeof(Node_t));
lpNode = lpNode->LpProxNode;
assert(lpNode!=NULL);
}
printf("\nPseudo String :\n");
lpNode = lpHeadNode;
while(lpNode != NULL)
{
printf("%s", lpNode->lpBuffer);
lpNode = lpNode->LpProxNode;
}
printf("\n\nMemory blocks:\n");
lpNode = lpHeadNode;
while(lpNode != NULL)
{
printf("Block \"%7s\" size = %lu\n", lpNode->lpBuffer, (long unsigned)(strlen(lpNode->lpBuffer) + 1));
lpNode = lpNode->LpProxNode;
}
printf("\nConcatenated string:\n");
lpNode = lpHeadNode;
while(lpNode != NULL)
{
lpBuffer = (char*)realloc(lpBuffer, (strlen(lpBuffer) + strlen(lpNode->lpBuffer)) + 1);
strcat(lpBuffer, lpNode->lpBuffer);
lpNode = lpNode->LpProxNode;
}
printf("%s", lpBuffer);
printf("\n\n");
// Deallocate memory
lpNode = lpHeadNode;
while(lpNode != NULL)
{
lpHeadNode = lpNode->LpProxNode;
free(lpNode->lpBuffer);
free(lpNode);
lpNode = lpHeadNode;
}
lpBuffer = (char*)realloc(lpBuffer, 0);
lpBuffer = NULL;
if((lpNode == NULL) && (lpBuffer == NULL))
{
printf("Deallocate memory = %s", (char*)lpNode);
}
printf("\n\n");
return 0;
}
I prefer to convert the map to a JSON string it is:
supports nested complex types within the object
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public static String getAsFormattedJsonString(Object object)
{
ObjectMapper mapper = new ObjectMapper();
try
{
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
}
catch (JsonProcessingException e)
{
e.printStackTrace();
}
return "";
}
May be better for sql2005+ to use:
DELETE TOP (1000)
FROM [MyTab]
WHERE YourConditions
For Sql2000:
DELETE FROM [MyTab]
WHERE YourIdField IN
(
SELECT TOP 1000
YourIdField
FROM [MyTab]
WHERE YourConditions
)
BUT
If you want to delete specific subset of rows instead of arbitrary subset, you should explicitly specify order to subquery:
DELETE FROM [MyTab]
WHERE YourIdField IN
(
SELECT TOP 1000
YourIdField
FROM [MyTab]
WHERE YourConditions
ORDER BY ExplicitSortOrder
)
Thanks tp @gbn for mentioning and demanding the more clear and exact answer.
For hibernate it is important to know that your object WILL have an id, when you want to persist/save it. Thus, make sure that
private String U_id;
will have a value, by the time you are going to persist your object. You can do that with the @GeneratedValue
annotation or by assigning a value manually.
In the case you need or want to assign your id's manually (and that's what the above error is actually about), I would prefer passing the values for the fields to your constructor, at least for U_id
, e.g.
public Role (String U_id) { ... }
This ensures that your object has an id, by the time you have instantiated it. I don't know what your use case is and how your application behaves in concurrency, however, in some cases this is not recommended. You need to ensure that your id is unique.
Further note: Hibernate will still require a default constructor, as stated in the hibernate documentation. In order to prevent you (and maybe other programmers if you're designing an api) of instantiations of Role
using the default constructor, just declare it as private
.
for any extra column if there is no mapping then map it to null like the following SQL query
Select Col1, Col2, Col3, Col4, Col5 from Table1
Union
Select Col1, Col2, Col3, Null as Col4, Null as Col5 from Table2````
When you get a UnicodeEncodeError
, it means that somewhere in your code you convert directly a byte string to a unicode one. By default in Python 2 it uses ascii encoding, and utf8 encoding in Python3 (both may fail because not every byte is valid in either encoding)
To avoid that, you must use explicit decoding.
If you may have 2 different encoding in your input file, one of them accepts any byte (say UTF8 and Latin1), you can try to first convert a string with first and use the second one if a UnicodeDecodeError occurs.
def robust_decode(bs):
'''Takes a byte string as param and convert it into a unicode one.
First tries UTF8, and fallback to Latin1 if it fails'''
cr = None
try:
cr = bs.decode('utf8')
except UnicodeDecodeError:
cr = bs.decode('latin1')
return cr
If you do not know original encoding and do not care for non ascii character, you can set the optional errors
parameter of the decode
method to replace
. Any offending byte will be replaced (from the standard library documentation):
Replace with a suitable replacement character; Python will use the official U+FFFD REPLACEMENT CHARACTER for the built-in Unicode codecs on decoding and ‘?’ on encoding.
bs.decode(errors='replace')
On the basic question of why openssl is not found: Short answer:Some installation packages for openssl have a default openssl.cnf pre-included. Other packages do not. In the latter case you will include one from the link shown below; You can enter additional user-specifics --DN name,etc-- as needed.
From https://www.openssl.org/docs/manmaster/man5/config.html,I quote directly:
"OPENSSL LIBRARY CONFIGURATION
Applications can automatically configure certain aspects of OpenSSL using the master OpenSSL configuration file, or optionally an alternative configuration file. The openssl utility includes this functionality: any sub command uses the master OpenSSL configuration file unless an option is used in the sub command to use an alternative configuration file.
To enable library configuration the default section needs to contain an appropriate line which points to the main configuration section. The default name is openssl_conf which is used by the openssl utility. Other applications may use an alternative name such as myapplication_conf. All library configuration lines appear in the default section at the start of the configuration file.
The configuration section should consist of a set of name value pairs which contain specific module configuration information. The name represents the name of the configuration module. The meaning of the value is module specific: it may, for example, represent a further configuration section containing configuration module specific information. E.g.:"
So it appears one must self configure openssl.cnf according to your Distinguished Name (DN), along with other entries specific to your use.
Here is the template file from which you can generate openssl.cnf with your specific entries.
One Application actually has a demo installation that includes a demo .cnf file.
Additionally, if you need to programmatically access .cnf files, you can include appropriate headers --openssl/conf.h-- and parse your .cnf files using
CONF_modules_load_file(const char *filename, const char *appname,
unsigned long flags);
Here are docs for "CONF_modules_load_file";
There are various ways to make it done, very simple technique with security peace in mind, here might help you
1. First you need to install Flask
pip install flask
in your command prompt, which is a python microframework, don't be afraid that you need to have another prior knowledge to learn that, it's really simple and just a few line of code.
If you wish you learn Flask quickly for complete novice here is the tutorial that I also learn from Flask Tutorial for beginner (YouTube)
2.Create a new folder
- 1st file will be
server.py
from flask import Flask, render_template_x000D_
app = Flask(__name__)_x000D_
_x000D_
@app.route('/')_x000D_
def index():_x000D_
return render_template('index.html')_x000D_
_x000D_
@app.route('/my-link/')_x000D_
def my_link():_x000D_
print ('I got clicked!')_x000D_
_x000D_
return 'Click.'_x000D_
_x000D_
if __name__ == '__main__':_x000D_
app.run(debug=True)
_x000D_
-2nd create another subfolder inside previous folder and name it as templates file will be your html file
index.html
<!doctype html>_x000D_
_x000D_
_x000D_
<head><title>Test</title> _x000D_
<meta charset=utf-8> </head>_x000D_
<body>_x000D_
<h1>My Website</h1>_x000D_
<form action="/my-link/">_x000D_
<input type="submit" value="Click me" />_x000D_
</form>_x000D_
_x000D_
<button> <a href="/my-link/">Click me</a></button>_x000D_
_x000D_
</body>
_x000D_
3.. To run, open command prompt to the New folder directory, type python server.py
to run the script, then go to browser type localhost:5000
, then you will see button. You can click and route to destination script file you created.
Hope this helpful. thank you.
Download the developer edition. There you can choose Express as license when installing.
None of the other solutions worked on Visual Studio for Mac
If you are using NUnit, you can add a small .NET
Console Project to your solution, and then reference the project you wish to test in the References of that new Console Project.
Whatever you were doing in your [Test()]
methods can be done in the Main
of the console application in this fashion:
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Console");
// Reproduce the unit test
var classToTest = new ClassToTest();
var expected = 42;
var actual = classToTest.MeaningOfLife();
Console.WriteLine($"Pass: {expected.Equals(actual)}, expected={expected}, actual={actual}");
}
}
You are free to use Console.Write
and Console.WriteLine
in your code under these circumstances.
This method works well for me. I use ISNULL() for the primary key field, and COALESCE() if the field should not be the primary key, but should also have a non-nullable value. This example yields ID field with a non-nullable primary key. The other fields are not keys, and have (None) as their Nullable attribute.
SELECT
ISNULL(P.ID, - 1) AS ID,
COALESCE (P.PurchaseAgent, U.[User Nickname]) AS PurchaseAgent,
COALESCE (P.PurchaseAuthority, 0) AS PurchaseAuthority,
COALESCE (P.AgencyCode, '') AS AgencyCode,
COALESCE (P.UserID, U.ID) AS UserID,
COALESCE (P.AssignPOs, 'false') AS AssignPOs,
COALESCE (P.AuthString, '') AS AuthString,
COALESCE (P.AssignVendors, 'false') AS AssignVendors
FROM Users AS U
INNER JOIN Users AS AU ON U.Login = AU.UserName
LEFT OUTER JOIN PurchaseAgents AS P ON U.ID = P.UserID
if you really don't have a primary key, you can spoof one by using ROW_NUMBER to generate a pseudo-key that is ignored by your code. For example:
SELECT
ROW_NUMBER() OVER(ORDER BY A,B) AS Id,
A, B
FROM SOMETABLE
If you don't give any position to parent then by default it takes static
. If you want to understand that difference refer to this example
Example 1::
#mainall
{
background-color:red;
height:150px;
overflow:scroll
}
Here parent class has no position so element is placed according to body.
Example 2::
#mainall
{
position:relative;
background-color:red;
height:150px;
overflow:scroll
}
In this example parent has relative position hence element are positioned absolute inside relative parent.
One of the main feature of Bootstrap is that it alleviates the use of !important tag. Using the above answer would defeat the purpose. You can easily customise bootstrap by modifying the classes in your own css file and linking it after including the boostrap css.
You can split and join the string, but why not use substrings? Then you only end up with one split instead of splitting the string into 5 parts and re-joining it. The end result is the same, but the substring is probably a bit faster.
string lcStart = "Some Very Large String Here";
int lnSpace = lcStart.IndexOf(' ');
if (lnSpace > -1)
{
string lcFirst = lcStart.Substring(0, lnSpace);
string lcRest = lcStart.Substring(lnSpace + 1);
}
https://jsfiddle.net/sudheernunna/tug98nfm/1/
var days = {};
days["monday"] = true;
days["tuesday"] = true;
days["wednesday"] = false;
days["thursday"] = true;
days["friday"] = false;
days["saturday"] = true;
days["sunday"] = false;
var userfalse=0,usertrue=0;
for(value in days)
{
if(days[value]){
usertrue++;
}else{
userfalse++;
}
console.log(days[value]);
}
alert("false",userfalse);
alert("true",usertrue);
The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.
For example,
Begin Transaction
-Do some T-SQL queries here.
Rollback transaction -- OR commit transaction
If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.
For example:
USE AdventureWorks;
GO
BEGIN TRANSACTION;
BEGIN TRY
-- Generate a constraint violation error.
DELETE FROM Production.Product
WHERE ProductID = 980;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
GO
See the following link for more details.
http://msdn.microsoft.com/en-us/library/ms175976.aspx
Hope this helps but please let me know if you need more details.
Task.GetAwaiter().GetResult()
is preferred over Task.Wait
and Task.Result
because it propagates exceptions rather than wrapping them in an AggregateException
. However, all three methods cause the potential for deadlock and thread pool starvation issues. They should all be avoided in favor of async/await
.
The quote below explains why Task.Wait
and Task.Result
don't simply contain the exception propagation behavior of Task.GetAwaiter().GetResult()
(due to a "very high compatibility bar").
As I mentioned previously, we have a very high compatibility bar, and thus we’ve avoided breaking changes. As such,
Task.Wait
retains its original behavior of always wrapping. However, you may find yourself in some advanced situations where you want behavior similar to the synchronous blocking employed byTask.Wait
, but where you want the original exception propagated unwrapped rather than it being encased in anAggregateException
. To achieve that, you can target the Task’s awaiter directly. When you write “await task;
”, the compiler translates that into usage of theTask.GetAwaiter()
method, which returns an instance that has aGetResult()
method. When used on a faulted Task,GetResult()
will propagate the original exception (this is how “await task;
” gets its behavior). You can thus use “task.GetAwaiter().GetResult()
” if you want to directly invoke this propagation logic.
https://blogs.msdn.microsoft.com/pfxteam/2011/09/28/task-exception-handling-in-net-4-5/
“
GetResult
” actually means “check the task for errors”In general, I try my best to avoid synchronously blocking on an asynchronous task. However, there are a handful of situations where I do violate that guideline. In those rare conditions, my preferred method is
GetAwaiter().GetResult()
because it preserves the task exceptions instead of wrapping them in anAggregateException
.
http://blog.stephencleary.com/2014/12/a-tour-of-task-part-6-results.html
To clone only one single specific commit on a particular branch or tag use:
git clone --depth=1 --branch NAME https://github.com/your/repo.git
Unfortunately, NAME
can only be branch name or tag name (not commit SHA).
Omit the --depth
flag to download the whole history and then checkout that branch or tag:
git clone --branch NAME https://github.com/your/repo.git
This works with recent version of git (I did it with version 2.18.0
).
Well to create Directory/folder in java we have two methods
Here makedirectory method creates single directory if it does not exist.
File dir = new File("path name");
boolean isCreated = dir.mkdir();
And
File dir = new File("path name");
boolean isCreated = dir.mkdirs();
Here makedirectories method will create all directories that are missing in the path which the file object represent.
For example refer link below (explained very well). Hope it helps!! https://www.flowerbrackets.com/create-directory-java-program/
What you are describing is a change of state in the parent. You pass that to the child via a prop. As you suggested, you would watch
that prop. When the child takes action, it notifies the parent via an emit
, and the parent might then change the state again.
var Child = {_x000D_
template: '<div>{{counter}}</div>',_x000D_
props: ['canI'],_x000D_
data: function () {_x000D_
return {_x000D_
counter: 0_x000D_
};_x000D_
},_x000D_
watch: {_x000D_
canI: function () {_x000D_
if (this.canI) {_x000D_
++this.counter;_x000D_
this.$emit('increment');_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
new Vue({_x000D_
el: '#app',_x000D_
components: {_x000D_
'my-component': Child_x000D_
},_x000D_
data: {_x000D_
childState: false_x000D_
},_x000D_
methods: {_x000D_
permitChild: function () {_x000D_
this.childState = true;_x000D_
},_x000D_
lockChild: function () {_x000D_
this.childState = false;_x000D_
}_x000D_
}_x000D_
})
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.js"></script>_x000D_
<div id="app">_x000D_
<my-component :can-I="childState" v-on:increment="lockChild"></my-component>_x000D_
<button @click="permitChild">Go</button>_x000D_
</div>
_x000D_
If you truly want to pass events to a child, you can do that by creating a bus (which is just a Vue instance) and passing it to the child as a prop.
Refer to here
write query with named parameter, use simple ListPreparedStatementSetter
with all parameters in sequence. Just add below snippet to convert the query in traditional form based to available parameters,
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);
List<Integer> parameters = new ArrayList<Integer>();
for (A a : paramBeans)
parameters.add(a.getId());
MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("placeholder1", parameters);
// create SQL with ?'s
String sql = NamedParameterUtils.substituteNamedParameters(parsedSql, parameterSource);
return sql;
To anyone that wants to Fast Forward they are not on to another remote branch (including itself) without checking out that branch, you can do:
git fetch origin master:other
This basically fast forwards the index of other
to origin/master
if you are not on other
branch. You can fast forward multiple branches this way.
If you working on another branch for some time, and wanted to update stale branches from remote to their respective head:
git fetch origin master:master other:other etc:etc
PRIMARY KEY (id, name)
didn't work for me. Adding a constraint did the job instead.
CREATE TABLE IF NOT EXISTS customer (
id INTEGER, name TEXT,
user INTEGER,
CONSTRAINT PK_CUSTOMER PRIMARY KEY (user, id)
)
This is the example code taken from the PHP documentation here: https://www.php.net/manual/en/function.filemtime.php
// outputs e.g. somefile.txt was last changed: December 29 2002 22:16:23.
$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
The code specifies the filename, then checks if it exists and then displays the modification time using filemtime()
.
filemtime()
takes 1 parameter which is the path to the file, this can be relative or absolute.
If you want to round the decimal, look at Math.Round()
I had the same program, I hope this could help.
I your using Windows 7, open Command Prompt-> run as Administrator. register your <...>.dll.
Why run as Administrator, you can register your <...>.dll using the run at the Windows Start, but still your dll only run as user even your account is administrator.
Now you can add your <...>.dll at the Project->Add Reference->Browse
Thanks
Try:
SELECT DATE(`date_time_field`) AS date_part, TIME(`date_time_field`) AS time_part FROM `your_table`
Add a column to the query which can sub identify the data to sort on that.
In the below example I use a Common Table Expression with the selects you showed which places them in specific groups in the CTE, and then do a union
off of both of those groups into AllStudents
.
The final select will then sort AllStudents
by the SortIndex
column first and then by the name
such as:
WITH Juveniles as
(
Select 1 as [SortIndex], id,name,age From Student
Where age < 15
),
AStudents as
(
Select 2 as [SortIndex], id,name,age From Student
Where Name like "%a%"
),
AllStudents as
(
select * from Juveniles
union
select * from AStudents
)
select * from AllStudents
sort by [SortIndex], name;
To summarize, it will get all the students which will be sorted by group first, and subsorted by the name within the group after that.
You're trying to put a text node inside an input element.
Input elements are empty and can't have children.
...
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "id";
var label = document.createElement('label')
label.htmlFor = "id";
label.appendChild(document.createTextNode('text for label after checkbox'));
container.appendChild(checkbox);
container.appendChild(label);
Very edge case, but I had to use a program that worked correctly only when I specified
StartInfo = {..., RedirectStandardOutput = true}
Not specifying it would result in an error. There was not even the need to read the output afterward.
lst *= 0
has the same effect as
lst[:] = []
It's a little simpler and maybe easier to remember. Other than that there's not much to say
The efficiency seems to be about the same
Not knowing how the OP happened to have {" String", "Tom Selleck "," Fish "}
in an array in the first place (6 years ago), I thought I'd share what I ended up with.
My array is the result of using split on a string which might have extra spaces around delimiters. My solution was to address this at the point of the split. My code follows. After testing, I put splitWithTrim() in my Utils class of my project. It handles my use case; you might want to consider what sorts of strings and delimiters you might encounter if you decide to use it.
public class Test {
public static void main(String[] args) {
test(" abc def ghi jkl ", " ");
test(" abc; def ;ghi ; jkl; ", ";");
}
public static void test(String str, String splitOn) {
System.out.println("Splitting \"" + str + "\" on \"" + splitOn + "\"");
String[] parts = splitWithTrim(str, splitOn);
for (String part : parts) {
System.out.println("(" + part + ")");
}
}
public static String[] splitWithTrim(String str, String splitOn) {
if (splitOn.equals(" ")) {
return str.trim().split(" +");
} else {
return str.trim().split(" *" + splitOn + " *");
}
}
}
Output of running the test application is:
Splitting " abc def ghi jkl " on " "
(abc)
(def)
(ghi)
(jkl)
Splitting " abc; def ;ghi ; jkl; " on ";"
(abc)
(def)
(ghi)
(jkl)
It seems the problem can arise from more than one reasons. Following two steps worked when I was having same error.
Globbing uses brackets, hence the need to escape them with a slash \
. Alternatively, the following command-line switch will disable globbing:
--globoff
(or the short-option version: -g
)
Ex:
curl --globoff https://www.google.com?test[]=1
I was able to get this to work by using the Invoke-Expression
cmdlet.
Invoke-Expression "& `"$scriptPath`" test -r $number -b $testNumber -f $FileVersion -a $ApplicationID"
Easiest workaround is Just change the table name and all column names to lowercase and your issue will be resolved.
For example:
Table_Name
to table_name
and ColumnName
to columnname
Often you will want to specify a manifest, like so:
jar -cvfm myJar.jar myManifest.txt myApp.class
Which reads: "create verbose jarFilename manifestFilename", followed by the files you want to include. Verbose means print messages about what it's doing.
Note that the name of the manifest file you supply can be anything, as jar
will automatically rename it and put it into the right directory within the jar file.
It's not only a Python bug with * actually, it can also happen when you pass a string as a part of your regular expression to be compiled, like ;
import re
input_line = "string from any input source"
processed_line= "text to be edited with {}".format(input_line)
target = "text to be searched"
re.search(processed_line, target)
this will cause an error if processed line contained some "(+)" for example, like you can find in chemical formulae, or such chains of characters. the solution is to escape but when you do it on the fly, it can happen that you fail to do it properly...
If you are looking for readability, I believe that this is that code:
print '%(kg).2f kg = %(lb).2f lb = %(gal).2f gal = %(l).2f l' % {
'kg': var1,
'lb': var2,
'gal': var3,
'l': var4,
}
you can take care of the first 3 items with slicing and head:
df[df.A>=4].head(1)
df[(df.A>=4)&(df.B>=3)].head(1)
df[(df.A>=4)&((df.B>=3) * (df.C>=2))].head(1)
The condition in case nothing comes back you can handle with a try or an if...
try:
output = df[df.A>=6].head(1)
assert len(output) == 1
except:
output = df.sort_values('A',ascending=False).head(1)
This error will also occur when using pdsh to hosts which are not contained in your "known_hosts" file.
I was able to correct this by SSH'ing into each host manually and accepting the question "Do you want to add this to known hosts".
If we are using apache commons logging wrapper on top of log4j, then we need to have both the jars available in classpath. Also, commons-logging.properties
and log4j.properties/xml
should be available in classpath.
We can also pass implementation class and log4j.properties
name as JAVA_OPTS
either using -Dorg.apache.commons.logging.Log=<logging implementation class name> -Dlog4j.configuration=<file:location of log4j.properties/xml file>
. Same can be done via setting JAVA_OPTS
in case of app/web server.
It will help to externalize properties which can be changed in deployment.
There's simpler solution for that - set fixed height of card elements - header and body. This way, we can set resposive layout with standard boostrap column grid.
Here is my example: http://codeply.com/go/RHDawRSBol
<div class="card-deck text-center">
<div class="col-sm-6 col-md-4 col-lg-3">
<div class="card mb-4">
<img class="card-img-top img-fluid" src="//placehold.it/500x280" alt="Card image cap">
<div class="card-body" style="height: 20rem">
<h4 class="card-title">1 Card title</h4>
<p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
</div>
</div>
Christophe,
The default value on a column is only applied if you don't specify the column in the INSERT statement.
Since you're explicitiy listing the column in your insert statement, and explicity setting it to NULL, that's overriding the default value for that column
What you need to do is "if a null is passed into your sproc then don't attempt to insert for that column".
This is a quick and nasty example of how to do that with some dynamic sql.
Create a table with some columns with default values...
CREATE TABLE myTable (
always VARCHAR(50),
value1 VARCHAR(50) DEFAULT ('defaultcol1'),
value2 VARCHAR(50) DEFAULT ('defaultcol2'),
value3 VARCHAR(50) DEFAULT ('defaultcol3')
)
Create a SPROC that dynamically builds and executes your insert statement based on input params
ALTER PROCEDURE t_insert (
@always VARCHAR(50),
@value1 VARCHAR(50) = NULL,
@value2 VARCHAR(50) = NULL,
@value3 VARCAHR(50) = NULL
)
AS
BEGIN
DECLARE @insertpart VARCHAR(500)
DECLARE @valuepart VARCHAR(500)
SET @insertpart = 'INSERT INTO myTable ('
SET @valuepart = 'VALUES ('
IF @value1 IS NOT NULL
BEGIN
SET @insertpart = @insertpart + 'value1,'
SET @valuepart = @valuepart + '''' + @value1 + ''', '
END
IF @value2 IS NOT NULL
BEGIN
SET @insertpart = @insertpart + 'value2,'
SET @valuepart = @valuepart + '''' + @value2 + ''', '
END
IF @value3 IS NOT NULL
BEGIN
SET @insertpart = @insertpart + 'value3,'
SET @valuepart = @valuepart + '''' + @value3 + ''', '
END
SET @insertpart = @insertpart + 'always) '
SET @valuepart = @valuepart + + '''' + @always + ''')'
--print @insertpart + @valuepart
EXEC (@insertpart + @valuepart)
END
The following 2 commands should give you an example of what you want as your outputs...
EXEC t_insert 'alwaysvalue'
SELECT * FROM myTable
EXEC t_insert 'alwaysvalue', 'val1'
SELECT * FROM myTable
EXEC t_insert 'alwaysvalue', 'val1', 'val2', 'val3'
SELECT * FROM myTable
I know this is a very convoluted way of doing what you need to do. You could probably equally select the default value from the InformationSchema for the relevant columns but to be honest, I might consider just adding the default value to param at the top of the procedure
Go to Project> Properties> C/C++ Build> Environment. You will see three fields, choose PATH. See if the folder containing make.exe is appended to the path or not. Sometimes the change to the System PATH variable (made from My Computer> Properties> Advanced System Settings...) is NOT reflected in Eclipse. This solved the problem for me, hope it helps you too!
I would like to emphasize @icza answer and simplify it a bit since it is a crucial concept. I assume that reader is familiar with slices.
c := append(a, b...)
This is a valid answer to the question. BUT if you need to use slices 'a' and 'c' later in code in different context, this is not the safe way to concatenate slices.
To explain, lets read the expression not in terms of slices, but in terms of underlying arrays:
"Take (underlying) array of 'a' and append elements from array 'b' to it. If array 'a' has enough capacity to include all elements from 'b' - underlying array of 'c' will not be a new array, it will actually be array 'a'. Basically, slice 'a' will show len(a) elements of underlying array 'a', and slice 'c' will show len(c) of array 'a'."
append() does not necessarily create a new array! This can lead to unexpected results. See Go Playground example.
Always use make() function if you want to make sure that new array is allocated for the slice. For example here are few ugly but efficient enough options for the task.
la := len(a)
c := make([]int, la, la + len(b))
_ = copy(c, a)
c = append(c, b...)
la := len(a)
c := make([]int, la + len(b))
_ = copy(c, a)
_ = copy(c[la:], b)
Since the rules are running in JavaScript, why not disable them using javascript (or in my examples case, jQuery)?
$('#fieldId').attr('disabled', 'disabled'); //Disable
$('#fieldId').removeAttr('disabled'); //Enable
UPDATE
The attr
function is no longer the primary approach to this, as was pointed out in the comments below. This is now done with the prop
function.
$( "input" ).prop( "disabled", true ); //Disable
$( "input" ).prop( "disabled", false ); //Enable
As this is the top post if you google for MySQL high CPU usage or load, I'll add an additional answer:
On the 1st of July 2012, a leap second was added to the current UTC-time to compensate for the slowing rotation of the earth due to the tides. When running ntp (or ntpd) this second was added to your computer's/server's clock. MySQLd does not seem to like this extra second on some OS'es, and yields a high CPU load. The quick fix is (as root):
$ /etc/init.d/ntpd stop
$ date -s "`date`"
$ /etc/init.d/ntpd start
In Typescript and ES6 you can also use for..of:
for (var product of products) {
console.log(product.product_desc)
}
which will be transcoded to javascript:
for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
var product = products_1[_i];
console.log(product.product_desc);
}
instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0;
once your window has scrolled pass a certain height:
jQuery
$(window).scroll(function(){
if ($(this).scrollTop() > 135) {
$('#task_flyout').addClass('fixed');
} else {
$('#task_flyout').removeClass('fixed');
}
});
css
.fixed {position:fixed; top:0; left:0;}
IIS7 defines a defaultDocument section in its configuration files which can be found in the %WinDir%\System32\InetSrv\Config folder. Most likely, the file index.aspx is already defined as a default document in one of IIS7's configuration files and you are adding it again in your web.config.
I suspect that removing the line
<add value="index.aspx" />
from the defaultDocument/files section will fix your issue.
The defaultDocument section of your config will look like:
<defaultDocument>
<files>
<remove value="default.aspx" />
<remove value="index.html" />
<remove value="iisstart.htm" />
<remove value="index.htm" />
<remove value="Default.asp" />
<remove value="Default.htm" />
</files>
</defaultDocument>
Note that index.aspx will still appear in the list of default documents for your site in the IIS manager.
For more information about IIS7 configuration, click here.
The short answer is YES. lucky you!
To do so, you need to override some styles of the Android default styles :
First, look at the definition of the themes in Android :
<style name="Theme.IconMenu">
<!-- Menu/item attributes -->
<item name="android:itemTextAppearance">@android:style/TextAppearance.Widget.IconMenu.Item</item>
<item name="android:itemBackground">@android:drawable/menu_selector</item>
<item name="android:itemIconDisabledAlpha">?android:attr/disabledAlpha</item>
<item name="android:horizontalDivider">@android:drawable/divider_horizontal_bright</item>
<item name="android:verticalDivider">@android:drawable/divider_vertical_bright</item>
<item name="android:windowAnimationStyle">@android:style/Animation.OptionsPanel</item>
<item name="android:moreIcon">@android:drawable/ic_menu_more</item>
<item name="android:background">@null</item>
</style>
So, the appearance of the text in the menu is in @android:style/TextAppearance.Widget.IconMenu.Item
Now, in the definition of the styles :
<style name="TextAppearance.Widget.IconMenu.Item" parent="TextAppearance.Small">
<item name="android:textColor">?textColorPrimaryInverse</item>
</style>
So now we have the name of the color in question, if you look in the color folder of the resources of the system :
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="@android:color/bright_foreground_light_disabled" />
<item android:state_window_focused="false" android:color="@android:color/bright_foreground_light" />
<item android:state_pressed="true" android:color="@android:color/bright_foreground_light" />
<item android:state_selected="true" android:color="@android:color/bright_foreground_light" />
<item android:color="@android:color/bright_foreground_light" />
<!-- not selected -->
</selector>
Finally, here is what you need to do :
Override "TextAppearance.Widget.IconMenu.Item" and create your own style. Then link it to your own selector to make it the way you want. Hope this helps you. Good luck!
Try something like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
}
The exception is in the $_
variable. You might explore $_
like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
$_ | fl * -Force
}
I think it will give you all the info you need.
My rule: if there is some data that is not displayed, try to use -force
.
One simple thing you could do is abstract the test inside a function.
local function isempty(s)
return s == nil or s == ''
end
if isempty(foo) then
foo = "default value"
end
dgv.Columns[0].HeaderText = "Your Header";
http://allu.wordpress.com/2006/11/08/difference-between-final-finally-and-finalize/
final – constant declaration.
finally – The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
finalize() – method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.
Did you try searching on google, and need clarification for an explanation?
If you have the capability to do so, I would recommend using either mod-jk or mod-proxy-ajp to pass requests from Apache to JBoss. The AJP protocol is much more efficient compared to using HTTP proxy requests and as a benefit, JBoss will see the request as coming from the original client and not Apache.
Sadly, Java 8 did not introduce pairs or tuples. You can always use org.apache.commons.lang3.tuple of course (which personally I do use in combination with Java 8) or you can create your own wrappers. Or use Maps. Or stuff like that, as is explained in the accepted answer to that question you linked to.
UPDATE: JDK 14 is introducing records as a preview feature. These aren't tuples, but can be used to save many of the same problems. In your specific example from above, that could look something like this:
public class Jdk14Example {
record CountForIndex(int index, long count) {}
public static void main(String[] args) {
boolean [][] directed_acyclic_graph = new boolean[][]{
{false, true, false, true, false, true},
{false, false, false, true, false, true},
{false, false, false, true, false, true},
{false, false, false, false, false, true},
{false, false, false, false, false, true},
{false, false, false, false, false, false}
};
System.out.println(
IntStream.range(0, directed_acyclic_graph.length)
.parallel()
.mapToObj(i -> {
long count = IntStream.range(0, directed_acyclic_graph[i].length)
.filter(j -> directed_acyclic_graph[j][i])
.count();
return new CountForIndex(i, count);
}
)
.filter(n -> n.count == 0)
.collect(() -> new ArrayList<CountForIndex>(), (c, e) -> c.add(e), (c1, c2) -> c1.addAll(c2))
);
}
}
When compiled and run with JDK 14 (at the time of writing, this an early access build) using the --enable-preview
flag, you get the following result:
[CountForIndex[index=0, count=0], CountForIndex[index=2, count=0], CountForIndex[index=4, count=0]]
I was looking for a solution for the nvm prefix problem a found this question(before finding the solution). Here is my shell "dialog". I hope, it can be usefull for somebody. I was able to set to prefix with the help of this post: https://github.com/npm/npm/issues/6592
When I tried npm config delete prefix
or nvm use --delete-prefix
before using npm --prefix="" set prefix ""
, I got only:
npm ERR! not ok code 0
Note that you will have to repeat the same procedure with every node version, the prefix is set back to (in my case) /usr/local after installation.
$ nvm install 0.10
######################################################################## 100.0%
nvm is not compatible with the npm config "prefix" option: currently set to "/usr/local"
Run `npm config delete prefix` or `nvm use --delete-prefix v0.10.44` to unset it.
$ npm --prefix="" set prefix ""
$ nvm use 0.10.44
nvm is not compatible with the npm config "prefix" option: currently set to "/home/john"
Run `npm config delete prefix` or `nvm use --delete-prefix v0.10.44` to unset it.
$ nvm use --delete-prefix v0.10.44
Now using node v0.10.44 (npm v1.3.10)
$ nvm ls
v0.10.44
v4.4.3
-> system
default -> 4.4.3 (-> v4.4.3)
node -> stable (-> v4.4.3) (default)
stable -> 4.4 (-> v4.4.3) (default)
iojs -> N/A (default)
$ npm config get prefix
/usr/local
You can use the sprintf
method, however the arg
method is preferred as it supports unicode.
QString str;
str.sprintf("%s %d", "string", 213);
For sake of simplicity, maybe you should consider using the Requests library.
An example with json response content would be something like:
import requests
r = requests.get('https://github.com/timeline.json')
r.json()
If you look for further information, in the Quickstart section, they have lots of working examples.
EDIT:
For your specific curl translation:
import requests
url = 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere'
payload = open("request.json")
headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'}
r = requests.post(url, data=payload, headers=headers)
It is now possible with the HTML5 webapp manifest. See below.
Original answer:
You can't lock a website or a web application in a specific orientation. It goes against the natural behaviour of the device.
You can detect the device orientation with CSS3 media queries like this:
@media screen and (orientation:portrait) {
// CSS applied when the device is in portrait mode
}
@media screen and (orientation:landscape) {
// CSS applied when the device is in landscape mode
}
Or by binding a JavaScript orientation change event like this:
document.addEventListener("orientationchange", function(event){
switch(window.orientation)
{
case -90: case 90:
/* Device is in landscape mode */
break;
default:
/* Device is in portrait mode */
}
});
Update on November 12, 2014: It is now possible with the HTML5 webapp manifest.
As explained on html5rocks.com, you can now force the orientation mode using a manifest.json
file.
You need to include those line into the json file:
{
"display": "standalone", /* Could be "fullscreen", "standalone", "minimal-ui", or "browser" */
"orientation": "landscape", /* Could be "landscape" or "portrait" */
...
}
And you need to include the manifest into your html file like this:
<link rel="manifest" href="manifest.json">
Not exactly sure what the support is on the webapp manifest for locking orientation mode, but Chrome is definitely there. Will update when I have the info.
If your form tag is like
<form action="" method="post" id="BookPackageForm">
Then fetch the form element by using forms object.
var formEl = document.forms.BookPackageForm;
Get the data from the form by using FormData objects.
var formData = new FormData(formEl);
Get the value of the fields by the form data object.
var name = formData.get('name');
INSERT INTO Table
( Event_ID
, col2
...
)
SELECT "155"
, col2
...
FROM Table WHERE Event_ID = "120"
Here, the col2, ... represent the remaining columns (the ones other than Event_ID) in your table.
You can try using jQuery with the Attribute Contains Prefix Selector.
$('[id|=q1_]')
Haven't tested it though.
GLM has good example of rotation : http://glm.g-truc.net/code.html
glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.f);
glm::mat4 ViewTranslate = glm::translate(
glm::mat4(1.0f),
glm::vec3(0.0f, 0.0f, -Translate)
);
glm::mat4 ViewRotateX = glm::rotate(
ViewTranslate,
Rotate.y,
glm::vec3(-1.0f, 0.0f, 0.0f)
);
glm::mat4 View = glm::rotate(
ViewRotateX,
Rotate.x,
glm::vec3(0.0f, 1.0f, 0.0f)
);
glm::mat4 Model = glm::scale(
glm::mat4(1.0f),
glm::vec3(0.5f)
);
glm::mat4 MVP = Projection * View * Model;
glUniformMatrix4fv(LocationMVP, 1, GL_FALSE, glm::value_ptr(MVP));
The vroom package provides a 'tidy' method of selecting / dropping columns by name during import. Docs: https://www.tidyverse.org/blog/2019/05/vroom-1-0-0/#column-selection
The vroom argument 'col_select' makes selecting columns to keep (or omit) more straightforward. The interface for col_select is the same as dplyr::select().
Select columns by namedata <- vroom("flights.tsv", col_select = c(year, flight, tailnum))
#> Observations: 336,776
#> Variables: 3
#> chr [1]: tailnum
#> dbl [2]: year, flight
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Drop columns by name
data <- vroom("flights.tsv", col_select = c(-dep_time, -air_time:-time_hour))
#> Observations: 336,776
#> Variables: 13
#> chr [4]: carrier, tailnum, origin, dest
#> dbl [9]: year, month, day, sched_dep_time, dep_delay, arr_time, sched_arr_time, arr...
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Use the selection helpers
data <- vroom("flights.tsv", col_select = ends_with("time"))
#> Observations: 336,776
#> Variables: 5
#> dbl [5]: dep_time, sched_dep_time, arr_time, sched_arr_time, air_time
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Or rename columns by name
data <- vroom("flights.tsv", col_select = list(plane = tailnum, everything()))
#> Observations: 336,776
#> Variables: 19
#> chr [ 4]: carrier, tailnum, origin, dest
#> dbl [14]: year, month, day, dep_time, sched_dep_time, dep_delay, arr_time, sched_arr...
#> dttm [ 1]: time_hour
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
data
#> # A tibble: 336,776 x 19
#> plane year month day dep_time sched_dep_time dep_delay arr_time
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 N142… 2013 1 1 517 515 2 830
#> 2 N242… 2013 1 1 533 529 4 850
#> 3 N619… 2013 1 1 542 540 2 923
#> 4 N804… 2013 1 1 544 545 -1 1004
#> 5 N668… 2013 1 1 554 600 -6 812
#> 6 N394… 2013 1 1 554 558 -4 740
#> 7 N516… 2013 1 1 555 600 -5 913
#> 8 N829… 2013 1 1 557 600 -3 709
#> 9 N593… 2013 1 1 557 600 -3 838
#> 10 N3AL… 2013 1 1 558 600 -2 753
#> # … with 336,766 more rows, and 11 more variables: sched_arr_time <dbl>,
#> # arr_delay <dbl>, carrier <chr>, flight <dbl>, origin <chr>,
#> # dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>, minute <dbl>,
#> # time_hour <dttm>
version for data.table based on code from dmanuge :
convNumValues<-function(ds){
ds<-data.table(ds)
dsnum<-data.table(data.matrix(ds))
num_cols <- sapply(dsnum,function(x){mean(as.numeric(is.na(x)))<0.5})
nds <- data.table( dsnum[, .SD, .SDcols=attributes(num_cols)$names[which(num_cols)]]
,ds[, .SD, .SDcols=attributes(num_cols)$names[which(!num_cols)]] )
return(nds)
}
This is because of wrong permission of phpMyAdmin
directory and the file config.inc.php
On *nix like OS set the permission of the directory and the file as follows
chmod -R 755 /path/to/phpMyAdmin
chmod 644 /path/to/phpMyAdmin/config.inc.php
If like me you run a Linux Virtual Machine which mount a Windows folder where phpMyAdmin
sources are located, edit config.inc.php
and add this line
$cfg['CheckConfigurationPermissions'] = false;
C++20 will have "uniform container erasure", and you'll be able to write:
std::erase_if(numbers, [](int n){ return n % 2 == 0 });
And that will work for vector
, set
, deque
, etc.
See cppReference for more info.
First, learn the core concepts of Node.js:
Then, you're going to want to see what the community has to offer:
The gold standard for Node.js package management is NPM.
It is a command line tool for managing your project's dependencies.
NPM is also a registry of pretty much every Node.js package out there
Finally, you're going to want to know what some of the more popular packages are for various tasks:
Useful Tools for Every Project:
Unit Testing:
Web Frameworks:
Trails is a modern web application framework. It builds on the pedigree of Rails and Grails to accelerate development by adhering to a straightforward, convention-based, API-driven design philosophy.
Danf is a full-stack OOP framework providing many features in order to produce a scalable, maintainable, testable and performant applications and allowing to code the same way on both the server (Node.js) and client (browser) sides.
Derbyjs is a reactive full-stack JavaScript framework. They are using patterns like reactive programming and isomorphic JavaScript for a long time.
Loopback.io is a powerful Node.js framework for creating APIs and easily connecting to backend data sources. It has an Angular.js SDK and provides SDKs for iOS and Android.
Web Framework Tools:
Networking:
Command Line Interaction:
Code Generators:
Work with streams:
I pointed the non-www to 54.243.64.13
and the www.domain.com
to the alias.herokuapp.com
and all worked nicely.
Found the IP only after pointing www.domain.com
and then running the dig command on the www.domain.com
and it showed:
;; ANSWER SECTION:
www.domain.com. 14400 IN CNAME aliasat.herokuapp.com.
aliasat.herokuapp.com. 300 IN CNAME us-east-1-a.route.herokuapp.com.
us-east-1-a.route.herokuapp.com. 60 IN A 54.235.186.37
;; AUTHORITY SECTION:
herokuapp.com. 900 IN NS ns-1378.awsdns-44.org.
herokuapp.com. 900 IN NS ns-1624.awsdns-11.co.uk.
herokuapp.com. 900 IN NS ns-505.awsdns-63.com.
herokuapp.com. 900 IN NS ns-662.awsdns-18.net.
May not be ideal but worked.
I have also used following link as others have suggested you for bluetooth communication.
http://developer.android.com/guide/topics/connectivity/bluetooth.html
The thing is all you need is a class BluetoothChatService.java
this class has following threads:
Now when you call start function of the BluetoothChatService like:
mChatService.start();
It starts accept thread which means it will start looking for connection.
Now when you call
mChatService.connect(<deviceObject>,false/true);
Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.
connect
function will start connecting thread which will look for any device which is running accept thread.
When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:
connected(mmSocket, mmDevice, mSocketType);
this method starts connected thread in both the devices:
Using this socket object connected thread obtains the input and output stream to the other device.
And calls read
function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.
BluetoothChatService also has a write
method which takes byte[]
as input and calls write method on connected thread.
mChatService.write("your message".getByte());
write method in connected thread just write this byte data to outputsream of the other device.
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
// mHandler.obtainMessage(
// BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
// buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.
IE8/9 render the non-breaking hyphen mentioned in CanSpice's answer longer than a typical hyphen. It is the length of an en-dash instead of a typical hyphen. This display difference was a deal breaker for me.
As I could not use the CSS answer specified by Deb I instead opted to use no break tags.
<nobr>e-mail</nobr>
In addition I found a specific scenario that caused IE8/9 to break on a hyphen.
IE renders it like this.
The following code reproduces the problem pictured above. I had to use a meta tag to force rendering to IE9 as IE10 has fixed the issue. No fiddle because it does not support meta tags.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<meta charset="utf-8"/>
<style>
body { padding: 20px; }
div { width: 300px; border: 1px solid gray; }
</style>
</head>
<body>
<div>
<p>If there is a - and words are separated by the whitespace code &nbsp; then IE will wrap on the dash.</p>
</div>
</body>
</html>
Finally found this method:
basename($_SERVER['REQUEST_URI']);
This will return all URLs with page name. (e.g.: index.php?id=1&name=rr&class=10
).
Try to use:
pattern="(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/\d{4}"
$(".mytext").mouseover(function() {
var width = 250;
var height = 270;
var posX = $(this).offset().left - $(document).scrollLeft() - width + $(this).outerWidth();
var posY = $(this).offset().top - $(document).scrollTop() + $(this).outerHeight();
$("#dialog").dialog({width:width, height:height ,position:[posX, posY]});
}
Positions a dialog just under an element. I used offset() function just because it calculates the position relative to upper left corner of the browser, but position() function calculates the position relative to parent div or iframe that parent of the element.
Instead of
<item name="android:statusBarColor">@android:color/transparent</item>
Use the following:
<item name="android:windowTranslucentStatus">true</item>
And make sure to remove the top padding (which is added by default) on your 'MainActivity' layout.
Note that this does not make the status bar fully transparent, and there will still be a "faded black" overlay over your status bar.
Here's a less broken datetime
-based solution to convert from datetime object to posix timestamp:
future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
return (future - datetime.datetime(1970, 1, 1)).total_seconds()
See more details at Converting datetime.date to UTC timestamp in Python.
did you try this ?
$("#yourdiv").load(url, function(){
your functions goes here !!!
});
You can try using the transform: translate property by passing the appropriate values inside the parenthesis using the inspect element in Google chrome.
You have to set translate property in such way that both the <div>
overlap each other then You can use JavaScript to show and hide both the <div>
according to your requirements
I cannot believe Oracle's documentation is SO LAME! In some documents it is misleading people to point to the JDK by specifying the path to the JDK root, e.g. on a Mac:
/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/
Reviewing /Applications/SQLDeveloper.app/Contents/MacOS/sqldeveloper.sh revealed the method they use to set up the path:
TMP_PATH=
/usr/libexec/java_home -F -v 9if [ -z "$TMP_PATH" ] ; then TMP_PATH=
/usr/libexec/java_home -F -v 1.8if [ -z "$TMP_PATH" ] ; then osascript -e 'tell app "System Events" to display dialog "SQL Developer requires a minimum of Java 8. \nJava 8 can be downloaded from:\n http://www.oracle.com/technetwork/java/javase/downloads/"' exit 1 fi fi
Executing this manually from Terminal:
/usr/libexec/java_home -F -v 1.8
Lists the path as:
/Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home
And this is what you need to specify as the value for
SetJavaHome /Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home
Thank you Oracle for wasting half a day on your "product" that does NOT even support your latest Java version, also released by you.
try getHibernateTemplate().replicate(entity,ReplicationMode.LATEST_VERSION)
To add a header just add the following code to the location block where you want to add the header:
location some-location {
add_header X-my-header my-header-content;
}
Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.
The simplest way of converting any string into a title case, is to use googles package org.apache.commons.lang.WordUtils
System.out.println(WordUtils.capitalizeFully("tHis will BE MY EXAMple"));
Will result this
This Will Be My Example
I'm not sure why its named "capitalizeFully", where in fact the function is not doing a full capital result, but anyways, thats the tool that we need.
Once you clear the interval using clearInterval
you could setInterval
once again. And to avoid repeating the callback externalize it as a separate function:
var ticker = function() {
console.log('idle');
};
then:
var myTimer = window.setInterval(ticker, 4000);
then when you decide to restart:
window.clearInterval(myTimer);
myTimer = window.setInterval(ticker, 4000);
There are 2 possible use of php code:
in case 1. the closing tag is totally unusefull, also I would like to see just 1 (one) php open tag and NO (zero) closing tag in such a case. This is a good practice as it make code clean and separate logic from presentation. For presentation case (2.) some found it is natural to close all tags (even the PHP-processed ones), that leads to confution, as the PHP has in fact 2 separate use case, that should not be mixed: logic/calculus and presentation
By default, Sublime Text set 'UTF8 without BOM'
, but that wasn't specified.
The only specicified things is 'UTF8 with BOM'
.
Hope this help :)
BOOTSTRAP 2 (source)
The problem is that there is no width set on the buttons. Try this:
.btn {width:20%;}
EDIT:
By default the buttons take an auto width of its text length plus some padding, so I guess for your example it is probably more like 14.5% for 5 buttons (to compensate for the padding).
Note:
If you don't want to try and compensate for padding you can use box-sizing:border-box;
select d.table_name,
d.constraint_name "Primary Constraint Name",
b.constraint_name "Referenced Constraint Name"
from user_constraints d,
(select c.constraint_name,
c.r_constraint_name,
c.table_name
from user_constraints c
where table_name='EMPLOYEES' --your table name instead of EMPLOYEES
and constraint_type='R') b
where d.constraint_name=b.r_constraint_name