Instead of extrapolating off the ends, you could return the extents of the y_list
. Most of the time your application is well behaved, and the Interpolate[x]
will be in the x_list
. The (presumably) linear affects of extrapolating off the ends may mislead you to believe that your data is well behaved.
Returning a non-linear result (bounded by the contents of x_list
and y_list
) your program's behavior may alert you to an issue for values greatly outside x_list
. (Linear behavior goes bananas when given non-linear inputs!)
Returning the extents of the y_list
for Interpolate[x]
outside of x_list
also means you know the range of your output value. If you extrapolate based on x
much, much less than x_list[0]
or x
much, much greater than x_list[-1]
, your return result could be outside of the range of values you expected.
def __getitem__(self, x):
if x <= self.x_list[0]:
return self.y_list[0]
elif x >= self.x_list[-1]:
return self.y_list[-1]
else:
i = bisect_left(self.x_list, x) - 1
return self.y_list[i] + self.slopes[i] * (x - self.x_list[i])
This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.
Sub Copy5CellsToRight()
ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub
If you want to include the activecell in the range that gets copied, you don't need the offset:
Sub ExtendAndCopy5CellsToRight()
ActiveCell.Resize(1, 6).Copy
End Sub
Note that you don't need to select before copying.
The C++ Standard says it like this :
3.9.1, §2 :
There are five signed integer types : "signed char", "short int", "int", "long int", and "long long int". In this list, each type provides at least as much storage as those preceding it in the list. Plain ints have the natural size suggested by the architecture of the execution environment (44); the other signed integer types are provided to meet special needs.
(44) that is, large enough to contain any value in the range of INT_MIN and INT_MAX, as defined in the header
<climits>
.
The conclusion : it depends on which architecture you're working on. Any other assumption is false.
It's not that key is a special word, but that dictionaries implement the iterator protocol. You could do this in your class, e.g. see this question for how to build class iterators.
In the case of dictionaries, it's implemented at the C level. The details are available in PEP 234. In particular, the section titled "Dictionary Iterators":
Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. [...] This means that we can write
for k in dict: ...
which is equivalent to, but much faster than
for k in dict.keys(): ...
as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.
Add methods to dictionaries that return different kinds of iterators explicitly:
for key in dict.iterkeys(): ... for value in dict.itervalues(): ... for key, value in dict.iteritems(): ...
This means that
for x in dict
is shorthand forfor x in dict.iterkeys()
.
In Python 3, dict.iterkeys()
, dict.itervalues()
and dict.iteritems()
are no longer supported. Use dict.keys()
, dict.values()
and dict.items()
instead.
I ran into this issue and it turned out the problem was that the jenkins service wasn't being run as the jenkins user. So running the commands as the jenkins user worked just fine.
Imports System.Net
Module MainLine
Sub Main()
Dim hostName As String = Dns.GetHostName
Console.WriteLine("Host Name : " & hostName & vbNewLine)
For Each address In Dns.GetHostEntry(hostName).AddressList()
Select Case Convert.ToInt32(address.AddressFamily)
Case 2
Console.WriteLine("IP Version 4 Address: " & address.ToString)
Case 23
Console.WriteLine("IP Version 6 Address: " & address.ToString)
End Select
Next
Console.ReadKey()
End Sub
End Module
There is advanced version of ping - "fping", which gives possibility to define the timeout in milliseconds.
#!/bin/bash
IP='192.168.1.1'
fping -c1 -t300 $IP 2>/dev/null 1>/dev/null
if [ "$?" = 0 ]
then
echo "Host found"
else
echo "Host not found"
fi
In Chrome, you are supposed to be able to allow this capability with a runtime flag --allow-file-access-from-files
However, it looks like there is a problem with current versions of Chrome (37, 38) where this doesn't work unless you also pass the runtime flag --disable-web-security
That's an unacceptable solution, except perhaps as a short-term workaround, but it has been identified as an issue: https://code.google.com/p/chromium/issues/detail?id=379206
There are two things to remember here. One is to add the -PassThru
argument and two is to add the -Wait
argument. You need to add the wait argument because of this defect: http://connect.microsoft.com/PowerShell/feedback/details/520554/start-process-does-not-return-exitcode-property
-PassThru [<SwitchParameter>]
Returns a process object for each process that the cmdlet started. By d
efault, this cmdlet does not generate any output.
Once you do this a process object is passed back and you can look at the ExitCode property of that object. Here is an example:
$process = start-process ping.exe -windowstyle Hidden -ArgumentList "-n 1 -w 127.0.0.1" -PassThru -Wait
$process.ExitCode
# This will print 1
If you run it without -PassThru
or -Wait
, it will print out nothing.
The same answer is here: How do I run a Windows installer and get a succeed/fail value in PowerShell?
I think you can use the nrows
parameter. From the docs:
nrows : int, default None
Number of rows of file to read. Useful for reading pieces of large files
which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):
In [1]: import pandas as pd
In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s
In [3]: len(z)
Out[3]: 20
In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s
The jsonlite package is easy to use and tries to convert json into data frames.
Example:
library(jsonlite)
# url with some information about project in Andalussia
url <- 'http://www.juntadeandalucia.es/export/drupaljda/ayudas.json'
# read url and convert to data.frame
document <- fromJSON(txt=url)
Your method doesn't have any callbacks so there is no reason to use .CallBack()
. You can simply return a Task with the desired values using .Returns()
and Task.FromResult, e.g.:
MyType someValue=...;
mock.Setup(arg=>arg.DoSomethingAsync())
.Returns(Task.FromResult(someValue));
Update 2014-06-22
Moq 4.2 has two new extension methods to assist with this.
mock.Setup(arg=>arg.DoSomethingAsync())
.ReturnsAsync(someValue);
mock.Setup(arg=>arg.DoSomethingAsync())
.ThrowsAsync(new InvalidOperationException());
Update 2016-05-05
As Seth Flowers mentions in the other answer, ReturnsAsync
is only available for methods that return a Task<T>
. For methods that return only a Task,
.Returns(Task.FromResult(default(object)))
can be used.
As shown in this answer, in .NET 4.6 this is simplified to .Returns(Task.CompletedTask);
, e.g.:
mock.Setup(arg=>arg.DoSomethingAsync())
.Returns(Task.CompletedTask);
It is not necessary to use another library like newChart or use other people's pull requests to pull this off. All you have to do is define an options object and add the label wherever and however you want it in the tooltip.
var optionsPie = {
tooltipTemplate: "<%= label %> - <%= value %>"
}
If you want the tooltip to be always shown you can make some other edits to the options:
var optionsPie = {
tooltipEvents: [],
showTooltips: true,
onAnimationComplete: function() {
this.showTooltip(this.segments, true);
},
tooltipTemplate: "<%= label %> - <%= value %>"
}
In your data items, you have to add the desired label property and value and that's all.
data = [
{
value: 480000,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Tobacco"
}
];
Now, all you have to do is pass the options object after the data to the new Pie like this: new Chart(ctx).Pie(data,optionsPie)
and you are done.
This probably works best for pies which are not very small in size.
You can't bind an event to the element before it exists, so you should do it in the onload
event:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
document.getElementById('foo').addEventListener('click', function (e) {
var img = document.createElement('img');
img.setAttribute('src', 'http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png');
e.target.appendChild(img);
});
};
</script>
</head>
<body>
<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
</body>
</html>
Since the accepted answer requires IIS Manager, and IIS Express doesn't have IIS Manager or any UI, here's the solution for you IIS Express users (and should work for everyone else too):
When you open Visual Studio and get the error message, right-click the project Solution Explorer and choose "Edit {ProjectName}.csproj"
In the project file, change the following line:
<UseIIS>True</UseIIS>
to
<UseIIS>False</UseIIS>
Save the file.
Now reload your project.
Done.
You'll then be able to open your project. If at this point, you want to use IIS, simply go to your project properties, click the "Web" tab, and select the option to use IIS. There's the button there to "Create Virtual Directory". It may tell you that you need to run Visual Studio as an administrator to create that directory, so do that if needed.
Use WinSCP for file transfer over SSH, putty is only for SSH commands.
To build your application without aidl is missing
error with compileSdkVersion 23
and buildToolsVersion "23.0.1"
you should specify latest versions for Android Gradle plugin (and Google Play Services Gradle plugin if you are using it) in main build.gradle
file:
buildscript {
repositories {
...
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.1'
classpath 'com.google.gms:google-services:1.3.1'
}
}
From MySQL docs:
A character set is a set of symbols and encodings. A collation is a set of rules for comparing characters in a character set. Let's make the distinction clear with an example of an imaginary character set.
Suppose that we have an alphabet with four letters: 'A', 'B', 'a', 'b'. We give each letter a number: 'A' = 0, 'B' = 1, 'a' = 2, 'b' = 3. The letter 'A' is a symbol, the number 0 is the encoding for 'A', and the combination of all four letters and their encodings is a character set.
Now, suppose that we want to compare two string values, 'A' and 'B'. The simplest way to do this is to look at the encodings: 0 for 'A' and 1 for 'B'. Because 0 is less than 1, we say 'A' is less than 'B'. Now, what we've just done is apply a collation to our character set. The collation is a set of rules (only one rule in this case): "compare the encodings." We call this simplest of all possible collations a binary collation.
But what if we want to say that the lowercase and uppercase letters are equivalent? Then we would have at least two rules: (1) treat the lowercase letters 'a' and 'b' as equivalent to 'A' and 'B'; (2) then compare the encodings. We call this a case-insensitive collation. It's a little more complex than a binary collation.
In real life, most character sets have many characters: not just 'A' and 'B' but whole alphabets, sometimes multiple alphabets or eastern writing systems with thousands of characters, along with many special symbols and punctuation marks. Also in real life, most collations have many rules: not just case insensitivity but also accent insensitivity (an "accent" is a mark attached to a character as in German 'ö') and multiple-character mappings (such as the rule that 'ö' = 'OE' in one of the two German collations).
First of all, if table2
's idProduct is an identity, you cannot insert it explicitly until you set IDENTITY_INSERT
on that table
SET IDENTITY_INSERT table2 ON;
before the insert.
So one of two, you modify your second stored and call it with only the parameters productName
and productDescription
and then get the new ID
EXEC test2 'productName', 'productDescription'
SET @newID = SCOPE_IDENTIY()
or you already have the ID of the product and you don't need to call SCOPE_IDENTITY()
and can make the insert on table1
with that ID
sys.maxint is not the largest integer supported by python. It's the largest integer supported by python's regular integer type.
You can use mysql_real_escape_string. mysql_real_escape_string()
does not escape %
and _
, so you should escape MySQL wildcards (%
and _
) separately.
I actually had this identical issue with the inverse solution. I had upgraded a .NET project to .NET 4.0 and then reverted back to .NET 3.5. The app.config in my project continued to have the following which was causing the above error in question:
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
The solution to solve the error for this was to revert it back to the proper 2.0 reference as follows:
<startup>
<supportedRuntime version="v2.0.50727"/>
</startup>
So if a downgrade is producing the above error, you might need to back up the .NET Framework supported version.
Root Cause #1 - The Delimiter Problem
Sql injection is possible because we use quotation marks to delimit strings and also to be parts of strings, making it impossible to interpret them sometimes. If we had delimiters that could not be used in string data, sql injection never would have happened. Solving the delimiter problem eliminates the sql injection problem. Structure queries do that.
Root Cause #2 - Human Nature, People are Crafty and Some Crafty People Are Malicious And All People Make Mistakes
The other root cause of sql injection is human nature. People, including programmers, make mistakes. When you make a mistake on a structured query, it does not make your system vulnerable to sql injection. If you are not using structured queries, mistakes can generate sql injection vulnerability.
How Structured Queries Resolve the Root Causes of SQL Injection
Structured Queries Solve The Delimiter Problem, by by putting sql commands in one statement and putting the data in a separate programming statement. Programming statements create the separation needed.
Structured queries help prevent human error from creating critical security holes. With regard to humans making mistakes, sql injection cannot happen when structure queries are used. There are ways of preventing sql injection that don't involve structured queries, but normal human error in that approaches usually leads to at least some exposure to sql injection. Structured Queries are fail safe from sql injection. You can make all the mistakes in the world, almost, with structured queries, same as any other programming, but none that you can make can be turned into a ssstem taken over by sql injection. That is why people like to say this is the right way to prevent sql injection.
So, there you have it, the causes of sql injection and the nature structured queries that makes them impossible when they are used.
Try this configuration:
position to absolute
width to 100%
height to 100px
bottom to 10
background-color: blue
This can help actually move the div to the bottom. Just modify accordingly.
They have already answered how to use a global variable.
I will tell you why the use of global variables is a bad idea as a result of this question carried out in stackoverflow in Spanish.
Explicit translation of the text in Spanish:
The problem with global variables is that they create hidden dependencies. When it comes to large applications, you yourself do not know / remember / you are clear about the objects you have and their relationships.
So, you can not have a clear notion of how many objects your global variable is using. And if you want to change something of the global variable, for example, the meaning of each of its possible values, or its type? How many classes or compilation units will that change affect? If the amount is small, it may be worth making the change. If the impact will be great, it may be worth looking for another solution.
But what is the impact? Because a global variable can be used anywhere in the code, it can be very difficult to measure it.
In addition, always try to have a variable with the shortest possible life time, so that the amount of code that makes use of that variable is the minimum possible, and thus better understand its purpose, and who modifies it.
A global variable lasts for the duration of the program, and therefore, anyone can use the variable, either to read it, or even worse, to change its value, making it more difficult to know what value the variable will have at any given program point. .
Another problem is the order of destruction. Variables are always destroyed in reverse order of their creation, whether they are local or global / static variables (an exception is the primitive types, int
,enum
s, etc., which are never destroyed if they are global / static until they end the program).
The problem is that it is difficult to know the order of construction of the global (or static) variables. In principle, it is indeterminate.
If all your global / static variables are in a single compilation unit (that is, you only have a .cpp
), then the order of construction is the same as the writing one (that is, variables defined before, are built before).
But if you have more than one .cpp
each with its own global / static variables, the global construction order is indeterminate. Of course, the order in each compilation unit (each .cpp
) in particular, is respected: if the global variableA
is defined before B
,A
will be built before B
, but It is possible that between A
andB
variables of other .cpp
are initialized. For example, if you have three units with the following global / static variables:
In the executable it could be created in this order (or in any other order as long as the relative order is respected within each .cpp
):
Why is this important? Because if there are relations between different static global objects, for example, that some use others in their destructors, perhaps, in the destructor of a global variable, you use another global object from another compilation unit that turns out to be already destroyed ( have been built later).
I tried to find the source that I will use in this example, but I can not find it (anyway, it was to exemplify the use of singletons, although the example is applicable to global and static variables). Hidden dependencies also create new problems related to controlling the behavior of an object, if it depends on the state of a global variable.
Imagine you have a payment system, and you want to test it to see how it works, since you need to make changes, and the code is from another person (or yours, but from a few years ago). You open a new main
, and you call the corresponding function of your global object that provides a bank payment service with a card, and it turns out that you enter your data and they charge you. How, in a simple test, have I used a production version? How can I do a simple payment test?
After asking other co-workers, it turns out that you have to "mark true", a global bool that indicates whether we are in test mode or not, before beginning the collection process. Your object that provides the payment service depends on another object that provides the mode of payment, and that dependency occurs in an invisible way for the programmer.
In other words, the global variables (or singletones), make it impossible to pass to "test mode", since global variables can not be replaced by "testing" instances (unless you modify the code where said code is created or defined). global variable, but we assume that the tests are done without modifying the mother code).
This is solved by means of what is called * dependency injection *, which consists in passing as a parameter all the dependencies that an object needs in its constructor or in the corresponding method. In this way, the programmer ** sees ** what has to happen to him, since he has to write it in code, making the developers gain a lot of time.
If there are too many global objects, and there are too many parameters in the functions that need them, you can always group your "global objects" into a class, style * factory *, that builds and returns the instance of the "global object" (simulated) that you want , passing the factory as a parameter to the objects that need the global object as dependence.
If you pass to test mode, you can always create a testing factory (which returns different versions of the same objects), and pass it as a parameter without having to modify the target class.
Not necessarily, there may be good uses for global variables. For example, constant values ??(the PI value). Being a constant value, there is no risk of not knowing its value at a given point in the program by any type of modification from another module. In addition, constant values ??tend to be primitive and are unlikely to change their definition.
It is more convenient, in this case, to use global variables to avoid having to pass the variables as parameters, simplifying the signatures of the functions.
Another can be non-intrusive "global" services, such as a logging class (saving what happens in a file, which is usually optional and configurable in a program, and therefore does not affect the application's nuclear behavior), or std :: cout
,std :: cin
or std :: cerr
, which are also global objects.
Any other thing, even if its life time coincides almost with that of the program, always pass it as a parameter. Even the variable could be global in a module, only in it without any other having access, but that, in any case, the dependencies are always present as parameters.
Answer by: Peregring-lk
The same answer as @Richard W but for Windows (PowerShell)
git tag | foreach-object -process { git tag -d $_ }
git fetch -t
Your question is missing most of the necessary information, so I'm going to make some assumptions:
The answer would be:
=IF(COUNTBLANK(F16:G16)<>2,H15+G16-F16,"")
COUNTBLANK
tells you how many cells are unfilled or set to "".
IF
lets you conditionally do one of two things based on whether the first statement is true or false. The second comma separated argument is what to do if it's true, the third comma separated argument is what to do if it's false.
<>
means "not equal to".
The equation says that if the number of blank cells in the range F16:G16
(your credit and debit cells) is not 2, which means both aren't blank, then calculate the equation you provided in your question. Otherwise set the cell to blank(""
).
When you copy this equation to new cells in column H other than H16
, it will update the row references so the proper rows for the credit and debit amounts are looked at.
CAVEAT: This equation is useful if you are just adding entries for credits and debits to the end of a list and want the running total to update automatically. You'd fill this equation down to some arbitrary long length well past the end of actual data. You wouldn't see the running total past the end of the credit/debit entries then, it would just be blank until you filled in a new credit/debit entry. If you left a blank row in your credit debit entries though, the reference to the previous total, H15
, would report blank, which is treated like a 0 in this case.
Now you don't need to add the public
to the methods to test then.
On newer versions of Swift it's only necessary to add the @testable
keyword.
PrimeNumberModelTests.swift
import XCTest
@testable import MyProject
class PrimeNumberModelTests: XCTestCase {
let testObject = PrimeNumberModel()
}
And your internal methods can keep Internal
PrimeNumberModel.swift
import Foundation
class PrimeNumberModel {
init() {
}
}
Note that private
(and fileprivate
) symbols are not available even with using @testable
.
There are two relevant concepts from Swift here (As Xcode 6 beta 6).
Internal access
Considering that tests are on another target on PrimeNumberModelTests.swift
you need to import
the target that contains the class that you want to test, if your target is called MyProject
will need to add import MyProject
to the PrimeNumberModelTests
:
PrimeNumberModelTests.swift
import XCTest
import MyProject
class PrimeNumberModelTests: XCTestCase {
let testObject = PrimeNumberModel()
}
But this is not enough to test your class PrimeNumberModel
, since the default Access Control level is Internal Access
, your class won't be visible to the test bundle, so you need to make it Public Access
and all the methods that you want to test:
PrimeNumberModel.swift
import Foundation
public class PrimeNumberModel {
public init() {
}
}
I've used this with Jackson 2.x and Spring 3.1.2+
servlet-context.xml:
Note that the root element is <beans:beans>
, so you may need to remove beans
and add mvc
to some of these elements depending on your setup.
<annotation-driven>
<message-converters>
<beans:bean
class="org.springframework.http.converter.StringHttpMessageConverter" />
<beans:bean
class="org.springframework.http.converter.ResourceHttpMessageConverter" />
<beans:bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<beans:property name="objectMapper" ref="jacksonObjectMapper" />
</beans:bean>
</message-converters>
</annotation-driven>
<beans:bean id="jacksonObjectMapper"
class="au.edu.unimelb.atcom.transfer.json.mappers.JSONMapper" />
au.edu.unimelb.atcom.transfer.json.mappers.JSONMapper.java:
public class JSONMapper extends ObjectMapper {
public JSONMapper() {
SimpleModule module = new SimpleModule("JSONModule", new Version(2, 0, 0, null, null, null));
module.addSerializer(Date.class, new DateSerializer());
module.addDeserializer(Date.class, new DateDeserializer());
// Add more here ...
registerModule(module);
}
}
DateSerializer.java:
public class DateSerializer extends StdSerializer<Date> {
public DateSerializer() {
super(Date.class);
}
@Override
public void serialize(Date date, JsonGenerator json,
SerializerProvider provider) throws IOException,
JsonGenerationException {
// The client side will handle presentation, we just want it accurate
DateFormat df = StdDateFormat.getBlueprintISO8601Format();
String out = df.format(date);
json.writeString(out);
}
}
DateDeserializer.java:
public class DateDeserializer extends StdDeserializer<Date> {
public DateDeserializer() {
super(Date.class);
}
@Override
public Date deserialize(JsonParser json, DeserializationContext context)
throws IOException, JsonProcessingException {
try {
DateFormat df = StdDateFormat.getBlueprintISO8601Format();
return df.parse(json.getText());
} catch (ParseException e) {
return null;
}
}
}
it is just that add below code in the index.html head tag
<html>
<head>
<base href="/">
...
that worked like a charm for me.
You could install Cygwin (http://www.cygwin.com/) and use sed from there.
$("#closeLink").click(closeIt);
Let's say you want to call your function passing some args to it i.e., closeIt(1, false)
. Then, you should build an anonymous function and call closeIt
from it.
$("#closeLink").click(function() {
closeIt(1, false);
});
You can use something like componentDidUpdate
componentDidUpdate() {
var elem = testNode //your ref to the element say testNode in your case;
elem.scrollTop = elem.scrollHeight;
};
You can set the state of the checkbox based on the value:
$('#your-checkbox').prop('checked', value == 1);
I have just found this site – http://unused-css.com/
Looks good but I would need to thoroughly check its outputted 'clean' css before uploading it to any of my sites.
Also as with all these tools I would need to check it didn't strip id's and classes with no style but are used as JavaScript selectors.
The below content is taken from http://unused-css.com/ so credit to them for recommending other solutions:
Latish Sehgal has written a windows application to find and remove unused CSS classes. I haven't tested it but from the description, you have to provide the path of your html files and one CSS file. The program will then list the unused CSS selectors. From the screenshot, it looks like there is no way to export this list or download a new clean CSS file. It also looks like the service is limited to one CSS file. If you have multiple files you want to clean, you have to clean them one by one.
Dust-Me Selectors is a Firefox extension (for v1.5 or later) that finds unused CSS selectors. It extracts all the selectors from all the stylesheets on the page you're viewing, then analyzes that page to see which of those selectors are not used. The data is then stored so that when testing subsequent pages, selectors can be crossed off the list as they're encountered. This tool is supposed to be able to spider a whole website but I unfortunately could make it work. Also, I don't believe you can configure and download the CSS file with the styles removed.
Topstyle is a windows application including a bunch of tools to edit CSS. I haven't tested it much but it looks like it has the ability to removed unused CSS selectors. This software costs 80 USD.
Liquidcity CSS cleaner is a php script that uses regular expressions to check the styles of one page. It will tell you the classes that aren't available in the HTML code. I haven't tested this solution.
Deadweight is a CSS coverage tool. Given a set of stylesheets and a set of URLs, it determines which selectors are actually used and lists which can be "safely" deleted. This tool is a ruby module and will only work with rails website. The unused selectors have to be manually removed from the CSS file.
Helium CSS is a javascript tool for discovering unused CSS across many pages on a web site. You first have to install the javascript file to the page you want to test. Then, you have to call a helium function to start the cleaning.
UnusedCSS.com is web application with an easy to use interface. Type the url of a site and you will get a list of CSS selectors. For each selector, a number indicates how many times a selector is used. This service has a few limitations. The @import statement is not supported. You can't configure and download the new clean CSS file.
CSSESS is a bookmarklet that helps you find unused CSS selectors on any site. This tool is pretty easy to use but it won't let you configure and download clean CSS files. It will only list unused CSS files.
You can use strcpy
but remember to end the array with '\0'
char array[20]; char string[100];
array[0]='1'; array[1]='7'; array[2]='8'; array[3]='.'; array[4]='9'; array[5]='\0';
strcpy(string, array);
printf("%s\n", string);
Here's a detailed explanation about the calculation of MaxClients and MaxRequestsPerChild
ServerLimit 16
StartServers 2
MaxClients 200
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
First of all, whenever an apache is started, it will start 2 child processes which is determined by StartServers
parameter. Then each process will start 25 threads determined by ThreadsPerChild
parameter so this means 2 process can service only 50 concurrent connections/clients i.e. 25x2=50. Now if more concurrent users comes, then another child process will start, that can service another 25 users. But how many child processes can be started is controlled by ServerLimit
parameter, this means that in the configuration above, I can have 16 child processes in total, with each child process can handle 25 thread, in total handling 16x25=400 concurrent users. But if number defined in MaxClients
is less which is 200 here, then this means that after 8 child processes, no extra process will start since we have defined an upper cap of MaxClients
. This also means that if I set MaxClients
to 1000, after 16 child processes and 400 connections, no extra process will start and we cannot service more than 400 concurrent clients even if we have increase the MaxClient
parameter. In this case, we need to also increase ServerLimit
to 1000/25 i.e. MaxClients/ThreadsPerChild=40
So this is the optmized configuration to server 1000 clients
<IfModule mpm_worker_module>
ServerLimit 40
StartServers 2
MaxClients 1000
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestsPerChild 0
</IfModule>
@Html.ActionLink("linkText", "Action", new {controller="Controller"}, new {target="_blank",@class="edit"})
script below will open the action view url in a new window
<script type="text/javascript">
$(function (){
$('a.edit').click(function () {
var url = $(this).attr('href');
window.open(url, "popupWindow", "width=600,height=800,scrollbars=yes");
});
return false;
});
</script>
If you deploy your application in Apache (Linux server) so you can follow following steps : Follow following steps :
Step 1:
ng build --prod --env=prod
Step 2. (Copy dist into server) then dist folder created, copy dist folder and deploy it in root directory of server.
Step 3. Creates .htaccess
file in root folder and paste this in the .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
It looks like you are trying to use (almost) straight up C code here. Go has a few differences.
const
. The term const
has a different meaning in Go, as it does in C. The list should be defined as var
instead.basenameOpts
as opposed to basename_opts
.char
type in Go. You probably want byte
(or rune
if you intend to allow unicode codepoints).var x = foo
.For example:
type opt struct {
shortnm byte
longnm, help string
needArg bool
}
var basenameOpts = []opt {
opt {
shortnm: 'a',
longnm: "multiple",
needArg: false,
help: "Usage for a",
},
opt {
shortnm: 'b',
longnm: "b-option",
needArg: false,
help: "Usage for b",
},
}
An alternative is to declare the list with its type and then use an init
function to fill it up. This is mostly useful if you intend to use values returned by functions in the data structure. init
functions are run when the program is being initialized and are guaranteed to finish before main
is executed. You can have multiple init
functions in a package, or even in the same source file.
type opt struct {
shortnm byte
longnm, help string
needArg bool
}
var basenameOpts []opt
func init() {
basenameOpts = []opt{
opt {
shortnm: 'a',
longnm: "multiple",
needArg: false,
help: "Usage for a",
},
opt {
shortnm: 'b',
longnm: "b-option",
needArg: false,
help: "Usage for b",
},
}
}
Since you are new to Go, I strongly recommend reading through the language specification. It is pretty short and very clearly written. It will clear a lot of these little idiosyncrasies up for you.
Today, I have used this feature, so here's my very fresh real-life example. (I have changed class and method names to generic ones so they won't distract from the actual point.)
I have a method that's meant to accept a Set
of A
objects that I originally wrote with this signature:
void myMethod(Set<A> set)
But it want to actually call it with Set
s of subclasses of A
. But this is not allowed! (The reason for that is, myMethod
could add objects to set
that are of type A
, but not of the subtype that set
's objects are declared to be at the caller's site. So this could break the type system if it were possible.)
Now here come generics to the rescue, because it works as intended if I use this method signature instead:
<T extends A> void myMethod(Set<T> set)
or shorter, if you don't need to use the actual type in the method body:
void myMethod(Set<? extends A> set)
This way, set
's type becomes a collection of objects of the actual subtype of A
, so it becomes possible to use this with subclasses without endangering the type system.
You can also use:
p::before {
content: "";
padding-left: 30px;
}
And replace "p" with any other selector you have in mind.
This is an old question, but I found that when you create a string like this:
<string name="newline_test">My
New line test</string>
The output in your app will be like this (no newline)
My New line test
When you put the string in quotation marks
<string name="newline_test">"My
New line test"</string>
the newline will appear:
My
New line test
Wrote one up myself:
let regex = /([\w+]+\:\/\/)?([\w\d-]+\.)*[\w-]+[\.\:]\w+([\/\?\=\&\#\.]?[\w-]+)*\/?/gm
It works on ALL of the following domains:
https://www.facebook.com
https://app-1.number123.com
http://facebook.com
ftp://facebook.com
http://localhost:3000
localhost:3000/
unitedkingdomurl.co.uk
this.is.a.url.com/its/still=going?wow
shop.facebook.org
app.number123.com
app1.number123.com
app-1.numbEr123.com
app.dashes-dash.com
www.facebook.com
facebook.com
fb.com/hello_123
fb.com/hel-lo
fb.com/hello/goodbye
fb.com/hello/goodbye?okay
fb.com/hello/goodbye?okay=alright
Hello www.google.com World http://yahoo.com
https://www.google.com.tr/admin/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
https://google.com.tr/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
http://google.com/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
ftp://google.com/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
www.google.com.tr/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
www.google.com/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
drive.google.com/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
https://www.example.pl
http://www.example.com
www.example.pl
example.com
http://blog.example.com
http://www.example.com/product
http://www.example.com/products?id=1&page=2
http://www.example.com#up
http://255.255.255.255
255.255.255.255
shop.facebook.org/derf.html
You can see how it performs here on regex101 and adjust as needed
This worked for me. I am using SQL Developer with Oracle DB:
ALTER TABLE YOUR_TABLE
ADD Date_Created TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL;
On our site we have pages where the content is static, and pages where it is loaded in with AJAX. On one page (a search page), there were cases when the AJAX results would more than fill the page, and cases where it would return no results. In order for the background image to fill the page in all cases we had to apply the following CSS:
html {
margin: 0px;
height: 100%;
width: 100%;
}
body {
margin: 0px;
min-height: 100%;
width: 100%;
}
height
for the html
and min-height
for the body
.
I solved this, without having to completely reinstall Visual Studio 2013.
For those who may come across this in the future, the following steps worked for me:
vs_professional.exe
).If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3
Click the link for 'examine the log file' and look near the bottom of the log, for this line:
open regedit.exe
and do an Edit > Find...
for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
. This was found in:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
Edit the BundleVersion
value and change it to a lower version. I changed mine from 12.0.21005.13
to 12.0.21000.13
:
Exit the registry
Run the ISO (or vs_professional.exe
) again. If it has a repair button like the image below, you can skip to step 4.
Run the ISO (or vs_professional.exe
) again. This time repair should be visible.
Click Repair
and let it update your installation and apply its embedded license key. This took about 20 minutes.
Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product
:
Hope this helps somebody in the future!
This should solve your problem, you should try to run the following below:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Editing Windows registries is not worth it and not safe, use Map network drive
and load the network share as if it's loaded from one of your local drives.
The base64 encoding of Content-Type: multipart/form-data
adds an extra 33% overhead. If the server supports it, it is more efficient to send the files directly:
$http.post
Requests Directly from a FileList$scope.upload = function(url, fileList) {
var config = {
headers: { 'Content-Type': undefined },
transformResponse: angular.identity
};
var promises = fileList.map(function(file) {
return $http.post(url, file, config);
});
return $q.all(promises);
};
When sending a POST with a File object, it is important to set 'Content-Type': undefined
. The XHR send method will then detect the File object and automatically set the content type.
ng-model
1The <input type=file>
element does not by default work with the ng-model directive. It needs a custom directive:
angular.module("app",[]);
angular.module("app").directive("selectNgFiles", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<h1>AngularJS Input `type=file` Demo</h1>
<input type="file" select-ng-files ng-model="fileList" multiple>
<h2>Files</h2>
<div ng-repeat="file in fileList">
{{file.name}}
</div>
</body>
_x000D_
if your using jellybean just start cmd, type adb devices to make sure your readable, type adb pull sdcard/ sdcard_(the date or extra) <---this file needs to be made in adb directory beforehand. PROFIT!
In other versions type adb pull mnt/sdcard/ sdcard_(the date or extra)
Remember to make file or your either gonna have a mess or it wont work.
This is an old questions with old answers. I wanted to add a new look at this problem and to answer why is this happens and not why is this useful.
So you have two functions:
var f1 = function () {
setTimeout(function(){
console.log("f1", "First function call...");
}, 0);
};
var f2 = function () {
console.log("f2", "Second call...");
};
and then call them in the following order f1(); f2();
just to see that the second one executed first.
And here is why: it is not possible to have setTimeout
with a time delay of 0 milliseconds. The Minimum value is determined by the browser and it is not 0 milliseconds. Historically browsers sets this minimum to 10 milliseconds, but the HTML5 specs and modern browsers have it set at 4 milliseconds.
If nesting level is greater than 5, and timeout is less than 4, then increase timeout to 4.
Also from mozilla:
To implement a 0 ms timeout in a modern browser, you can use window.postMessage() as described here.
P.S. information is taken after reading the following article.
The data from the request (content, inputs, files, querystring values) is all on this object HttpContext.Current.Request
To read the posted content
StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
string requestFromPost = reader.ReadToEnd();
To navigate through the all inputs
foreach (string key in HttpContext.Current.Request.Form.AllKeys)
{
string value = HttpContext.Current.Request.Form[key];
}
A workaround of mine is to manipulate a model variable just for the ng-class toggling:
For example, I want to toggle class according to the state of my list:
1) Whenever my list is empty, I update my model:
$scope.extract = function(removeItemId) {
$scope.list= jQuery.grep($scope.list, function(item){return item.id != removeItemId});
if (!$scope.list.length) {
$scope.liststate = "empty";
}
}
2) Whenever my list is not empty, I set another state
$scope.extract = function(item) {
$scope.list.push(item);
$scope.liststate = "notempty";
}
3) When my list is not ever touched, I want to give another class (this is where the page is initiated):
$scope.liststate = "init";
3) I use this additional model on my ng-class:
ng-class="{'bg-empty': liststate == 'empty', 'bg-notempty': liststate == 'notempty', 'bg-init': liststate = 'init'}"
An NDF file is a user defined secondary database file of Microsoft SQL Server with an extension .ndf, which store user data. Moreover, when the size of the database file growing automatically from its specified size, you can use .ndf file for extra storage and the .ndf file could be stored on a separate disk drive. Every NDF file uses the same filename as its corresponding MDF file. We cannot open an .ndf file in SQL Server Without attaching its associated .mdf file.
Editing VM Configuration worked for me.
-Djava.util.Arrays.useLegacyMergeSort=true
There are 3 access specifiers
for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:
Public - The members declared as Public are accessible from outside the Class through an object of the class.
Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.
Private - These members are only accessible from within the class. No outside Access is allowed.
An Source Code Example:
class MyClass
{
public:
int a;
protected:
int b;
private:
int c;
};
int main()
{
MyClass obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, gives compiler error
obj.c = 30; //Not Allowed, gives compiler error
}
Inheritance in C++ can be one of the following types:
Private
Inheritance Public
Inheritance Protected
inheritance Here are the member access rules with respect to each of these:
First and most important rule
Private
members of a class are never accessible from anywhere except the members of the same class.
All
Public
members of the Base Class becomePublic
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.
Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:public Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomePrivate
Members of the Derived class &
AllProtected
members of the Base Class becomePrivate
Members of the Derived Class.
An code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:private Base //Not mentioning private is OK because for classes it defaults to private
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Not Allowed, Compiler Error, a is private member of Derived now
b = 20; //Not Allowed, Compiler Error, b is private member of Derived now
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomeProtected
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
A Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:protected Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2
b = 20; //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
Remember the same access rules apply to the classes and members down the inheritance hierarchy.
- Access Specification is per-Class not per-Object
Note that the access specification C++ work on per-Class basis and not per-object basis.
A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed.
- A Derived class can only access members of its own Base class
Consider the following code example:
class Myclass
{
protected:
int x;
};
class derived : public Myclass
{
public:
void f( Myclass& obj )
{
obj.x = 5;
}
};
int main()
{
return 0;
}
It gives an compilation error:
prog.cpp:4: error: ‘int Myclass::x’ is protected
Because the derived class can only access members of its own Base Class. Note that the object obj
being passed here is no way related to the derived
class function in which it is being accessed, it is an altogether different object and hence derived
member function cannot access its members.
friend
? How does friend
affect access specification rules?You can declare a function or class as friend
of another class. When you do so the access specification rules do not apply to the friend
ed class/function. The class or function can access all the members of that particular class.
So do
friend
s break Encapsulation?
No they don't, On the contrary they enhance Encapsulation!
friend
ship is used to indicate a intentional strong coupling between two entities.
If there exists a special relationship between two entities such that one needs access to others private
or protected
members but You do not want everyone to have access by using the public
access specifier then you should use friend
ship.
Slightly better version of the unique2 suggestion is below:
insert overwrite table target_table
select * from
(
select stack(
3, # generating new table with 3 records
'John', 80, # record_1
'Bill', 61 # record_2
'Martha', 101 # record_3
)
) s;
Which does not require the hack with using an already exiting table.
Just install the server certificate in the client's trusted root certificates container (if certified it's expired may not work). For further details see this post of similar question.
<?php
// Custom PHP MySQL Pagination Tutorial and Script
// You have to put your mysql connection data and alter the SQL queries(both queries)
mysql_connect("DATABASE_Host_Here","DATABASE_Username_Here","DATABASE_Password_Here") or die (mysql_error());
mysql_select_db("DATABASE_Name_Here") or die (mysql_error());
////////////// QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
$sql = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC");
//////////////////////////////////// Pagination Logic ////////////////////////////////////////////////////////////////////////
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
$pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
//$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
$pn = 1;
}
//This is where we set how many database items to show on each page
$itemsPerPage = 10;
// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
$pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
$pn = $lastPage; // force it to be $lastpage's value
}
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
} else if ($pn == $lastPage) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> ';
} else if ($pn > 1 && $pn < $lastPage) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
}
// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC $limit");
//////////////////////////////// END Pagination Logic ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Pagination Display Setup /////////////////////////////////////////////////////////////////////
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1"){
// This shows the user what page they are on, and the total number of pages
$paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. ' ';
// If we are not on page 1 we can place the Back button
if ($pn != 1) {
$previous = $pn - 1;
$paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
}
// Lay in the clickable numbers display here between the Back and Next links
$paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
// If we are not on the very last page we can place the Next button
if ($pn != $lastPage) {
$nextPage = $pn + 1;
$paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
}
}
///////////////////////////////////// END Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
// Build the Output Section Here
$outputList = '';
while($row = mysql_fetch_array($sql2)){
$id = $row["id"];
$firstname = $row["firstname"];
$country = $row["country"];
$outputList .= '<h1>' . $firstname . '</h1><h2>' . $country . ' </h2><hr />';
} // close while loop
?>
<html>
<head>
<title>Simple Pagination</title>
</head>
<body>
<div style="margin-left:64px; margin-right:64px;">
<h2>Total Items: <?php echo $nr; ?></h2>
</div>
<div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
<div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
<div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
</body>
</html>
Python 3.9 math
module's gcd
and lcm
support over a list of numbers.
import math
lst = [1,2,3,4,5,6,7,8,9]
print(math.lcm(*lst))
print(math.gcd(*lst))
To illustrate the preceding answers, here a quick JSFiddle snippet :
function test () {_x000D_
console.log()_x000D_
_x000D_
}_x000D_
_x000D_
console.log(typeof test) // >> "function"_x000D_
_x000D_
// implicit test, in javascript if an entity exist it returns implcitly true unless the element value is false as :_x000D_
// var test = false_x000D_
if(test){ console.log(true)}_x000D_
else{console.log(false)}_x000D_
_x000D_
// test by the typeof method_x000D_
if( typeof test === "function"){ console.log(true)}_x000D_
else{console.log(false)}_x000D_
_x000D_
_x000D_
// confirm that the test is effective : _x000D_
// - entity with false value_x000D_
var test2 = false_x000D_
if(test2){ console.log(true)}_x000D_
else{console.log(false)}_x000D_
_x000D_
// confirm that the test is effective :_x000D_
// - typeof entity_x000D_
if( typeof test ==="foo"){ console.log(true)}_x000D_
else{console.log(false)}_x000D_
_x000D_
/* Expected :_x000D_
function_x000D_
true _x000D_
true _x000D_
false_x000D_
false_x000D_
*/
_x000D_
Check installation of python 2.7 than install/reinstall pip which described here than open command line and write
pip install numpy
or
pip install scipy
if already installed try this
pip install -U numpy
Easiest way is to do this from your accounts with Xcode:
Head over Xcode -> Preferences -> Choose Accounts Tab -> View Details -> Hit refresh button on the bottom left -> Done.
Build again and it should work.
Actually a much better (GUI) solution is to copy the Eclipse.app to e.g. Eclipse2.app and you'll have two Eclipse icons in Dock as well as Eclipse2 in Spotlight. Repeat as necessary.
It's relative to the CSS file.
Perhaps use information_schema:
SELECT EXISTS(
SELECT *
FROM information_schema.tables
WHERE
table_schema = 'company3' AND
table_name = 'tableincompany3schema'
);
Okay, how about a CSS answer! We use display: table
. Then each of the divs are rows, and finally we apply height of 100% to middle 'row' and voilà.
body { display: table; }
div { display: table-row; }
#content {
width:450px;
margin:0 auto;
text-align: center;
background-color: blue;
color: white;
height: 100%;
}
Two answers, both valid, depending on how sloppy you like to be:
1) No, it's not currently possible to inject audio into a phone conversation.
2) Yes, it's possible. It's also an ugly, ugly kludge. Turn on the hands free function of your phone. Create a media player, set the media source, set the volume to 1.0f (highest) and call player.start()
. If the microphone and speakers on the phone are of reasonable quality, the other party to the call will hear the music. He or she will also continue to hear anything you say, as well as ambient and other sounds in your immediate vicinity.
If you're targeting Android 6.0 - Marshmallow (API level 23) or higher it's possible to use the new NetworkCapabilities class, i.e:
public static boolean hasInternetConnection(final Context context) {
final ConnectivityManager connectivityManager = (ConnectivityManager)context.
getSystemService(Context.CONNECTIVITY_SERVICE);
final Network network = connectivityManager.getActiveNetwork();
final NetworkCapabilities capabilities = connectivityManager
.getNetworkCapabilities(network);
return capabilities != null
&& capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
}
Also in the many IDEs now, ex: VSC, you can install an extension for AWS and simply click upload from there, no effort of typing all those commands + region.
Here's an example:
Here are a couple of quick functions I use when bash scripting Kafka Data Load into Demo Environments. In this example I use HDP with no security, but it is easily modified to other environments and intended to be quick and functional rather than particularly robust.
The first retrieves the address of the first ZooKeeper node from the config:
ZKS1=$(cat /usr/hdp/current/zookeeper-client/conf/zoo.cfg | grep server.1)
[[ ${ZKS1} =~ server.1=(.*?):[0-9]*:[0-9]* ]]
export ZKADDR=${BASH_REMATCH[1]}:2181
echo "using ZooKeeper Server $ZKADDR"
The second retrieves the Broker IDs from ZooKeeper:
echo "Fetching list of Kafka Brokers"
export BROKERIDS=$(/usr/hdp/current/kafka-broker/bin/zookeeper-shell.sh ${ZKADDR} <<< 'ls /brokers/ids' | tail -1)
export BROKERIDS=${BROKERIDS//[!0-9 ]/}
echo "Found Kafka Broker IDS: $BROKERIDS"
The third parses ZooKeeper again to retrieve the list of Kafka Brokers Host:port ready for use in the command-line client:
unset BROKERS
for i in $BROKERIDS
do
DETAIL=$(/usr/hdp/current/kafka-broker/bin/zookeeper-shell.sh ${ZKADDR} <<< "get /brokers/ids/$i")
[[ $DETAIL =~ PLAINTEXT:\/\/(.*?)\"\] ]]
if [ -z ${BROKERS+x} ]; then BROKERS=${BASH_REMATCH[1]}; else
BROKERS="${BROKERS},${BASH_REMATCH[1]}"; fi
done
echo "Found Brokerlist: $BROKERS"
You can use `` quotes (wich are below Esc button) with ES6. So you can write something like this:
var text = `fjskdfjslfjsl
skfjslfkjsldfjslfjs
jfsfkjslfsljs`;
This error comes because compile does not know where to find the class..so it occurs mainly when u copy or import item ..to solve this .. 1.change the namespace in the formname.cs and formname.designer.cs to the name of your project .
If you really want to use the DEGREE CELSIUS character “?”, then copy and paste is OK, provided that your document is UTF-8 encoded and declared as such in HTTP headers. Using the character reference ℃
would work equally well, and would work independently of character encoding, but the source would be much less readable.
The problem with Blackberry is most probably a font issue. I don’t know about fonts on Blackberry, but the font repertoire might be limited. There’s nothing you can do about this in HTML, but you can use CSS, possibly with @font face
.
But there is seldom any reason to use the DEGREE CELSIUS. It is a compatibility character, included in Unicode due to its use in East Asian writing. The Unicode Standard explicitly says in Chapter 15 (section 15.2, page 497):
“In normal use, it is better to represent degrees Celsius “°C” with a sequence of U+00B0 degree sign + U+0043 latin capital letter c, rather than U+2103 degree celsius.”
The degree sign “°” can be entered in many ways, including the entity reference `°, but normally it is best to insert it as a character, via copy and paste or otherwise. On Windows, you can use Alt 0176.
Caveat: Some browsers may treat the degree sign as allowing a line break after it even when no space intervenes, putting “°” and the following “C” on separate lines. There are different ways to prevent this. A simple and effective method is this: <nobr>42 °C</nobr>
.
The only problem with threads is accessing the same object from different threads without synchronization.
If each function only uses parameters for reading and local variables, they don't need any synchronization to be thread-safe.
json.loads
take a string as input and returns a dictionary as output.
json.dumps
take a dictionary as input and returns a string as output.
With json.loads({"('Hello',)": 6, "('Hi',)": 5})
,
You are calling json.loads
with a dictionary as input.
You can fix it as follows (though I'm not quite sure what's the point of that):
d1 = {"('Hello',)": 6, "('Hi',)": 5}
s1 = json.dumps(d1)
d2 = json.loads(s1)
The values are determined by the bit of the image. 8 bit 0 to 255
16 bit...some ridiculous number..0 to 65,000 approx.
32 bit are 0 to 1
I use .004 with 32 bit images...this gives 1.02 as a result when multiplied by 255
You can create your getValue function with the following code:
bool getValue(const std::map<int, Bar>& input, int key, Bar& out)
{
std::map<int, Bar>::iterator foundIter = input.find(key);
if (foundIter != input.end())
{
out = foundIter->second;
return true;
}
return false;
}
If you select the input by the id and then add the input[readonly="readonly"]
tag in the css, something like:
#inputID input[readonly="readonly"] {
background-color: #000000;
}
That will not work. You have to select a parent class or id an then the input. Something like:
.parentClass, #parentID input[readonly="readonly"] {
background-color: #000000;
}
My 2 cents while waiting for new tickets at work :D
<script type="text/javascript">
$(function() {
$("#datepicker").datepicker({
onSelect: function(value, date) {
window.location = 'day.jsp' ;
}
});
});
</script>
<div id="datepicker"></div>
I think you can try this .It works fine .
I solved same issue by adding polyfill following:
<script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=default,Array.prototype.includes,Array.prototype.find"></script>
A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it.
Hope someone find this helpful.
Select
is used for projecting some or all fields of a dataframe
. It won't give you an value
as an output but a new dataframe
. Its a transformation
.
I'm using Eclipse Europa, which also has the Favorite preference section:
Window > Preferences > Java > Editor > Content Assist > Favorites
In mine, I have the following entries (when adding, use "New Type" and omit the .*
):
org.hamcrest.Matchers.*
org.hamcrest.CoreMatchers.*
org.junit.*
org.junit.Assert.*
org.junit.Assume.*
org.junit.matchers.JUnitMatchers.*
All but the third of those are static imports. By having those as favorites, if I type "assertT
" and hit Ctrl+Space, Eclipse offers up assertThat
as a suggestion, and if I pick it, it will add the proper static import to the file.
<a href="#Foo" onclick="return runMyFunction();">Do it!</a>
and
function runMyFunction() {
//code
return true;
}
This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.
probably old credentials are invalid
see the answer below
or short names may work
see the answer below stackoverflow answer
or product name same as project name as answered already
at times one may include extra space in the
check twice this line so that you are redirected to the correct url
You could run it without the -jar
command line argument if you happen to know the name of the main class you wish to run:
java -classpath .;myjar.jar;lib/referenced-class.jar my.package.MainClass
If perchance you are using linux, you should use ":" instead of ";" in the classpath.
Use the str
accessor with square brackets:
df['col'] = df['col'].str[:9]
Or str.slice:
df['col'] = df['col'].str.slice(0, 9)
The specificity is calculated based on the amount of id, class and tag selectors in your rule. Id has the highest specificity, then class, then tag. Your first rule is now more specific than the second one, since they both have a class selector, but the first one also has two tag selectors.
To make the second one override the first one, you can make more specific by adding information of it's parents:
table.rule1 tr td.rule2 {
background-color: #ffff00;
}
Here is a nice article for more information on selector precedence.
If /home/smith/Desktop/Test/../
is what you want:
dirname 'path/to/child/dir'
as seen here.
To find a div
of a certain class that contains a span
at any depth containing certain text, try:
//div[contains(@class, 'measure-tab') and contains(.//span, 'someText')]
That said, this solution looks extremely fragile. If the table happens to contain a span
with the text you're looking for, the div
containing the table will be matched, too. I'd suggest to find a more robust way of filtering the elements. For example by using IDs or top-level document structure.
Yes you need to use overlays.
You need to get the MapView's overlays and add your new overlay onto it.
Your class extends Overlay, which is a transparent canvas in which you can draw on it like any other canvas.
You can use mapView.getProjection() to get projection of map view.
...
More info found here: http://blogoscoped.com/archive/2008-12-15-n14.html
Swift 3
Time format 24 hours to 12 hours
let dateAsString = "13:15"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "h:mm a"
let Date12 = dateFormatter.string(from: date!)
print("12 hour formatted Date:",Date12)
output will be 12 hour formatted Date: 1:15 PM
Time format 12 hours to 24 hours
let dateAsString = "1:15 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "HH:mm"
let Date24 = dateFormatter.string(from: date!)
print("24 hour formatted Date:",Date24)
output will be 24 hour formatted Date: 13:15
There is no DrawCircle
method; use DrawEllipse
instead. I have a static class with handy graphics extension methods. The following ones draw and fill circles. They are wrappers around DrawEllipse
and FillEllipse
:
public static class GraphicsExtensions
{
public static void DrawCircle(this Graphics g, Pen pen,
float centerX, float centerY, float radius)
{
g.DrawEllipse(pen, centerX - radius, centerY - radius,
radius + radius, radius + radius);
}
public static void FillCircle(this Graphics g, Brush brush,
float centerX, float centerY, float radius)
{
g.FillEllipse(brush, centerX - radius, centerY - radius,
radius + radius, radius + radius);
}
}
You can call them like this:
g.FillCircle(myBrush, centerX, centerY, radius);
g.DrawCircle(myPen, centerX, centerY, radius);
Generators? Recursion? Why so much hatin' on mutatin'? ;-)
If it is acceptable as long as we "hide" it, then just accept the use of a unary operator and we can keep things simple:
Number.prototype.times = function(f) { let n=0 ; while(this.valueOf() > n) f(n++) }
Just like in ruby:
> (3).times(console.log)
0
1
2
This might help someone.
With a little of javascript you can search for all datetime-local inputs, search if the year the user is trying to input, greater that 100 years in the future:
$('input[type=datetime-local]').each(function( index ) {
$(this).change(function() {
var today = new Date();
var date = new Date(this.value);
var yearFuture = new Date();
yearFuture.setFullYear(yearFuture.getFullYear()+100);
if(date.getFullYear() > yearFuture.getFullYear()) {
this.value = today.getFullYear() + this.value.slice(4);
}
})
});
I get a better tips to get non-duplicate entries in a file
awk '$0 != x ":FOO" && NR>1 {print x} {x=$0} END {print}' file_name | uniq -f1 -u
An alternative would be add the public half of the user's key to the authorized-keys file on the target system. On the system you are initiating the transfer from, you can run an ssh-agent daemon and add the private half of the key to the agent. The batch job can then be configured to use the agent to get the private key, rather than prompting for the key's password.
This should be do-able on either a UNIX/Linux system or on Windows platform using pageant and pscp.
Swift 4 and 5
For example, you have a UITableViewCell
with name MyCell
class MyCell: UITableViewCell {
var delegate:MyCellDelegate!
@IBAction private func myAction(_ sender: UIButton){
delegate.didPressButton(cell: self)
}
}
Now create a protocol
protocol MyCellDelegate {
func didPressButton(cell: UITableViewCell)
}
Next step, create an Extension of UITableView
extension UITableView {
func returnIndexPath(cell: UITableViewCell) -> IndexPath?{
guard let indexPath = self.indexPath(for: cell) else {
return nil
}
return indexPath
}
}
In your UIViewController
implement the protocol MyCellDelegate
class ViewController: UIViewController, MyCellDelegate {
func didPressButton(cell: UITableViewCell) {
if let indexpath = self.myTableView.returnIndexPath(cell: cell) {
print(indexpath)
}
}
}
In UIViewController
override func viewDidLoad() {
super.viewDidLoad()
//using the same `UITableView extension` get the IndexPath here
didPressButton = { cell in
if let indexpath = self.myTableView.returnIndexPath(cell: cell) {
print(indexpath)
}
}
}
var didPressButton: ((UITableViewCell) -> Void)
class MyCell: UITableViewCell {
@IBAction private func myAction(_ sender: UIButton){
didPressButton(self)
}
}
Note:- if you want to get
UICollectionView
indexPath you can use thisUICollectionView extension
and repeat the above steps
extension UICollectionView {
func returnIndexPath(cell: UICollectionViewCell) -> IndexPath?{
guard let indexPath = self.indexPath(for: cell) else {
return nil
}
return indexPath
}
}
You can also use the transform property, with required value in scale:
input[type=radio]{transform:scale(2);}
You can enable connection logging. For SQL Server 2008, you can enable Login Auditing. In SQL Server Management Studio, open SQL Server Properties > Security > Login Auditing select "Both failed and successful logins".
Make sure to restart the SQL Server service.
Once you've done that, connection attempts should be logged into SQL's error log. The physical logs location can be determined here.
All these answers with .ReadAllBytes()
. Another, similar (I won't say duplicate, since they were trying to refactor their code) question was asked on SO here: Best way to read a large file into a byte array in C#?
A comment was made on one of the posts regarding .ReadAllBytes()
:
File.ReadAllBytes throws OutOfMemoryException with big files (tested with 630 MB file
and it failed) – juanjo.arana Mar 13 '13 at 1:31
A better approach, to me, would be something like this, with BinaryReader
:
public static byte[] FileToByteArray(string fileName)
{
byte[] fileData = null;
using (FileStream fs = File.OpenRead(fileName))
{
var binaryReader = new BinaryReader(fs);
fileData = binaryReader.ReadBytes((int)fs.Length);
}
return fileData;
}
But that's just me...
Of course, this all assumes you have the memory to handle the byte[]
once it is read in, and I didn't put in the File.Exists
check to ensure the file is there before proceeding, as you'd do that before calling this code.
Set following php parameters to same value in seconds:
session.cookie_lifetime
session.gc_maxlifetime
in php.ini, .htaccess or for example with
ini_set('session.cookie_lifetime', 86400);
ini_set('session.gc_maxlifetime', 86400);
for a day.
Links:
try json_decode like so
<?php
$var = '["SupplierInvoiceReconciliation"]';
$var = json_decode($var, TRUE);
print_r($var);
?>
Bigger question is: would you drive with a blindfold on? That’s how it is if you develop a system without referential constraints. Keep in mind, that business requirements change, application design changes, respective logical assumptions in the code changes, logic itself can be refactored, and so on. In general, constraints in databases are put in place under contemporary logical assumptions, seemingly correct for particular set of logical assertions and assumptions.
Through the lifecycle of an application, referential and data checks constraints police data collection via the application, especially when new requirements drive logical application changes.
To the subject of this listing - a foreign key does not by itself "improve performance", nor does it "degrade performance" significantly from a standpoint of real-time transaction processing system. However, there is an aggregated cost for constraint checking in HIGH volume "batch" system. So, here is the difference, real-time vs. batch transaction process; batch processing - where aggreated cost, incured by constraint checks, of a sequentially processed batch poses a performance hit.
In a well designed system, data consistency checks would be done "before" processing a batch through (nevertheless, there is a cost associated here also); therefore, foreign key constraint checks are not required during load time. In fact all constraints, including foreign key, should be temporarily disabled till the batch is processed.
QUERY PERFORMANCE - if tables are joined on foreign keys, be cognizant of the fact that foreign key columns are NOT INDEXED (though the respective primary key is indexed by definition). By indexing a foreign key, for that matter, by indexing any key, and joining tables on indexed helps with better performances, not by joining on non-indexed key with foreign key constraint on it.
Changing subjects, if a database is just supporting website display/rendering content/etc and recording clicks, then a database with full constraints on all tables is over kill for such purposes. Think about it. Most websites don’t even use a database for such. For similar requirements, where data is just being recorded and not referenced per say, use an in-memory database, which does not have constraints. This doesn’t mean that there is no data model, yes logical model, but no physical data model.
I have found better option,
<style type="text/css">
.form {
margin: 0 auto;
width: 210px;
}
.form label{
display: inline-block;
text-align: right;
float: left;
}
.form input{
display: inline-block;
text-align: left;
float: right;
}
</style>
Demo here: https://jsfiddle.net/durtpwvx/
It's a bad idea to change the behavior of the home key. This is why Google doesn't allow you to override the home key. I wouldn't mess with the home key generally speaking. You need to give the user a way to get out of your app if it goes off into the weeds for whatever reason.
I'd image any work around will have unwanted side effects.
In CellContentDoubleClick event fires only when double clicking on cell's content. I used this and works:
private void dgvUserList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show(e.RowIndex.ToString());
}
Add object-fit: cover to the style of video
<video controls style="object-fit: cover;" >
Just for those that are trying to do this on Jira
. Just add \\
at the end of each line and a new line will be created:
|Something|Something else \\ that's rather long|Something else|
Will render this:
Source: Text breaks on Jira
You can also use:
@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/mybundle")
To specify the format of your output in a scenario where you need to use Charset, Type, etc.
Maybe not the best solution but it gets the job done:
import { Link } from 'react-router-dom';
// create functional component Post
export default Post = () => (
<div className="component post">
<button className="button delete-post" onClick={() => {
// ... delete post
// then redirect, without page reload, by triggering a hidden Link
document.querySelector('.trigger.go-home').click();
}}>Delete Post</button>
<Link to="/" className="trigger go-home hidden"></Link>
</div>
);
Basically, a logic tied to one action (in this case a post deletion) will end up calling a trigger for redirect. This is not ideal because you will add a DOM node 'trigger' to your markup just so you can conveniently call it when needed. Also, you will directly interact with the DOM, which in a React component may not be desired.
Still, this type of redirect is not required that often. So one or two extra, hidden links in your component markup would not hurt that much, especially if you give them meaningful names.
For MySql 8 you can use following script:
SET GLOBAL validate_password.LENGTH = 4;
SET GLOBAL validate_password.policy = 0;
SET GLOBAL validate_password.mixed_case_count = 0;
SET GLOBAL validate_password.number_count = 0;
SET GLOBAL validate_password.special_char_count = 0;
SET GLOBAL validate_password.check_user_name = 0;
ALTER USER 'user'@'localhost' IDENTIFIED BY 'pass';
FLUSH PRIVILEGES;
As an added extra, you can add an alias for pip as well (in .bashrc or bash_aliases):
alias pip='pip3'
You many find that a clean install of python3 actually points to python3.x so you may need:
alias pip='pip3.6'
alias python='python3.6'
One solution that hasn't come up yet is using length, which successfully handles NULL. As far as I can tell, all values except NULL have a length greater than 0.
x <- list(4, -1, NULL, NA, Inf, -Inf, NaN, T, x = 0, y = "", z = c(1,2,3))
lapply(x, function(el) print(length(el)))
[1] 1
[1] 1
[1] 0
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 3
Thus we could make a simple function that works with both named and numbered indices:
element.exists <- function(var, element)
{
tryCatch({
if(length(var[[element]]) > -1)
return(T)
}, error = function(e) {
return(F)
})
}
If the element doesn't exist, it causes an out-of-bounds condition caught by the tryCatch block.
The method .transpose() converts columns to rows and rows to column, hence you could even write
df.transpose().ix[3]
As an alternative you can also query the information_schema
database and retrieve the data from the global_variables
(and global_status
of course too). This approach provides the same information, but gives you the opportunity to do more with the results, as it is a plain old query.
For example you can convert units to become more readable. The following query provides the current global setting for the innodb_log_buffer_size
in bytes and megabytes:
SELECT
variable_name,
variable_value AS innodb_log_buffer_size_bytes,
ROUND(variable_value / (1024*1024)) AS innodb_log_buffer_size_mb
FROM information_schema.global_variables
WHERE variable_name LIKE 'innodb_log_buffer_size';
As a result you get:
+------------------------+------------------------------+---------------------------+
| variable_name | innodb_log_buffer_size_bytes | innodb_log_buffer_size_mb |
+------------------------+------------------------------+---------------------------+
| INNODB_LOG_BUFFER_SIZE | 268435456 | 256 |
+------------------------+------------------------------+---------------------------+
1 row in set (0,00 sec)
It just means that the server cannot find your image.
Remember The image path must be relative to the CSS file location
Check the path and if the image file exist.
Try this
SELECT CONVERT(varchar(11),getdate(),101) -- Converts to 'mm/dd/yyyy'
SELECT CONVERT(varchar(11),getdate(),103) -- Converts to 'dd/mm/yyyy'
More info here: https://msdn.microsoft.com/en-us/library/ms187928.aspx
In Eclipse Kepler,
JST Server Adapters
and JST Server Adapters Extensions
and install itAfter Eclipse restart, go to Window / Preferences / Server / Runtime Environments
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\
Git
folderJust resolved this issue. Its documented here.
I was calling $rootScope.$apply
twice in the same flow. All I did is wrapped the content of the service function with a setTimeout(func, 1)
.
You're using JSTL 2.0 right? You don't need to put <c:out/>
around all variables. Have you tried something like this?
<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
<c:set var="myVar" value="${myVar}${currentItem}" />
</c:forEach>
Edit: Beaten by the above
To perform an HTTP PUT:
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write("Resource content");
out.close();
httpCon.getInputStream();
To perform an HTTP DELETE:
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
httpCon.connect();
$("#d1 img").click(e=> e.target.src= pic[e.target.src.match(pic[0]) ? 1:0] );
let pic=[
"https://picsum.photos/id/237/40/40", // arbitrary - eg: "img1_on.gif",
"https://picsum.photos/id/238/40/40", // arbitrary - eg: "img2_on.gif"
];
$("#d1 img").click(e=> e.target.src= pic[e.target.src.match(pic[0]) ? 1:0] );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="d1">
<div class="c1">
<a href="#"><img src="img1_on.gif"></a>
<a href="#"><img src="img2_on.gif"></a>
</div>
</div>
_x000D_
Try format
function:
> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"
Use:
$("tr").find("td:first");
js fiddle - this example has .text()
on the end to show that it is returning the elements.
Alternatively, you can use:
$("td:first-child");
.find()
- jQuery API Documentation
Bootstrap 4 progress bar
<div class="progress">
<div class="progress-bar" role="progressbar" style="" aria-valuenow="" aria-valuemin="0" aria-valuemax="100"></div>
</div>
Javascript
change progress bar on next/previous page actions
var count = Number(document.getElementById('count').innerHTML); //set this on page load in a hidden field after an ajax call
var total = document.getElementById('total').innerHTML; //set this on initial page load
var pcg = Math.floor(count/total*100);
document.getElementsByClassName('progress-bar').item(0).setAttribute('aria-valuenow',pcg);
document.getElementsByClassName('progress-bar').item(0).setAttribute('style','width:'+Number(pcg)+'%');
http://www.gnu.org/software/make/manual/make.html#Recursion
subsystem:
cd subdir && $(MAKE)
or, equivalently, this :
subsystem:
$(MAKE) -C subdir
This worked for me on CentOS:
Install dependencies:
yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel
Get Git
cd /usr/local/src
wget http://code.google.com/p/git-core/downloads/detail?name=git-1.7.8.3.tar.gz
tar xvzf git-1.7.8.3.tar.gz
cd git-1.7.8.3
Build Git
./configure
make
make install
In my experience, just pick a relatively high number (between 1024-65535) that you think is unlikely to be used by anything else. For example, port # 8080 and # 5555 are ones that I routinely use. Just pick a port number like this as opposed to just making the code randomly select it and then having to find the port number later is much easier for me.
For example, in my current ChatBot project:
port = 8080
The error message,
Cannot access database on the main thread since it may potentially lock the UI for a long periods of time.
Is quite descriptive and accurate. The question is how should you avoid accessing the database on the main thread. That is a huge topic, but to get started, read about AsyncTask (click here)
-----EDIT----------
I see you are having problems when you run a unit test. You have a couple of choices to fix this:
Run the test directly on the development machine rather than on an Android device (or emulator). This works for tests that are database-centric and don't really care whether they are running on a device.
Use the annotation
@RunWith(AndroidJUnit4.class)
to run the test on the android device, but not in an activity with a UI.
More details about this can be found in this tutorial
I previously had this problem with my EC2 instance (I was serving couchdb to serve resources -- am considering Amazon's S3 for the future).
One thing to check (assuming Ec2) is that the couchdb port is added to your open ports within your security policy.
I specifically encountered
"[Errno 111] Connection refused"
over EC2 when the instance was stopped and started. The problem seems to be a pidfile race. The solution for me was killing couchdb (entirely and properly) via:
pkill -f couchdb
and then restarting with:
/etc/init.d/couchdb restart
I have the same question but cannot ask it because it would be a duplicate.
The accepted answer, using exit, does not work when the script is a bit more complicated. If you use a background process to check for the condition, exit only exits that process, as it runs in a sub-shell. To kill the script, you have to explicitly kill it (at least that is the only way I know).
Here is a little script on how to do it:
#!/bin/bash
boom() {
while true; do sleep 1.2; echo boom; done
}
f() {
echo Hello
N=0
while
((N++ <10))
do
sleep 1
echo $N
# ((N > 5)) && exit 4 # does not work
((N > 5)) && { kill -9 $$; exit 5; } # works
done
}
boom &
f &
while true; do sleep 0.5; echo beep; done
This is a better answer but still incomplete a I really don't know how to get rid of the boom part.
The proper function is int fileno(FILE *stream)
. It can be found in <stdio.h>
, and is a POSIX standard but not standard C.
Use this:
SELECT * FROM Table WHERE Column LIKE '%[0-9]%'
the following code, which is on dicts which follows json syntax more than 3 times faster than deepcopy
def CopyDict(dSrc):
try:
return json.loads(json.dumps(dSrc))
except Exception as e:
Logger.warning("Can't copy dict the preferred way:"+str(dSrc))
return deepcopy(dSrc)
I use something like this in my document.ready
var height = $(window).height();//gets height from device
var width = $(window).width(); //gets width from device
$("#container").width(width+"px");
$("#container").height(height+"px");
After several tries, I got it! I'm setting the keyboard values programmatically like this:
myEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
Or if you want you can edit the XML like so:
android: inputType = "numberPassword"
Both configs will display password bullets, so we need to create a custom ClickableSpan
class:
private class NumericKeyBoardTransformationMethod extends PasswordTransformationMethod {
@Override
public CharSequence getTransformation(CharSequence source, View view) {
return source;
}
}
Finally we need to implement it on the EditText
in order to display the characters typed.
myEditText.setTransformationMethod(new NumericKeyBoardTransformationMethod());
This is how my keyboard looks like now:
EDIT: As @Jukka K. Korpela correctly points out, RFC 1738 was updated by RFC 3986. This has expanded and clarified the characters valid for host, unfortunately it's not easily copied and pasted, but I'll do my best.
In first matched order:
host = IP-literal / IPv4address / reg-name
IP-literal = "[" ( IPv6address / IPvFuture ) "]"
IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
IPv6address = 6( h16 ":" ) ls32
/ "::" 5( h16 ":" ) ls32
/ [ h16 ] "::" 4( h16 ":" ) ls32
/ [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
/ [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
/ [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
/ [ *4( h16 ":" ) h16 ] "::" ls32
/ [ *5( h16 ":" ) h16 ] "::" h16
/ [ *6( h16 ":" ) h16 ] "::"
ls32 = ( h16 ":" h16 ) / IPv4address
; least-significant 32 bits of address
h16 = 1*4HEXDIG
; 16 bits of address represented in hexadecimal
IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
dec-octet = DIGIT ; 0-9
/ %x31-39 DIGIT ; 10-99
/ "1" 2DIGIT ; 100-199
/ "2" %x30-34 DIGIT ; 200-249
/ "25" %x30-35 ; 250-255
reg-name = *( unreserved / pct-encoded / sub-delims )
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" <---This seems like a practical shortcut, most closely resembling original answer
reserved = gen-delims / sub-delims
gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / "+" / "," / ";" / "="
pct-encoded = "%" HEXDIG HEXDIG
Original answer from RFC 1738 specification:
Thus, only alphanumerics, the special characters "
$-_.+!*'(),
", and reserved characters used for their reserved purposes may be used unencoded within a URL.
^ obsolete since 1998.
You need to select "#foo2" as your selector. Then, get it with html().
Here is the html:
<div id="foo1">
</div>
<div id="foo2">
<div>Foo Here</div>
</div>?
Here is the javascript:
$("#foo2").click(function() {
//alert("clicked");
var value=$(this).html();
$("#foo1").html(value);
});?
Here is the jsfiddle: http://jsfiddle.net/fritzdenim/DhCjf/
The solution is the /Y
switch:
xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y
The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.
Conclusion
Let's me explain more detail:
Question: How many Transaction we have? Answer: Only one
Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.
Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction
Go to the catch outside
Spring will set the rollBackOnly to true -> it determine we must
rollback the caller (processNextRegistrationMessage) also.
The persist() will rollback itself first.
Question: Why we change PROPAGATION to REQUIRES_NEW, it works?
Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.
Thanks
My 50 cents, I had this problem too and solved by:
inspect logs via UI from very begining of building process (eg. after commit, restart dynos) to see what happens before crash
when link modules do not include root directory of project (my problem..)
this:
const router = require('./logic/router.js')
instead of:
const router = require('../DMS/logic/router.js')
HTML 4.x & HTML5 disallow nested forms, but HTML5 will allow a workaround with "form" attribute ("form owner").
As for HTML 4.x you can:
Call System.Reflection.MethodBase.GetCurrentMethod().Name
from within the method.
I use this class:
class ProcessWrapper : Process, IDisposable
{
public enum PipeType { StdOut, StdErr }
public class Output
{
public string Message { get; set; }
public PipeType Pipe { get; set; }
public override string ToString()
{
return $"{Pipe}: {Message}";
}
}
private readonly string _command;
private readonly string _args;
private readonly bool _showWindow;
private bool _isDisposed;
private readonly Queue<Output> _outputQueue = new Queue<Output>();
private readonly ManualResetEvent[] _waitHandles = new ManualResetEvent[2];
private readonly ManualResetEvent _outputSteamWaitHandle = new ManualResetEvent(false);
public ProcessWrapper(string startCommand, string args, bool showWindow = false)
{
_command = startCommand;
_args = args;
_showWindow = showWindow;
}
public IEnumerable<string> GetMessages()
{
while (!_isDisposed)
{
_outputSteamWaitHandle.WaitOne();
if (_outputQueue.Any())
yield return _outputQueue.Dequeue().ToString();
}
}
public void SendCommand(string command)
{
StandardInput.Write(command);
StandardInput.Flush();
}
public new int Start()
{
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = _command,
Arguments = _args,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
CreateNoWindow = !_showWindow
};
StartInfo = startInfo;
OutputDataReceived += delegate (object sender, DataReceivedEventArgs args)
{
if (args.Data == null)
{
_waitHandles[0].Set();
}
else if (args.Data.Length > 0)
{
_outputQueue.Enqueue(new Output { Message = args.Data, Pipe = PipeType.StdOut });
_outputSteamWaitHandle.Set();
}
};
ErrorDataReceived += delegate (object sender, DataReceivedEventArgs args)
{
if (args.Data == null)
{
_waitHandles[1].Set();
}
else if (args.Data.Length > 0)
{
_outputSteamWaitHandle.Set();
_outputQueue.Enqueue(new Output { Message = args.Data, Pipe = PipeType.StdErr });
}
};
base.Start();
_waitHandles[0] = new ManualResetEvent(false);
BeginErrorReadLine();
_waitHandles[1] = new ManualResetEvent(false);
BeginOutputReadLine();
return Id;
}
public new void Dispose()
{
StandardInput.Flush();
StandardInput.Close();
if (!WaitForExit(1000))
{
Kill();
}
if (WaitForExit(1000))
{
WaitHandle.WaitAll(_waitHandles);
}
base.Dispose();
_isDisposed = true;
}
}
The os function dup2() should provide what you need (if not references to exactly what you need).
More specifically, you can dup2() the stdin file descriptor to another file descriptor, do other stuff with stdin, and then copy it back when you want.
The dup() function duplicates an open file descriptor. Specifically, it provides an alternate interface to the service provided by the fcntl() function using the F_DUPFD constant command value, with 0 for its third argument. The duplicated file descriptor shares any locks with the original.
On success, dup() returns a new file descriptor that has the following in common with the original:
- Same open file (or pipe)
- Same file pointer (both file descriptors share one file pointer)
- Same access mode (read, write, or read/write)
You need to put a space for the <!-- [if !IE] -->
My full css block goes as follows, since IE8 is terrible with media queries
<!-- IE 8 or below -->
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" href="/Resources/css/master1300.css" />
<![endif]-->
<!-- IE 9 or above -->
<!--[if gte IE 9]>
<link rel="stylesheet" type="text/css" media="(max-width: 100000px) and (min-width:481px)"
href="/Resources/css/master1300.css" />
<link rel="stylesheet" type="text/css" media="(max-width: 480px)"
href="/Resources/css/master480.css" />
<![endif]-->
<!-- Not IE -->
<!-- [if !IE] -->
<link rel="stylesheet" type="text/css" media="(max-width: 100000px) and (min-width:481px)"
href="/Resources/css/master1300.css" />
<link rel="stylesheet" type="text/css" media="(max-width: 480px)"
href="/Resources/css/master480.css" />
<!-- [endif] -->
If you don't want to save any changes and don't want that Save prompt while saving an Excel file using Macro then this piece of code may helpful for you
Sub Auto_Close()
ThisWorkbook.Saved = True
End Sub
Because the Saved
property is set to True
, Excel responds as though the workbook has already been saved and no changes have occurred since that last save, so no Save prompt.
You can increase the performance of excel export by following these steps:
1) When you fetch data from database, avoid casting the result set to the list of entity classes. Instead assign it directly to List
List<Object[]> resultList =session.createSQLQuery("SELECT t1.employee_name, t1.employee_id ... from t_employee t1 ").list();
instead of
List<Employee> employeeList =session.createSQLQuery("SELECT t1.employee_name, t1.employee_id ... from t_employee t1 ").list();
2) Create excel workbook object using SXSSFWorkbook instead of XSSFWorkbook and create new row using SXSSFRow when the data is not empty.
3) Use java.util.Iterator to iterate the data list.
Iterator itr = resultList.iterator();
4) Write data into excel using column++.
int rowCount = 0;
int column = 0;
while(itr.hasNext()){
SXSSFRow row = xssfSheet.createRow(rowCount++);
Object[] object = (Object[]) itr.next();
//column 1
row.setCellValue(object[column++]); // write logic to create cell with required style in setCellValue method
//column 2
row.setCellValue(object[column++]);
itr.remove();
}
5) While iterating the list, write the data into excel sheet and remove the row from list using remove method. This is to avoid holding unwanted data from the list and clear the java heap size.
itr.remove();
Search across files - Press Ctrl+Shift+F
Find - Press Ctrl+F
Find and Replace - Ctrl+H
For basic editing options follow this link - https://code.visualstudio.com/docs/editor/codebasics
Note : For mac the Ctrl represents the command button
%run YourNotebookfile.ipynb is working fine;
if you want to import a specific module then just add the import command after the ipynb i.e YourNotebookfile.ipynb having def Add()
then you can just use it
%run YourNotebookfile.ipynb import Add
Brighams answer uses literal regexp
.
Solution with a Regex object.
var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');
TRY IT HERE : JSFiddle Working Example
You can have more than one statement when still return:
[]() -> your_type {return (
your_statement,
even_more_statement = just_add_comma,
return_value);}
I just put the content in the question in a file called test.php
and ran php test.php
.
(In the folder where the test.php
is.)
$ php foo.php
15
You can list all existing tags git tag
or you could filter the list with git tag -l 'v1.1.*'
, where *
acts as a wildcard. It will return a list of tags marked with v1.1
.
You will notice that when you call git tag
you do not get to see the contents of your annotations. To preview them you must add -n
to your command: git tag -n2
.
$ git tag -l -n2
v1.0 Release version 1.0
v1.1 Release version 1.1
The command lists all existing tags with maximum 3 lines of their tag message. By default -n
only shows the first line. For more info be sure to check this tag related article as well.
A DataSet
already contains DataTables
. You can just use:
DataTable firstTable = dataSet.Tables[0];
or by name:
DataTable customerTable = dataSet.Tables["Customer"];
Note that you should have using
statements for your SQL code, to ensure the connection is disposed properly:
using (SqlConnection conn = ...)
{
// Code here...
}
The answers are outdated. You simply have to conda install pip and git. Then you can use pip normally:
Activate your conda environment source activate myenv
conda install git pip
pip install git+git://github.com/scrappy/scrappy@master
Zapping - you can use this javascript lib; DefiantJS. There is no need to restructure JSON data into objects to ease searching. Instead, you can search the JSON structure with an XPath expression like this:
var data = [
{
"id": "one",
"pId": "foo1",
"cId": "bar1"
},
{
"id": "two",
"pId": "foo2",
"cId": "bar2"
},
{
"id": "three",
"pId": "foo3",
"cId": "bar3"
}
],
res = JSON.search( data, '//*[id="one"]' );
console.log( res[0].cId );
// 'bar1'
DefiantJS extends the global object JSON with a new method; "search" which returns array with the matches (empty array if none were found). You can try it out yourself by pasting your JSON data and testing different XPath queries here:
http://www.defiantjs.com/#xpath_evaluator
XPath is, as you know, a standardised query language.
One thing I want to add. Sometimes, there can be precision loss. You may want to add some epsilon value first before converting. Not sure why that works... but it work.
int someint = (somedouble+epsilon);
It's included because your minimum SDK version is set to 10. The ActionBar
was introduced in API 11. Eclipse adds it automatically so your app can look more consistent throughout the spectrum of all android versions you are supporting.
MySQL 5.x specification for decimal datatype is: DECIMAL[(M[,D])] [UNSIGNED] [ZEROFILL]
. The answer above is wrong (now corrected) in saying that unsigned decimals are not possible.
To define a field allowing only unsigned decimals, with a total length of 6 digits, 4 of which are decimals, you would use: DECIMAL (6,4) UNSIGNED
.
You can likewise create unsigned (ie. not negative) FLOAT and DOUBLE datatypes.
Update on MySQL 8.0.17+, as in MySQL 8 Manual: 11.1.1 Numeric Data Type Syntax:
"Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by default, so the SIGNED attribute has no effect.*
As of MySQL 8.0.17, the UNSIGNED attribute is deprecated for columns of type FLOAT, DOUBLE, and DECIMAL (and any synonyms); you should expect support for it to be removed in a future version of MySQL. Consider using a simple CHECK constraint instead for such columns.
As per late 2020 this as easy as follows.
For the geometry
key to be presented on a place selected from the places dropdown, the field geometry
should be set on Autocomplete
object instance with setFields()
method.
The code should look like this.
Load the API library:
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initAutocomplete"
Init the autocomplete and process the selected place data generally same as all answers above. But use autocomplete.setFields(['geometry'])
to get coordinates back;
const autocomplete;
// Init the autocomplete object
function initAutocomplete() {
autocomplete = new window.google.maps.places.Autocomplete(
document.getElementById('current_location'), { types: ["geocode"] }
);
// !!! This is where you set `geometry` field to be returned with the place.
autocomplete.setFields(['address_component', 'geometry']); // <--
autocomplete.addListener("place_changed", fillInAddress);
}
// Process the address selected by user
function fillInAddress() {
const place = autocomplete.getPlace();
// Here you can get your coordinates like this
console.log(place.geometry.location.lat());
console.log(place.geometry.location.lng());
}
See the Google API docs on Autocomplete.setFields
and geometry
option.
You can make it even simplier, if you want to avoid extra structures.
service:
mappings:
key1: value1
key2: value2
@Configuration
@EnableConfigurationProperties
public class ServiceConfigurationProperties {
@Bean
@ConfigurationProperties(prefix = "service.mappings")
public Map<String, String> serviceMappings() {
return new HashMap<>();
}
}
And then use it as usual, for example with a constructor:
public class Foo {
private final Map<String, String> serviceMappings;
public Foo(Map<String, String> serviceMappings) {
this.serviceMappings = serviceMappings;
}
}
I use the following function extensively. As pointed out above, using other methods can sometimes give inaccurate results due to used range updates, gaps in the data, or different columns having different row counts.
Example of use:
lastRow=FindRange("Sheet1","A1:A1000")
would return the last occupied row number of the entire range. You can specify any range you want from single columns to random rows, eg FindRange("Sheet1","A100:A150")
Public Function FindRange(inSheet As String, inRange As String) As Long
Set fr = ThisWorkbook.Sheets(inSheet).Range(inRange).find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If Not fr Is Nothing Then FindRange = fr.row Else FindRange = 0
End Function
You can do something like the following these days by referencing the "beforeSubmit" jquery form event. I'm disabling and enabling the submit button to avoid duplicate requests, submitting via ajax, returning a message that's a json array and displaying the information in a pNotify:
jQuery('body').on('beforeSubmit', "#formID", function() {
$('.submitter').prop('disabled', true);
var form = $('#formID');
$.ajax({
url : form.attr('action'),
type : 'post',
data : form.serialize(),
success: function (response)
{
response = jQuery.parseJSON(response);
new PNotify({
text: response.message,
type: response.status,
styling: 'bootstrap3',
delay: 2000,
});
$('.submitter').prop('disabled', false);
},
error : function ()
{
console.log('internal server error');
}
});
});
This works for me:
Console.OutputEncoding = System.Text.Encoding.Default;
To display some of the symbols, it's required to set Command Prompt's font to Lucida Console:
Open Command Prompt;
Right click on the top bar of the Command Prompt;
Click Properties;
If the font is set to Raster Fonts, change it to Lucida Console.
You may also find this command useful:
mkdir dirname && cd $_
where dirname is the name of the directory you want to create
Here is another way :
var currentMonth = 1
var months = ["ENE", "FEB", "MAR", "APR", "MAY", "JUN",
"JUL", "AGO", "SEP", "OCT", "NOV", "DIC"];
console.log(months[currentMonth - 1]);
when you pushing code to another branch just follow the below git command. Remember demo is my other branch name you can replace with your branch name.
git push origin master:demo
First, you can switch on an enum
in Java. I'm guessing you intended to say you can’t, but you can. char
s have a set range of values, so it's easy to compare. Strings can be anything.
A switch
statement is usually implemented as a jump table (branch table) in the underlying compilation, which is only possible with a finite set of values. C# can switch on strings, but it causes a performance decrease because a jump table cannot be used.
Java 7 and later supports String
switches with the same characteristics.
I find it really useful when you've got cleanup to do that has to be done even if there's an exception:
try:
data = something_that_can_go_wrong()
except Exception as e: # yes, I know that's a bad way to do it...
handle_exception(e)
else:
do_stuff(data)
finally:
clean_up()
The standard best practice for REST APIs is to have a hyphen, not camelcase or underscores.
This comes from Mark Masse's "REST API Design Rulebook" from Oreilly.
In addition, note that Stack Overflow itself uses hyphens in the URL: .../hyphen-underscore-or-camelcase-as-word-delimiter-in-uris
As does WordPress: http://inventwithpython.com/blog/2012/03/18/how-much-math-do-i-need-to-know-to-program-not-that-much-actually
If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".
Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".
This is what I was looking for and I did for sorting an Array of Arrays based on another Array:
It's On^3 and might not be the best practice(ES6)
function sortArray(arr, arr1){_x000D_
return arr.map(item => {_x000D_
let a = [];_x000D_
for(let i=0; i< arr1.length; i++){_x000D_
for (const el of item) {_x000D_
if(el == arr1[i]){_x000D_
a.push(el);_x000D_
} _x000D_
}_x000D_
}_x000D_
return a;_x000D_
});_x000D_
}_x000D_
_x000D_
const arr1 = ['fname', 'city', 'name'];_x000D_
const arr = [['fname', 'city', 'name'],_x000D_
['fname', 'city', 'name', 'name', 'city','fname']];_x000D_
console.log(sortArray(arr,arr1));
_x000D_
Menu Tools ? Options ? Package Manager
Give a name and folder location. Click OK. Drop your NuGet package files in that folder.
Go to your Project, right click and select "Manage NuGet Packages" and select your new package source.
Here is the documentation.
Don't use quotes with <<EOF
:
var=$1
sudo tee "/path/to/outfile" > /dev/null <<EOF
Some text that contains my $var
EOF
Variable expansion is the default behavior inside of here-docs. You disable that behavior by quoting the label (with single or double quotes).
Here is another answer. No extra packages required.
datetime.date(year + int(month/12), month%12+1, 1)-datetime.timedelta(days=1)
Get the first day of the next month and subtract a day from it.
In general when the user upload the file, the PHP server doen't catch any exception mistake or errors, it means that the file is uploaded successfully. https://www.php.net/manual/en/reserved.variables.files.php#109648
if ( boolval( $_FILES['image']['error'] === 0 ) ) {
// ...
}
The proper solution is the one provided by @Jojo.Lechelt.
However if you don't want to commit for any reason and still want to pull the changes,you may save your changes somewhere else,replace the conflicting file with HEAD revision and then pull.
Later you can paste your changes again and compare it with HEAD and incorporate other people changes into your file.
Here is the code to read the excel data by column.
public ArrayList<String> extractExcelContentByColumnIndex(int columnIndex){
ArrayList<String> columndata = null;
try {
File f = new File("sample.xlsx")
FileInputStream ios = new FileInputStream(f);
XSSFWorkbook workbook = new XSSFWorkbook(ios);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
columndata = new ArrayList<>();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(row.getRowNum() > 0){ //To filter column headings
if(cell.getColumnIndex() == columnIndex){// To match column index
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
columndata.add(cell.getNumericCellValue()+"");
break;
case Cell.CELL_TYPE_STRING:
columndata.add(cell.getStringCellValue());
break;
}
}
}
}
}
ios.close();
System.out.println(columndata);
} catch (Exception e) {
e.printStackTrace();
}
return columndata;
}
Try this with appcompat from style.xml
. It provides support for all platforms.
<!-- Application theme. -->
<style name="AppTheme.FullScreen" parent="AppTheme">
<item name="android:windowFullscreen">true</item>
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="@style/Theme.AppCompat.Light.NoActionBar" />
How do I use Python's itertools.groupby()?
You can use groupby to group things to iterate over. You give groupby an iterable, and a optional key function/callable by which to check the items as they come out of the iterable, and it returns an iterator that gives a two-tuple of the result of the key callable and the actual items in another iterable. From the help:
groupby(iterable[, keyfunc]) -> create an iterator which returns
(key, sub-iterator) grouped by each value of key(value).
Here's an example of groupby using a coroutine to group by a count, it uses a key callable (in this case, coroutine.send
) to just spit out the count for however many iterations and a grouped sub-iterator of elements:
import itertools
def grouper(iterable, n):
def coroutine(n):
yield # queue up coroutine
for i in itertools.count():
for j in range(n):
yield i
groups = coroutine(n)
next(groups) # queue up coroutine
for c, objs in itertools.groupby(iterable, groups.send):
yield c, list(objs)
# or instead of materializing a list of objs, just:
# return itertools.groupby(iterable, groups.send)
list(grouper(range(10), 3))
prints
[(0, [0, 1, 2]), (1, [3, 4, 5]), (2, [6, 7, 8]), (3, [9])]
UPDATE 2020: SQL Server 2016+ JSON Serialization and De-serialization Examples
The data provided by the OP inserted into a temporary table called #project_members
drop table if exists #project_members;
create table #project_members(
empName varchar(20) not null,
projID varchar(20) not null);
go
insert #project_members(empName, projID) values
('ANDY', 'A100'),
('ANDY', 'B391'),
('ANDY', 'X010'),
('TOM', 'A100'),
('TOM', 'A510');
How to serialize this data into a single JSON string with a nested array containing projID's
select empName, (select pm_json.projID
from #project_members pm_json
where pm.empName=pm_json.empName
for json path, root('projList')) projJSON
from #project_members pm
group by empName
for json path;
Result
'[
{
"empName": "ANDY",
"projJSON": {
"projList": [
{ "projID": "A100" },
{ "projID": "B391" },
{ "projID": "X010" }
]
}
},
{
"empName": "TOM",
"projJSON": {
"projList": [
{ "projID": "A100" },
{ "projID": "A510" }
]
}
}
]'
How to de-serialize this data from a single JSON string back to it's original rows and columns
declare @json nvarchar(max)=N'[{"empName":"ANDY","projJSON":{"projList":[{"projID":"A100"},
{"projID":"B391"},{"projID":"X010"}]}},{"empName":"TOM","projJSON":
{"projList":[{"projID":"A100"},{"projID":"A510"}]}}]';
select oj.empName, noj.projID
from openjson(@json) with (empName varchar(20),
projJSON nvarchar(max) as json) oj
cross apply openjson(oj.projJSON, '$.projList') with (projID varchar(20)) noj;
Results
empName projID
ANDY A100
ANDY B391
ANDY X010
TOM A100
TOM A510
How to persist the unique empName to a table and store the projID's in a nested JSON array
drop table if exists #project_members_with_json;
create table #project_members_with_json(
empName varchar(20) unique not null,
projJSON nvarchar(max) not null);
go
insert #project_members_with_json(empName, projJSON)
select empName, (select pm_json.projID
from #project_members pm_json
where pm.empName=pm_json.empName
for json path, root('projList'))
from #project_members pm
group by empName;
Results
empName projJSON
ANDY {"projList":[{"projID":"A100"},{"projID":"B391"},{"projID":"X010"}]}
TOM {"projList":[{"projID":"A100"},{"projID":"A510"}]}
How to de-serialize from a table with unique empName and nested JSON array column containing projID's
select wj.empName, oj.projID
from
#project_members_with_json wj
cross apply
openjson(wj.projJSON, '$.projList') with (projID varchar(20)) oj;
Results
empName projID
ANDY A100
ANDY B391
ANDY X010
TOM A100
TOM A510
Sometimes a lot of troubles with it. In attribute value of datapicker data is 28-06-2014, but datepicker is show or today or nothing. I decided it in a such way:
<input type="text" class="form-control datepicker" data-value="<?= date('d-m-Y', (!$event->date ? time() : $event->date)) ?>" value="<?= date('d-m-Y', (!$event->date ? time() : $event->date)) ?>" />
I added to the input of datapicker attribute data-value, because if call jQuery(this).val() OR jQuery(this).attr('value') - nothing works. I decided init in cycle each datapicker and take its value from attribute data-value:
$("form .datepicker").each(function() {
var time = jQuery(this).data('value');
time = time.split('-');
$(this).datepicker('setDate', new Date(time[2], time[1], time[0], 0, 0, 0));
});
and it is works fine =)
You can't see this method in javadoc because it's added by the compiler.
Documented in three places :
The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.
Enum.valueOf
classvalues
method is mentioned in description of valueOf
method)All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.
The values
function simply list all values of the enumeration.
I've tested it using the following code:
$emails = ['[email protected]', '[email protected]','[email protected]'];
Mail::send('emails.welcome', [], function($message) use ($emails)
{
$message->to($emails)->subject('This is test e-mail');
});
var_dump( Mail:: failures());
exit;
Result - empty array for failures.
But of course you need to configure your app/config/mail.php
properly. So first make sure you can send e-mail just to one user and then test your code with many users.
Moreover using this simple code none of my e-mails were delivered to free mail accounts, I got only emails to inboxes that I have on my paid hosting accounts, so probably they were caught by some filters (it's maybe simple topic/content issue but I mentioned it just in case you haven't received some of e-mails) .
Try the os.path.exists
function
if not os.path.exists(dir):
os.mkdir(dir)
In python notebooks I often want to filter out 'dangling' numpy.ndarray
's, in particular the ones that are stored in _1
, _2
, etc that were never really meant to stay alive.
I use this code to get a listing of all of them and their size.
Not sure if locals()
or globals()
is better here.
import sys
import numpy
from humanize import naturalsize
for size, name in sorted(
(value.nbytes, name)
for name, value in locals().items()
if isinstance(value, numpy.ndarray)):
print("{:>30}: {:>8}".format(name, naturalsize(size)))
Using SQL connection via Windows Authentication: A "Kerberos double hop" is happening: one hop is your client application connecting to the SQL Server, a second hop is the SQL Server connecting to the remote "\\NETWORK_MACHINE\". Such a double hop falls under the restrictions of Constrained Delegation and you end up accessing the share as Anonymous Login and hence the Access Denied.
To resolve the issue you need to enable constrained delegation for the SQL Server service account. See here for a good post that explains it quite well
SQL Server using SQL Authentication You need to create a credential for your SQL login and use that to access that particular network resource. See here
$("a[href*='id=ABC']").addClass('active_jquery_menu');
I think you probably should not use ternary operator in php. Consider next example:
<?php
function f1($n) {
var_dump("first funct");
return $n == 1;
}
function f2($n) {
var_dump("second funct");
return $n == 2;
}
$foo = 1;
$a = (f1($foo)) ? "uno" : (f2($foo)) ? "dos" : "tres";
print($a);
How do you think, what $a
variable will contain? (hint: dos)
And it will remain the same even if $foo
variable will be assigned to 2.
To make things better you should either refuse to using this operator or surround right part with braces in the following way:
$a = (f1($foo)) ? "uno" : ((f2($foo)) ? "dos" : "tres");
#define NAME(x) printf("Hello " #x);
main(){
NAME(Ian)
}
//will print: Hello Ian
I had a similar problem with *std::shared_ptr* with Eclipse using MinGW and gcc 4.8.1. No matter what, Eclipse would not resolve *shared_ptr*. To fix this, I manually added the __cplusplus macro to the C++ symbols and - viola! - Eclipse can find it. Since I specified -std=c++11 as a compile option, I (ahem) assumed that the Eclipse code analyzer would use that option as well. So, to fix this:
The only problem with this is that gcc will complain that the symbol is already defined(!) but the compile will complete as before.
1.Create a new class which supers UITabBarController. E.g:
class xxx: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
}
2.Add the following code to the function viewDidLoad():
self.selectedIndex = 1; //set the tab index you want to show here, start from 0
3.Go to storyboard, and set the Custom Class of your Tab Bar Controller to this new class. (MyVotes1 as the example in the pic)
I ran into this today. Led by Greg Hewgill's answer, I looked at running processes on my system to see if anything was "stuck" or if other users were logged into the machine doing anything with git. I then launched cygwin (installed separately) on this particular machine. It launched ok. I closed it and then tried the Git Extensions again (I was trying a pull operation) and it worked. Not sure if the launching of cygwin cleared something that was shared but this is the first time I ran into this error and this seemed to fix it for me.
The example in Liam's answer saves the file as string in a single line. I prefer to add formatting. Someone in the future may want to change some value manually in the file. If you add formatting it's easier to do so.
The following adds basic JSON indentation:
string json = JsonConvert.SerializeObject(_data.ToArray(), Formatting.Indented);
It's not possible to clear user history without plugins. And also it's not an issue at developer's perspective, it's the burden of the user to clear his history.
For information refer to How to clear browsers (IE, Firefox, Opera, Chrome) history using JavaScript or Java except from browser itself?
You can simply do :
<%= Html.TextBoxFor(x => x.Age, new { @Value = "0"}) %>
or better, this will switch to default value '0' if the model is null, for example if you have the same view for both editing and creating :
@Html.TextBoxFor(x => x.Age, new { @Value = (Model==null) ? "0" : Model.Age.ToString() })
There's an easy way to produce this error:
$joe = null;
$joe->anything();
Will render the error:
Fatal error: Call to a member function
anything()
on a non-object in /Applications/XAMPP/xamppfiles/htdocs/casMail/dao/server.php on line 23
It would be a lot better if PHP would just say,
Fatal error: Call from Joe is not defined because (a) joe is null or (b) joe does not define
anything()
in on line <##>.
Usually you have build your class so that $joe
is not defined in the constructor or