In Expression Language you can just use the ==
or eq
operator to compare object values. Behind the scenes they will actually use the Object#equals()
. This way is done so, because until with the current EL 2.1 version you cannot invoke methods with other signatures than standard getter (and setter) methods (in the upcoming EL 2.2 it would be possible).
So the particular line
<c:when test="${lang}.equals(${pageLang})">
should be written as (note that the whole expression is inside the {
and }
)
<c:when test="${lang == pageLang}">
or, equivalently
<c:when test="${lang eq pageLang}">
Both are behind the scenes roughly interpreted as
jspContext.findAttribute("lang").equals(jspContext.findAttribute("pageLang"))
If you want to compare constant String
values, then you need to quote it
<c:when test="${lang == 'en'}">
or, equivalently
<c:when test="${lang eq 'en'}">
which is behind the scenes roughly interpreted as
jspContext.findAttribute("lang").equals("en")
The variable set by varStatus
is a LoopTagStatus
object, not an int. Use:
<div id="divIDNo${theCount.index}">
To clarify:
${theCount.index}
starts counting at 0
unless you've set the begin
attribute${theCount.count}
starts counting at 1
it also can be a great idea using concat for EL + MAP + JSON problem like in this example :
#{myMap[''.concat(myid)].content}
You don't need the jsp:useBean
to set the model if you already have a controller which prepared the model.
Just access it plain by EL:
<p>${Questions.questionPaperID}</p>
<p>${Questions.question}</p>
or by JSTL <c:out>
tag if you'd like to HTML-escape the values or when you're still working on legacy Servlet 2.3 containers or older when EL wasn't supported in template text yet:
<p><c:out value="${Questions.questionPaperID}" /></p>
<p><c:out value="${Questions.question}" /></p>
Unrelated to the problem, the normal practice is by the way to start attribute name with a lowercase, like you do with normal variable names.
session.setAttribute("questions", questions);
and alter EL accordingly to use ${questions}
.
Also note that you don't have any JSTL tag in your code. It's all plain JSP.
Try the following:
<c:set var="count" value="0" scope="page" />
//in your loops
<c:set var="count" value="${count + 1}" scope="page"/>
I got away with simply using two if tags, thought I'd add an answer in case it's of use to anyone else:
<c:if test="${condition}">
...
</c:if>
<c:if test="${!condition}">
...
</c:if>
whilst technically not an if-else
per se, the behaviour is the same and avoids the clunky approach of using the choose
tag, so depending on how complex your requirement is this might be preferable.
if all you're trying to do is get the value of a single entry in a map, there's no need to loop over any collection at all. simplifying gautum's response slightly, you can get the value of a named map entry as follows:
<c:out value="${map['key']}"/>
where 'map' is the collection and 'key' is the string key for which you're trying to extract the value.
Either !=
or ne
will work, but you need to get the accessor syntax and nested quotes sorted out.
<c:if test="${content.contentType.name ne 'MCE'}">
<%-- snip --%>
</c:if>
I found this solution amazing.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%
ArrayList list = new ArrayList();
list.add("one");
list.add("two");
list.add("three");
%>
<c:set var="list" value="<%=list%>" />
<html>
<body>
My list is ${list}<br/>
<c:if test='${fn:contains(list, "two")}'>
My list contains two <br/>
</c:if>
<c:if test='${fn:contains(list, ",")}'>
My list contains ,
</c:if>
</body>
</html>
The output for the code above is
My list is [one, two, three]
My list contains two
My list contains ,
I hope it helps someone.
Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file
<style type="text/css">
<%@include file="css/style.css" %>
</style>
<script type="text/javascript">
<%@include file="js/script.js" %>
</script>
There's also the function tags, a bit more flexible:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">
And here's the tag documentation.
one more approach to use.
first, define the following somewhere on the page:
<div id="valueHolderId">${someValue}</div>
then in JS, just do something similar to
var someValue = $('#valueHolderId').html();
it works great for the cases when all scripts are inside .js files and obviously there is no jstl available
Real simple. You just need to have the string 'selected' added to the right option. In the following code, ${myBean.foo == val ? 'selected' : ' '} will add the string 'selected' if the option's value is the same as the bean value;
<select name="foo" id="foo" value="${myBean.foo}">
<option value="">ALL</option>
<c:forEach items="${fooList}" var="val">
<option value="${val}" ${myBean.foo == val ? 'selected' : ' '}><c:out value="${val}" ></c:out></option>
</c:forEach>
</select>
All that the test
attribute looks for to determine if something is true is the string "true" (case in-sensitive). For example, the following code will print "Hello world!"
<c:if test="true">Hello world!</c:if>
The code within the <%= %>
returns a boolean, so it will either print the string "true" or "false", which is exactly what the <c:if>
tag looks for.
to also check blank string, I suggest following
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:if test="${empty fn:trim(var1)}">
</c:if>
It also handles nulls
Instead of using the "c" tags, you could also do the following:
<h:outputLink value="Images/thumb_02.jpg" target="_blank" rendered="#{not empty user or user.userId eq 0}" />
<h:graphicImage value="Images/thumb_02.jpg" rendered="#{not empty user or user.userId eq 0}" />
<h:outputLink value="/DisplayBlobExample?userId=#{user.userId}" target="_blank" rendered="#{not empty user and user.userId neq 0}" />
<h:graphicImage value="/DisplayBlobExample?userId=#{user.userId}" rendered="#{not empty user and user.userId neq 0}"/>
I think that's a little more readable alternative to skuntsel's alternative answer and is utilizing the JSF rendered attribute instead of nesting a ternary operator. And off the answer, did you possibly mean to put your image in between the anchor tags so the image is clickable?
The comparison needs to be evaluated fully inside EL ${ ... }
, not outside.
<c:if test="${values.type eq 'object'}">
As to the docs, those ${}
things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.
<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />
By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass()
and then Class#getSimpleName()
instead of adding a custom getter.
<c:forEach items="${list}" var="value">
<c:if test="${value['class'].simpleName eq 'Object'}">
<!-- code here -->
</c:if>
</c:forEeach>
c:out
escapes HTML characters so that you can avoid cross-site scripting.
if person.name = <script>alert("Yo")</script>
the script will be executed in the second case, but not when using c:out
If you are using JSP 2.0 and above It will come with the EL support:
so that you can write in plain english and use and
with empty
operators to write your test:
<c:if test="${(empty object_1.attribute_A) and (empty object_2.attribute_B)}">
If you just want to output different text, a more concise example would be
${condition ? "some text when true" : "some text when false"}
It is way shorter than c:choose.
Add this directive to your page: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Paste the JAR file in your WEB-INF/lib folder. This should work. (It worked for me.)
Like this:
<c:forEach var="entry" items="${myMap}">
Key: <c:out value="${entry.key}"/>
Value: <c:out value="${entry.value}"/>
</c:forEach>
If you are using eclipse and maven for handling dependencies, you may need to take these extra steps to make sure eclipse copies the dependencies properly Maven dependencies not visible in WEB-INF/lib (namely the Deployment Assembly for Dynamic web application)
If you just happen to have a Map
with Integer
keys you cannot change, you could write a custom EL function to convert a Long
to Integer
. This would allow you to do something like:
<c:out value="${map[myLib:longToInteger(1)]}"/>
Mark, this is already answered in your previous topic. But OK, here it is again:
Suppose ${list}
points to a List<Object>
, then the following
<c:forEach items="${list}" var="item">
${item}<br>
</c:forEach>
does basically the same as as following in "normal Java":
for (Object item : list) {
System.out.println(item);
}
If you have a List<Map<K, V>>
instead, then the following
<c:forEach items="${list}" var="map">
<c:forEach items="${map}" var="entry">
${entry.key}<br>
${entry.value}<br>
</c:forEach>
</c:forEach>
does basically the same as as following in "normal Java":
for (Map<K, V> map : list) {
for (Entry<K, V> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
The key
and value
are here not special methods or so. They are actually getter methods of Map.Entry
object (click at the blue Map.Entry
link to see the API doc). In EL (Expression Language) you can use the .
dot operator to access getter methods using "property name" (the getter method name without the get
prefix), all just according the Javabean specification.
That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".
If youre using Maven, here's something for your pom.xml file
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<c:forEach items="${sessionScope.empL}" var="emp">
<tr>
<td>Employee ID: <c:out value="${emp.eid}"/></td>
<td>Employee Pass: <c:out value="${emp.ename}"/></td>
</tr>
</c:forEach>
This works for me:
<c:forEach var="i" begin="1970" end="2000">
<option value="${2000-(i-1970)}">${2000-(i-1970)}
</option>
</c:forEach>
Since i have have just one element in my Set the order is not important So I can access to the first element like this :
${ attachments.iterator().next().id }
@skaffman nailed it down. They live each in its own context. However, I wouldn't consider using scriptlets as the solution. You'd like to avoid them. If all you want is to concatenate strings in EL and you discovered that the +
operator fails for strings in EL (which is correct), then just do:
<c:out value="abc${test}" />
Or if abc
is to obtained from another scoped variable named ${resp}
, then do:
<c:out value="${resp}${test}" />
Thymeleaf has an equivalent to <c:choose>
and <c:when>
: the th:switch
and th:case
attributes introduced in Thymeleaf 2.0.
They work as you'd expect, using *
for the default case:
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p>
</div>
See this for a quick explanation of syntax (or the Thymeleaf tutorials).
Disclaimer: As required by StackOverflow rules, I'm the author of Thymeleaf.
Add JSTL library as dependency to your project (javax.servlet.jsp.jstl.core.Config
is a part of this package).
For example, if you were using Gradle, you could write in a build.gradle:
dependencies {
compile 'javax.servlet:jstl:1.2'
}
A simple comparison against string works:
<c:when test="${someModel.status == 'OLD'}">
Try:
<c:if test = "${ansokanInfo.PSystem == 'NAT'}">
JSP/Servlet 2.4 (I think that's the version number) doesn't support method calls in EL and only support properties. The latest servlet containers do support method calls (ie Tomcat 7).
Just noting this here in case anyone else has a similar issue.
If you're directing a request directly to a JSP, using Apache Tomcat web.xml configuration, then ${requestScope.attr}
doesn't seem to work, instead ${param.attr}
contains the request attribute attr
.
It will work perfectly when you will place the two required jar files under /WEB-INF/lib folder i.e. jstl-1.2.jar and javax.servlet.jsp under /WEB-INF/lib folder.
Hope it helps. :)
I was getting this problem with a maven project using the eclipse IDE. I changed the 'Order and Export' in the project's build path putting the Maven dependencies first and the error disappeared. I guess it's because the eclipse IDE was initially building my application source before loading the Maven libraries.
in your pom.xml just add
<!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
and try run
mvn eclipse:eclipse -Dwtpversion=2.0
will solve the problem
You mean size() don't you?
#{MyBean.somelist.size()}
works for me (using JBoss Seam which has the Jboss EL extensions)
I get the same error on my JSP and the bad rated answer was correct
I had the folowing line:
<c:forEach var="agent" items=" ${userList}" varStatus="rowCounter">
and get the folowing error:
javax.el.PropertyNotFoundException: Property 'agent' not found on type java.lang.String
deleting the space before ${userList} solved my problem
If some have the same problem, he will find quickly this post and does not waste 3 days in googeling to find help.
Maybe I don't completely understand the accepted answer so it didn't work for me.
What i did was simply to check if the variable is null, assign it to a known value from my database. Which seems to be similar to the accepted answer whereby you first declare an known value and set it to selected
<select name="department">
<c:forEach var="item" items="${dept}">
<option value="${item.key}">${item.value}</option>
</c:forEach>
</select>
because none of the options are selected, thus item = null
<%
if(item == null){
item = "selectedDept"; //known value from your database
}
%>
This way if the user then selects another option, my IF clause will not catch it and assign to the fixed value that was declared at the start. My concept could be wrong here but it works for me
Here is code based on bestsss' answer:
Enumeration<URL> en = getClass().getClassLoader().getResources(
"META-INF");
List<String> profiles = new ArrayList<>();
while (en.hasMoreElements()) {
URL url = en.nextElement();
JarURLConnection urlcon = (JarURLConnection) (url.openConnection());
try (JarFile jar = urlcon.getJarFile();) {
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
String entry = entries.nextElement().getName();
System.out.println(entry);
}
}
}
Windows must be created on the same stack (aka microtask) as the user-initiated event, e.g. a click callback--so they can't be created later, asynchronously.
However, you can create a window without a URL and you can then change that window's URL once you do know it, even asynchronously!
window.onclick = () => {
// You MUST create the window on the same event
// tick/stack as the user-initiated event (e.g. click callback)
const googleWindow = window.open();
// Do your async work
fakeAjax(response => {
// Change the URL of the window you created once you
// know what the full URL is!
googleWindow.location.replace(`https://google.com?q=${response}`);
});
};
function fakeAjax(callback) {
setTimeout(() => {
callback('example');
}, 1000);
}
Modern browsers will open the window with a blank page (often called about:blank
), and assuming your async task to get the URL is fairly quick, the resulting UX is mostly fine. If you instead want to render a loading message (or anything) into the window while the user waits, you can use Data URIs.
window.open('data:text/html,<h1>Loading...<%2Fh1>');
This code also works.
$(".circle").hover(function() {$(this).hide(200).show(200);});
_x000D_
.circle{_x000D_
width:100px;_x000D_
height:100px;_x000D_
border-radius:50px;_x000D_
font-size:20px;_x000D_
color:black;_x000D_
line-height:100px;_x000D_
text-align:center;_x000D_
background:yellow_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>_x000D_
<div class="circle">hover me</div>
_x000D_
Just to have a simple and complete example for Python 3, which most people seem to be using now.
class MySuper(object):
def __init__(self,a):
self.a = a
class MySub(MySuper):
def __init__(self,a,b):
self.b = b
super().__init__(a)
my_sub = MySub(42,'chickenman')
print(my_sub.a)
print(my_sub.b)
gives
42
chickenman
barplot(data)
barplot(data, yaxp=c(0, max(data), 5))
yaxp=c(minY-axis, maxY-axis, Interval)
You can use this:
"drawCallback": function(settings) {
console.log(settings.json);
//do whatever
},
Using the release version of MVC, here is what I do:
[AcceptVerbs(HttpVerbs.Get)]
[OutputCache(CacheProfile = "CustomerImages")]
public FileResult Show(int customerId, string imageName)
{
var path = string.Concat(ConfigData.ImagesDirectory, customerId, "\\", imageName);
return new FileStreamResult(new FileStream(path, FileMode.Open), "image/jpeg");
}
I obviously have some application specific stuff in here regarding the path construction, but the returning of the FileStreamResult is nice and simple.
I did some performance testing in regards to this action against your everyday call to the image (bypassing the controller) and the difference between the averages was only about 3 milliseconds (controller avg was 68ms, non-controller was 65ms).
I had tried some of the other methods mentioned in answers here and the performance hit was much more dramatic... several of the solutions responses were as much as 6x the non-controller (other controllers avg 340ms, non-controller 65ms).
My answer wouldn't help you probably, but it help with this problem generally.
When you see this kind of exception you should try to open your xml file in any Hex Editor and sometime you can see additional bytes at the beginning of the file which text-editor doesn't show.
Delete them and your xml will be parsed.
Put from before where, and order_by on last:
$this->db->select('*');
$this->db->from('courses');
$this->db->where('tennant_id',$tennant_id);
$this->db->order_by("UPPER(course_name)","desc");
Or try BINARY:
ORDER BY BINARY course_name DESC;
You should add manually on codeigniter for binary sorting.
And set "course_name" character column.
If sorting is used on a character type column, normally the sort is conducted in a case-insensitive fashion.
What type of structure data in courses table?
If you frustrated you can put into array and return using PHP:
Use natcasesort for order in "natural order": (Reference: http://php.net/manual/en/function.natcasesort.php)
Your array from database as example: $array_db = $result_from_db
:
$final_result = natcasesort($array_db);
print_r($final_result);
7-zip understands most kinds of archives, including rpm and the included cpio.
no, jquery always returns a jquery object regardless if a selector was matched or not. You need to use .length
if ( $('#someDiv').length ){
}
byte x = 51; //00101011
byte y = (byte) (x >> 2); //00001010 aka Base(10) 10
/**
* Intent to Send SMS
*
*
* Extras:
*
* "subject"
* A string for the message subject (usually for MMS only).
* "sms_body"
* A string for the text message.
* EXTRA_STREAM
* A Uri pointing to the image or video to attach.
*
* For More Info:
* https://developer.android.com/guide/components/intents-common#SendMessage
*
* @param phoneNumber on which SMS to send
* @param message text Message to send with SMS
*/
public void startSMSIntent(String phoneNumber, String message) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
// This ensures only SMS apps respond
intent.setData(Uri.parse("smsto:"+phoneNumber));
intent.putExtra("sms_body", message);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
(This is pointed out in a comment by Zan Lynx, but I think it deserves an aswer - given that the accepted answer doesn't mention it).
The essential difference between puts(mystr);
and printf(mystr);
is that in the latter the argument is interpreted as a formatting string. The result will be often the same (except for the added newline) if the string doesn't contain any control characters (%
) but if you cannot rely on that (if mystr
is a variable instead of a literal) you should not use it.
So, it's generally dangerous -and conceptually wrong- to pass a dynamic string as single argument of printf
:
char * myMessage;
// ... myMessage gets assigned at runtime, unpredictable content
printf(myMessage); // <--- WRONG! (what if myMessage contains a '%' char?)
puts(myMessage); // ok
printf("%s\n",myMessage); // ok, equivalent to the previous, perhaps less efficient
The same applies to fputs
vs fprintf
(but fputs
doesn't add the newline).
$total_ratings
is an array.
you make the use of the HTML Helper and have
@using(Html.BeginForm())
{
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" value="Login">
<input type="submit" value="Create Account"/>
}
or use the Url helper
<form method="post" action="@Url.Action("MyAction", "MyController")" >
Html.BeginForm
has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:
@using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
< ... >
}
If you don't specify any arguments, the Html.BeginForm()
will create a POST
form that points to your current controller and current action. As an example, let's say you have a controller called Posts
and an action called Delete
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
return View(model);
}
[HttpPost]
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
if(model != null)
db.DeletePost(id);
return RedirectToView("Index");
}
and your html page would be something like:
<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>@Model.Title</strong> will be deleted.</p>
@using(Html.BeginForm())
{
<input type="submit" class="btn btn-danger" value="Delete Post"/>
<text>or</text>
@Url.ActionLink("go to list", "Index")
}
First, you should install "platformio-ide-terminal": Open "Preferences ?," >> Click "+ Install" >> In "Search packages" type "platformio-ide-terminal" >> Click "Install".
And answering exactly the question. If you have previously installed, just use:
ctrl-`
or Option+Command+T (??T)This is deletes the table table_name
.
Replace it with the name of the table, which shall be deleted.
DELETE FROM table_name;
Like most of the others, I'd recommend trying a finite number of times and sleeping between attempts. This way, you don't find yourself in an infinite loop in case something were to actually happen to the remote server.
I'd also recommend continuing only when you get the specific exception you're expecting. This way, you can still handle exceptions you might not expect.
from urllib.error import HTTPError
import traceback
from time import sleep
attempts = 10
while attempts > 0:
try:
#code with possible error
except HTTPError:
attempts -= 1
sleep(1)
continue
except:
print(traceback.format_exc())
#the rest of the code
break
Also, you don't need an else block. Because of the continue in the except block, you skip the rest of the loop until the try block works, the while condition gets satisfied, or an exception other than HTTPError comes up.
s=[52, 33, 70, 39, 57, 59, 7, 2, 46, 69, 11, 74, 58, 60, 63, 43, 75, 92, 65, 19, 1, 79, 22, 38, 26, 3, 66, 88, 9, 15, 28, 44, 67, 87, 21, 49, 85, 32, 89, 77, 47, 93, 35, 12, 73, 76, 50, 45, 5, 29, 97, 94, 95, 56, 48, 71, 54, 55, 51, 23, 84, 80, 62, 30, 13, 34]
dic={}
for i in range(0,len(s),10):
dic[i,i+10]=list(filter(lambda x:((x>=i)&(x<i+10)),s))
print(dic)
for keys,values in dic.items():
print(keys)
print(values)
Output:
(0, 10)
[7, 2, 1, 3, 9, 5]
(20, 30)
[22, 26, 28, 21, 29, 23]
(30, 40)
[33, 39, 38, 32, 35, 30, 34]
(10, 20)
[11, 19, 15, 12, 13]
(40, 50)
[46, 43, 44, 49, 47, 45, 48]
(60, 70)
[69, 60, 63, 65, 66, 67, 62]
(50, 60)
[52, 57, 59, 58, 50, 56, 54, 55, 51]
I prefer not to use a prefix on interfaces:
The prefix hurts readability.
Using interfaces in clients is the standard best way to program, so interfaces names should be as short and pleasant as possible. Implementing classes should be uglier to discourage their use.
When changing from an abstract class to an interface a coding convention with prefix I implies renaming all the occurrences of the class --- not good!
Does your cacerts.pem file hold a single certificate? Since it is a PEM, have a look at it (with a text editor), it should start with
-----BEGIN CERTIFICATE-----
and end with
-----END CERTIFICATE-----
Finally, to check it is not corrupted, get hold of openssl and print its details using
openssl x509 -in cacerts.pem -text
Consider that the files you need to delete have an extension txt
and is located in the location D:\My Folder
, then you could use the below code inside the bat file.
cd "D:\My Folder"
DEL *.txt
/// <summary>
/// map properties
/// </summary>
/// <param name="sourceObj"></param>
/// <param name="targetObj"></param>
private void MapProp(object sourceObj, object targetObj)
{
Type T1 = sourceObj.GetType();
Type T2 = targetObj.GetType();
PropertyInfo[] sourceProprties = T1.GetProperties(BindingFlags.Instance | BindingFlags.Public);
PropertyInfo[] targetProprties = T2.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var sourceProp in sourceProprties)
{
object osourceVal = sourceProp.GetValue(sourceObj, null);
int entIndex = Array.IndexOf(targetProprties, sourceProp);
if (entIndex >= 0)
{
var targetProp = targetProprties[entIndex];
targetProp.SetValue(targetObj, osourceVal);
}
}
}
First solution - simply change the extension of your .json file to .ts and add export default
at the beginning of the file, like so:
export default {
property: value;
}
Then you can just simply import the file without the need to add typings, like so:
import data from 'data';
Second solution get the json via HttpClient.
Inject HttpClient into your component, like so:
export class AppComponent {
constructor(public http: HttpClient) {}
}
and then use this code:
this.http.get('/your.json').subscribe(data => {
this.results = data;
});
This solution has one clear adventage over other solutions provided here - it doesn't require you to rebuild entire application if your json will change (it's loaded dynamically from a separate file, so you can modify only that file).
As mentioned in the question, Multiprocessing in Python is the only real way to achieve true parallelism. Multithreading cannot achieve this because the GIL prevents threads from running in parallel.
As a consequence, threading may not always be useful in Python, and in fact, may even result in worse performance depending on what you are trying to achieve. For example, if you are performing a CPU-bound task such as decompressing gzip files or 3D-rendering (anything CPU intensive) then threading may actually hinder your performance rather than help. In such a case, you would want to use Multiprocessing as only this method actually runs in parallel and will help distribute the weight of the task at hand. There could be some overhead to this since Multiprocessing involves copying the memory of a script into each subprocess which may cause issues for larger-sized applications.
However, Multithreading becomes useful when your task is IO-bound. For example, if most of your task involves waiting on API-calls, you would use Multithreading because why not start up another request in another thread while you wait, rather than have your CPU sit idly by.
TL;DR
Most of the time you get such a error, problem is in code. I am not trying to say that you are writing code that is bad, I am trying to say that you need to carefully observe what's there in that is using this much amount of memory.
Always remember "Garbage collection in PHP is pretty bad", it's not like Java, any other such language. there is a way to enforce garbage collection through gc_collect_cycle, but, in my personal opinion, that won't solve your problem. PHP free all memory used for executing a page, once request-response cycle is complete, so you may run into memory issues, if your script is long running, like a background script(Gearman etc), because, memory isn't freed till script is running.
If above is not the case with your scr,pt, and as you said there is no code that requires such a huge amount of memory, then problem is most definitely in code it self, and upgrading to any version of PHP won't solve the problem. I was facing with one of my Gearman scripts once, and there was a problem with one of my loop where I was appending one variable to one of my array, the variable itself was very heavy (approx 110KB of data). So I would suggest, do a careful inspection of your code.
Ravish
Depending on what you want to achieve with the removed scroll you could just fix the element that you want to remove scroll from (on click, or whatever other trigger you'd like to temporarily deactivate scroll)
I was searching around for a "temp no scroll" solution and for my needs, this solved it
make a class
.fixed{
position: fixed;
}
then with Jquery
var someTrigger = $('#trigger'); //a trigger button
var contentContainer = $('#content'); //element I want to temporarily remove scroll from
contentContainer.addClass('notfixed'); //make sure that the element has the "notfixed" class
//Something to trigger the fixed positioning. In this case we chose a button.
someTrigger.on('click', function(){
if(contentContainer.hasClass('notfixed')){
contentContainer.removeClass('notfixed').addClass('fixed');
}else if(contentContainer.hasClass('fixed')){
contentContainer.removeClass('fixed').addClass('notfixed');
};
});
I found that this was a simple enough solution that works well on all browsers, and also makes for simple use on portable devices (i.e. iPhones, tablets etc). Since the element is temporarily fixed, there is no scroll :)
NOTE! Depending on the placement of your "contentContainer" element you might need to adjust it from the left. Which can easily be done by adding a css left value to that element when the fixed class is active
contentContainer.css({
'left': $(window).width() - contentContainer.width()/2 //This would result in a value that is the windows entire width minus the element we want to "center" divided by two (since it's only pushed from one side)
});
To include an external Javascript file you use the <script>
tag. The src
attribute points to the location of your Javascript file within your web project.
<script src="some.js" type="text/javascript"></script>
JQuery is simply a Javascript file, so if you download a copy of the file you can include it within your page using a script tag. You can also include Jquery from a content distribution network such as the one hosted by Google.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
sudo apt-get install python3-dev
sudo apt-get install libmysqlclient-dev
sudo apt-get install zlib1g-dev
sudo pip3 install mysqlclient
that worked for me!
You can use ggplot2 to rotate the x-axis label adding an additional layer
theme(axis.text.x = element_text(angle = 90, hjust = 1))
You can have something like this
switch (EncodingFormat.Trim().ToLower())
{
case "utf-8":
File.WriteAllBytes(fileName, ASCIIEncoding.Convert(ASCIIEncoding.ASCII, new UTF8Encoding(false), convertToCSV(result, fileName)));
break;
case "utf-8+bom":
File.WriteAllBytes(fileName, ASCIIEncoding.Convert(ASCIIEncoding.ASCII, new UTF8Encoding(true), convertToCSV(result, fileName)));
break;
case "ISO-8859-1":
File.WriteAllBytes(fileName, ASCIIEncoding.Convert(ASCIIEncoding.ASCII, Encoding.GetEncoding("iso-8859-1"), convertToCSV(result, fileName)));
break;
case ..............
}
Just if any one is interested this worked for me. I have a custom Identity which uses int for a primary key so I overrode the GetUserAsync method
Override GetUserAsync
public override Task<User> GetUserAsync(ClaimsPrincipal principal)
{
var userId = GetUserId(principal);
return FindByNameAsync(userId);
}
Get Identity User
var user = await _userManager.GetUserAsync(User);
If you are using a regular Guid primary key you don't need to override GetUserAsync. This is all assuming that you token is configured correctly.
public async Task<string> GenerateTokenAsync(string email)
{
var user = await _userManager.FindByEmailAsync(email);
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_tokenProviderOptions.SecretKey);
var userRoles = await _userManager.GetRolesAsync(user);
var roles = userRoles.Select(o => new Claim(ClaimTypes.Role, o));
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString(CultureInfo.CurrentCulture)),
new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName),
new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName),
new Claim(JwtRegisteredClaimNames.Email, user.Email),
}
.Union(roles);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddHours(_tokenProviderOptions.Expires),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return Task.FromResult(new JwtSecurityTokenHandler().WriteToken(token)).Result;
}
If anyone is using Maven, you'll need to add the dependency in the POM.XML file. The latest version as of this post is below:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
Its acctualy possible ;-)
# not pep8 compatible^
sam = ['Sam',]
try: print('hello',sam) if sam[0] != 'harry' else rais
except: pass
You can do very ugly stuff in python like:
def o(s):return''.join([chr(ord(n)+(13if'Z'<n<'n'or'N'>n else-13))if n.isalpha()else n for n in s])
which is function for rot13/cesa encryption in one line with 99 characters.
IF the table is existed. you can try insert into table_name select * from old_tale;
IF the table is not existed. you should try create table table_name like old_table; insert into table_name select * from old_tale;
You can also use split
and join
:
"Sonic Free Games".split(" ").join("-").toLowerCase(); //sonic-free-games
In Java 8 with stream:
int[] ints = {1, 2, 3};
List<Integer> list = new ArrayList<Integer>();
Collections.addAll(list, Arrays.stream(ints).boxed().toArray(Integer[]::new));
or with Collectors
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());
Beware that when the mounted
event is fired on a component, not all Vue components are replaced yet, so the DOM may not be final yet.
To really simulate the DOM onload
event, i.e. to fire after the DOM is ready but before the page is drawn, use vm.$nextTick from inside mounted
:
mounted: function () {
this.$nextTick(function () {
// Will be executed when the DOM is ready
})
}
If you have a pd.Series
object x
with index named 'Gene', you can use reset_index
and supply the name
argument:
df = x.reset_index(name='count')
Here's a demo:
x = pd.Series([2, 7, 1], index=['Ezh2', 'Hmgb', 'Irf1'])
x.index.name = 'Gene'
df = x.reset_index(name='count')
print(df)
Gene count
0 Ezh2 2
1 Hmgb 7
2 Irf1 1
You have to redirect output from second java executable to some file. Then, use SendSignal to send "-3" to your second process.
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()
If you use a context manager, the file is closed automatically for you
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s" % TotalAmount)
If you're using Python2.6 or higher, it's preferred to use str.format()
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: {0}".format(TotalAmount))
For python2.7 and higher you can use {}
instead of {0}
In Python3, there is an optional file
parameter to the print
function
with open("Output.txt", "w") as text_file:
print("Purchase Amount: {}".format(TotalAmount), file=text_file)
Python3.6 introduced f-strings for another alternative
with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)
Suppose you made changes to multiple files, like:
But you want to commit only changes of File1 and File3.
There are two ways for doing this:
1.Stage only these two files, using:
git add file1 file2
then, commit
git commit -m "your message"
then push,
git push
2.Direct commit
git commit file1 file3 -m "my message"
then push,
git push
Actually first method is useful in case if we are modifying files regularly and staging them --> Large Projects, generally Live projects.
But if we are modifying files and not staging them then we can do direct commit --> Small projects
#!/bin/bash
CURL='/usr/bin/curl'
RVMHTTP="https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer"
CURLARGS="-f -s -S -k"
# you can store the result in a variable
raw="$($CURL $CURLARGS $RVMHTTP)"
# or you can redirect it into a file:
$CURL $CURLARGS $RVMHTTP > /tmp/rvm-installer
or:
We can do same Springboard behavior using UICollectionView and for that we need to write code for custom layout.
I have achieved it with my custom layout class implementation with "SMCollectionViewFillLayout"
Code repository:
https://github.com/smindia1988/SMCollectionViewFillLayout
Output as below:
1.png
2_Code_H-Scroll_V-Fill.png
If you are using GCC, you can use the GNU extension asprintf function.
char* str;
asprintf (&str, "%i", 12313);
free(str);
If you just need a very simple call, you can use URL directly:
import java.net.URL;
new URL("http://wheredatapp.com").openStream();
Here is my solution for that issue:
in Activity A:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE)
{
if(resultCode == Activity.RESULT_OK)
{
tvTitle.setText(data.getExtras().getString("title", ""));
}
}
}
in Activity B:
@Override
public void onBackPressed()
{
setResult(Activity.RESULT_OK, getIntent());
super.onBackPressed();
}
activity b holds the fragment.
in fragment:
private void setText(String text)
{
Intent intent = new Intent();
intent.putExtra("title", text);
getActivity().setIntent(intent);
}
in that way the Intent Object "data" in activity A will get the string from the fragment
Easily done in 2 steps:
dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]
Or in 1 step:
dictionary[new_key] = dictionary.pop(old_key)
which will raise KeyError
if dictionary[old_key]
is undefined. Note that this will delete dictionary[old_key]
.
>>> dictionary = { 1: 'one', 2:'two', 3:'three' }
>>> dictionary['ONE'] = dictionary.pop(1)
>>> dictionary
{2: 'two', 3: 'three', 'ONE': 'one'}
>>> dictionary['ONE'] = dictionary.pop(1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 1
hope you have found a good solution by now. If not, the solution below is an ES6 promise implementation based on js-spark-md5
import SparkMD5 from 'spark-md5';
// Read in chunks of 2MB
const CHUCK_SIZE = 2097152;
/**
* Incrementally calculate checksum of a given file based on MD5 algorithm
*/
export const checksum = (file) =>
new Promise((resolve, reject) => {
let currentChunk = 0;
const chunks = Math.ceil(file.size / CHUCK_SIZE);
const blobSlice =
File.prototype.slice ||
File.prototype.mozSlice ||
File.prototype.webkitSlice;
const spark = new SparkMD5.ArrayBuffer();
const fileReader = new FileReader();
const loadNext = () => {
const start = currentChunk * CHUCK_SIZE;
const end =
start + CHUCK_SIZE >= file.size ? file.size : start + CHUCK_SIZE;
// Selectively read the file and only store part of it in memory.
// This allows client-side applications to process huge files without the need for huge memory
fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
};
fileReader.onload = e => {
spark.append(e.target.result);
currentChunk++;
if (currentChunk < chunks) loadNext();
else resolve(spark.end());
};
fileReader.onerror = () => {
return reject('Calculating file checksum failed');
};
loadNext();
});
It seems that the struct
datatype is commonly used in SOAP:
var_dump($client->__getTypes());
array(52) {
[0] =>
string(43) "struct Bank {\n string Code;\n string Name;\n}"
}
This is not a native PHP datatype!
It seems that the properties of the struct
type referred to in SOAP can be accessed as a simple PHP stdClass
object:
$some_struct = $client->SomeMethod();
echo 'Name: ' . $some_struct->Name;
Yes, you could use either the JavaScript setTimeout()
method or setInterval()
method to invoke the code that you would like to run. Here's how you might do it with setTimeout:
function executeQuery() {
$.ajax({
url: 'url/path/here',
success: function(data) {
// do something with the return value here if you like
}
});
setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}
$(document).ready(function() {
// run the first time; all subsequent calls will take care of themselves
setTimeout(executeQuery, 5000);
});
Like that
var purchCount = (from purchase in myBlaContext.purchases select purchase).Count();
or even easier
var purchCount = myBlaContext.purchases.Count()
Or add "sort name" to list alphabetically
Get-ADPrincipalGroupMembership username | select name | sort name
Splice is good, everyone explain splice so I didn't explain it. You can also use delete keyword in JavaScript, it's good. You can use $.grep also to manipulate this using jQuery.
The jQuery Way :
data.items = jQuery.grep(
data.items,
function (item,index) {
return item.id != "1";
});
DELETE Way:
delete data.items[0]
For Adding PUSH is better the splice, because splice is heavy weighted function. Splice create a new array , if you have a huge size of array then it may be troublesome. delete is sometime useful, after delete if you look for the length of the array then there is no change in length there. So use it wisely.
d = dict([(x,0) for x in a])
**edit Tim's solution is better because it uses generators see the comment to his answer.
Sure, how about:
They all seem to be a bit work in progress, but work to some degree. They are also similar to XPath and XQuery conceptually; even though XML and JSON have different conceptual models (hierarchic vs object/struct).
EDIT Sep-2015: Actually there is now JSON Pointer standard that allows very simple and efficient traversal of JSON content. It is not only formally specified, but also supported by many JSON libraries. So I would call it actual real useful standard, although due to its limited expressiveness it may or may not be considered Query Language per se.
The below one is another approach to extend an User. I feel it is more clear,easy,readable then above two approaches.
http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/
Using above approach:
This solved my problem
var url = "http://localhost/tech1/index.php?route=app/upload/ajax";
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
var $link = $('.'+ids);
var $img = $link.find('i');
$link.html('Uploading..('+percentComplete+'%)');
$link.append($img);
}
}, false);
return xhr;
},
url: url,
type: "POST",
data: JSON.stringify(uploaddata),
contentType: "application/json",
dataType: "json",
success: function(result) {
console.log(result);
}
});
If you downloaded mySQL using a DMG (easiest way to download found here http://dev.mysql.com/downloads/mysql/) in Terminal try: cd /usr/local/
When you type ls
you should see mysql-YOUR-VERSION. You will also see mysql which is the installation directory.
Try:
float x = (float)rand()/(float)(RAND_MAX/a);
To understand how this works consider the following.
N = a random value in [0..RAND_MAX] inclusively.
The above equation (removing the casts for clarity) becomes:
N/(RAND_MAX/a)
But division by a fraction is the equivalent to multiplying by said fraction's reciprocal, so this is equivalent to:
N * (a/RAND_MAX)
which can be rewritten as:
a * (N/RAND_MAX)
Considering N/RAND_MAX
is always a floating point value between 0.0 and 1.0, this will generate a value between 0.0 and a
.
Alternatively, you can use the following, which effectively does the breakdown I showed above. I actually prefer this simply because it is clearer what is actually going on (to me, anyway):
float x = ((float)rand()/(float)(RAND_MAX)) * a;
Note: the floating point representation of a
must be exact or this will never hit your absolute edge case of a
(it will get close). See this article for the gritty details about why.
Sample
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[])
{
srand((unsigned int)time(NULL));
float a = 5.0;
for (int i=0;i<20;i++)
printf("%f\n", ((float)rand()/(float)(RAND_MAX)) * a);
return 0;
}
Output
1.625741
3.832026
4.853078
0.687247
0.568085
2.810053
3.561830
3.674827
2.814782
3.047727
3.154944
0.141873
4.464814
0.124696
0.766487
2.349450
2.201889
2.148071
2.624953
2.578719
You want something more like this:
SELECT TableA.*, TableB.*, TableC.*, TableD.*
FROM TableA
JOIN TableB
ON TableB.aID = TableA.aID
JOIN TableC
ON TableC.cID = TableB.cID
JOIN TableD
ON TableD.dID = TableA.dID
WHERE DATE(TableC.date)=date(now())
In your example, you are not actually including TableD
. All you have to do is perform another join just like you have done before.
A note: you will notice that I removed many of your parentheses, as they really are not necessary in most of the cases you had them, and only add confusion when trying to read the code. Proper nesting is the best way to make your code readable and separated out.
This is possible in HTML5. Example (PHP 5.4):
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple>
<input type="submit" value="Upload">
</form>
<?php
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
?>
<p>File #<?= $i+1 ?>:</p>
<p>
Name: <?= $myFile["name"][$i] ?><br>
Temporary file: <?= $myFile["tmp_name"][$i] ?><br>
Type: <?= $myFile["type"][$i] ?><br>
Size: <?= $myFile["size"][$i] ?><br>
Error: <?= $myFile["error"][$i] ?><br>
</p>
<?php
}
}
?>
</body>
</html>
Here's what it looks like in Chrome after selecting 2 items in the file dialog:
And here's what it looks like after clicking the "Upload" button.
This is just a sketch of a fully working answer. See PHP Manual: Handling file uploads for more information on proper, secure handling of file uploads in PHP.
I would say static block
is just syntactic sugar. There is nothing you could do with static
block and not with anything else.
To re-use some examples posted here.
This piece of code could be re-written without using static
initialiser.
Method #1: With static
private static final HashMap<String, String> MAP;
static {
MAP.put("banana", "honey");
MAP.put("peanut butter", "jelly");
MAP.put("rice", "beans");
}
Method #2: Without static
private static final HashMap<String, String> MAP = getMap();
private static HashMap<String, String> getMap()
{
HashMap<String, String> ret = new HashMap<>();
ret.put("banana", "honey");
ret.put("peanut butter", "jelly");
ret.put("rice", "beans");
return ret;
}
Here you can access "set2" property following:
var obj = {
"set1": [1, 2, 3],
"set2": [4, 5, 6, 7, 8],
"set3": [9, 10, 11, 12]
};
var output = Object.keys(obj)[1];
Object.keys return all the keys of provided object as Array..
I got stumped here a bit. Wanted to package some resource files into a wheel file and access them. Did the packaging using manifest file, but pip install was not installing it unless it was a sub directory. Hoping these sceen shots will help
+-- cnn_client
¦ +-- image_preprocessor.py
¦ +-- __init__.py
¦ +-- resources
¦ ¦ +-- mscoco_complete_label_map.pbtxt
¦ ¦ +-- retinanet_complete_label_map.pbtxt
¦ ¦ +-- retinanet_label_map.py
¦ +-- tf_client.py
MANIFEST.in
recursive-include cnn_client/resources *
Created a weel using standard setup.py . pip installed the wheel file. After installation checked if resources are installed. They are
ls /usr/local/lib/python2.7/dist-packages/cnn_client/resources
mscoco_complete_label_map.pbtxt
retinanet_complete_label_map.pbtxt
retinanet_label_map.py
In tfclient.py to access these files. from
templates_dir = os.path.join(os.path.dirname(__file__), 'resources')
file_path = os.path.join(templates_dir, \
'mscoco_complete_label_map.pbtxt')
s = open(file_path, 'r').read()
And it works.
According to @Shovalt's answer, but in short:
Alternatively you could use the following lines of code
from sklearn.metrics import f1_score
metrics.f1_score(y_test, y_pred, labels=np.unique(y_pred))
This should remove your warning and give you the result you wanted, because it no longer considers the difference between the sets, by using the unique mode.
@Inject
instead of Spring’s @Autowired
to inject a bean.
@Named
instead of Spring’s @Component
to declare a bean.
Those JSR-330 standard annotations are scanned and retrieved the same way as Spring annotation (as long as the following jar
is in your classpath)
Useful tip - if you use __FILE__
and __LINE__
then format your debug as:
"file(line): Your output here"
then when you click on that line in the output window Visual Studio will jump directly to that line of code. An example:
#include <Windows.h>
#include <iostream>
#include <sstream>
void DBOut(const char *file, const int line, const WCHAR *s)
{
std::wostringstream os_;
os_ << file << "(" << line << "): ";
os_ << s;
OutputDebugStringW(os_.str().c_str());
}
#define DBOUT(s) DBOut(__FILE__, __LINE__, s)
I wrote a blog post about this so I always knew where I could look it up: https://windowscecleaner.blogspot.co.nz/2013/04/debug-output-tricks-for-visual-studio.html
Jquery.min.js is nothing else but compressed version of jquery.js. You can use it the same way as jquery.js, but it's smaller, so in production you should use minified version and when you're debugging you can use normal jquery.js version. If you want to compress your own javascript file you can these compressors:
Or just read topis on StackOverflow about js compression :) :
The jQuery docs say to use prop() for things like disabled, checked, etc. Also the more concise way is to use their selectors engine. So to disable all form elements in a div or form parent.
$myForm.find(':input:not(:disabled)').prop('disabled',true);
And to enable again you could do
$myForm.find(':input:disabled').prop('disabled',false);
If you want to know the user version in your code, then you can use using app()
helper function
app()->version();
It is defined in this file ../src/Illuminate/Foundation/Application.php
Hope it will help :)
If you're on a shared hosting environment you won't have access to the php.ini to make these changes, if you need access, a virtual private server (VPS) or a dedicated server may be a better option if you're confident in managing it yourself.
Alternatively if you create a new file called .htaccess in your root of your web directory (Ensure it doesn't contain a .txt extension if using notepad to create the file) and copy something like this inside.
php_value settingToChange 6000
This will only work if your hosting provider let's you override the certain config value. Best to ask if it doesn't work after trying.
Since I have been doing a bit of research in that field lately (Jan, '12), the most promising client is actually : WebSocket for Python. It support a normal socket that you can call like this :
ws = EchoClient('http://localhost:9000/ws')
The client
can be Threaded
or based on IOLoop
from Tornado project. This will allow you to create a multi concurrent connection client. Useful if you want to run stress tests.
The client also exposes the onmessage
, opened
and closed
methods. (WebSocket style).
Just remove the break. since it is already inside first if it will not execute else. It will exit anyway.
static
renders variable local to the file which is generally a good thing, see for example this Wikipedia entry.
There is a simple why that I prefered to the bundle due to the no duplicate data in memory. It consists of a init public method for the fragment
private ArrayList<Music> listMusics = new ArrayList<Music>();
private ListView listMusic;
public static ListMusicFragment createInstance(List<Music> music) {
ListMusicFragment fragment = new ListMusicFragment();
fragment.init(music);
return fragment;
}
public void init(List<Music> music){
this.listMusic = music;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.musiclistview, container, false);
listMusic = (ListView) view.findViewById(R.id.musicListView);
listMusic.setAdapter(new MusicBaseAdapter(getActivity(), listMusics));
return view;
}
}
In two words, you create an instance of the fragment an by the init method (u can call it as u want) you pass the reference of your list without create a copy by serialization to the instance of the fragment. This is very usefull because if you change something in the list u will get it in the other parts of the app and ofcourse, you use less memory.
**EDITED for Swift 4.2:
As @Koen commented, swift 4.2 allows:
guard let self = self else {
return // Could not get a strong reference for self :`(
}
// Now self is a strong reference
self.doSomething()
P.S.: Since I am having some up-votes, I would like to recommend the reading about escaping closures.
EDITED: As @tim-vermeulen has commented, Chris Lattner said on Fri Jan 22 19:51:29 CST 2016, this trick should not be used on self, so please don't use it. Check the non escaping closures info and the capture list answer from @gbk.**
For those who use [weak self] in capture list, note that self could be nil, so the first thing I do is check that with a guard statement
guard let `self` = self else {
return
}
self.doSomething()
If you are wondering what the quote marks are around self
is a pro trick to use self inside the closure without needing to change the name to this, weakSelf or whatever.
Precision, Scale, and Length in the SQL Server 2000 documentation reads:
Precision is the number of digits in a number. Scale is the number of digits to the right of the decimal point in a number. For example, the number 123.45 has a precision of 5 and a scale of 2.
Yes. You can throw anything you want: integers, strings, objects, whatever. If you want to throw an object, then simply create a new object, just as you would create one under other circumstances, and then throw it. Mozilla's Javascript reference has several examples.
Real power comes with understanding and implementation membership provider together with role provider. You can assign users into roles and according to that restriction you can apply different access roles for different user to controller actions or controller itself.
[Authorize(Users = "Betty, Johnny")]
public ActionResult SpecificUserOnly()
{
return View();
}
or you can restrict according to group
[Authorize(Roles = "Admin, Super User")]
public ActionResult AdministratorsOnly()
{
return View();
}
What you need is a datetime which is 30 minutes later than your given datetime, and a datetime which is 30 minutes before a given datetime. In other words, you need a future datetime and a past datetime. Hence, classes that achieve that are called Future
and Past
. What data do they need to calculate what you need? Apparently, they must have a datetime relative to which to count those 30 minutes, and an interval itself -- 30 minutes in your case. Thus, the desired datetime looks like the following:
use Meringue\ISO8601DateTime\FromCustomFormat as DateTimeCreatedFromCustomFormat;
(new Future(
new DateTimeCreatedFromCustomFormat('H:i', '10:00'),
new NMinutes(30)
))
->value();
If you want to format it somehow, you can do:
use Meringue\ISO8601DateTime\FromCustomFormat as DateTimeCreatedFromCustomFormat;
(new ISO8601Formatted(
new Future(
new DateTimeCreatedFromCustomFormat('H:i', '10:00'),
new NMinutes(30)
),
'H:i'
))
->value();
It's more verbose, but I guess it's way less cryptic than built-in php functions.
If you liked this approach, you can learn some more about the meringue library used in this example, and the overall approach.
I just had the same problem. It is not a network permission but rather thread issue. Below code helped me to solve it. Put is in main activity
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
First add the new column to the old table through SSMStudio. Go to the database >> table >> columns. Right click on columns and choose new column. Follow the wizard. Then create the new table with the columns ordered as desired as follows:
select * into my_new_table from (
select old_col1, my_new_col, old_col2, old_col3
from my_old_table
) as A
;
Then rename the tables as desired through SSMStudio. Go to the database >> table >> choose rename.
The document looks fine to me but I suspect that it contains invisible characters. Open it in a hex editor to check that there really isn't anything before the very first "<". Make sure the spaces in the XML header are spaces. Maybe delete the space before "?>". Check which line breaks are used.
Make sure the document is proper UTF-8. Some windows editors save the document as UTF-16 (i.e. every second byte is 0).
I needed to break some text into paragraphs ("p" tags), so I created a simple helper using some of the recommendations in previous answers (thank you guys).
public static MvcHtmlString ToParagraphs(this HtmlHelper html, string value)
{
value = html.Encode(value).Replace("\r", String.Empty);
var arr = value.Split('\n').Where(a => a.Trim() != string.Empty);
var htmlStr = "<p>" + String.Join("</p><p>", arr) + "</p>";
return MvcHtmlString.Create(htmlStr);
}
Usage:
@Html.ToParagraphs(Model.Comments)
From linux/typecheck.h:
/*
* Check at compile time that something is of a particular type.
* Always evaluates to 1 so you may use it easily in comparisons.
*/
#define typecheck(type,x) \
({ type __dummy; \
typeof(x) __dummy2; \
(void)(&__dummy == &__dummy2); \
1; \
})
Here you can find explanation which statements from standard and which GNU extensions above code uses.
(Maybe a bit not in scope of the question, since question is not about failure on type mismatch, but anyway, leaving it here).
In Tomcat 8.0.44 I did this: create the JNDI on Tomcat's server.xml between the tag "GlobalNamingResources" For example:
<GlobalNamingResources>_x000D_
<!-- Editable user database that can also be used by_x000D_
UserDatabaseRealm to authenticate users_x000D_
-->_x000D_
<!-- Other previus resouces -->_x000D_
<Resource auth="Container" driverClassName="org.postgresql.Driver" global="jdbc/your_jndi" _x000D_
maxActive="100" maxIdle="20" maxWait="1000" minIdle="5" name="jdbc/your_jndi" password="your_password" _x000D_
type="javax.sql.DataSource" url="jdbc:postgresql://localhost:5432/your_database?user=postgres" username="database_username"/>_x000D_
</GlobalNamingResources>
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<Context reloadable="true" >_x000D_
<ResourceLink name="jdbc/your_jndi"_x000D_
global="jdbc/your_jndi"_x000D_
auth="Container"_x000D_
type="javax.sql.DataSource" />_x000D_
</Context>
_x000D_
So if you're using Hiberte with spring you can tell to him to use the JNDI in your persistence.xml
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"_x000D_
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">_x000D_
<persistence-unit name="UNIT_NAME" transaction-type="RESOURCE_LOCAL">_x000D_
<provider>org.hibernate.ejb.HibernatePersistence</provider>_x000D_
_x000D_
<properties>_x000D_
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />_x000D_
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect" />_x000D_
_x000D_
<!-- <property name="hibernate.jdbc.time_zone" value="UTC"/>-->_x000D_
<property name="hibernate.hbm2ddl.auto" value="update" />_x000D_
<property name="hibernate.show_sql" value="false" />_x000D_
<property name="hibernate.format_sql" value="true"/> _x000D_
</properties>_x000D_
</persistence-unit>_x000D_
</persistence>
_x000D_
So in your spring.xml you can do that:
<bean id="postGresDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">_x000D_
<property name="jndiName" value="java:comp/env/jdbc/your_jndi" />_x000D_
</bean>_x000D_
_x000D_
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">_x000D_
<property name="persistenceUnitName" value="UNIT_NAME" />_x000D_
<property name="dataSource" ref="postGresDataSource" />_x000D_
<property name="jpaVendorAdapter"> _x000D_
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />_x000D_
</property>_x000D_
</bean>
_x000D_
<property name="jndiName" value="java:comp/env/jdbc/your_jndi" />
_x000D_
In this example I used spring with xml but you can do this programmaticaly if you prefer.
That's it, I hope helped.
Make sure that your .gitignore
is in the root of the working directory, and in that directory run git status
and copy the path to the file from the status output and paste it into the .gitignore
.
If that doesn’t work, then it’s likely that your file is already tracked by Git. You can confirm this through the output of git status
. If the file is not listed in the “Untracked files” section, then it is already tracked by Git and it will ignore the rule from the .gitignore
file.
The reason to ignore files in Git is so that they won't be added to the repository. If you previously added a file you want to be ignored, then it will be tracked by Git and the ignore rules matching it will be skipped. Git does this since the file is already part of the repository.
In order to actually ignore the file, you have to untrack it and remove it from the repository. You can do that by using git rm --cached sites/default/settings.php
. This removes the file from the repository without physically deleting the file (that’s what the --cached
does). After committing that change, the file will be removed from the repository, and ignoring it should work properly.
Nope, it is more complicated than just calling a method, if you want to transparently add it into the user's calendar.
You've got a couple of choices;
Calling the intent to add an event on the calendar
This will pop up the Calendar application and let the user add the event. You can pass some parameters to prepopulate fields:
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", false);
intent.putExtra("rrule", "FREQ=DAILY");
intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
intent.putExtra("title", "A Test Event from android app");
startActivity(intent);
Or the more complicated one:
Get a reference to the calendar with this method
(It is highly recommended not to use this method, because it could break on newer Android versions):
private String getCalendarUriBase(Activity act) {
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://calendar/";
} else {
calendars = Uri.parse("content://com.android.calendar/calendars");
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://com.android.calendar/";
}
}
return calendarUriBase;
}
and add an event and a reminder this way:
// get calendar
Calendar cal = Calendar.getInstance();
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events");
ContentResolver cr = getContentResolver();
// event insert
ContentValues values = new ContentValues();
values.put("calendar_id", 1);
values.put("title", "Reminder Title");
values.put("allDay", 0);
values.put("dtstart", cal.getTimeInMillis() + 11*60*1000); // event starts at 11 minutes from now
values.put("dtend", cal.getTimeInMillis()+60*60*1000); // ends 60 minutes from now
values.put("description", "Reminder description");
values.put("visibility", 0);
values.put("hasAlarm", 1);
Uri event = cr.insert(EVENTS_URI, values);
// reminder insert
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
values = new ContentValues();
values.put( "event_id", Long.parseLong(event.getLastPathSegment()));
values.put( "method", 1 );
values.put( "minutes", 10 );
cr.insert( REMINDERS_URI, values );
You'll also need to add these permissions to your manifest for this method:
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
Update: ICS Issues
The above examples use the undocumented Calendar APIs, new public Calendar APIs have been released for ICS, so for this reason, to target new android versions you should use CalendarContract.
More infos about this can be found at this blog post.
At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on window.onload
maybe. Something like this:
<html>
<head>
<title></title>
<script type="text/javascript">
window.onload = function(){
var refButton = document.getElementById("btnButton");
refButton.onclick = function() {
alert('I am clicked!');
}
};
</script>
</head>
<body>
<form id="form1">
<div>
<input id="btnButton" type="button" value="Click me"/>
</div>
</form>
</body>
</html>
You can use the jQuery load function:
<div id="topBar">
<a href ="#" id="load_home"> HOME </a>
</div>
<div id ="content">
</div>
<script>
$(document).ready( function() {
$("#load_home").on("click", function() {
$("#content").load("content.html");
});
});
</script>
Sorry. Edited for the on click instead of on load.
Pyparsing can be used to parse mathematical expressions. In particular, fourFn.py shows how to parse basic arithmetic expressions. Below, I've rewrapped fourFn into a numeric parser class for easier reuse.
from __future__ import division
from pyparsing import (Literal, CaselessLiteral, Word, Combine, Group, Optional,
ZeroOrMore, Forward, nums, alphas, oneOf)
import math
import operator
__author__ = 'Paul McGuire'
__version__ = '$Revision: 0.0 $'
__date__ = '$Date: 2009-03-20 $'
__source__ = '''http://pyparsing.wikispaces.com/file/view/fourFn.py
http://pyparsing.wikispaces.com/message/view/home/15549426
'''
__note__ = '''
All I've done is rewrap Paul McGuire's fourFn.py as a class, so I can use it
more easily in other places.
'''
class NumericStringParser(object):
'''
Most of this code comes from the fourFn.py pyparsing example
'''
def pushFirst(self, strg, loc, toks):
self.exprStack.append(toks[0])
def pushUMinus(self, strg, loc, toks):
if toks and toks[0] == '-':
self.exprStack.append('unary -')
def __init__(self):
"""
expop :: '^'
multop :: '*' | '/'
addop :: '+' | '-'
integer :: ['+' | '-'] '0'..'9'+
atom :: PI | E | real | fn '(' expr ')' | '(' expr ')'
factor :: atom [ expop factor ]*
term :: factor [ multop factor ]*
expr :: term [ addop term ]*
"""
point = Literal(".")
e = CaselessLiteral("E")
fnumber = Combine(Word("+-" + nums, nums) +
Optional(point + Optional(Word(nums))) +
Optional(e + Word("+-" + nums, nums)))
ident = Word(alphas, alphas + nums + "_$")
plus = Literal("+")
minus = Literal("-")
mult = Literal("*")
div = Literal("/")
lpar = Literal("(").suppress()
rpar = Literal(")").suppress()
addop = plus | minus
multop = mult | div
expop = Literal("^")
pi = CaselessLiteral("PI")
expr = Forward()
atom = ((Optional(oneOf("- +")) +
(ident + lpar + expr + rpar | pi | e | fnumber).setParseAction(self.pushFirst))
| Optional(oneOf("- +")) + Group(lpar + expr + rpar)
).setParseAction(self.pushUMinus)
# by defining exponentiation as "atom [ ^ factor ]..." instead of
# "atom [ ^ atom ]...", we get right-to-left exponents, instead of left-to-right
# that is, 2^3^2 = 2^(3^2), not (2^3)^2.
factor = Forward()
factor << atom + \
ZeroOrMore((expop + factor).setParseAction(self.pushFirst))
term = factor + \
ZeroOrMore((multop + factor).setParseAction(self.pushFirst))
expr << term + \
ZeroOrMore((addop + term).setParseAction(self.pushFirst))
# addop_term = ( addop + term ).setParseAction( self.pushFirst )
# general_term = term + ZeroOrMore( addop_term ) | OneOrMore( addop_term)
# expr << general_term
self.bnf = expr
# map operator symbols to corresponding arithmetic operations
epsilon = 1e-12
self.opn = {"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv,
"^": operator.pow}
self.fn = {"sin": math.sin,
"cos": math.cos,
"tan": math.tan,
"exp": math.exp,
"abs": abs,
"trunc": lambda a: int(a),
"round": round,
"sgn": lambda a: abs(a) > epsilon and cmp(a, 0) or 0}
def evaluateStack(self, s):
op = s.pop()
if op == 'unary -':
return -self.evaluateStack(s)
if op in "+-*/^":
op2 = self.evaluateStack(s)
op1 = self.evaluateStack(s)
return self.opn[op](op1, op2)
elif op == "PI":
return math.pi # 3.1415926535
elif op == "E":
return math.e # 2.718281828
elif op in self.fn:
return self.fn[op](self.evaluateStack(s))
elif op[0].isalpha():
return 0
else:
return float(op)
def eval(self, num_string, parseAll=True):
self.exprStack = []
results = self.bnf.parseString(num_string, parseAll)
val = self.evaluateStack(self.exprStack[:])
return val
You can use it like this
nsp = NumericStringParser()
result = nsp.eval('2^4')
print(result)
# 16.0
result = nsp.eval('exp(2^4)')
print(result)
# 8886110.520507872
Same package error:
First globally declare
Context mContext;
pass context with the constructor, by modifying it.
public FeedAdapter(List<Post> myDataset, Context context) {
mDataset = myDataset;
this.mContext = context;
}
then use the mContext
whereever you need it
The difference between the two is really simple!.
<context:annotation-config />
Enables you to use annotations that are restricted to wiring up properties and constructors only of beans!.
Where as
<context:component-scan base-package="org.package"/>
Enables everything that <context:annotation-config />
can do, with addition of using stereotypes eg.. @Component
, @Service
, @Repository
. So you can wire entire beans and not just restricted to constructors or properties!.
I can import with this command
docker-compose exec -T mysql mysql -uroot -proot mydatabase < ~/Desktop/mydatabase_2019-10-05.sql
The first answer was great, but I had to add try/catch to avoid Java compiler errors.
Also, I had troubles to figure how to read the HttpResponse
with Java libraries.
Here is the more complete code :
/*
* Create the POST request
*/
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Bob"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
/*
* Execute the HTTP Request
*/
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity respEntity = response.getEntity();
if (respEntity != null) {
// EntityUtils to get the response content
String content = EntityUtils.toString(respEntity);
}
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
While you use .on(), it's basically a live query that you are using.
On the other hand, .ready (as in your case) is a static query. While using it, you can dynamically update data and do not have to wait for the page to load. You can simply pass on the values into your database (if required) when a particular value is entered.
The use of live queries is common in forms where we enter data (account or posts or even comments).
What worked for me was to import the project with "File -> New -> Project from Version Control" then choose your online source (GitHub for example). This way all the .gradle files were created in the import.
From JDK 14+ which includes JEP 305 we can do Pattern Matching for instanceof
Patterns basically test that a value has a certain type, and can extract information from the value when it has the matching type.
Before Java 14
if (obj instanceof String) {
String str = (String) obj; // need to declare and cast again the object
.. str.contains(..) ..
}else{
str = ....
}
Java 14 enhancements
if (!(obj instanceof String str)) {
.. str.contains(..) .. // no need to declare str object again with casting
} else {
.. str....
}
We can also combine the type check and other conditions together
if (obj instanceof String str && str.length() > 4) {.. str.contains(..) ..}
The use of pattern matching in instanceof
should reduce the overall number of explicit casts in Java programs.
PS: instanceOf
will only match when the object is not null, then only it can be assigned to str
.
If you're using SQL Server, you can set the value of bit fields with 0 and 1
or
'true' and 'false'
(yes, using strings)
...your_bit_field='false'... => equivalent to 0
For those looking for the SSMS 2012 solution... see this answer:
Essentially, in 2012 you can delete the server from the server list dropdown which clears all cached logins for that server.
Works also in v17 (build 14.x).
You can set the color of a JLabel by altering the foreground category:
JLabel title = new JLabel("I love stackoverflow!", JLabel.CENTER);
title.setForeground(Color.white);
As far as I know, the simplest way to create the two-color label you want is to simply make two labels, and make sure they get placed next to each other in the proper order.
With Git 2.23 (August 2019), that would be, using git switch -f
:
git switch -f master
That avoids the confusion with git checkout
(which deals with files or branches).
And that will proceeds, even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
If --recurse-submodules
is specified, submodule content is also restored to match the switching target.
This is used to throw away local changes.
I like this naming style:
OrdersShouldBeCreated();
OrdersWithNoProductsShouldFail();
and so on. It makes really clear to a non-tester what the problem is.
Either you set LDAP_DOMAIN variable or you misconfigured it. Jump inside of ldap machine/container and run:
slapcat > backup.ldif
If it fails, check punctuation, quotes etc while you assigned variable "LDAP_DOMAIN" Otherwise you will find answer inside on backup.ldif file.
If you just want to round the number for output purposes, then the "%.2f"
format string is indeed the correct answer. However, if you actually want to round the floating point value for further computation, something like the following works:
#include <math.h>
float val = 37.777779;
float rounded_down = floorf(val * 100) / 100; /* Result: 37.77 */
float nearest = roundf(val * 100) / 100; /* Result: 37.78 */
float rounded_up = ceilf(val * 100) / 100; /* Result: 37.78 */
Notice that there are three different rounding rules you might want to choose: round down (ie, truncate after two decimal places), rounded to nearest, and round up. Usually, you want round to nearest.
As several others have pointed out, due to the quirks of floating point representation, these rounded values may not be exactly the "obvious" decimal values, but they will be very very close.
For much (much!) more information on rounding, and especially on tie-breaking rules for rounding to nearest, see the Wikipedia article on Rounding.
Reflection is pretty "heavy"
Perhaps try this solution:
C#
if (item is IEnumerable) {
foreach (object o in item as IEnumerable) {
//do function
}
} else {
foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties()) {
if (p.CanRead) {
Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, null)); //possible function
}
}
}
VB.Net
If TypeOf item Is IEnumerable Then
For Each o As Object In TryCast(item, IEnumerable)
'Do Function
Next
Else
For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()
If p.CanRead Then
Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, Nothing)) 'possible function
End If
Next
End If
Reflection slows down +/- 1000 x the speed of a method call, shown in The Performance of Everyday Things
Hope this helps: http://nrecursions.blogspot.in/2014/02/how-to-trigger-jenkins-build-on-git.html
It's just a matter of using curl
to trigger a Jenkins job using the git hooks provided by git.
The command
curl http://localhost:8080/job/someJob/build?delay=0sec
can run a Jenkins job, where someJob
is the name of the Jenkins job.
Search for the hooks
folder in your hidden .git folder. Rename the post-commit.sample
file to post-commit
. Open it with Notepad, remove the : Nothing
line and paste the above command into it.
That's it. Whenever you do a commit, Git will trigger the post-commit commands defined in the file.
I always use this:
function validEmail($email){
// First, we check that there's one @ symbol, and that the lengths are right
if (!preg_match("/^[^@]{1,64}@[^@]{1,255}$/", $email)) {
// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("@", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
return false;
}
}
if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
return false;
}
}
}
return true;
}
The below code helps, if you use Gradle. Allows you to easily remove unneeded Google services (presuming you're using them) to get back below the 65k threshold. All credit to this post: https://gist.github.com/dmarcato/d7c91b94214acd936e42
Edit 2014-10-22: There's been a lot of interesting discussion on the gist referenced above. TLDR? look at this one: https://gist.github.com/Takhion/10a37046b9e6d259bb31
Paste this code at the bottom of your build.gradle file and adjust the list of google services you do not need:
def toCamelCase(String string) {
String result = ""
string.findAll("[^\\W]+") { String word ->
result += word.capitalize()
}
return result
}
afterEvaluate { project ->
Configuration runtimeConfiguration = project.configurations.getByName('compile')
ResolutionResult resolution = runtimeConfiguration.incoming.resolutionResult
// Forces resolve of configuration
ModuleVersionIdentifier module = resolution.getAllComponents().find { it.moduleVersion.name.equals("play-services") }.moduleVersion
String prepareTaskName = "prepare${toCamelCase("${module.group} ${module.name} ${module.version}")}Library"
File playServiceRootFolder = project.tasks.find { it.name.equals(prepareTaskName) }.explodedDir
Task stripPlayServices = project.tasks.create(name: 'stripPlayServices', group: "Strip") {
inputs.files new File(playServiceRootFolder, "classes.jar")
outputs.dir playServiceRootFolder
description 'Strip useless packages from Google Play Services library to avoid reaching dex limit'
doLast {
copy {
from(file(new File(playServiceRootFolder, "classes.jar")))
into(file(playServiceRootFolder))
rename { fileName ->
fileName = "classes_orig.jar"
}
}
tasks.create(name: "stripPlayServices" + module.version, type: Jar) {
destinationDir = playServiceRootFolder
archiveName = "classes.jar"
from(zipTree(new File(playServiceRootFolder, "classes_orig.jar"))) {
exclude "com/google/ads/**"
exclude "com/google/android/gms/analytics/**"
exclude "com/google/android/gms/games/**"
exclude "com/google/android/gms/plus/**"
exclude "com/google/android/gms/drive/**"
exclude "com/google/android/gms/ads/**"
}
}.execute()
delete file(new File(playServiceRootFolder, "classes_orig.jar"))
}
}
project.tasks.findAll { it.name.startsWith('prepare') && it.name.endsWith('Dependencies') }.each { Task task ->
task.dependsOn stripPlayServices
}
}
Actually, the simplest way to manipulate this is to
And then the URL www.yoursite.com/data will read that index.php file. If you want to take it further, open a subfolder (e.g. "List") in it, put another index.php in that folder and you can have www.yoursite.com/data/list run that PHP file.
This way you can have full control over this, very useful for SEO.
As a matter of fact, if unsuccessful after following suggestions by marc_s, please keep in mind that a <security> element in server binding configuration (or lack thereof) in web.config on the server may cause this exception. For instance the server is expecting Message
-level security and client is configured to None
(or, if the server is not part of an Active Directory domain but the remote client host is).
Tip: In such cases the client app will most likely invoke the web service fine when executed directly on the server machine under administrative account in RDP session.
I had this same problem and solved it by adding an event handler for the play action in addition to the click action. I hide the controls while playing to avoid the pause button issue.
var v = document.getElementById('videoID');
v.addEventListener(
'play',
function() {
v.play();
},
false);
v.onclick = function() {
if (v.paused) {
v.play();
v.controls=null;
} else {
v.pause();
v.controls="controls";
}
};
Seeking still acts funny though, but at least the confusion with the play control is gone. Hope this helps.
Anyone have a solution to that?
sed -i 's/[^[:print:]]//' FILENAME
Also, this acts like dos2unix
Properties prop = new Properties();
prop.load(...); // FileInputStream
prop.setProperty("key", "value");
prop.store(...); // FileOutputStream
The simple way to do that is to use git format-patch.
Assume we have 2 git repositories foo and bar.
foo contains:
bar contains:
and we want to end-up with foo containing the bar history and these files:
So to do that:
1. create a temporary directory eg PATH_YOU_WANT/patch-bar
2. go in bar directory
3. git format-patch --root HEAD --no-stat -o PATH_YOU_WANT/patch-bar --src-prefix=a/foobar/ --dst-prefix=b/foobar/
4. go in foo directory
5. git am PATH_YOU_WANT/patch-bar/*
And if we want to rewrite all message commits from bar we can do, eg on Linux:
git filter-branch --msg-filter 'sed "1s/^/\[bar\] /"' COMMIT_SHA1_OF_THE_PARENT_OF_THE_FIRST_BAR_COMMIT..HEAD
This will add "[bar] " at the beginning of each commit message.
select * from table
where DATEADD(ms, DATEDIFF(ms, '20000101', date), '20000101') > '2010-07-20 03:21:52'
You'll have to trim milliseconds before comparison, which will be slow over many rows
Do one of these to fix this:
datetime2(0)
The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval()
and Bind()
, taking advantage of the strongly-typed bindings.
*Note: this will only work if you're not using a SqlDataSource
or an anonymous object
. It requires a Strongly-typed object (from an EF model or any other class).
This code snippet shows how Eval
and Bind
would be used for a ListView
control (InsertItem
needs Bind
, as explained by Darin Dimitrov above, and ItemTemplate
is read-only (hence they're labels), so just needs an Eval
):
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
<InsertItemTemplate>
<li>
Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />
Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />
<asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />
</li>
</InsertItemTemplate>
<ItemTemplate>
<li>
Title: <asp:Label ID="Title" runat="server" Text='<%# Eval("Title") %>' /><br />
Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />
<asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
</li>
</ItemTemplate>
From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType
, which points to the type of object you're assigning to its data source.
<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>
Picture
is the strongly type object (from EF model). We then replace:
Bind(property) -> BindItem.property
Eval(property) -> Item.property
So this:
<%# Bind("Title") %>
<%# Bind("Description") %>
<%# Eval("Title") %>
<%# Eval("Description") %>
Would become this:
<%# BindItem.Title %>
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>
Advantages over Eval & Bind:
Source: from this excellent book
You might want want to rethink the structure of you application, if you really, really want one method to return multiple values.
Either break things apart, so distinct methods return distinct values, or figure out a logical grouping and build an object to hold that data that can in turn be returned.
' this is the VB6/VBA equivalent of a struct
' data, no methods
Private Type settings
root As String
path As String
name_first As String
name_last As String
overwrite_prompt As Boolean
End Type
Public Sub Main()
Dim mySettings As settings
mySettings = getSettings()
End Sub
' if you want this to be public, you're better off with a class instead of a User-Defined-Type (UDT)
Private Function getSettings() As settings
Dim sets As settings
With sets ' retrieve values here
.root = "foo"
.path = "bar"
.name_first = "Don"
.name_last = "Knuth"
.overwrite_prompt = False
End With
' return a single struct, vb6/vba-style
getSettings = sets
End Function
In the "Welcome to Android Studio" opening dialog you can highlight the app you want to remove from Android Studio and hit delete on your keyboard.
You need to make sure that the clocks on all your servers are correct. Kerberos errors are normally caused by your server clock being out of sync with your domain.
UPDATE
Failure code 0x12 very specifically means "Clients credentials have been revoked", which means that this error has happened once the account has been disabled, expired, or locked out.
It would be useful to try and find the previous error messages if you think that the account was active - i.e. this error message may not be the root cause, you will have different errors preceding this error, which cause the account to get locked.
Ideally, to get a full answer, you will need to reactivate the account and keep an eye on the logs for an error occurring before the 0x12 error messages.
I found this image most helpful for understanding frame, bounds, etc.
Also please note that frame.size != bounds.size
when the image is rotated.
No.
A developer is responsible for keeping track of time-zone information associated with a DateTime value via some external mechanism.
A quote from an excellent article here. A must read for every .Net developer.
So my advice is to write a little wrapper class that suits your needs.
SQL Server and the .NET Framework are based on different type systems. For example, the .NET Framework Decimal structure has a maximum scale of 28, whereas the SQL Server decimal and numeric data types have a maximum scale of 38. Click Here's a link! for detail
https://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx
I've used bundle update --source
myself for a long time but there are scenarios where it doesn't work. Luckily, there's a gem called bundler-patch
which has the goal of fixing this shortcoming.
I also wrote a short blog post about how to use bundler-patch
and why bundle update --source
doesn't work consistently. Also, be sure to check out a post by chrismo that explains in great detail what the --source
option does.
I have just published to npm a micro-library called sort-helper (source on github). The idea is to import the helper by
to create the comparison function for sort
array method through the syntax items.sort(by(column, ...otherColumns))
, with several way to express the columns to sort by:
persons.sort(by('lastName', 'firstName'))
,dates.sort(by(x => x.toISOString()))
,[3, 2, 4, 1].sort(by(desc(n => n)))
? [3, 2, 1, 0]
,['B', 'D', 'c', 'a'].sort(by(ignoreCase(x => x))).join('')
? 'aBcD'
.It's similar to the nice thenBy mentioned in this answer but with the following differences that may be more to the taste of some:
thenBy
fluent API),I got this error when using pinvoke on a method that takes a reference to a StringBuilder
. I had used the default constructor which apparently only allocates 16 bytes. Windows tried to put more than 16 bytes in the buffer and caused a buffer overrun.
Instead of
StringBuilder windowText = new StringBuilder(); // Probable overflow of default capacity (16)
Use a larger capacity:
StringBuilder windowText = new StringBuilder(3000);
You have some syntax issues with your script. Here is a fixed version:
#!/bin/bash
if [ "$seconds" -eq 0 ]; then
timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
echo "Unknown parameter"
fi
Response you are getting is in object form i.e.
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
Replace below line of code :
List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))
with
Post post = gson.fromJson(reader, Post.class);
function truncate ($str, $length) {
if (strlen($str) > $length) {
$str = substr($str, 0, $length+1);
$pos = strrpos($str, ' ');
$str = substr($str, 0, ($pos > 0)? $pos : $length);
}
return $str;
}
Example:
print truncate('The first step to eternal life is you have to die.', 25);
string(25) "The first step to eternal"
print truncate('The first step to eternal life is you have to die.', 12);
string(9) "The first"
print truncate('FirstStepToEternalLife', 5);
string(5) "First"
You create __main__.py
in yourpackage
to make it executable as:
$ python -m yourpackage
Here is a working version of the "build defs". This is similar to my previous answer but I figured out the build month. (You just can't compute build month in a #if
statement, but you can use a ternary expression that will be compiled down to a constant.)
Also, according to the documentation, if the compiler cannot get the time of day it will give you question marks for these strings. So I added tests for this case, and made the various macros return an obviously wrong value (99) if this happens.
#ifndef BUILD_DEFS_H
#define BUILD_DEFS_H
// Example of __DATE__ string: "Jul 27 2012"
// Example of __TIME__ string: "21:06:19"
#define COMPUTE_BUILD_YEAR \
( \
(__DATE__[ 7] - '0') * 1000 + \
(__DATE__[ 8] - '0') * 100 + \
(__DATE__[ 9] - '0') * 10 + \
(__DATE__[10] - '0') \
)
#define COMPUTE_BUILD_DAY \
( \
((__DATE__[4] >= '0') ? (__DATE__[4] - '0') * 10 : 0) + \
(__DATE__[5] - '0') \
)
#define BUILD_MONTH_IS_JAN (__DATE__[0] == 'J' && __DATE__[1] == 'a' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_FEB (__DATE__[0] == 'F')
#define BUILD_MONTH_IS_MAR (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'r')
#define BUILD_MONTH_IS_APR (__DATE__[0] == 'A' && __DATE__[1] == 'p')
#define BUILD_MONTH_IS_MAY (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'y')
#define BUILD_MONTH_IS_JUN (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_JUL (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'l')
#define BUILD_MONTH_IS_AUG (__DATE__[0] == 'A' && __DATE__[1] == 'u')
#define BUILD_MONTH_IS_SEP (__DATE__[0] == 'S')
#define BUILD_MONTH_IS_OCT (__DATE__[0] == 'O')
#define BUILD_MONTH_IS_NOV (__DATE__[0] == 'N')
#define BUILD_MONTH_IS_DEC (__DATE__[0] == 'D')
#define COMPUTE_BUILD_MONTH \
( \
(BUILD_MONTH_IS_JAN) ? 1 : \
(BUILD_MONTH_IS_FEB) ? 2 : \
(BUILD_MONTH_IS_MAR) ? 3 : \
(BUILD_MONTH_IS_APR) ? 4 : \
(BUILD_MONTH_IS_MAY) ? 5 : \
(BUILD_MONTH_IS_JUN) ? 6 : \
(BUILD_MONTH_IS_JUL) ? 7 : \
(BUILD_MONTH_IS_AUG) ? 8 : \
(BUILD_MONTH_IS_SEP) ? 9 : \
(BUILD_MONTH_IS_OCT) ? 10 : \
(BUILD_MONTH_IS_NOV) ? 11 : \
(BUILD_MONTH_IS_DEC) ? 12 : \
/* error default */ 99 \
)
#define COMPUTE_BUILD_HOUR ((__TIME__[0] - '0') * 10 + __TIME__[1] - '0')
#define COMPUTE_BUILD_MIN ((__TIME__[3] - '0') * 10 + __TIME__[4] - '0')
#define COMPUTE_BUILD_SEC ((__TIME__[6] - '0') * 10 + __TIME__[7] - '0')
#define BUILD_DATE_IS_BAD (__DATE__[0] == '?')
#define BUILD_YEAR ((BUILD_DATE_IS_BAD) ? 99 : COMPUTE_BUILD_YEAR)
#define BUILD_MONTH ((BUILD_DATE_IS_BAD) ? 99 : COMPUTE_BUILD_MONTH)
#define BUILD_DAY ((BUILD_DATE_IS_BAD) ? 99 : COMPUTE_BUILD_DAY)
#define BUILD_TIME_IS_BAD (__TIME__[0] == '?')
#define BUILD_HOUR ((BUILD_TIME_IS_BAD) ? 99 : COMPUTE_BUILD_HOUR)
#define BUILD_MIN ((BUILD_TIME_IS_BAD) ? 99 : COMPUTE_BUILD_MIN)
#define BUILD_SEC ((BUILD_TIME_IS_BAD) ? 99 : COMPUTE_BUILD_SEC)
#endif // BUILD_DEFS_H
With the following test code, the above works great:
printf("%04d-%02d-%02dT%02d:%02d:%02d\n", BUILD_YEAR, BUILD_MONTH, BUILD_DAY, BUILD_HOUR, BUILD_MIN, BUILD_SEC);
However, when I try to use those macros with your stringizing macro, it stringizes the literal expression! I don't know of any way to get the compiler to reduce the expression to a literal integer value and then stringize.
Also, if you try to statically initialize an array of values using these macros, the compiler complains with an error: initializer element is not constant
message. So you cannot do what you want with these macros.
At this point I'm thinking that your best bet is the Python script that just generates a new include file for you. You can pre-compute anything you want in any format you want. If you don't want Python we can write an AWK script or even a C program.
I wrapped mp3 decoder library and made it available for .net developers. You can find it here:
http://sourceforge.net/projects/mpg123net/
Included are the samples to convert mp3 file to PCM, and read ID3 tags.
You are missing that rsync can also compare files by checksum.
--size-only
means that rsync will skip files that match in size, even if the timestamps differ. This means it will synchronise fewer files than the default behaviour. It will miss any file with changes that don't affect the overall file size. If you have something that changes the dates on files without changing the files, and you don't want rsync to spend lots of time checksumming those files to discover they haven't changed, this is the option to use.
--ignore-times
means that rsync will checksum every file, even if the timestamps and file sizes match. This means it will synchronise more files than the default behaviour. It will include changes to files even where the file size is the same and the modification date/time has been reset to the original value. Checksumming every file means it has to be entirely read from disk, which may be slow. Some build pipelines will reset timestamps to a specific date (like 1970-01-01) to ensure that the final build file is reproducible bit for bit, e.g. when packed into a tar file that saves the timestamps.
In android google maps application there is a very easy way to find distance between 2 locations, to do so follow the following easy steps:
when you first open the app go to " your timeline " from the drop menue on the top left.
once the new windwo opens, chose from the settings on your top right menue and choose "add place".
Good luck
While you are debugging in Visual Studio, display the "Output" window (View->Output). It will show there.
Nope, this is not possible at all. There is no provision for it in the mailto:
protocol, and it would be a gaping security hole if it were possible.
The best idea to send a file, but have the client send the E-Mail that I can think of is:
mailto:
link that contains the URL to the uploaded file in the message body You can also just use:
Write-Host "";
Or, to put it in terms of your specific question:
$str = ""
foreach($line in $file){
if($line -Match $review){ #Special condition
$str += Write-Host ""
$str += ANSWER #looking for ANSWER
}
#code.....
}
You can use flatMap
to flatten the internal lists (after converting them to Streams) into a single Stream, and then collect the result into a list:
List<List<Object>> list = ...
List<Object> flat =
list.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
You could extend FutureTask
class, and override the done()
method, then add the FutureTask
object to the ExecutorService
, so the done()
method will invoke when the FutureTask
completed immediately.
When a client sends ABORT, no transactions are rolled back. To avoid this behavior we have to use SET_XACT_ABORT ON https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql?view=sql-server-ver15
AngularJS's Filter worked out for me.
Assuming the code/id
is unique, we can filter out that particular object with AngularJS's filter
and work with the selected objects properties. Considering the example above:
<select ng-options="size.code as size.name for size in sizes"
ng-model="item.size.code"
ng-change="update(MAGIC_THING); search.code = item.size.code">
</select>
<!-- OUTSIDE THE SELECT BOX -->
<h1 ng-repeat="size in sizes | filter:search:true"
ng-init="search.code = item.size.code">
{{size.name}}
</h1>
Now, there are 3 important aspects to this:
ng-init="search.code = item.size.code"
- on initializing h1
element outside select
box, set the filter query to the selected option.
ng-change="update(MAGIC_THING); search.code = item.size.code"
- when you change the select input, we'll run one more line which will set the "search" query to the currently selected item.size.code
.
filter:search:true
- Pass true
to filter to enable strict matching.
That's it. If the size.code
is uniqueID, we'll have only one h1
element with the text of size.name
.
I've tested this in my project and it works.
Good Luck
I faced same issue for chrome build 61.0.3163.100
on MacOs Sierra with localhost
as server. Chrome started logging this message when I changed network speed configuration to 3G fast/ 3G slow and again back to Online.
Fix: When I tried selecting Offline mode and again Online mode, the logging issue disappeared. (This fix may no work on some devices or versions)
Update on 30th Jan 2018
I updated google chrome to Version 64.0.3282.119 (Official Build) (64-bit)
, it seems this bug is fixed now.
You should use Joda Time library because Java Util Date returns wrong values sometimes.
Joda vs Java Util Date
For example days between yesterday (dd-mm-yyyy, 12-07-2016) and first day of year in 1957 (dd-mm-yyyy, 01-01-1957):
public class Main {
public static void main(String[] args) {
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Date date = null;
try {
date = format.parse("12-07-2016");
} catch (ParseException e) {
e.printStackTrace();
}
//Try with Joda - prints 21742
System.out.println("This is correct: " + getDaysBetweenDatesWithJodaFromYear1957(date));
//Try with Java util - prints 21741
System.out.println("This is not correct: " + getDaysBetweenDatesWithJavaUtilFromYear1957(date));
}
private static int getDaysBetweenDatesWithJodaFromYear1957(Date date) {
DateTime jodaDateTime = new DateTime(date);
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy");
DateTime y1957 = formatter.parseDateTime("01-01-1957");
return Days.daysBetween(y1957 , jodaDateTime).getDays();
}
private static long getDaysBetweenDatesWithJavaUtilFromYear1957(Date date) {
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Date y1957 = null;
try {
y1957 = format.parse("01-01-1957");
} catch (ParseException e) {
e.printStackTrace();
}
return TimeUnit.DAYS.convert(date.getTime() - y1957.getTime(), TimeUnit.MILLISECONDS);
}
So I really advice you to use Joda Time library.
If installed as an admin, use:-
uname - admin
pw - the passkey that was generated during installation
Open the MySQL Command Line Client and type in your password
Change to the database you want to use for importing the .sql file data into. Do this by typing:
USE your_database_name
Now locate the .sql file you want to execute.
If the file is located in the main local C: drive directory and the .sql script file name is currentSqlTable.sql
, you would type the following:
\. C:\currentSqlTable.sql
and press Enter to execute the SQL script file.
I had a similar problem and update the input[type="number"]
example on angular docs for works with decimals precision and I'm using this approach to solve it.
PS: A quick reminder is that the browsers supports the characters 'e' and 'E' in the input[type="number"], because that the keypress
event is required.
angular.module('numfmt-error-module', [])
.directive('numbersOnly', function() {
return {
require: 'ngModel',
scope: {
precision: '@'
},
link: function(scope, element, attrs, modelCtrl) {
var currencyDigitPrecision = scope.precision;
var currencyDigitLengthIsInvalid = function(inputValue) {
return countDecimalLength(inputValue) > currencyDigitPrecision;
};
var parseNumber = function(inputValue) {
if (!inputValue) return null;
inputValue.toString().match(/-?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?/g).join('');
var precisionNumber = Math.round(inputValue.toString() * 100) % 100;
if (!!currencyDigitPrecision && currencyDigitLengthIsInvalid(inputValue)) {
inputValue = inputValue.toFixed(currencyDigitPrecision);
modelCtrl.$viewValue = inputValue;
}
return inputValue;
};
var countDecimalLength = function (number) {
var str = '' + number;
var index = str.indexOf('.');
if (index >= 0) {
return str.length - index - 1;
} else {
return 0;
}
};
element.on('keypress', function(evt) {
var charCode, isACommaEventKeycode, isADotEventKeycode, isANumberEventKeycode;
charCode = String.fromCharCode(evt.which || event.keyCode);
isANumberEventKeycode = '0123456789'.indexOf(charCode) !== -1;
isACommaEventKeycode = charCode === ',';
isADotEventKeycode = charCode === '.';
var forceRenderComponent = false;
if (modelCtrl.$viewValue != null && !!currencyDigitPrecision) {
forceRenderComponent = currencyDigitLengthIsInvalid(modelCtrl.$viewValue);
}
var isAnAcceptedCase = isANumberEventKeycode || isACommaEventKeycode || isADotEventKeycode;
if (!isAnAcceptedCase) {
evt.preventDefault();
}
if (forceRenderComponent) {
modelCtrl.$render(modelCtrl.$viewValue);
}
return isAnAcceptedCase;
});
modelCtrl.$render = function(inputValue) {
return element.val(parseNumber(inputValue));
};
modelCtrl.$parsers.push(function(inputValue) {
if (!inputValue) {
return inputValue;
}
var transformedInput;
modelCtrl.$setValidity('number', true);
transformedInput = parseNumber(inputValue);
if (transformedInput !== inputValue) {
modelCtrl.$viewValue = transformedInput;
modelCtrl.$commitViewValue();
modelCtrl.$render(transformedInput);
}
return transformedInput;
});
}
};
});
And in your html you can use this approach
<input
type="number"
numbers-only
precision="2"
ng-model="model.value"
step="0.10" />
Here is a simple approach:
#!/bin/bash
USE_IP='-o StrictHostKeyChecking=no [email protected]'
FILE_NAME=/home/user/file.txt
SSH_PASS='sshpass -p password-for-remote-machine'
if $SSH_PASS ssh $USE_IP stat $FILE_NAME \> /dev/null 2\>\&1
then
echo "File exists"
else
echo "File does not exist"
fi
You need to install sshpass on your machine to work it.
This is one of the most accurate answers that is able to resolve the birthday of 29th of Feb compared to any year of 28th Feb.
public int GetAge(DateTime birthDate)
{
int age = DateTime.Now.Year - birthDate.Year;
if (birthDate.DayOfYear > DateTime.Now.DayOfYear)
age--;
return age;
}
Here is the example directly from PEP 8 on limiting line length:
class Rectangle(Blob):
def __init__(self, width, height,
color='black', emphasis=None, highlight=0):
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong' or
highlight > 100):
raise ValueError("sorry, you lose")
if width == 0 and height == 0 and (color == 'red' or
emphasis is None):
raise ValueError("I don't think so -- values are %s, %s" %
(width, height))
Blob.__init__(self, width, height,
color, emphasis, highlight)
You've Ruby 1.8 so you need to upgrade to at least 1.9 to make it working.
If so, then check How to install a specific version of a ruby gem?
If this won't help, then reinstalling ruby-dev
again.
Adding this android:hardwareAccelerated="true"
in the manifest was the only thing that significantly improved the performance for me
More info here: http://developer.android.com/guide/topics/manifest/application-element.html#hwaccel
this.$router.push({ query: Object.assign(this.$route.query, { new: 'param' }) })
There are two ways to handle the situation where we do not want the index to be stored in csv file.
As others have stated you can use index=False while saving your
dataframe to csv file.
df.to_csv('file_name.csv',index=False)
df.to_csv(' file_name.csv ')
df_new = pd.read_csv('file_name.csv').drop(['unnamed 0'],axis=1)
Here is a example of embedding without an iFrame:
<div style="width: 560px; height: 315px; float: none; clear: both; margin: 2px auto;">
<embed
src="https://www.youtube.com/embed/J---aiyznGQ?autohide=1&autoplay=1"
wmode="transparent"
type="video/mp4"
width="100%" height="100%"
allow="autoplay; encrypted-media; picture-in-picture"
allowfullscreen
title="Keyboard Cat"
>
</div>
_x000D_
compare to regular iframe "embed" code from YouTube:
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/J---aiyznGQ?autoplay=1"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen>
</iframe>
_x000D_
and as far as HTML5 goes, use <object>
tag like so (corrected):
<object
style="width: 820px; height: 461.25px; float: none; clear: both; margin: 2px auto;"
data="http://www.youtube.com/embed/J---aiyznGQ?autoplay=1">
</object>
_x000D_
Extracting the address all by itself is a bit difficult, but you can get the entire IP Address line easily.
To show all IP addresses on any English-language Windows OS:
ipconfig | findstr /R /C:"IP.* Address"
To show only IPv4 or IPv6 addresses on Windows 7+:
ipconfig | findstr /R /C:"IPv4 Address"
ipconfig | findstr /R /C:"IPv6 Address"
Here's some sample output from an XP machine with 3 network adapters.
IP Address. . . . . . . . . . . . : 192.168.1.10
IP Address. . . . . . . . . . . . : 10.6.102.205
IP Address. . . . . . . . . . . . : 192.168.56.1
pip install --user --upgrade jupyter
Using the above command should do the job in Ubuntu 18.04
If it doesn't, follow the steps from here
See in_array
<?php
$arr = array(0 => "kitchen", 1 => "bedroom", 2 => "living_room", 3 => "dining_room");
if (in_array("kitchen", $arr))
{
echo sprintf("'kitchen' is in '%s'", implode(', ', $arr));
}
?>
There is another option that does not introduce global gotchas when trying to initialize multiple variables to the same value. Whether or not it is preferable to the long way is a judgement call. It will likely be slower and may or may not be more readable. In your specific case, I think that the long way is probably more readable and maintainable as well as being faster.
The other way utilizes Destructuring assignment.
let [moveUp, moveDown,_x000D_
moveLeft, moveRight,_x000D_
mouseDown, touchDown] = Array(6).fill(false);_x000D_
_x000D_
console.log(JSON.stringify({_x000D_
moveUp, moveDown,_x000D_
moveLeft, moveRight,_x000D_
mouseDown, touchDown_x000D_
}, null, ' '));_x000D_
_x000D_
// NOTE: If you want to do this with objects, you would be safer doing this_x000D_
let [obj1, obj2, obj3] = Array(3).fill(null).map(() => ({}));_x000D_
console.log(JSON.stringify({_x000D_
obj1, obj2, obj3_x000D_
}, null, ' '));_x000D_
// So that each array element is a unique object_x000D_
_x000D_
// Or another cool trick would be to use an infinite generator_x000D_
let [a, b, c, d] = (function*() { while (true) yield {x: 0, y: 0} })();_x000D_
console.log(JSON.stringify({_x000D_
a, b, c, d_x000D_
}, null, ' '));_x000D_
_x000D_
// Or generic fixed generator function_x000D_
function* nTimes(n, f) {_x000D_
for(let i = 0; i < n; i++) {_x000D_
yield f();_x000D_
}_x000D_
}_x000D_
let [p1, p2, p3] = [...nTimes(3, () => ({ x: 0, y: 0 }))];_x000D_
console.log(JSON.stringify({_x000D_
p1, p2, p3_x000D_
}, null, ' '));
_x000D_
This allows you to initialize a set of var
, let
, or const
variables to the same value on a single line all with the same expected scope.
References:
MDN: Array Global Object
MDN: Array.fill
Just use basename
:
echo `basename "$filename"`
The quotes are needed in case $filename contains e.g. spaces.
For completeness, it is also a rather important (and relatively new) method in statistics that uses resampling / simulation to infer population properties from a sample. It has its own lengthy Wikipedia article on bootstrapping (statistics).
I had the same problem and solved it using a boolean flag that gets set when the form is closing (the System.Timers.Timer does not have an IsDisposed property). Everywhere on the form I was starting the timer, I had it check this flag. If it was set, then don't start the timer. Here's the reason:
The Reason:
I was stopping and disposing of the timer in the form closing event. I was starting the timer in the Timer_Elapsed() event. If I were to close the form in the middle of the Timer_Elapsed() event, the timer would immediately get disposed by the Form_Closing() event. This would happen before the Timer_Elapsed() event would finish and more importantly, before it got to this line of code:
_timer.Start()
As soon as that line was executed an ObjectDisposedException() would get thrown with the error you mentioned.
The Solution:
Private Sub myForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
' set the form closing flag so the timer doesn't fire even after the form is closed.
_formIsClosing = True
_timer.Stop()
_timer.Dispose()
End Sub
Here's the timer elapsed event:
Private Sub Timer_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles _timer.Elapsed
' Don't want the timer stepping on itself (ie. the time interval elapses before the first call is done processing)
_timer.Stop()
' do work here
' Only start the timer if the form is open. Without this check, the timer will run even if the form is closed.
If Not _formIsClosing Then
_timer.Interval = _refreshInterval
_timer.Start() ' ObjectDisposedException() is thrown here unless you check the _formIsClosing flag.
End If
End Sub
The interesting thing to know, even though it would throw the ObjectDisposedException when attempting to start the timer, the timer would still get started causing it to run even when the form was closed (the thread would only stop when the application was closed).
Only Double and Float type support POSITIVE_INFINITY
constant.
Official npm page suggest a structured method to update angular version for both global and local scenarios.
1.First of all, you need to uninstall the current angular from your system.
npm uninstall -g angular-cli
npm uninstall --save-dev angular-cli
npm uninstall -g @angular/cli
2.Clean up the cache
npm cache clean
EDIT
As pointed out by @candidj
npm cache clean
is renamed as npm cache verify
from npm 5 onwards
3.Install angular globally
npm install -g @angular/cli@latest
4.Local project setup if you have one
rm -rf node_modules
npm install --save-dev @angular/cli@latest
npm install
Please check the same down on the link below:
https://www.npmjs.com/package/@angular/cli#updating-angular-cli
This will solve the problem.
I just want to add that you have to make sure your database is created with COLLATE utf8_general_ci or whichever collation you want to use, Else you might end up with another one than intended.
In phpmyadmin you can see the collation by clicking your database and choose operations. If you try create tables with another collation than your database, your tables will end up with the database collation anyways.
So make sure the collation for your database is right before creating tables. Hope this saves someone a few hours lol
I use this method for bubble sorting
public static int[] bubbleSort (int[] a) {
int n = a.length;
int j = 0;
boolean swap = true;
while (swap) {
swap = false;
for (int j = 1; j < n; j++) {
if (a[j-1] > a[j]) {
j = a[j-1];
a[j-1] = a[j];
a[j] = j;
swap = true;
}
}
n = n - 1;
}
return a;
}//end bubbleSort
#ffffff
are actually 3 color components in hexadecimal notation - red ff
, green ff
and blue ff
. You can write hexadecimal notation in Swift using 0x
prefix, e.g 0xFF
To simplify the conversion, let's create an initializer that takes integer (0 - 255) values:
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(rgb: Int) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF
)
}
}
Usage:
let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF)
let color2 = UIColor(rgb: 0xFFFFFF)
How to get alpha?
Depending on your use case, you can simply use the native UIColor.withAlphaComponent
method, e.g.
let semitransparentBlack = UIColor(rgb: 0x000000).withAlphaComponent(0.5)
Or you can add an additional (optional) parameter to the above methods:
convenience init(red: Int, green: Int, blue: Int, a: CGFloat = 1.0) {
self.init(
red: CGFloat(red) / 255.0,
green: CGFloat(green) / 255.0,
blue: CGFloat(blue) / 255.0,
alpha: a
)
}
convenience init(rgb: Int, a: CGFloat = 1.0) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF,
a: a
)
}
(we cannot name the parameter alpha
because of a name collision with the existing initializer).
Called as:
let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0.5)
let color2 = UIColor(rgb: 0xFFFFFF, a: 0.5)
To get the alpha as an integer 0-255, we can
convenience init(red: Int, green: Int, blue: Int, a: Int = 0xFF) {
self.init(
red: CGFloat(red) / 255.0,
green: CGFloat(green) / 255.0,
blue: CGFloat(blue) / 255.0,
alpha: CGFloat(a) / 255.0
)
}
// let's suppose alpha is the first component (ARGB)
convenience init(argb: Int) {
self.init(
red: (argb >> 16) & 0xFF,
green: (argb >> 8) & 0xFF,
blue: argb & 0xFF,
a: (argb >> 24) & 0xFF
)
}
Called as
let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0xFF)
let color2 = UIColor(argb: 0xFFFFFFFF)
Or a combination of the previous methods. There is absolutely no need to use strings.
This might not really answer the question, but just in case someone just need to quickly send a string value to a function that require a NSArray parameter.
NSArray *data = @[@"The String Value"];
if you need to send more than just 1 string value, you could also use
NSArray *data = @[@"The String Value", @"Second String", @"Third etc"];
then you can send it to the function like below
theFunction(data);
$.fn.extend({
insertAtCaret: function(myValue) {
var elemSelected = window.getSelection();
if(elemSelected) {
var startPos = elemSelected.getRangeAt(0).startOffset;
var endPos = elemSelected.getRangeAt(0).endOffset;
this.val(this.val().substring(0, startPos)+myValue+this.val().substring(endPos,this.val().length));
} else {
this.val(this.val()+ myValue) ;
}
}
});
I know it's too late, but there is an approach in javascript that can help you detect witch html element is causing the horizontal overflow -> scrollbar to appear
Here is a link to the post on CSS Tricks
var docWidth = document.documentElement.offsetWidth;
[].forEach.call(
document.querySelectorAll('*'),
function(el) {
if (el.offsetWidth > docWidth) {
console.log(el);
}
}
);
it Might return something like this:
<div class="div-with-extra-width">...</div>
then you just remove the extra width from the div
or set it's max-width:100%
Hope this helps!
It fixed the problem for me :]
I know this is extremely old, but I understand that this error type is a common mistake for beginners to make since most beginners will call their functions upon their header element being loaded. Seeing as this solution is not addressed at all in this thread, I'll add it. It is very likely that this javascript function was placed before the actual html was loaded. Remember, if you immediately call your javascript before the document is ready then elements requiring an element from the document might find an undefined value.
I encountered similar problems too. In my case it was solved by getting the cursor in this way:
cursor = self.conn.cursor(buffered=True)
You can use this:
select count(customer) as count, pets
from table
group by pets
You need to commit at least one time on master before creating a new branch.
If embed no longer works for you, try with /v
instead:
<iframe width="420" height="315" src="https://www.youtube.com/v/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe>
public String getStringBetweenTwoChars(String input, String startChar, String endChar) {
try {
int start = input.indexOf(startChar);
if (start != -1) {
int end = input.indexOf(endChar, start + startChar.length());
if (end != -1) {
return input.substring(start + startChar.length(), end);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return input; // return null; || return "" ;
}
Usage :
String input = "test string (67)";
String startChar = "(";
String endChar = ")";
String output = getStringBetweenTwoChars(input, startChar, endChar);
System.out.println(output);
// Output: "67"
If you are using some of the examples they might not work
Here is my version for scroll view
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
View,
ScrollView,
TouchableOpacity,
Image
} from 'react-native';
class AwesomeProject extends Component {
render() {
return (
<View>
<ScrollView
ref={(scrollView) => { _scrollView = scrollView; }}
automaticallyAdjustContentInsets={false}
onScroll={() => { console.log('onScroll!'); }}
scrollEventThrottle={200}
style={styles.scrollView}>
{THUMBS.map(createThumbRow)}
</ScrollView>
<TouchableOpacity
style={styles.button}
onPress={() => { _scrollView.scrollTo({y: 0}); }}>
<Text>Scroll to top</Text>
</TouchableOpacity>
</View>
);
}
}
var Thumb = React.createClass({
shouldComponentUpdate: function(nextProps, nextState) {
return false;
},
render: function() {
return (
<View style={styles.button}>
<Image style={styles.img} source={{uri:this.props.uri}} />
</View>
);
}
});
var THUMBS = [
'http://loremflickr.com/320/240?random='+Math.round(Math.random()*10000) + 1,
'http://loremflickr.com/320/240?random='+Math.round(Math.random()*10000) + 1,
'http://loremflickr.com/320/240?random='+Math.round(Math.random()*10000) + 1
];
THUMBS = THUMBS.concat(THUMBS); // double length of THUMBS
var createThumbRow = (uri, i) => <Thumb key={i} uri={uri} />;
var styles = StyleSheet.create({
scrollView: {
backgroundColor: '#6A85B1',
height: 600,
},
horizontalScrollView: {
height: 120,
},
containerPage: {
height: 50,
width: 50,
backgroundColor: '#527FE4',
padding: 5,
},
text: {
fontSize: 20,
color: '#888888',
left: 80,
top: 20,
height: 40,
},
button: {
margin: 7,
padding: 5,
alignItems: 'center',
backgroundColor: '#eaeaea',
borderRadius: 3,
},
buttonContents: {
flexDirection: 'row',
width: 64,
height: 64,
},
img: {
width: 321,
height: 200,
}
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
I am not expert, but this may work as well,
dat <- dat[2:nrow(dat), ]
It is a conflict (bug) between Themes inside style.xml file in android versions 7 (Api levels 24,25) & 8 (api levels 26,27), when you have
android:screenOrientation="portrait"
:inside specific activity (that crashes) in AndroidManifest.xml
&
<item name="android:windowIsTranslucent">true</item>
in the theme that applied to that activity inside style.xml
It can be solve by these ways according to your need :
1- Remove on of the above mentioned properties that make conflict
2- Change Activity orientation to one of these values as you need : unspecified
or behind
and so on that can be found here : Google reference for android:screenOrientation
`
3- Set the orientation programmatically in run time
Give your img tag an id, then you can
document.getElementById("imageid").src="../template/save.png";
This is a little function I use all the time its handy if you are debugging arrays. Its pretty much the same thing Darryl and Karim posted. I just added a parameter title so you have some debug info as what array you are printing. it also checks if you have supplied it with a valid array and lets you know if you didn't.
function print_array($title,$array){
if(is_array($array)){
echo $title."<br/>".
"||---------------------------------||<br/>".
"<pre>";
print_r($array);
echo "</pre>".
"END ".$title."<br/>".
"||---------------------------------||<br/>";
}else{
echo $title." is not an array.";
}
}
Basic usage:
//your array
$array = array('cat','dog','bird','mouse','fish','gerbil');
//usage
print_array("PETS", $array);
Results:
PETS
||---------------------------------||
Array
(
[0] => cat
[1] => dog
[2] => bird
[3] => mouse
[4] => fish
[5] => gerbil
)
END PETS
||---------------------------------||
My suggestion would be a combination of implement a few of them and analyze some implementations of them. For example, within .Net, there are uses of adapter patterns if you look at Data Adapters, as well as a few others if one does a little digging into the framework.
Since Node.js is using the CommonJS patterns, you can only share variables between modules with module.exports
or by setting a global var like you would in the browser, but instead of using window you use global.your_var = value;
.
There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.
One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.
Check the permissions on your Ruby script (may not have execute permission), your theme file and directory (in case it can't read the theme or tries to create other themes in there), and the directory you're in when you run the script (in case it makes temporary files in the current directory rather then /tmp
).
Any one of them could be causing you grief.
using Range with
[Range(typeof(Decimal), "0", "9999", ErrorMessage = "{0} must be a decimal/number between {1} and {2}.")]
[Range(typeof(Decimal),"0.0", "1000000000000000000"]
Hope it will help
Based on another solutions. I have use this:
IntPtr xAsIntPtr = new IntPtr(excelObj.Application.Hwnd);
excelObj.ActiveWorkbook.Close();
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("Excel");
foreach (System.Diagnostics.Process p in process)
{
if (p.MainWindowHandle == xAsIntPtr)
{
try
{
p.Kill();
}
catch { }
}
}
Using the "MainWindowHandle" to identify the process and close him.
excelObj: This is my Application Interop excel objecto
Try to do these checks:
Enjoy :)
Basically I prefer to use some extra backups in case if one of IP is not accessible. So I use this method.
public static string GetExternalIPAddress()
{
string result = string.Empty;
try
{
using (var client = new WebClient())
{
client.Headers["User-Agent"] =
"Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
"(compatible; MSIE 6.0; Windows NT 5.1; " +
".NET CLR 1.1.4322; .NET CLR 2.0.50727)";
try
{
byte[] arr = client.DownloadData("http://checkip.amazonaws.com/");
string response = System.Text.Encoding.UTF8.GetString(arr);
result = response.Trim();
}
catch (WebException)
{
}
}
}
catch
{
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("https://ipinfo.io/ip").Replace("\n", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("https://api.ipify.org").Replace("\n", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("https://icanhazip.com").Replace("\n", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("https://wtfismyip.com/text").Replace("\n", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("http://bot.whatismyipaddress.com/").Replace("\n", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
string url = "http://checkip.dyndns.org";
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
System.Net.WebResponse resp = req.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
string response = sr.ReadToEnd().Trim();
string[] a = response.Split(':');
string a2 = a[1].Substring(1);
string[] a3 = a2.Split('<');
result = a3[0];
}
catch (Exception)
{
}
}
return result;
}
In order to update GUI control (WPF, .NET 4.5), for instance some Label I use this code
void GetPublicIPAddress()
{
Task.Factory.StartNew(() =>
{
var ipAddress = SystemHelper.GetExternalIPAddress();
Action bindData = () =>
{
if (!string.IsNullOrEmpty(ipAddress))
labelMainContent.Content = "IP External: " + ipAddress;
else
labelMainContent.Content = "IP External: ";
labelMainContent.Visibility = Visibility.Visible;
};
this.Dispatcher.InvokeAsync(bindData);
});
}
Hope it is useful.
Here is an example of app that will include this code.
I had run into the same issue while I was dealing with large dataset. One thing I've noticed was the NoSuchElementException
is thrown when the Scanner reaches the endOfFile
, where it is not going to affect our data.
Here, I've placed my code in try block
and catch block
handles the exception
. You can also leave it empty, if you don't want to perform any task.
For the above question, because you are using file.next()
both in the condition and in the while loop you can handle the exception as
while(!file.next().equals(treasure)){
try{
file.next(); //stack trace error here
}catch(NoSuchElementException e) { }
}
This worked perfectly for me, if there are any corner cases for my approach, do let me know through comments.
this works:
window.onscroll = function (e) {
// called when the window is scrolled.
}
edit:
you said this is a function in a TimeInterval..
Try doing it like so:
userHasScrolled = false;
window.onscroll = function (e)
{
userHasScrolled = true;
}
then inside your Interval insert this:
if(userHasScrolled)
{
//do your code here
userHasScrolled = false;
}
Try setting the timeout value in your web service proxy class:
WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds
Try this,
$('td').click(function(){
var row_index = $(this).parent().index();
var col_index = $(this).index();
});
If you need the index of table contain td then you can change it to
var row_index = $(this).parent('table').index();
Logically speaking Rohit's solution should have worked, but it didn't. I think SQL Management Studio messed up when trying to optimize this.
But by modifying the string before comparing them I was able to get the right results. This worked for me:
SELECT [ExternalId]
FROM [EquipmentSerialsMaster] where LOWER('0'+[ExternalId]) COLLATE Latin1_General_CS_AS != '0'+[ExternalId]
I have seen many solutions in the above.
Here I am using map function to find the index of the search text in an array object.
I am going to explain my answer with using students data.
step 1: create array object for the students(optional you can create your own array object).
var students = [{name:"Rambabu",htno:"1245"},{name:"Divya",htno:"1246"},{name:"poojitha",htno:"1247"},{name:"magitha",htno:"1248"}];
step 2: Create variable to search text
var studentNameToSearch = "Divya";
step 3: Create variable to store matched index(here we use map function to iterate).
var matchedIndex = students.map(function (obj) { return obj.name; }).indexOf(studentNameToSearch);
var students = [{name:"Rambabu",htno:"1245"},{name:"Divya",htno:"1246"},{name:"poojitha",htno:"1247"},{name:"magitha",htno:"1248"}];_x000D_
_x000D_
var studentNameToSearch = "Divya";_x000D_
_x000D_
var matchedIndex = students.map(function (obj) { return obj.name; }).indexOf(studentNameToSearch);_x000D_
_x000D_
console.log(matchedIndex);_x000D_
_x000D_
alert("Your search name index in array is:"+matchedIndex)
_x000D_
Not yet, but there is the experimental :matches()
pseudo-class function that does just that:
:matches(.a .b) .c {
/* stuff goes here */
}
You can find more info on it here and here. Currently, most browsers support its initial version :any()
, which works the same way, but will be replaced by :matches()
. We just have to wait a little more before using this everywhere (I surely will).
fmin
and fmax
are specifically for use with floating point numbers (hence the "f"). If you use it for ints, you may suffer performance or precision losses due to conversion, function call overhead, etc. depending on your compiler/platform.
std::min
and std::max
are template functions (defined in header <algorithm>
) which work on any type with a less-than (<
) operator, so they can operate on any data type that allows such a comparison. You can also provide your own comparison function if you don't want it to work off <
.
This is safer since you have to explicitly convert arguments to match when they have different types. The compiler won't let you accidentally convert a 64-bit int into a 64-bit float, for example. This reason alone should make the templates your default choice. (Credit to Matthieu M & bk1e)
Even when used with floats the template may win in performance. A compiler always has the option of inlining calls to template functions since the source code is part of the compilation unit. Sometimes it's impossible to inline a call to a library function, on the other hand (shared libraries, absence of link-time optimization, etc.).