To evaporate the warning, you can use libxml_use_internal_errors(true)
// create new DOMDocument
$document = new \DOMDocument('1.0', 'UTF-8');
// set error level
$internalErrors = libxml_use_internal_errors(true);
// load HTML
$document->loadHTML($html);
// Restore error level
libxml_use_internal_errors($internalErrors);
I had something similar when passing a script to a function with invoke-command. I ran the command in single quotes instead of double quotes, because it then becomes a string literal. 'Set-Mailbox $sourceUser -LitigationHoldEnabled $false -ElcProcessingDisabled $true';
Another solution without background image and without the need for a container (though the max sizes of the bounding box must be known):
img{
max-height: 100px;
max-width: 100px;
width: auto; /* These two are added only for clarity, */
height: auto; /* as the default is auto anyway */
}
img {
max-height: 100%;
max-width: 100%;
width: auto; /* These two are added only for clarity, */
height: auto; /* as the default is auto anyway */
}
div.container {
width: 100px;
height: 100px;
}
For this you would have something like:
<table>
<tr>
<td>Lorem</td>
<td>Ipsum<br />dolor</td>
<td>
<div class="container"><img src="image5.png" /></div>
</td>
</tr>
</table>
gitk --all
you could also try creating a button, this will work if you put it outside of the form;
<button onClick="moreFields(); return false;">Give me more fields!</button>
Verify this code : It works on change of phone number field in ms crm 2016 form .
function validatePhoneNumber() {
var mob = Xrm.Page.getAttribute("gen_phone").getValue();
var length = mob.length;
if (length < 10 || length > 10) {
alert("Please Enter 10 Digit Number:");
Xrm.Page.getAttribute("gen_phone").setValue(null);
return true;
}
if (mob > 31 && (mob < 48 || mob > 57)) {} else {
alert("Please Enter 10 Digit Number:");
Xrm.Page.getAttribute("gen_phone").setValue(null);
return true;
}
}
join is not a jQuery function .Its a javascript function.
The join() method joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).
Move the cursor to the begining or end with insert mode
I
- Moves the cursor to the first non blank character in the current line and enables insert mode.A
- Moves the cursor to the last character in the current line and enables insert mode.Here I
is equivalent to ^
+ i
. Similarly A
is equivalent to $
+ a
.
Just moving the cursor to the begining or end
^
- Moves the cursor to the first non blank character in the current
line0
- Moves the cursor to the first character in the current line$
- Moves the cursor to the last character in the current lineI had a much stranger solution. In case anyone runs into this, it's worth double checking your gradle file. It turns out that as I was cloning this git and gradle was runnning, it deleted one line from my build.gradle (app) file.
dependencies {
provided files(providedFiles)
Obviously the problem here was to just add it back and re-sync with gradle.
To remove specific key and element from hashmap use
hashmap.remove(key)
full source code is like
import java.util.HashMap;
public class RemoveMapping {
public static void main(String a[]){
HashMap hashMap = new HashMap();
hashMap.put(1, "One");
hashMap.put(2, "Two");
hashMap.put(3, "Three");
System.out.println("Original HashMap : "+hashMap);
hashMap.remove(3);
System.out.println("Changed HashMap : "+hashMap);
}
}
If your list contains pure integer strings, the accepted awnswer is the way to go. This solution will crash if you give it things that are not integers.
So: if you have data that may contain ints, possibly floats or other things as well - you can leverage your own function with errorhandling:
def maybeMakeNumber(s):
"""Returns a string 's' into a integer if possible, a float if needed or
returns it as is."""
# handle None, "", 0
if not s:
return s
try:
f = float(s)
i = int(f)
return i if f == i else f
except ValueError:
return s
data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]
converted = list(map(maybeMakeNumber, data))
print(converted)
Output:
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
To also handle iterables inside iterables you can use this helper:
from collections.abc import Iterable, Mapping
def convertEr(iterab):
"""Tries to convert an iterable to list of floats, ints or the original thing
from the iterable. Converts any iterable (tuple,set, ...) to itself in output.
Does not work for Mappings - you would need to check abc.Mapping and handle
things like {1:42, "1":84} when converting them - so they come out as is."""
if isinstance(iterab, str):
return maybeMakeNumber(iterab)
if isinstance(iterab, Mapping):
return iterab
if isinstance(iterab, Iterable):
return iterab.__class__(convertEr(p) for p in iterab)
data = ["unkind", {1: 3,"1":42}, "data", "42", 98, "47.11", "of mixed",
("0", "8", {"15", "things"}, "3.141"), "types"]
converted = convertEr(data)
print(converted)
Output:
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed',
(0, 8, {'things', 15}, 3.141), 'types'] # sets are unordered, hence diffrent order
DECLARE @EmpGroup INT =3 ,
@IsActive BIT=1
DECLARE @tblEmpMaster AS TABLE
(EmpCode VARCHAR(20),EmpName VARCHAR(50),EmpAddress VARCHAR(500))
INSERT INTO @tblEmpMaster EXECUTE SPGetEmpList @EmpGroup,@IsActive
SELECT * FROM @tblEmpMaster
If you want to explore options of communicating between components and feel like it is getting harder and harder, then you might consider adopting a good design pattern: Flux.
It is simply a collection of rules that defines how you store and mutate application wide state, and use that state to render components.
There are many Flux implementations, and Facebook's official implementation is one of them. Although it is considered the one that contains most boilerplate code, but it is easier to understand since most of the things are explicit.
Some of Other alternatives are flummox fluxxor fluxible and redux.
Just for the record (took me quite a while) before Grzegorzs answer worked for me I had to install "android support repository" through the SDK Manager!
Install it and add the following code above apply plugin: 'android-library' in the build.gradle of actionbarsherlock folder!
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.+'
}
}
The accepted answer is not ideal, so I decided to add my 2 cents
timeStamp.toLocalDateTime().toLocalDate();
is a bad solution in general, I'm not even sure why they added this method to the JDK as it makes things really confusing by doing an implicit conversion using the system timezone. Usually when using only java8 date classes the programmer is forced to specify a timezone which is a good thing.
The good solution is
timestamp.toInstant().atZone(zoneId).toLocalDate()
Where zoneId is the timezone you want to use which is typically either ZoneId.systemDefault() if you want to use your system timezone or some hardcoded timezone like ZoneOffset.UTC
The general approach should be
The below css works for both Chrome and Firefox
input[type=number]::-webkit-outer-spin-button,
input[type=number]::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type=number] {
-moz-appearance:textfield;
}
I will rather do it manually
...database/migrations
folderphp artisan migrate
, log into your phpmyadmin or SQL(whichever the case is) and in your database, delete the table created by the migrationWorks for me, hope it helps!
If you are building your own boost do not forget to use the --layout=versioned
otherwise the search for a particular version of library will fail
The build path should contain the path 'till before' that of the package name.
For eg, if the folder structure is: src/main/java/com/example/dao
If the class containing the import statement'package com.example.dao'
complains of the incorrect package error, then, the build path should include:src/main/java
This should solve the issue.
DWORD ReplaceString(__inout PCHAR source, __in DWORD dwSourceLen, __in const char* pszTextToReplace, __in const char* pszReplaceWith)
{
DWORD dwRC = NO_ERROR;
PCHAR foundSeq = NULL;
PCHAR restOfString = NULL;
PCHAR searchStart = source;
size_t szReplStrcLen = strlen(pszReplaceWith), szRestOfStringLen = 0, sztextToReplaceLen = strlen(pszTextToReplace), remainingSpace = 0, dwSpaceRequired = 0;
if (strcmp(pszTextToReplace, "") == 0)
dwRC = ERROR_INVALID_PARAMETER;
else if (strcmp(pszTextToReplace, pszReplaceWith) != 0)
{
do
{
foundSeq = strstr(searchStart, pszTextToReplace);
if (foundSeq)
{
szRestOfStringLen = (strlen(foundSeq) - sztextToReplaceLen) + 1;
remainingSpace = dwSourceLen - (foundSeq - source);
dwSpaceRequired = szReplStrcLen + (szRestOfStringLen);
if (dwSpaceRequired > remainingSpace)
{
dwRC = ERROR_MORE_DATA;
}
else
{
restOfString = CMNUTIL_calloc(szRestOfStringLen, sizeof(CHAR));
strcpy_s(restOfString, szRestOfStringLen, foundSeq + sztextToReplaceLen);
strcpy_s(foundSeq, remainingSpace, pszReplaceWith);
strcat_s(foundSeq, remainingSpace, restOfString);
}
CMNUTIL_free(restOfString);
searchStart = foundSeq + szReplStrcLen; //search in the remaining str. (avoid loops when replWith contains textToRepl
}
} while (foundSeq && dwRC == NO_ERROR);
}
return dwRC;
}
I am a programmer who has to deal with a lot of code on a daily basis. Open source and what has been developed in house.
As a programmer, I find it useful to have many source files open at once, and often organise my desktop on my (widescreen) monitor so that two source files are side by side. I might be programming in both, or just reading one and programming in the other.
I find it dissatisfying and frustrating when one of those source files is >120 characters in width, because it means I can't comfortably fit a line of code on a line of screen. It upsets formatting to line wrap.
I say '120' because that's the level to which I would get annoyed at code being wider than. After that many characters, you should be splitting across lines for readability, let alone coding standards.
I write code with 80 columns in mind. This is just so that when I do leak over that boundary, it's not such a bad thing.
You can use the ThenBy and ThenByDescending extension methods:
foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
Maybe you are looking for Vector
. It's capacity is automatically expanded if needed. It's not the best choice but will do in simple situations. It's worth your time to read up on ArrayList
instead.
From the Framework Design Guidelines 2nd Edition (pg. 256):
DO NOT return null values from collection properties or from methods returning collections. Return an empty collection or an empty array instead.
Here's another interesting article on the benefits of not returning nulls (I was trying to find something on Brad Abram's blog, and he linked to the article).
Edit- as Eric Lippert has now commented to the original question, I'd also like to link to his excellent article.
Cygwin + sftp/scp natrually
I you don't want to modify your code. If so, I recommended you to try BottomNavigationViewEx?
You just need replace call a method setCurrentItem(index);
and getCurrentItem()
?
When use method delete in form then must have to set route delete
Route::delete("empresas/eliminar/{id}", "CompaniesController@delete");
To my knowledge, there is sadly no CSS filter to colorise an element (perhaps with the use of some SVG filter magic, but I'm somewhat unfamiliar with that) and even if that wasn't the case, filters are basically only supported by webkit browsers.
With that said, you could still work around this and use a canvas
to modify your image. Basically, you can draw an image element onto a canvas and then loop through the pixels, modifying the respective RGBA values to the colour you want.
However, canvases do come with some restrictions. Most importantly, you have to make sure that the image src comes from the same domain as the page. Otherwise the browser won't allow you to read or modify the pixel data of the canvas.
Here's a JSFiddle changing the colour of the JSFiddle logo.
//Base64 source, but any local source will work_x000D_
var src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAgCAYAAACGhPFEAAAABGdBTUEAALGPC/xhBQAABzhJREFUWAnNWAtwXFUZ/v9zs4GUJJu+k7tb5DFAGWO1aal1sJUiY3FQQaWidqgPLAMqYzd9CB073VodhCa7KziiFgWhzvAYQCiCD5yK4gOTDnZK2ymdZoruppu0afbu0pBs7p7f7yy96W662aw2QO/Mzj2P//Gd/5z/+89dprfzubnTN332Re+xiKawllxWucm+9O4eCi9xT8ctn45yKd3AXX1BPsu3XIiuY+K5kDmrUA7jORb5m2baLm7uscNrJr9eOF9Je8JAz9ySnFHlq9nEpG6CYx+RdJDQDtKymxT1iWZLFDUy0/kkfDUxzYVzV0hvHZLs946Gph+uBLCRmRDQdjTVwmw9DZCNMPi4KzqWbPX/sxwIu71vlrKq10HnZizwTSFZngj5f1NOx5s7bdB2LHWDEusBOD487LrX9qyd8qpnvJL3zGjqAh+pR4W4RVhu715Vv2U8PTWeQLn5YHvms4qsR4TpH/ImLfhfARvbPaGGrrjTtwjH5hFFfHcgkv5SOZ9mbvxIgwGaZl+8ULGcJ8zOsJa9R1r9B2d8v2eGb1KNieqBhLNz8ekyAoV3VAX985+FvSXEenF8lf9lA7DUUxa0HUl/RTG1EfOUQmUwwCtggDewiHmc1R+Ir/MfKJz/f9tTwn31Nf7qVxlHLR6qXwg7cHXqU/p4hPdUB6Lp55TiXwDYTsrpG12dbdY5t0WLrCSRSVjIItG0dqIAG2jHwlPTmvQdsL3Ajjg3nAq3zIgdS98ZiGV0MJZeWVJs2WNWIJK5hcLh0osuqVTxIAdi6X3w/0LFGoa+AtFMzo5kflix0gQLBiLOZmAYro84RcfSc3NKpFAcliM9eYDdjZ7QO/1mRc+CTapqFX+4lO9TQEPoUpz//anQ5FQphXdizB1QXXk/moOl/JUC7aLMDpQSHj02PdxbG9xybM60u47UjZ4bq290Zm451ky3HSi6kxTKJ9fXHQVvZJm1XTjutYsozw53T1L+2ufBGPMTe/c30M/mD3uChW+c+6tQttthuBnbqMBLKGbydI54/eFQ3b5CWa/dGMl8xFJ0D/rvg1Pjdxil+2XK5b6ZWD15lyfnvYOxTBYs9TrY5NbuUENRUo5EGtGyVUNtBwBfDjA/IDtTkiNRsdYD8O+NcVN2KUfXo3UnukvA6Z3I+mWeY++NpNoAwDvAv1Uiss7oiNBmYD+XraoO0NvnPVnvrbUsA4CcYusPgajzY2/cvN+KtOFl/6w/IWrvdTV/Ktla92KhkNcOxpwPCqm/IgLbEvteW1m4E2/d8iY9AZOXQ/7WxKq6nxq9YNT5OLF6DmAfTHT13EL3XjTk2csXk4bqX2OXWiQ73Jz49tS4N5d/oxoHLr14EzPfAf1IIlS/2oznIx1omLURhL5Qa1oxFuC8EeHb8U6I88bXCwGbuZ61jb2Jgz1XYUHb0b0vEHNWmHE9lNsjWrcmnMhNhYDNnCkmNJSFHFdzte82M1b04HgC6HrYbAPw1pFdNOc4GE334wz9qkihRAdK/0HBub/E1MkhJBiq6V8gq7Htm05OjN2C/z/jCP1xbAlCwcnsAsbdkGHF/trPIcoNrtbjFRNmoama6EgZ42SimRG5FjLHWakNwWjmirLyZpLpKH7TysghZ00OUHNTxFmK2yDNQSKlx7u0Q0GQeLtQdy4rY5zMzqVb/ccoJ/OQMEmoPWW3988to4NY8DxYf6WMDCW6ktuRvFqxmqewgguhdLCcwsic0DMA8lE7kvrYyFhBw446X2B/nRNo739/YnX9azKUXYCg9CtlvdAUyywuEB1p4gh9AzbPZc0mF8Z+sINgn0MIwiVgKcAG6rGlT86AMdqw2n8ppR63o+mveQXCFAxzX2BWD0P6pcT+g3uNlmEDV3JX4iOh1xICdWU2gGXOMXN5HfRhK4IoPxlfXQfmKf+Ajh1I+MEeHMcKzqvoxoZsHsoOXgP+fEkxbw1e2JhB0h2q9tc4OL/fAVdsdd3jnyhklmRo8qGBQXchIvMMKPW7Pt85/SM66CNmDw1mh75cHu6JWZFZxNLNSJTPIM5PuJquKEt3o6zmqyJZH4LTC7CIfTonO5Jr/B2jxIq6jW3OZVYVX4edDSD6e1BAXqwgl/I2miKp+ZayOkT0CjaJww21/2bhznio7uoiL2dQB8HdhoV++ri4AdUdtgfw789mRHspzulXzyCcI1BMVQXgL5LodnP7zFfE+N9/9yOUyedxTn/SFHWWj0ifAY1ANHUleOJRlPqdCUmbO85J1jjxUfkUkgVCsg1/uGw0n/fvFm67LT2NLTLfi98Cke8dpMGl3r9QxVRnPuPrWzaIUmsAtgas0okd6ETh7AYt5d7+BeCbhfKVcQ6CtwgJjjoiP3fdgVbcbY57/otBnxidfndvo6/67BtxUf4kztJsbMg0CJaU9QxN2FskhePQBWr7La6wvzRFarTtyoBgB4hm5M//aAMT2+/Vlfzp81/vywLMWSBN1QAAAABJRU5ErkJggg==";_x000D_
var canvas = document.getElementById("theCanvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
var img = new Image;_x000D_
_x000D_
//wait for the image to load_x000D_
img.onload = function() {_x000D_
//Draw the original image so that you can fetch the colour data_x000D_
ctx.drawImage(img,0,0);_x000D_
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);_x000D_
_x000D_
/*_x000D_
imgData.data is a one-dimensional array which contains _x000D_
the respective RGBA values for every pixel _x000D_
in the selected region of the context _x000D_
(note i+=4 in the loop)_x000D_
*/_x000D_
_x000D_
for (var i = 0; i < imgData.data.length; i+=4) {_x000D_
imgData.data[i] = 255; //Red, 0-255_x000D_
imgData.data[i+1] = 255; //Green, 0-255_x000D_
imgData.data[i+2] = 255; //Blue, 0-255_x000D_
/* _x000D_
imgData.data[i+3] contains the alpha value_x000D_
which we are going to ignore and leave_x000D_
alone with its original value_x000D_
*/_x000D_
}_x000D_
ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the original image_x000D_
ctx.putImageData(imgData, 0, 0); //paint the new colorised image_x000D_
}_x000D_
_x000D_
//Load the image!_x000D_
img.src = src;
_x000D_
body {_x000D_
background: green;_x000D_
}
_x000D_
<canvas id="theCanvas"></canvas>
_x000D_
document.onkeydown = function(e) {
switch(e.which) {
case 37: // left
break;
case 38: // up
break;
case 39: // right
break;
case 40: // down
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
};
If you need to support IE8, start the function body as e = e || window.event; switch(e.which || e.keyCode) {
.
(edit 2020)
Note that KeyboardEvent.which
is now deprecated. See this example using KeyboardEvent.key
for a more modern solution to detect arrow keys.
Works that way as well, a bit more tidy.
getQuery()
just returns the underlying builder, which already contains the table reference.
$browser_total_raw = DB::raw('count(*) as total');
$user_info = Usermeta::getQuery()
->select('browser', $browser_total_raw)
->groupBy('browser')
->pluck('total','browser');
The most simple and the correct way is to use Record type Record<string, string>
const myVar : Record<string, string> = {
key1: 'val1',
key2: 'val2',
}
I have found that using cabs(double)
, cabsf(float)
, cabsl(long double)
, __cabsf(float)
, __cabs(double)
, __cabsf(long double)
is the solution
You can place a TEXTAREA of similar size under your DIV, so the standard control's frame would be visible around div.
It's probably good to set it to be disabled, to prevent accidental focus stealing.
Raymond's answer is great for python2 (though, you don't need the abs() nor the parens around 10 ** 8). However, for python3, there are important caveats. First, you'll need to make sure you are passing an encoded string. These days, in most circumstances, it's probably also better to shy away from sha-1 and use something like sha-256, instead. So, the hashlib approach would be:
>>> import hashlib
>>> s = 'your string'
>>> int(hashlib.sha256(s.encode('utf-8')).hexdigest(), 16) % 10**8
80262417
If you want to use the hash() function instead, the important caveat is that, unlike in Python 2.x, in Python 3.x, the result of hash() will only be consistent within a process, not across python invocations. See here:
$ python -V
Python 2.7.5
$ python -c 'print(hash("foo"))'
-4177197833195190597
$ python -c 'print(hash("foo"))'
-4177197833195190597
$ python3 -V
Python 3.4.2
$ python3 -c 'print(hash("foo"))'
5790391865899772265
$ python3 -c 'print(hash("foo"))'
-8152690834165248934
This means the hash()-based solution suggested, which can be shortened to just:
hash(s) % 10**8
will only return the same value within a given script run:
#Python 2:
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543
#Python 3:
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
12954124
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
32065451
So, depending on if this matters in your application (it did in mine), you'll probably want to stick to the hashlib-based approach.
If you use a navigation controller and set its delegate, then the view{Will,Did}{Appear,Disappear} methods are not invoked.
You need to use the navigation controller delegate methods instead:
navigationController:willShowViewController:animated:
navigationController:didShowViewController:animated:
since you followed the tutorial, I presume you have a screen that says Hello World.
that means you have some code in your layout xml that looks like this
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
you want to display an image, so instead of TextView you want to have ImageView. and instead of a text attribute you want an src attribute, that links to your drawable resource
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/cool_pic"
/>
You can use javascript to block form submission until the appropriate time. A very crude example:
<form onsubmit='return false;' id='frmNoEnterSubmit' action="index.html">
<input type='text' name='txtTest' />
<input type='button' value='Submit'
onclick='document.forms["frmNoEnterSubmit"].onsubmit=""; document.forms["frmNoEnterSubmit"].submit();' />
</form>
Pressing enter will still trigger the form to submit, but the javascript will keep it from actually submitting, until you actually press the button.
If this is from a SQL Server datebase you could issue this kind of query...
Select Top 1 DepartureTime From TrainSchedule where DepartureTime >
GetUTCDate()
Order By DepartureTime ASC
GetDate()
could also be used, not sure how dates are being stored.
I am not sure how the data is being stored and/or read.
When testing for directories remember that every directory contains two special files.
One is called '.' and the other '..'
. is the directory's own name while .. is the name of it's parent directory.
To avoid trailing backslash problems just test to see if the directory knows it's own name.
eg:
if not exist %temp%\buffer\. mkdir %temp%\buffer
These are different Form content types defined by W3C. If you want to send simple text/ ASCII data, then x-www-form-urlencoded will work. This is the default.
But if you have to send non-ASCII text or large binary data, the form-data is for that.
You can use Raw if you want to send plain text or JSON or any other kind of string. Like the name suggests, Postman sends your raw string data as it is without modifications. The type of data that you are sending can be set by using the content-type header from the drop down.
Binary can be used when you want to attach non-textual data to the request, e.g. a video/audio file, images, or any other binary data file.
Refer to this link for further reading: Forms in HTML documents
slicing operator. http://docs.python.org/tutorial/introduction.html#strings and scroll down a bit
It depends on what the span is for. If it refers to the text of the link, and not the fact that it is a link, choose #1. If the span refers to the link as a whole, then choose #2. Unless you explain what the span represents, there's not much more of an answer than that. They're both inline elements, can be syntactically nested in any order.
Not sure if this is already answered, but if you want only a table in a figure window, then you can hide the axes:
fig, ax = plt.subplots()
# Hide axes
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
# Table from Ed Smith answer
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
ax.table(cellText=clust_data,colLabels=collabel,loc='center')
Hi there is my code for pagination: Use in blade @include('pagination.default', ['paginator' => $users])
Views/pagination/default.blade.php
@if ($paginator->lastPage() > 1)
si la pagina actual es distinto a 1 y hay mas de 5 hojas muestro el boton de 1era hoja --> if actual page is not equals 1, and there is more than 5 pages then I show first page button --> @if ($paginator->currentPage() != 1 && $paginator->lastPage() >= 5) << @endif
<!-- si la pagina actual es distinto a 1 muestra el boton de atras -->
@if($paginator->currentPage() != 1)
<li>
<a href="{{ $paginator->url($paginator->currentPage()-1) }}" >
<
</a>
</li>
@endif
<!-- dibuja las hojas... Tomando un rango de 5 hojas, siempre que puede muestra 2 hojas hacia atras y 2 hacia adelante -->
<!-- I draw the pages... I show 2 pages back and 2 pages forward -->
@for($i = max($paginator->currentPage()-2, 1); $i <= min(max($paginator->currentPage()-2, 1)+4,$paginator->lastPage()); $i++)
<li class="{{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
<a href="{{ $paginator->url($i) }}">{{ $i }}</a>
</li>
@endfor
<!-- si la pagina actual es distinto a la ultima muestra el boton de adelante -->
<!-- if actual page is not equal last page then I show the forward button-->
@if ($paginator->currentPage() != $paginator->lastPage())
<li>
<a href="{{ $paginator->url($paginator->currentPage()+1) }}" >
>
</a>
</li>
@endif
<!-- si la pagina actual es distinto a la ultima y hay mas de 5 hojas muestra el boton de ultima hoja -->
<!-- if actual page is not equal last page, and there is more than 5 pages then I show last page button -->
@if ($paginator->currentPage() != $paginator->lastPage() && $paginator->lastPage() >= 5)
<li>
<a href="{{ $paginator->url($paginator->lastPage()) }}" >
>>
</a>
</li>
@endif
</ul>
NOTE: This is exactly what OP said they did. (But didn't show code for.) I show the details here, so that you can compare it to the accepted answer. My point is that OP's original instinct was, IMHO, better than the answer he accepted.
Given how highly upvoted the accepted answer is, I'd like to point out the "naive" answer to one-time initialization of static methods, is hardly more code than that implementation of Singleton -- and has an essential advantage.
final class MyClass {
public static function someMethod1() {
MyClass::init();
// whatever
}
public static function someMethod2() {
MyClass::init();
// whatever
}
private static $didInit = false;
private static function init() {
if (!self::$didInit) {
self::$didInit = true;
// one-time init code.
}
}
// private, so can't create an instance.
private function __construct() {
// Nothing to do - there are no instances.
}
}
The advantage of this approach, is that you get to call with the straightforward static function syntax:
MyClass::someMethod1();
Contrast it to the calls required by the accepted answer:
MyClass::getInstance->someMethod1();
As a general principle, it is best to pay the coding price once, when you code a class, to keep callers simpler.
If you are NOT using PHP 7.4's opcode.cache
, then use Victor Nicollet's answer. Simple. No extra coding required. No "advanced" coding to understand. (I recommend including FrancescoMM's comment, to make sure "init" will never execute twice.) See Szczepan's explanation of why Victor's technique won't work with opcode.cache
.
If you ARE using opcode.cache
, then AFAIK my answer is as clean as you can get. The cost is simply adding the line MyClass::init();
at start of every public method. NOTE: If you want public properties, code them as a get
/ set
pair of methods, so that you have a place to add that init
call.
(Private members do NOT need that init
call, as they are not reachable from the outside - so some public method has already been called, by the time execution reaches the private member.)
Sounds like more work than its worth.
1) Why not just have a single JavaScript variable that stores a reference to the currently selected element\jQuery object.
2) Why not add a class to the currently selected element. Then you could query the DOM for the ".active" class or something.
None of the above solutions worked for me.
I didn't have a toolbar in my project, but got the same error.
I cleaned up the project, uninstalled the app. Then I ran a gradlew build --refresh-dependencies, and found out there were some onclick events without corresponding code in the xml files.
I removed them, rebuilt the project, and it worked.
The dependencies didn't seem like were updated, but that's another story.
Unfortunately there is no such a thing as Lock/Unlock. What you have to do is:
Enter the below query:
<QueryList> <Query Id="0" Path="Security"> <Select Path="Security"> *[EventData[Data[@Name='LogonType']='7'] and (System[(EventID='4634')] or System[(EventID='4624')]) ]</Select> </Query> </QueryList>
That's it
If this is part of a batch script (.bat
file) and you have a large list of files, you can use a multi-line ^
, and optional /Y
flag to suppresses prompting to confirm you want to overwrite an existing destination file.
REM Concatenate several files to one
COPY /Y ^
this_is_file_1.csv + ^
this_is_file_2.csv + ^
this_is_file_3.csv + ^
this_is_file_4.csv + ^
this_is_file_5.csv + ^
this_is_file_6.csv + ^
this_is_file_7.csv + ^
this_is_file_8.csv + ^
this_is_file_9.csv ^
output_file.csv
This is tidier than performing the command on one line.
Use Eclipse to search and replace (remove) all instances of "@Override". Then add back the non-interface overrides using "Clean Up".
Steps:
Code coverage is a measurement of how many lines/blocks/arcs of your code are executed while the automated tests are running.
Code coverage is collected by using a specialized tool to instrument the binaries to add tracing calls and run a full set of automated tests against the instrumented product. A good tool will give you not only the percentage of the code that is executed, but also will allow you to drill into the data and see exactly which lines of code were executed during a particular test.
Our team uses Magellan - an in-house set of code coverage tools. If you are a .NET shop, Visual Studio has integrated tools to collect code coverage. You can also roll some custom tools, like this article describes.
If you are a C++ shop, Intel has some tools that run for Windows and Linux, though I haven't used them. I've also heard there's the gcov tool for GCC, but I don't know anything about it and can't give you a link.
As to how we use it - code coverage is one of our exit criteria for each milestone. We have actually three code coverage metrics - coverage from unit tests (from the development team), scenario tests (from the test team) and combined coverage.
BTW, while code coverage is a good metric of how much testing you are doing, it is not necessarily a good metric of how well you are testing your product. There are other metrics you should use along with code coverage to ensure the quality.
I've found that the best way to debug is to use the microsoft tool called DTCPing
I've had my fare deal of problems in our old company network, and I've got a few tips:
In my experience, if the DTCPing is able to setup a DTC connection initiated from the client and initiated from the server, your transactions are not the problem any more.
You probably want to use the assets_base_urls
configuration.
framework:
templating:
assets_base_urls:
http: [http://www.website.com]
ssl: [https://www.website.com]
http://symfony.com/doc/current/reference/configuration/framework.html#assets
Note that the configuration is different since Symfony 2.7:
framework:
# ...
assets:
base_urls:
- 'http://cdn.example.com/'
I prefer Google Collections over Apache StringUtils for this particular problem:
Joiner.on(separator).join(array)
Compared to StringUtils, the Joiner API has a fluent design and is a bit more flexible, e.g. null
elements may be skipped or replaced by a placeholder. Also, Joiner
has a feature for joining maps with a separator between key and value.
The error demo:
007@WIN10-711082301 MINGW64 /d/1 (dev)
$ git add --all
007@WIN10-711082301 MINGW64 /d/1 (dev)
$ git status
On branch dev
Initial commit
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: index.html
new file: photo.jpg
new file: style.css
007@WIN10-711082301 MINGW64 /d/1 (dev)
$ git push origin dev
error: src refspec dev does not match any.
error: failed to push some refs to '[email protected]:yourRepo.git'
You maybe not to do $ git commit -m "discription"
.
Solution:
007@WIN10-711082301 MINGW64 /d/1 (dev)
$ git commit -m "discription"
[dev (root-commit) 0950617] discription
3 files changed, 148 insertions(+)
create mode 100644 index.html
create mode 100644 photo.jpg
create mode 100644 style.css
007@WIN10-711082301 MINGW64 /d/1 (dev)
$ git push origin dev
To [email protected]:Tom007Cheung/Rookie-s-Resume.git
! [rejected] dev -> dev (fetch first)
error: failed to push some refs to '[email protected]:yourRepo.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
I had this error and other related ones, when I imported at 16 GB SQL file. For me, editing my.ini and setting the following (based on several different posts) in the [mysqld] section:
max_allowed_packet = 110M
innodb_buffer_pool_size=511M
innodb_log_file_size=500M
innodb_log_buffer_size = 800M
net_read_timeout = 600
net_write_timeout = 600
If you are running under Windows, go to the control panel, services, and look at the details for MySQL and you will see where my.ini is. Then after you edit and save my.ini, restart the mysql service (or restart the computer).
If you are using HeidiSQL, you can also set some or all of these using that.
You can not add an element to an array, since arrays, in Java, are fixed-length. However, you could build a new array from the existing one using Arrays.copyOf(array, size)
:
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3};
System.out.println(Arrays.toString(array));
array = Arrays.copyOf(array, array.length + 1); //create new array from old array and allocate one more element
array[array.length - 1] = 4;
System.out.println(Arrays.toString(array));
}
I would still recommend to drop working with an array and use a List
.
from sklearn.linear_model import LinearRegression
X, Y = x.reshape(-1,1), y.reshape(-1,1)
plt.plot( X, LinearRegression().fit(X, Y).predict(X) )
1) Server.MapPath(".")
-- Returns the "Current Physical Directory" of the file (e.g. aspx
) being executed.
Ex. Suppose D:\WebApplications\Collage\Departments
2) Server.MapPath("..")
-- Returns the "Parent Directory"
Ex. D:\WebApplications\Collage
3) Server.MapPath("~")
-- Returns the "Physical Path to the Root of the Application"
Ex. D:\WebApplications\Collage
4) Server.MapPath("/")
-- Returns the physical path to the root of the Domain Name
Ex. C:\Inetpub\wwwroot
One way to do this is to put both images in the HTML, inside a SPAN or DIV, you can hide the default either with CSS, or with JS on page load. Then you can toggle on click. Here is a similar example I am using to put left/down icons on a list:
$(document).ready(function(){
$(".button").click(function () {
$(this).children(".arrow").toggle();
return false;
});
});
<a href="#" class="button">
<span class="arrow">
<img src="/images/icons/left.png" alt="+" />
</span>
<span class="arrow" style="display: none;">
<img src="/images/down.png" alt="-" />
</span>
</a>
In .NET4.5
, MVC 5
no need for widgets.
Javascript:
object in JS:
mechanism that does post.
$('.button-green-large').click(function() {
$.ajax({
url: 'Quote',
type: "POST",
dataType: "json",
data: JSON.stringify(document.selectedProduct),
contentType: 'application/json; charset=utf-8',
});
});
C#
Objects:
public class WillsQuoteViewModel
{
public string Product { get; set; }
public List<ClaimedFee> ClaimedFees { get; set; }
}
public partial class ClaimedFee //Generated by EF6
{
public long Id { get; set; }
public long JourneyId { get; set; }
public string Title { get; set; }
public decimal Net { get; set; }
public decimal Vat { get; set; }
public string Type { get; set; }
public virtual Journey Journey { get; set; }
}
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Quote(WillsQuoteViewModel data)
{
....
}
Object received:
Hope this saves you some time.
Shortest for loop code
a=i=[];for(;i<100;)a[i++]=0;
edit:
for(a=i=[];i<100;)a[i++]=0;
or
for(a=[],i=100;i--;)a[i]=0;
Safe var version
var a=[],i=0;for(;i<100;)a[i++]=0;
edit:
for(var i=100,a=[];i--;)a[i]=0;
Inspired by Radek and Spencer... On Rails 4(.0.2 - Ruby 2.1.0 ), I was able to append this to config/boot.rb:
# config/boot.rb
# ...existing code
require 'rails/commands/server'
module Rails
# Override default development
# Server port
class Server
def default_options
super.merge(Port: 3100)
end
end
end
All other configuration in default_options are still set, and command-line switches still override defaults.
docker run -dit --rm IMAGE
docker cp CONTAINER:SRC_PATH DEST_PATH
https://docs.docker.com/engine/reference/commandline/run/ https://docs.docker.com/engine/reference/commandline/cp/
You can use setCustomValidity
function when oninvalid
event occurs.
Like below:-
<input class="form-control" type="email" required=""
placeholder="username" oninvalid="this.setCustomValidity('Please Enter valid email')">
</input>
To clear the message once you start entering use oninput="setCustomValidity('')
attribute to clear the message.
<input class="form-control" type="email" required="" placeholder="username"
oninvalid="this.setCustomValidity('Please Enter valid email')"
oninput="setCustomValidity('')"></input>
If you are having any one or more row(s) with less or more number of columns than 2 in the dataset then this error may arise.
I am also new to Pyspark and trying to read CSV file. Following code worked for me:
In this code I am using dataset from kaggle the link is: https://www.kaggle.com/carrie1/ecommerce-data
1. Without mentioning the schema:
from pyspark.sql import SparkSession
scSpark = SparkSession \
.builder \
.appName("Python Spark SQL basic example: Reading CSV file without mentioning schema") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
sdfData = scSpark.read.csv("data.csv", header=True, sep=",")
sdfData.show()
Now check the columns: sdfData.columns
Output will be:
['InvoiceNo', 'StockCode','Description','Quantity', 'InvoiceDate', 'CustomerID', 'Country']
Check the datatype for each column:
sdfData.schema
StructType(List(StructField(InvoiceNo,StringType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,StringType,true),StructField(InvoiceDate,StringType,true),StructField(UnitPrice,StringType,true),StructField(CustomerID,StringType,true),StructField(Country,StringType,true)))
This will give the data frame with all the columns with datatype as StringType
2. With schema: If you know the schema or want to change the datatype of any column in the above table then use this (let's say I am having following columns and want them in a particular data type for each of them)
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField
from pyspark.sql.types import DoubleType, IntegerType, StringType
schema = StructType([\
StructField("InvoiceNo", IntegerType()),\
StructField("StockCode", StringType()), \
StructField("Description", StringType()),\
StructField("Quantity", IntegerType()),\
StructField("InvoiceDate", StringType()),\
StructField("CustomerID", DoubleType()),\
StructField("Country", StringType())\
])
scSpark = SparkSession \
.builder \
.appName("Python Spark SQL example: Reading CSV file with schema") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
sdfData = scSpark.read.csv("data.csv", header=True, sep=",", schema=schema)
Now check the schema for datatype of each column:
sdfData.schema
StructType(List(StructField(InvoiceNo,IntegerType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,IntegerType,true),StructField(InvoiceDate,StringType,true),StructField(CustomerID,DoubleType,true),StructField(Country,StringType,true)))
Edited: We can use the following line of code as well without mentioning schema explicitly:
sdfData = scSpark.read.csv("data.csv", header=True, inferSchema = True)
sdfData.schema
The output is:
StructType(List(StructField(InvoiceNo,StringType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,IntegerType,true),StructField(InvoiceDate,StringType,true),StructField(UnitPrice,DoubleType,true),StructField(CustomerID,IntegerType,true),StructField(Country,StringType,true)))
The output will look like this:
sdfData.show()
+---------+---------+--------------------+--------+--------------+----------+-------+
|InvoiceNo|StockCode| Description|Quantity| InvoiceDate|CustomerID|Country|
+---------+---------+--------------------+--------+--------------+----------+-------+
| 536365| 85123A|WHITE HANGING HEA...| 6|12/1/2010 8:26| 2.55| 17850|
| 536365| 71053| WHITE METAL LANTERN| 6|12/1/2010 8:26| 3.39| 17850|
| 536365| 84406B|CREAM CUPID HEART...| 8|12/1/2010 8:26| 2.75| 17850|
| 536365| 84029G|KNITTED UNION FLA...| 6|12/1/2010 8:26| 3.39| 17850|
| 536365| 84029E|RED WOOLLY HOTTIE...| 6|12/1/2010 8:26| 3.39| 17850|
| 536365| 22752|SET 7 BABUSHKA NE...| 2|12/1/2010 8:26| 7.65| 17850|
| 536365| 21730|GLASS STAR FROSTE...| 6|12/1/2010 8:26| 4.25| 17850|
| 536366| 22633|HAND WARMER UNION...| 6|12/1/2010 8:28| 1.85| 17850|
| 536366| 22632|HAND WARMER RED P...| 6|12/1/2010 8:28| 1.85| 17850|
| 536367| 84879|ASSORTED COLOUR B...| 32|12/1/2010 8:34| 1.69| 13047|
| 536367| 22745|POPPY'S PLAYHOUSE...| 6|12/1/2010 8:34| 2.1| 13047|
| 536367| 22748|POPPY'S PLAYHOUSE...| 6|12/1/2010 8:34| 2.1| 13047|
| 536367| 22749|FELTCRAFT PRINCES...| 8|12/1/2010 8:34| 3.75| 13047|
| 536367| 22310|IVORY KNITTED MUG...| 6|12/1/2010 8:34| 1.65| 13047|
| 536367| 84969|BOX OF 6 ASSORTED...| 6|12/1/2010 8:34| 4.25| 13047|
| 536367| 22623|BOX OF VINTAGE JI...| 3|12/1/2010 8:34| 4.95| 13047|
| 536367| 22622|BOX OF VINTAGE AL...| 2|12/1/2010 8:34| 9.95| 13047|
| 536367| 21754|HOME BUILDING BLO...| 3|12/1/2010 8:34| 5.95| 13047|
| 536367| 21755|LOVE BUILDING BLO...| 3|12/1/2010 8:34| 5.95| 13047|
| 536367| 21777|RECIPE BOX WITH M...| 4|12/1/2010 8:34| 7.95| 13047|
+---------+---------+--------------------+--------+--------------+----------+-------+
only showing top 20 rows
To access the requested directory other than local network, you need to change the XAMPP security concept
configured in the file "httpd-xampp.conf".
xampp\apache\conf\extra\httpd-xampp.conf
Require Directive Selects which authenticated users can access a resource
Syntax «
Require entity-name [entity-name] ...
From « XAMPP security concept allows only local environment - Require local
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
Require local
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
To « XAMPP security concept allows any environment - Require all granted
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
Require all granted
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
Access forbidden! message from HTML Page.
Allow Directive Controls which hosts can access an area of the server
Syntax «
Allow from all|host|env=[!]env-variable [host|env=[!]env-variable] ...
Allowing only local environment. Using any of the below specified url's.
http://localhost/phpmyadmin/
http://127.0.0.1/phpmyadmin/
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
Order deny,allow
Deny from all
Allow from ::1 127.0.0.0/8 \
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
Allowing only to specified IPv4, IPv6 address spaces.
fe80::/10
A unique local address (ULA) is an IPv6 address in the block fc00::/7
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
Order deny,allow
Deny from all
Allow from ::1 127.0.0.0/8 \
fc00::/7 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 \
fe80::/10 169.254.0.0/16
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
Allowing for any network address. Allow from all
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
Order deny,allow
Allow from all
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
404 - XAMPP Control Panel: Unable to start Apache HTTP server.
URL: http://localhost/xampp/index.php
Error «
Not Found
HTTP Error 404. The requested resource is not found.
Required default Apache HTTP server port 80 is actually used by other Service.
You need to find the service running with port 80 and stop the service, then start the Apache HTTP server.
Use Netstat to displays active TCP connections, ports on which the computer is listening.
C:\Users\yashwanth.m>netstat -ano
Active Connections
Proto Local Address Foreign Address State PID
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 2920
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 1124
TCP 127.0.0.1:5354 0.0.0.0:0 LISTENING 3340
TCP [::]:80 [::]:0 LISTENING 2920
C:\Users\yashwanth.m>netstat -ano |findstr 2920
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 2920
TCP 0.0.0.0:443 0.0.0.0:0 LISTENING 2920
TCP [::]:80 [::]:0 LISTENING 2920
TCP [::]:443 [::]:0 LISTENING 2920
C:\Users\yashwanth.m>taskkill /pid 2920 /F
SUCCESS: The process with PID 2920 has been terminated.
Change listening port from main Apache HTTP server configuration file D:\xampp\apache\conf\httpd.conf
. Ex: 81
. From Listen 80
To Listen 81
, the access URL will be http://localhost:81/xampp/index.php
.
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 0.0.0.0:80
#Listen [::]:80
Listen 80
For more information related to httpd and virtual host on XAMPP
Update:
Improved and simplified version of previous directive (one instead of two) with same functionality:
.directive('myTestExpression', ['$parse', function ($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
var expr = attrs.myTestExpression;
var watches = attrs.myTestExpressionWatch;
ctrl.$validators.mytestexpression = function (modelValue, viewValue) {
return expr == undefined || (angular.isString(expr) && expr.length < 1) || $parse(expr)(scope, { $model: modelValue, $view: viewValue }) === true;
};
if (angular.isString(watches)) {
angular.forEach(watches.split(",").filter(function (n) { return !!n; }), function (n) {
scope.$watch(n, function () {
ctrl.$validate();
});
});
}
}
};
}])
Example usage:
<input ng-model="price1"
my-test-expression="$model > 0"
my-test-expression-watch="price2,someOtherWatchedPrice" />
<input ng-model="price2"
my-test-expression="$model > 10"
my-test-expression-watch="price1"
required />
Result: Mutually dependent test expressions where validators are executed on change of other's directive model and current model.
Test expression has local $model
variable which you should use to compare it to other variables.
Previously:
I've made an attempt to improve @Plantface code by adding extra directive. This extra directive very useful if our expression needs to be executed when changes are made in more than one ngModel variables.
.directive('ensureExpression', ['$parse', function($parse) {
return {
restrict: 'A',
require: 'ngModel',
controller: function () { },
scope: true,
link: function (scope, element, attrs, ngModelCtrl) {
scope.validate = function () {
var booleanResult = $parse(attrs.ensureExpression)(scope);
ngModelCtrl.$setValidity('expression', booleanResult);
};
scope.$watch(attrs.ngModel, function(value) {
scope.validate();
});
}
};
}])
.directive('ensureWatch', ['$parse', function ($parse) {
return {
restrict: 'A',
require: 'ensureExpression',
link: function (scope, element, attrs, ctrl) {
angular.forEach(attrs.ensureWatch.split(",").filter(function (n) { return !!n; }), function (n) {
scope.$watch(n, function () {
scope.validate();
});
});
}
};
}])
Example how to use it to make cross validated fields:
<input name="price1"
ng-model="price1"
ensure-expression="price1 > price2"
ensure-watch="price2" />
<input name="price2"
ng-model="price2"
ensure-expression="price2 > price3"
ensure-watch="price3" />
<input name="price3"
ng-model="price3"
ensure-expression="price3 > price1 && price3 > price2"
ensure-watch="price1,price2" />
ensure-expression
is executed to validate model when ng-model
or any of ensure-watch
variables is changed.
To fix this issue, I simply let Tortoise Git install its update.
df.to_sql(name = "owner", con= db_connection, schema = 'aws', if_exists='replace', index = >True, index_label='id')
You can use type
or isinstance
.
In Python 2:
>>> type(u'abc') # Python 2 unicode string literal
<type 'unicode'>
>>> type('abc') # Python 2 byte string literal
<type 'str'>
In Python 2, str
is just a sequence of bytes. Python doesn't know what
its encoding is. The unicode
type is the safer way to store text.
If you want to understand this more, I recommend http://farmdev.com/talks/unicode/.
In Python 3:
>>> type('abc') # Python 3 unicode string literal
<class 'str'>
>>> type(b'abc') # Python 3 byte string literal
<class 'bytes'>
In Python 3, str
is like Python 2's unicode
, and is used to
store text. What was called str
in Python 2 is called bytes
in Python 3.
You can call decode
. If it raises a UnicodeDecodeError exception, it wasn't valid.
>>> u_umlaut = b'\xc3\x9c' # UTF-8 representation of the letter 'Ăś'
>>> u_umlaut.decode('utf-8')
u'\xdc'
>>> u_umlaut.decode('ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
In VB
: This should work
ConfigurationManager.ConnectionStrings("SQLServer").ConnectionString
In C#
it would be (as per comment of Ala)
ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString
@Column
is not the appropriate annotation. You don't want to store a whole User or Question in a column. You want to create an association between the entities. Start by renaming Questions
to Question
, since an instance represents a single question, and not several ones. Then create the association:
@Entity
@Table(name = "UserAnswer")
public class UserAnswer {
// this entity needs an ID:
@Id
@Column(name="useranswer_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "question_id")
private Question question;
@Column(name = "response")
private String response;
//getter and setter
}
The Hibernate documentation explains that. Read it. And also read the javadoc of the annotations.
Try this command:
$ top
http://www.cyberciti.biz/tips/how-do-i-find-out-linux-cpu-utilization.html
It finally worked!!!
I needed to do things to get it to work
I had to add these to both for it to work.
If I added any subdirectories, it did not work for some reason.
Thank you all for your responses.
ArrayList<String[]> action = new ArrayList<String[]>();
Don't need String[2]
;
Regarding 3rd definition:
var foo = function foo() { return 5; }
Heres an example which shows how to use possibility of recursive call:
a = function b(i) {
if (i>10) {
return i;
}
else {
return b(++i);
}
}
console.log(a(5)); // outputs 11
console.log(a(10)); // outputs 11
console.log(a(11)); // outputs 11
console.log(a(15)); // outputs 15
Edit: more interesting example with closures:
a = function(c) {
return function b(i){
if (i>c) {
return i;
}
return b(++i);
}
}
d = a(5);
console.log(d(3)); // outputs 6
console.log(d(8)); // outputs 8
There is a slightly better way to access attached files. You could use template reference variable to get an instance of the input element.
Here is an example based on the first answer:
@Component({
selector: 'my-app',
template: `
<div>
<input type="file" #file (change)="onChange(file.files)"/>
</div>
`,
providers: [ UploadService ]
})
export class AppComponent {
onChange(files) {
console.log(files);
}
}
Here is an example app to demonstrate this in action.
Template reference variables might be useful, e.g. you could access them via @ViewChild directly in the controller.
You can run this command to find the version of Java that's under /Library/Internet Plugins/:
defaults read /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Info.plist CFBundleVersion
NB This answer is factually incorrect; as pointed out by a comment below, success() does return the original promise. I'll not change; and leave it to OP to edit.
The major difference between the 2 is that .then()
call returns a promise (resolved with a value returned from a callback) while .success()
is more traditional way of registering callbacks and doesn't return a promise.
Promise-based callbacks (.then()
) make it easy to chain promises (do a call, interpret results and then do another call, interpret results, do yet another call etc.).
The .success()
method is a streamlined, convenience method when you don't need to chain call nor work with the promise API (for example, in routing).
In short:
.then()
- full power of the promise API but slightly more verbose.success()
- doesn't return a promise but offeres slightly more convienient syntaxNow I hope you can execute update-database successfully.
I've come up with a solution to this that doesn't require you to know the number of row returned.
For example, if you want to get all the locations logged in a table, except the latest 1 (or 2, or 5, or 34)
SELECT *
FROM
(SELECT ROW_NUMBER() OVER (ORDER BY CreatedDate) AS Row, *
FROM Locations
WHERE UserId = 12345) AS SubQuery
WHERE Row > 1 -- or 2, or 5, or 34
The Answer by Bhesh Gurung is correct… unless your NetBeans project is Maven based.
Under Maven, you add a "dependency". A dependency is a description of a library (its name & version number) you want to use from your code.
Or a dependency could be a description of a library which another library needs ("depends on"). Maven automatically handles this chain, libraries that need other libraries that then need other libraries and so on. For the mathematical-minded, perhaps the phrase "Maven resolves the transitive dependencies" makes sense.
Maven gets this related-ness information, and the libraries themselves from a Maven repository. A repository is basically an online database and collection of download files (the dependency library).
Adding a dependency to a Maven-based project is really quite easy. That is the whole point to Maven, to make managing dependent libraries easy and to make building them into your project easy. To get started with adding a dependency, see this Question, Adding dependencies in Maven Netbeans and my Answer with screenshot.
I've seen this kind of thing work in the wild:
<input type="button" th:onclick="'javascript:getContactId(\'' + ${contact.id} + '\');'" />
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div
= document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i <
a.length; i++) {
txtValue = a[i].textContent || a[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
_x000D_
#myInput {
box-sizing: border-box;
background-image: url('searchicon.png');
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: none;
border-bottom: 1px solid #ddd;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
overflow: auto;
border: 1px solid #ddd;
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {
background-color: #ddd;
}
.show {
display: block;
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
<a href="#about">home</a>
<a href="#base">contact</a>
</div>
</div>
_x000D_
Delete node_module and re-install again by command
rm -rf node_modules && npm i
NATIVE is Non access modifier.it can be applied only to METHOD. It indicates the PLATFORM-DEPENDENT implementation of method or code.
you can use localStorage for storing the json data:
the example is given below:-
let JSONDatas = [
{"id": "Open"},
{"id": "OpenNew", "label": "Open New"},
{"id": "ZoomIn", "label": "Zoom In"},
{"id": "ZoomOut", "label": "Zoom Out"},
{"id": "Find", "label": "Find..."},
{"id": "FindAgain", "label": "Find Again"},
{"id": "Copy"},
{"id": "CopyAgain", "label": "Copy Again"},
{"id": "CopySVG", "label": "Copy SVG"},
{"id": "ViewSVG", "label": "View SVG"}
]
localStorage.setItem("datas", JSON.stringify(JSONDatas));
let data = JSON.parse(localStorage.getItem("datas"));
console.log(data);
I would use static readonly
if the Consumer is in a different assembly. Having the const
and the Consumer in two different assemblies is a nice way to shoot yourself in the foot.
Here is couple of ways to calculate length of variable :
echo ${#VAR}
echo -n $VAR | wc -m
echo -n $VAR | wc -c
printf $VAR | wc -m
expr length $VAR
expr $VAR : '.*'
and to set the result in another variable just assign above command with back quote into another variable as following:
otherVar=`echo -n $VAR | wc -m`
echo $otherVar
http://techopsbook.blogspot.in/2017/09/how-to-find-length-of-string-variable.html
A solution which worked in my case is:
1. Go to the module having Main class.
2. Right click on pom.xml under this module.
3. Select "Run Maven" -> "UpdateSnapshots"
simple:
today="$(date '+%Y-%m-%d')"
yesterday="$(date -d yesterday '+%Y-%m-%d')"
Pandas will automatically align these passed in series and create the joint index
They happen to be the same here. reset_index
moves the index to a column.
In [2]: s1 = Series(randn(5),index=[1,2,4,5,6])
In [4]: s2 = Series(randn(5),index=[1,2,4,5,6])
In [8]: DataFrame(dict(s1 = s1, s2 = s2)).reset_index()
Out[8]:
index s1 s2
0 1 -0.176143 0.128635
1 2 -1.286470 0.908497
2 4 -0.995881 0.528050
3 5 0.402241 0.458870
4 6 0.380457 0.072251
If someone is sniffing your plain-text HTTP traffic (or cache/cookies) for passwords just turning the password into a hash won't help - The hash password can be "replayed" just as well as plain-text. The client would need to hash the password with something somewhat random (like the date and time) See the section on "AUTH CRAM-MD5" here: http://www.fehcom.de/qmail/smtpauth.html
A node
is the generic name for any type of object in the DOM hierarchy. A node
could be one of the built-in DOM elements such as document
or document.body
, it could be an HTML tag specified in the HTML such as <input>
or <p>
or it could be a text node that is created by the system to hold a block of text inside another element. So, in a nutshell, a node
is any DOM object.
An element
is one specific type of node
as there are many other types of nodes (text nodes, comment nodes, document nodes, etc...).
The DOM consists of a hierarchy of nodes where each node can have a parent, a list of child nodes and a nextSibling and previousSibling. That structure forms a tree-like hierarchy. The document
node has the html
node as its child.
The html
node has its list of child nodes (the head
node and the body
node). The body
node would have its list of child nodes (the top level elements in your HTML page) and so on.
So, a nodeList
is simply an array-like list of nodes
.
An element is a specific type of node, one that can be directly specified in the HTML with an HTML tag and can have properties like an id
or a class
. can have children, etc... There are other types of nodes such as comment nodes, text nodes, etc... with different characteristics. Each node has a property .nodeType
which reports what type of node it is. You can see the various types of nodes here (diagram from MDN):
You can see an ELEMENT_NODE
is one particular type of node where the nodeType
property has a value of 1
.
So document.getElementById("test")
can only return one node and it's guaranteed to be an element (a specific type of node). Because of that it just returns the element rather than a list.
Since document.getElementsByClassName("para")
can return more than one object, the designers chose to return a nodeList
because that's the data type they created for a list of more than one node. Since these can only be elements (only elements typically have a class name), it's technically a nodeList
that only has nodes of type element in it and the designers could have made a differently named collection that was an elementList
, but they chose to use just one type of collection whether it had only elements in it or not.
EDIT: HTML5 defines an HTMLCollection
which is a list of HTML Elements (not any node, only Elements). A number of properties or methods in HTML5 now return an HTMLCollection
. While it is very similar in interface to a nodeList
, a distinction is now made in that it only contains Elements, not any type of node.
The distinction between a nodeList
and an HTMLCollection
has little impact on how you use one (as far as I can tell), but the designers of HTML5 have now made that distinction.
For example, the element.children
property returns a live HTMLCollection.
In answer to the question in how to write to a file in PHP you can use the following as an example:
$fp = fopen ($filename, "a"); # a = append to the file. w = write to the file (create new if doesn't exist)
if ($fp) {
fwrite ($fp, $text); //$text is what you are writing to the file
fclose ($fp);
$writeSuccess = "Yes";
#echo ("File written");
}
else {
$writeSuccess = "No";
#echo ("File was not written");
}
Before answering, I would like to give you some data from Wiki
Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.
When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.
To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.
gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:
typedef struct
{
char Data1;
int Data2;
unsigned short Data3;
char Data4;
}sSampleStruct;
sizeof(sSampleStruct)
will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:
typedef struct
{
char Data1;
//3-Bytes Added here.
int Data2;
unsigned short Data3;
char Data4;
//1-byte Added here.
}sSampleStruct;
We can use __attribute__((packed, aligned(X)))
to insist particular(X) sized padding. X should be powers of two. Refer here
typedef struct
{
char Data1;
int Data2;
unsigned short Data3;
char Data4;
}__attribute__((packed, aligned(1))) sSampleStruct;
so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.
If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma
#pragma pack(push, 1)
//Structure 1
......
//Structure 2
......
#pragma pack(pop)
No need to do so much of trouble! Its simple
This will create 2 * 3 matrix of string.
var array=[];
var x = 2, y = 3;
var s = 'abcdefg';
for(var i = 0; i<x; i++){
array[i]=new Array();
for(var j = 0; j<y; j++){
array[i].push(s.charAt(counter++));
}
}
In your manifest use:-
android:theme="@style/AppTheme" >
in styles.xml:-
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
</style>
Surprisingly this works as yo desire, Using the same parent of AppBaseTheme in AppTheme does not.
Open Source: CMU Sphinx
Shareware: http://www.e-speaking.com/ (Windows)
Commercial: Dragon NaturallySpeaking (Windows)
Try this:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+elemA+"&lon="+elemB+"&setLatLon=Set";
To put a variable in a string enclose the variable in quotes and addition signs like this:
var myname = "BOB";
var mystring = "Hi there "+myname+"!";
Just remember that one rule!
To come full circle and include all versions of Visual Studio, @Myster originally stated that;
Pre Visual Studio 2015 the paths to applicationhost.config were:
%userprofile%\documents\iisexpress\config\applicationhost.config
%userprofile%\my documents\iisexpress\config\applicationhost.config
Visual Studio 2015/2017 path can be found at: (credit: @Talon)
$(solutionDir)\.vs\config\applicationhost.config
Visual Studio 2019 path can be found at: (credit: @Talon)
$(solutionDir)\.vs\config\$(ProjectName)\applicationhost.config
But the part that might get some people is that the project settings in the .sln file can repopulate the applicationhost.config for Visual Studio 2015+. (credit: @Lex Li)
So, if you make a change in the applicationhost.config you also have to make sure your changes match here:
$(solutionDir)\ProjectName.sln
The two important settings should look like:
Project("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}") = "ProjectName", "ProjectPath\", "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"
and
VWDPort = "Port#"
What is important here is that the two settings in the .sln must match the name and bindingInformation respectively in the applicationhost.config file if you plan on making changes. There may be more places that link these two files and I will update as I find more links either by comments or more experience.
It's basically how association is made to the element. .click
applies to the current DOM, while .on
(using delegation) will continue to be valid for new elements added to the DOM after event association.
Which is better to use, I'd say it depends on the case.
Example:
<ul id="todo">
  <li>Do 1</li>
  <li>Do 2</li>
  <li>Do 3</li>
  <li>Do 4</li>
</ul>
.Click Event:
$("li").click(function () {
  $(this).remove ();
});
Event .on:
$("#todo").on("click", "li", function () {
  $(this).remove();
});
Note that I've separated the selector in the .on. I'll explain why.
Let us suppose that after this association, let us do the following:
$("#todo").append("<li>Do 5</li>");
That is where you will notice the difference.
If the event was associated via .click, task 5 will not obey the click event, and so it will not be removed.
If it was associated via .on, with the selector separate, it will obey.
If one wants to have the conf\logging.properties
read one must (see also here) dump this file into the Servers\Tomcat v7.0 Server at localhost-config\
folder and then add the lines :
-Djava.util.logging.config.file="${workspace_loc}\Servers\Tomcat v7.0 Server at localhost-config\logging.properties" -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
to the VM arguments of the launch configuration one is using.
This may have taken a restart or two (or not) but finally I saw in the console in bright red :
FINE: No TLD files were found in [file:/C:/Dropbox/eclipse_workspaces/javaEE/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ted2012/WEB-INF/lib/logback-classic-1.0.7.jar]. Consider adding the JAR to the tomcat.util.scan.DefaultJarScanner.jarsToSkip or org.apache.catalina.startup.TldConfig.jarsToSkip property in CATALINA_BASE/conf/catalina.properties file. //etc
I still don't know when exactly this EDIT: from the comment by @Stephan: "The FINE warning appears each time any change is done in the JSP file".FINE
warning appears - does not appear immediately on tomcat launch
Bonus: To make the warning go away add in catalina.properties
:
# Additional JARs (over and above the default JARs listed above) to skip when
# scanning for TLDs. The list must be a comma separated list of JAR file names.
org.apache.catalina.startup.TldConfig.jarsToSkip=logback-classic-1.0.7.jar,\
joda-time-2.1.jar,joda-time-2.1-javadoc.jar,mysql-connector-java-5.1.24-bin.jar,\
logback-core-1.0.7.jar,javax.servlet.jsp.jstl-api-1.2.1.jar
use the time and datetime packages.
if anybody want to execute this script and also find out how much time it took to execute in minutes
import time
from time import strftime
from datetime import datetime
from time import gmtime
def start_time_():
#import time
start_time = time.time()
return(start_time)
def end_time_():
#import time
end_time = time.time()
return(end_time)
def Execution_time(start_time_,end_time_):
#import time
#from time import strftime
#from datetime import datetime
#from time import gmtime
return(strftime("%H:%M:%S",gmtime(int('{:.0f}'.format(float(str((end_time-start_time))))))))
start_time = start_time_()
# your code here #
[i for i in range(0,100000000)]
# your code here #
end_time = end_time_()
print("Execution_time is :", Execution_time(start_time,end_time))
The above code works for me. I hope this helps.
this.setState({
arrayvar: [...this.state.arrayvar, ...newelement]
})
If your team uses TFS and you want to use Git you might want to consider a "git to tfs" bridge. Essentially you work day to day using Git on your computer, then when you want to push your changes you push them to the TFS server.
There are a couple out there (on github). I used one at my last place (along with another developer) with some success. See:
7 years later and this code has helped me. However, my times still were not showing up correctly.
Using Matplotlib 2.0.0 and I had to add the following bit of code from Editing the date formatting of x-axis tick labels in matplotlib by Paul H.
import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)
I changed the format to (%H:%M) and the time displayed correctly.
All thanks to the community.
Query in Parado's answer is correct, if you want to use MySql too instead GETDATE() you must use (because you've tagged this question with Sql server and Mysql):
select * from tab
where DateCol between adddate(now(),-7) and now()
Or like this :
npm install cors
cors = require("cors");
app.use(cors());
This little extension method should give you exception-safe async iteration:
public static async Task ForEachAsync<T>(this List<T> list, Func<T, Task> func)
{
foreach (var value in list)
{
await func(value);
}
}
Since we're changing the return type of the lambda from void
to Task
, exceptions will propagate up correctly. This will allow you to write something like this in practice:
await db.Groups.ToList().ForEachAsync(async i => {
await GetAdminsFromGroup(i.Gid);
});
Run WampServer: Apache->service->test port 80.
Find out what application which occupies the port 80(e.g. skype)
Shut down and restarts WampServer.
var elementCheckBox = document.getElementById("IdOfCheckBox");_x000D_
_x000D_
_x000D_
elementCheckBox[0].checked //return true if checked and false if not checked
_x000D_
thanks
valgrind (only avail for *nix platforms) is a very nice memory checker
Swift 4
In viewDidLoad() just call below code:
CODE SAMPLE
//txtVComplaint is a textView
txtVComplaint.tintColor = UIColor.white
txtVComplaint.tintColorDidChange()
An array is a pointer. It points to the start of a sequence of "objects".
If we do this: ìnt arr[10];
, then arr
is a pointer to a memory location, from which ten integers follow. They are uninitialised, but the memory is allocated. It is exactly the same as doing int *arr = new int[10];
.
You can do something like:
s = np.random.normal(2, 3, 1000)
import matplotlib.pyplot as plt
count, bins, ignored = plt.hist(s, 30, density=True)
plt.plot(bins, 1/(3 * np.sqrt(2 * np.pi)) * np.exp( - (bins - 2)**2 / (2 * 3**2) ),
linewidth=2, color='r')
plt.show()
simply use loc:
>>> df
A B C
one 1 2 3
>>> df.loc["two"] = [4,5,6]
>>> df
A B C
one 1 2 3
two 4 5 6
Use subprocess.Popen()
with the close_fds=True
parameter, which will allow the spawned subprocess to be detached from the Python process itself and continue running even after Python exits.
https://gist.github.com/yinjimmy/d6ad0742d03d54518e9f
import os, time, sys, subprocess
if len(sys.argv) == 2:
time.sleep(5)
print 'track end'
if sys.platform == 'darwin':
subprocess.Popen(['say', 'hello'])
else:
print 'main begin'
subprocess.Popen(['python', os.path.realpath(__file__), '0'], close_fds=True)
print 'main end'
Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.
So, first build a list, then use pickle.dump
to send it to a file...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
>>> import pickle
>>>
>>> with open('parrot.pkl', 'wb') as f:
... pickle.dump(mylist, f)
...
>>>
Then quit and come back later… and open with pickle.load
...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
... mynewlist = pickle.load(f)
...
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
you should convert test type >>>> test.tostring();
change the last line to this :
Label1.Text = "Du har nu lĂĄnat filmen:" + test.tostring();
One option is to put the character literally in your script, e.g.:
const omega = 'O';
This requires that you let the browser know the correct source encoding, see Unicode in JavaScript
However, if you can't or don't want to do this (e.g. because the character is too exotic and can't be expected to be available in the code editor font), the safest option may be to use new-style string escape or String.fromCodePoint
:
const omega = '\u{3a9}';
// or:
const omega = String.fromCodePoint(0x3a9);
This is not restricted to UTF-16 but works for all unicode code points. In comparison, the other approaches mentioned here have the following downsides:
const omega = 'Ω';
): only work when rendered unescaped in an HTML elementconst omega = '\u03A9';
): restricted to UTF-16String.fromCharCode
: restricted to UTF-16In Android Studio 1.0 - 1.1b4, I found this to be the easiest way to remove a module:
Open settings.gradle
found under Gradle Scripts
Delete module's name from the include statement
Sync Project with Gradle Files
Optionally, delete it manually from the project folder
Example
Old:
include ':app', ':greendao'
New:
include ':app'
I collected some ideas from other SO question (largely from here and this css page)
The idea is to use relative and absolute positioning to move your line to the bottom:
@media (min-width: 768px ) {
.row {
position: relative;
}
#bottom-align-text {
position: absolute;
bottom: 0;
right: 0;
}}
The display:flex
option is at the moment a solution to make the div get the same size as its parent. This breaks on the other hand the bootstrap possibilities to auto-linebreak on small devices by adding col-sx-12
class. (This is why the media query is needed)
I like the free GeoLite City from Maxmind which works for most applications and from which you can upgrade to a paying version if it's not precise enough. There is a PHP API included, as well as for other languages. And if you are running Lighttpd as a webserver, you can even use a module to get the information in the SERVER variable for every visitor if that's what you need.
I should add there is also a free Geolite Country (which would be faster if you don't need to pinpoint the city the IP is from) and Geolite ASN (if you want to know who owns the IP) and that finally all these are downloadable on your own server, are updated every month and are pretty quick to lookup with the provided APIs as they state "thousands of lookups per second".
A lesser perplexing way to look at it would be:
string = 'happy'
print(string)
'happy'
string_reversed = string[-1::-1]
print(string_reversed)
'yppah'
In English [-1::-1] reads as:
"Starting at -1, go all the way, taking steps of -1"
str=str.replace(/^\s+|\s+$/g,'');
String query="select * from test1 where "+selected+" like '%"+SelectedStr+"%';";
PreparedStatement preparedStatement=con.prepareStatement(query);
// where seleced and SelectedStr are String Variables in my program
Seems like a lazy way to always know that your WHERE clause is already defined and allow you to keep adding conditions without having to check if it is the first one.
Just a brief note - I'm using a modified version of plain.bst sitting in the directory with my Latex files; it turns out having sorting by order of appearance is a relatively easy change; just find the piece of code:
...
ITERATE {presort}
SORT
...
... and comment it - I turned it to:
...
%% % avoid sort:
%% ITERATE {presort}
%%
%% SORT
...
... and then, after running bibtex
, pdflatex
, pdflatex
- the citations will be sorted by order of appearance (that is, they will be unsorted :) ).
Cheers!
EDIT: just realized that what I wrote is actually in the comment by @ChrisN: "can you edit it to remove the SORT command" ;)
For ASP.NET try this:
<script type="text/javascript">
Sys.Application.add_load(function() { ... });
</script>
This appears to work on page load and on update panel load
Please find the full discussion here.
I recently had a similar problem in latest Eclipse (Kepler) and fixed it by disabling the option "Honour all XML schema locations" in Preferences > XML > XML Files > Validation. It disables validation for references to the same namespaces that point to different schema locations, only taking the first found generally in the XML file being validated. This option comes from the Xerces library.
WTP Doc: http://www.eclipse.org/webtools/releases/3.1.0/newandnoteworthy/sourceediting.php
Xerces Doc: http://xerces.apache.org/xerces2-j/features.html#honour-all-schemaLocations
Here is one Postman echo: https://docs.postman-echo.com/
example:
curl --request POST \
--url https://postman-echo.com/post \
--data 'This is expected to be sent back as part of response body.'
response:
{"args":{},"data":"","files":{},"form":{"This is expected to be sent back as part of response body.":""},"headers":{"host":"postman-echo.com","content-length":"58","accept":"*/*","content-type":"application/x-www-form-urlencoded","user-agent":"curl/7.54.0","x-forwarded-port":"443","x-forwarded-proto":"https"},"json":{"...
Call To the following function with argument as you file path:
private String getFileContent(String targetFilePath){
File file = new File(targetFilePath);
try {
fileInputStream = new FileInputStream(file);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e("",""+e.printStackTrace());
}
StringBuilder sb;
while(fileInputStream.available() > 0) {
if(null== sb) sb = new StringBuilder();
sb.append((char)fileInputStream.read());
}
String fileContent;
if(null!=sb){
fileContent= sb.toString();
// This is your fileContent in String.
}
try {
fileInputStream.close();
}
catch(Exception e){
// TODO Auto-generated catch block
Log.e("",""+e.printStackTrace());
}
return fileContent;
}
Some social tools like Google+ use a simple method to get a favicon for external links, fetching http://your.domainname.com/favicon.ico
Since they don't prefetch the HTML content, the <link>
tag will not work. In this case, you might want to use a mod_rewrite rule or just place the file in the default location.
Ok, sorry for my previous answer, I had never seen that Overview screen before.
Here is how I did it:
With this command you will see all changes in the repository path/to/repo
that were committed in revision <revision>
:
svn diff -c <revision> path/to/repo
The -c
indicates that you would like to look at a changeset, but there are many other ways you can look at diffs and changesets. For example, if you would like to know which files were changed (but not how), you can issue
svn log -v -r <revision>
Or, if you would like to show at the changes between two revisions (and not just for one commit):
svn diff -r <revA>:<revB> path/to/repo
If it's okay that you can use Python, then numexpr
module has a function for this:
In [5]: import numexpr as ne
In [6]: ne.detect_number_of_cores()
Out[6]: 8
also this:
In [7]: ne.ncores
Out[7]: 8
To query this information from the command prompt use:
# runs whatever valid Python code given as a string with `-c` option
$ python -c "import numexpr as ne; print(ne.ncores)"
8
Or simply it is possible to get this info from multiprocessing.cpu_count()
function
$ python -c "import multiprocessing; print(multiprocessing.cpu_count())"
Or even more simply use os.cpu_count()
$ python -c "import os; print(os.cpu_count())"
If you just want an array of month names from the beginning of the year to the end e.g. to populate a drop-down select, I would just use the following;
for ($i = 0; $i < 12; ++$i) {
$months[$m] = $m = date("F", strtotime("January +$i months"));
}
Cors issue has been faced in my application. refer above screenshot. After adding proxy config issue has been resolved. my application url: localhost:4200 and requesting api url:"http://www.datasciencetoolkit.org/maps/api/geocode/json?sensor=false&address="
Api side no-cors permission allowed. And also I'm not able to change cors-issue in server side and I had to change only in angular(client side).
Steps to resolve:
{ "/maps/*": { "target": "http://www.datasciencetoolkit.org", "secure": false, "logLevel": "debug", "changeOrigin": true } }
this.http .get<GeoCode>('maps/api/geocode/json?sensor=false&address=' + cityName) .pipe( tap(cityResponse => this.responseCache.set(cityName, cityResponse)) );
Note: We have skip hostname name url in Api request, it will auto add while giving request. whenever changing proxy.conf.js we have to restart ng-serve, then only changes will update.
"serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "TestProject:build", "proxyConfig": "src/proxy.conf.json" }, "configurations": { "production": { "browserTarget": "TestProject:build:production" } } },
After finishing these step restart ng-serve Proxy working correctly as expect refer here
> WARNING in
> D:\angular\Divya_Actian_Assignment\src\environments\environment.prod.ts
> is part of the TypeScript compilation but it's unused. Add only entry
> points to the 'files' or 'include' properties in your tsconfig.
> ** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ ** : Compiled
> successfully. [HPM] GET
> /maps/api/geocode/json?sensor=false&address=chennai ->
> http://www.datasciencetoolkit.org
How about a software solution:
Install SSH server on the application server. Then, use socket tunnel to create a link between your local port and the remote port on the application server. You can use ssh client tools to do so. Have your client application connect to your mapped local port instead. Then, you can break the socket tunnel at will to simulate the connection timeout.
if you have API level smaller than 23 than you must use it this way. it worked for me declare this under v21/style.
<item name="colorPrimaryDark" tools:targetApi="23">@color/colorPrimary</item>
<item name="android:windowLightStatusBar" tools:targetApi="23">true</item>
you could try:
<a href="#/controllerone">Controller One</a>||
<a href="#/controllerTwo">Controller Two</a>||
<a href="#/controllerThree">Controller Three</a>
<div>
<div ng-view=""></div>
</div>
Try this code to use:
/* For Mozile Firefox Browser */
::-moz-selection { background-color: #4CAF50; }
/* For Other Browser*/
::selection { background-color: #4CAF50; }
For me the cleanest and easiest way was:
import java.util.Arrays;
Arrays.toString(e.getStackTrace());
If you have vectors destined to become rows, concatenate them using c()
, pass them to a matrix row-by-row, and convert that matrix to a dataframe.
For example, rows
dummydata1=c(2002,10,1,12.00,101,426340.0,4411238.0,3598.0,0.92,57.77,4.80,238.29,-9.9)
dummydata2=c(2002,10,2,12.00,101,426340.0,4411238.0,3598.0,-3.02,78.77,-9999.00,-99.0,-9.9)
dummydata3=c(2002,10,8,12.00,101,426340.0,4411238.0,3598.0,-5.02,88.77,-9999.00,-99.0,-9.9)
can be converted to a data frame thus:
dummyset=c(dummydata1,dummydata2,dummydata3)
col.len=length(dummydata1)
dummytable=data.frame(matrix(data=dummyset,ncol=col.len,byrow=TRUE))
Admittedly, I see 2 major limitations: (1) this only works with single-mode data, and (2) you must know your final # columns for this to work (i.e., I'm assuming that you're not working with a ragged array whose greatest row length is unknown a priori).
This solution seems simple, but from my experience with type conversions in R, I'm sure it creates new challenges down-the-line. Can anyone comment on this?
Isn't this what default constructors are for?
class MyModel
{
public MyModel()
{
this.ReturnDate = DateTime.Now;
}
public date ReturnDate {get; set;};
}
If you want a quick&easy solution and save yourself from typing newlines, you could opt for a list instead, e.g.:
def func(*args, **kwargs):
string = '\n'.join([
'first line of very long string and',
'second line of the same long thing and',
'third line of ...',
'and so on...',
])
print(string)
return
The speed cannot be controlled by the API. Though you can modify CSS that is in charge of that.
In the carousel.less
file find
.item {
display: none;
position: relative;
.transition(.6s ease-in-out left);
}
and change .6s
to whatever you want.
In case you do not use .less, find in the bootstrap.css
file:
.carousel-inner > .item {
position: relative;
display: none;
-webkit-transition: 0.6s ease-in-out left;
-moz-transition: 0.6s ease-in-out left;
-o-transition: 0.6s ease-in-out left;
transition: 0.6s ease-in-out left;
}
and change 0.6s
to the time you want. You also might want to edit time in the function call below:
.emulateTransitionEnd(2000)
at bootstrap.js
in function Carousel.prototype.slide
. That synchronize transition and prevent slide to disapear before transition ends.
EDIT 7/8/2014
As @YellowShark pointed out the edits in JS are not needed anymore. Only apply css changes.
EDIT 20/8/2015 Now, after you edit your css file, you just need to edit CAROUSEL.TRANSITION_DURATION (in bootstrap.js) or c.TRANSITION_DURATION (if you use bootstrap.min.js) and to change the value inside it (600 for default). The final value must be the same that you put in your css file( for example 10s in css = 10000 in .js)
EDIT 16/01/2018 For Bootstrap 4, to change the transition time to e.g., 2 seconds, add
$(document).ready(function() {
jQuery.fn.carousel.Constructor.TRANSITION_DURATION = 2000 // 2 seconds
});
to your site's JS file, and
.carousel-inner .carousel-item {
transition: -webkit-transform 2s ease;
transition: transform 2s ease;
transition: transform 2s ease, -webkit-transform 2s ease;
}
to your site's CSS file.
Ok, I did that and it works:
nano ~/.bash_profile
And paste
export PATH=~/.composer/vendor/bin:$PATH
do source ~/.bash_profile
and enjoy ;)
Important: If you want to know the difference between bash_profile and bashrc please check this link
Note: For Ubuntu 16.04 running laravel 5.1, the path is: ~/.config/composer/vendor/bin
On other platforms: To check where your Composer global directory is, run composer global about
. Add /vendor/bin
to the directory that gets listed after "Changed current directory to ..." to get the path you should add to your PATH
.
There is very little overall difference between GCC 4.8 and clang 3.3 in terms of speed of the resulting binary. In most cases code generated by both compilers performs similarly. Neither of these two compilers dominates the other one.
Benchmarks telling that there is a significant performance gap between GCC and clang are coincidental.
Program performance is affected by the choice of the compiler. If a developer or a group of developers is exclusively using GCC then the program can be expected to run slightly faster with GCC than with clang, and vice versa.
From developer viewpoint, a notable difference between GCC 4.8+ and clang 3.3 is that GCC has the -Og
command line option. This option enables optimizations that do not interfere with debugging, so for example it is always possible to get accurate stack traces. The absence of this option in clang makes clang harder to use as an optimizing compiler for some developers.
One way would be to create a variable that represents the first of the month (ie 5/1/2009), either pass it into the proc or build it (concatenate month/1/year). Then use the DateDiff function.
WHERE DateDiff(m,@Date,DateField) = 0
This will return anything with a matching month and year.
If you use Safari, you can write
console.log("your message here");
and it appears right on the console of the browser.
Call the parent method with the parent scope resolution operator.
Parent::method()
class Primate {
public:
void whatAmI(){
cout << "I am of Primate order";
}
};
class Human : public Primate{
public:
void whatAmI(){
cout << "I am of Human species";
}
void whatIsMyOrder(){
Primate::whatAmI(); // <-- SCOPE RESOLUTION OPERATOR
}
};
I know this is a damn old question, but as the OP is about scripting, and for the fact that google brought me here, opening file descriptors for reading and writing at the same time should also be mentioned.
#!/bin/bash
# Open file descriptor (fd) 3 for read/write on a text file.
exec 3<> poem.txt
# Let's print some text to fd 3
echo "Roses are red" >&3
echo "Violets are blue" >&3
echo "Poems are cute" >&3
echo "And so are you" >&3
# Close fd 3
exec 3>&-
Then cat
the file on terminal
$ cat poem.txt
Roses are red
Violets are blue
Poems are cute
And so are you
This example causes file poem.txt to be open for reading and writing on file descriptor 3. It also shows that *nix boxes know more fd's then just stdin, stdout and stderr (fd 0,1,2). It actually holds a lot. Usually the max number of file descriptors the kernel can allocate can be found in /proc/sys/file-max
or /proc/sys/fs/file-max
but using any fd above 9 is dangerous as it could conflict with fd's used by the shell internally. So don't bother and only use fd's 0-9. If you need more the 9 file descriptors in a bash script you should use a different language anyways :)
Anyhow, fd's can be used in a lot of interesting ways.
There are many options how to write a regex pattern for that
^(?:(?!0)\d{1,2}|100)$
^(?:[1-9]\d?|100)$
^(?!0)(?=100$|..$|.$)\d+$
Is this a console program project or a Windows project? I'm asking because for a Win32 and similar project, the entry point is WinMain()
.
If it says Subsystem Windows
your entry point should be WinMain(), i.e.
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd)
{
your code here ...
}
Besides, speaking of the comments. This is a compile (or more precisely a Link) error, not a run-time error. When you start to debug, the compiler needs to make a complete program (not just to compile your module) and that is when the error occurs.
It does not even get to the point being loaded and run.
I think a better answer here is simply this:
mike@sleepycat:~? kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1
11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM
16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ
26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR
31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3
38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7
58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
As for the "significance" of 9... I would say there is probably none. According to The Linux Programming Interface(p 388):
Each signal is defined as a unique (small) integer, starting sequentially from 1. These integers are defined in with symbolic names of the form SIGxxxx . Since the actual numbers used for each signal vary across implementations, it is these symbolic names that are always used in programs.
No, you can't do it by using an actual <select>
, but there are techniques that allow you to "replace" them with javascript solutions that look better.
Here's a good article on the topic: <select> Something New
Like this :
jQuery(document).ready(function () {
var title = jQuery(this).attr('title');
});
works for IE, Firefox and Chrome.
If your only requirement is to print the third field of every line, with each field delimited by a comma, you can use cut:
cut -d, -f3 file
-d,
sets the delimiter to a comma-f3
specifies that only the third field is to be printedA function call needs to be performed with objects. You are doing the equivalent of this:
// function declaration/definition
void foo(int) {}
// function call
foo(int); // wat!??
i.e. passing a type where an object is required. This makes no sense in C or C++. You need to be doing
int i = 42;
foo(i);
or
foo(42);
<p>Here is a quote from WWF's website:</p>.
In this part <p>
is a tag.
<blockquote cite="www.facebook.com">facebook is the world's largest socialsite..</blockquote>
in this part <blockquote>
is an element.
I faced similar problem. So far I know result may different for different names, so finally came to this solution.
public String getMimeType(String filePath) {
String type = null;
String extension = null;
int i = filePath.lastIndexOf('.');
if (i > 0)
extension = filePath.substring(i+1);
if (extension != null)
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
return type;
}
If your html is similar to the example, so the click event is produced over the label, not in the input, so I use the next code: Html example:
<div id="myButtons" class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
</label>
</div>
Javascript code for the event:
$('#option1').parent().on("click", function () {
alert("click fired");
});
A DataSet
already contains DataTables
. You can just use:
DataTable firstTable = dataSet.Tables[0];
or by name:
DataTable customerTable = dataSet.Tables["Customer"];
Note that you should have using
statements for your SQL code, to ensure the connection is disposed properly:
using (SqlConnection conn = ...)
{
// Code here...
}
Whatever I understood from my learning and what I think it is is here. I am Quoting some part from a book i learnt this things. Nexus Repository Manager and Nexus Repository Manager OSS started as a repository manager supporting the Maven repository format. While it supports many other repository formats now, the Maven repository format is still the most common and well supported format for build and provisioning tools running on the JVM and beyond. This chapter shows example configurations for using the repository manager with Apache Maven and a number of other tools. The setups take advantage of merging many repositories and exposing them via a repository group. Setting this up is documented in the chapter in addition to the configuration used by specific tools.
From the WordPress Codex:
<?php
$the_slug = 'my_slug';
$args = array(
'name' => $the_slug,
'post_type' => 'post',
'post_status' => 'publish',
'numberposts' => 1
);
$my_posts = get_posts($args);
if( $my_posts ) :
echo 'ID on the first post found ' . $my_posts[0]->ID;
endif;
?>
The reason it suggest to replace ==
with ===
is that the ===
operator is more reliable than ==
. In our context reliable means ===
also goes for type checking. Considering the best programming practices we should always choose more reliable feature over less reliable one. Again whenever we think about exactly equal to operator most of the time, we are by default consider the type should be same. As ===
provides the same, we should go for it.
How to write literal boolean value in SQL Server?
select * from SomeTable where PSEUDO_TRUE
There is no such thing.
You have to compare the value with something using = < > like ...
. The closest you get a boolean value in SQL Server is the bit. And that is an integer that can have the values null
, 0
and 1
.
Of course it is an old post but just for people how will find it through search engine.
Another solution is to run it like this for IE9 and later
iexplore.exe" -noframemerging http://google.com
iexplore.exe" -noframemerging http://gmail.com
-noframemerging means run IE independently. For example it you want to run 2 browser and login as different username it will not work if you just run 2 IE. but with -noframemerging it will work. -noframemerging works for IE9 and later, for early versions like IE8 it is -nomerge
usually I create 1 but file like this run_ie.bat
"c:\Program Files (x86)\Internet Explorer\iexplore.exe" -noframemerging %1
and I create another bat file like this run_2_ie.bat
start run_ie.bat http://google.com
start run_ie.bat http://yahoo.com
with pages as (
SELECT object_id, SUM (reserved_page_count) as reserved_pages, SUM (used_page_count) as used_pages,
SUM (case
when (index_id < 2) then (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)
else lob_used_page_count + row_overflow_used_page_count
end) as pages
FROM sys.dm_db_partition_stats
group by object_id
), extra as (
SELECT p.object_id, sum(reserved_page_count) as reserved_pages, sum(used_page_count) as used_pages
FROM sys.dm_db_partition_stats p, sys.internal_tables it
WHERE it.internal_type IN (202,204,211,212,213,214,215,216) AND p.object_id = it.object_id
group by p.object_id
)
SELECT object_schema_name(p.object_id) + '.' + object_name(p.object_id) as TableName, (p.reserved_pages + isnull(e.reserved_pages, 0)) * 8 as reserved_kb,
pages * 8 as data_kb,
(CASE WHEN p.used_pages + isnull(e.used_pages, 0) > pages THEN (p.used_pages + isnull(e.used_pages, 0) - pages) ELSE 0 END) * 8 as index_kb,
(CASE WHEN p.reserved_pages + isnull(e.reserved_pages, 0) > p.used_pages + isnull(e.used_pages, 0) THEN (p.reserved_pages + isnull(e.reserved_pages, 0) - p.used_pages + isnull(e.used_pages, 0)) else 0 end) * 8 as unused_kb
from pages p
left outer join extra e on p.object_id = e.object_id
Takes into account internal tables, such as those used for XML storage.
Edit: If you divide the data_kb
and index_kb
values by 1024.0, you will get the numbers you see in the GUI.
You can do this by adding following script and style
function appHeight() {
const doc = document.documentElement
doc.style.setProperty('--vh', (window.innerHeight*.01) + 'px');
}
window.addEventListener('resize', appHeight);
appHeight();
Style
.module {
height: 100vh; /* Fallback for browsers that do not support Custom Properties */
height: calc(var(--vh, 1vh) * 100);
}
Find Microsoft Visual C++ 2010 x86/x64 Redistributable – 10.0.xxxxx in the control panel of the add or remove programs if xxxxx > 30319 renmove it
Following is another version that does the same thing (and handle nested properties), which I think is simpler (no dependencies on external libraries and can be modified easily to do things other than logging):
public class ObjectDumper
{
public static string Dump(object obj)
{
return new ObjectDumper().DumpObject(obj);
}
StringBuilder _dumpBuilder = new StringBuilder();
string DumpObject(object obj)
{
DumpObject(obj, 0);
return _dumpBuilder.ToString();
}
void DumpObject(object obj, int nestingLevel = 0)
{
var nestingSpaces = "".PadLeft(nestingLevel * 4);
if (obj == null)
{
_dumpBuilder.AppendFormat("{0}null\n", nestingSpaces);
}
else if (obj is string || obj.GetType().IsPrimitive)
{
_dumpBuilder.AppendFormat("{0}{1}\n", nestingSpaces, obj);
}
else if (ImplementsDictionary(obj.GetType()))
{
using (var e = ((dynamic)obj).GetEnumerator())
{
var enumerator = (IEnumerator)e;
while (enumerator.MoveNext())
{
dynamic p = enumerator.Current;
var key = p.Key;
var value = p.Value;
_dumpBuilder.AppendFormat("{0}{1} ({2})\n", nestingSpaces, key, value != null ? value.GetType().ToString() : "<null>");
DumpObject(value, nestingLevel + 1);
}
}
}
else if (obj is IEnumerable)
{
foreach (dynamic p in obj as IEnumerable)
{
DumpObject(p, nestingLevel);
}
}
else
{
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
{
string name = descriptor.Name;
object value = descriptor.GetValue(obj);
_dumpBuilder.AppendFormat("{0}{1} ({2})\n", nestingSpaces, name, value != null ? value.GetType().ToString() : "<null>");
DumpObject(value, nestingLevel + 1);
}
}
}
bool ImplementsDictionary(Type t)
{
return t.GetInterfaces().Any(i => i.Name.Contains("IDictionary"));
}
}
I decided I didn't want to use a pickle because I wanted to be able to open the text file and change its contents easily during testing. Therefore, I did this:
score = [1,2,3,4,5]
with open("file.txt", "w") as f:
for s in score:
f.write(str(s) +"\n")
score = []
with open("file.txt", "r") as f:
for line in f:
score.append(int(line.strip()))
So the items in the file are read as integers, despite being stored to the file as strings.
Just test if the array is empty.
$.getJSON(url,function(json){
if ( json.length == 0 ) {
console.log("NO DATA!")
}
});
In my opinion, the solution proposed by user1965719 is really elegant. In my project, all objects going in to the containing div is dynamically created, so adding the extra hidden button is a breeze:
aspx code:
<asp:Button runat="server" id="btnResponse1" Text=""
style="display: none; width:100%; height:100%"
OnClick="btnResponses_Clicked" />
<div class="circlebuttontext" id="calendarButtonText">Calendar</div>
</div>
C# code behind:
protected void btnResponses_Clicked(object sender, EventArgs e)
{
if(sender == btnResponse1)
{
//Your code behind logic for that button goes here
}
}
You can use the transpose
function from the data.table
library. Simple and fast solution that keeps numeric
values as numeric
.
library(data.table)
# get data
data("mtcars")
# transpose
t_mtcars <- transpose(mtcars)
# get row and colnames in order
colnames(t_mtcars) <- rownames(mtcars)
rownames(t_mtcars) <- colnames(mtcars)
I am using a very simple solution. Here my code:
imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.getLayoutParams().height = imageView.getLayoutParams().width;
imageView.setMinimumHeight(imageView.getLayoutParams().width);
My pictures are added dynamically in a gridview. When you make these settings to the imageview, the picture can be automatically displayed in 1:1 ratio.
Try doing this, there's no special character to concatenate in bash :
mystring="${arg1}12${arg2}endoffile"
If you don't put brackets, you will ask bash to concatenate $arg112 + $argendoffile
(I guess that's not what you asked) like in the following example :
mystring="$arg112$arg2endoffile"
The brackets are delimiters for the variables when needed. When not needed, you can use it or not.
bash
> 3.1)
$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile
As the dictionary documentation for python 2 and python 3 would tell you, in python 2 items
returns a list, while iteritems
returns a iterator.
In python 3, items
returns a view, which is pretty much the same as an iterator.
If you are using python 2, you may want to user iteritems
if you are dealing with large dictionaries and all you want to do is iterate over the items (not necessarily copy them to a list)
Shorter version:
dependencies {
implementation fileTree('lib')
}
This should cover a slightly more general case, but you should be able to customize it for your purpose
def selectiveReplace(myStr):
answer = []
for index,char in enumerate(myStr):
if char == ';':
if index%2 == 1: # replace ';' in even indices with ":"
answer.append(":")
else:
answer.append("!") # replace ';' in odd indices with "!"
else:
answer.append(char)
return ''.join(answer)
Hope this helps
"IP conntrack functionality has some negative impact on venet performance (uo to about 10%), so they better be disabled by default." It's need for nat
https://serverfault.com/questions/593263/iptables-nat-does-not-exist
The below is my code from reading text file to excel file.
Sub openteatfile()
Dim i As Long, j As Long
Dim filepath As String
filepath = "C:\Users\TarunReddyNuthula\Desktop\sample.ctxt"
ThisWorkbook.Worksheets("Sheet4").Range("Al:L20").ClearContents
Open filepath For Input As #1
i = l
Do Until EOF(1)
Line Input #1, linefromfile
lineitems = Split(linefromfile, "|")
For j = LBound(lineitems) To UBound(lineitems)
ThisWorkbook.Worksheets("Sheet4").Cells(i, j + 1).value = lineitems(j)
Next j
i = i + 1
Loop
Close #1
End Sub
@jim's answer is correct -- fuser
is what you want.
Additionally (or alternately), you can use lsof
to get more information including the username, in case you need permission (without having to run an additional command) to kill the process. (THough of course, if killing the process is what you want, fuser
can do that with its -k
option. You can have fuser
use other signals with the -s
option -- check the man page for details.)
For example, with a tail -F /etc/passwd
running in one window:
ghoti@pc:~$ lsof | grep passwd
tail 12470 ghoti 3r REG 251,0 2037 51515911 /etc/passwd
Note that you can also use lsof
to find out what processes are using particular sockets. An excellent tool to have in your arsenal.
void reverse(char *s)
{
char *end,temp;
end = s;
while(*end != '\0'){
end++;
}
end--; //end points to last letter now
for(;s<end;s++,end--){
temp = *end;
*end = *s;
*s = temp;
}
}
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar
ojdbc14.jar(it's jar file)
I had the same problem
I resolved it that used below command
$ git branch --set-upstream develop origin/develop
and it will add a config in the config file in the .git folder.
#include <iostream>
#include <iomanip>
#include <sstream>
int main()
{
int x, y;
std::stringstream stream;
std::cin >> x;
stream << x;
stream >> std::hex >> y;
std::cout << y;
return 0;
}
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
Add the following to your ~/.gitconfig
file
[alias]
cat = "!git show \"$1:$2\" #"
And then try this
git cat BRANCHNAME FILEPATH
Personally I prefer separate parameters without a colon. Why? This choice mirrors the parameters of the checkout
command, which I tend to use rather frequently and I find it thus much easier to remember than the bizarro colon-separated parameter of the show
command.
For easy to use asynchronous convert all callback to promise use some library like "bluebird" .
.then(function(results) {
fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
if (err) {
console.log(err);
} else {
console.log("JSON saved");
return results;
}
})
}).catch(function(err) {
console.log(err);
});
Try solution with promise (bluebird)
var amazon = require('amazon-product-api');
var fs = require('fs');
var Promise = require('bluebird');
var client = amazon.createClient({
awsId: "XXX",
awsSecret: "XXX",
awsTag: "888"
});
var array = fs.readFileSync('./test.txt').toString().split('\n');
Promise.map(array, function (ASIN) {
client.itemLookup({
domain: 'webservices.amazon.de',
responseGroup: 'Large',
idType: 'ASIN',
itemId: ASIN
}).then(function(results) {
fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
if (err) {
console.log(err);
} else {
console.log("JSON saved");
return results;
}
})
}).catch(function(err) {
console.log(err);
});
});
Surprised no one has posted the type-safe C++ version yet:
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
Benefits:
copysign
is slow, especially if you need to promote and then narrow again. This is branchless and optimizes excellentlyCaveats:
The < 0
part of the check triggers GCC's -Wtype-limits
warning when instantiated for an unsigned type. You can avoid this by using some overloads:
template <typename T> inline constexpr
int signum(T x, std::false_type is_signed) {
return T(0) < x;
}
template <typename T> inline constexpr
int signum(T x, std::true_type is_signed) {
return (T(0) < x) - (x < T(0));
}
template <typename T> inline constexpr
int signum(T x) {
return signum(x, std::is_signed<T>());
}
(Which is a good example of the first caveat.)
Same happened to me, I had to go into Packages and re-enable Tabs and Tree-View (both part of core).
The commands are adduser
and addgroup
.
Here's a template for Docker you can use in busybox environments (alpine) as well as Debian-based environments (Ubuntu, etc.):
ENV USER=docker
ENV UID=12345
ENV GID=23456
RUN adduser \
--disabled-password \
--gecos "" \
--home "$(pwd)" \
--ingroup "$USER" \
--no-create-home \
--uid "$UID" \
"$USER"
Note the following:
--disabled-password
prevents prompt for a password--gecos ""
circumvents the prompt for "Full Name" etc. on Debian-based systems--home "$(pwd)"
sets the user's home to the WORKDIR. You may not want this.--no-create-home
prevents cruft getting copied into the directory from /etc/skel
The usage description for these applications is missing the long flags present in the code for adduser and addgroup.
The following long-form flags should work both in alpine as well as debian-derivatives:
BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.
Usage: adduser [OPTIONS] USER [GROUP]
Create new user, or add USER to GROUP
--home DIR Home directory
--gecos GECOS GECOS field
--shell SHELL Login shell
--ingroup GRP Group (by name)
--system Create a system user
--disabled-password Don't assign a password
--no-create-home Don't create home directory
--uid UID User id
One thing to note is that if --ingroup
isn't set then the GID is assigned to match the UID. If the GID corresponding to the provided UID already exists adduser will fail.
BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.
Usage: addgroup [-g GID] [-S] [USER] GROUP
Add a group or add a user to a group
--gid GID Group id
--system Create a system group
I discovered all of this while trying to write my own alternative to the fixuid project for running containers as the hosts UID/GID.
My entrypoint helper script can be found on GitHub.
The intent is to prepend that script as the first argument to ENTRYPOINT
which should cause Docker to infer UID and GID from a relevant bind mount.
An environment variable "TEMPLATE" may be required to determine where the permissions should be inferred from.
(At the time of writing I don't have documentation for my script. It's still on the todo list!!)
You could also try this simpler regex:
str = str.replaceAll("\\P{Alnum}", "");