Something simple like this can be done using subqueries in the select
clause:
select ((select sum(hours) from resource) +
(select sum(hours) from projects-time)
) as totalHours
For such a simple query as this, such a subselect is reasonable.
In some databases, you might have to add from dual
for the query to compile.
If you want to output each individually:
select (select sum(hours) from resource) as ResourceHours,
(select sum(hours) from projects-time) as ProjectHours
If you want both and the sum, a subquery is handy:
select ResourceHours, ProjectHours, (ResourceHours+ProjecctHours) as TotalHours
from (select (select sum(hours) from resource) as ResourceHours,
(select sum(hours) from projects-time) as ProjectHours
) t
You can use the following:
$regex = '#<\s*?code\b[^>]*>(.*?)</code\b[^>]*>#s';
\b
ensures that a typo (like <codeS>
) is not captured.[^>]*
captures the content of a tag with attributes (eg a class).s
capture content with newlines.See the result here : http://lumadis.be/regex/test_regex.php?id=1081
You can use this simple code in loop by incrementing count
cv2.imwrite("C:\Sharat\Python\Images\frame%d.jpg" % count, image)
images will be saved in the folder by name line frame0.jpg, frame1.jpg frame2.jpg etc..
LD_LIBRARY_PATH
is the predefined environmental variable in Linux/Unix which sets the path which the linker should look in to while linking dynamic libraries/shared libraries.
LD_LIBRARY_PATH
contains a colon separated list of paths and the linker gives priority to these paths over the standard library paths /lib
and /usr/lib
. The standard paths will still be searched, but only after the list of paths in LD_LIBRARY_PATH
has been exhausted.
The best way to use LD_LIBRARY_PATH
is to set it on the command line or script immediately before executing the program. This way the new LD_LIBRARY_PATH
isolated from the rest of your system.
Example Usage:
$ export LD_LIBRARY_PATH="/list/of/library/paths:/another/path"
$ ./program
Since you talk about .dll
you are on a windows system and a .dll
must be placed at a path which the linker searches at link time, in windows this path is set by the environmental variable PATH
, So add that .dll
to PATH
and it should work fine.
Use command
google-chrome-stable
We can also use command
google-chrome
To open terminal but in my case when I make an interrupt ctrl + c
then it get closed so I would recommend to use google-chrome-stable
instead of google-chrome
The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.
The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.
Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.
It's about classes dependency rate to another ones which is so low in loosely coupled and so high in tightly coupled. To be clear in the service orientation architecture, services are loosely coupled to each other against monolithic which classes dependency to each other is on purpose
You are very close.
You applied the round to the series of values given by df.value1
.
The return type is thus a Series.
You need to assign that series back to the dataframe (or another dataframe with the same Index).
Also, there is a pandas.Series.round
method which is basically a short hand for pandas.Series.apply(np.round)
.
In[2]:
df.value1 = df.value1.round()
print df
Out[2]:
item value1 value2
0 a 1 1.3
1 a 2 2.5
2 a 0 0.0
3 b 3 -1.0
4 b 5 -1.0
You could use:
echo date('F Y', strtotime('20130814'));
which should do the trick.
Edit: You have a date which is in a string format. To be able to format it nicelt, you first need to change it into a date itself - which is where strtotime comes in. It is a fantastic feature that converts almost any plausible expression of a date into a date itself. Then we can actually use the date() function to format the output into what you want.
This is how I did it:
package main
import (
"fmt"
"os"
"bytes"
"log"
)
func main() {
filerc, err := os.Open("filename")
if err != nil{
log.Fatal(err)
}
defer filerc.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(filerc)
contents := buf.String()
fmt.Print(contents)
}
Many of these answers do work, but I have found the easiest way by far is to send data through ViewData or ViewBag and let JSON.Net serialize it.
I use this technique when Javascript is needed for HTML generation before the page load or when AJAX overhead needs to be avoided:
In the controller:
public ActionResult MyController()
{
var addresses = myAddressesGetter();
ViewData["addresses"] = addresses ;
return View();
}
In the view:
@section scripts {
<script type="text/javascript">
var MyjavascriptAddresses: @Html.Raw(JsonConvert.SerializeObject(ViewData["addresses"])),
</script>
}
You can always rely on JSON.NET whereas some browsers have poor JSON deserialization support.
Another benefit over some methods in that you can see the Javascript using your browser's View --> Source
, since it is simply text generated server-side.
Note that In most situations, Web API a more elegant way to get JSON to the client.
The problem with editing JavaScript like you can CSS and HTML is that there is no clean way to propagate the changes. JavaScript can modify the DOM, send Ajax requests, and dynamically modify existing objects and functions at runtime. So, once you have loaded a page with JavaScript, it might be completely different after the JavaScript has run. The browser would have to keep track of every modification your JavaScript code performs so that when you edit the JS, it rolls back the changes to a clean page.
But, you can modify JavaScript dynamically a few other ways:
javascript: alert (1);
The first two options are great because you can modify any JavaScript variables and functions currently in scope. However, you won't be able to modify the code and run it with a "just-served" page like you can with the third option.
Other than that, as far as I know, there is no edit-and-run JavaScript editor in the browser. Hope this helps,
In Go 1.10+ there is strings.Builder
, here.
A Builder is used to efficiently build a string using Write methods. It minimizes memory copying. The zero value is ready to use.
It's almost the same with bytes.Buffer
.
package main
import (
"strings"
"fmt"
)
func main() {
// ZERO-VALUE:
//
// It's ready to use from the get-go.
// You don't need to initialize it.
var sb strings.Builder
for i := 0; i < 1000; i++ {
sb.WriteString("a")
}
fmt.Println(sb.String())
}
Click to see this on the playground.
StringBuilder's methods are being implemented with the existing interfaces in mind. So that you can switch to the new Builder type easily in your code.
It can only grow or reset.
It has a copyCheck mechanism built-in that prevents accidentially copying it:
func (b *Builder) copyCheck() { ... }
In bytes.Buffer
, one can access the underlying bytes like this: (*Buffer).Bytes()
.
strings.Builder
prevents this problem.io.Reader
etc.bytes.Buffer.Reset()
rewinds and reuses the underlying buffer whereas the strings.Builder.Reset()
does not, it detaches the buffer.
Check out its source code for more details, here.
Remember that your img is not really a DOM element but a javascript expression.
This is a JSX attribute expression. Put curly braces around the src string expression and it will work. See http://facebook.github.io/react/docs/jsx-in-depth.html#attribute-expressions
In javascript, the class attribute is reference using className. See the note in this section: http://facebook.github.io/react/docs/jsx-in-depth.html#react-composite-components
/** @jsx React.DOM */
var Hello = React.createClass({
render: function() {
return <div><img src={'http://placehold.it/400x20&text=slide1'} alt="boohoo" className="img-responsive"/><span>Hello {this.props.name}</span></div>;
}
});
React.renderComponent(<Hello name="World" />, document.body);
May be helpful... :)
$(document).ready(function() {
$('#buutonId').on('click', function() {
$('#modalId').modal('open');
});
});
You don't need the "
to define a regular expression so just:
var regex = /(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is; // this is valid syntax
If value
is a variable and you want a dynamic regular expression then you can't use this notation; use the alternative notation.
String.replace
also accepts strings as input, so you can do "fox".replace("fox", "bear");
Alternative:
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(.*?)\b/", "is");
Keep in mind that if value
contains regular expressions characters like (
, [
and ?
you will need to escape them.
There are three way to generate unique id in java.
1) the UUID class provides a simple means for generating unique ids.
UUID id = UUID.randomUUID();
System.out.println(id);
2) SecureRandom and MessageDigest
//initialization of the application
SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
//generate a random number
String randomNum = new Integer(prng.nextInt()).toString();
//get its digest
MessageDigest sha = MessageDigest.getInstance("SHA-1");
byte[] result = sha.digest(randomNum.getBytes());
System.out.println("Random number: " + randomNum);
System.out.println("Message digest: " + new String(result));
3) using a java.rmi.server.UID
UID userId = new UID();
System.out.println("userId: " + userId);
You can use the %
operator to find the remainder of a division, and compare the result with 0
.
Example:
if (number % divisor == 0)
{
//code for perfect divisor
}
else
{
//the number doesn't divide perfectly by divisor
}
I had this problem as well. I found out that having a $(document).ready function that included a $.cookie in a script tag inside body while having cookie js load in the head BELOW jquery as intended resulted in $(document).ready beeing processed before the cookie plugin could finish loading.
I moved the cookie plugin load script in the body before the $(document).ready script and the error disappeared :D
In addition to border-radius: 0
, add -webkit-appearance: none;
.
At the root of your project type below in the console:
gradlew --version
You will have gradle version with other information (as a sample):
------------------------------------------------------------
Gradle 5.1.1 << Here is the version
------------------------------------------------------------
Build time: 2019-01-10 23:05:02 UTC
Revision: 3c9abb645fb83932c44e8610642393ad62116807
Kotlin DSL: 1.1.1
Kotlin: 1.3.11
Groovy: 2.5.4
Ant: Apache Ant(TM) version 1.9.13 compiled on July 10 2018
JVM: 10.0.2 ("Oracle Corporation" 10.0.2+13)
OS: Windows 10 10.0 amd64
I think for gradle version it uses gradle/wrapper/gradle-wrapper.properties
under the hood.
In addition to performance benefits, CHAR
can be used to indicate that all values should be the same length, e.g., a column for U.S. state abbreviations.
I don't know if this is what you are looking for, but you can achieve this by passing a callback to the child class.
first define a generic callback:
public interface ITypedCallback<T> {
void execute(T type);
}
create a new ITypedCallback instance on ServerConnections instantiation:
public Server(int _address) {
serverConnectionHandler = new ServerConnections(new ITypedCallback<Socket>() {
@Override
public void execute(Socket socket) {
// do something with your socket here
}
});
}
call the execute methode on the callback object.
public class ServerConnections implements Runnable {
private ITypedCallback<Socket> callback;
public ServerConnections(ITypedCallback<Socket> _callback) {
callback = _callback;
}
@Override
public void run() {
try {
mainSocket = new ServerSocket(serverPort);
while (true) {
callback.execute(mainSocket.accept());
}
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
btw: I didn't check if it's 100% correct, directly coded it here.
In a Chrome extension, you can use
chrome.webRequest.onHeadersReceived.addListener
to rewrite the server response headers. You can either replace an existing header or add an additional header. This is the header you want:
Access-Control-Allow-Origin: *
https://developers.chrome.com/extensions/webRequest#event-onHeadersReceived
I was stuck on CORB issues, and this fixed it for me.
How about alias gcc99= gcc -std=c99
?
It depends a bit on your version. Before 5.0.13 this is not possible with mysqldump.
From the mysqldump man page (v 5.1.30)
--routines, -R
Dump stored routines (functions and procedures) from the dumped
databases. Use of this option requires the SELECT privilege for the
mysql.proc table. The output generated by using --routines contains
CREATE PROCEDURE and CREATE FUNCTION statements to re-create the
routines. However, these statements do not include attributes such
as the routine creation and modification timestamps. This means that
when the routines are reloaded, they will be created with the
timestamps equal to the reload time.
...
This option was added in MySQL 5.0.13. Before that, stored routines
are not dumped. Routine DEFINER values are not dumped until MySQL
5.0.20. This means that before 5.0.20, when routines are reloaded,
they will be created with the definer set to the reloading user. If
you require routines to be re-created with their original definer,
dump and load the contents of the mysql.proc table directly as
described earlier.
I resolved that situation in this way. I created a util method that return a object extracted from request body, using the readValue method of ObjectMapper that is capable of receiving a Reader.
public static <T> T getBody(ResourceRequest request, Class<T> class) {
T objectFromBody = null;
try {
ObjectMapper objectMapper = new ObjectMapper();
HttpServletRequest httpServletRequest = PortalUtil.getHttpServletRequest(request);
objectFromBody = objectMapper.readValue(httpServletRequest.getReader(), class);
} catch (IOException ex) {
log.error("Error message", ex);
}
return objectFromBody;
}
To be sure about your path, you can use double quotes " to locate the path or if you are in Windows, you can browse to path to select "C:\Program Files\Java\jdk1.8.0_121\bin"
folder.
SELECT
main.CustomerID,
f.Data AS FirstName,
m.Data AS MiddleName,
l.Data AS LastName,
d.Data AS Date
FROM table main
INNER JOIN table f on f.CustomerID = main.CustomerID
INNER JOIN table m on m.CustomerID = main.CustomerID
INNER JOIN table l on l.CustomerID = main.CustomerID
INNER JOIN table d on d.CustomerID = main.CustomerID
WHERE f.DBColumnName = 'FirstName'
AND m.DBColumnName = 'MiddleName'
AND l.DBColumnName = 'LastName'
AND d.DBColumnName = 'Date'
Edit: I have written this without an editor & have not run the SQL. I hope, you get the idea.
Use tf.train.Saver to save a model, remerber, you need to specify the var_list, if you want to reduce the model size. The val_list can be tf.trainable_variables or tf.global_variables.
<script type="text/javascript">
$(document).ready(function() {
$('#upload').bind("click",function()
{
var imgVal = $('#uploadImage').val();
if(imgVal=='')
{
alert("empty input file");
}
return false;
});
});
</script>
<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload" id="upload" class="send_upload" value="upload" />
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.getString(i));
}
}
When you have the debug console open and the Disable Cache
option turned on, preflight requests will always be sent (i.e. before each and every request). if you don't disable the cache, a pre-flight request will be sent only once (per server)
truncate without zeroes
function toTrunc(value,n){
return Math.floor(value*Math.pow(10,n))/(Math.pow(10,n));
}
or
function toTrunc(value,n){
x=(value.toString()+".0").split(".");
return parseFloat(x[0]+"."+x[1].substr(0,n));
}
test:
toTrunc(17.4532,2) //17.45
toTrunc(177.4532,1) //177.4
toTrunc(1.4532,1) //1.4
toTrunc(.4,2) //0.4
truncate with zeroes
function toTruncFixed(value,n){
return toTrunc(value,n).toFixed(n);
}
test:
toTrunc(17.4532,2) //17.45
toTrunc(177.4532,1) //177.4
toTrunc(1.4532,1) //1.4
toTrunc(.4,2) //0.40
The Error is here
lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1
wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this
lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1
Similarly
wsPOR.Range("A2:G" & lastrow).Select
should be
wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select
I found @Piyush's answer helpful, and just to add to it, if you programatically create a select, then there is an important way to get this behavior that may not be obvious. Let's say you have a function and you create a new select:
var changeitem = function (sel) {
console.log(sel.selectedIndex);
}
var newSelect = document.createElement('select');
newSelect.id = 'newselect';
The normal behavior may be to say
newSelect.onchange = changeitem;
But this does not really allow you to specify that argument passed in, so instead you may do this:
newSelect.setAttribute('onchange', 'changeitem(this)');
And you are able to set the parameter. If you do it the first way, then the argument you'll get to your onchange
function will be browser dependent. The second way seems to work cross-browser just fine.
- First to me Iterating
and Looping
are 2 different things.
Eg: Increment a variable till 5 is Looping.
int count = 0;
for (int i=0 ; i<5 ; i++){
count = count + 1;
}
Eg: Iterate over the Array to print out its values, is about Iteration
int[] arr = {5,10,15,20,25};
for (int i=0 ; i<arr.length ; i++){
System.out.println(arr[i]);
}
Now about all the Loops:
- Its always better to use For-Loop when you know the exact nos of time you gonna Loop, and if you are not sure of it go for While-Loop. Yes out there many geniuses can say that it can be done gracefully with both of them and i don't deny with them...but these are few things which makes me execute my program flawlessly...
For Loop
:
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("The sum is " + sum);
The Difference between While and Do-While is as Follows :
- While
is a Entry Control Loop
, Condition is checked in the Beginning before entering the loop.
- Do-While
is a Exit Control Loop
, Atleast once the block is always executed then the Condition is checked.
While Loop
:
int sum = 0;
int i = 0; // i is 0 Here
while (i<100) {
sum += i;
i++;
}
System.out.println("The sum is " + sum);
do-While
:
int sum = 0;
int i = 0; // i is 0 Here
do{
sum += i;
i++
}while(i < 100; );
System.out.println("The sum is " + sum);
From Java 5 we also have For-Each Loop to iterate over the Collections, even its handy with Arrays.
ArrayList<String> arr = new ArrayList<String>();
arr.add("Vivek");
arr.add("Is");
arr.add("Good");
arr.add("Boy");
for (String str : arr){ // str represents the value in each index of arr
System.out.println(str);
}
Use this expression:
/\(([^()]+)\)/g
e.g:
function()
{
var mts = "something/([0-9])/([a-z])".match(/\(([^()]+)\)/g );
alert(mts[0]);
alert(mts[1]);
}
if data are unique set() will be the most efficient, but of two - dict (which also requires uniqueness, oops :)
Using autoview
image.heightAnchor.constraint(equalToConstant: CGFloat(8)).isActive = true
along with these two variants, there is also jade.renderFile
which generates html that need not be passed to the client.
usage-
var jade = require('jade');
exports.getJson = getJson;
function getJson(req, res) {
var html = jade.renderFile('views/test.jade', {some:'json'});
res.send({message: 'i sent json'});
}
getJson()
is available as a route in app.js.
Make sure you do Run As > Java Application.
If not you could try a Project > Clean
Some more questions that deals with this that could be helpful, Refer this
I recently purchased a MacBook Air (mid-2011 model) and was really happy to find that Apple officially supports Windows 7. If you purchase Windows 7 (I got DSP), you can use the Boot Camp assistant in OSX to designate part of your hard drive to Windows. Then you can install and run Windows 7 natively as if it were as Windows notebook.
I use Visual Studio 2010 on Windows 7 on my MacBook Air (I kept OSX as well) and I could not be happier. Heck, the initial start-up of the program only takes 3 seconds thanks to the SSD.
As others have mentions, you can run it on OSX using Parallels, etc. but I prefer to run it natively.
On thing to remember here is that the default param must be the last param in the function definition.
Following code will not compile:
void fun(int first, int second = 10, int third);
Following code will compile:
void fun(int first, int second, int third = 10);
yes, in a limited sense.
public class DataSet : System.Data.DataSet
{
public static void SpecialMethod() { }
}
This works but Console doesn't because it's static.
public static class Console
{
public static void WriteLine(String x)
{ System.Console.WriteLine(x); }
public static void WriteBlueLine(String x)
{
System.Console.ForegroundColor = ConsoleColor.Blue;
System.Console.Write(.x);
}
}
This works because as long as it's not on the same namespace. The problem is that you have to write a proxy static method for every method that System.Console have. It's not necessarily a bad thing as you can add something like this:
public static void WriteLine(String x)
{ System.Console.WriteLine(x.Replace("Fck","****")); }
or
public static void WriteLine(String x)
{
System.Console.ForegroundColor = ConsoleColor.Blue;
System.Console.WriteLine(x);
}
The way it works is that you hook something into the standard WriteLine. It could be a line count or bad word filter or whatever. Whenever you just specify Console in your namespace say WebProject1 and import the namespace System, WebProject1.Console will be chosen over System.Console as default for those classes in namespace WebProject1. So this code will turn all the Console.WriteLine calls into blue insofar as you never specified System.Console.WriteLine.
<script>
function initMap() {
//echo hiii;
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(8.5241, 76.9366),
zoom: 12
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('package');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
// var name = markerElem.getAttribute('name');
// var address = markerElem.getAttribute('address');
// var type = markerElem.getAttribute('type');
// var latitude = results[0].geometry.location.lat();
// var longitude = results[0].geometry.location.lng();
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('latitude')),
parseFloat(markerElem.getAttribute('longitude'))
);
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var package = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
package.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, package);
});
});
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
I am new to retrofit and I am enjoying it. So here is a simple way to understand it for those that might want to query with more than one query: The ? and & are automatically added for you.
Interface:
public interface IService {
String BASE_URL = "https://api.test.com/";
String API_KEY = "SFSDF24242353434";
@GET("Search") //i.e https://api.test.com/Search?
Call<Products> getProducts(@Query("one") String one, @Query("two") String two,
@Query("key") String key)
}
It will be called this way. Considering you did the rest of the code already.
Call<Results> call = service.productList("Whatever", "here", IService.API_KEY);
For example, when a query is returned, it will look like this.
//-> https://api.test.com/Search?one=Whatever&two=here&key=SFSDF24242353434
Link to full project: Please star etc: https://github.com/Cosmos-it/ILoveZappos
If you found this useful, don't forget to star it please. :)
So this error is occurring because you have a value in your source for the AppID column that is not valid for your AppID column in the destination.
Some possible examples:
SSIS is governed by metadata, and it expects that you've set up your inputs and outputs properly such that the acceptable values for both are within the same range.
when you add a new data set to a geom you need to use the data=
argument. Or put the arguments in the proper order mapping=..., data=...
. Take a look at the arguments for ?geom_line
.
Thus:
p + geom_line(data=df.last, aes(HrEnd, MWh, group=factor(Date)), color="red")
Or:
p + geom_line(aes(HrEnd, MWh, group=factor(Date)), df.last, color="red")
I ended up using matplotlib :)
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
x = [1000,1000,1000,1000,1000,5000,5000,5000,5000,5000,10000,10000,10000,10000,10000]
y = [13,21,29,37,45,13,21,29,37,45,13,21,29,37,45]
z = [75.2,79.21,80.02,81.2,81.62,84.79,87.38,87.9,88.54,88.56,88.34,89.66,90.11,90.79,90.87]
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.2)
plt.show()
Resource is a RESTful subset of Endpoint.
An endpoint by itself is the location where a service can be accessed:
https://www.google.com # Serves HTML
8.8.8.8 # Serves DNS
/services/service.asmx # Serves an ASP.NET Web Service
A resource refers to one or more nouns being served, represented in namespaced fashion, because it is easy for humans to comprehend:
/api/users/johnny # Look up johnny from a users collection.
/v2/books/1234 # Get book with ID 1234 in API v2 schema.
All of the above could be considered service endpoints, but only the bottom group would be considered resources, RESTfully speaking. The top group is not expressive regarding the content it provides.
A REST request is like a sentence composed of nouns (resources) and verbs (HTTP methods):
GET
(method) the user named johnny
(resource).DELETE
(method) the book with id 1234
(resource).Endpoint typically refers to a service, but resource could mean a lot of things. Here are some examples of resource that are dependent on the context they're used in.
Something that can be used to help you:
The library was a valuable resource, and he frequently made use of it.
Resources are natural substances such as water and wood which are valuable in supporting life:
[ pl ] The earth has limited resources, and if we don’t recycle them we use them up.
Resources are also things of value such as money or possessions that you can use when you need them:
[ pl ] The government doesn’t have the resources to hire the number of teachers needed.
The term resource by definition has a lot of nuance. It all depends on the context its used in.
This answer was a little more detailed than I thought but read it through.
DLL:
In most cases, a DLL file is a library. There are a couple of types of libraries, dynamic and static - read about the difference. DLL stands for dynamic link library which tells us that it's a part of the program but not the whole thing. It's made of reusable software components (library) which you could use for more than a single program. Bear in mind that it's always possible to use the library source code in many applications using copy-paste, but the idea of a DLL/Static Library is that you could update the code of a library and at the same time update all the applications using it - without compiling.
For example:
Imagine you're creating a Windows GUI component like a Button. In most cases you'd want to re-use the code you've written because it's a complex but a common component - You want many applications to use it but you don't want to give them the source code You can't copy-paste the code for the button in every program, so you decide you want to create a DL-Library (DLL).
This "button" library is required by EXEcutables to run, and without it they will not run because they don't know how to create the button, only how to talk to it.
Likewise, a DLL cannot be executed - run, because it's only a part of the program but doesn't have the information required to create a "process".
EXE:
An executable is the program. It knows how to create a process and how to talk to the DLL. It needs the DLL to create a button, and without it the application doesn't run - ERROR.
hope this helps....
This is the easiest way to do it: http://jsfiddle.net/thirtydot/jwJBd/
(or with table-layout: fixed
for even width distribution: http://jsfiddle.net/thirtydot/jwJBd/59/)
This won't work in IE7.
#horizontal-style {
display: table;
width: 100%;
/*table-layout: fixed;*/
}
#horizontal-style li {
display: table-cell;
}
#horizontal-style a {
display: block;
border: 1px solid red;
text-align: center;
margin: 0 5px;
background: #999;
}
Old answer before your edit: http://jsfiddle.net/thirtydot/DsqWr/
Public variable declarations in classes is the easiest way:
On target class:
public class MyFragment extends Fragment {
public MyCallerFragment caller; // Declare the caller var
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Do what you want with the vars
caller.str = "I changed your value!";
caller.i = 9999;
...
return inflater.inflate(R.layout.my_fragment, container, false);
}
...
}
On caller class:
public class MyCallerFragment extends Fragment {
public Integer i; // Declared public var
public String str; // Declared public var
...
FragmentManager fragmentManager = getParentFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
myFragment = new MyFragment();
myFragment.caller = this;
transaction.replace(R.id.nav_host_fragment, myFragment)
.addToBackStack(null).commit();
...
}
If you want to use the main activity it is easy too:
On main activity class:
public class MainActivity extends AppCompatActivity {
public String str; // Declare public var
public EditText myEditText; // You can declare public elements too.
// Taking care that you have it assigned
// correctly.
...
}
On called class:
public class MyFragment extends Fragment {
private MainActivity main; // Declare the activity var
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Assign the main activity var
main = (MainActivity) getActivity();
// Do what you want with the vars
main.str = "I changed your value!";
main.myEditText.setText("Wow I can modify the EditText too!");
...
return inflater.inflate(R.layout.my_fragment, container, false);
}
...
}
Note: Take care when using events (onClick, onChanged, etc) because you can be on a "fighting" situation where more than one assign a variable. The result will be that the variable sometimes does not will change or will return to the last value magically.
For more combinations use your creativity. :)
Here is another reason why errors might not be visible:
I had the same issue. In my case, I had copied the source from a production environment. Hence the ENVIRONMENT
variable defined in index.php
was set to 'production'
. This caused error_reporting
to be set to 0 (no logging). Just set it to 'development'
and you should start seeing error messages in apache log.
Turned out the 500 was due to a semi colon missing in database config :-)
this might be old but my answer might help someone
You can simply use
$str = '<textformat leading="2"><p align="left"><font size="10">get me</font></p></textformat>';
echo strip_tags($str);
Easier still: return a pointer to a string that's been malloc'd with strdup.
#include <ncurses.h>
char * getStr(int length)
{
char word[length];
for (int i = 0; i < length; i++)
{
word[i] = getch();
}
word[i] = '\0';
return strdup(&word[0]);
}
int main()
{
char wordd[10];
initscr();
*wordd = getStr(10);
printw("The string is:\n");
printw("%s\n",*wordd);
getch();
endwin();
return 0;
}
The best solution in C#/all static .NET languages is to use the CodeDOM for such things. (As a note, its other main purpose is for dynamically constructing bits of code, or even whole classes.)
Here's a nice short example take from LukeH's blog, which uses some LINQ too just for fun.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
class Program
{
static void Main(string[] args)
{
var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
parameters.GenerateExecutable = true;
CompilerResults results = csc.CompileAssemblyFromSource(parameters,
@"using System.Linq;
class Program {
public static void Main(string[] args) {
var q = from i in Enumerable.Range(1,100)
where i % 2 == 0
select i;
}
}");
results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
}
}
The class of primary importance here is the CSharpCodeProvider
which utilises the compiler to compile code on the fly. If you want to then run the code, you just need to use a bit of reflection to dynamically load the assembly and execute it.
Here is another example in C# that (although slightly less concise) additionally shows you precisely how to run the runtime-compiled code using the System.Reflection
namespace.
Kotlin Code with runOnUiThread
runOnUiThread(
object : Runnable {
override fun run() {
Toast.makeText(applicationContext, "Calling from runOnUiThread()", Toast.LENGTH_SHORT)
}
}
)
Better solution :
window.history.pushState(null, null, window.location.pathname);
By default time zone of laravel project is **UTC*
'timezone' => 'UTC',
now change according to your time zone for me it's Asia/Calcutta
so for me setting will be 'timezone' => 'Asia/Calcutta',
*for time zone list visit this url https://www.w3schools.com/php/php_ref_timezones.asp
This works in my case for getting table name and column name in the corresponding table for indexed fields.
SELECT TABLE_NAME , COLUMN_NAME, COMMENT
FROM information_schema.statistics
WHERE table_schema = 'database_name';
If you want to see the environment variable you just set, you need to open a new command window.
Variables set with setx variables are available in future command windows only, not in the current command window. (Setx, Examples)
you can split a string by line break by using the following statement :
String textStr[] = yourString.split("\\r?\\n");
you can split a string by Whitespace by using the following statement :
String textStr[] = yourString.split("\\s+");
I have this issue, and all I did was make sure that I was referencing the right .Net framework in all the projects then just change the web.config from
From
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
To
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework" requirePermission="false"/>
All works..
If you want them on separate lines do what Balon said. If you want them on the same lines, do:
<td>
<div style="float:left;width:50%;">this is left</div>
<div style="float:right;width:50%;">this is right</div>
</td>
We can have two ways of calling the functions written in pgadmin for postgre sql database.
Suppose we have defined the function as below:
CREATE OR REPLACE FUNCTION helloWorld(name text) RETURNS void AS $helloWorld$
DECLARE
BEGIN
RAISE LOG 'Hello, %', name;
END;
$helloWorld$ LANGUAGE plpgsql;
We can call the function helloworld in one of the following way:
SELECT "helloworld"('myname');
SELECT public.helloworld('myname')
every javascript object is a simple hashmap which accepts a string or a Symbol as its key, so you could write your code as:
var map = {};
// add a item
map[key1] = value1;
// or remove it
delete map[key1];
// or determine whether a key exists
key1 in map;
javascript object is a real hashmap on its implementation, so the complexity on search is O(1), but there is no dedicated hashcode()
function for javascript strings, it is implemented internally by javascript engine (V8, SpiderMonkey, JScript.dll, etc...)
2020 Update:
javascript today supports other datatypes as well: Map
and WeakMap
. They behave more closely as hash maps than traditional objects.
Best way is using BoxDecoration()
Advantage
Disadvantage
BoxDecoration
only use with Container
widget so you want to wrap your widget in Container()
Example
Container(
margin: EdgeInsets.all(10),
padding: EdgeInsets.all(10),
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.orange,
border: Border.all(
color: Colors.pink[800],// set border color
width: 3.0), // set border width
borderRadius: BorderRadius.all(
Radius.circular(10.0)), // set rounded corner radius
boxShadow: [BoxShadow(blurRadius: 10,color: Colors.black,offset: Offset(1,3))]// make rounded corner of border
),
child: Text("My demo styling"),
)
Is there a reason why you aren't using a table variable and the aggregate SUM operator, instead of a cursor? SQL excels at set-oriented operations. 99.87% of the time that you find yourself using a cursor, there's a set-oriented alternative that's more efficient:
declare @MonthsSale table
(
MonthNumber int,
MonthName varchar(9),
MonthSale decimal(18,2)
)
insert into @MonthsSale
select
1, 'January', 100.00
union select
2, 'February', 200.00
union select
3, 'March', 300.00
union select
4, 'April', 400.00
union select
5, 'May', 500.00
union select
6, 'June', 600.00
union select
7, 'July', 700.00
union select
8, 'August', 800.00
union select
9, 'September', 900.00
union select
10, 'October', 1000.00
union select
11, 'November', 1100.00
union select
12, 'December', 1200.00
select * from @MonthsSale
select SUM(MonthSale) as [TotalSales] from @MonthsSale
There's little need to set all the variables you're setting. CMake sets them to reasonable defaults. You should definitely not modify CMAKE_BINARY_DIR
or CMAKE_CACHEFILE_DIR
. Treat these as read-only.
First remove the existing problematic cache file from the src directory:
cd src
rm CMakeCache.txt
cd ..
Then remove all the set()
commands and do:
cd Compile && rm -rf *
cmake ../src
As long as you're outside of the source directory when running CMake, it will not modify the source directory unless your CMakeList explicitly tells it to do so.
Once you have this working, you can look at where CMake puts things by default, and only if you're not satisfied with the default locations (such as the default value of EXECUTABLE_OUTPUT_PATH
), modify only those you need. And try to express them relative to CMAKE_BINARY_DIR
, CMAKE_CURRENT_BINARY_DIR
, PROJECT_BINARY_DIR
etc.
If you look at CMake documentation, you'll see variables partitioned into semantic sections. Except for very special circumstances, you should treat all those listed under "Variables that Provide Information" as read-only inside CMakeLists.
I think the best way is to run a sample code to find the supported locales. I've made a code snippet that does it:
final Locale[] availableLocales=Locale.getAvailableLocales();
for(final Locale locale : availableLocales)
Log.d("Applog",":"+locale.getDisplayName()+":"+locale.getLanguage()+":"
+locale.getCountry()+":values-"+locale.toString().replace("_","-r"));
the columns are : displayName (how it looks to the user), the locale, the variant, and the folder that the developer is supposed to put the strings into.
Here's a table I've made out of the 5.0.1 emulator: https://docs.google.com/spreadsheets/d/1Hx1CTPT82qFSbzuWiU1nyGROCNM6HKssKCPhxinvdww/
Weird thing is that for some cases, I got "#" which is something I've never seen before. It's probably quite new, and the rule I've chosen is probably incorrect for those cases (though it still compiles fine when I put such folders and files), but for the rest it should be fine.
If anyone knows about what the "#" is, and how to handle it, please let me know.
If you want to remove all pending tasks and also the active and reserved ones to completely stop Celery, this is what worked for me:
from proj.celery import app
from celery.task.control import inspect, revoke
# remove pending tasks
app.control.purge()
# remove active tasks
i = inspect()
jobs = i.active()
for hostname in jobs:
tasks = jobs[hostname]
for task in tasks:
revoke(task['id'], terminate=True)
# remove reserved tasks
jobs = i.reserved()
for hostname in jobs:
tasks = jobs[hostname]
for task in tasks:
revoke(task['id'], terminate=True)
Most probably your server socket is bound to the loopback IP address 127.0.0.1
instead of the "all IP addresses" symbolic IP 0.0.0.0
(note this is NOT a netmask). To confirm this, run sudo netstat -ntlp
(If you are on linux) or netstat -an -f inet -p tcp | grep LISTEN
(OSX) and check which IP your process is bound to (look for the line with ":3000"). If you see "127.0.0.1", that's the problem. Fix it by passing "0.0.0.0" to the listen
call:
var app = connect().use(connect.static('public')).listen(3000, "0.0.0.0");
A year after asking the question comes a new article on the subject:
http://erniemiller.org/2014/10/23/in-defense-of-alias/
It seems that "so many men, so many minds." From the former article author encourages to use alias_method
, while the latter suggests using alias
.
However there's a common overview of these methods in both blogposts and answers above:
alias
when you want to limit aliasing to the scope where it's definedalias_method
to allow inherited classes to access itIf you want to define your ItemReader
instance and your Step
instance in a single JavaConfig class. You can use the @StepScope
and the @Value
annotations such as:
@Configuration
public class ContributionCardBatchConfiguration {
private static final String WILL_BE_INJECTED = null;
@Bean
@StepScope
public FlatFileItemReader<ContributionCard> contributionCardReader(@Value("#{jobParameters['fileName']}")String contributionCardCsvFileName){
....
}
@Bean
Step ingestContributionCardStep(ItemReader<ContributionCard> reader){
return stepBuilderFactory.get("ingestContributionCardStep")
.<ContributionCard, ContributionCard>chunk(1)
.reader(contributionCardReader(WILL_BE_INJECTED))
.writer(contributionCardWriter())
.build();
}
}
The trick is to pass a null value to the itemReader since it will be injected through the @Value("#{jobParameters['fileName']}")
annotation.
Thanks to Tobias Flohre for his article : Spring Batch 2.2 – JavaConfig Part 2: JobParameters, ExecutionContext and StepScope
>>> a = set([6, 7, 8, 9, 10, 11, 12])
>>> sub_a = set([6, 9, 12])
>>> a - sub_a
set([8, 10, 11, 7])
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true"
android:drawable="@drawable/pause" />
<item android:state_selected="false"
android:drawable="@drawable/play" />
<!-- default -->
</selector>
<ImageView
android:id="@+id/iv_play"
android:layout_width="@dimen/_50sdp"
android:layout_height="@dimen/_50sdp"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:background="@drawable/pause_button"
android:gravity="center"
android:scaleType="fitXY" />
iv_play = (ImageView) findViewById(R.id.iv_play);
iv_play.setSelected(false);
and also add this
iv_play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
iv_play.setSelected(!iv_play.isSelected());
if (iv_play.isSelected()) {
((GifDrawable) gif_1.getDrawable()).start();
((GifDrawable) gif_2.getDrawable()).start();
} else {
iv_play.setSelected(false);
((GifDrawable) gif_1.getDrawable()).stop();
((GifDrawable) gif_2.getDrawable()).stop();
}
}
});
Json.NET - Documentation
http://james.newtonking.com/json/help/index.html?topic=html/SelectToken.htm
Interpretation for the author
var o = JObject.Parse(response);
var a = o.SelectToken("data").Select(jt => jt.ToObject<TheUser>()).ToList();
Another reason is the use of the C pre-processor for locating declarations. Even with header guards, .h still have to be parsed over and over, every time they're included. Some compilers support pre-compiled headers that can help with this, but they are not always used.
See also: C++ Frequently Questioned Answers
. argument of 0
is interpreted as infinite
. in order to drag the highGUI windows, you need to continually call the cv::waitKey()
function. eg for static images:
cv::imshow("winname", img);
while(cv::waitKey(1) != 27); // 27 = ascii value of ESC
Ugly, hackish, but should work:
select top(M + N - 1) * from TableName
except
select top(N - 1) * from TableName
arrowdodger's answer is correct and preferred on many occasions. I would simply like to add an alternative to his answer:
You could add an "imported" library target, instead of a link-directory. Something like:
# Your-external "mylib", add GLOBAL if the imported library is located in directories above the current.
add_library( mylib SHARED IMPORTED )
# You can define two import-locations: one for debug and one for release.
set_target_properties( mylib PROPERTIES IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/res/mylib.so )
And then link as if this library was built by your project:
TARGET_LINK_LIBRARIES(GLBall mylib)
Such an approach would give you a little more flexibility: Take a look at the add_library( ) command and the many target-properties related to imported libraries.
I do not know if this will solve your problem with "updated versions of libs".
You can try this ! This should work on windows machines.
for /F "usebackq tokens=1,2,3 delims=-" %%I IN (`echo %date%`) do echo "%%I" "%%J" "%%K"
I faced this kind of issue while creating DB from the textfile.
mysql -uroot -padmin < E:\important\sampdb\createdb.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\create_student.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\create_absence.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\insert_student.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\insert_absence.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\load_student.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\load_absence.sql
I just wrote the above lines in Create.bat
and run the bat file.
My mistake is in the sequence order of execution in my sql files. I tried to create table with primary key and also foreign key. While its running it will search for the reference table but tables are not there. So it will return those kind of error.
If you creating tables with foreign key then check the reference tables were present or not. And also check the name of the reference tables and fields.
Depending on the language you're using it's going to be something simple like
CInt(CDate("1970-1-1") - CDate(Today()))
Ironically enough, yesterday was day 40,000 if you use 1/1/1900 as "day zero" like many computer systems use.
Code for dealing with scope variables should go in controller, and service calls go to the service.
You can inject $rootScope
for the purpose of using $rootScope.$broadcast
and $rootScope.$on
.
Otherwise avoid injecting $rootScope
. See
Try one of these other mime-types (from here: http://filext.com/file-extension/CSV )
Also, the mime-type might be case sensitive...
Integration Services project templates are now available in the latest release of SSDT for Visual Studio 2017.
Note: if you have recently installed SSDT for Visual Studio 2017. You need to remove the Reporting Services and Analysis Services installations before you proceed with installing SSDT.
In Pandas version 1.10 and above you can use parameters xlabel
and ylabel
in the method plot
:
df.plot(xlabel='X Label', ylabel='Y Label', title='Plot Title')
I don't know of a better way but you can datamine the page with php. For instance if you go to google and share a folder then go to that folder it will look something like
https://drive.google.com/folderview?id=0B8TT0olkjsdkfji9jekbFF4LWc&usp=sharing
^^^ not a real link
What you are looking for is the individual images inside the source code of this page
then using php get the source code with
<? $f = fopen ("http://www.example.com/f", r);
echo $f;
?>
now $f has the source and you can use other php commands to seperate only the URLS with the images you want. It will take a bit of work but highly doable.
once you have these image links showing the way you want just build them into a div or table structure to display on a gallery maybe even add a greybox element for effect
An alternative that worked for me is to tell Maven to use http: instead of https: when using Maven Central by adding the following to settings.xml:
<settings>
.
.
.
<mirrors>
<mirror>
<id>central-no-ssl</id>
<name>Central without ssl</name>
<url>http://repo.maven.apache.org/maven2</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
.
.
.
</settings>
Your mileage may vary of course.
If you are checking if an instance of a custom class or struct is contained in an array, you'll need to implement the Equatable protocol before you can use .contains(myObject).
For example:
struct Cup: Equatable {
let filled:Bool
}
static func ==(lhs:Cup, rhs:Cup) -> Bool { // Implement Equatable
return lhs.filled == rhs.filled
}
then you can do:
cupArray.contains(myCup)
Tip: The == override should be at the global level, not within your class/struct
You are not initializing connection.That's why this kind of error is coming to you.
Your code:
cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ");
Corrected code:
cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ",connection1);
Thanks Rich, I will take note of that. So here is the script for my own solution. It requires no third party unzip tools.
Include the script below at the start of the batch file to create the function, and then to call the function, the command is...
cscript /B j_unzip.vbs zip_file_name_goes_here.zip
Here is the script to add to the top...
REM Changing working folder back to current directory for Vista & 7 compatibility %~d0 CD %~dp0 REM Folder changed REM This script upzip's files... > j_unzip.vbs ECHO ' >> j_unzip.vbs ECHO ' UnZip a file script >> j_unzip.vbs ECHO ' >> j_unzip.vbs ECHO ' It's a mess, I know!!! >> j_unzip.vbs ECHO ' >> j_unzip.vbs ECHO. >> j_unzip.vbs ECHO ' Dim ArgObj, var1, var2 >> j_unzip.vbs ECHO Set ArgObj = WScript.Arguments >> j_unzip.vbs ECHO. >> j_unzip.vbs ECHO If (Wscript.Arguments.Count ^> 0) Then >> j_unzip.vbs ECHO. var1 = ArgObj(0) >> j_unzip.vbs ECHO Else >> j_unzip.vbs ECHO. var1 = "" >> j_unzip.vbs ECHO End if >> j_unzip.vbs ECHO. >> j_unzip.vbs ECHO If var1 = "" then >> j_unzip.vbs ECHO. strFileZIP = "example.zip" >> j_unzip.vbs ECHO Else >> j_unzip.vbs ECHO. strFileZIP = var1 >> j_unzip.vbs ECHO End if >> j_unzip.vbs ECHO. >> j_unzip.vbs ECHO 'The location of the zip file. >> j_unzip.vbs ECHO REM Set WshShell = CreateObject("Wscript.Shell") >> j_unzip.vbs ECHO REM CurDir = WshShell.ExpandEnvironmentStrings("%%cd%%") >> j_unzip.vbs ECHO Dim sCurPath >> j_unzip.vbs ECHO sCurPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".") >> j_unzip.vbs ECHO strZipFile = sCurPath ^& "\" ^& strFileZIP >> j_unzip.vbs ECHO 'The folder the contents should be extracted to. >> j_unzip.vbs ECHO outFolder = sCurPath ^& "\" >> j_unzip.vbs ECHO. >> j_unzip.vbs ECHO. WScript.Echo ( "Extracting file " ^& strFileZIP) >> j_unzip.vbs ECHO. >> j_unzip.vbs ECHO Set objShell = CreateObject( "Shell.Application" ) >> j_unzip.vbs ECHO Set objSource = objShell.NameSpace(strZipFile).Items() >> j_unzip.vbs ECHO Set objTarget = objShell.NameSpace(outFolder) >> j_unzip.vbs ECHO intOptions = 256 >> j_unzip.vbs ECHO objTarget.CopyHere objSource, intOptions >> j_unzip.vbs ECHO. >> j_unzip.vbs ECHO. WScript.Echo ( "Extracted." ) >> j_unzip.vbs ECHO.
I suggest split (not saying that the other answers are invalid, this is just another way to do it):
def findreplace(char, string):
return ''.join(string.split(char))
Splitting by a character removes all the characters and turns it into a list. Then we join the list with the join function. You can see the ipython console test below
In[112]: findreplace('i', 'it is icy')
Out[112]: 't s cy'
And the speed...
In[114]: timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
Out[114]: 0.9927914671134204
Not as fast as replace or translate, but ok.
Public Function arrayIsEmpty(arrayToCheck() As Variant) As Boolean
On Error GoTo Err:
Dim forCheck
forCheck = arrayToCheck(0)
arrayIsEmpty = False
Exit Function
Err:
arrayIsEmpty = True
End Function
Change string[] lines = File.ReadLines("c:\\file.txt");
to IEnumerable<string> lines = File.ReadLines("c:\\file.txt");
The rest of your code should work fine.
Use this
<xsl:text disable-output-escaping="yes">&</xsl:text>nbsp;
edit: Downvoters should probably validate that this works first (it does, and is the most general solution to the problem.)
Try this:
while read line
do
echo -e |wc -m
done <abc.txt
<script>
var url= "http://www.google.com";
window.location = url;
</script>
Unique annotation should be placed right above the attribute declaration. UniqueContraints go into the @Table annotation above the data class declaration. See below:
@Entity
@Table(uniqueConstraints= arrayOf(UniqueConstraint(columnNames = arrayOf("col_1", "col_2"))))
data class Action(
@Id @GeneratedValue @Column(unique = true)
val id: Long?,
val col_1: Long?,
val col_2: Long?,
)
If you don't mind using absolute positioning, you can position your background image, and then add an overlay using opacity.
div {
width:50px;
height:50px;
background: url('http://images1.wikia.nocookie.net/__cb20120626155442/adventuretimewithfinnandjake/images/6/67/Link.gif');
position:absolute;
left:0;
top:0;
}
.overlay {
background:red;
opacity:.5;
}
See here: http://jsfiddle.net/4yh9L/
Aside from pandas, Apache pyarrow also provides way to transform parquet to dataframe
The code is simple, just type:
import pyarrow.parquet as pq
df = pq.read_table(source=your_file_path).to_pandas()
For more information, see the document from Apache pyarrow Reading and Writing Single Files
No libraries no complications just simple:
console.log(red('Error!'));
function red(s) {
return '\033[31m' + s;
}
The other answers explained it well already, but I'd like to offer another experiment illustrating the nature of range objects:
>>> r = range(5)
>>> for i in r:
print(i, 2 in r, list(r))
0 True [0, 1, 2, 3, 4]
1 True [0, 1, 2, 3, 4]
2 True [0, 1, 2, 3, 4]
3 True [0, 1, 2, 3, 4]
4 True [0, 1, 2, 3, 4]
As you can see, a range object is an object that remembers its range and can be used many times (even while iterating over it), not just a one-time generator.
"Global" JavaScript variables are members of the window object. You could access the reference as a member of the window object.
var v = "initialized";
function byref(ref) {
window[ref] = "changed by ref";
}
byref((function(){for(r in window){if(window[r]===v){return(r);}}})());
// It could also be called like... byref('v');
console.log(v); // outputs changed by ref
Note, the above example will not work for variables declared within a function.
Pelo Hyper-V:
private PerformanceCounter theMemCounter = new PerformanceCounter(
"Hyper-v Dynamic Memory VM",
"Physical Memory",
Process.GetCurrentProcess().ProcessName);
Assuming you're passing in strings rather than integers, try casting the arguments to integers:
def example(arg1, arg2, arg3):
if int(arg1) == 1 and int(arg2) == 2 and int(arg3) == 3:
print("Example Text")
(Edited to emphasize I'm not asking for clarification; I was trying to be diplomatic in my answer. )
don't do anything just type in your command prompt
C:\> sh
then you got like this
sh-4.4$
# type here
ssh-4.4$ ssh-keygen -t rsa -b 4096 -C "[email protected]"
this should must work.
use box-shadow
with no horizontal offset.
http://www.css3.info/preview/box-shadow/
eg.
div {_x000D_
-webkit-box-shadow: 0 10px 5px #888888;_x000D_
-moz-box-shadow: 0 10px 5px #888888;_x000D_
box-shadow: 0 10px 5px #888888;_x000D_
}
_x000D_
<div>wefwefwef</div>
_x000D_
There will be a slight shadow on the sides with a large blur radius (5px in above example)
first, store the last time the user made a request
<?php
$_SESSION['timeout'] = time();
?>
in subsequent request, check how long ago they made their previous request (10 minutes in this example)
<?php
if ($_SESSION['timeout'] + 10 * 60 < time()) {
// session timed out
} else {
// session ok
}
?>
The ideal solution would be to use inline-block
for the columns instead of floating. I think the browser support is pretty good if you follow (a) apply inline-block
only to elements that are normally inline (eg span
); and (b) add -moz-inline-box
for Firefox.
Check your page in FF2 as well because I had a ton of problems when nesting certain elements (surprisingly, this is the one case where IE performs much better than FF).
The result of a subtraction generating a negative number in an unsigned type is well-defined:
- [...] A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type. (ISO/IEC 9899:1999 (E) §6.2.5/9)
As you can see, (unsigned)0 - (unsigned)1
equals -1 modulo UINT_MAX+1, or in other words, UINT_MAX.
Note that although it does say "A computation involving unsigned operands can never overflow", which might lead you to believe that it applies only for exceeding the upper limit, this is presented as a motivation for the actual binding part of the sentence: "a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type." This phrase is not restricted to overflow of the upper bound of the type, and applies equally to values too low to be represented.
use &
in place of &
change to
<string name="magazine">Newspaper & Magazines</string>
An example using SFINAE and template partial specialization, by writing a Has_foo
concept check:
#include <type_traits>
struct A{};
struct B{ int foo(int a, int b);};
struct C{void foo(int a, int b);};
struct D{int foo();};
struct E: public B{};
// available in C++17 onwards as part of <type_traits>
template<typename...>
using void_t = void;
template<typename T, typename = void> struct Has_foo: std::false_type{};
template<typename T>
struct Has_foo<T, void_t<
std::enable_if_t<
std::is_same<
int,
decltype(std::declval<T>().foo((int)0, (int)0))
>::value
>
>>: std::true_type{};
static_assert(not Has_foo<A>::value, "A does not have a foo");
static_assert(Has_foo<B>::value, "B has a foo");
static_assert(not Has_foo<C>::value, "C has a foo with the wrong return. ");
static_assert(not Has_foo<D>::value, "D has a foo with the wrong arguments. ");
static_assert(Has_foo<E>::value, "E has a foo since it inherits from B");
sometime you missed some file like I missed my one file rt.java
so better to check yours .........
C:\Program Files\Java\jdk1.8.0_112\jre\lib
In addition to the good advice already given, I would add this:
It is probably best to avoid using require()
unless you actually will be using the value it returns e.g in some error checking loop such as given by thierry.
In most other cases it is better to use library()
, because this will give an error message at package loading time if the package is not available. require()
will just fail without an error if the package is not there. This is the best time to find out if the package needs to be installed (or perhaps doesn't even exist because it it spelled wrong). Getting error feedback early and at the relevant time will avoid possible headaches with tracking down why later code fails when it attempts to use library routines
To disable certain items:
MenuItem item = menu.findItem(R.id.ID_ASSING_TO_THE_ITEM_IN_MENU_XML);
item.setEnabled(false);
You can press OK and install xampp to C:\xampp and not into program files
You can also create your plot using ggvis:
library(ggvis)
x <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x,1,1)
df <- data.frame(x, y1, y2)
df %>%
ggvis(~x, ~y1, stroke := 'red') %>%
layer_paths() %>%
layer_paths(data = df, x = ~x, y = ~y2, stroke := 'blue')
This will create the following plot:
In my Jenkins instance (version 1.548) the configuration file is at:
/var/lib/jenkins/jobs/-the-project-name-/config.xml
Owned by jenkins user and jenkins group with 644 permissions. Copying the file to and from here should work. I haven't tried changing it directly but have backed-up the config from this spot in case the project needs to be setup again.
This fixed the problem I had on CentOS
sudo yum install java-1.8.0-openjdk-devel
The important thing is that the icon you want to be displayed as the application icon ( in the title bar and in the task bar ) must be the FIRST icon in the resource script file
The file is in the res folder and is named (applicationName).rc
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
(icon ID ) ICON "res\\filename.ico"
Maybe off-topic, but R features two nice, fast and empty-aware functions for reducing logical vectors -- any
and all
:
if(any(x=='dolphin')) stop("Told you, no mammals!")
You are passing floats to a classifier which expects categorical values as the target vector. If you convert it to int
it will be accepted as input (although it will be questionable if that's the right way to do it).
It would be better to convert your training scores by using scikit's labelEncoder
function.
The same is true for your DecisionTree and KNeighbors qualifier.
from sklearn import preprocessing
from sklearn import utils
lab_enc = preprocessing.LabelEncoder()
encoded = lab_enc.fit_transform(trainingScores)
>>> array([1, 3, 2, 0], dtype=int64)
print(utils.multiclass.type_of_target(trainingScores))
>>> continuous
print(utils.multiclass.type_of_target(trainingScores.astype('int')))
>>> multiclass
print(utils.multiclass.type_of_target(encoded))
>>> multiclass
You may also want to look at rsync if you're doing a lot of files.
If you're going to making a lot of changes and want to keep your directories and files in sync, you may want to use a version control system like Subversion or Git. See http://xoa.petdance.com/How_to:_Keep_your_home_directory_in_Subversion
full solution here:
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:checked="true"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:layout_marginTop="20dp"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:layout_marginTop="20dp"
android:text="RadioButton" />
</RadioGroup>
selector XML
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/orange_btn_selected" android:state_checked="true"/>
<item android:drawable="@drawable/orange_btn_unselected" android:state_checked="false"/>
</selector>
it will create the file in the root directory of your project/solution.
You can specify a location of choice in the web.config of your app as follows:
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="c:/ServiceLogs/Olympus.Core.log" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value=".yyyyMMdd.log" />
<maximumFileSize value="5MB" />
<staticLogFileName value="true" />
<lockingModel type="log4net.Appender.RollingFileAppender+MinimalLock" />
<maxSizeRollBackups value="-1" />
<countDirection value="1" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level [%thread] %logger - %message%newline%exception" />
</layout>
</appender>
the file tag specifies the location.
You MUST add below part to enable NameVirtualHost
functionality with given IP.
NameVirtualHost IP_Address:443
You are using <input name='C[]'
in your HTML. This creates an array in PHP when the form is sent.
You are using echo $_POST['C'];
to echo that array - this will not work, but instead emit that notice and the word "Array".
Depending on what you did with the rest of the code, you should probably use echo $_POST['C'][0];
You can use esentutl to copy (mainly big) files with a progress bar:
esentutl /y "my.file" /d "another.file" /o
the progress bar looks like this:
pd.datetime.now().strftime("%d/%m/%Y")
this will give output as '11/02/2019'
you can use add time if you want
pd.datetime.now().strftime("%d/%m/%Y %I:%M:%S")
this will give output as '11/02/2019 11:08:26'
I think using document.bind is a bit more elegant
constructor($scope, $document) {
var that = this;
$document.bind("keydown", function(event) {
$scope.$apply(function(){
that.handleKeyDown(event);
});
});
}
To get document to the controller constructor:
controller: ['$scope', '$document', MyCtrl]
If you simply want to see the column names this one line should provide it without changing any settings:
describe database.tablename;
However, if that doesn't work for your version of hive this code will provide it, but your default database will now be the database you are using:
use database;
describe tablename;
Let me try a complex computation using datetime and considering nulls or empty spaces. I am reducing 30 years on a datetime column and using apply
method as well as lambda
and converting datetime format. Line if x != '' else x
will take care of all empty spaces or nulls accordingly.
df['Date'] = df['Date'].fillna('')
df['Date'] = df['Date'].apply(lambda x : ((datetime.datetime.strptime(str(x), '%m/%d/%Y') - datetime.timedelta(days=30*365)).strftime('%Y%m%d')) if x != '' else x)
$ PATH=$PATH:/Library/PostgreSQL/9.1/bin sudo gem install pg
replace the 9.1 for the version installed on your system.
Kotlin Code for getting DeviceId ( IMEI ) with handling permission & comparability check for all android versions :
val telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
== PackageManager.PERMISSION_GRANTED) {
// Permission is granted
val imei : String? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) telephonyManager.imei
// older OS versions
else telephonyManager.deviceId
imei?.let {
Log.i("Log", "DeviceId=$it" )
}
} else { // Permission is not granted
}
Also add this permission to AndroidManifest.xml :
<uses-permission android:name="android.permission.READ_PHONE_STATE"/> <!-- IMEI-->
I realize this has been answered, but I used a different approach and thought it might be worth sharing. Also, I feel like my approach might produce unwanted overhead. However, I'm not able to observer or calculate anything happening that is that bad under the loads we observe. I was looking for any useful feedback on this approach.
The problem with working with dynamics is that you can't attach any functions to the dynamic object directly. You have to use something that can figure out the assignments that you don't want to figure out every time.
When planning this simple solution, I looked at what the valid intermediaries are when attempting to retype similar objects. I found that a binary array, string (xml, json) or hard coding a conversion (IConvertable) were the usual approaches. I don't want to get into binary conversions due to a code maintainability factor and laziness.
My theory was that Newtonsoft could do this by using a string intermediary.
As a downside, I am fairly certain that when converting the string to an object, that it would use reflection by searching the current assembly for an object with matching properties, create the type, then instantiate the properties, which would require more reflection. If true, all of this can be considered avoidable overhead.
C#:
//This lives in a helper class
public static ConvertDynamic<T>(dynamic data)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(Newtonsoft.Json.JsonConvert.SerializeObject(data));
}
//Same helper, but in an extension class (public static class),
//but could be in a base class also.
public static ToModelList<T>(this List<dynamic> list)
{
List<T> retList = new List<T>();
foreach(dynamic d in list)
{
retList.Add(ConvertDynamic<T>(d));
}
}
With that said, this fits another utility I've put together that lets me make any object into a dynamic. I know I had to use reflection to do that correctly:
public static dynamic ToDynamic(this object value)
{
IDictionary<string, object> expando = new ExpandoObject();
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
expando.Add(property.Name, property.GetValue(value));
return expando as ExpandoObject;
}
I had to offer that function. An arbitrary object assigned to a dynamic typed variable cannot be converted to an IDictionary, and will break the ConvertDynamic function. For this function chain to be used it has to be provided a dynamic of System.Dynamic.ExpandoObject, or IDictionary<string, object>.
<head>
<script>
function myFunction() {
var x;
var r = confirm("Do you want to clear data?");
if (r == true) {
x = "Your Data is Cleared";
window.location.href = "firstpage.php";
}
else {
x = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = x;
}
</script>
</head>
<body>
<button onclick="myFunction()">Retest</button>
<p id="demo"></p>
</body>
</html>
This will redirect to new php page.
The answer of Fabio is really good but it take a long execution time (as Trilarion already has written)
I have an other solution with faster execution.
START TRANSACTION;
set @N := (now());
INSERT INTO table2 select * from table1 where ts < date_sub(@N,INTERVAL 32 DAY);
DELETE FROM table1 WHERE ts < date_sub(@N,INTERVAL 32 DAY);
COMMIT;
@N gets the Timestamp at the begin and is used for both commands. All is in a Transaction to be sure nobody is disturbing
{{game.gameDate | date('c')}} // 2014-02-05T16:45:22+00:00
For full date time string including timezone offset.
One solution that I haven't seen mentioned here, is using session storage instead of cookies. Of course this might not fit everyone's requirements, but for some cases it's an easy fix.
Calling async
code from synchronous code can be quite tricky.
I explain the full reasons for this deadlock on my blog. In short, there's a "context" that is saved by default at the beginning of each await
and used to resume the method.
So if this is called in an UI context, when the await
completes, the async
method tries to re-enter that context to continue executing. Unfortunately, code using Wait
(or Result
) will block a thread in that context, so the async
method cannot complete.
The guidelines to avoid this are:
ConfigureAwait(continueOnCapturedContext: false)
as much as possible. This enables your async
methods to continue executing without having to re-enter the context.async
all the way. Use await
instead of Result
or Wait
.If your method is naturally asynchronous, then you (probably) shouldn't expose a synchronous wrapper.
If your problem is retaining the Console Window within Visual Studio without modifying your application (c-code) and are running it with Ctrl+F5 (when running Ctrl+F5) but the window is still closing the principal hint is to set the /SUBSYSTEM:CONSOLE linker option in your Visual Studio project.
as explained by DJMooreTX in http://social.msdn.microsoft.com/Forums/en-US/vcprerelease/thread/21073093-516c-49d2-81c7-d960f6dc2ac6
1) Open up your project, and go to the Solution Explorer. If you're following along with me in K&R, your "Solution" will be 'hello' with 1 project under it, also 'hello' in bold.
Right click on the 'hello" (or whatever your project name is.)
Choose "Properties" from the context menu.
Choose Configuration Properties>Linker>System.
For the "Subsystem" property in the right-hand pane, click the drop-down box in the right hand column.
Choose "Console (/SUBSYSTEM:CONSOLE)"
Click Apply, wait for it to finish doing whatever it does, then click OK. (If "Apply" is grayed out, choose some other subsystem option, click Apply, then go back and apply the console option. My experience is that OK by itself won't work.)
Now do Boris' CTRL-F5, wait for your program to compile and link, find the console window under all the other junk on your desktop, and read your program's output, followed by the beloved "Press any key to continue...." prompt.
Again, CTRL-F5 and the subsystem hints work together; they are not separate options.
req.query
will return a JS object after the query string is parsed.
/user?name=tom&age=55 - req.query
would yield {name:"tom", age: "55"}
req.params
will return parameters in the matched route.
If your route is /user/:id and you make a request to /user/5 - req.params
would yield {id: "5"}
req.param
is a function that peels parameters out of the request. All of this can be found here.
UPDATE
If the verb is a POST
and you are using bodyParser
, then you should be able to get the form body in you function with req.body
. That will be the parsed JS version of the POST
ed form.
This script does the trick! Just paste it into the top of your bat file. If you want to review the output of your script, add a "pause" command at the bottom of your batch file.
UPDATE: This script is now slightly edited to support command line arguments and a 64 bit OS.
Thank you Eneerge @ https://sites.google.com/site/eneerge/scripts/batchgotadmin
@echo off
:: BatchGotAdmin
:-------------------------------------
REM --> Check for permissions
IF "%PROCESSOR_ARCHITECTURE%" EQU "amd64" (
>nul 2>&1 "%SYSTEMROOT%\SysWOW64\cacls.exe" "%SYSTEMROOT%\SysWOW64\config\system"
) ELSE (
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
)
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
echo Requesting administrative privileges...
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params= %*
echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params:"=""%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------
<YOUR BATCH SCRIPT HERE>
The Easiest way to do it is to have good site structure and write it as a constant.
DEFINE("BACK_ROOT","/var/www/");
One more way that might be helpful - to use some kind of "alias". For example:
public enum Status
{
New = 10,
Old = 20,
Actual = 30,
// Use Status.Default to specify default status in your code.
Default = New
}
$("#myNode").parent(x).html();
Where 'x' is the node number, beginning with 0 as the first one, should get the right node you want, if you're trying to get a specific one. If you have child nodes, you should really be putting an ID on the one you want, though, to just zero in on that one. Using that methodology and no 'x' worked fine for me.
Old, but maybe useful for readers to have a full example of how use modal.
I do like following ( working example jsfiddle ) :
$('button.btn.btn-success').click(function(event)
{
event.preventDefault();
$.post('getpostcodescript.php', $('form').serialize(), function(data, status, xhr)
{
// do something here with response;
console.info(data);
console.info(status);
console.info(xhr);
})
.done(function() {
// do something here if done ;
alert( "saved" );
})
.fail(function() {
// do something here if there is an error ;
alert( "error" );
})
.always(function() {
// maybe the good state to close the modal
alert( "finished" );
// Set a timeout to hide the element again
setTimeout(function(){
$("#myModal").hide();
}, 3000);
});
});
To deal easier with modals, I recommend using eModal, which permit to go faster on base use of bootstrap 3 modals.
Because it's not.
Indexing is covered by IList
. IEnumerable
means "I have some of the powers of IList, but not all of them."
Some collections (like a linked list), cannot be indexed in a practical way. But they can be accessed item-by-item. IEnumerable
is intended for collections like that. Note that a collection can implement both IList & IEnumerable (and many others). You generally only find IEnumerable
as a function parameter, meaning the function can accept any kind of collection, because all it needs is the simplest access mode.
Why not use the following: (from Draw custom Back button on iPhone Navigation Bar)
// Add left
UINavigationItem *previousItem = [[UINavigationItem alloc] initWithTitle:@"Back title"];
UINavigationItem *currentItem = [[UINavigationItem alloc] initWithTitle:@"Main Title"];
[self.navigationController.navigationBar setItems:[NSArray arrayWithObjects:previousItem, currentItem, nil] animated:YES];
// set the delegate to self
[self.navigationController.navigationBar setDelegate:self];
In lightsail a virtual machine, SSD-based storage, data transfer, DNS management, and a static IP are all offered as a package. Whereas in normal case you provision an EC2 instance and then setup the rest of these things.Also Bandwidth included in the price, no security groups to set up, no need to worry about EBS volumes sizing.
SELECT COLUMN_NAME
FROM YourDatabase.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTableName'
The selected answer is out of date and no others worked for me (Django 1.6 and [apparantly] no registered namespace.)
For Django 1.5 and later (from the docs)
Warning Don’t forget to put quotes around the function path or pattern name!
With a named URL you could do:
(r'^login/', login_view, name='login'),
...
<a href="{% url 'login' %}">logout</a>
Just as easy if the view takes another parameter
def login(request, extra_param):
...
<a href="{% url 'login' 'some_string_containing_relevant_data' %}">login</a>
WebViewClient provides the following callback methods, with which you can interfere in how WebView
makes a transition to the next content.
void doUpdateVisitedHistory (WebView view, String url, boolean isReload)
void onFormResubmission (WebView view, Message dontResend, Message resend)
void onLoadResource (WebView view, String url)
void onPageCommitVisible (WebView view, String url)
void onPageFinished (WebView view, String url)
void onPageStarted (WebView view, String url, Bitmap favicon)
void onReceivedClientCertRequest (WebView view, ClientCertRequest request)
void onReceivedError (WebView view, int errorCode, String description, String failingUrl)
void onReceivedError (WebView view, WebResourceRequest request, WebResourceError error)
void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm)
void onReceivedHttpError (WebView view, WebResourceRequest request, WebResourceResponse errorResponse)
void onReceivedLoginRequest (WebView view, String realm, String account, String args)
void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error)
boolean onRenderProcessGone (WebView view, RenderProcessGoneDetail detail)
void onSafeBrowsingHit (WebView view, WebResourceRequest request, int threatType, SafeBrowsingResponse callback)
void onScaleChanged (WebView view, float oldScale, float newScale)
void onTooManyRedirects (WebView view, Message cancelMsg, Message continueMsg)
void onUnhandledKeyEvent (WebView view, KeyEvent event)
WebResourceResponse shouldInterceptRequest (WebView view, WebResourceRequest request)
WebResourceResponse shouldInterceptRequest (WebView view, String url)
boolean shouldOverrideKeyEvent (WebView view, KeyEvent event)
boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request)
boolean shouldOverrideUrlLoading (WebView view, String url)
WebChromeClient provides the following callback methods, with which your Activity
or Fragment
can update the surroundings of WebView
.
Bitmap getDefaultVideoPoster ()
View getVideoLoadingProgressView ()
void getVisitedHistory (ValueCallback<String[]> callback)
void onCloseWindow (WebView window)
boolean onConsoleMessage (ConsoleMessage consoleMessage)
void onConsoleMessage (String message, int lineNumber, String sourceID)
boolean onCreateWindow (WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg)
void onExceededDatabaseQuota (String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, WebStorage.QuotaUpdater quotaUpdater)
void onGeolocationPermissionsHidePrompt ()
void onGeolocationPermissionsShowPrompt (String origin, GeolocationPermissions.Callback callback)
void onHideCustomView ()
boolean onJsAlert (WebView view, String url, String message, JsResult result)
boolean onJsBeforeUnload (WebView view, String url, String message, JsResult result)
boolean onJsConfirm (WebView view, String url, String message, JsResult result)
boolean onJsPrompt (WebView view, String url, String message, String defaultValue, JsPromptResult result)
boolean onJsTimeout ()
void onPermissionRequest (PermissionRequest request)
void onPermissionRequestCanceled (PermissionRequest request)
void onProgressChanged (WebView view, int newProgress)
void onReachedMaxAppCacheSize (long requiredStorage, long quota, WebStorage.QuotaUpdater quotaUpdater)
void onReceivedIcon (WebView view, Bitmap icon)
void onReceivedTitle (WebView view, String title)
void onReceivedTouchIconUrl (WebView view, String url, boolean precomposed)
void onRequestFocus (WebView view)
void onShowCustomView (View view, int requestedOrientation, WebChromeClient.CustomViewCallback callback)
void onShowCustomView (View view, WebChromeClient.CustomViewCallback callback)
boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
Some time ago I wrote simple Webcam Capture API which can be used for that. The project is available on Github.
Example code:
Webcam webcam = Webcam.getDefault();
webcam.open();
try {
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));
} catch (IOException e) {
e.printStackTrace();
} finally {
webcam.close();
}
Because of the GDPR it makes no sense to use the iframe, you should rather use the object tag with the embed tag and also use the embed link.
<object width="100%" height="333">
<param name="movie" value="https://www.youtube-nocookie.com/embed/Sdg0ef2PpBw">
<embed src="https://www.youtube-nocookie.com/embed/Sdg0ef2PpBw" width="100%" height="333">
</object>
_x000D_
You should also activate the extended data protection mode function to receive the no cookie url.
type="application/x-shockwave-flash"
flash does not have to be used
Nocookie, however, means that data is still being transmitted, namely the thumbnail that is loaded from YouTube. But at least data is no longer passed on to advertising networks (as example DoubleClick). And no user data is stored on your website by youtube.
Generally speaking, people refer to an application's presentation layer as its front end, its persistence layer (database, usually) as the back end, and anything between as middle tier. This set of ideas is often referred to as 3-tier architecture. They let you separate your application into more easily comprehensible (and testable!) chunks; you can also reuse lower-tier code more easily in higher tiers.
Which code is part of which tier is somewhat subjective; graphic designers tend to think of everything that isn't presentation as the back end, database people think of everything in front of the database as the front end, and so on.
Not all applications need to be separated out this way, though. It's certainly more work to have 3 separate sub-projects than it is to just open index.php and get cracking; depending on (1) how long you expect to have to maintain the app (2) how complex you expect the app to get, you may want to forgo the complexity.
PLEASE NOTE: THE ANSWER BELOW IS HORRIBLY OUTDATED, AND MIGHT NOT BE ENTIRELY CORRECT ANYMORE.
You can program in C/C++ using the Android NDK. You'll have to wrap your c++ codebase in a static library and load that through a Java wrapper & JNI.
The standard NDK does not support RTTI and a lot of the functionality of standard c++ is also not available such as std::string, etc. To solve this you can recompile the NDK. Dmitry Moskalchuk supplies a modified version of the NDK that supports this at http://www.crystax.net/android/ndk-r3.php. This modified version works on all Android phones that run on an ARM processor.
Depending on the kind of application you should decide to use Java or C/C++. I'd use C/C++ for anything that requires above average computational power and games -- Java for the rest.
Just pick one language and write the majority of your application in that language; JNI calls can decrease your performance by a lot. Java isn't that hard though -- if you know how to program in C/C++. The advantage of Java is that the application can run on any device running Android, where as NDK applications depend on the architecture it was compiled for.
If you're going to have a lot of inheritence (that's the case here) I suggest you to pass all parameters using **kwargs
, and then pop
them right after you use them (unless you need them in upper classes).
class First(object):
def __init__(self, *args, **kwargs):
self.first_arg = kwargs.pop('first_arg')
super(First, self).__init__(*args, **kwargs)
class Second(First):
def __init__(self, *args, **kwargs):
self.second_arg = kwargs.pop('second_arg')
super(Second, self).__init__(*args, **kwargs)
class Third(Second):
def __init__(self, *args, **kwargs):
self.third_arg = kwargs.pop('third_arg')
super(Third, self).__init__(*args, **kwargs)
This is the simplest way to solve those kind of problems.
third = Third(first_arg=1, second_arg=2, third_arg=3)
You need to return a Callable<>
if you want spring.mvc.async.request-timeout=5000
to work.
@RequestMapping(method = RequestMethod.GET)
public Callable<String> getFoobar() throws InterruptedException {
return new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(8000); //this will cause a timeout
return "foobar";
}
};
}
df[cols] = pd.to_numeric(df[cols].stack(), errors='coerce').unstack()
This should do the trick.
<activity ... android:launchMode="singleTop" />
When you create an intent to start the app use:
Intent intent= new Intent(context, YourActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
This is that should be needed.
This code sample can be used to change date format. Here I want to change from yyyy-MM-dd to dd-MM-yyyy. Here pos
is position of column.
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
class Test{
public static void main( String[] args )
{
String input="D:\\somefolder\\somefile.xlsx";
String output="D:\\somefolder\\someoutfile.xlsx"
FileInputStream file = new FileInputStream(new File(input));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> iterator = sheet.iterator();
Cell cell = null;
Row row=null;
row=iterator.next();
int pos=5; // 5th column is date.
while(iterator.hasNext())
{
row=iterator.next();
cell=row.getCell(pos-1);
//CellStyle cellStyle = wb.createCellStyle();
XSSFCellStyle cellStyle = (XSSFCellStyle)cell.getCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("dd-MM-yyyy"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d=null;
try {
d= sdf.parse(cell.getStringCellValue());
} catch (ParseException e) {
// TODO Auto-generated catch block
d=null;
e.printStackTrace();
continue;
}
cell.setCellValue(d);
cell.setCellStyle(cellStyle);
}
file.close();
FileOutputStream outFile =new FileOutputStream(new File(output));
workbook.write(outFile);
workbook.close();
outFile.close();
}}
I post my final way of doing it based on the accepted answer:
@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {
private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
private String uploadsDirName;
@Override
public void init() throws ServletException {
super.init();
uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// ...
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Collection<Part> parts = req.getParts();
for (Part part : parts) {
File save = new File(uploadsDirName, getFilename(part) + "_"
+ System.currentTimeMillis());
final String absolutePath = save.getAbsolutePath();
log.debug(absolutePath);
part.write(absolutePath);
sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
}
}
// helpers
private static String getFilename(Part part) {
// courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim()
.replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1)
.substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
}
where :
@SuppressWarnings("serial")
class Controller extends HttpServlet {
static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
static ServletContext sc;
Logger log;
// private
// "/WEB-INF/app.properties" also works...
private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
private Properties properties;
@Override
public void init() throws ServletException {
super.init();
// synchronize !
if (sc == null) sc = getServletContext();
log = LoggerFactory.getLogger(this.getClass());
try {
loadProperties();
} catch (IOException e) {
throw new RuntimeException("Can't load properties file", e);
}
}
private void loadProperties() throws IOException {
try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
if (is == null)
throw new RuntimeException("Can't locate properties file");
properties = new Properties();
properties.load(is);
}
}
String property(final String key) {
return properties.getProperty(key);
}
}
and the /WEB-INF/app.properties :
upload.location=C:/_/
HTH and if you find a bug let me know
We were running into the same problem and all we wanted was to set the
app:collapseIcon
attribute in the toolbar in the end, which we did not find since it is not very well documented :)
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="@dimen/toolbarHeight"
app:collapseIcon="@drawable/collapseBackIcon" />
In Python, you can use urllib2
(http://docs.python.org/2/library/urllib2.html) to do all of that work for you.
Simply enough:
import urllib2
f = urllib2.urlopen(url)
print f.read()
Will print the received HTTP response.
To pass GET/POST parameters the urllib.urlencode()
function can be used. For more information, you can refer to the Official Urllib2 Tutorial
the logical and ordered way:
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace DirLister
{
class Program
{
public static void Main(string[] args)
{
//with reflection I get the directory from where this program is running, thus listing all files from there and all subdirectories
string[] st = FindFileDir(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
using ( StreamWriter sw = new StreamWriter("listing.txt", false ) )
{
foreach(string s in st)
{
//I write what I found in a text file
sw.WriteLine(s);
}
}
}
private static string[] FindFileDir(string beginpath)
{
List<string> findlist = new List<string>();
/* I begin a recursion, following the order:
* - Insert all the files in the current directory with the recursion
* - Insert all subdirectories in the list and rebegin the recursion from there until the end
*/
RecurseFind( beginpath, findlist );
return findlist.ToArray();
}
private static void RecurseFind( string path, List<string> list )
{
string[] fl = Directory.GetFiles(path);
string[] dl = Directory.GetDirectories(path);
if ( fl.Length>0 || dl.Length>0 )
{
//I begin with the files, and store all of them in the list
foreach(string s in fl)
list.Add(s);
//I then add the directory and recurse that directory, the process will repeat until there are no more files and directories to recurse
foreach(string s in dl)
{
list.Add(s);
RecurseFind(s, list);
}
}
}
}
}
You can also set onSubmit
attribute's value in form tag. You can set its value using Javascript.
Something like this:
<form id="whatever" name="whatever" onSubmit="return xyz();">
Here is your entire form
<input type="submit">
</form>;
<script type=text/javascript>
function xyz() {
document.getElementById('whatever').action = 'whatever you want'
}
</script>
Remember that onSubmit
has higher priority than action attribute. So whenever you specify onSubmit
value, that operation will be performed first and then the form will move to action.
foo = {}
foo[#foo+1]="bar"
foo[#foo+1]="baz"
This works because the #
operator computes the length of the list. The empty list has length 0, etc.
If you're using Lua 5.3+, then you can do almost exactly what you wanted:
foo = {}
setmetatable(foo, { __shl = function (t,v) t[#t+1]=v end })
_= foo << "bar"
_= foo << "baz"
Expressions are not statements in Lua and they need to be used somehow.
I think you should try
data = {"shareInfo":[{"id":"1","a":"sss","b":"sss","question":"whi?"},
{"id":"2","a":"sss","b":"sss","question":"whi?"},
{"id":"3","a":"sss","b":"sss","question":"whi?"},
{"id":"4","a":"sss","b":"sss","question":"whi?"}]};
ShareInfoLength = data.shareInfo.length;
alert(ShareInfoLength);
for(var i=0; i<ShareInfoLength; i++)
{
alert(Object.keys(data.shareInfo[i]).length);
}
Its also possible to just create a matplotlib figure
object and then use plt.savefig(...)
:
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
df = sns.load_dataset('iris')
plt.figure() # Push new figure on stack
sns_plot = sns.pairplot(df, hue='species', size=2.5)
plt.savefig('output.png') # Save that figure
I would like to point out that it is not that bad to read from the store -- it might be just much more convenient to decide what should be done based on the store, than to pass everything to the component and then as a parameter of a function. I agree with Dan completely, that it is much better not to use store as a singletone, unless you are 100% sure that you will use only for client-side rendering (otherwise hard to trace bugs might appear).
I have created a library recently to deal with verbosity of redux, and I think it is a good idea to put everything in the middleware, so you have everyhing as a dependency injection.
So, your example will look like that:
import { createSyncTile } from 'redux-tiles';
const someTile = createSyncTile({
type: ['some', 'tile'],
fn: ({ params, selectors, getState }) => {
return {
data: params.data,
items: selectors.another.tile(getState())
};
},
});
However, as you can see, we don't really modify data here, so there is a good chance that we can just use this selector in other place to combine it somewhere else.
Inside relative path tag do as follows
<relative>{project_name}/pom.xml</relative>
and then RunAs-> Maven build
It worked for me.
Two ways to get this:
The configuration manager shows the dll builds as a mix of '64' and 'any cpu' builds. Putting them all to the same build fixes it.
When switching between branches, the IIS express path is sometimes not updated. Right click 'IIS Express' in the task bar > Show all applications and verifty that the path is to the correct branch.
application/font-woff for woff: http://www.iana.org/assignments/media-types/application/font-woff
We've always used an
if(iserror(vlookup,"n/a",vlookup))
Excel 2007 introduced IfError which allows you to do the vlookup and add output in case of error, but that doesn't help you with 2003...
About this I think you can reference to http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html.
Here're my understandings about this, with the Identity Federation Use Case to give a details for those concepts:
IdP provides the Persistent identifiers, they are used for linking to the local accounts in SPs, but they identify as the user profile for the specific service each alone. For example, the persistent identifiers are kind of like : johnForAir, jonhForCar, johnForHotel, they all just for one specified service, since it need to link to its local identity in the service.
Transient identifiers are what IdP tell the SP that the users in the session have been granted to access the resource on SP, but the identities of users do not offer to SP actually. For example, The assertion just like “Anonymity(Idp doesn’t tell SP who he is) has the permission to access /resource on SP”. SP got it and let browser to access it, but still don’t know Anonymity' real name.
The explanation for it in the spec is "The interpretation of the content of the element is left to individual implementations". Which means IdP defines the real format for it, and it assumes that SP knows how to parse the format data respond from IdP. For example, IdP gives a format data "UserName=XXXXX Country=US", SP get the assertion, and can parse it and extract the UserName is "XXXXX".
You can set the special character, which is looked for upon execution of a script, to another value by means of using the SET DEFINE <1_CHARACTER>
By default, the DEFINE function itself is on, and it is set to &
It can be turned off - as mentioned already - but it can be avoided as well by means of setting it to a different value. Be very aware of what sign you set it to. In the below example, I've chose the # character, but that choice is just an example.
SQL> select '&var_ampersand #var_hash' from dual;
Enter value for var_ampersand: a value
'AVALUE#VAR_HASH'
-----------------
a value #var_hash
SQL> set define #
SQL> r
1* select '&var_ampersand #var_hash' from dual
Enter value for var_hash: another value
'&VAR_AMPERSANDANOTHERVALUE'
----------------------------
&var_ampersand another value
SQL>
future.utils
allows for python 2 and 3 compatibility.
# Python 2 and 3: option 3
from future.utils import iteritems
heights = {'man': 185,'lady': 165}
for (key, value) in iteritems(heights):
print(key,value)
>>> ('lady', 165)
>>> ('man', 185)
See this link: https://python-future.org/compatible_idioms.html
Java is not platform independent in that it runs on the JVM. Having said that, you gain platform independence via programming against a single abstract machine that has concrete realizations on most common OS platforms (and some embedded appliances).
A related idea is the hardware abstraction layer present in many operating systems that allows the same OS to run on disparate hardware.
In you original question, Turbo C is analagous to the javac program, and the JVM is the OS/HAL.
You can use datetime's strftime function to get this. The problem is that time's strftime accepts a timetuple that does not carry microsecond information.
from datetime import datetime
datetime.now().strftime("%H:%M:%S.%f")
Should do the trick!
I use testproxy to do this.
npm install testproxy
testproxy http://10.0.2.2
You then get the url (and QR code) you can access on your mobile device. It even works with virtual machines you can't reach by just entering the IP of your dev machine.
As noted in the accepted answer - you can use the special { props.children } property. However - you can just pass a component as a prop as the title requests. I think this is cleaner sometimes as you might want to pass several components and have them render in different places. Here's the react docs with an example of how to do it:
https://reactjs.org/docs/composition-vs-inheritance.html
Make sure you are actually passing a component and not an object (this tripped me up initially).
The code is simply this:
const Parent = () => {
return (
<Child componentToPassDown={<SomeComp />} />
)
}
const Child = ({ componentToPassDown }) => {
return (
<>
{componentToPassDown}
</>
)
}
Mono comes with a wrapper, use theirs!
https://github.com/mono/mono/tree/master/mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_2.0 gives code to wrap the actual SQLite dll ( http://www.sqlite.org/sqlite-shell-win32-x86-3071300.zip found on the download page http://www.sqlite.org/download.html/ ) in a .net friendly way. It works on Linux or Windows.
This seems the thinnest of all worlds, minimizing your dependence on third party libraries. If I had to do this project from scratch, this is the way I would do it.
When you update the version of PHP (especially when going from version X.Y to version X.Z), you must update the PHP extensions as well.
This is because PHP extensions are developped in C, and are "close" to the internals of PHP -- which means that, if the APIs of those internals change, the extension must be re-compiled, to use the new versions.
And, between PHP 5.2 and PHP 5.3, for what I remember, there have been some modifications in the internal data-structures used by the PHP engine -- which means extensions must be re-compiled, in order to match that new version of those data-structures.
How to update your PHP extensions will depend on which system you are using.
If you are on windows, you can find the .dll
for some extensions here : http://downloads.php.net/pierre/
For more informations about the different versions, you can take a look at what's said on the left-sidebar of windows.php.net.
If you are on Linux, you must either :
pecl
command, to re-download the sources of the extensions in question, and re-compile them.enum ServicePlatform {
UPLAY = "uplay",
PSN = "psn",
XBL = "xbl"
}
becomes:
{ UPLAY: 'uplay', PSN: 'psn', XBL: 'xbl' }
so
ServicePlatform.UPLAY in ServicePlatform // false
SOLUTION:
ServicePlatform.UPLAY.toUpperCase() in ServicePlatform // true
As everyone else has said. No, you can't. However even though people have said many times over the years that you should use multiple interfaces they haven't really gone into how. Hopefully this will help.
Say you have class Foo
and class Bar
that you both want to try extending into a class FooBar
. Of course, as you said, you can't do:
public class FooBar extends Foo, Bar
People have gone into the reasons for this to some extent already. Instead, write interfaces
for both Foo
and Bar
covering all of their public methods. E.g.
public interface FooInterface {
public void methodA();
public int methodB();
//...
}
public interface BarInterface {
public int methodC(int i);
//...
}
And now make Foo
and Bar
implement the relative interfaces:
public class Foo implements FooInterface { /*...*/ }
public class Bar implements BarInterface { /*...*/ }
Now, with class FooBar
, you can implement both FooInterface
and BarInterface
while keeping a Foo
and Bar
object and just passing the methods straight through:
public class FooBar implements FooInterface, BarInterface {
Foo myFoo;
Bar myBar;
// You can have the FooBar constructor require the arguments for both
// the Foo and the Bar constructors
public FooBar(int x, int y, int z){
myFoo = new Foo(x);
myBar = new Bar(y, z);
}
// Or have the Foo and Bar objects passed right in
public FooBar(Foo newFoo, Bar newBar){
myFoo = newFoo;
myBar = newBar;
}
public void methodA(){
myFoo.methodA();
}
public int methodB(){
return myFoo.methodB();
}
public int methodC(int i){
return myBar.methodC(i);
}
//...
}
The bonus for this method, is that the FooBar
object fits the moulds of both FooInterface
and BarInterface
. That means this is perfectly fine:
FooInterface testFoo;
testFoo = new FooBar(a, b, c);
testFoo = new Foo(a);
BarInterface testBar;
testBar = new FooBar(a, b, c);
testBar = new Bar(b, c);
Hope this clarifies how to use interfaces instead of multiple extensions. Even if I am a few years late.
Single line:
${str:${#str}-1:1}
Now:
echo "${str:${#str}-1:1}"
I use javascript encodeURI() function for the URL part that has forward slashes that should be seen as characters instead of http address. Eg:
"/api/activites/" + encodeURI("?categorie=assemblage&nom=Manipulation/Finition")
Try this:
> HISTTIMEFORMAT="%d/%m/%y %T "
> history
You can adjust the format to your liking, of course.
Just saw that Amazon added a "How to Empty a Bucket" option to the AWS console menu:
http://docs.aws.amazon.com/AmazonS3/latest/UG/DeletingaBucket.html
According to documentation:
random.sample(population, k)
Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
Basically, it picks k unique random elements, a sample, from a sequence:
>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]
random.sample
works also directly from a range:
>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]
In addition to sequences, random.sample
works with sets too:
>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]
However, random.sample
doesn't work with arbitrary iterators:
>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set. For dicts, use list(d).
Bryan Denny's post above is not working for me since not all extensions have a "Content Type" sub-key in the registry. I had to tweak the code as follows:
private string GetMimeType(string sFileName)
{
// Get file extension and if it is empty, return unknown
string sExt = Path.GetExtension(sFileName);
if (string.IsNullOrEmpty(sExt)) return "Unknown file type";
// Default type is "EXT File"
string mimeType = string.Format("{0} File", sExt.ToUpper().Replace(".", ""));
// Open the registry key for the extension under HKEY_CLASSES_ROOT and return default if it doesn't exist
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(sExt);
if (regKey == null) return mimeType;
// Get the "(Default)" value and re-open the key for that value
string sSubType = regKey.GetValue("").ToString();
regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(sSubType);
// If it exists, get the "(Default)" value of the new key
if (regKey?.GetValue("") != null) mimeType = regKey.GetValue("").ToString();
// Return the value
return mimeType;
}
Now it works fine for me for all registered file types and un-registered or generic file types (like JPG, etc).
Jason's answer will do the trick. However, instead of setting svn:ignore to "." on the cache directory, you may want to include "cache" in the parent directory's svn:ignore property, in case the cache directory is not always present. I do this on a number of "throwaway" folders.
We put the default values in the database through migrations (by specifying the :default
option on each column definition) and let Active Record use these values to set the default for each attribute.
IMHO, this approach is aligned with the principles of AR : convention over configuration, DRY, the table definition drives the model, not the other way around.
Note that the defaults are still in the application (Ruby) code, though not in the model but in the migration(s).