follow this tutorial and all the discussion beneath it - http://www.curious-creature.org/2012/12/11/android-recipe-1-image-with-rounded-corners/
according to this post written by Guy Romain, one of the leading developers of the entire Android UI toolkit, it is possible to make a container (and all his child views) with rounded corners, but he explained that it too expensive (from performances of rendering issues).
I'll recommend you to go according to his post, and if you want rounded corners, then implement rounded corners ImageView
according to this post. then, you could place it inside a container with any background, and you'll get the affect you wish.
that's what I did also also eventually.
It has been asked in the past, apparently it costs a lot to mobile browsers, so it's been disabled.
Check this comment by @PaulIrish:
Fixed-backgrounds have huge repaint cost and decimate scrolling performance, which is, I believe, why it was disabled.
you can see workarounds to this in this posts:
You can use background-size: cover;
try a negative margin.
margin-top: -10px; /* as an example */
From w3 schools:
<style>
/* Tooltip container */
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black; /* If you want dots under the hoverable text */
}
/* Tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
/* Position the tooltip text - see examples below! */
position: absolute;
z-index: 1;
}
/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
visibility: visible;
}
</style>
<div class="tooltip">Hover over me
<img src="/pathtoimage" class="tooltiptext">
</div>
Sounds like about what you want
You can set shadow to your view from storyboard also
If each user has its own SQL Server login you could try this
select
so.name, su.name, so.crdate
from
sysobjects so
join
sysusers su on so.uid = su.uid
order by
so.crdate
I would put this as a comment, but I don't have the rep for it. What Josh Crozier answered is correct, but for IE .cur and .ani are the only supported formats for this. So you should probably have a fallback just in case:
.test {
cursor:url("http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif"), url(foo.cur), auto;
}
Use this function
var result = $('div').sort(function (a, b) {
var contentA =parseInt( $(a).data('sort'));
var contentB =parseInt( $(b).data('sort'));
return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
});
$('#mylist').html(result);
You can call this function just after adding new divs.
If you want to preserve javascript events within the divs, DO NOT USE html replace as in the above example. Instead use:
$(targetSelector).sort(function (a, b) {
// ...
}).appendTo($container);
I would say that the basic difference is this:
Grids are used as computing/storage platform.
We start talking about cloud computing when it offers services. I would almost say that cloud computing is higher-level grid. Now I know these are not definitions, but maybe it will make it more clear.
As far as application domains go, grids require users (developers mostly) to actually create services from low-level functions that grid offers. Cloud will offer complete blocks of functionality that you can use in your application.
Example (you want to create physical simulation of ball dropping from certain height): Grid: Study how to compute physics on a computer, create appropriate code, optimize it for certain hardware, think about paralellization, set inputs send application to grid and wait for answer
Cloud: Set diameter of a ball, material from pre-set types, height from which the ball is dropping, etc and ask for results
I would say that if you created OS for grid, you would actually create cloud OS.
sklearn.externals.joblib
has been deprecated since 0.21
and will be removed in v0.23
:
/usr/local/lib/python3.7/site-packages/sklearn/externals/joblib/init.py:15: FutureWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickled models, you may need to re-serialize those models with scikit-learn 0.21+.
warnings.warn(msg, category=FutureWarning)
Therefore, you need to install joblib
:
pip install joblib
and finally write the model to disk:
import joblib
from sklearn.datasets import load_digits
from sklearn.linear_model import SGDClassifier
digits = load_digits()
clf = SGDClassifier().fit(digits.data, digits.target)
with open('myClassifier.joblib.pkl', 'wb') as f:
joblib.dump(clf, f, compress=9)
Now in order to read the dumped file all you need to run is:
with open('myClassifier.joblib.pkl', 'rb') as f:
my_clf = joblib.load(f)
You might want colored output with this.
I use this one-liner for listing the tracked files and directories in the current directory of the current branch:
ls --group-directories-first --color=auto -d $(git ls-tree $(git branch | grep \* | cut -d " " -f2) --name-only)
You might want to add it as an alias:
alias gl='ls --group-directories-first --color=auto -d $(git ls-tree $(git branch | grep \* | cut -d " " -f2) --name-only)'
If you want to recursively list files:
'ls' --color=auto -d $(git ls-tree -rt $(git branch | grep \* | cut -d " " -f2) --name-only)
And an alias:
alias glr="'ls' --color=auto -d \$(git ls-tree -rt \$(git branch | grep \\* | cut -d \" \" -f2) --name-only)"
Here is an example of copying text file with fs.readFile
and fs.writeFile
:
var fs = require('fs');
var copyFile = function(source, destination, next) {
// we should read source file first
fs.readFile(source, function(err, data) {
if (err) return next(err); // error occurred
// now we can write data to destination file
fs.writeFile(destination, data, next);
});
};
And that's an example of using copyFile
function:
copyFile('foo.txt', 'bar.txt', function(err) {
if (err) {
// either fs.readFile or fs.writeFile returned an error
console.log(err.stack || err);
} else {
console.log('Success!');
}
});
Common node.js pattern suggests that the first argument of the callback function is an error. You should use this pattern because all control flow modules rely on it:
next(new Error('I cannot do it!')); // error
next(null, results); // no error occurred, return result
You can just use the normal setTimeout method in JavaScript.
ie...
setTimeout( function(){
// Do something after 1 second
} , 1000 );
In your example, you might want to use showStickySuccessToast
directly.
Change the name of the .CSS file Load the page and then change the file again in the original name it works for me.
Install it from CMD using the command
setup.exe -ignorePrereq -J"-Doracle.install.client.validate.clientSupportedOSCheck=false"
The most common way I have seen to encode this is with a character class whose members form a partition of the set of all possible characters.
Usually people write that as [\s\S]
(whitespace or non-whitespace), though [\w\W]
, [\d\D]
, etc. would all work.
The Subject, in security, is the thing being secured. In this case it could be a persons email or a website or a machine.
If we take the example of an email, say my email, then the subject key container would be the protected location containing my private key.
The certificate store usually refers to Microsoft certificate store which contains certificates form trusted roots, machines on the network, people etc. In my case the subjects certificate store would be the place, within this store, holding my certificates.
If you are working within a microsoft domain then the subject name will invariably hold the Distinguished Name, of the subject, which is how the domain references the subject and holds it in its directory. e.g. CN=Mark Sutton, OU=Developers, O=Mycompany C=UK
To look at your certificates on a microsoft machine:-
Log in as you run>mmc Select File>add/remove snap-in and select certificates then select my user account click Finish then close then ok. Look in the personal area of the store.
In the other areas of the store you will see the other trusted certificates used to validate signatures etc.
The simplest way I found to just send raw XML to a SOAP service using Node.js is to use the Node.js http implementation. It looks like this.
var http = require('http');
var http_options = {
hostname: 'localhost',
port: 80,
path: '/LocationOfSOAPServer/',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': xml.length
}
}
var req = http.request(http_options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.')
})
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
// write data to request body
req.write(xml); // xml would have been set somewhere to a complete xml document in the form of a string
req.end();
You would have defined the xml variable as the raw xml in the form of a string.
But if you just want to interact with a SOAP service via Node.js and make regular SOAP calls, as opposed to sending raw xml, use one of the Node.js libraries. I like node-soap.
I got over this issue by using git merge command with the --no-commit
option and then explicitly removed the staged file and ignore the changes to the file.
E.g.: say I want to ignore any changes to myfile.txt
I proceed as follows:
git merge --no-ff --no-commit <merge-branch>
git reset HEAD myfile.txt
git checkout -- myfile.txt
git commit -m "merged <merge-branch>"
You can put statements 2 & 3 in a for loop, if you have a list of files to skip.
Easiest way, follow the steps :
step 1: After Archive project, right click on project and select show in finder
step 2: Right click on that project and select show as Show package contents, in that go to Products>Applications
step 3: Right click on projectname.app
step 4: Copy projectname.app into a empty folder and zip the folder(foldername.zip)
step 5: Change the zipfolder extension to .ipa(foldername.zip -> foldername.ipa)
step 6: Now you have the final .ipa file
I don't know if this is still the recommended thing to use but the "Object Linking and Embedding" framework allows you to embed certain objects/controls directly into your application. This will probably only work for certain applications, I'm not sure if Notepad is one of them. For really simple things like notepad, you'll probably have an easier time just working with the text box controls provided by whatever medium you're using (e.g. WinForms).
Here's a link to OLE info to get started:
you can also use
.detail_container h1:nth-of-type(1)
By changing the number 1 by any other number you can select any other h1 item.
Thanks to CSS3 there is a solution !
The solution is to put the image as background-image
and then set the background-size
to contain
.
HTML
<div class='bounding-box'>
</div>
CSS
.bounding-box {
background-image: url(...);
background-repeat: no-repeat;
background-size: contain;
}
Test it here: http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=contain
Full compatibility with latest browsers: http://caniuse.com/background-img-opts
To align the div in the center, you can use this variation:
.bounding-box {
background-image: url(...);
background-size: contain;
position: absolute;
background-position: center;
background-repeat: no-repeat;
height: 100%;
width: 100%;
}
We have had the same issue in eclipse or intellij. After trying many alternative solutions, I found simple solution - add this config to your application.properties:
spring.main.web-application-type=none
Stop your running application.(in Eclipse) After you try again.
double amount = 31.245678;
amount = Math.Floor(amount * 100) / 100;
I think this example is self explanatory. It runs the method of first parameter, whose name is given in the second parameter.
class MyClass:
def __init__(self):
pass
def MyMethod(self):
print("Method ran")
# Create an object
object = MyClass()
# Get all the methods of a class
method_list = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
# You can use any of the methods in method_list
# "MyMethod" is the one we want to use right now
# This is the same as running "object.MyMethod()"
getattr(object,'MyMethod')()
visibility=hidden
is very useful, but it will still take up space on the page. You can also use
display=none
because that will not only hide the object, but make it so that it doesn't take up space until it is displayed. (Also keep in mind that display's opposite is "block," not "visible")
If your using PHP and MySQL you can use the mysql_insert_id() function which will tell you the ID of item you Just instered.
But without your Language and DBMS I'm just shooting in the dark here.
Keep in mind that MySQL has a maximum row size limit
The internal representation of a MySQL table has a maximum row size limit of 65,535 bytes, not counting BLOB and TEXT types. BLOB and TEXT columns only contribute 9 to 12 bytes toward the row size limit because their contents are stored separately from the rest of the row. Read more about Limits on Table Column Count and Row Size.
Maximum size a single column can occupy, is different before and after MySQL 5.0.3
Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 255 before MySQL 5.0.3, and 0 to 65,535 in 5.0.3 and later versions. The effective maximum length of a VARCHAR in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used.
However, note that the limit is lower if you use a multi-byte character set like utf8 or utf8mb4.
Use TEXT
types inorder to overcome row size limit.
The four TEXT types are TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT. These correspond to the four BLOB types and have the same maximum lengths and storage requirements.
More details on BLOB and TEXT Types
Even more
Checkout more details on Data Type Storage Requirements which deals with storage requirements for all data types.
If you wanna have everything into one only piece of code, then you can mix tim's answer with the example's approach found on the API for JTextField, and you'll get something like this:
public class JTextFieldLimit extends JTextField {
private int limit;
public JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
@Override
protected Document createDefaultModel() {
return new LimitDocument();
}
private class LimitDocument extends PlainDocument {
@Override
public void insertString( int offset, String str, AttributeSet attr ) throws BadLocationException {
if (str == null) return;
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}
}
Then there is no need to add a Document to the JTextFieldLimit due to JTextFieldLimit already have the functionality inside.
If you want to trigger the event as you type, use the following:
$('input[name=myInput]').on('keyup', function() { ... });
If you want to trigger the event on leaving the input field, use the following:
$('input[name=myInput]').on('change', function() { ... });
You need to have a container for your content div that you wish to be 100% - 100px
#container {
width: 100%
}
#content {
margin-right:100px;
width:100%;
}
<div id="container">
<div id="content">
Your content here
</div>
</div>
You might need to add a clearing div just before the last </div>
if your content div is overflowing.
<div style="clear:both; height:1px; line-height:0"> </div>
There actually doesn't seem to be a lot of explanation on this subject apparently but the exit codes are supposed to be used to give an indication on how the thread exited, 0
tends to mean that it exited safely whilst anything else tends to mean it didn't exit as expected. But then this exit code can be set in code by yourself to completely overlook this.
The closest link I could find to be useful for more information is this
Quote from above link:
What ever the method of exiting, the integer that you return from your process or thread must be values from 0-255(8bits). A zero value indicates success, while a non zero value indicates failure. Although, you can attempt to return any integer value as an exit code, only the lowest byte of the integer is returned from your process or thread as part of an exit code. The higher order bytes are used by the operating system to convey special information about the process. The exit code is very useful in batch/shell programs which conditionally execute other programs depending on the success or failure of one.
From the Documentation for GetEXitCodeThread
Important The GetExitCodeThread function returns a valid error code defined by the application only after the thread terminates. Therefore, an application should not use STILL_ACTIVE (259) as an error code. If a thread returns STILL_ACTIVE (259) as an error code, applications that test for this value could interpret it to mean that the thread is still running and continue to test for the completion of the thread after the thread has terminated, which could put the application into an infinite loop.
My understanding of all this is that the exit code doesn't matter all that much if you are using threads within your own application for your own application. The exception to this is possibly if you are running a couple of threads at the same time that have a dependency on each other. If there is a requirement for an outside source to read this error code, then you can set it to let other applications know the status of your thread.
Naïve approach:
a = "A long string with a . in the middle ending with ."
fchar = '.'
rchar = '. -'
a[::-1].replace(fchar, rchar[::-1], 1)[::-1]
Out[2]: 'A long string with a . in the middle ending with . -'
Aditya Sihag's answer with a single rfind
:
pos = a.rfind('.')
a[:pos] + '. -' + a[pos+1:]
excel stores dates and times as a number representing the number of days since 1900-Jan-0, if you want to get the dates in date format using python, just subtract 2 days from the days column, as shown below:
Date = sheet.cell(1,0).value-2 //in python
at column 1 in my excel, i have my date and above command giving me date values minus 2 days, which is same as date present in my excel sheet
Be careful, reset --hard
will remove your local (uncommitted) modifications, too.
git reset --hard HEAD^
note: if you're on windows you'll need to quote the HEAD^ so
git reset --hard "HEAD^"
If you want to revert the commit WITHOUT throwing away work, use the --soft flag instead of --hard
This code lists modules imported by your module:
import sys
before = [str(m) for m in sys.modules]
import my_module
after = [str(m) for m in sys.modules]
print [m for m in after if not m in before]
It should be useful if you want to know what external modules to install on a new system to run your code, without the need to try again and again.
It won't list the sys
module or modules imported from it.
input.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n")
This will work if the input contains only one type of line breaks - either CR, or LF, or CR+LF.
My efforts in WSL have been unsuccessful.
For those running on Windows Subsystem for Linux (WSL) there seems to be an open issue at this time for missing core dump files.
The comments indicate that
This is a known issue that we are aware of, it is something we are investigating.
# Problem: Given c1 and c2:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
# how do you get c3 to be [[13, 32], [7, 13, 28], [1, 6]] ?
Here's one way to set c3
that doesn't involve sets:
c3 = []
for sublist in c2:
c3.append([val for val in c1 if val in sublist])
But if you prefer to use just one line, you can do this:
c3 = [[val for val in c1 if val in sublist] for sublist in c2]
It's a list comprehension inside a list comprehension, which is a little unusual, but I think you shouldn't have too much trouble following it.
It fails because str.c_str()
returns constant string but char * strtok (char * str, const char * delimiters )
requires volatile string. So you need to use *const_cast< char > inorder to make it voletile.
I am giving you a complete but small program to tokenize the string using C strtok() function.
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main() {
string s="20#6 5, 3";
// strtok requires volatile string as it modifies the supplied string in order to tokenize it
char *str=const_cast< char *>(s.c_str());
char *tok;
tok=strtok(str, "#, " );
int arr[4], i=0;
while(tok!=NULL){
arr[i++]=stoi(tok);
tok=strtok(NULL, "#, " );
}
for(int i=0; i<4; i++) cout<<arr[i]<<endl;
return 0;
}
NOTE: strtok may not be suitable in all situation as the string passed to function gets modified by being broken into smaller strings. Pls., ref to get better understanding of strtok functionality.
How strtok works
Added few print statement to better understand the changes happning to string in each call to strtok and how it returns token.
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main() {
string s="20#6 5, 3";
char *str=const_cast< char *>(s.c_str());
char *tok;
cout<<"string: "<<s<<endl;
tok=strtok(str, "#, " );
cout<<"String: "<<s<<"\tToken: "<<tok<<endl;
while(tok!=NULL){
tok=strtok(NULL, "#, " );
cout<<"String: "<<s<<"\t\tToken: "<<tok<<endl;
}
return 0;
}
Output:
string: 20#6 5, 3
String: 206 5, 3 Token: 20
String: 2065, 3 Token: 6
String: 2065 3 Token: 5
String: 2065 3 Token: 3
String: 2065 3 Token:
strtok iterate over the string first call find the non delemetor character (2 in this case) and marked it as token start then continues scan for a delimeter and replace it with null charater (# gets replaced in actual string) and return start which points to token start character( i.e., it return token 20 which is terminated by null). In subsequent call it start scaning from the next character and returns token if found else null. subsecuntly it returns token 6, 5, 3.
Yegor256's answer worked for me, but I thought I would just add some comments to help out those who are not so good at mounting drives(like me!):
Amazon gives you a choice of what you want to name the volume when you attach it. You have use a name in the range from /dev/sda - /dev/sdp The newer versions of Ubuntu will then rename what you put in there to /dev/xvd(x) or something to that effect.
So for me, I chose /dev/sdp as name the mount name in AWS, then I logged into the server, and discovered that Ubuntu had renamed my volume to /dev/xvdp1). I then had to mount the drive - for me I had to do it like this:
mount -t ext4 xvdp1 /mnt/tmp
After jumping through all those hoops I could access my files at /mnt/tmp
Indeed, the keyword is "ajax": Asynchronous JavaScript and XML. However, last years it's more than often Asynchronous JavaScript and JSON. Basically, you let JS execute an asynchronous HTTP request and update the HTML DOM tree based on the response data.
Since it's pretty a tedious work to make it to work across all browsers (especially Internet Explorer versus others), there are plenty of JavaScript libraries out which simplifies this in single functions and covers as many as possible browser-specific bugs/quirks under the hoods, such as jQuery, Prototype, Mootools. Since jQuery is most popular these days, I'll use it in the below examples.
String
as plain textCreate a /some.jsp
like below (note: the code snippets in this answer doesn't expect the JSP file being placed in a subfolder, if you do so, alter servlet URL accordingly from "someservlet"
to "${pageContext.request.contextPath}/someservlet"
; it's merely omitted from the code snippets for brevity):
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 4112686</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
$.get("someservlet", function(responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
$("#somediv").text(responseText); // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
});
</script>
</head>
<body>
<button id="somebutton">press here</button>
<div id="somediv"></div>
</body>
</html>
Create a servlet with a doGet()
method which look like this:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = "some text";
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(text); // Write response body.
}
Map this servlet on an URL pattern of /someservlet
or /someservlet/*
as below (obviously, the URL pattern is free to your choice, but you'd need to alter the someservlet
URL in JS code examples over all place accordingly):
package com.example;
@WebServlet("/someservlet/*")
public class SomeServlet extends HttpServlet {
// ...
}
Or, when you're not on a Servlet 3.0 compatible container yet (Tomcat 7, Glassfish 3, JBoss AS 6, etc or newer), then map it in web.xml
the old fashioned way (see also our Servlets wiki page):
<servlet>
<servlet-name>someservlet</servlet-name>
<servlet-class>com.example.SomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>someservlet</servlet-name>
<url-pattern>/someservlet/*</url-pattern>
</servlet-mapping>
Now open the http://localhost:8080/context/test.jsp in the browser and press the button. You'll see that the content of the div get updated with the servlet response.
List<String>
as JSONWith JSON instead of plaintext as response format you can even get some steps further. It allows for more dynamics. First, you'd like to have a tool to convert between Java objects and JSON strings. There are plenty of them as well (see the bottom of this page for an overview). My personal favourite is Google Gson. Download and put its JAR file in /WEB-INF/lib
folder of your webapplication.
Here's an example which displays List<String>
as <ul><li>
. The servlet:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> list = new ArrayList<>();
list.add("item1");
list.add("item2");
list.add("item3");
String json = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
The JS code:
$(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
$.get("someservlet", function(responseJson) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
var $ul = $("<ul>").appendTo($("#somediv")); // Create HTML <ul> element and append it to HTML DOM element with ID "somediv".
$.each(responseJson, function(index, item) { // Iterate over the JSON array.
$("<li>").text(item).appendTo($ul); // Create HTML <li> element, set its text content with currently iterated item and append it to the <ul>.
});
});
});
Do note that jQuery automatically parses the response as JSON and gives you directly a JSON object (responseJson
) as function argument when you set the response content type to application/json
. If you forget to set it or rely on a default of text/plain
or text/html
, then the responseJson
argument wouldn't give you a JSON object, but a plain vanilla string and you'd need to manually fiddle around with JSON.parse()
afterwards, which is thus totally unnecessary if you set the content type right in first place.
Map<String, String>
as JSONHere's another example which displays Map<String, String>
as <option>
:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String> options = new LinkedHashMap<>();
options.put("value1", "label1");
options.put("value2", "label2");
options.put("value3", "label3");
String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
And the JSP:
$(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
$.get("someservlet", function(responseJson) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
var $select = $("#someselect"); // Locate HTML DOM element with ID "someselect".
$select.find("option").remove(); // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
$.each(responseJson, function(key, value) { // Iterate over the JSON object.
$("<option>").val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
});
});
});
with
<select id="someselect"></select>
List<Entity>
as JSONHere's an example which displays List<Product>
in a <table>
where the Product
class has the properties Long id
, String name
and BigDecimal price
. The servlet:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products = someProductService.list();
String json = new Gson().toJson(products);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
The JS code:
$(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
$.get("someservlet", function(responseJson) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
var $table = $("<table>").appendTo($("#somediv")); // Create HTML <table> element and append it to HTML DOM element with ID "somediv".
$.each(responseJson, function(index, product) { // Iterate over the JSON array.
$("<tr>").appendTo($table) // Create HTML <tr> element, set its text content with currently iterated item and append it to the <table>.
.append($("<td>").text(product.id)) // Create HTML <td> element, set its text content with id of currently iterated product and append it to the <tr>.
.append($("<td>").text(product.name)) // Create HTML <td> element, set its text content with name of currently iterated product and append it to the <tr>.
.append($("<td>").text(product.price)); // Create HTML <td> element, set its text content with price of currently iterated product and append it to the <tr>.
});
});
});
List<Entity>
as XMLHere's an example which does effectively the same as previous example, but then with XML instead of JSON. When using JSP as XML output generator you'll see that it's less tedious to code the table and all. JSTL is this way much more helpful as you can actually use it to iterate over the results and perform server side data formatting. The servlet:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products = someProductService.list();
request.setAttribute("products", products);
request.getRequestDispatcher("/WEB-INF/xml/products.jsp").forward(request, response);
}
The JSP code (note: if you put the <table>
in a <jsp:include>
, it may be reusable elsewhere in a non-ajax response):
<?xml version="1.0" encoding="UTF-8"?>
<%@page contentType="application/xml" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<data>
<table>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.id}</td>
<td><c:out value="${product.name}" /></td>
<td><fmt:formatNumber value="${product.price}" type="currency" currencyCode="USD" /></td>
</tr>
</c:forEach>
</table>
</data>
The JS code:
$(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
$.get("someservlet", function(responseXml) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response XML...
$("#somediv").html($(responseXml).find("data").html()); // Parse XML, find <data> element and append its HTML to HTML DOM element with ID "somediv".
});
});
You'll by now probably realize why XML is so much more powerful than JSON for the particular purpose of updating a HTML document using Ajax. JSON is funny, but after all generally only useful for so-called "public web services". MVC frameworks like JSF use XML under the covers for their ajax magic.
You can use jQuery $.serialize()
to easily ajaxify existing POST forms without fiddling around with collecting and passing the individual form input parameters. Assuming an existing form which works perfectly fine without JavaScript/jQuery (and thus degrades gracefully when enduser has JavaScript disabled):
<form id="someform" action="someservlet" method="post">
<input type="text" name="foo" />
<input type="text" name="bar" />
<input type="text" name="baz" />
<input type="submit" name="submit" value="Submit" />
</form>
You can progressively enhance it with ajax as below:
$(document).on("submit", "#someform", function(event) {
var $form = $(this);
$.post($form.attr("action"), $form.serialize(), function(response) {
// ...
});
event.preventDefault(); // Important! Prevents submitting the form.
});
You can in the servlet distinguish between normal requests and ajax requests as below:
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String foo = request.getParameter("foo");
String bar = request.getParameter("bar");
String baz = request.getParameter("baz");
boolean ajax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
// ...
if (ajax) {
// Handle ajax (JSON or XML) response.
} else {
// Handle regular (JSP) response.
}
}
The jQuery Form plugin does less or more the same as above jQuery example, but it has additional transparent support for multipart/form-data
forms as required by file uploads.
If you don't have a form at all, but just wanted to interact with the servlet "in the background" whereby you'd like to POST some data, then you can use jQuery $.param()
to easily convert a JSON object to an URL-encoded query string.
var params = {
foo: "fooValue",
bar: "barValue",
baz: "bazValue"
};
$.post("someservlet", $.param(params), function(response) {
// ...
});
The same doPost()
method as shown here above can be reused. Do note that above syntax also works with $.get()
in jQuery and doGet()
in servlet.
If you however intend to send the JSON object as a whole instead of as individual request parameters for some reason, then you'd need to serialize it to a string using JSON.stringify()
(not part of jQuery) and instruct jQuery to set request content type to application/json
instead of (default) application/x-www-form-urlencoded
. This can't be done via $.post()
convenience function, but needs to be done via $.ajax()
as below.
var data = {
foo: "fooValue",
bar: "barValue",
baz: "bazValue"
};
$.ajax({
type: "POST",
url: "someservlet",
contentType: "application/json", // NOT dataType!
data: JSON.stringify(data),
success: function(response) {
// ...
}
});
Do note that a lot of starters mix contentType
with dataType
. The contentType
represents the type of the request body. The dataType
represents the (expected) type of the response body, which is usually unnecessary as jQuery already autodetects it based on response's Content-Type
header.
Then, in order to process the JSON object in the servlet which isn't being sent as individual request parameters but as a whole JSON string the above way, you only need to manually parse the request body using a JSON tool instead of using getParameter()
the usual way. Namely, servlets don't support application/json
formatted requests, but only application/x-www-form-urlencoded
or multipart/form-data
formatted requests. Gson also supports parsing a JSON string into a JSON object.
JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);
String foo = data.get("foo").getAsString();
String bar = data.get("bar").getAsString();
String baz = data.get("baz").getAsString();
// ...
Do note that this all is more clumsy than just using $.param()
. Normally, you want to use JSON.stringify()
only if the target service is e.g. a JAX-RS (RESTful) service which is for some reason only capable of consuming JSON strings and not regular request parameters.
Important to realize and understand is that any sendRedirect()
and forward()
call by the servlet on an ajax request would only forward or redirect the ajax request itself and not the main document/window where the ajax request originated. JavaScript/jQuery would in such case only retrieve the redirected/forwarded response as responseText
variable in the callback function. If it represents a whole HTML page and not an ajax-specific XML or JSON response, then all you could do is to replace the current document with it.
document.open();
document.write(responseText);
document.close();
Note that this doesn't change the URL as enduser sees in browser's address bar. So there are issues with bookmarkability. Therefore, it's much better to just return an "instruction" for JavaScript/jQuery to perform a redirect instead of returning the whole content of the redirected page. E.g. by returning a boolean, or an URL.
String redirectURL = "http://example.com";
Map<String, String> data = new HashMap<>();
data.put("redirect", redirectURL);
String json = new Gson().toJson(data);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
function(responseJson) {
if (responseJson.redirect) {
window.location = responseJson.redirect;
return;
}
// ...
}
Add this code after updating the list
Suppose:
The ArrayAdapter<String> variable name is dataAdapter, and the List variable name is keys.
I had a problem there. When I JSON encode a string with a character like "é", every browsers will return the same "é", except IE which will return "\u00e9".
Then with PHP json_decode(), it will fail if it find "é", so for Firefox, Opera, Safari and Chrome, I've to call utf8_encode() before json_decode().
Note : with my tests, IE and Firefox are using their native JSON object, others browsers are using json2.js.
You have to assign the returned value of the setInterval
function to a variable
var interval;
$(document).on('ready',function(){
interval = setInterval(updateDiv,3000);
});
and then use clearInterval(interval)
to clear it again.
I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.
I have to assume you are using windows because you have mentioned notepad++.
Use notepad++. Right click on the file and choose "edit with notepad++"
Use notepad Change the filename extension to .txt and double click the file.
Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"
If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.
Thanks for your answers. I didn't understand what type of object "MyTable" was (in your answers) and the following code gave me the error shown below.
DataTable dt = ds.Tables[0];
var name = from r in dt
where r.ID == 0
select r.Name;
Could not find an implementation of the query pattern for source type 'System.Data.DataTable'. 'Where' not found
So I continued my googling and found something that does work:
var rowColl = ds.Tables[0].AsEnumerable();
string name = (from r in rowColl
where r.Field<int>("ID") == 0
select r.Field<string>("NAME")).First<string>();
What do you think?
Use simplest way of doing this-
SELECT GROUP_CONCAT(Column) from table
you can identify your button from there name tag like below, You need to check like this in you controller
if (Request.Form["submit"] != null)
{
//Write your code here
}
else if (Request.Form["process"] != null)
{
//Write your code here
}
After digging and digging on this issue, for me it was solved by Johannes on another thread: Local CSS file is not loading from HTML
The
type
attribute in yourlink
tag has typographical quote characters:type=“text/css”
. Try to change these to "plain" quotes liketype="text/css"
I couldn't get it to work using Calendar. You have to use DateFormat
//Wednesday, July 20, 2011 3:54:44 PM PDT
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateTimeString = df.format(new Date());
//Wednesday, July 20, 2011
df = DateFormat.getDateInstance(DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateString = df.format(new Date());
//3:54:44 PM PDT
df = DateFormat.getTimeInstance(DateFormat.FULL);
df.setTimeZone(Timezone.getTimeZone("PST"));
final String timeString = df.format(new Date());
I had the same problem when trying to use a token with Github.
The only syntax that has worked for me with Python 3 is:
import requests
myToken = '<token>'
myUrl = '<website>'
head = {'Authorization': 'token {}'.format(myToken)}
response = requests.get(myUrl, headers=head)
I have spent 3 hours for solving the error The JAVA_HOME
environment variable is not defined correctly. This environment variable is needed to run this program NB: JAVA_HOME
should point to a JDK not a JRE
Finally I got the solution. Please set the JAVA_HOME
value by Browse Directory
button/option. Try to find the jdk path. Ex: C:\Program Files\Java\jdk1.8.0_181
File -> Export -> Web -> WAR file
OR in Kepler follow as shown below :
Here is a solution using Guava
private User findUserByName(List<User> userList, final String name) {
Optional<User> userOptional =
FluentIterable.from(userList).firstMatch(new Predicate<User>() {
@Override
public boolean apply(@Nullable User input) {
return input.getName().equals(name);
}
});
return userOptional.isPresent() ? userOptional.get() : null; // return user if found otherwise return null if user name don't exist in user list
}
var chart = new Chart(ctx, {
...
options:{
scales:{
xAxes: [{
display: false //this will remove all the x-axis grid lines
}]
}
}
});
var chart = new Chart(ctx, {
...
options: {
scales: {
xAxes: [{
ticks: {
display: false //this will remove only the label
}
}]
}
}
});
Reference: chart.js documentation
Old answer (written when the current version was 1.0 beta) just for reference below:
To avoid displaying labels in chart.js
you have to set scaleShowLabels : false
and also avoid to pass the labels
:
<script>
var options = {
...
scaleShowLabels : false
};
var lineChartData = {
//COMMENT THIS LINE TO AVOID DISPLAYING THE LABELS
//labels : ["1","2","3","4","5","6","7"],
...
}
...
</script>
Yes. This should work on all major browsers.
None of the posted solutions worked for me.
I had to vi
into my Makefile and edit the path so that the path to the include
folder and the OS subsystem (in my case, -I/usr/lib/jvm/java-8-openjdk-amd64/include/linux
) was correct. This allowed me to run make
and make install
without issues.
new Guid(string)
You could also look at using a TypeConverter
.
I'd have another anectode on test coverage I'd like to share.
We have a huge project wherein, over twitter, I noted that, with 700 unit tests, we only have 20% code coverage.
Scott Hanselman replied with words of wisdom:
Is it the RIGHT 20%? Is it the 20% that represents the code your users hit the most? You might add 50 more tests and only add 2%.
Again, it goes back to my Testivus on Code Coverage Answer. How much rice should you put in the pot? It depends.
For scala
import org.apache.spark.sql.functions.regexp_replace
import org.apache.spark.sql.functions.col
data.withColumn("addr_new", regexp_replace(col("addr_line"), "\\*", ""))
I'm not an attorney, but clicking the like button without the express permission of a facebook user might be a violation of facebook policy. You should have your corporate attorney check out the facebook policy.
You should encode the url to a page with a like button, so when scanned by the phone, it opens up a browser window to the like page, where now the user has the option to like it or not.
If you think you'll be using more than 1 db for any reason, go with the variable because you'll be able to change one parameter to switch to an entirely different db. I.e. for testing , autobackup, etc.
I know the question asked about "write" but in a more general sense "append" might be useful in some cases as it is easy to use in a loop to add text to a file (whether the file exists or not). Use a "\n" if you want to add lines eg:
var fs = require('fs');
for (var i=0; i<10; i++){
fs.appendFileSync("junk.csv", "Line:"+i+"\n");
}
This works for any object, not just functions:
IF OBJECT_ID('YourObjectName') IS NOT NULL
then just add your flavor of object, as in:
IF OBJECT_ID('YourFunction') IS NOT NULL
DROP FUNCTION YourFunction
This answer assumes you have some JavaScript that you don't want to convert to TypeScript, but you want to benefit from type checking with minimal changes to your .js
.
A .d.ts
file is very much like a C or C++ header file. Its purpose is to define an interface. Here is an example:
mashString.d.ts
/** Makes a string harder to read. */
declare function mashString(
/** The string to obscure */
str: string
):string;
export = mashString;
mashString.js
// @ts-check
/** @type {import("./mashString")} */
module.exports = (str) => [...str].reverse().join("");
main.js
// @ts-check
const mashString = require("./mashString");
console.log(mashString("12345"));
The relationship here is: mashString.d.ts
defines an interface, mashString.js
implements the interface and main.js
uses the interface.
To get the type checking to work you add // @ts-check
to your .js
files.
But this only checks that main.js
uses the interface correctly. To also ensure that mashString.js
implements it correctly we add /** @type {import("./mashString")} */
before the export.
You can create your initial .d.ts
files using tsc -allowJs main.js -d
then edit them as required manually to improve the type checking and documentation.
In most cases the implementation and interface have the same name, here mashString
. But you can have alternative implementations. For example we could rename mashString.js
to reverse.js
and have an alternative encryptString.js
.
Too bad Oracle has limitations like these. Sure, the result for a column not in the GROUP BY would be random, but sometimes you want that. Silly Oracle, you can do this in MySQL/MSSQL.
BUT there is a work around for Oracle:
While the following line does not work
SELECT unique_id_col, COUNT(1) AS cnt FROM yourTable GROUP BY col_A;
You can trick Oracle with some 0's like the following, to keep your column in scope, but not group by it (assuming these are numbers, otherwise use CONCAT)
SELECT MAX(unique_id_col) AS unique_id_col, COUNT(1) AS cnt
FROM yourTable GROUP BY col_A, (unique_id_col*0 + col_A);
You just need to add a /A
behind the line.
Example:
get-childitem C:\temp\ -exclude *.svn-base,".svn" -recurse | foreach ($_) {remove-item $_.fullname} /a
From The Byte Order Fallacy by Rob Pike:
Let's say your data stream has a little-endian-encoded 32-bit integer. Here's how to extract it (assuming unsigned bytes):
i = (data[0]<<0) | (data[1]<<8) | (data[2]<<16) | (data[3]<<24);
If it's big-endian, here's how to extract it:
i = (data[3]<<0) | (data[2]<<8) | (data[1]<<16) | (data[0]<<24);
TL;DR: don't worry about your platform native order, all that counts is the byte order of the stream your are reading from, and you better hope it's well defined.
Note: it was remarked in the comment that absent explicit type conversion, it was important that data
be an array of unsigned char
or uint8_t
. Using signed char
or char
(if signed) will result in data[x]
being promoted to an integer and data[x] << 24
potentially shifting a 1 into the sign bit which is UB.
If you are on Linux, gitg
is way to go to do it very quickly and graphically.
If you insist on command line you can use:
git log --oneline --decorate
To make git log
nicer by default, I typically set these global preferences:
git config --global log.decorate true
git config --global log.abbrevCommit true
Another option is to use a list comprehension:
df['First Season'] = [1 if year > 1990 else year for year in df['First Season']]
I had the same question. This works great in Wordpress!
<a href="//pinterest.com/pin/create/link/?url=<?php the_permalink();?>&description=<?php the_title();?>">Pin this</a>
You can use the pluck
method:
Word_relation::where('word_one', $word_id)->pluck('word_two')->toArray();
For more info on what methods are available for using with collection, you can you can check out the Laravel Documentation.
It is possible to load the second version of the jQuery use it and then restore to the original or keep the second version if there was no jQuery loaded before. Here is an example:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
var jQueryTemp = jQuery.noConflict(true);
var jQueryOriginal = jQuery || jQueryTemp;
if (window.jQuery){
console.log('Original jQuery: ', jQuery.fn.jquery);
console.log('Second jQuery: ', jQueryTemp.fn.jquery);
}
window.jQuery = window.$ = jQueryTemp;
</script>
<script type="text/javascript">
console.log('Script using second: ', jQuery.fn.jquery);
</script>
<script type="text/javascript">
// Restore original jQuery:
window.jQuery = window.$ = jQueryOriginal;
console.log('Script using original or the only version: ', jQuery.fn.jquery);
</script>
This will get you the name of the day:
SELECT DATENAME(weekday, GETDATE())
Great work Andreas. I created a bean version so the SessionFactory could be autowired.
import javax.persistence.EntityManagerFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
....
@Autowired
private EntityManagerFactory entityManagerFactory;
@Bean
public SessionFactory getSessionFactory() {
if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
throw new NullPointerException("factory is not a hibernate factory");
}
return entityManagerFactory.unwrap(SessionFactory.class);
}
This may seem bizarre, but it's worked for me and I have written a C# program to automate this.
Step 1: Truncate the transaction log (Back up only the transaction log, turning on the option to remove inactive transactions)
Step 2: Run a database shrink, moving all the pages to the start of the files
Step 3: Truncate the transaction log again, as step 2 adds log entries
Step 4: Run a database shrink again.
My stripped down code, which uses the SQL DMO library, is as follows:
SQLDatabase.TransactionLog.Truncate();
SQLDatabase.Shrink(5, SQLDMO.SQLDMO_SHRINK_TYPE.SQLDMOShrink_NoTruncate);
SQLDatabase.TransactionLog.Truncate();
SQLDatabase.Shrink(5, SQLDMO.SQLDMO_SHRINK_TYPE.SQLDMOShrink_Default);
How to break out in java??
Ans: Best way: System.exit(0);
Java language provides three jump statemnts that allow you to interrupt the normal flow of program.
These include break , continue ,return ,labelled break statement for e.g
import java.util.Scanner;
class demo
{
public static void main(String args[])
{
outerLoop://Label
for(int i=1;i<=10;i++)
{
for(int j=1;j<=i;j++)
{
for(int k=1;k<=j;k++)
{
System.out.print(k+"\t");
break outerLoop;
}
System.out.println();
}
System.out.println();
}
}
}
Output: 1
Now Note below Program:
import java.util.Scanner;
class demo
{
public static void main(String args[])
{
for(int i=1;i<=10;i++)
{
for(int j=1;j<=i;j++)
{
for(int k=1;k<=j;k++)
{
System.out.print(k+"\t");
break ;
}
}
System.out.println();
}
}
}
output:
1
11
111
1111
and so on upto
1111111111
Similarly you can use continue statement just replace break with continue in above example.
Things to Remember :
A case label cannot contain a runtime expressions involving variable or method calls
outerLoop:
Scanner s1=new Scanner(System.in);
int ans=s1.nextInt();
// Error s1 cannot be resolved
You can accomplish this (if I understand what you are trying to do) using dynamic SQL.
The trick is that you need to create a string containing the SQL statement. That's because the tablename has to specified in the actual SQL text, when you execute the statement. The table references and column references can't be supplied as parameters, those have to appear in the SQL text.
So you can use something like this approach:
SET @stmt = 'INSERT INTO @tmpTbl1 SELECT ' + @KeyValue
+ ' AS fld1 FROM tbl' + @KeyValue
EXEC (@stmt)
First, we create a SQL statement as a string. Given a @KeyValue of 'Foo', that would create a string containing:
'INSERT INTO @tmpTbl1 SELECT Foo AS fld1 FROM tblFoo'
At this point, it's just a string. But we can execute the contents of the string, as a dynamic SQL statement, using EXECUTE
(or EXEC
for short).
The old-school sp_executesql
procedure is an alternative to EXEC, another way to execute dymamic SQL, which also allows you to pass parameters, rather than specifying all values as literals in the text of the statement.
FOLLOWUP
EBarr points out (correctly and importantly) that this approach is susceptible to SQL Injection.
Consider what would happen if @KeyValue
contained the string:
'1 AS foo; DROP TABLE students; -- '
The string we would produce as a SQL statement would be:
'INSERT INTO @tmpTbl1 SELECT 1 AS foo; DROP TABLE students; -- AS fld1 ...'
When we EXECUTE that string as a SQL statement:
INSERT INTO @tmpTbl1 SELECT 1 AS foo;
DROP TABLE students;
-- AS fld1 FROM tbl1 AS foo; DROP ...
And it's not just a DROP TABLE that could be injected. Any SQL could be injected, and it might be much more subtle and even more nefarious. (The first attacks can be attempts to retreive information about tables and columns, followed by attempts to retrieve data (email addresses, account numbers, etc.)
One way to address this vulnerability is to validate the contents of @KeyValue, say it should contain only alphabetic and numeric characters (e.g. check for any characters not in those ranges using LIKE '%[^A-Za-z0-9]%'
. If an illegal character is found, then reject the value, and exit without executing any SQL.
you can use script module
Example
- name: Transfer and execute a script.
hosts: all
tasks:
- name: Copy and Execute the script
script: /home/user/userScript.sh
The problem might be in the rest of the html, the part that you didn't post.
With this example (I just closed the open tags):
<a class="item" ng-href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026" href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026">
<div class="col-lg-2 col-sm-3 col-xs-4 item-list-image">
<img ng-src="csa/images/library/Service_Design.png" src="csa/images/library/Service_Design.png">
</div>
<div class="col-lg-8 col-sm-9 col-xs-8">
<div class="col-xs-12">
<p>
<strong class="ng-binding">Smoke Sequential</strong>
</p>
</div>
</div>
</a>
I was able to find the element without trouble with:
driver.findElement(By.linkText("Smoke Sequential")).click();
If there is more text inside the element, you could try a find by partial link text:
driver.findElement(By.partialLinkText("Sequential")).click();
Use pandas.Series.dt.day_name()
, since pandas.Timestamp.weekday_name
has been deprecated:
import pandas as pd
df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['day_of_week'] = df['my_dates'].dt.day_name()
Output:
my_dates myvals day_of_week
0 2015-01-01 1 Thursday
1 2015-01-02 2 Friday
2 2015-01-03 3 Saturday
As user jezrael points out below, dt.weekday_name
was added in version 0.18.1
Pandas Docs
import pandas as pd
df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['day_of_week'] = df['my_dates'].dt.weekday_name
Output:
my_dates myvals day_of_week
0 2015-01-01 1 Thursday
1 2015-01-02 2 Friday
2 2015-01-03 3 Saturday
Use this:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.dayofweek.html
See this:
Get weekday/day-of-week for Datetime column of DataFrame
If you want a string instead of an integer do something like this:
import pandas as pd
df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['day_of_week'] = df['my_dates'].dt.dayofweek
days = {0:'Mon',1:'Tues',2:'Weds',3:'Thurs',4:'Fri',5:'Sat',6:'Sun'}
df['day_of_week'] = df['day_of_week'].apply(lambda x: days[x])
Output:
my_dates myvals day_of_week
0 2015-01-01 1 Thurs
1 2015-01-02 2 Fri
2 2015-01-01 3 Thurs
You can try it out http://api.jquery.com/mouseover/ on the jQuery doc page. It's a nice little, interactive demo that makes it very clear and you can actually see for yourself.
In short, you'll notice that a mouse over event occurs on an element when you are over it - coming from either its child OR parent element, but a mouse enter event only occurs when the mouse moves from the parent element to the element.
It's a simple concept. Redux creates a ubiquitous state object (a store) from the actions in the reducers. Like a React component, this state doesn't have to be explicitly coded anywhere, but it helps developers to see a default state object in the reducer file to visualise what is happening. You import the reducer in the component to access the file. Then mapStateToProps selects only the key/value pairs in the store that its component needs. Think of it like Redux creating a global version of a React component's
this.state = ({
cats = [],
dogs = []
})
It is impossible to change the structure of the state by using mapStateToProps(). What you are doing is choosing only the store's key/value pairs that the component needs and passing in the values (from a list of key/values in the store) to the props (local keys) in your component. You do this one value at a time in a list. No structure changes can occur in the process.
P.S. The store is local state. Reducers usually also pass state along to the database with Action Creators getting into the mix, but understand this simple concept first for this specific posting.
P.P.S. It is good practice to separate the reducers into separate files for each one and only import the reducer that the component needs.
duckduckgo.com doesn't ignore special characters, at least if the whole string is between ""
https://duckduckgo.com/?q=%22*222%23%22
Moshe's solution is great but the problem may still exist if you need to put the list inside a div
. (read: CSS counter-reset on nested list)
This style could prevent that issue:
ol > li {_x000D_
counter-increment: item;_x000D_
}_x000D_
_x000D_
ol > li:first-child {_x000D_
counter-reset: item;_x000D_
}_x000D_
_x000D_
ol ol > li {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
ol ol > li:before {_x000D_
content: counters(item, ".") ". ";_x000D_
margin-left: -20px;_x000D_
}
_x000D_
<ol>_x000D_
<li>list not nested in div</li>_x000D_
</ol>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<div>_x000D_
<ol>_x000D_
<li>nested in div</li>_x000D_
<li>two_x000D_
<ol>_x000D_
<li>two.one</li>_x000D_
<li>two.two</li>_x000D_
<li>two.three</li>_x000D_
</ol>_x000D_
</li>_x000D_
<li>three_x000D_
<ol>_x000D_
<li>three.one</li>_x000D_
<li>three.two_x000D_
<ol>_x000D_
<li>three.two.one</li>_x000D_
<li>three.two.two</li>_x000D_
</ol>_x000D_
</li>_x000D_
</ol>_x000D_
</li>_x000D_
<li>four</li>_x000D_
</ol>_x000D_
</div>
_x000D_
You can also set the counter-reset on li:before
.
$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");
in 2020, the accepted answer is kinda out of date since the PageRequest
is deprecated, so you should use code like this :
Pageable page = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by("id").descending());
return repository.findAll(page);
You could also do something like this:
SELECT tb1.* FROM Table tb1 WHERE id = (SELECT MAX(tb2.id) FROM Table tb2);
Its useful when you want to make some joins.
I think you want something like this:
Intent foo = new Intent(this, viewContacts.class);
foo.putExtra("myFirstKey", "myFirstValue");
foo.putExtra("mySecondKey", "mySecondValue");
startActivity(foo);
or you can combine them into a bundle first. Corresponding getExtra() routines exist for the other side. See the intent topic in the dev guide for more information.
Sorry for joining the party late, but there is a way to do this with Microsoft public API.
Here's what you need:
System.Net.Http.dll
System.Net.Http.Formatting.dll
Note The Nuget packages come with more assemblies, but at the time of writing you only need the above.
Once you have the assemblies referenced, the code can look like this (using .NET 4.5 for convenience):
public static async Task ParseFiles(
Stream data, string contentType, Action<string, Stream> fileProcessor)
{
var streamContent = new StreamContent(data);
streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);
var provider = await streamContent.ReadAsMultipartAsync();
foreach (var httpContent in provider.Contents)
{
var fileName = httpContent.Headers.ContentDisposition.FileName;
if (string.IsNullOrWhiteSpace(fileName))
{
continue;
}
using (Stream fileContents = await httpContent.ReadAsStreamAsync())
{
fileProcessor(fileName, fileContents);
}
}
}
As for usage, say you have the following WCF REST method:
[OperationContract]
[WebInvoke(Method = WebRequestMethods.Http.Post, UriTemplate = "/Upload")]
void Upload(Stream data);
You could implement it like so
public void Upload(Stream data)
{
MultipartParser.ParseFiles(
data,
WebOperationContext.Current.IncomingRequest.ContentType,
MyProcessMethod);
}
Here you go:
SELECT Field1, COUNT(Field1)
FROM Table1
GROUP BY Field1
HAVING COUNT(Field1) > 1
ORDER BY Field1 desc
You might be looking for IgnoreDataMemberAttribute
.
The
RecyclerView
is a new ViewGroup that is prepared to render any adapter-based view in a similar way. It is supossed to be the successor ofListView and GridView
, and it can be found in thelatest support-v7 version
. TheRecyclerView
has been developed with extensibility in mind, so it is possible to create any kind of layout you can think of, but not without a little pain-in-the-ass dose.
Answer taken from Antonio leiva
compile 'com.android.support:recyclerview-v7:27.0.0'
RecyclerView
is indeed a powerful view
than ListView
.
For more details you can visit This page.
The typical use is
void* ret = NULL;
pthread_t tid = something; /// change it suitably
if (pthread_join (tid, &ret))
handle_error();
// do something with the return value ret
Try to install JST Server Adapters
and JST Server Adapters Extentions
. I am running Eclipse 4.4.2 Luna and it worked.
Here are the steps I followed:
Help -> Install New Software
Choose "Luna - http://download.eclipse.org/releases/luna" site
Expand "Web, XML, and Java EE Development"
Check JST Server Adapters and JST Server Adapters Extentions
function sizeOf(parent_data, size)
{
for (var prop in parent_data)
{
let value = parent_data[prop];
if (typeof value === 'boolean')
{
size += 4;
}
else if (typeof value === 'string')
{
size += value.length * 2;
}
else if (typeof value === 'number')
{
size += 8;
}
else
{
let oldSize = size;
size += sizeOf(value, oldSize) - oldSize;
}
}
return size;
}
function roughSizeOfObject(object)
{
let size = 0;
for each (let prop in object)
{
size += sizeOf(prop, 0);
} // for..
return size;
}
An additional item to a really useful list.
I have found Celery unforgiving in relation to errors in tasks (or at least I haven't been able to trace the appropriate log entries) and it doesn't register them. I have had a number of issues with running Celery as a service, which have been predominantly permissions related.
The latest related to permissions writing to a log file. I had no issues in development or running celery at the command line, but the service reported the task as unregistered.
I needed to change the log folder permissions to enable the service to write to it.
Source: CodePath - UI Testing With Espresso
- Finally, we need to pull in the Espresso dependencies and set the test runner in our app build.gradle:
// build.gradle
...
android {
...
defaultConfig {
...
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}
dependencies {
...
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2') {
// Necessary if your app targets Marshmallow (since Espresso
// hasn't moved to Marshmallow yet)
exclude group: 'com.android.support', module: 'support-annotations'
}
androidTestCompile('com.android.support.test:runner:0.5') {
// Necessary if your app targets Marshmallow (since the test runner
// hasn't moved to Marshmallow yet)
exclude group: 'com.android.support', module: 'support-annotations'
}
}
I've added that to my gradle file and the warning disappeared.
Also, if you get any other dependency listed as conflicting, such as support-annotations, try excluding it too from the androidTestCompile dependencies.
To handle many newline delimiters, including character combinations like \r\n
, use splitlines (see this related post) use the following:
'<br />'.join(thatLine.splitlines())
If #uploadedfile
is an input with type "file" :
var file = $("#uploadedfile")[0].files[0];
var fileName = file.name;
var fileSize = file.size;
alert("Uploading: "+fileName+" @ "+fileSize+"bytes");
Normally this would fire on the change event, like so:
$("#uploadedfile").on("change", function(){
var file = this.files[0],
fileName = file.name,
fileSize = file.size;
alert("Uploading: "+fileName+" @ "+fileSize+"bytes");
CustomFileHandlingFunction(file);
});
If you're not limited to using the git command prompt, then you can always run git gui
and use the Branch->Delete menu item. Select all the branches you want to delete and let it rip.
I just found a new trick to center a box in the middle of the screen even if you don't have fixed dimensions. Let's say you would like a box 60% width / 60% height. The way to make it centered is by creating 2 boxes: a "container" box that position left: 50% top :50%, and a "text" box inside with reverse position left: -50%; top :-50%;
It works and it's cross browser compatible.
Check out the code below, you probably get a better explanation:
jQuery('.close a, .bg', '#message').on('click', function() {_x000D_
jQuery('#message').fadeOut();_x000D_
return false;_x000D_
});
_x000D_
html, body {_x000D_
min-height: 100%;_x000D_
}_x000D_
_x000D_
#message {_x000D_
height: 100%;_x000D_
left: 0;_x000D_
position: fixed;_x000D_
top: 0;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
#message .container {_x000D_
height: 60%;_x000D_
left: 50%;_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
z-index: 10;_x000D_
width: 60%;_x000D_
}_x000D_
_x000D_
#message .container .text {_x000D_
background: #fff;_x000D_
height: 100%;_x000D_
left: -50%;_x000D_
position: absolute;_x000D_
top: -50%;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
#message .bg {_x000D_
background: rgba(0, 0, 0, 0.5);_x000D_
height: 100%;_x000D_
left: 0;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
width: 100%;_x000D_
z-index: 9;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="message">_x000D_
<div class="container">_x000D_
<div class="text">_x000D_
<h2>Warning</h2>_x000D_
<p>The message</p>_x000D_
<p class="close"><a href="#">Close Window</a></p>_x000D_
</div>_x000D_
</div>_x000D_
<div class="bg"></div>_x000D_
</div>
_x000D_
Instagram deprecated their legacy APIs in support for Basic Display API during the late 2019
In Basic Display API you are supposed to use the following API endpoint to get the media id. You will need to supply a valid access token.
https://graph.instagram.com/me/media?fields=id,caption&access_token={access-token}
You can read here on how to configure test account and generate access token on Facebook developer portal.
Here is another article which also describes about how to get access token.
printf(...)
is equivalent to fprintf(stdout,...)
.
fprintf
is used to output to stream.
sprintf(buffer,...)
is used to format a string to a buffer.
Note there is also vsprintf
, vfprintf
and vprintf
To be sure I need to see how you're rendering the form. The initial value is only used in a unbound form, if it's bound and a value for that field is not included nothing will be selected.
double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
You can also manually tag the column with a contrasts
attribute, which seems to be respected by the regression functions:
contrasts(df$factorcol) <- contr.treatment(levels(df$factorcol),
base=which(levels(df$factorcol) == 'RefLevel'))
Random Samples and Permutations ina dataframe If it is in matrix form convert into data.frame use the sample function from the base package indexes = sample(1:nrow(df1), size=1*nrow(df1)) Random Samples and Permutations
Simple and easy :
<form onSubmit="return confirm('Do you want to submit?') ">_x000D_
<input type="submit" />_x000D_
</form>
_x000D_
You could use --where option on mysqldump to produce an output that you are waiting for:
mysqldump -u root -p test t1 --where="1=1 limit 100" > arquivo.sql
At most 100 rows from test.t1 will be dumped from database table.
Cheers, WB
I assume that you haven't set the TableName
property of the DataTable, for example via constructor:
var tbl = new DataTable("dtImage");
If you don't provide a name, it will be automatically created with "Table1"
, the next table will get "Table2"
and so on.
Then the solution would be to provide the TableName
and then check with Contains(nameOfTable)
.
To clarify it: You'll get an ArgumentException
if that DataTable already belongs to the DataSet (the same reference). You'll get a DuplicateNameException
if there's already a DataTable in the DataSet with the same name(not case-sensitive).
Or this:
Range("A2", Range("D" & Rows.Count).End(xlUp).Address).Sort Key1:=[b3], _
Order1:=xlAscending, Header:=xlYes
I had lots of duplicate column names, and once I ran
df = df.loc[:,~df.columns.duplicated()]
I was able to see the full list of columns
IIS express configuration is managed by applicationhost.config.
You can find it in
Users\<username>\Documents\IISExpress\config folder.
Inside you can find the sites section that hold a section for each IIS Express configured site.
Add (or modify) a site section like this:
<site name="WebSiteWithVirtualDirectory" id="20">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="c:\temp\website1" />
</application>
<application path="/OffSiteStuff" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="d:\temp\SubFolderApp" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:1132:localhost" />
</bindings>
</site>
Practically you need to add a new application tag in your site for each virtual directory. You get a lot of flexibility because you can set different configuration for the virtual directory (for example a different .Net Framework version)
EDIT Thanks to Fevzi Apaydin to point to a more elegant solution.
You can achieve same result by adding one or more virtualDirectory tag to the Application tag:
<site name="WebSiteWithVirtualDirectory" id="20">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="c:\temp\website1" />
<virtualDirectory path="/OffSiteStuff" physicalPath="d:\temp\SubFolderApp" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:1132:localhost" />
</bindings>
</site>
Reference:
Similar to other answers but more succinct:
'use strict';
const interfaces = require('os').networkInterfaces();
const addresses = Object.keys(interfaces)
.reduce((results, name) => results.concat(interfaces[name]), [])
.filter((iface) => iface.family === 'IPv4' && !iface.internal)
.map((iface) => iface.address);
Although John Sansom's solution works, there's another way to do this, without having to use a potentially inefficient scalar valued UDF. In the SSRS report, on the parameters tab of the query definition, set the parameter value to
=join(Parameters!<your param name>.Value,",")
In your query, you can then reference the value like so:
where yourColumn in (@<your param name>)
Also iftop:
display bandwidth usage on an interface
iftop does for network usage what top(1) does for CPU usage. It listens to network traffic on a named interface and displays a table of current bandwidth usage by pairs of hosts. Handy for answering the question "why is our ADSL link so slow?"...
Extensions without enough permission on chrome can cause these warnings, for example for React developer tools, check if the following procedure solves your problem:
Or
Then choose "this can read and write site data". You should see 3 options in the list, pick one that is strict enough based on how much you trust the extension and also satisfies the extensions's needs.
Method A is recommended by httpclient developer community.
Please refer http://www.mail-archive.com/[email protected]/msg02455.html for more details.
In order to simulate the issue that you are facing, I created the following sample using SSIS 2008 R2
with SQL Server 2008 R2
backend. The example is based on what I gathered from your question. This example doesn't provide a solution but it might help you to identify where the problem could be in your case.
Created a simple CSV file with two columns namely order number and order date. As you had mentioned in your question, values of both the columns are qualified with double quotes (") and also the lines end with Line Feed (\n) with the date being the last column. The below screenshot was taken using Notepad++, which can display the special characters in a file. LF in the screenshot denotes Line Feed.
Created a simple table named dbo.Destination
in the SQL Server database to populate the CSV file data using SSIS package. Create script for the table is given below.
CREATE TABLE [dbo].[Destination](
[OrderNumber] [varchar](50) NULL,
[OrderDate] [date] NULL
) ON [PRIMARY]
GO
On the SSIS package, I created two connection managers. SQLServer was created using the OLE DB Connection to connect to the SQL Server database. FlatFile is a flat file connection manager.
Flat file connection manager was configured to read the CSV file and the settings are shown below. The red arrows indicate the changes made.
Provided a name to the flat file connection manager. Browsed to the location of the CSV file and selected the file path. Entered the double quote ("
) as the text qualifier. Changed the Header row delimiter from {CR}{LF} to {LF}
. This header row delimiter change also reflects on the Columns section.
No changes were made in the Columns section.
Changed the column name from Column0 to OrderNumber
.
Changed the column name from Column1 to OrderDate
and also changed the data type to date [DT_DATE]
Preview of the data within the flat file connection manager looks good.
On the Control Flow
tab of the SSIS package, placed a Data Flow Task
.
Within the Data Flow Task, placed a Flat File Source
and an OLE DB Destination
.
The Flat File Source
was configured to read the CSV file data using the FlatFile connection manager. Below three screenshots show how the flat file source component was configured.
The OLE DB Destination
component was configured to accept the data from Flat File Source and insert it into SQL Server database table named dbo.Destination
. Below three screenshots show how the OLE DB Destination component was configured.
Using the steps mentioned in the below 5 screenshots, I added a data viewer on the flow between the Flat File Source and OLE DB Destination.
Before running the package, I verified the initial data present in the table. It is currently empty because I created this using the script provided at the beginning of this post.
Executed the package and the package execution temporarily paused to display the data flowing from Flat File Source to OLE DB Destination in the data viewer. I clicked on the run button to proceed with the execution.
The package executed successfully.
Flat file source data was inserted successfully into the table dbo.Destination
.
Here is the layout of the table dbo.Destination. As you can see, the field OrderDate is of data type date and the package still continued to insert the data correctly.
This post even though is not a solution. Hopefully helps you to find out where the problem could be in your scenario.
In (ANSI) C99, you can use a designated initializer to initialize a structure:
MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 };
Edit: Other members are initialized as zero: "Omitted field members are implicitly initialized the same as objects that have static storage duration." (https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html)
The res.json()
function should be sufficient for most cases.
app.get('/', (req, res) => res.json({ answer: 42 }));
The res.json()
function converts the parameter you pass to JSON using JSON.stringify()
and sets the Content-Type
header to application/json; charset=utf-8
so HTTP clients know to automatically parse the response.
Had a similar situation myself. I think it is best to create the tar elsewhere and then use -C to tell tar the base directory for the compressed files. Example:
tar -cjf workspace.tar.gz -C <path_to_workspace> $(ls -A <path_to_workspace>)
This way there is no need to exclude your own tarfile. As noted in other comments, -A will list hidden files.
the following can be used:
install.packages("data.table")
library(data.table)
We store our URLs in a database and load them at runtime.
public class ServiceClientFactory<TChannel> : ClientBase<TChannel> where TChannel : class
{
public TChannel Create(string url)
{
this.Endpoint.Address = new EndpointAddress(new Uri(url));
return this.Channel;
}
}
Implementation
var client = new ServiceClientFactory<yourServiceChannelInterface>().Create(newUrl);
Easy quick solution which worked for me. 1. Go to the root folder. Copy the default.aspx file. 2. Delete the original file. 3. Rename the copied file to default.aspx.
Its all set to experiment again. Not sure how sharepoint referencing these webparts in that page. But works :)
I got pretty good results with my HTML mailing list by using the following:
p { margin-bottom: 0; }
ul { margin-top: 0; }
This does not reset all margin values but only those that create such a gap before ordered list, and still doesn't assume anything about default margin values.
For the record, to force angular to re-render the current page, you can use:
$route.reload();
According to AngularJS documentation:
Causes $route service to reload the current route even if $location hasn't changed.
As a result of that, ngView creates new scope, reinstantiates the controller.
You can use the setTimeout
or setInterval
functions.
>>> s = bytes("s","utf-8")
>>> print(s)
b's'
>>> s = s.decode("utf-8")
>>> print(s)
s
Well if useful for you in case removing annoying 'b' character.If anyone got better idea please suggest me or feel free to edit me anytime in here.I'm just newbie
This code will perform the click operation on the WebElement
"we" after 100 ms:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("var elem=arguments[0]; setTimeout(function() {elem.click();}, 100)", we);
use the time and datetime packages.
if anybody want to execute this script and also find out how much time it took to execute in minutes
import time
from time import strftime
from datetime import datetime
from time import gmtime
def start_time_():
#import time
start_time = time.time()
return(start_time)
def end_time_():
#import time
end_time = time.time()
return(end_time)
def Execution_time(start_time_,end_time_):
#import time
#from time import strftime
#from datetime import datetime
#from time import gmtime
return(strftime("%H:%M:%S",gmtime(int('{:.0f}'.format(float(str((end_time-start_time))))))))
start_time = start_time_()
# your code here #
[i for i in range(0,100000000)]
# your code here #
end_time = end_time_()
print("Execution_time is :", Execution_time(start_time,end_time))
The above code works for me. I hope this helps.
One way to do this without JS is to use the hover action to reveal a HTML element that is otherwise hidden, see this codepen:
http://codepen.io/c0un7z3r0/pen/LZWXEw
Note that the span that contains the tooltip content is relative to the parent li. The magic is here:
ul#list_of_thrones li > span{
display:none;
}
ul#list_of_thrones li:hover > span{
position: absolute;
display:block;
...
}
As you can see, the span is hidden unless the listitem is hovered over, thus revealing the span element, the span can contain as much html as you need. In the codepen attached I have also used a :after element for the arrow but that of course is entirely optional and has only been included in this example for cosmetic purposes.
I hope this helps, I felt compelled to post as all the other answers included JS solutions but the OP asked for a HTML/CSS only solution.
Answer is chmod 755 hello - it makes file executable... It is funny, so no-one answered it. I had same problem on MacOS, which is now solved.
nano hello.c make hello chmod 755 hello Then you run it by ./hello
clang --version Apple LLVM version 8.0.0 (clang-800.0.42.1) Target: x86_64-apple-darwin15.6.0
nothing was installed, nano make (clang) chmod - all inside MacOS already
I had the same problem here. In my case I need to use an old version of JDK and I'm using sdkmanager to manage the versions of JDK, so, I changed the version of the virtual machine to 1.8.
sdk use java 8.0.222.j9-adpt
After that, the app runs as expected here.
grep -rnw "some thing to grep" --include=*.{module,inc,php,js,css,html,htm} ./
Solved by downgrading Node.js version from 12.14.0
to 10.18.0
and reinstalling node_modules
.
Even better, you do not need to create separate android xml layout for list cell view. You can just use "android.R.layout.simple_list_item_1" if the list only contains textview.
private class ExampleAdapter extends ArrayAdapter<String>{
public ExampleAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setTextColor(0);
return view;
}
Nothing.
$('#content').click(function(e) {
alert(1);
});
Will bind to an existing HTML element with the ID set to content
, and will show a message box on click.
#content
exists before using that codeyou can use a string formatter to pad any integer with zeros. It acts just like C's printf
.
>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'
Updated for py36: Use f-strings! For general int
s you can use the d
formatter and explicitly tell it to pad with zeros:
>>> d = datetime.date.today()
>>> f"{d.month:02d}"
'07'
But datetime
s are special and come with special formatters that are already zero padded:
>>> f"{d:%d}" # the day
'01'
>>> f"{d:%m}" # the month
'07'
your elemId
as its name suggests, is an Id
attribute, these are all you can do to check if it exists:
Vanilla JavaScript: in case you have more advanced selectors:
//you can use it for more advanced selectors
if(document.querySelectorAll("#elemId").length){}
if(document.querySelector("#elemId")){}
//you can use it if your selector has only an Id attribute
if(document.getElementById("elemId")){}
jQuery:
if(jQuery("#elemId").length){}
I kept getting results in seconds, so this worked for me:
(Time.now - self.created_at) / 86400
If you know the type of numbers you are going to store, your can choose accordingly. In this case your have 'id' which can never be negative. So you can use unsigned int. Range of signed int: -n/2 to +n/2 Range of unsigned int: 0 to n So you have twice the number of positive numbers available. Choose accordingly.
Function overloading
- functions with same name, but different number of arguments
Function overriding
- concept of inheritance. Functions with same name and same number of arguments. Here the second function is said to have overridden the first
"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.
Check that you don't send ANY content before calling session_start
. Better yet, just make session_start
the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).
I was attempting something similar, and the RoboSpice example helped me work it out:
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");
HttpEntity<String> request = new HttpEntity<>(input, createHeader());
String url = "http://awesomesite.org";
Uri.Builder uriBuilder = Uri.parse(url).buildUpon();
uriBuilder.appendQueryParameter(key, value);
uriBuilder.appendQueryParameter(key, value);
...
String url = uriBuilder.build().toString();
HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request , String.class);
Refer to this:
<a href="Http://WWW.stackoverflow.com">Link to the website opened in different tab</a>
<a href="#MyDive">Link to the div in the page(look at the chaneged url)</a>
<a href="javascript:;">Nothing happens if there is no javaScript to render</a>
As an addition to e.g. @Intrepidd s answer, in certain situations you want to use fetch
instead of []
. For fetch
not to throw an exception when the key is not found, pass it a default value.
puts "ok" if hash.fetch('key', nil) == 'X'
Reference: https://docs.ruby-lang.org/en/2.3.0/Hash.html .
If you're using Matplotlib interactively, for example in a web application, (e.g. ipython) you maybe looking for
plt.show()
instead of plt.close()
or plt.clf()
.
For objects, you may not be able to use the cast operator. Instead, I use the json_encode()
method.
For example, the following will output contents to the error log:
error_log(json_encode($args));
David's answer is correct, but if it's still a little abstract, here are two examples:
You might want to zero all freed pointers to catch memory problems earlier. C-style you'd do:
void freeAndZero(void** ptr)
{
free(*ptr);
*ptr = 0;
}
void* ptr = malloc(...);
...
freeAndZero(&ptr);
In C++ to do the same, you might do:
template<class T> void freeAndZero(T* &ptr)
{
delete ptr;
ptr = 0;
}
int* ptr = new int;
...
freeAndZero(ptr);
When dealing with linked-lists - often simply represented as pointers to a next node:
struct Node
{
value_t value;
Node* next;
};
In this case, when you insert to the empty list you necessarily must change the incoming pointer because the result is not the NULL
pointer anymore. This is a case where you modify an external pointer from a function, so it would have a reference to pointer in its signature:
void insert(Node* &list)
{
...
if(!list) list = new Node(...);
...
}
There's an example in this question.
Use subquery
SELECT * FROM RES_DATA inner join (SELECT [CUSTOMER ID], sum([TOTAL AMOUNT]) FROM INV_DATA group by [CUSTOMER ID]) T on RES_DATA.[CUSTOMER ID] = t.[CUSTOMER ID]
It's usually describes as for optional add-on software packages
source, or anything that isn't part of the base system. Only some distributions use it, others simply use /usr/local
.
Errors and exceptions in PowerShell are structured objects. The error message you see printed on the console is actually a formatted message with information from several elements of the error/exception object. You can (re-)construct it yourself like this:
$formatstring = "{0} : {1}`n{2}`n" +
" + CategoryInfo : {3}`n" +
" + FullyQualifiedErrorId : {4}`n"
$fields = $_.InvocationInfo.MyCommand.Name,
$_.ErrorDetails.Message,
$_.InvocationInfo.PositionMessage,
$_.CategoryInfo.ToString(),
$_.FullyQualifiedErrorId
$formatstring -f $fields
If you just want the error message displayed in your catch
block you can simply echo the current object variable (which holds the error at that point):
try {
...
} catch {
$_
}
If you need colored output use Write-Host
with a formatted string as described above:
try {
...
} catch {
...
Write-Host -Foreground Red -Background Black ($formatstring -f $fields)
}
With that said, usually you don't want to just display the error message as-is in an exception handler (otherwise the -ErrorAction Stop
would be pointless). The structured error/exception objects provide you with additional information that you can use for better error control. For instance you have $_.Exception.HResult
with the actual error number. $_.ScriptStackTrace
and $_.Exception.StackTrace
, so you can display stacktraces when debugging. $_.Exception.InnerException
gives you access to nested exceptions that often contain additional information about the error (top level PowerShell errors can be somewhat generic). You can unroll these nested exceptions with something like this:
$e = $_.Exception
$msg = $e.Message
while ($e.InnerException) {
$e = $e.InnerException
$msg += "`n" + $e.Message
}
$msg
In your case the information you want to extract seems to be in $_.ErrorDetails.Message
. It's not quite clear to me if you have an object or a JSON string there, but you should be able to get information about the types and values of the members of $_.ErrorDetails
by running
$_.ErrorDetails | Get-Member
$_.ErrorDetails | Format-List *
If $_.ErrorDetails.Message
is an object you should be able to obtain the message string like this:
$_.ErrorDetails.Message.message
otherwise you need to convert the JSON string to an object first:
$_.ErrorDetails.Message | ConvertFrom-Json | Select-Object -Expand message
Depending what kind of error you're handling, exceptions of particular types might also include more specific information about the problem at hand. In your case for instance you have a WebException
which in addition to the error message ($_.Exception.Message
) contains the actual response from the server:
PS C:\> $e.Exception | Get-Member TypeName: System.Net.WebException Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj), bool _Exception.E... GetBaseException Method System.Exception GetBaseException(), System.Excep... GetHashCode Method int GetHashCode(), int _Exception.GetHashCode() GetObjectData Method void GetObjectData(System.Runtime.Serialization.S... GetType Method type GetType(), type _Exception.GetType() ToString Method string ToString(), string _Exception.ToString() Data Property System.Collections.IDictionary Data {get;} HelpLink Property string HelpLink {get;set;} HResult Property int HResult {get;} InnerException Property System.Exception InnerException {get;} Message Property string Message {get;} Response Property System.Net.WebResponse Response {get;} Source Property string Source {get;set;} StackTrace Property string StackTrace {get;} Status Property System.Net.WebExceptionStatus Status {get;} TargetSite Property System.Reflection.MethodBase TargetSite {get;}
which provides you with information like this:
PS C:\> $e.Exception.Response IsMutuallyAuthenticated : False Cookies : {} Headers : {Keep-Alive, Connection, Content-Length, Content-T...} SupportsHeaders : True ContentLength : 198 ContentEncoding : ContentType : text/html; charset=iso-8859-1 CharacterSet : iso-8859-1 Server : Apache/2.4.10 LastModified : 17.07.2016 14:39:29 StatusCode : NotFound StatusDescription : Not Found ProtocolVersion : 1.1 ResponseUri : http://www.example.com/ Method : POST IsFromCache : False
Since not all exceptions have the exact same set of properties you may want to use specific handlers for particular exceptions:
try {
...
} catch [System.ArgumentException] {
# handle argument exceptions
} catch [System.Net.WebException] {
# handle web exceptions
} catch {
# handle all other exceptions
}
If you have operations that need to be done regardless of whether an error occured or not (cleanup tasks like closing a socket or a database connection) you can put them in a finally
block after the exception handling:
try {
...
} catch {
...
} finally {
# cleanup operations go here
}
Everyone who answered before me is correct. You use it kind of as an alias shortcut name for a table when you have long queries or queries that have joins. Here's a couple examples.
Example 1
SELECT P.ProductName,
P.ProductGroup,
P.ProductRetailPrice
FROM Products AS P
Example 2
SELECT P.ProductName,
P.ProductRetailPrice,
O.Quantity
FROM Products AS P
LEFT OUTER JOIN Orders AS O ON O.ProductID = P.ProductID
WHERE O.OrderID = 123456
Example 3 It's a good practice to use the AS keyword, and very recommended, but it is possible to perform the same query without one (and I do often).
SELECT P.ProductName,
P.ProductRetailPrice,
O.Quantity
FROM Products P
LEFT OUTER JOIN Orders O ON O.ProductID = P.ProductID
WHERE O.OrderID = 123456
As you can tell, I left out the AS keyword in the last example. And it can be used as an alias.
Example 4
SELECT P.ProductName AS "Product",
P.ProductRetailPrice AS "Retail Price",
O.Quantity AS "Quantity Ordered"
FROM Products P
LEFT OUTER JOIN Orders O ON O.ProductID = P.ProductID
WHERE O.OrderID = 123456
Output of Example 4
Product Retail Price Quantity Ordered
Blue Raspberry Gum $10 pk/$50 Case 2 Cases
Twizzler $5 pk/$25 Case 10 Cases
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
Static NSString *CellIdentifier = @"Cell";
QTStaffViewCell *cell = (QTStaffViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
If (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"QTStaffViewCell" owner:self options:nil];
cell = [nib objectAtIndex: 0];
}
StaffData = [self.staffArray objectAtIndex:indexPath.row];
NSString *title = StaffData.title;
NSString *fName = StaffData.firstname;
NSString *lName = StaffData.lastname;
UIFont *FedSanDemi = [UIFont fontWithName:@"Aller" size:18];
cell.drName.text = [NSString stringWithFormat:@"%@ %@ %@", title,fName,lName];
[cell.drName setFont:FedSanDemi];
UIFont *aller = [UIFont fontWithName:@"Aller" size:14];
cell.drJob.text = StaffData.job;
[cell.drJob setFont:aller];
if ([StaffData.title isEqualToString:@"Dr"])
{
cell.drJob.frame = CGRectMake(83, 26, 227, 40);
}
else
{
cell.drJob.frame = CGRectMake(90, 26, 227, 40);
}
if ([StaffData.staffPhoto isKindOfClass:[NSString class]])
{
NSURL *url = [NSURL URLWithString:StaffData.staffPhoto];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url
completionHandler:^(NSURL *location,NSURLResponse *response, NSError *error) {
NSData *imageData = [NSData dataWithContentsOfURL:location];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_sync(dispatch_get_main_queue(),
^{
cell.imageView.image = image;
});
}];
[task resume];
}
return cell;}
You can pass PHP arrays to JavaScript using json_encode
PHP function.
<?php
$phpArray = array(
0 => "Mon",
1 => "Tue",
2 => "Wed",
3 => "Thu",
4 => "Fri",
5 => "Sat",
6 => "Sun",
)
?>
<script type="text/javascript">
var jArray = <?php echo json_encode($phpArray); ?>;
for(var i=0; i<jArray.length; i++){
alert(jArray[i]);
}
</script>
data.removeAll(data);
will do the work, I think.
Here's an example of how to do it in C.
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void segfault_sigaction(int signal, siginfo_t *si, void *arg)
{
printf("Caught segfault at address %p\n", si->si_addr);
exit(0);
}
int main(void)
{
int *foo = NULL;
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sigemptyset(&sa.sa_mask);
sa.sa_sigaction = segfault_sigaction;
sa.sa_flags = SA_SIGINFO;
sigaction(SIGSEGV, &sa, NULL);
/* Cause a seg fault */
*foo = 1;
return 0;
}
The currently accepted answer is incorrect. It is NOT required to set maxBufferSize
and maxReceivedMessageSize
on the client and the server binding. It depends!
If your request is too large (i.e., method parameters of the service operation are memory intensive) set the properties on the server-side, if the response is too large (i.e., the method return value of the service operation is memory intensive) set the values on the client-side.
For the difference between maxBufferSize
and maxReceivedMessageSize
see MaxBufferSize property?.
If you want information about all exceptions then use exception.ToString()
. It will collect data from all inner exceptions.
If you want only the original exception then use exception.GetBaseException().ToString()
. This will get you the first exception, e.g. the deepest inner exception or the current exception if there is no inner exception.
Example:
try {
Exception ex1 = new Exception( "Original" );
Exception ex2 = new Exception( "Second", ex1 );
Exception ex3 = new Exception( "Third", ex2 );
throw ex3;
} catch( Exception ex ) {
// ex => ex3
Exception baseEx = ex.GetBaseException(); // => ex1
}
if you add a jpg,png,pdf picture, you should use pdflatex to compile it.
It works on firefox, if you change onClick() to click() in javascript part.
$("img.foo").click(function()_x000D_
{_x000D_
// Get the src of the image_x000D_
var src = $(this).attr("src");_x000D_
_x000D_
// Send Ajax request to backend.php, with src set as "img" in the POST data_x000D_
$.post("/backend.php", {"img": src});_x000D_
});
_x000D_
If you set a variable via SETX, you cannot use this variable or its changes immediately. You have to restart the processes that want to use it.
Use the following sequence to directly set it in the setting process too (works for me perfectly in scripts that do some init stuff after setting global variables):
SET XYZ=test
SETX XYZ test
For anyone coming along later, like I did, and seeing this...
I was receiving the same error because I did not have the extension "enabled" in my php.ini file. I would imagine you might also get this error if you have recently upgraded your php version and did not properly update your php.ini file.
If you are receiving this error shortly after upgrading your php version, the info below might help you out:
PHP 7.4 slightly changed its syntax in the php.ini file.
Now, to enable the mysql pdo, make sure extension=pdo_mysql
is uncommented in your php.ini file. (line 931 in the default php.ini setup)
The line used to be:
extension=php_pdo_mysql.dll on Windows
extension=php_pdo_mysql.so on Linux/Mac
as Sk8erPeter pointed out. but the .dll and .so endings are to be deprecated and so it is best practice to begin getting rid of those endings and using just extension=<ext>
The below is pulled from the default php.ini-production file from the php 7.4 zip download under "Dynamic Extensions":
Note : The syntax used in previous PHP versions ('extension=.so' and 'extension='php_.dll') is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (
extension=<ext>
) syntax.
You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.
You can Start the android Service by this command.
adb shell am startservice -n packageName/.ServiceClass
I had to do 2 things: Do what Joseph Wu said and change the authentication to be SQL and Windows. But I also had to go to Server Properties > Advanced and change "Enable Contained Databases" to True.
check "git status" and "git pull" in the shell and find out what's wrong. and my problem is http.proxy node in config, therefore Github Windows should much more smart like just pop the shell and give more tips after the error(s) emit.
Can you show code which you use for setting date object? Anyway< you can use this code for intialisation of date:
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2011-01-01 00:00:00")
If you want to center map onto a marker and you have the cordinate, something like click on a list item and the map should center on that coordinate then the following code will work:
In HTML:
<ul class="locationList" ng-repeat="LocationDetail in coordinateArray| orderBy:'LocationName'">
<li>
<div ng-click="focusMarker(LocationDetail)">
<strong><div ng-bind="locationDetail.LocationName"></div></strong>
<div ng-bind="locationDetail.AddressLine"></div>
<div ng-bind="locationDetail.State"></div>
<div ng-bind="locationDetail.City"></div>
<div>
</li>
</ul>
In Controller:
$scope.focusMarker = function (coords) {
map.setCenter(new google.maps.LatLng(coords.Latitude, coords.Longitude));
map.setZoom(14);
}
Location Object:
{
"Name": "Taj Mahal",
"AddressLine": "Tajganj",
"City": "Agra",
"State": "Uttar Pradesh",
"PhoneNumber": "1234 12344",
"Latitude": "27.173891",
"Longitude": "78.042068"
}
orphanRemoval
has nothing to do with ON DELETE CASCADE
.
orphanRemoval
is an entirely ORM-specific thing. It marks "child" entity to be removed when it's no longer referenced from the "parent" entity, e.g. when you remove the child entity from the corresponding collection of the parent entity.
ON DELETE CASCADE
is a database-specific thing, it deletes the "child" row in the database when the "parent" row is deleted.
ngStyle
accepts a map:
$scope.myStyle = {
"width" : "900px",
"background" : "red"
};
plot.new() error occurs when only part of the function is ran.
Please find the attachment for an example to correct error With error....When abline is ran without plot() above Error-free ...When both plot and abline ran together
Yes, you should be able to set its height and width, as with any element. However, some browsers do not really take these properties into account.
This demo gives an overview of what is possible and how it is displayed in various browsers: https://www.456bereastreet.com/lab/styling-form-controls-revisited/radio-button/
As you'll see, styling radio buttons is not easy :-D
A workaround is to use JavaScript and CSS to replace the radio buttons and other form elements with custom images:
You can do something like this, than you you'll access the native mongodb functions inside mongoose:
var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/local');
var connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', function () {
connection.db.collection("YourCollectionName", function(err, collection){
collection.find({}).toArray(function(err, data){
console.log(data); // it will print your collection data
})
});
});
Wouldn't it just be:
SELECT CURRENT_DATE - CHDLM FROM CHCART00 WHERE CHSTAT = '05';
That should return the number of days between the two dates, if I understand how date arithmetic works in DB2 correctly.
If CHDLM isn't a date you'll have to convert it to one. According to IBM the DATE() function would not be sufficient for the yyyymmdd format, but it would work if you can format like this: yyyy-mm-dd.
<asp:GridView ID="grd_item_list" runat="server" AutoGenerateColumns="false" Width="100%" CssClass="table table-bordered table-hover" OnRowCommand="grd_item_list_RowCommand">
<Columns>
<asp:TemplateField HeaderText="No">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:Button ID="remove_itemIndex" OnClientClick="if(confirm('Are You Sure to delete?')==true){ return true;} else{ return false;}" runat="server" class="btn btn-primary" Text="REMOVE" CommandName="REMOVE_ITEM" CommandArgument='<%# Container.DataItemIndex+1 %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
**This is the row binding event**
protected void grd_item_list_RowCommand(object sender, GridViewCommandEventArgs e) {
item_list_bind_structure();
if (ViewState["item_list"] != null)
dt = (DataTable)ViewState["item_list"];
if (e.CommandName == "REMOVE_ITEM") {
var RowNum = Convert.ToInt32(e.CommandArgument.ToString()) - 1;
DataRow dr = dt.Rows[RowNum];
dr.Delete();
}
grd_item_list.DataSource = dt;
grd_item_list.DataBind();
}
You can also get it by just adding this line in your JavaScript code:
document.getElementById('<%=btnName.ClientID%>').click()
I think this one is very much easy!
You only need the async
pipe:
<li *ngFor="let afd of afdeling | async">
{{afd.patientid}}
</li>
always use the async
pipe when dealing with Observables directly without explicitly unsubscribe.
(function ($) {
$.fn.inputFilter = function (inputFilter) {
return this.on('input keydown keyup mousedown mouseup select contextmenu drop', function () {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty('oldValue')) {
this.value = this.oldValue;
//this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = '';
}
});
};
})(jQuery);
$('.positive_int').inputFilter(function (value) {
return /^\d*[.]?\d{0,2}$/.test(value);
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="positive_int"/>
_x000D_
Above code works fine for all !!! And it will also prevent inserting more than 2 decimal points. And if you don't need this just remove\d{0,2} or if need more limited decimal point just change number 2
You can also use git-copy.
Install it with Gem,
gem install git-copy
Then
git copy https://github.com/exampleuser/old-repository.git \
https://github.com/exampleuser/new-repository.git
Here you go:
$(document).ready(function(){
$('#submenu li').hover(function(){
$('#carousel').css('background-position', '10px 10px');
}, function(){
$('#carousel').css('background-position', '');
});
});
Very simple piece of code to do this
$date - extract(day from $date) + 1
two ways to do this:
my_date - extract(day from my_date) + 1
'2014/01/21' - extract(day from '2014/01/21') + 1
git tag -d your_tag_name
git push origin :refs/tags/your_tag_name
The first line deletes your_tag_name
from local repo and second line deletes your_tag_name
from remote repo.
For those who use GitHub, one more step is needed: discarding draft.
You have to add this to your pg_hba.conf and restart your PostgreSQL.
host all all 192.168.56.1/24 md5
This works with VirtualBox and host-only adapter enabled. If you don't use Virtualbox you have to replace the IP address.
Most of these answers seem to ignore the possibility of using the word boundary metacharacter (\b). A shorter version of Greg Dean's answer utilizing it:
function toTitleCase(str)
{
return str.replace(/\b\w/g, function (txt) { return txt.toUpperCase(); });
}
Works for hyphenated names like Jim-Bob too.
As it was mentioned, there is no direct equivalent, but very close approximation could be created with Java bytecode modifications (for both async/await-like instructions and underlying continuations implementation).
I'm working right now on a project that implements async/await on top of JavaFlow continuation library, please check https://github.com/vsilaev/java-async-await
No Maven mojo is created yet, but you may run examples with supplied Java agent. Here is how async/await code looks like:
public class AsyncAwaitNioFileChannelDemo {
public static void main(final String[] argv) throws Exception {
...
final AsyncAwaitNioFileChannelDemo demo = new AsyncAwaitNioFileChannelDemo();
final CompletionStage<String> result = demo.processFile("./.project");
System.out.println("Returned to caller " + LocalTime.now());
...
}
public @async CompletionStage<String> processFile(final String fileName) throws IOException {
final Path path = Paths.get(new File(fileName).toURI());
try (
final AsyncFileChannel file = new AsyncFileChannel(
path, Collections.singleton(StandardOpenOption.READ), null
);
final FileLock lock = await(file.lockAll(true))
) {
System.out.println("In process, shared lock: " + lock);
final ByteBuffer buffer = ByteBuffer.allocateDirect((int)file.size());
await( file.read(buffer, 0L) );
System.out.println("In process, bytes read: " + buffer);
buffer.rewind();
final String result = processBytes(buffer);
return asyncResult(result);
} catch (final IOException ex) {
ex.printStackTrace(System.out);
throw ex;
}
}
@async is the annotation that flags a method as asynchronously executable, await() is a function that waits on CompletableFuture using continuations and a call to "return asyncResult(someValue)" is what finalizes associated CompletableFuture/Continuation
As with C#, control flow is preserved and exception handling may be done in regular manner (try/catch like in sequentially executed code)
How to do it programatically :
To enable EditText use:
et.setEnabled(true);
To disable EditText use:
et.setEnabled(false);
To add to Oleg's answer:
I was able to find the DLL at runtime by appending Visual Studio's $(ExecutablePath)
to the PATH environment variable in Configuration Properties->Debugging. This macro is exactly what's defined in the Configuration Properties->VC++ Directories->Executable Directories field*, so if you have that setup to point to any DLLs you need, simply adding this to your PATH makes finding the DLLs at runtime easy!
* I actually don't know if the $(ExecutablePath)
macro uses the project's Executable Directories setting or the global Property Pages' Executable Directories setting. Since I have all of my libraries that I often use configured through the Property Pages, these directories show up as defaults for any new projects I create.
I've created an example to show how to. Updated state
definition would be:
$stateProvider
.state('home', {
url: '/:foo?bar',
views: {
'': {
templateUrl: 'tpl.home.html',
controller: 'MainRootCtrl'
},
...
}
And this would be the controller:
.controller('MainRootCtrl', function($scope, $state, $stateParams) {
//..
var foo = $stateParams.foo; //getting fooVal
var bar = $stateParams.bar; //getting barVal
//..
$scope.state = $state.current
$scope.params = $stateParams;
})
What we can see is that the state home now has url defined as:
url: '/:foo?bar',
which means, that the params in url are expected as
/fooVal?bar=barValue
These two links will correctly pass arguments into the controller:
<a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})">
<a ui-sref="home({foo: 'fooVal2', bar: 'barVal2'})">
Also, the controller does consume $stateParams
instead of $stateParam
.
Link to doc:
You can check it here
params : {}
There is also new, more granular setting params : {}
. As we've already seen, we can declare parameters as part of url
. But with params : {}
configuration - we can extend this definition or even introduce paramters which are not part of the url:
.state('other', {
url: '/other/:foo?bar',
params: {
// here we define default value for foo
// we also set squash to false, to force injecting
// even the default value into url
foo: {
value: 'defaultValue',
squash: false,
},
// this parameter is now array
// we can pass more items, and expect them as []
bar : {
array : true,
},
// this param is not part of url
// it could be passed with $state.go or ui-sref
hiddenParam: 'YES',
},
...
Settings available for params are described in the documentation of the $stateProvider
Below is just an extract
We can call these params this way:
// hidden param cannot be passed via url
<a href="#/other/fooVal?bar=1&bar=2">
// default foo is skipped
<a ui-sref="other({bar: [4,5]})">
Check it in action here
There are different ways to do this some of them has given.
implode(), join(), var_export(), print_r(), serialize(), json_encode()
exc... You can also write your own function without these:
A For()
loop is very useful. You can add your array's value to another variable like this:
<?php
$dizi=array('mother','father','child'); //This is array
$sayi=count($dizi);
for ($i=0; $i<$sayi; $i++) {
$dizin.=("'$dizi[$i]',"); //Now it is string...
}
echo substr($dizin,0,-1); //Write it like string :D
?>
In this code we added $dizi's values and comma to $dizin:
$dizin.=("'$dizi[$i]',");
Now
$dizin = 'mother', 'father', 'child',
It's a string, but it has an extra comma :)
And then we deleted the last comma, substr($dizin, 0, -1);
Output:
'mother','father','child'
That's because your input string can’t be converted according to the encoding rules (strict by default).
I don't know, but I always encoded using directly unicode() constructor, at least that's the ways at the official documentation:
unicode(your_str, errors="ignore")
You need to convert your image to a numpy array this way:
import numpy
import PIL
img = PIL.Image.open("foo.jpg").convert("L")
imgarr = numpy.array(img)
If you don't need full debugging support, you can now view JavaScript console logs directly within Chrome for iOS at chrome://inspect.
https://blog.chromium.org/2019/03/debugging-websites-in-chrome-for-ios.html
Start your OnClickListener, but when you get to the first set up parenthesis, type new, then View, and press enter. Should look like this when you're done:
Button btn1 = (Button)findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//your stuff here.
}
});
Regex.Matches(input, "true").Count
None of the answers here quite hit the nail on the head.
How to store a datetime in MySQL with timezone info
Use two columns: DATETIME
, and a VARCHAR
to hold the time zone information, which may be in several forms:
A timezone or location such as America/New_York
is the highest data fidelity.
A timezone abbreviation such as PST
is the next highest fidelity.
A time offset such as -2:00
is the smallest amount of data in this regard.
Some key points:
TIMESTAMP
because it's limited to the year 2038, and MySQL relates it to the server timezone, which is probably undesired.INT
field, because there are half-hour and quarter-hour offsets.If it's important for your use case to have MySQL compare or sort these dates chronologically, DATETIME
has a problem:
'2009-11-10 11:00:00 -0500'
is before '2009-11-10 10:00:00 -0700'
in terms of "instant in time", but they would sort the other way when inserted into a DATETIME
.
You can do your own conversion to UTC. In the above example, you would then have '2009-11-10 16:00:00'
and '2009-11-10 17:00:00'
respectively, which would sort correctly. When retrieving the data, you would then use the timezone info to revert it to its original form.
One recommendation which I quite like is to have three columns:
local_time DATETIME
utc_time DATETIME
time_zone VARCHAR(X)
where X is appropriate for what kind of data you're storing there. (I would choose 64 characters for timezone/location.)An advantage to the 3-column approach is that it's explicit: with a single DATETIME
column, you can't tell at a glance if it's been converted to UTC before insertion.
Regarding the descent of accuracy through timezone/abbreviation/offset:
America/Juneau
, you can know accurately what the wall clock time is for them at any point in the past or future (barring changes to the way Daylight Savings is handled in that location). The start/end points of DST, and whether it's used at all, are dependent upon location, so this is the only reliable way.-0700
, you will be unable to predict a wall clock time in the past or future. For example, in the United States, Colorado and Arizona both use MST, but Arizona doesn't observe DST. So if the user uploads his cat photo at 14:00 -0700
during the winter months, was he in Arizona or California? If you added six months exactly to that date, would it be 14:00
or 13:00
for the user?These things are important to consider when your application has time, dates, or scheduling as core function.
References:
I would suggest doing this in a more functional style :P
function CreateMessageboard(BoardMessages) {
var htmlMessageboardString = BoardMessages
.map(function(BoardMessage) {
return MessageToHTMLString(BoardMessage);
})
.join('');
}
Try this