Just for the sake of completeness, here is a link to the golang documentation which describes all types. In your case it is numeric types:
uint8 the set of all unsigned 8-bit integers (0 to 255)
uint16 the set of all unsigned 16-bit integers (0 to 65535)
uint32 the set of all unsigned 32-bit integers (0 to 4294967295)
uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)
int8 the set of all signed 8-bit integers (-128 to 127)
int16 the set of all signed 16-bit integers (-32768 to 32767)
int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
float32 the set of all IEEE-754 32-bit floating-point numbers
float64 the set of all IEEE-754 64-bit floating-point numbers
complex64 the set of all complex numbers with float32 real and imaginary parts
complex128 the set of all complex numbers with float64 real and imaginary parts
byte alias for uint8
rune alias for int32
Which means that you need to use float64(integer_value)
.
you can implement double-tap using the GestureDetectorCompat
class.
in this sample when double-tap on textview you can do your logic.
public class MainActivity extends AppCompatActivity {
GestureDetectorCompat gestureDetectorCompat;
TextView textElement;
@Override
protected void onCreate(Bundle savedInstanceState) {
.....
textElement = findViewById(R.id.textElement);
gestureDetectorCompat = new GestureDetectorCompat(this, new MyGesture());
textElement.setOnTouchListener(onTouchListener);
}
View.OnTouchListener onTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
gestureDetectorCompat.onTouchEvent(event);
return true;
}
};
class MyGesture extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
// whatever on double click
return true;
}
}
I'm doing this on my raspberry pi from the command line by running:
for i in *;do omxplayer "$i";done
Class Parent cannot be declared because it is PHP reserved keyword so in effect it's already in use
If X
can really be cast to Y
you should be able to use
List<Y> listOfY = listOfX.Cast<Y>().ToList();
Some things to be aware of (H/T to commenters!)
using System.Linq;
to get this extension methodList<Y>
will be created by the call to ToList()
.You need to write a little PHP code. When user first click tab you can check is he like the page or not. Below is the sample code
include_once("facebook.php");
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true,
));
$signed_request = $facebook->getSignedRequest();
// Return you the Page like status
$like_status = $signed_request["page"]["liked"];
if($like_status)
{
echo 'User Liked the page';
// Place some content you wanna show to user
}else{
echo 'User do not liked the page';
// Place some content that encourage user to like the page
}
I have a one-liner answer (this example gives you 999 lines of data and one header row per file)
cat bigFile.csv | parallel --header : --pipe -N999 'cat >file_{#}.csv'
keytool -printcert -file ANDROID_.RSA or keytool -list -printcert -jarfile app.apk
to obtain the hash md5keytool -list -v -keystore clave-release.jks
You missed the *
in front of NgIf (like we all have, dozens of times):
<div *ngIf="answer.accepted">✔</div>
Without the *
, Angular sees that the ngIf
directive is being applied to the div
element, but since there is no *
or <template>
tag, it is unable to locate a template, hence the error.
If you get this error with Angular v5:
Error: StaticInjectorError[TemplateRef]:
StaticInjectorError[TemplateRef]:
NullInjectorError: No provider for TemplateRef!
You may have <template>...</template>
in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>
.
Dim dr As DataRow()
dr = dt.Select("A="& a & "and B="& b & "and C=" & c,"A",DataViewRowState.CurrentRows)
Where A,B,C are the column names where second parameter is for sort expression
Now you can also use Talentsoft.Moq.SetupAsync package https://github.com/TalentSoft/Moq.SetupAsync
Which on the base on the answers found here and ideas proposed to Moq but still not yet implemented here: https://github.com/moq/moq4/issues/384, greatly simplify setup of async methods
Few examples found in previous responses done with SetupAsync extension:
mock.SetupAsync(arg=>arg.DoSomethingAsync());
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Callback(() => { <my code here> });
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Throws(new InvalidOperationException());
I was playing with this and came up with an alternative.
$ VAR=/home/me/mydir/file.c
$ DIR=`echo $VAR |xargs dirname`
$ echo $DIR
/home/me/mydir
The part I liked is it was easy to extend backup the tree:
$ DIR=`echo $VAR |xargs dirname |xargs dirname |xargs dirname`
$ echo $DIR
/home
Use the hashchange
event:
window.addEventListener("hashchange", function(e) {
// ...
})
If you need to support older browsers, check out the hashChange
Event section in Modernizr's HTML5 Cross Browser Polyfills wiki page.
Run it as a CGI-script via a simple http call, AJAX, whatever - with the coordinates you want to move the mouse to, eg:
http://localhost:9876/cgi/mousemover?x=200&y=450
PS: For any problem, there are hundreds of excuses as to why, and how - it can't, and shouldn't - be done.. But in this infinite universe, it's really just a matter of determination - as to whether YOU will make it happen.
You can not get hive version from command line.
You can checkout hadoop version as mentioned by Dave.
Also if you are using cloudera distribution, then look directly at the libs:
ls /usr/lib/hive/lib/ and check for hive library
hive-hwi-0.7.1-cdh3u3.jar
You can also check the compatible versions here:
I have created tool similar to Ned Batchelder:
Searching .dll and .exe files in PATH
While my tool is primarly for searching of various dll versions it shows more info (date, size, version) but it do not use PATHEXT (I hope to update my tool soon).
The easiest thing to do would be to insert the elements with the disabled
attribute.
<input type="hidden" name="not_gonna_submit" disabled="disabled" value="invisible" />
This way you can still access them as children of the form.
Disabled fields have the downside that the user can't interact with them at all- so if you have a disabled
text field, the user can't select the text. If you have a disabled
checkbox, the user can't change its state.
You could also write some javascript to fire on form submission to remove the fields you don't want to submit.
The == operator, also known as equality or double equal, will return true if both objects are equal and false if they are not.
"koan" == "koan" # Output: => true
The != operator, also known as inequality, is the opposite of ==. It will return true if both objects are not equal and false if they are equal.
"koan" != "discursive thought" # Output: => true
Note that two arrays with the same elements in a different order are not equal, uppercase and lowercase versions of the same letter are not equal and so on.
When comparing numbers of different types (e.g., integer and float), if their numeric value is the same, == will return true.
2 == 2.0 # Output: => true
Unlike the == operator which tests if both operands are equal, the equal method checks if the two operands refer to the same object. This is the strictest form of equality in Ruby.
Example: a = "zen" b = "zen"
a.object_id # Output: => 20139460
b.object_id # Output :=> 19972120
a.equal? b # Output: => false
In the example above, we have two strings with the same value. However, they are two distinct objects, with different object IDs. Hence, the equal? method will return false.
Let's try again, only this time b will be a reference to a. Notice that the object ID is the same for both variables, as they point to the same object.
a = "zen"
b = a
a.object_id # Output: => 18637360
b.object_id # Output: => 18637360
a.equal? b # Output: => true
In the Hash class, the eql? method it is used to test keys for equality. Some background is required to explain this. In the general context of computing, a hash function takes a string (or a file) of any size and generates a string or integer of fixed size called hashcode, commonly referred to as only hash. Some commonly used hashcode types are MD5, SHA-1, and CRC. They are used in encryption algorithms, database indexing, file integrity checking, etc. Some programming languages, such as Ruby, provide a collection type called hash table. Hash tables are dictionary-like collections which store data in pairs, consisting of unique keys and their corresponding values. Under the hood, those keys are stored as hashcodes. Hash tables are commonly referred to as just hashes. Notice how the word hashcan refer to a hashcode or to a hash table. In the context of Ruby programming, the word hash almost always refers to the dictionary-like collection.
Ruby provides a built-in method called hash for generating hashcodes. In the example below, it takes a string and returns a hashcode. Notice how strings with the same value always have the same hashcode, even though they are distinct objects (with different object IDs).
"meditation".hash # Output: => 1396080688894079547
"meditation".hash # Output: => 1396080688894079547
"meditation".hash # Output: => 1396080688894079547
The hash method is implemented in the Kernel module, included in the Object class, which is the default root of all Ruby objects. Some classes such as Symbol and Integer use the default implementation, others like String and Hash provide their own implementations.
Symbol.instance_method(:hash).owner # Output: => Kernel
Integer.instance_method(:hash).owner # Output: => Kernel
String.instance_method(:hash).owner # Output: => String
Hash.instance_method(:hash).owner # Output: => Hash
In Ruby, when we store something in a hash (collection), the object provided as a key (e.g., string or symbol) is converted into and stored as a hashcode. Later, when retrieving an element from the hash (collection), we provide an object as a key, which is converted into a hashcode and compared to the existing keys. If there is a match, the value of the corresponding item is returned. The comparison is made using the eql? method under the hood.
"zen".eql? "zen" # Output: => true
# is the same as
"zen".hash == "zen".hash # Output: => true
In most cases, the eql? method behaves similarly to the == method. However, there are a few exceptions. For instance, eql? does not perform implicit type conversion when comparing an integer to a float.
2 == 2.0 # Output: => true
2.eql? 2.0 # Output: => false
2.hash == 2.0.hash # Output: => false
Many of Ruby's built-in classes, such as String, Range, and Regexp, provide their own implementations of the === operator, also known as case-equality, triple equals or threequals. Because it's implemented differently in each class, it will behave differently depending on the type of object it was called on. Generally, it returns true if the object on the right "belongs to" or "is a member of" the object on the left. For instance, it can be used to test if an object is an instance of a class (or one of its subclasses).
String === "zen" # Output: => true
Range === (1..2) # Output: => true
Array === [1,2,3] # Output: => true
Integer === 2 # Output: => true
The same result can be achieved with other methods which are probably best suited for the job. It's usually better to write code that is easy to read by being as explicit as possible, without sacrificing efficiency and conciseness.
2.is_a? Integer # Output: => true
2.kind_of? Integer # Output: => true
2.instance_of? Integer # Output: => false
Notice the last example returned false because integers such as 2 are instances of the Fixnum class, which is a subclass of the Integer class. The ===, is_a? and instance_of? methods return true if the object is an instance of the given class or any subclasses. The instance_of method is stricter and only returns true if the object is an instance of that exact class, not a subclass.
The is_a? and kind_of? methods are implemented in the Kernel module, which is mixed in by the Object class. Both are aliases to the same method. Let's verify:
Kernel.instance_method(:kind_of?) == Kernel.instance_method(:is_a?) # Output: => true
When the === operator is called on a range object, it returns true if the value on the right falls within the range on the left.
(1..4) === 3 # Output: => true
(1..4) === 2.345 # Output: => true
(1..4) === 6 # Output: => false
("a".."d") === "c" # Output: => true
("a".."d") === "e" # Output: => false
Remember that the === operator invokes the === method of the left-hand object. So (1..4) === 3 is equivalent to (1..4).=== 3. In other words, the class of the left-hand operand will define which implementation of the === method will be called, so the operand positions are not interchangeable.
Returns true if the string on the right matches the regular expression on the left. /zen/ === "practice zazen today" # Output: => true # is the same as "practice zazen today"=~ /zen/
This operator is also used under the hood on case/when statements. That is its most common use.
minutes = 15
case minutes
when 10..20
puts "match"
else
puts "no match"
end
# Output: match
In the example above, if Ruby had implicitly used the double equal operator (==), the range 10..20 would not be considered equal to an integer such as 15. They match because the triple equal operator (===) is implicitly used in all case/when statements. The code in the example above is equivalent to:
if (10..20) === minutes
puts "match"
else
puts "no match"
end
The =~ (equal-tilde) and !~ (bang-tilde) operators are used to match strings and symbols against regex patterns.
The implementation of the =~ method in the String and Symbol classes expects a regular expression (an instance of the Regexp class) as an argument.
"practice zazen" =~ /zen/ # Output: => 11
"practice zazen" =~ /discursive thought/ # Output: => nil
:zazen =~ /zen/ # Output: => 2
:zazen =~ /discursive thought/ # Output: => nil
The implementation in the Regexp class expects a string or a symbol as an argument.
/zen/ =~ "practice zazen" # Output: => 11
/zen/ =~ "discursive thought" # Output: => nil
In all implementations, when the string or symbol matches the Regexp pattern, it returns an integer which is the position (index) of the match. If there is no match, it returns nil. Remember that, in Ruby, any integer value is "truthy" and nil is "falsy", so the =~ operator can be used in if statements and ternary operators.
puts "yes" if "zazen" =~ /zen/ # Output: => yes
"zazen" =~ /zen/?"yes":"no" # Output: => yes
Pattern-matching operators are also useful for writing shorter if statements. Example:
if meditation_type == "zazen" || meditation_type == "shikantaza" || meditation_type == "kinhin"
true
end
Can be rewritten as:
if meditation_type =~ /^(zazen|shikantaza|kinhin)$/
true
end
The !~ operator is the opposite of =~, it returns true when there is no match and false if there is a match.
More info is available at this blog post.
For person who are afraid on re-creating AppStore distribution certificate Apple documentation says:
Important: Re-creating your development or distribution certificates doesn’t affect apps that you’ve submitted to the App Store nor does it affect your ability to update them.
But it affects apps for Apple Developer Enterprise ecosystem.
I don't know if this will help, but here's the SWT FAQ question How do I use Mozilla as the Browser's underlying renderer?
Edit: Having researched this further, it sounds like this isn't possible in Eclipse 3.4, but may be slated for a later release.
This will ensure you get a two-digit day and month.
function formattedDate(d = new Date) {
let month = String(d.getMonth() + 1);
let day = String(d.getDate());
const year = String(d.getFullYear());
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return `${day}/${month}/${year}`;
}
Or terser:
function formattedDate(d = new Date) {
return [d.getDate(), d.getMonth()+1, d.getFullYear()]
.map(n => n < 10 ? `0${n}` : `${n}`).join('/');
}
One more point in addition to the above answers. When using a font inside a fragment, the typeface instantiation should be done in the onAttach method ( override ) as given below:
@Override
public void onAttach(Activity activity){
super.onAttach(activity);
Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
}
Reason:
There is a short span of time before a fragment is attached to an activity. If CreateFromAsset method is called before attaching fragment to an activity an error occurs.
try getHibernateTemplate().saveOrUpdate()
its solved. Use nuget and search for the "ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client".
and install the package. it will resolve the issue for me.
Close... try:
select
Sum(case when rsp_ind = 0 then 1 Else 0 End) as 'New',
Sum(case when rsp_ind = 1 then 1 else 0 end) as 'Accepted'
from tb_a
My idea is that you assume that first and second members of the array are your first max and second max. Then you take each new member of an array and compare it with the 2nd max. Don't forget to compare 2nd max with the 1st one. If it's bigger, just swap them.
public static int getMax22(int[] arr){
int max1 = arr[0];
int max2 = arr[1];
for (int i = 2; i < arr.length; i++){
if (arr[i] > max2)
{
max2 = arr[i];
}
if (max2 > max1)
{
int temp = max1;
max1 = max2;
max2 = temp;
}
}
return max2;
}
Simplest answer if your browser supports the trim()
function
if (myString && !myString.trim()) {
//First condition to check if string is not empty
//Second condition checks if string contains just whitespace
}
I had same problem
I resolved it by installing 64 bit JVM from
The reason that you get the 404 File Not Found
error, is that your path to CSS given as a value to the href
attribute is missing context path.
An HTTP request URL contains the following parts:
http://[host]:[port][request-path]?[query-string]
The request path is further composed of the following elements:
Context path: A concatenation of a forward slash (/) with the context
root of the servlet's web application. Example: http://host[:port]/context-root[/url-pattern]
Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).
Path info: The part of the request path that is not part of the context path or the servlet path.
Read more here.
There are several solutions to your problem, here are some of them:
<c:url>
tag from JSTLIn my Java web applications I usually used <c:url>
tag from JSTL when defining the path to CSS/JavaScript/image and other static resources. By doing so you can be sure that those resources are referenced always relative to the application context (context path).
If you say, that your CSS is located inside WebContent folder, then this should work:
<link type="text/css" rel="stylesheet" href="<c:url value="/globalCSS.css" />" />
The reason why it works is explained in the "JavaServer Pages™ Standard Tag Library" version 1.2 specification chapter 7.5 (emphasis mine):
7.5 <c:url>
Builds a URL with the proper rewriting rules applied.
...
The URL must be either an absolute URL starting with a scheme (e.g. "http:// server/context/page.jsp") or a relative URL as defined by JSP 1.2 in JSP.2.2.1 "Relative URL Specification". As a consequence, an implementation must prepend the context path to a URL that starts with a slash (e.g. "/page2.jsp") so that such URLs can be properly interpreted by a client browser.
NOTE
Don't forget to use Taglib directive in your JSP to be able to reference JSTL tags. Also see an example JSP page here.
An alternative solution is using Expression Language (EL) to add application context:
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/globalCSS.css" />
Here we have retrieved the context path from the request object. And to access the request object we have used the pageContext implicit object.
<c:set>
tag from JSTLDISCLAIMER
The idea of this solution was taken from here.
To make accessing the context path more compact than in the solution ?2, you can first use the JSTL <c:set>
tag, that sets the value of an EL variable or the property of an EL variable in any of the JSP scopes (page, request, session, or application) for later access.
<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<link type="text/css" rel="stylesheet" href="${root}/globalCSS.css" />
IMPORTANT NOTE
By default, in order to set the variable in such manner, the JSP that contains this set tag must be accessed at least once (including in case of setting the value in the application scope using scope attribute, like <c:set var="foo" value="bar" scope="application" />
), before using this new variable. For instance, you can have several JSP files where you need this variable. So you must ether a) both set the new variable holding context path in the application scope AND access this JSP first, before using this variable in other JSP files, or b) set this context path holding variable in EVERY JSP file, where you need to access to it.
The more effective way to make accessing the context path more compact is to set a variable that will hold the context path and store it in the application scope using a Listener. This solution is similar to solution ?3, but the benefit is that now the variable holding context path is set right at the start of the web application and is available application wide, no need for additional steps.
We need a class that implements ServletContextListener interface. Here is an example of such class:
package com.example.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class AppContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext sc = event.getServletContext();
sc.setAttribute("ctx", sc.getContextPath());
}
@Override
public void contextDestroyed(ServletContextEvent event) {}
}
Now in a JSP we can access this global variable using EL:
<link type="text/css" rel="stylesheet" href="${ctx}/globalCSS.css" />
NOTE
@WebListener annotation is available since Servlet version 3.0. If you use a servlet container or application server that supports older Servlet specifications, remove the @WebServlet annotation and instead configure the listener in the deployment descriptor (web.xml). Here is an example of web.xml file for the container that supports maximum Servlet version 2.5 (other configurations are omitted for the sake of brevity):
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
...
<listener>
<listener-class>com.example.listener.AppContextListener</listener-class>
</listener>
...
</webapp>
As suggested by user @gavenkoa you can also use scriptlets like this:
<%= request.getContextPath() %>
For such a small thing it is probably OK, just note that generally the use of scriptlets in JSP is discouraged.
I personally prefer either the first solution (used it in my previous projects most of the time) or the second, as they are most clear, intuitive and unambiguous (IMHO). But you choose whatever suits you most.
You can deploy your web app as the default application (i.e. in the default root context), so it can be accessed without specifying context path. For more info read the "Update" section here.
very simple solution for this is by using useRef
hook
const buttonRef = useRef();
const disableButton = () =>{
buttonRef.current.disabled = true; // this disables the button
}
<button
className="btn btn-primary mt-2"
ref={buttonRef}
onClick={disableButton}
>
Add
</button>
Similarly you can enable the button by using buttonRef.current.disabled = false
When you say pair[0]
, that gives you ("a", 1)
. The thing in parentheses is a tuple, which, like a list, is a type of collection. So you can access the first element of that thing by specifying [0]
or [1]
after its name. So all you have to do to get the first element of the first element of pair
is say pair[0][0]
. Or if you want the second element of the third element, it's pair[2][1]
.
Have you considered a lookup table using a Dictionary?
enum GroupTypes
{
TheGroup,
TheOtherGroup
}
Dictionary<string, GroupTypes> GroupTypeLookup = new Dictionary<string, GroupTypes>();
// initialize lookup table:
GroupTypeLookup.Add("OEM", TheGroup);
GroupTypeLookup.Add("CMB", TheOtherGroup);
You can then use GroupTypeLookup.TryGetValue() to look up a string when you read it.
You might have already received a response but this might help others since I experienced the same issue recently and this is what I did:
Then I opened cmd prompt with administrative privileges and copied this
@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin
into the cmd prompt.
Google used to recommend putting it just before the </body>
tag, because the original method they provided for loading ga.js
was blocking. The newer async syntax, though, can safely be put in the head with minimal blockage, so the current recommendation is just before the </head>
tag.
<head>
will add a little latency; in the footer will reduce the number of pageviews recorded at some small margin. It's a tradeoff. ga.js
is heavily cached and present on a large percentage of sites across the web, so its often served from the cache, reducing latency to almost nil.
As a matter of personal preference, I like to include it in the <head>
, but its really a matter of preference.
while dropping unique key we use index
ALTER TABLE tbl
DROP INDEX unique_address;
There is a trick you can do for Outlook 2007 using conditional html comments.
The code below will make sure that Outlook table is 800px wide, its not max-width but it works better than letting the table span across the entire window.
<!--[if gte mso 9]>
<style>
#tableForOutlook {
width:800px;
}
</style>
<![endif]-->
<table style="width:98%;max-width:800px">
<!--[if gte mso 9]>
<table id="tableForOutlook"><tr><td>
<![endif]-->
<tr><td>
[Your Content Goes Here]
</td></tr>
<!--[if gte mso 9]>
</td></tr></table>
<![endif]-->
<table>
I'm surprised no one mentioned the HTML entities  
and  
which produce horizontal white space equivalent to the characters n and m, respectively. If you want to accumulate horizontal white space quickly, those are more efficient than
.
 
 
Along with <space>
and  
, these are the five entities HTML provides for horizontal white space.
Note that except for
, all entities allow breaking. Whatever text surrounds them will wrap to a new line if it would otherwise extend beyond the container boundary. With
it would wrap to a new line as a block even if the text before
could fit on the previous line.
Depending on your use case, that may be desired or undesired. For me, unless I'm dealing with things like names (John
Doe), addresses or references (see eq.
5), breaking as a block is usually undesired.
Both C# and Java don't have plain functions only member functions (aka methods). And the methods are not first-class citizens. First-class functions allow us to create beautiful and powerful code, as seen in F# or Clojure languages. (For instance, first-class functions can be passed as parameters and can return functions.) Java and C# ameliorate this somewhat with interfaces/delegates.
Func<int, int, int> randInt = (n1, n2) => new Random().Next(n1, n2);
So, Func
is a built-in delegate which brings some functional programming features and helps reduce code verbosity.
final MessageDigest digest = MessageDigest.getInstance("SHA-1");
result = digest.digest(stringToHash.getBytes("UTF-8"));
// Another way to construct HEX, my previous post was only the method like your solution
StringBuilder sb = new StringBuilder();
for (byte b : result) // This is your byte[] result..
{
sb.append(String.format("%02X", b));
}
String messageDigest = sb.toString();
I find this image very meaningful :
(from : Oliver Steele -My Git Workflow (2008) )
I just wrote this one-liner to select the first empty cell found in a column based on a selected cell. Only works on first column of selected cells. Modify as necessary
Selection.End(xlDown).Range("A2").Select
My answer:
file_path = 'myfile.dat'
try:
fp = open(file_path)
except IOError:
# If not exists, create the file
fp = open(file_path, 'w+')
I actually like MY JavaScript files to be validated, but I definitely don't want to validate and deal with trivial warnings with third party libraries.
That's why I think that turning off validation all together is too drastic. Fortunately with Eclipse, you can selectively remove some JavaScript sources from validation.
Excluded
pattern.Exclusion patterns
box.Browse
button to mention the JavaScript source by name.The information about JavaScript source inclusion/exclusion is saved into .settings/.jsdtscope
file. Do not forget to add it to your SCM.
Here is how configuration looks with jQuery files removed from validation:
If you want to check the display value, https://stackoverflow.com/a/1189281/5622596 already posted the answer.
However if instead of checking whether an element has a style of style="display:none"
you want to know if that element is visible. Then use .is(":visible")
For example:
$('#idDetails').is(":visible");
This will be true
if it is visible & false
if it is not.
Use a JOIN
in the DELETE
statement.
DELETE p, pa
FROM pets p
JOIN pets_activities pa ON pa.id = p.pet_id
WHERE p.order > :order
AND p.pet_id = :pet_id
Alternatively you can use...
DELETE pa
FROM pets_activities pa
JOIN pets p ON pa.id = p.pet_id
WHERE p.order > :order
AND p.pet_id = :pet_id
...to delete only from pets_activities
See this.
For single table deletes, yet with referential integrity, there are other ways of doing with EXISTS
, NOT EXISTS
, IN
, NOT IN
and etc. But the one above where you specify from which tables to delete with an alias before the FROM
clause can get you out of a few pretty tight spots more easily. I tend to reach out to an EXISTS
in 99% of the cases and then there is the 1% where this MySQL syntax takes the day.
Or take the .not() method
$(".thisClass").not("#thisId").doAction();
I have a solution which is not specified here
z = {}
z.update(x) or z.update(y)
This will not update x as well as y. Performance? I don't think it will be terribly slow.
when try to make foreign key when using laravel migration
like this example:
user table
public function up()
{
Schema::create('flights', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->TinyInteger('color_id')->unsigned();
$table->foreign('color_id')->references('id')->on('colors');
$table->timestamps();
});
}
colors table
public function up()
{
Schema::create('flights', function (Blueprint $table) {
$table->increments('id');
$table->string('color');
$table->timestamps();
});
}
sometimes properties didn't work
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
this error happened because the foreign key (type) in [user table] is deferent from primary key (type) in [colors table]
To solve this problem should change the primary key in [colors table]
$table->tinyIncrements('id');
When you use primary key $table->Increments('id');
you should use Integer
as a foreign key
$table-> unsignedInteger('fk_id');
$table->foreign('fk_id')->references('id')->on('table_name');
When you use primary key $table->tinyIncrements('id');
you should use unsignedTinyInteger
as a foreign key
$table-> unsignedTinyInteger('fk_id');
$table->foreign('fk_id')->references('id')->on('table_name');
When you use primary key $table->smallIncrements('id');
you should use unsignedSmallInteger
as a foreign key
$table-> unsignedSmallInteger('fk_id');
$table->foreign('fk_id')->references('id')->on('table_name');
When you use primary key $table->mediumIncrements('id');
you should use unsignedMediumInteger
as a foreign key
$table-> unsignedMediumInteger('fk_id');
$table->foreign('fk_id')->references('id')->on('table_name');
If you want to make them a lot bigger, like for multiple lines of input, you may want to use a textarea tag instead of the input tag. This allows you to put in number of rows and columns you want on your textarea without messing with css (e.g. <textarea rows="2" cols="25"></textarea>
).
Text areas are resizable by default. If you want to disable that, just use the resize css rule:
#signin textarea {
resize: none;
}
A simple solution to your question about default text that disappears when the user clicks is to use the placeholder attribute. This will work for <input>
tags as well.
<textarea rows="2" cols="25" placeholder="This is the default text"></textarea>
This text will disappear when the user enters information rather than when they click, but that is common functionality for this kind of thing.
document.body.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
console.log('clicked ;)');
}
});
DEMO
Write a function
CREATE FUNCTION dbo.SAP_TO_DATETIME(@input VARCHAR(14))
RETURNS datetime
AS BEGIN
DECLARE @ret datetime
DECLARE @dtStr varchar(19)
SET @dtStr = substring(@input,1,4) + '-' + substring(@input,5,2) + '-' + substring(@input,7,2)
+ ' ' + substring(@input,9,2) + ':' + substring(@input,11,2) + ':' + substring(@input,13,2);
SET @ret = COALESCE(convert(DATETIME, @dtStr, 20),null);
RETURN @ret
END
with this script in file.sh
#!/bin/bash
echo Your container args are: "$@"
and this Dockerfile
FROM ubuntu:14.04
COPY ./file.sh /
ENTRYPOINT ["/file.sh"]
you should be able to:
% docker build -t test .
% docker run test hello world
Your container args are: hello world
It means that the delegate will run on the UI thread, even if you call that method from a background worker or thread-pool thread. UI elements have thread affinity - they only like talking directly to one thread: the UI thread. The UI thread is defined as the thread that created the control instance, and is therefore associated with the window handle. But all of that is an implementation detail.
The key point is: you would call this method from a worker thread so that you can access the UI (to change the value in a label, etc) - since you are not allowed to do that from any other thread than the UI thread.
You can use Integer.parseInt()
or Integer.valueOf()
to get the integer from the string, and catch the exception if it is not a parsable int. You want to be sure to catch the NumberFormatException
it can throw.
It may be helpful to note that valueOf() will return an Integer object, not the primitive int.
When adding datepicker at runtime generated input textboxes you have to check if it already contains datepicker then first remove class hasDatepicker then apply datePicker to it.
function convertTxtToDate() {
$('.dateTxt').each(function () {
if ($(this).hasClass('hasDatepicker')) {
$(this).removeClass('hasDatepicker');
}
$(this).datepicker();
});
}
In swift:
if self.mainScroll.contentSize.height > self.mainScroll.bounds.size.height {
let bottomOffset = CGPointMake(0, self.mainScroll.contentSize.height - self.mainScroll.bounds.size.height);
self.mainScroll.setContentOffset(bottomOffset, animated: true)
}
- It is a very easy to use method in C++11.
- We can use std::chrono::high_resolution_clock from header
- We can write a method to print the method execution time in a much readable form.
For example, to find the all the prime numbers between 1 and 100 million, it takes approximately 1 minute and 40 seconds. So the execution time get printed as:
Execution Time: 1 Minutes, 40 Seconds, 715 MicroSeconds, 715000 NanoSeconds
The code is here:
#include <iostream>
#include <chrono>
using namespace std;
using namespace std::chrono;
typedef high_resolution_clock Clock;
typedef Clock::time_point ClockTime;
void findPrime(long n, string file);
void printExecutionTime(ClockTime start_time, ClockTime end_time);
int main()
{
long n = long(1E+8); // N = 100 million
ClockTime start_time = Clock::now();
// Write all the prime numbers from 1 to N to the file "prime.txt"
findPrime(n, "C:\\prime.txt");
ClockTime end_time = Clock::now();
printExecutionTime(start_time, end_time);
}
void printExecutionTime(ClockTime start_time, ClockTime end_time)
{
auto execution_time_ns = duration_cast<nanoseconds>(end_time - start_time).count();
auto execution_time_ms = duration_cast<microseconds>(end_time - start_time).count();
auto execution_time_sec = duration_cast<seconds>(end_time - start_time).count();
auto execution_time_min = duration_cast<minutes>(end_time - start_time).count();
auto execution_time_hour = duration_cast<hours>(end_time - start_time).count();
cout << "\nExecution Time: ";
if(execution_time_hour > 0)
cout << "" << execution_time_hour << " Hours, ";
if(execution_time_min > 0)
cout << "" << execution_time_min % 60 << " Minutes, ";
if(execution_time_sec > 0)
cout << "" << execution_time_sec % 60 << " Seconds, ";
if(execution_time_ms > 0)
cout << "" << execution_time_ms % long(1E+3) << " MicroSeconds, ";
if(execution_time_ns > 0)
cout << "" << execution_time_ns % long(1E+6) << " NanoSeconds, ";
}
Parsing can be considered as a synonym of "Breaking down into small pieces" and then analysing what is there or using it in a modified way. In Java, Strings are parsed into Decimal, Octal, Binary, Hexadecimal, etc. It is done if your application is taking input from the user in the form of string but somewhere in your application you want to use that input in the form of an integer or of double type. It is not same as type casting. For type casting the types used should be compatible in order to caste but nothing such in parsing.
I apologize for resurecting this old thread, but I just wanted to let everyone know there is a very close Bootstrap like CSS framework specifically created for email styling, here is the link: http://zurb.com/ink/
Hope it helps someone.
Ninja edit: It has since been renamed to Foundation for Emails
and the new link is: https://foundation.zurb.com/emails.html
Silent but deadly edit: New link https://get.foundation/emails.html
readChar doesn't have much flexibility so I combined your solutions (readLines and paste).
I have also added a space between each line:
con <- file("/Users/YourtextFile.txt", "r", blocking = FALSE)
singleString <- readLines(con) # empty
singleString <- paste(singleString, sep = " ", collapse = " ")
close(con)
There is an updated version of the very nice and slim Open Terminal Here posted by vgm64 and d0k. The change was made by james david low. He published the new version on his site. Just download OpenTerminalHere.zip, extract it, move the bundle to your Library/Scripts folder and drag it from there to your Finder toolbar.
What is special about it is that it always opens a new tab if a Terminal.app window is already open. Very useful! I also noted that the style of the button of the application better fits the Snow Leopard Finder.app style than cdto posted by redacted did.
TextView tekst = (TextView) findViewById(R.id.editText1);
You cannot cast EditText
to TextView
.
A working jQuery validate example:
$(function () {
$('input[type=file]').on('change', function() {
var $el = $(this);
var files = this.files;
var image = new Image();
image.onload = function() {
$el
.attr('data-upload-width', this.naturalWidth)
.attr('data-upload-height', this.naturalHeight);
}
image.src = URL.createObjectURL(files[0]);
});
jQuery.validator.unobtrusive.adapters.add('imageminwidth', ['imageminwidth'], function (options) {
var params = {
imageminwidth: options.params.imageminwidth.split(',')
};
options.rules['imageminwidth'] = params;
if (options.message) {
options.messages['imageminwidth'] = options.message;
}
});
jQuery.validator.addMethod("imageminwidth", function (value, element, param) {
var $el = $(element);
if(!element.files && element.files[0]) return true;
return parseInt($el.attr('data-upload-width')) >= parseInt(param["imageminwidth"][0]);
});
} (jQuery));
There seems to be multiple reasons for this failure. For me, the issue was that in AndroidManifest file I had referenced a non-existing library(only in this particular device) using the 'uses-library' tag. After removing the library which this device did not have the apk got installed properly.
\b is used as word boundary
word = "categorical cat"
Find all "cat" in the above word
without \b
re.findall(r'cat',word)
['cat', 'cat']
with \b
re.findall(r'\bcat\b',word)
['cat']
If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.
This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
<div class="row">_x000D_
<div class="col-sm-3">Under me should be a DIV</div>_x000D_
<div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
<div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
</div>_x000D_
</div>
_x000D_
The format you've used is not recognized by strtotime(). Replace
$date = "04-15-2013";
by
$date = "04/15/2013";
Or if you want to use -
then use the following line with the year in front:
$date = "2013-04-15";
For reference, I am attaching my location
block for catching files with the .php
extension:
location ~ \.php$ {
include /path/to/fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}
Double-check the /path/to/fastcgi-params
, and make sure that it is present and readable by the nginx user.
It is a very common issue and the solution is very easy... Just update the SDK in SDK manager(see full instructions below)
Thanks for asking that question :)
I had a similar problem: In my test-cases executions I always got this error. I found out, that my "Distributed Transaction Service" was not started (run: services.msc -> start "Distributed Transaction Service" (best to set it to start automatic)). After I did that, it worked like a charm...
If your data is from json, you can do that
import json
json.loads('true')
True
The kernel is part of the operating system and closer to the hardware it provides low level services like:
An operating system also includes applications like the user interface (shell, gui, tools, and services).
Create a new empty class and past this inside it:
using System.Windows.Forms;
namespace ExtensionMethods
{
public static class TabPageExtensions
{
public static bool IsVisible(this TabPage tabPage)
{
if (tabPage.Parent == null)
return false;
else if (tabPage.Parent.Contains(tabPage))
return true;
else
return false;
}
public static void HidePage(this TabPage tabPage)
{
TabControl parent = (TabControl)tabPage.Parent;
parent.TabPages.Remove(tabPage);
}
public static void ShowPageInTabControl(this TabPage tabPage,TabControl parent)
{
parent.TabPages.Add(tabPage);
}
}
}
2- Add reference to ExtensionMethods namespace in your form code:
using ExtensionMethods;
3- Now you can use yourTabPage.IsVisible();
to check its visibility, yourTabPage.HidePage();
to hide it, and yourTabPage.ShowPageInTabControl(parentTabControl);
to show it.
First, if you are unfamiliar with the command line, try using phpmyadmin from your webbrowser. This will make sure you actually have a mysql database created and a username.
This is how you connect from the command line (bash):
mysql -h hostname -u username -p database_name
For example:
fabio@crunchbang ~ $ mysql -h 127.0.0.1 -u fabio -p fabiodb
Take out the method name from in your import statement. e.g.
import Dan.Vik.disp;
becomes:
import Dan.Vik;
You should use ExecuteScalar()
(which returns the first row first column) instead of ExecuteNonQuery()
(which returns the no. of rows affected).
You should refer differences between executescalar and executenonquery for more details.
Hope it helps!
LANGUAGE INDEPENDENCY:
The Andrei Coscodan solution is language dependent, so a way to try to fix it is to reserve all the tags for each field: year, month and day on target languages. Consider Portugese and English, after the parsing do a final set as:
set Year=%yy%%aa%
set Month=%mm%
set Day=%dd%
Look for the year setting, I used both tags from English and Portuguese, it worked for me in Brazil where we have these two languages as the most common in Windows instalations. I expect this will work also for some languages with Latin origin like as French, Spanish, and so on.
Well, the full script could be:
@echo off
setlocal enabledelayedexpansion
:: Extract date fields - language dependent
for /f "tokens=1-4 delims=/-. " %%i in ('date /t') do (
set v1=%%i& set v2=%%j& set v3=%%k
if "%%i:~0,1%%" gtr "9" (set v1=%%j& set v2=%%k& set v3=%%l)
for /f "skip=1 tokens=2-4 delims=(-)" %%m in ('echo.^|date') do (
set %%m=!v1!& set %%n=!v2!& set %%o=!v3!
)
)
:: Final set for language independency (English and Portuguese - maybe works for Spanish and French)
set year=%yy%%aa%
set month=%mm%
set day=%dd%
:: Testing
echo Year:[%year%] - month:[%month%] - day:[%day%]
endlocal
pause
I hope this helps someone that deal with diferent languages.
$("#" + $(this).attr("name")).hide();
$('#timePicker').datetimepicker({
// dateFormat: 'dd-mm-yy',
format:'DD/MM/YYYY HH:mm:ss',
minDate: getFormattedDate(new Date())
});
function getFormattedDate(date) {
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear().toString().slice(2);
return day + '-' + month + '-' + year;
}
You need to pass datepicker() the date formatted correctly.
You're comparing apples to oranges here:
webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service
basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.
So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).
Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:
basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security
wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network
For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding
It sounds to me that you really want to limit the rows being returned in your query and page through the results. If so, you can do something like:
select * from (select rownum myrow, a.* from TEST1 a )
where myrow between 5 and 10 ;
You just have to determine your boundaries.
there are some syntax errors to your program heres a working code;
#include<stdio.h>
int main()
{
int a,b;
printf("enter any two number\n");
scanf("%d%d",&a,&b);
if (a%b==0){
printf("this is multiple number");
}
else if (b%a==0){
printf("this is multiple number");
}
else{
printf("this is not multiple number");
return 0;
}
}
In simple, Normalisation is Reduction of Redundancies.
Examples of Redundancies:
a) white spaces outside of the root/document tags(...<document></document>...)
b) white spaces within start tag (<...>) and end tag (</...>)
c) white spaces between attributes and their values (ie. spaces between key name and =")
d) superfluous namespace declarations
e) line breaks/white spaces in texts of attributes and tags
f) comments etc...
Since the introduction of Visual Studio 2015, this location has changed and is added into your solution root under the following location:
C:\<Path\To\Solution>\.vs\config\applicationhost.config
I hope this saves you some time!
SELECT SUBSTRING('[email protected]',1,(CHARINDEX('@','[email protected]')-1)) Before, RIGHT('[email protected]',(CHARINDEX('@','[email protected]')+1)) After
"Using HTML5/Canvas/JavaScript to take screenshots" answers your problem.
You can use JavaScript/Canvas to do the job but it is still experimental.
Using the -X
flag with whatever HTTP verb you want:
curl -X PUT -d arg=val -d arg2=val2 localhost:8080
This example also uses the -d
flag to provide arguments with your PUT request.
Use update instead of stop
http://api.jqueryui.com/sortable/
update( event, ui )
Type: sortupdate
This event is triggered when the user stopped sorting and the DOM position has changed.
.
stop( event, ui )
Type: sortstop
This event is triggered when sorting has stopped. event Type: Event
Piece of code:
<script type="text/javascript">
var sortable = new Object();
sortable.s1 = new Array(1, 2, 3, 4, 5);
sortable.s2 = new Array(1, 2, 3, 4, 5);
sortable.s3 = new Array(1, 2, 3, 4, 5);
sortable.s4 = new Array(1, 2, 3, 4, 5);
sortable.s5 = new Array(1, 2, 3, 4, 5);
sortingExample();
function sortingExample()
{
// Init vars
var tDiv = $('<div></div>');
var tSel = '';
// ul
for (var tName in sortable)
{
// Creating ul list
tDiv.append(createUl(sortable[tName], tName));
// Add selector id
tSel += '#' + tName + ',';
}
$('body').append('<div id="divArrayInfo"></div>');
$('body').append(tDiv);
// ul sortable params
$(tSel).sortable({connectWith:tSel,
start: function(event, ui)
{
ui.item.startPos = ui.item.index();
},
update: function(event, ui)
{
var a = ui.item.startPos;
var b = ui.item.index();
var id = this.id;
// If element moved to another Ul then 'update' will be called twice
// 1st from sender list
// 2nd from receiver list
// Skip call from sender. Just check is element removed or not
if($('#' + id + ' li').length < sortable[id].length)
{
return;
}
if(ui.sender === null)
{
sortArray(a, b, this.id, this.id);
}
else
{
sortArray(a, b, $(ui.sender).attr('id'), this.id);
}
printArrayInfo();
}
}).disableSelection();;
// Add styles
$('<style>')
.attr('type', 'text/css')
.html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
.appendTo('head');
printArrayInfo();
}
function printArrayInfo()
{
var tStr = '';
for ( tName in sortable)
{
tStr += tName + ': ';
for(var i=0; i < sortable[tName].length; i++)
{
// console.log(sortable[tName][i]);
tStr += sortable[tName][i] + ', ';
}
tStr += '<br>';
}
$('#divArrayInfo').html(tStr);
}
function createUl(tArray, tId)
{
var tUl = $('<ul>', {id:tId, class:'sortableClass'})
for(var i=0; i < tArray.length; i++)
{
// Create Li element
var tLi = $('<li>' + tArray[i] + '</li>');
tUl.append(tLi);
}
return tUl;
}
function sortArray(a, b, idA, idB)
{
var c;
c = sortable[idA].splice(a, 1);
sortable[idB].splice(b, 0, c);
}
</script>
It's been a while, but last time I had something similar:
ROLLBACK TRAN
or trying to
COMMIT
what had allready been done free'd everything up so I was able to clear things out and start again.
PUT
$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
POST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
GET See @Dan H answer
DELETE
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
UPDATE: There are better options than my original answer. This works outside of MVC quite well but it's better to stick with the built-in methods of returning image content. See up-voted answers.
You certainly can. Try out these steps:
Here's some sample code:
string pathToFile = @"C:\Documents and Settings\some_path.jpg";
byte[] imageData = File.ReadAllBytes(pathToFile);
Response.ContentType = "image/jpg";
Response.BinaryWrite(imageData);
Hope that helps!
this is the path to the web root directory c:\wamp\www
you can create different projects by adding different folders to this directory and call them like:
localhost/project1 from browser
this will run the index.html or index.php, lying inside project1
@RequestBody annotation binds the HTTPRequest body to the domain object. Spring automatically deserializes incoming HTTP Request to object using HttpMessageConverters. HttpMessageConverter converts body of request to resolve the method argument depending on the content type of the request. Many examples how to use converters https://upcodein.com/search/jc/mg/ResponseBody/page/0
You can use fiddler as webdebugger http://www.telerik.com/fiddler/web-debugging
Fiddler is a debugging tool from telerik software, which helps you to intercept every request that is initiated from your machine.
You might want to check HTML frames, which can do pretty much exactly what you are looking for. They are considered outdated however.
The canonical way to do this with Rails 3:
Foo.includes(:bar).where("bars.id IS NOT NULL")
ActiveRecord 4.0 and above adds where.not
so you can do this:
Foo.includes(:bar).where.not('bars.id' => nil)
Foo.includes(:bar).where.not(bars: { id: nil })
When working with scopes between tables, I prefer to leverage merge
so that I can use existing scopes more easily.
Foo.includes(:bar).merge(Bar.where.not(id: nil))
Also, since includes
does not always choose a join strategy, you should use references
here as well, otherwise you may end up with invalid SQL.
Foo.includes(:bar)
.references(:bar)
.merge(Bar.where.not(id: nil))
Go to Path C:\ProgramData\Oracle\Java\javapath (This path is in my case might be different in your case). Rename the folder ORACLE with other name line ORACLE_OLD. And Restart the STS/IDE . This works for me
Regarding coding style:
Most coding standards no matter language ban multiple return statements from a single function as bad practice.
(Although personally I would say there are several cases where multiple return statements do make sense: text/data protocol parsers, functions with extensive error handling etc)
The consensus from all those industry coding standards is that the expression should be written as:
int result;
if(A > B)
{
result = A+1;
}
else
{
result = A-1;
}
return result;
Regarding efficiency:
The above example and the two examples in the question are all completely equivalent in terms of efficiency. The machine code in all these cases have to compare A > B, then branch to either the A+1 or the A-1 calculation, then store the result of that in a CPU register or on the stack.
EDIT :
Sources:
You may approach this differently; omit the use of the :empty
pseudo-class and utilize input
events to detect a significant value in the <input>
field and style it accordingly:
var inputs = document.getElementsByTagName('input');_x000D_
_x000D_
for (var i = 0; i < inputs.length; i++) {_x000D_
var input = inputs[i];_x000D_
input.addEventListener('input', function() {_x000D_
var bg = this.value ? 'green' : 'red';_x000D_
this.style.backgroundColor = bg;_x000D_
});_x000D_
}
_x000D_
body {_x000D_
padding: 40px;_x000D_
}_x000D_
#inputList li {_x000D_
list-style-type: none;_x000D_
padding-bottom: 1.5em;_x000D_
}_x000D_
#inputList li input,_x000D_
#inputList li label {_x000D_
float: left;_x000D_
width: 10em;_x000D_
}_x000D_
#inputList li input {_x000D_
color: white;_x000D_
background-color: red;_x000D_
}_x000D_
#inputList li label {_x000D_
text-align: right;_x000D_
padding-right: 1em;_x000D_
}
_x000D_
<ul id="inputList">_x000D_
<li>_x000D_
<label for="username">Enter User Name:</label>_x000D_
<input type="text" id="username" />_x000D_
</li>_x000D_
<li>_x000D_
<label for="password">Enter Password:</label>_x000D_
<input type="password" id="password" />_x000D_
</li>_x000D_
</ul>
_x000D_
input
Events (DOM Mutation Events are now deprecated in DOM level 4, and have been replaced by DOM Mutation Observers).Disclaimer: note that input
events are currently experimental, and probably not widely supported.
The modern approach uses the java.time classes.
YearMonth.from(
ZonedDateTime.parse(
"Mon Mar 14 16:02:37 GMT 2011" ,
DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" )
)
).toString()
2011-03
The modern way is with java.time classes. The old date-time classes such as Calendar
have proven to be poorly-designed, confusing, and troublesome.
Define a custom formatter to match your string input.
String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );
Parse as a ZonedDateTime
.
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
You are interested in the year and month. The java.time classes include YearMonth
class for that purpose.
YearMonth ym = YearMonth.from( zdt );
You can interrogate for the year and month numbers if needed.
int year = ym.getYear();
int month = ym.getMonthValue();
But the toString
method generates a string in standard ISO 8601 format.
String output = ym.toString();
Put this all together.
String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
YearMonth ym = YearMonth.from( zdt );
int year = ym.getYear();
int month = ym.getMonthValue();
Dump to console.
System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ym: " + ym );
input: Mon Mar 14 16:02:37 GMT 2011
zdt: 2011-03-14T16:02:37Z[GMT]
ym: 2011-03
See this code running in IdeOne.com.
If you must have a Calendar
object, you can convert to a GregorianCalendar
using new methods added to the old classes.
GregorianCalendar gc = GregorianCalendar.from( zdt );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
The Best solution to change background checkbox color
input[type=checkbox] {_x000D_
margin-right: 5px;_x000D_
cursor: pointer;_x000D_
font-size: 14px;_x000D_
width: 15px;_x000D_
height: 12px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:after {_x000D_
position: absolute;_x000D_
width: 10px;_x000D_
height: 15px;_x000D_
top: 0;_x000D_
content: " ";_x000D_
background-color: #ff0000;_x000D_
color: #fff;_x000D_
display: inline-block;_x000D_
visibility: visible;_x000D_
padding: 0px 3px;_x000D_
border-radius: 3px;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:checked:after {_x000D_
content: "?";_x000D_
font-size: 12px;_x000D_
}
_x000D_
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>_x000D_
<input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>_x000D_
_x000D_
<input type="checkbox" name="vehicle" value="Car" checked> I have a bus<br>
_x000D_
Also adding insert option, as not mentioned yet.
std::string str("Hello World");
char ch;
str.push_back(ch); //ch is the character to be added
OR
str.append(sizeof(ch),ch);
OR
str.insert(str.length(),sizeof(ch),ch) //not mentioned above
\mbox
is the simplest answer. Regarding the update:
TeX prefers overlong lines to adding too much space between words on a line; I think the idea is that you will notice the lines that extend into the margin (and the black boxes it inserts after such lines), and will have a chance to revise the contents, whereas if there was too much space, you might not notice it.
Use \sloppy
or \begin{sloppypar}...\end{sloppypar}
to adjust this behavior, at least a little. Another possibility is \raggedright
(or \begin{raggedright}...\end{raggedright}
).
Try this code:
[self.navigationController presentViewController:controller animated:YES completion:nil];
No you can't do if in CSS, but you can choose which style sheet you will use
Here is an example :
<!--[if IE 6]>
Special instructions for IE 6 here
<![endif]-->
will use only for IE 6 here is the website where it is from http://www.quirksmode.org/css/condcom.html , only IE has conditional comments. Other browser do not, although there are some properties you can use for Firefox starting with -moz or for safari starting with -webkit. You can use javascript to detect which browser you're using and use javascript if for whatever actions you want to perform but that is a bad idea, since it can be disabled.
How about this?
WAITFOR DELAY '00:00:02';
If you have "00:02" it's interpreting that as Hours:Minutes.
A simple representation written by 'Robert Sedgwick' and 'Kevin Wayne' is available at http://algs4.cs.princeton.edu/41graph/Graph.java.html
Explanation copied from the above page.
The Graph class represents an undirected graph of vertices named 0 through V - 1.
It supports the following two primary operations: add an edge to the graph, iterate over all of the vertices adjacent to a vertex. It also provides methods for returning the number of vertices V and the number of edges E. Parallel edges and self-loops are permitted. By convention, a self-loop v-v appears in the adjacency list of v twice and contributes two to the degree of v.
This implementation uses an adjacency-lists representation, which is a vertex-indexed array of Bag objects. All operations take constant time (in the worst case) except iterating over the vertices adjacent to a given vertex, which takes time proportional to the number of such vertices.
To clarify one point in @EdChum's answer, per the documentation, you can include the object columns by using df.describe(include='all')
. It won't provide many statistics, but will provide a few pieces of info, including count, number of unique values, top value. This may be a new feature, I don't know as I am a relatively new user.
There is an important detail that has been omitted in the answer above.
MySQL imposes a limit of 65,535 bytes for the max size of each row.
The size of a VARCHAR
column is counted towards the maximum row size, while TEXT
columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR
field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.
Also note that the actual number of bytes required by a VARCHAR
field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4
(which you almost certainly should) it will use up even more of your maximum row size.
Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR
/TEXT
field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)
Reasons to use TEXT
:
Reasons to use VARCHAR
:
There is no automated uninstaller.
You have to remove Eclipse manually. At least Eclipse does not write anything in the system registry, so deleting some directories and files is enough.
Note: I use Unix style paths in this answer but the locations should be the same on Windows or Unix systems, so ~
refers to the user home directory even on Windows.
According to this discussion about uninstalling Eclipse, the reasoning for not providing an uninstaller is that the Eclipse installer is supposed to just automate a few tasks that in the past had to be done manually (like downloading and extracting Eclipse and adding shortcuts), so they also can be undone manually. There is no entry in "Programs and Features" because the installer does not register anything in the system registry.
Just delete the Eclipse directory and any desktop and start menu shortcuts and be done with it, if you don't mind a few leftover files.
In my opinion this is generally enough and I would stop here, because multiple Eclipse installations can share some files and you don't accidentally want to delete those shared files. You also keep all your projects.
If you really want to remove Eclipse without leaving any traces, you have to manually delete
~/eclipse/photon/
)The installer has a "Bundle Pools" menu entry which lists the locations of all bundle pools. If you have other Eclipse installations on your system you can use the "Cleanup Agent" to clean up unused bundles. If you don't have any other Eclipse installations you can delete the whole bundle pool directory instead (by default ~/p2/
).
If you want to completely remove the Eclipse installer too, delete the installer's executable and the ~/.eclipse/
directory.
Depending on what kind of work you did with Eclipse, there can be more directories that you may want to delete. If you used Maven, then ~/.m2/
contains the Maven cache and settings (shared with Maven CLI and other IDEs). If you develop Eclipse plugins, then there might be JUnit workspaces from test runs, next to you Eclipse workspace. Likewise other build tools and development environments used in Eclipse could have created similar directories.
If you want to delete your projects and workspace metadata, you have to delete your workspace(s). The default workspace location is ´~/workspace/´. You can also search for the .metadata
directory to get all Eclipse workspaces on your machine.
If you are working with Git projects, these are generally not saved in the workspace but in the ~/git/
directory.
If some other portion of your layout is influencing the div
width you can set width:auto
and the div
(which is a block element) will fill the space
<div style="width:auto">
<div style="margin-left:45px;width:auto">
<asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
</div>
</div>
If that's still not working we may need to see more of your layout HTML/CSS
If you need check ranges you are probably better off with if
and else if
statements, like so:
if (range > 0 && range < 5)
{
// ..
}
else if (range > 5 && range < 9)
{
// ..
}
else
{
// Fall through
}
A switch could get large on bigger ranges.
I strongly suspect the problem is simply that the current culture of the thread handling the request isn't set appropriately.
You can either set it for the whole request, or specify the culture while formatting. Either way, I would suggest not use string.Format
with a composite format unless you really have more than one thing to format (or a wider message). Instead, I'd use:
@price.ToString("C", culture)
It just makes it somewhat simpler.
EDIT: Given your comment, it sounds like you may well want to use a UK culture regardless of the culture of the user. So again, either set the UK culture as the thread culture for the whole request, or possibly introduce your own helper class with a "constant":
public static class Cultures
{
public static readonly CultureInfo UnitedKingdom =
CultureInfo.GetCultureInfo("en-GB");
}
Then:
@price.ToString("C", Cultures.UnitedKingdom)
In my experience, having a "named" set of cultures like this makes the code using it considerably simpler to read, and you don't need to get the string right in multiple places.
table-layout:fixed
will resolve the expanding cell problem, but will create a new one. IE by default will hide the overflow but Mozilla will render it outside the box.
Another solution would be to use: overflow:hidden;width:?px
<table style="table-layout:fixed; width:100px">
<tr>
<td style="overflow:hidden; width:50px;">fearofthedarkihaveaconstantfearofadark</td>
<td>
test
</td>
</tr>
</table>
You'll have to use JS to open the popup, though you can put it on the page conditionally with PHP, you're right that you'll have to use a JavaScript function.
You can do it by using Arrays.sort and Recursion. The same wine but in a different bottle....
import java.util.Arrays;
public class ArrayTest {
public static int mainCount=0;
public static void main(String[] args) {
String prevItem = "";
String[] array = {"name1","name1","name2","name2", "name2"};
Arrays.sort(array);
for(String item:array){
if(! prevItem.equals(item)){
mainCount = 0;
countArray(array, 0, item);
prevItem = item;
}
}
}
private static void countArray(String[] arr, int currentPos, String item) {
if(currentPos == arr.length){
System.out.println(item + " " + mainCount);
return;
}
else{
if(arr[currentPos].toString().equals(item)){
mainCount += 1;
}
countArray(arr, currentPos+1, item);
}
}
}
Try using the onbeforeunload property, which will let the user choose whether he wants to navigate away from the page.
Example: https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload
In HTML5 you can use sandbox property. Please see Pankrat's answer below. http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/
It is used to find the how many rows contain data in a worksheet that contains data in the column "A". The full usage is
lastRowIndex = ws.Cells(ws.Rows.Count, "A").End(xlUp).row
Where ws
is a Worksheet object. In the questions example it was implied that the statement was inside a With
block
With ws
lastRowIndex = .Cells(.Rows.Count, "A").End(xlUp).row
End With
ws.Rows.Count
returns the total count of rows in the worksheet (1048576 in Excel 2010)..Cells(.Rows.Count, "A")
returns the bottom most cell in column "A" in the worksheetThen there is the End
method. The documentation is ambiguous as to what it does.
Returns a Range object that represents the cell at the end of the region that contains the source range
Particularly it doesn't define what a "region" is. My understanding is a region is a contiguous range of non-empty cells. So the expected usage is to start from a cell in a region and find the last cell in that region in that direction from the original cell. However there are multiple exceptions for when you don't use it like that:
rng.cells(1,1)
. So Range.End
is not a trivial function.
.row
returns the row index of that cell.For your problem, the solution might be to attach CDN hosted by google with certain library:
https://developers.google.com/speed/libraries/devguide
Also, you can add this at the bottom of page (just before </body>
):
<script type="text/javascript">
(function() {
var script = document.createElement('script')
script.setAttribute("type", "text/javascript")
script.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js")
document.getElementsByTagName("head")[0].appendChild(script)
})();
</script>
However, this is risky in my opinion. You have an asynchronous call for jquery, thus your jquery has to wait until it loads (ie. $(document).ready
won't work in this case). So my answer would be: use a CDN like google suggests; put your javascript on the bottom just before </body>
; and, ignore flags from profilers.
I searched for a one line solution to read specific line from a file. Here my solution:
echo file('dayInt.txt')[1]
If your testing requires pulling quasi-real credit reports from the bureaus, the inactive SSNs of other answers won't work and you'll need designated test numbers.
I found this site Which appears to contain test social security numbers with associated test names and credit card numbers.
Transunion has a test environment you can link and send data to, including associated dummy credit reports. Sending a SSN to them with certain numbers in certain positions will automatically route the inquiry to their test environment Other credit bureaus will have similar systems in place.
Try add min-width: 100%
to style of your textarea:
<textarea class="form-control" style="min-width: 100%"></textarea>
My solution for a Date/Time parameter:
=CDate(Today())
The trick is to convert back to a DateTime as recommend Perhentian.
Chrome changed a lot since the times facebook could disable console...
As per March 2017 this doesn't work anymore.
Best you can do is disable some of the console functions, example:
if(!window.console) window.console = {};
var methods = ["log", "debug", "warn", "info", "dir", "dirxml", "trace", "profile"];
for(var i=0;i<methods.length;i++){
console[methods[i]] = function(){};
}
It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:
When location matches the last part of the directive’s value: it is better to use the root directive instead:
which would yield:
server {
listen 8080;
server_name www.mysite.com mysite.com;
error_log /home/www-data/logs/nginx_www.error.log;
error_page 404 /404.html;
location /public/doc/ {
autoindex on;
root /home/www-data/mysite;
}
location = /404.html {
root /home/www-data/mysite/static/html;
}
}
You might want to look into open2 and open3 in case you need bidirectional communication.
Actually pprint seems to sort the keys for you under python2.5
>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3}
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
'b': 9,
'c': 8,
'd': 7,
'e': 6,
'f': 5,
'g': 4,
'h': 3,
'i': 2,
'j': 1,
'k': 0}
But not always under python 2.4
>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
'b': 9,
'c': 8,
'd': 7,
'e': 6,
'f': 5,
'g': 4,
'h': 3,
'i': 2,
'j': 1,
'k': 0}
>>>
Reading the source code of pprint.py (2.5) it does sort the dictionary using
items = object.items()
items.sort()
for multiline or this for single line
for k, v in sorted(object.items()):
before it attempts to print anything, so if your dictionary sorts properly like that then it should pprint properly. In 2.4 the second sorted() is missing (didn't exist then) so objects printed on a single line won't be sorted.
So the answer appears to be use python2.5, though this doesn't quite explain your output in the question.
Python3 Update
Pretty print by sorted keys (lambda x: x[0]):
for key, value in sorted(dict_example.items(), key=lambda x: x[0]):
print("{} : {}".format(key, value))
Pretty print by sorted values (lambda x: x[1]):
for key, value in sorted(dict_example.items(), key=lambda x: x[1]):
print("{} : {}".format(key, value))
forward to nikobelia
For those who using jenkins to run the play book, I just added to my jenkins job before running the ansible-playbook the he environment variable ANSIBLE_HOST_KEY_CHECKING = False For instance this:
export ANSIBLE_HOST_KEY_CHECKING=False
ansible-playbook 'playbook.yml' \
--extra-vars="some vars..." \
--tags="tags_name..." -vv
Here is a version, basically the same as a couple of the other answers, but that you can copy paste into your SQL server Management Studio to test, (and without generating any unwanted tables), thanks to some inline values.
WITH [TestData]([ID],[SKU],[PRODUCT]) AS
(
SELECT *
FROM (
VALUES
(1, 'FOO-23', 'Orange'),
(2, 'BAR-23', 'Orange'),
(3, 'FOO-24', 'Apple'),
(4, 'FOO-25', 'Orange')
)
AS [TestData]([ID],[SKU],[PRODUCT])
)
SELECT * FROM [TestData] WHERE [ID] IN
(
SELECT MIN([ID])
FROM [TestData]
GROUP BY [PRODUCT]
)
Result
ID SKU PRODUCT
1 FOO-23 Orange
3 FOO-24 Apple
I have ignored the following ...
WHERE ([SKU] LIKE 'FOO-%')
as its only part of the authors faulty code and not part of the question. It's unlikely to be helpful to people looking here.
please don't try with the old cv module, use cv2:
import cv2
cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,0), 2)
x1,y1 ------
| |
| |
| |
--------x2,y2
[edit] to append the follow-up questions below:
cv2.imwrite("my.png",img)
cv2.imshow("lalala", img)
k = cv2.waitKey(0) # 0==wait forever
For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.
However, if you had multiple rules like this:
#foo > ul > li > ul > li > a:nth-child(3n+1) {
color: red;
}
#foo > ul > li > ul > li > a:nth-child(3n+2) {
color: green;
}
#foo > ul > li > ul > li > a:nth-child(3n+3) {
color: blue;
}
You could condense them to one of the following:
/* Sass */
#foo > ul > li > ul > li
> a:nth-child(3n+1)
color: red
> a:nth-child(3n+2)
color: green
> a:nth-child(3n+3)
color: blue
/* SCSS */
#foo > ul > li > ul > li {
> a:nth-child(3n+1) { color: red; }
> a:nth-child(3n+2) { color: green; }
> a:nth-child(3n+3) { color: blue; }
}
First of all, your description is misleading. Double
is a floating point data type. You presumably want to pad your digits with leading zeros in a string. The following code does that:
$s = sprintf('%02d', $digit);
For more information, refer to the documentation of sprintf
.
I'm not sure I'm repeating someone but some time ago some good soul wrote Y-operator for recursively called function like:
def tail_recursive(func):
y_operator = (lambda f: (lambda y: y(y))(lambda x: f(lambda *args: lambda: x(x)(*args))))(func)
def wrap_func_tail(*args):
out = y_operator(*args)
while callable(out): out = out()
return out
return wrap_func_tail
and then recursive function needs form:
def my_recursive_func(g):
def wrapped(some_arg, acc):
if <condition>: return acc
return g(some_arg, acc)
return wrapped
# and finally you call it in code
(tail_recursive(my_recursive_func))(some_arg, acc)
for Fibonacci numbers your function looks like this:
def fib(g):
def wrapped(n_1, n_2, n):
if n == 0: return n_1
return g(n_2, n_1 + n_2, n-1)
return wrapped
print((tail_recursive(fib))(0, 1, 1000000))
output:
..684684301719893411568996526838242546875
(actually tones of digits)
just seperate the class name with a comma.
.a,.b{
your styles
}
It looks like you can say
Convert.ToInt64(value, 16)
to get the decimal from hexdecimal.
The other way around is:
otherVar.ToString("X");
Variables can point to anywhere they want.. An error will be thrown if you do the following:
a = "dog"
print a #dog
a[1] = "g" #ERROR!!!!!! STRINGS ARE IMMUTABLE
Use nanosleep(2). It uses structure timespec
that is used to specify intervals of time with nanosecond precision.
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
I had a CASE statement with WHEN column = 'sometext & more text' THEN ....
I replaced it with WHEN column = 'sometext ' || CHR(38) || ' more text' THEN ...
you could also use WHEN column LIKE 'sometext _ more text' THEN ...
(_ is the wildcard for a single character)
You can use the "filter" filter in your controller to get all the "C" grades. Getting the first element of the result array will give you the title of the subject that has grade "C".
$scope.gradeC = $filter('filter')($scope.results.subjects, {grade: 'C'})[0];
http://jsbin.com/ewitun/1/edit
The same with plain ES6:
$scope.gradeC = $scope.results.subjects.filter((subject) => subject.grade === 'C')[0]
Your data type is DECIMAL with decimal places, say DECIMAL(10,2). The values in your database are 12, 15, 18, and 20.
12 is the same as 12.0 and 12.00 and 12.000 . It is up to the tool you are using to select the data with, how to display the numbers. Yours either defaults to two digits for decimals or it takes the places from your data definition.
If you only want integers in your column, then change its data type to INT. It makes no sense to use DECIMAL then.
If you want integers and decimals in that column then stay with the DECIMAL type. If you don't like the way you are shown the values, then format them in your application. It's up to that client program to decide for instance if to display point or comma for the decimal separator. (The database can be used from different locations.)
Also don't rely on any database or session settings like a decimal separator being a point and not a comma and then use REPLACE on it. That can work for one person and not for the other.
You can basically do this
if(s.charAt(i)==32){
return true;
}
You must write boolean method.Whitespace char is 32.
You can use this code, this code is for AES-256-CBC or you can use it for other AES encryption. Key length error mainly comes in 256-bit encryption.
This error comes due to the encoding or charset name we pass in the SecretKeySpec. Suppose, in my case, I have a key length of 44, but I am not able to encrypt my text using this long key; Java throws me an error of invalid key length. Therefore I pass my key as a BASE64 in the function, and it converts my 44 length key in the 32 bytes, which is must for the 256-bit encryption.
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.Security;
import java.util.Base64;
public class Encrypt {
static byte [] arr = {1,2,3,4,5,6,7,8,9};
// static byte [] arr = new byte[16];
public static void main(String...args) {
try {
// System.out.println(Cipher.getMaxAllowedKeyLength("AES"));
Base64.Decoder decoder = Base64.getDecoder();
// static byte [] arr = new byte[16];
Security.setProperty("crypto.policy", "unlimited");
String key = "Your key";
// System.out.println("-------" + key);
String value = "Hey, i am adnan";
String IV = "0123456789abcdef";
// System.out.println(value);
// log.info(value);
IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
// IvParameterSpec iv = new IvParameterSpec(arr);
// System.out.println(key);
SecretKeySpec skeySpec = new SecretKeySpec(decoder.decode(key), "AES");
// System.out.println(skeySpec);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// System.out.println("ddddddddd"+IV);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
// System.out.println(cipher.getIV());
byte[] encrypted = cipher.doFinal(value.getBytes());
String encryptedString = Base64.getEncoder().encodeToString(encrypted);
System.out.println("encrypted string,,,,,,,,,,,,,,,,,,,: " + encryptedString);
// vars.put("input-1",encryptedString);
// log.info("beanshell");
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
In my case I was using the prototype name as the object name. For e.g.
function proto1()
{}
var proto1 = new proto1();
It was a silly mistake but might be of help to someone like me ;)
Find out the web server user
open up terminal and type
lsof -i tcp:80
This will show you the user of the web server process Here is an example from a raspberry pi running debian:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
apache2 7478 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
apache2 7664 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
apache2 7794 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
The user is www-data
If you give ownership of the web files to the web server:
chown www-data:www-data -R /opt/lamp/htdocs
And chmod 755 for good measure:
chmod 755 -R /opt/lamp/htdocs
Let me know how you go, maybe you need to use 'sudo' before the command, i.e.
sudo chown www-data:www-data -R /opt/lamp/htdocs
if it doesn't work, please give us the output of:
ls -al /opt/lamp/htdocs
On Linux, you can download the Docker Compose binary from the Compose repository release page on GitHub. Follow the instructions from the link, which involve running the curl command in your terminal to download the binaries. These step-by-step instructions are also included below.
1:Run this command to download the current stable release of Docker Compose:
sudo curl -L "https://github.com/docker/compose/releases/download/1.26.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
To install a different version of Compose, substitute 1.26.2 with the version of Compose you want to use.
2:Apply executable permissions to the binary:
sudo chmod +x /usr/local/bin/docker-compose
Note: If the command docker-compose fails after installation, check your path. You can also create a symbolic link to /usr/bin or any other directory in your path.
since you capitalized the word, I assume you are referring to the interface javax.naming.Context
. A few classes implement this interface, and at its simplest description, it (generically) is a set of name/object pairs.
My solution is
fig = plt.figure()
fig.add_subplot(1, 2, 1) #top and bottom left
fig.add_subplot(2, 2, 2) #top right
fig.add_subplot(2, 2, 4) #bottom right
plt.show()
Some months ago I ran into an odd situation where I also needed to send some Json-formatted date back to my controller. Here's what I came up with after pulling my hair out:
My class looks like this :
public class NodeDate
{
public string nodedate { get; set; }
}
public class NodeList1
{
public List<NodeDate> nodedatelist { get; set; }
}
and my c# code as follows :
public string getTradeContribs(string Id, string nodedates)
{
//nodedates = @"{""nodedatelist"":[{""nodedate"":""01/21/2012""},{""nodedate"":""01/22/2012""}]}"; // sample Json format
System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
NodeList1 nodes = (NodeList1)ser.Deserialize(nodedates, typeof(NodeList1));
string thisDate = "";
foreach (var date in nodes.nodedatelist)
{ // iterate through if needed...
thisDate = date.nodedate;
}
}
and so I was able to Deserialize my nodedates Json object parameter in the "nodes" object; naturally of course using the class "NodeList1" to make it work.
I hope this helps.... Bob
Like this:
import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);
Or adding from an Array/ or multiple literals; wrap to a list, first.
Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b)); // from an array variable
b.addAll( Arrays.asList( 8, 9, 10)); // from literals
To get the intersection:
// copies all from A; then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print; r.toString() implied.
System.out.println("A intersect B="+r);
Hope this answer helps. Vote for it!
Try this:
Get-ChildItem C:\windows\System32 -Include *.txt -Recurse | select -ExpandProperty FullName
From version 1.9 Easier and official way of getting json
from django.http import JsonResponse
from django.forms.models import model_to_dict
return JsonResponse( model_to_dict(modelinstance) )
Swift 2.0
Pass info using userInfo
which is a optional Dictionary of type [NSObject : AnyObject]?
let imageDataDict:[String: UIImage] = ["image": image]
// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil, userInfo: imageDataDict)
// Register to receive notification in your class
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: notificationName, object: nil)
// handle notification
func showSpinningWheel(notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
// do something with your image
}
}
Swift 3.0 version and above
The userInfo now takes [AnyHashable:Any]? as an argument, which we provide as a dictionary literal in Swift
let imageDataDict:[String: UIImage] = ["image": image]
// post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// handle notification
// For swift 4.0 and above put @objc attribute in front of function Definition
func showSpinningWheel(_ notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
// do something with your image
}
}
NOTE: Notification “names” are no longer strings, but are of type Notification.Name, hence why we are using NSNotification.Name(rawValue:"notificationName")
and we can extend Notification.Name with our own custom notifications.
extension Notification.Name {
static let myNotification = Notification.Name("myNotification")
}
// and post notification like this
NotificationCenter.default.post(name: .myNotification, object: nil)
Public Function GetLastRow(ByVal SheetName As String) As Integer
Dim sht As Worksheet
Dim FirstUsedRow As Integer 'the first row of UsedRange
Dim UsedRows As Integer ' number of rows used
Set sht = Sheets(SheetName)
''UsedRange.Rows.Count for the empty sheet is 1
UsedRows = sht.UsedRange.Rows.Count
FirstUsedRow = sht.UsedRange.Row
GetLastRow = FirstUsedRow + UsedRows - 1
Set sht = Nothing
End Function
sheet.UsedRange.Rows.Count: retrurn number of rows used, not include empty row above the first row used
if row 1 is empty, and the last used row is 10, UsedRange.Rows.Count will return 9, not 10.
This function calculate the first row number of UsedRange plus number of UsedRange rows.
I had a directory of files that I wanted to check. I created an Excel macro to determine ANSI vs. UTF-8. This worked for me.
Sub GetTextFileEncoding()
Dim sFile As String
Dim sPath As String
Dim sTextLine As String
Dim iRow As Integer
'Set Defaults and Initial Values
iRow = 1
sPath = "C:textfiles\"
sFile = Dir(sPath & "*.txt")
Do While Len(sFile) > 0
'Get FileType
'Debug.Print sFile & " - " & FileEncodeType(sPath & sFile)
'Show on Excel Worksheet
Cells(iRow, 1).Value = sFile
Cells(iRow, 2).Value = FileEncodeType(sPath & sFile)
'Get next file
sFile = Dir
'Increment Row
iRow = iRow + 1
Loop
End Sub
Function FileEncodeType(sFile As String) As String
Dim bEF As Boolean
Dim bBB As Boolean
Dim bBF As Boolean
bEF = False
bBB = False
bBF = False
Open sFile For Input As #1
If Not EOF(1) Then
'Read first line
Line Input #1, textline
'Debug.Print textline
For i = 1 To 3
'Debug.Print Asc(Mid(textline, i, 1)) & " - " & Mid(textline, i, 1)
Select Case i
Case 1
If Asc(Mid(textline, i, 1)) = 239 Then
bEF = True
End If
Case 2
If Asc(Mid(textline, i, 1)) = 187 Then
bBB = True
End If
Case 3
If Asc(Mid(textline, i, 1)) = 191 Then
bBF = True
End If
Case 4
End Select
Next
End If
Close #1
If bEF And bBB And bBF Then
FileEncodeType = "UTF-8"
Else
FileEncodeType = "ANSI"
End If
End Function
In many case It is java facet problem ,jdk or jre or jsp version is difference than maven project face.
Solutions above are good but they require ~/.bash_profile. /usr/local/bin
is already in the $PATH and it can be confirmed by doing echo $PATH
. Download maven and run the following commands -
$ cd ~/Downloads
$ tar xvf apache-maven-3.5.3-bin.tar.gz
$ mv apache-maven-3.5.3 /usr/local/
$ cd /usr/local/bin
$ sudo ln -s ../apache-maven-3.5.3/bin/mvn mvn
$ mvn -version
$ which mvn
Note: The version of apache maven would be the one you will download.
I need exactly this requirement during my Travis job but with multiple values. I start with this solution but when calling multiple time this is very slow (I need 5 expresions).
I wrote a simple maven plugin to extract pom.xml's values into .sh file.
https://github.com/famaridon/ci-tools-maven-plugin
mvn com.famaridon:ci-tools-maven-plugin:0.0.1-SNAPSHOT:environment -Dexpressions=project.artifactId,project.version,project.groupId,project.build.sourceEncoding
Will produce that:
#!/usr/bin/env bash
CI_TOOLS_PROJECT_ARTIFACTID='ci-tools-maven-plugin';
CI_TOOLS_PROJECT_VERSION='0.0.1-SNAPSHOT';
CI_TOOLS_PROJECT_GROUPID='com.famaridon';
CI_TOOLS_PROJECT_BUILD_SOURCEENCODING='UTF-8';
now you can simply source the file
source .target/ci-tools-env.sh
Have fun.
This is null-safe
Number tmp = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
Long value1 = tmp == null ? null : tmp.longValue();
For those who are searching for a light answer, you can get a simple working example from here:
html {
position: relative;
min-height: 100%;
}
body {
margin-bottom: 60px /* Height of the footer */
}
footer {
position: absolute;
bottom: 0;
width: 100%;
height: 60px /* Example value */
}
Just play with the body
's margin-bottom
for adding space between the content and footer.
From 1700 to 1917, official calendar was the Julian calendar. Since then they we use the Gregorian calendar system. The transition from the Julian to Gregorian calendar system occurred in 1918, when the next day after January 31st was February 14th. This means that 32nd day in 1918, was the February 14th.
In both calendar systems, February is the only month with a variable amount of days, it has 29 days during a leap year, and 28 days during all other years. In the Julian calendar, leap years are divisible by 4 while in the Gregorian calendar, leap years are either of the following:
Divisible by 400.
Divisible by 4 and not divisible by 100.
So the program for leap year will be:
def leap_notleap(year):
yr = ''
if year <= 1917:
if year % 4 == 0:
yr = 'leap'
else:
yr = 'not leap'
elif year >= 1919:
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
yr = 'leap'
else:
yr = 'not leap'
else:
yr = 'none actually, since feb had only 14 days'
return yr
If only to 0 then you can use memset
:
int* a = new int[6];
memset(a, 0, 6*sizeof(int));
You need to call self.a()
to invoke a
from b
. a
is not a global function, it is a method on the class.
You may want to read through the Python tutorial on classes some more to get the finer details down.
Something like this should do it:
for element in list_:
sys.stdout.write(str(element))
you don't need to create a hidden field for all checkboxes just copy my code.
it will change the value of checkbox if not checked the value
will assign 0
and if checkbox checked then assign value
into 1
$("form").submit(function () {
var this_master = $(this);
this_master.find('input[type="checkbox"]').each( function () {
var checkbox_this = $(this);
if( checkbox_this.is(":checked") == true ) {
checkbox_this.attr('value','1');
} else {
checkbox_this.prop('checked',true);
//DONT' ITS JUST CHECK THE CHECKBOX TO SUBMIT FORM DATA
checkbox_this.attr('value','0');
}
})
})
Something like this seems to work for me:
SELECT * FROM Parameters WHERE Name LIKE '%\n%'
To summarize the contents of other (already good!) answers, isinstance
caters for inheritance (an instance of a derived class is an instance of a base class, too), while checking for equality of type
does not (it demands identity of types and rejects instances of subtypes, AKA subclasses).
Normally, in Python, you want your code to support inheritance, of course (since inheritance is so handy, it would be bad to stop code using yours from using it!), so isinstance
is less bad than checking identity of type
s because it seamlessly supports inheritance.
It's not that isinstance
is good, mind you—it's just less bad than checking equality of types. The normal, Pythonic, preferred solution is almost invariably "duck typing": try using the argument as if it was of a certain desired type, do it in a try
/except
statement catching all exceptions that could arise if the argument was not in fact of that type (or any other type nicely duck-mimicking it;-), and in the except
clause, try something else (using the argument "as if" it was of some other type).
basestring
is, however, quite a special case—a builtin type that exists only to let you use isinstance
(both str
and unicode
subclass basestring
). Strings are sequences (you could loop over them, index them, slice them, ...), but you generally want to treat them as "scalar" types—it's somewhat incovenient (but a reasonably frequent use case) to treat all kinds of strings (and maybe other scalar types, i.e., ones you can't loop on) one way, all containers (lists, sets, dicts, ...) in another way, and basestring
plus isinstance
helps you do that—the overall structure of this idiom is something like:
if isinstance(x, basestring)
return treatasscalar(x)
try:
return treatasiter(iter(x))
except TypeError:
return treatasscalar(x)
You could say that basestring
is an Abstract Base Class ("ABC")—it offers no concrete functionality to subclasses, but rather exists as a "marker", mainly for use with isinstance
. The concept is obviously a growing one in Python, since PEP 3119, which introduces a generalization of it, was accepted and has been implemented starting with Python 2.6 and 3.0.
The PEP makes it clear that, while ABCs can often substitute for duck typing, there is generally no big pressure to do that (see here). ABCs as implemented in recent Python versions do however offer extra goodies: isinstance
(and issubclass
) can now mean more than just "[an instance of] a derived class" (in particular, any class can be "registered" with an ABC so that it will show as a subclass, and its instances as instances of the ABC); and ABCs can also offer extra convenience to actual subclasses in a very natural way via Template Method design pattern applications (see here and here [[part II]] for more on the TM DP, in general and specifically in Python, independent of ABCs).
For the underlying mechanics of ABC support as offered in Python 2.6, see here; for their 3.1 version, very similar, see here. In both versions, standard library module collections (that's the 3.1 version—for the very similar 2.6 version, see here) offers several useful ABCs.
For the purpose of this answer, the key thing to retain about ABCs (beyond an arguably more natural placement for TM DP functionality, compared to the classic Python alternative of mixin classes such as UserDict.DictMixin) is that they make isinstance
(and issubclass
) much more attractive and pervasive (in Python 2.6 and going forward) than they used to be (in 2.5 and before), and therefore, by contrast, make checking type equality an even worse practice in recent Python versions than it already used to be.
Select top 1 * from foo where id > 4 order by id asc
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT * FROM learer WHERE id = @id";
cmd.Parameters.AddWithValue("@id", index);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
}
}
}
In C (not C++), you have to declare struct variables like:
struct myStruct myVariable;
In order to be able to use myStruct myVariable;
instead, you can typedef
the struct:
typedef struct myStruct someStruct;
someStruct myVariable;
You can combine struct
definition and typedef
s it in a single statement which declares an anonymous struct
and typedef
s it.
typedef struct { ... } myStruct;
Do it with lodash and identity lambda function, just define it before use your object
const _ = require('lodash');
...
_.uniqBy([{a:1,b:2},{a:1,b:2},{a:1,b:3}], v=>v.a.toString()+v.b.toString())
_.uniq([1,2,3,3,'a','a','x'])
and will have:
[{a:1,b:2},{a:1,b:3}]
[1,2,3,'a','x']
(this is the simplest way )
Use TimeSpan.Parse
to convert the string
http://msdn.microsoft.com/en-us/library/system.timespan.parse(v=vs.110).aspx
An angular solution using $anchorScroll
taken from a now archived blog post by Ben Lesh, which is also reproduced in some detail at this SO answer he contributed (including a rewrite of how to do this within a routing):
app.controller('MainCtrl', function($scope, $location, $anchorScroll) {
var i = 1;
$scope.items = [{ id: 1, name: 'Item 1' }];
$scope.addItem = function (){
i++;
//add the item.
$scope.items.push({ id: i, name: 'Item ' + i});
//now scroll to it.
$location.hash('item' + i);
$anchorScroll();
};
});
And here is the plunker, from the blog that provided this solution: http://plnkr.co/edit/xi2r8wP6ZhQpmJrBj1jM?p=preview
Important to note that the template at that plunker includes this, which sets up the id
that you're using $anchorScroll
to scroll to:
<li ng-repeat="item in items"
id="item{{item.id}}"
>{{item.name}</li>
And if you care for a pure javascript solution, here is one:
Invoke runScroll in your code with parent container id and target scroll id:
function runScroll(parentDivId,targetID) {
var longdiv;
longdiv = document.querySelector("#" + parentDivId);
var div3pos = document.getElementById(targetID).offsetTop;
scrollTo(longdiv, div3pos, 600);
}
function scrollTo(element, to, duration) {
if (duration < 0) return;
var difference = to - element.scrollTop;
var perTick = difference / duration * 10;
setTimeout(function () {
element.scrollTop = element.scrollTop + perTick;
if (element.scrollTop == to) return;
scrollTo(element, to, duration - 10);
}, 10);
}
Reference: Cross browser JavaScript (not jQuery...) scroll to top animation
Of course that works; when @item1 = N''
, it IS NOT NULL
.
You can define @item1
as NULL
by default at the top of your stored procedure, and then not pass in a parameter.
If it’s one table only then all you need to do is
One thing you’ll have to consider is other updates such as migrating other objects in the future. Note that your source and destination tables do not have the same name. This means that you’ll also have to make changes if you dependent objects such as views, stored procedures and other.
Whit one or several objects you can go manually w/o any issues. However, when there are more than just a few updates 3rd party comparison tools come in very handy. Right now I’m using ApexSQL Diff for schema migrations but you can’t go wrong with any other tool out there.
You could do $stmt->queryString
to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.
In case of MAC users, go to Terminal and do the following
lsof -i :8080 //returns the PID (process id) that runs on port 8080
kill 1234 //kill the process using PID (used dummy PID here)
lsof -i :8443
kill 4321
8080 is HTTP port and 8443 is HTTPS port, by default.
I found the new emulator Build.HARDWARE = "ranchu"
.
Reference:https://groups.google.com/forum/#!topic/android-emulator-dev/dltBnUW_HzU
And also I found the Android official way to check whether emulator or not.I think it's good reference for us.
Since Android API Level 23 [Android 6.0]
package com.android.internal.util;
/**
* @hide
*/
public class ScreenShapeHelper {
private static final boolean IS_EMULATOR = Build.HARDWARE.contains("goldfish");
}
We have ScreenShapeHelper.IS_EMULATOR
to check whether emulator.
Since Android API Level 24 [Android 7.0]
package android.os;
/**
* Information about the current build, extracted from system properties.
*/
public class Build {
/**
* Whether this build was for an emulator device.
* @hide
*/
public static final boolean IS_EMULATOR = getString("ro.kernel.qemu").equals("1");
}
We have Build.IS_EMULATOR
to check whether emulator.
The way the official to check whether emulator is not new,and also maybe not enough,the answers above also mentioned.
But this maybe show us that the official will provide the way of official to check whether emulator or not.
As using the above all ways mentioned,right now we can also use the two ways about to check whether emulator.
How to access the com.android.internal
package and @hide
and wait for the official open SDK.
The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:
try:
assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
print 'Houston, we have a problem.'
raise
Which gives the following output that includes the offending statement and line number:
Houston, we have a problem.
Traceback (most recent call last):
File "/tmp/poop.py", line 2, in <module>
assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie
Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):
import logging
try:
assert False == True
except AssertionError:
logging.error("Nothing is real but I can't quit...", exc_info=True)
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
Use the border-spacing
property on the table
element to set the spacing between cells.
Make sure border-collapse
is set to separate
(or there will be a single border between each cell instead of a separate border around each one that can have spacing between them).
Get days between Current date to destination Date
SELECT DATEDIFF('2019-04-12', CURDATE()) AS days;
output
335
http://msdn.microsoft.com/en-us/library/k6h9cz8h.aspx - See this on registering IIS for ASP.NET 4.0
To add to Joachim Sauer's answer, if you ever need to do this in a static context, you can do something like the following:
static {
Properties prop = new Properties();
InputStream in = CurrentClassName.class.getResourceAsStream("foo.properties");
prop.load(in);
in.close()
}
(Exception handling elided, as before.)
You can do this very easily in Android Studio.
Create a libraries
folder underneath your project main directory. For example, if your project is OpenCVExamples
, you would create a OpenCVExamples/libraries
folder.
Go to the location where you have SDK "\OpenCV-2.4.8-android-sdk\sdk" here you will find the java
folder, rename it to opencv
.
Now copy the complete opencv directory from the SDK into the libraries folder you just created.
Now create a build.gradle
file in the opencv
directory with the following contents
apply plugin: 'android-library'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.9.+'
}
}
android {
compileSdkVersion 19
buildToolsVersion "19.0.1"
defaultConfig {
minSdkVersion 8
targetSdkVersion 19
versionCode 2480
versionName "2.4.8"
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
res.srcDirs = ['res']
aidl.srcDirs = ['src']
}
}
}
Edit your settings.gradle file in your application’s main directory and add this line:
include ':libraries:opencv'
Sync your project with Gradle and it should looks like this
Right click on your project then click on the Open Module Settings
then Choose Modules from the left-hand list, click on your application’s module, click on the Dependencies tab, and click on the + button to add a new module dependency.
Choose Module dependency
. It will open a dialog with a list of modules to choose from; select “:libraries:opencv”.
Create a jniLibs
folder in the /app/src/main/
location and copy the all the folder with *.so files (armeabi, armeabi-v7a, mips, x86) in the jniLibs
from the OpenCV SDK.
Click OK. Now everything done, go and enjoy with OpenCV.
Microsoft Windows users of 64 bit Python installations will need to download the 64 bit .whl
of Scipy from here, then simply cd
into the folder you've downloaded the .whl
file and run:
pip install scipy-0.16.1-cp27-none-win_amd64.whl
Excel export script works on IE7+, Firefox and Chrome.
function fnExcelReport()
{
var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange; var j=0;
tab = document.getElementById('headerTable'); // id of table
for(j = 0 ; j < tab.rows.length ; j++)
{
tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text=tab_text+"</table>";
tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
}
else //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
Just create a blank iframe:
<iframe id="txtArea1" style="display:none"></iframe>
Call this function on:
<button id="btnExport" onclick="fnExcelReport();"> EXPORT </button>
INSERT INTO vendors (
name,
phone,
addressLine1,
addressLine2,
city,
state,
postalCode,
country,
customer_id
)
SELECT
name,
phone,
addressLine1,
addressLine2,
city,
state ,
postalCode,
country,
customer_id
FROM
customers;
Andy E. gave a good answer.
I would add, if you feel to select all the childs in some special selector (this need happened to me recently), you can apply the method "getElementsByTagName()" on any DOM object you want.
For an example, I needed to just parse "visual" part of the web page, so I just made this
var visualDomElts = document.body.getElementsByTagName('*');
This will never take in consideration the head part.
Here's an improved version of Evan's answer which seems to properly account for overflow logic.
function element_scrollbars(node) {
var element = $(node);
var overflow_x = element.css("overflow-x");
var overflow_y = element.css("overflow-y");
var overflow = element.css("overflow");
if (overflow_x == "undefined") overflow_x == "";
if (overflow_y == "undefined") overflow_y == "";
if (overflow == "undefined") overflow == "";
if (overflow_x == "") overflow_x = overflow;
if (overflow_y == "") overflow_y = overflow;
var scrollbar_vertical = (
(overflow_y == "scroll")
|| (
(
(overflow_y == "hidden")
|| (overflow_y == "visible")
)
&& (
(node.scrollHeight > node.clientHeight)
)
)
);
var scrollbar_horizontal = (
(overflow_x == "scroll")
|| (
(
(overflow_x == "hidden")
|| (overflow_x == "visible")
)
&& (
(node.scrollWidth > node.clientWidth)
)
)
);
return {
vertical: scrollbar_vertical,
horizontal: scrollbar_horizontal
};
}
Looks like the extension is not installed in the particular database you require it.
You should connect to this particular database with
\CONNECT my_database
Then install the extension in this database
CREATE EXTENSION "uuid-ossp";
change drop down to start file your project
There's a much easier approach using PrintWriter (see here)
Basically all you need is:
// set up URL connection
URL urlToRequest = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection)urlToRequest.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// write out form parameters
String postParamaters = "param1=value1¶m2=value2"
urlConnection.setFixedLengthStreamingMode(postParameters.getBytes().length);
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(postParameters);
out.close();
// connect
urlConnection.connect();
I don't believe Windows (as opposed to .NET) provides a direct way to get that.
The only way I know of is to enumerate all the top level windows with EnumWindows()
and then find what process each belongs to GetWindowThreadProcessID()
. This sounds indirect and inefficient, but it's not as bad as you might expect -- in a typical case, you might have a dozen top level windows to walk through...
Application_Error having issue with Ajax requests. If error handled in Action which called by Ajax - it will display your Error View inside the resulting container.
$("#someElement").fadeTo(3000, 0.3 ).fadeTo(3000, 1).fadeTo(3000, 0.3 ).fadeTo(3000, 1);
3000 is 3 seconds
From opacity 1 it is faded to 0.3, then to 1 and so on.
You can stack more of these.
Only jQuery is needed. :)