Here you go:
^[^<>]*$
This will test for string that has no <
and no >
If you want to test for a string that may have <
and >
, but must also have something other you should use just
[^<>] (or ^.*[^<>].*$)
Where [<>]
means any of <
or >
and [^<>]
means any that is not of <
or >
.
And of course the mandatory link.
pkill NAMEofAPP
Non rooted marshmallow, termux & terminal emulator.
if you want to populate contents of your partial view inside your view you can use
@Html.Partial("PartialViewName")
or
{@Html.RenderPartial("PartialViewName");}
if you want to make server request and process the data and then return partial view to you main view filled with that data you can use
...
@Html.Action("Load", "Home")
...
public PartialViewResult Load()
{
return PartialView("_LoadView");
}
if you want user to click on the link and then populate the data of partial view you can use:
@Ajax.ActionLink(
"Click Here to Load the Partial View",
"ActionName",
"ControlerName",
null,
new AjaxOptions { UpdateTargetId = "toUpdate" }
)
At my work we have our restful services on a different port number and the data resides in db2 on a pair of AS400s. We typically use the $.getJSON
AJAX method because it easily returns JSONP using the ?callback=?
without having any issues with CORS.
data ='USER=<?echo trim($USER)?>' +
'&QRYTYPE=' + $("input[name=QRYTYPE]:checked").val();
//Call the REST program/method returns: JSONP
$.getJSON( "http://www.stackoverflow.com/rest/resttest?callback=?",data)
.done(function( json ) {
// loading...
if ($.trim(json.ERROR) != '') {
$("#error-msg").text(message).show();
}
else{
$(".error").hide();
$("#jsonp").text(json.whatever);
}
})
.fail(function( jqXHR, textStatus, error ) {
var err = textStatus + ", " + error;
alert('Unable to Connect to Server.\n Try again Later.\n Request Failed: ' + err);
});
Changing the web.config generally causes an application restart.
If you really need your application to edit its own settings, then you should consider a different approach such as databasing the settings or creating an xml file with the editable settings.
I might have read all questions about this for two days. None of the answers worked for me.
In my case I was lacking cURL module for PHP.
Be aware that, just because you can use cURL on terminal, it does not mean that you have PHP cURL module and it is active.
There was no error showing about it. Not even on /var/log/apache2/error.log
How to install module: (replace version number for the apropiated one)
sudo apt install php7.2-curl
sudo service apache2 reload
Using awk only
foo="uNcapItalizedstrIng"
echo $foo | awk '{print toupper(substr($0,0,1))tolower(substr($0,2))}'
if you're using C++ another option is to use template metaprogramming:
// recursive template to sum bits in an int
template <int BITS>
int countBits(int val) {
// return the least significant bit plus the result of calling ourselves with
// .. the shifted value
return (val & 0x1) + countBits<BITS-1>(val >> 1);
}
// template specialisation to terminate the recursion when there's only one bit left
template<>
int countBits<1>(int val) {
return val & 0x1;
}
usage would be:
// to count bits in a byte/char (this returns 8)
countBits<8>( 255 )
// another byte (this returns 7)
countBits<8>( 254 )
// counting bits in a word/short (this returns 1)
countBits<16>( 256 )
you could of course further expand this template to use different types (even auto-detecting bit size) but I've kept it simple for clarity.
edit: forgot to mention this is good because it should work in any C++ compiler and it basically just unrolls your loop for you if a constant value is used for the bit count (in other words, I'm pretty sure it's the fastest general method you'll find)
I use a wrapper around a Dictionary<T, object>
, storing nulls in the values. This gives O(1) add, lookup and remove on the keys, and to all intents and purposes acts like a set.
Date.prototype.toUTCArray= function(){
var D= this;
return [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(),
D.getUTCMinutes(), D.getUTCSeconds()];
}
Date.prototype.toISO= function(){
var tem, A= this.toUTCArray(), i= 0;
A[1]+= 1;
while(i++<7){
tem= A[i];
if(tem<10) A[i]= '0'+tem;
}
return A.splice(0, 3).join('-')+'T'+A.join(':');
}
You need to open the file in binary mode i.e. wb
instead of w
. If you don't, the end of line characters are auto-converted to OS specific ones.
Here is an excerpt from Python reference about open()
.
The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.
None of the install/rebuild solutions resolved the issue for me (using gulp).
Here is how I resolved it:
1) Download the missing binding file from the repository.
2) Rename the file binding.node
.
3) Create node_modules/node-sass/vendor/darwin-x64-11
(path from error message) directory if it doesn't exist.
4) Add the binding file to node_modules/node-sass/vendor/darwin-x64-11
Here is an article with live working demo Class Animation In JQuery
You can try this,
$(function () {
$("#btnSubmit").click(function () {
$("#btnClass").removeClass("btnDiv").addClass("btn");
});
});
you can also use switchClass() method - it allows you to animate the transition of adding and removing classes at the same time.
$(function () {
$("#btnSubmit").click(function () {
$("#btnClass").switchClass("btn", "btnReset", 1000, "easeInOutQuad");
});
});
This didn't answer the same issue for me under Mac OS X Lion. I ended up adding:
ssh-add ~/.ssh/id_rsa &>/dev/null
To my .zshrc (but .profile would be fine too), which seems to have fixed it.
(As suggested here: http://geek.michaelgrace.org/2011/09/permanently-add-ssh-key-ssh-add/ )
We can insert the string in a stack and when we extract the words, they will be in reverse order.
void ReverseWords(char Arr[])
{
std::stack<std::string> s;
char *str;
int length = strlen(Arr);
str = new char[length+1];
std::string ReversedArr;
str = strtok(Arr," ");
while(str!= NULL)
{
s.push(str);
str = strtok(NULL," ");
}
while(!s.empty())
{
ReversedArr = s.top();
cout << " " << ReversedArr;
s.pop();
}
}
if (!('foo' in obj)) {
// not set.
}
It does not work because your script in JSFiddle is running inside it's own scope (see the "OnLoad" drop down on the left?).
One way around this is to bind your event handler in javascript (where it should be):
document.getElementById('optionID').onchange = function () {
document.getElementById("message").innerHTML = "Having a Baby!!";
};
Another way is to modify your code for the fiddle environment and explicitly declare your function as global so it can be found by your inline event handler:
window.changeMessage() {
document.getElementById("message").innerHTML = "Having a Baby!!";
};
?
Effective January 15, 2020, The Central Repository no longer supports insecure communication over plain HTTP and requires that all requests to the repository are encrypted over HTTPS.
If you're receiving this error, then you need to replace all URL references to Maven Central with their canonical HTTPS counterparts.
(source)
We have made the following changes in my project's build.gradle:
Old:
repositories {
maven { url "http://repo.maven.apache.org/maven2" }
}
New:
repositories {
maven { url "https://repo.maven.apache.org/maven2" }
}
For my own future reference:
With cx_Oracle use cursor.setinputsize(...):
mycursor = connection.cursor();
mycursor.setinputsize( mytimestamp=cx_Oracle.TIMESTAMP );
params = { 'mytimestamp': timestampVar };
cusrsor.execute("INSERT INTO mytable (timestamp_field9 VALUES(:mytimestamp)", params);
No converting in the db needed. See Oracle Documentation
I was getting this error while posting a FormData object because I was not setting up the ajax call correctly. Setup below fixed my issue.
var myformData = new FormData();
myformData.append('leadid', $("#leadid").val());
myformData.append('date', $(this).val());
myformData.append('time', $(e.target).prev().val());
$.ajax({
method: 'post',
processData: false,
contentType: false,
cache: false,
data: myformData,
enctype: 'multipart/form-data',
url: 'include/ajax.php',
success: function (response) {
$("#subform").html(response).delay(4000).hide(1);
}
});
Check out this code. It works in every major browser.
remove_item = function(arr, value) {
var b = '';
for (b in arr) {
if (arr[b] === value) {
arr.splice(b, 1);
break;
}
}
return arr;
};
var array = [1,3,5,6,5,9,5,3,55]
var res = remove_item(array,5);
console.log(res)
_x000D_
Open $CATALINA_BASE/conf/web.xml
and find this
<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.
This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different
I have been struggling to find a proper way to create a timeline, which I could finally do with this modification. Usually while creating a timeline the problem was that I could not add a text to explain each date clearly with a longer text. I modified and further utilized @Zoe Gagnon's latex script. Please feel free to see the following:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{snakes}
\usepackage{rotating}
\begin{document}
\begin{center}
\begin{tikzpicture}
% draw horizontal line
\draw (-5,0) -- (6,0);
% draw vertical lines
\foreach \x in {-5,-4,-3,-2, -1,0,1,2}
\draw (\x cm,3pt) -- (\x cm,-3pt);
% draw nodes
\draw (-5,0) node[below=3pt] {$ 0 $} node[above=3pt] {$ $};
\draw (-4,0) node[below=3pt] {$ 1 $} node[above=3pt] {$\begin{turn}{45}
All individuals vote
\end{turn}$};
\draw (-3,0) node[below=3pt] {$ 2 $} node[above=3pt] {$\begin{turn}{45}
Policy vector decided
\end{turn}$};
\draw (-2,0) node[below=3pt] {$ 3 $} node[above=3pt] {$\begin{turn}{45} Becoming a bureaucrat \end{turn} $};
\draw (-1,0) node[below=3pt] {$ 4 $} node[above=3pt] {$\begin{turn}{45} Bureaucrats' effort choice \end{turn}$};
\draw (0,0) node[below=3pt] {$ 5 $} node[above=3pt] {$\begin{turn}{45} Tax evasion decision made \end{turn}$};
\draw (1,0) node[below=3pt] {$ 6$} node[above=3pt] {$\begin{turn}{45} $p(x_{t})$ tax evaders caught \end{turn}$};
\draw (2,0) node[below=3pt] {$ 7 $} node[above=3pt] {$\begin{turn}{45} $q_{t}$ shirking bureaucrats \end{turn}$};
\draw (3,0) node[below=3pt] {$ $} node[above=3pt] {$\begin{turn}{45} Public service provided \end{turn} $};
\end{tikzpicture}
\end{center}
\end{document}
Longer texts are not allowed, unfortunately. It will look like this:
Don't write your own util class to do this - I would recommend using Guava, which is full of all kinds of goodness. In this case you'd want either the Files
class (if you're really just reading a file) or CharStreams for more general purpose reading. It has methods to read the data into a list of strings (readLines
) or totally (toString
).
It has similar useful methods for binary data too. And then there's the rest of the library...
I agree it's annoying that there's nothing similar in the standard libraries. Heck, just being able to supply a CharSet
to a FileReader
would make life a little simpler...
Setting your provisioning profile moved. It confounded me for a while until I found it also.
DateTime.Now.Date.ToShortDateString()
I think this is what you are looking for
I got this same error in a conda environment, only six+ years later. The other responses were helpful, and eventually I tracked it down to this problem:
> conda list numpy
# packages in environment at [Anaconda3]:
#
# Name Version Build Channel
numpy 1.14.5 pypi_0 pypi
numpy-base 1.18.1 py36hc3f5095_1
numpydoc 0.9.1 pypi_0 pypi
The problem was that 'numpy' was a different version than 'numpy-base'. I solved this with:
> conda install numpy-base=1.14.5
so the two of them matched each other.
ENOSPC
means that there is no space on the drive.
Perhaps /tmp
is full? You can configure npm
to use a different temp folder by setting npm config set tmp /path/to/some/other/dir
, or maybe delete everything out of the /tmp
folder.
Source: npm 1.1.21 cannot write, ENOSPC in npm's repo in github.
Note I solved my problem in the way that described in above source. However, see Murali Krishna's answer, which is more comprehensive.
You can also try this: Go to the path where Python is installed in your system. For me it was something like C:\Users\\Local Settings\Application Data\Programs\Python\Python37 In this folder, you'll find a python executable. Just create a duplicate and rename it to python3. Works every time.
<input type="text" id="text" name="search">
<table id="table_data">
<tr class="listR"><td>PHP</td></tr>
<tr class="listR"><td>MySql</td></tr>
<tr class="listR"><td>AJAX</td></tr>
<tr class="listR"><td>jQuery</td></tr>
<tr class="listR"><td>JavaScript</td></tr>
<tr class="listR"><td>HTML</td></tr>
<tr class="listR"><td>CSS</td></tr>
<tr class="listR"><td>CSS3</td></tr>
</table>
$("#textbox").on('keyup',function(){
var f = $(this).val();
$("#table_data tr.listR").each(function(){
if ($(this).text().search(new RegExp(f, "i")) < 0) {
$(this).fadeOut();
} else {
$(this).show();
}
});
});
Demo You can perform by search() method with use RegExp matching text
function getBackgroundColor($dom) {
var bgColor = "";
while ($dom[0].tagName.toLowerCase() != "html") {
bgColor = $dom.css("background-color");
if (bgColor != "rgba(0, 0, 0, 0)" && bgColor != "transparent") {
break;
}
$dom = $dom.parent();
}
return bgColor;
}
working properly under Chrome and Firefox
When you test with device you want to add your PC ip address.
in pc run in cmd Ipconfig
in ubuntu run terminal ifconfig
Then use "http://your_pc_ip_address:8080/register"
insted of using "http://10.0.2.2:8080/register"
in my pc = 192.168.1.3
and also add internet permission to Manifest
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
thing_index = thing_list.index(elem) if elem in thing_list else -1
One line. Simple. No exceptions.
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
After using following load balancer setting my problem solved for wss but for ws problem still exists for specific one ISP.
Try this:
.countTable table tr td:first-child + td
You could also reiterate in order to style the others columns:
.countTable table tr td:first-child + td + td {...} /* third column */
.countTable table tr td:first-child + td + td + td {...} /* fourth column */
.countTable table tr td:first-child + td + td + td +td {...} /* fifth column */
improving the post of @Peter T, by gathering all solutions together at one place.
function myFunction() {
window.document.body.insertAdjacentHTML( 'afterbegin', '<div id="myID" style="color:blue;"> With some data...</div>' );
}
function addElement(){
var elemDiv = document.createElement('div');
elemDiv.style.cssText = 'width:100%;height:10%;background:rgb(192,192,192);';
elemDiv.innerHTML = 'Added element with some data';
window.document.body.insertBefore(elemDiv, window.document.body.firstChild);
// document.body.appendChild(elemDiv); // appends last of that element
}
function addCSS() {
window.document.getElementsByTagName("style")[0].innerHTML += ".mycss {text-align:center}";
}
Using XPath
find the position of the Element in the DOM Tree and insert the specified text at a specified position to an XPath_Element. try this code over browser console.
function insertHTML_ByXPath( xpath, position, newElement) {
var element = document.evaluate(xpath, window.document, null, 9, null ).singleNodeValue;
element.insertAdjacentHTML(position, newElement);
element.style='border:3px solid orange';
}
var xpath_DOMElement = '//*[@id="answer-33669996"]/table/tbody/tr[1]/td[2]/div';
var childHTML = '<div id="Yash">Hi My name is <B>\"YASHWANTH\"</B></div>';
var position = 'beforeend';
insertHTML_ByXPath(xpath_DOMElement, position, childHTML);
The following code is Linux (maybe Unix) only, but it works in a real project.
private double getAverageValueByLinux() throws InterruptedException {
try {
long delay = 50;
List<Double> listValues = new ArrayList<Double>();
for (int i = 0; i < 100; i++) {
long cput1 = getCpuT();
Thread.sleep(delay);
long cput2 = getCpuT();
double cpuproc = (1000d * (cput2 - cput1)) / (double) delay;
listValues.add(cpuproc);
}
listValues.remove(0);
listValues.remove(listValues.size() - 1);
double sum = 0.0;
for (Double double1 : listValues) {
sum += double1;
}
return sum / listValues.size();
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
private long getCpuT throws FileNotFoundException, IOException {
BufferedReader reader = new BufferedReader(new FileReader("/proc/stat"));
String line = reader.readLine();
Pattern pattern = Pattern.compile("\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)")
Matcher m = pattern.matcher(line);
long cpuUser = 0;
long cpuSystem = 0;
if (m.find()) {
cpuUser = Long.parseLong(m.group(1));
cpuSystem = Long.parseLong(m.group(3));
}
return cpuUser + cpuSystem;
}
I tried all the answers and nothing really worked for me.
So I've created my own method that compares simple java objects without going deep into nested structures...
Method returns null if all fields match or string containing mismatch details.
Only properties that have a getter method are compared.
How to use
assertNull(TestUtils.diff(obj1,obj2,ignore_field1, ignore_field2));
Sample output if there is a mismatch
Output shows property names and respective values of compared objects
alert_id(1:2), city(Moscow:London)
Code (Java 8 and above):
public static String diff(Object x1, Object x2, String ... ignored) throws Exception{
final StringBuilder response = new StringBuilder();
for (Method m:Arrays.stream(x1.getClass().getMethods()).filter(m->m.getName().startsWith("get")
&& m.getParameterCount()==0).collect(toList())){
final String field = m.getName().substring(3).toLowerCase();
if (Arrays.stream(ignored).map(x->x.toLowerCase()).noneMatch(ignoredField->ignoredField.equals(field))){
Object v1 = m.invoke(x1);
Object v2 = m.invoke(x2);
if ( (v1!=null && !v1.equals(v2)) || (v2!=null && !v2.equals(v1))){
response.append(field).append("(").append(v1).append(":").append(v2).append(")").append(", ");
}
}
}
return response.length()==0?null:response.substring(0,response.length()-2);
}
Here is a nice little function that worked for me.
function getDisplayDatetime() {
var d = new Date(); var hh = d.getHours(); var mm = d.getMinutes(); var dd = "AM"; var h = hh;
if (mm.toString().length == 1) {
mm = "0" + mm;
}
if (h >= 12) {
h = hh - 12;
dd = "PM";
}
if (h == 0) {
h = 12;
}
var Datetime = "Datetime: " + d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getUTCDate() + " " + h + ":" + mm;
return Datetime + " " + dd;
}
First set "Grouped" on storyboard: it has to happen at init time, you can't really set it later, so it's easier to remember to do it on storyboard:
Next,
func tableView(_ tableView: UITableView,
heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat(70.0)
}
There is still an Apple bug - for ten years now - where it simply won't show the first header (i.e., index 0) if you don't have heightForHeaderInSection
call.
So, tableView.sectionHeaderHeight = 70
simply doesn't work, it's broken.
In viewForHeaderInSection
simply create a UIView().
It is pointless / achieves nothing if you UIView(frame ...) since iOS simply sets the size of the view as determined by the table.
So the first line of viewForHeaderInSection
will be simply let view = UIView()
and that is the view you return.
func tableView(_ tableView: UITableView,
viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
let l = UILabel()
view.addSubview(l)
l.bindEdgesToSuperview()
l.backgroundColor = .systemOrange
l.font = UIFont.systemFont(ofSize: 15)
l.textColor = .yourClientsFavoriteColor
switch section {
case 0:
l.text = "First section on screen"
case 1:
l.text = "Here's the second section"
default:
l.text = ""
}
return view
}
That's it - anything else is a time waste.
Another "fussy" Apple issue.
The convenience extension used above is:
extension UIView {
// incredibly useful:
func bindEdgesToSuperview() {
guard let s = superview else {
preconditionFailure("`superview` nil in bindEdgesToSuperview")
}
translatesAutoresizingMaskIntoConstraints = false
leadingAnchor.constraint(equalTo: s.leadingAnchor).isActive = true
trailingAnchor.constraint(equalTo: s.trailingAnchor).isActive = true
topAnchor.constraint(equalTo: s.topAnchor).isActive = true
bottomAnchor.constraint(equalTo: s.bottomAnchor).isActive = true
}
}
TL;DR
.col-X-Y
means on screen size X and up, stretch this element to fill Y columns.
Bootstrap provides a grid of 12 columns per .row
, so Y=3 means width=25%.
xs, sm, md, lg
are the sizes for smartphone, tablet, laptop, desktop respectively.
The point of specifying different widths on different screen sizes is to let you make things larger on smaller screens.
Example
<div class="col-lg-6 col-xs-12">
Meaning: 50% width on Desktops, 100% width on Mobile, Tablet, and Laptop.
I have another solution that works great.
On one hand, Ortwin's approach & solution works only with iOS 6.0 and later, but fails to work correctly on iOS 5.0, 5.1 and 5.1.1, and on the other hand there is something that I don't like and can't understand with Ortwin's approach, it's the use of the method [webView sizeThatFits:CGSizeZero]
with the parameter CGSizeZero
: If you read Apple Official documentation about this methods and its parameter, it says clearly :
The default implementation of this method returns the size portion of the view’s bounds rectangle. Subclasses can override this method to return a custom value based on the desired layout of any subviews. For example, a UISwitch object returns a fixed size value that represents the standard size of a switch view, and a UIImageView object returns the size of the image it is currently displaying.
What I mean is that it's like he came across his solution without any logic, because reading the documentation, the parameter passed to [webView sizeThatFits: ...]
should at least have the desired width
. With his solution, the desired width is set to the webView
's frame before calling sizeThatFits
with a CGSizeZero
parameter. So I maintain this solution is working on iOS 6 by "chance".
I imagined a more rational approach, which has the advantage of working for iOS 5.0 and later... And also in complex situations where more than one webView (With its property webView.scrollView.scrollEnabled = NO
is embedded in a scrollView
.
Here is my code to force the Layout of the webView
to the desired width
and get the corresponding height
set back to the webView
itself:
Obj-C
- (void)webViewDidFinishLoad:(UIWebView *)aWebView
{
aWebView.scrollView.scrollEnabled = NO; // Property available in iOS 5.0 and later
CGRect frame = aWebView.frame;
frame.size.width = 200; // Your desired width here.
frame.size.height = 1; // Set the height to a small one.
aWebView.frame = frame; // Set webView's Frame, forcing the Layout of its embedded scrollView with current Frame's constraints (Width set above).
frame.size.height = aWebView.scrollView.contentSize.height; // Get the corresponding height from the webView's embedded scrollView.
aWebView.frame = frame; // Set the scrollView contentHeight back to the frame itself.
}
Swift 4.x
func webViewDidFinishLoad(_ aWebView: UIWebView) {
aWebView.scrollView.isScrollEnabled = false
var frame = aWebView.frame
frame.size.width = 200
frame.size.height = 1
aWebView.frame = frame
frame.size.height = aWebView.scrollView.contentSize.height
aWebView.frame = frame;
}
Note that in my example, the webView
was embedded in a custom scrollView
having other webViews
... All these webViews
had their webView.scrollView.scrollEnabled = NO
, and the last piece of code I had to add was the calculation of the height
of the contentSize
of my custom scrollView
embedding these webViews
, but it was as easy as summing my webView
's frame.size.height
computed with the trick described above...
You can just use a simple loop: -
>>> mylist = ['10', '12', '14']
>>> for elem in mylist:
print elem
10
12
14
I hope this helps:
var token = document.getElementById('token').value;
var nombre = document.getElementById('txtNombre').value;
$("#txtNombre").keyup(function () {
$.ajax({
type: "POST",
url: host() + "Formulario/BuscarNombreAutocompletar/",
data: JSON.stringify({ "nombre": nombre }),
headers: {
'Authorization': 'Bearer ' + token
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var dataArray = [];
if (controlCarga(data)) {
$.each(data[1], function (i, item) {
dataArray.push(item.frmNombre)
});
$('#txtNombre').autocomplete({
clearButton: true,
source: dataArray,
selectFirst: true,
minLength: 2
});
}
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error: ' + xhr.responseText);
}
});
});
The easiest way is through css3 $("select option:selected")
and then use the .text()
or .html()
function. depending on what you want to have.
In case someone need to handle a dynamic object come from Json, I has modified Seth Reno answer to handle dynamic object deserialized from NewtonSoft.Json.JObjcet.
public static bool PropertyExists(dynamic obj, string name)
{
if (obj == null) return false;
if (obj is ExpandoObject)
return ((IDictionary<string, object>)obj).ContainsKey(name);
if (obj is IDictionary<string, object> dict1)
return dict1.ContainsKey(name);
if (obj is IDictionary<string, JToken> dict2)
return dict2.ContainsKey(name);
return obj.GetType().GetProperty(name) != null;
}
How about this one:
select
from_unixtime(unix_timestamp(timestamp) - unix_timestamp(timestamp) mod 300) as ts,
sum(value)
from group_interval
group by ts
order by ts
;
Try HostingEnvironment.MapPath
, which is static
.
See this SO question for confirmation that HostingEnvironment.MapPath
returns the same value as Server.MapPath
: What is the difference between Server.MapPath and HostingEnvironment.MapPath?
You can use the Series.to_list
method.
For example:
import pandas as pd
df = pd.DataFrame({'a': [1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9],
'b': [3, 5, 6, 2, 4, 6, 7, 8, 7, 8, 9]})
print(df['a'].to_list())
Output:
[1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9]
To drop duplicates you can do one of the following:
>>> df['a'].drop_duplicates().to_list()
[1, 3, 5, 7, 4, 6, 8, 9]
>>> list(set(df['a'])) # as pointed out by EdChum
[1, 3, 4, 5, 6, 7, 8, 9]
Here is a one line lambda that also works:
df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)
Input:
searchfor = ['og', 'at']
df = pd.DataFrame([('cat', 1000.0), ('hat', 2000000.0), ('dog', 1000.0), ('fog', 330000.0),('pet', 330000.0)], columns=['col1', 'col2'])
col1 col2
0 cat 1000.0
1 hat 2000000.0
2 dog 1000.0
3 fog 330000.0
4 pet 330000.0
Apply Lambda:
df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)
Output:
col1 col2 TrueFalse
0 cat 1000.0 1
1 hat 2000000.0 1
2 dog 1000.0 1
3 fog 330000.0 1
4 pet 330000.0 0
When used in an <image>
tag SVG must be contained in a single file for privacy reasons. This bugzilla bug has more details on exactly why this is so. Unfortunately you can't use a different tag such as an <iframe>
because that won't work as a link so you'll have to embed the CSS in a <style>
tag within the file itself.
One other way to do this would be to have the SVG data within the main html file i.e.
<a href='http://youtube.com/...' target='_blank'>
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 56.69 56.69">
<g>
<path d="M28.44......./>
</g>
</svg>
</a>
You could style that with an external CSS file using the HTML <link>
tag.
Yes. Try:
class USBDevice : GenericDevice, IOurDevice
Note: The base class should come before the list of interface names.
Of course, you'll still need to implement all the members that the interfaces define. However, if the base class contains a member that matches an interface member, the base class member can work as the implementation of the interface member and you are not required to manually implement it again.
Declaration in config/app.php under aliases:-
'Input' => Illuminate\Support\Facades\Input::class,
Or You can import Input facade directly as required,
use Illuminate\Support\Facades\Input;
or
use Illuminate\Support\Facades\Input as input;
Compare two string using equals(-,-) and equalsIgnoreCase(-,-) method of Apache Commons StringUtils class.
StringUtils.equals(-, -) :
StringUtils.equals(null, null) = true
StringUtils.equals(null, "abc") = false
StringUtils.equals("abc", null) = false
StringUtils.equals("abc", "abc") = true
StringUtils.equals("abc", "ABC") = false
StringUtils.equalsIgnoreCase(-, -) :
StringUtils.equalsIgnoreCase(null, null) = true
StringUtils.equalsIgnoreCase(null, "abc") = false
StringUtils.equalsIgnoreCase("xyz", null) = false
StringUtils.equalsIgnoreCase("xyz", "xyz") = true
StringUtils.equalsIgnoreCase("xyz", "XYZ") = true
INSERT INTO mt_magazine_subscription (
magazine_subscription_id,
subscription_name,
magazine_id,
status )
VALUES (
(SELECT magazine_subscription_id,
subscription_name,
magazine_id,'1' as status
FROM tbl_magazine_subscription
ORDER BY magazine_subscription_id ASC));
Added: I found something that should do the trick right away, but the rest of the code below also offers an alternative.
Use the subplots_adjust()
function to move the bottom of the subplot up:
fig.subplots_adjust(bottom=0.2) # <-- Change the 0.02 to work for your plot.
Then play with the offset in the legend bbox_to_anchor
part of the legend command, to get the legend box where you want it. Some combination of setting the figsize
and using the subplots_adjust(bottom=...)
should produce a quality plot for you.
Alternative: I simply changed the line:
fig = plt.figure(1)
to:
fig = plt.figure(num=1, figsize=(13, 13), dpi=80, facecolor='w', edgecolor='k')
and changed
lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0))
to
lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,-0.02))
and it shows up fine on my screen (a 24-inch CRT monitor).
Here figsize=(M,N)
sets the figure window to be M inches by N inches. Just play with this until it looks right for you. Convert it to a more scalable image format and use GIMP to edit if necessary, or just crop with the LaTeX viewport
option when including graphics.
NOTE: see Cheetah's answer below as it identifies a prerequisite to get this solution to work. Setting the BackColor
of the TextBox
.
I think what you really want to do is enable the TextBox
and set the ReadOnly
property to true
.
It's a bit tricky to change the color of the text in a disabled TextBox
. I think you'd probably have to subclass and override the OnPaint
event.
ReadOnly
though should give you the same result as !Enabled
and allow you to maintain control of the color and formatting of the TextBox
. I think it will also still support selecting and copying text from the TextBox
which is not possible with a disabled TextBox
.
Another simple alternative is to use a Label
instead of a TextBox
.
Rails provides a solution to this: shallow nesting.
I think this is a good because when you deal directly with a known resource, there's no need to use nested routes, as has been discussed in other answers here.
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
// ...
Path filePath = new File("fileName").toPath();
Charset charset = Charset.defaultCharset();
List<String> stringList = Files.readAllLines(filePath, charset);
String[] stringArray = stringList.toArray(new String[]{});
I solved this with Access options.
Go to the Office Button --> Access Options --> Trust Center --> Trust Center Settings Button --> Message Bar
In the right hand pane I selected the radio button "Show the message bar in all applications when content has been blocked."
Closed Access, reopened the database and got the warning for blocked content again.
One possibility that the above answers don't address is that you may not have an ssh access from your shell. That is, you may be in a network (some college networks do this) where ssh service is blocked.In that case you will not only be able to get github services but also any other ssh services. You can test if this is the problem by trying to use any other ssh service.This was the case with me.
To add timezone
information in Python 3.2+
import datetime
>>> d = datetime.datetime.now(tz=datetime.timezone.utc)
>>> print(d.tzinfo)
'UTC+00:00'
I think the only way of doing this in SQL-Server 2008R2 is to use a correlated subquery, or an outer apply:
SELECT datekey,
COALESCE(RunningTotal, 0) AS RunningTotal,
COALESCE(RunningCount, 0) AS RunningCount,
COALESCE(RunningDistinctCount, 0) AS RunningDistinctCount
FROM document
OUTER APPLY
( SELECT SUM(Amount) AS RunningTotal,
COUNT(1) AS RunningCount,
COUNT(DISTINCT d2.dateKey) AS RunningDistinctCount
FROM Document d2
WHERE d2.DateKey <= document.DateKey
) rt;
This can be done in SQL-Server 2012 using the syntax you have suggested:
SELECT datekey,
SUM(Amount) OVER(ORDER BY DateKey) AS RunningTotal
FROM document
However, use of DISTINCT
is still not allowed, so if DISTINCT is required and/or if upgrading isn't an option then I think OUTER APPLY
is your best option
You can extend multiple Interfaces
but you cannot extend multiple classes
.
The reason that it is not possible in Java to extending multiple classes, is the bad experience from C++ where this is possible.
The alternative for multipe inheritance is that a class can implement multiple interfaces (or an Interface can extend multiple Interfaces)
Quite simple, with a *
wildcard.
cp -r Folder1/* Folder2/
But according to your example recursion is not needed so the following will suffice:
cp Folder1/* Folder2/
EDIT:
Or skip the mkdir Folder2
part and just run:
cp -r Folder1 Folder2
Reference Decoder of CRL,CRT,CSR,NEW CSR,PRIVATE KEY, PUBLIC KEY,RSA,RSA Public Key Parser
RSA Public Key
-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----
Encrypted Private Key
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
-----END RSA PRIVATE KEY-----
CRL
-----BEGIN X509 CRL-----
-----END X509 CRL-----
CRT
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
CSR
-----BEGIN CERTIFICATE REQUEST-----
-----END CERTIFICATE REQUEST-----
NEW CSR
-----BEGIN NEW CERTIFICATE REQUEST-----
-----END NEW CERTIFICATE REQUEST-----
PEM
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
PKCS7
-----BEGIN PKCS7-----
-----END PKCS7-----
PRIVATE KEY
-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----
DSA KEY
-----BEGIN DSA PRIVATE KEY-----
-----END DSA PRIVATE KEY-----
Elliptic Curve
-----BEGIN EC PRIVATE KEY-----
-----END EC PRIVATE KEY-----
PGP Private Key
-----BEGIN PGP PRIVATE KEY BLOCK-----
-----END PGP PRIVATE KEY BLOCK-----
PGP Public Key
-----BEGIN PGP PUBLIC KEY BLOCK-----
-----END PGP PUBLIC KEY BLOCK-----
This is an interesting question and since it isn't explained very explicitly in the documentation I'll answer this by going through the sourcecode of mod_rewrite; demonstrating a big benefit of open-source.
In the top section you'll quickly spot the defines used to name these flags:
#define CONDFLAG_NONE 1<<0
#define CONDFLAG_NOCASE 1<<1
#define CONDFLAG_NOTMATCH 1<<2
#define CONDFLAG_ORNEXT 1<<3
#define CONDFLAG_NOVARY 1<<4
and searching for CONDFLAG_ORNEXT confirms that it is used based on the existence of the [OR] flag:
else if ( strcasecmp(key, "ornext") == 0
|| strcasecmp(key, "OR") == 0 ) {
cfg->flags |= CONDFLAG_ORNEXT;
}
The next occurrence of the flag is the actual implementation where you'll find the loop that goes through all the RewriteConditions a RewriteRule has, and what it basically does is (stripped, comments added for clarity):
# loop through all Conditions that precede this Rule
for (i = 0; i < rewriteconds->nelts; ++i) {
rewritecond_entry *c = &conds[i];
# execute the current Condition, see if it matches
rc = apply_rewrite_cond(c, ctx);
# does this Condition have an 'OR' flag?
if (c->flags & CONDFLAG_ORNEXT) {
if (!rc) {
/* One condition is false, but another can be still true. */
continue;
}
else {
/* skip the rest of the chained OR conditions */
while ( i < rewriteconds->nelts
&& c->flags & CONDFLAG_ORNEXT) {
c = &conds[++i];
}
}
}
else if (!rc) {
return 0;
}
}
You should be able to interpret this; it means that OR has a higher precedence, and your example indeed leads to if ( (A OR B) AND (C OR D) )
. If you would, for example, have these Conditions:
RewriteCond A [or]
RewriteCond B [or]
RewriteCond C
RewriteCond D
it would be interpreted as if ( (A OR B OR C) and D )
.
ALTER SEQUENCE sequence_name RESTART WITH (SELECT max(id) FROM table_name);
Doesn't work.
Copied from @tardate answer:
SELECT setval(pg_get_serial_sequence('table_name', 'id'), MAX(id)) FROM table_name;
I'd suggest a RelativeLayout instead of a FrameLayout.
Assuming that you want to have the TextView always below the ImageView I'd use following layout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"
android:src="@drawable/icon"
android:visibility="visible"/>
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_below="@id/imageview"
android:gravity="center"
android:text="@string/hello"/>
</RelativeLayout>
Note that if you set the visibility
of an element to gone
then the space that element would consume is gone whereas when you use invisible
instead the space it'd consume will be preserved.
If you want to have the TextView on top of the ImageView then simply leave out the android:layout_alignParentTop
or set it to false
and on the TextView leave out the android:layout_below="@id/imageview"
attribute. Like this.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="false"
android:layout_centerInParent="true"
android:src="@drawable/icon"
android:visibility="visible"/>
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="@string/hello"/>
</RelativeLayout>
I hope this is what you were looking for.
There's a CodeProject article for an ID3 reader. And a thread at kixtart.org that has more information for other properties. Basically, you need to call the GetDetailsOf()
method on the folder shell object for shell32.dll
.
There are two products JavaSE and JavaEE. EE is the web application/enterprise edition that allows the development and running of web application. SE is the plain Java product that has no EE specifics in it, but is a subset of EE. The SE comes in two types a JDK and a JRE.
There is one big difference that may not be obvious, and I am not sure if it applies to all Operating Systems but under Windows the JRE does not have the server HotSpot JVM, only the client one, the JDK has both, and as far as I know all other OS's have both for the JDK and the JRE. The real difference is the the JDK contains the Java compiler, that is the JDK allows you to compile and run Java from source code where as the JRE only allows the running of Java byte code, that is Source that has already been compiled. And yes newer versions bundle a number of extra components, such as NetBeans editor environment and Java in memory Database (derby/cloudscape), but these are optional.
Apache Thrift is a cross-language RPC option developed at Facebook. Works over sockets, function signatures are defined in text files in a language-independent way.
No, you cannot.
From SQL Server Books Online:
User-defined functions cannot be used to perform actions that modify the database state.
Ref.
git commit -am 'Conflicts resolved'
This worked for me. You can try this also.
I adapted a bit the code of everyone, made it in a Function, made it faster (array), and added parameters :
Public Function FirstBlankCell(Optional Sh As Worksheet, Optional SourceCol As Long = 1, Optional ByVal StartRow& = 1, Optional ByVal SelectCell As Boolean = False) As Long
Dim RowCount As Long, CurrentRow As Long
Dim CurrentRowValue As String
Dim Data()
If Sh Is Nothing Then Set Sh = ActiveSheet
With Sh
rowCount = .Cells(.Rows.Count, SourceCol).End(xlUp).Row
Data = .Range(.Cells(1, SourceCol), .Cells(rowCount, SourceCol)).Value2
For currentRow = StartRow To RowCount
If Data(currentRow, SourceCol) = vbNullString Then
If SelectCell Then .Cells(currentRow, SourceCol).Select
'if selection is out of screen, intead of .select , use : application.goto reference:=.cells(...), scroll:= true
FirstBlankCell = currentRow
Exit For
End If
Next
End With ' Sh
Erase Data
Set Sh = Nothing
End Function
You can do like this basically:
int[] ints = new[] { 10, 20, 10, 34, 113 };
this is your array, and than you can call your new list like this:
var newList = new List<int>(ints);
You can do this for complex object too.
If you are using Oracle 10g, you can use the DECODE
function to pivot the rows into columns:
CREATE TABLE doc_tab (
loan_number VARCHAR2(20),
document_type VARCHAR2(20),
document_id VARCHAR2(20)
);
INSERT INTO doc_tab VALUES('992452533663', 'Voters ID', 'XPD0355636');
INSERT INTO doc_tab VALUES('992452533663', 'Pan card', 'CHXPS5522D');
INSERT INTO doc_tab VALUES('992452533663', 'Drivers licence', 'DL-0420110141769');
COMMIT;
SELECT
loan_number,
MAX(DECODE(document_type, 'Voters ID', document_id)) AS voters_id,
MAX(DECODE(document_type, 'Pan card', document_id)) AS pan_card,
MAX(DECODE(document_type, 'Drivers licence', document_id)) AS drivers_licence
FROM
doc_tab
GROUP BY loan_number
ORDER BY loan_number;
Output:
LOAN_NUMBER VOTERS_ID PAN_CARD DRIVERS_LICENCE ------------- -------------------- -------------------- -------------------- 992452533663 XPD0355636 CHXPS5522D DL-0420110141769
You can achieve the same using Oracle PIVOT
clause, introduced in 11g:
SELECT *
FROM doc_tab
PIVOT (
MAX(document_id) FOR document_type IN ('Voters ID','Pan card','Drivers licence')
);
SQLFiddle example with both solutions: SQLFiddle example
Read more about pivoting here: Pivot In Oracle by Tim Hall
$("#edate").change(function(){
var edate = new Date($('#edate').val());
var sdate = new Date($('#sdate').val());
days = (edate- sdate) / (1000 * 60 * 60 * 24);
days=days+1;
alert (days);
$("#nod").val(days);
});
Another example for anyone who runs into a problem with types such as Int? and CGFloat?. You simply set you class as a subclass of NSObject and declare your variables as follows e.g:
class Theme : NSObject{
dynamic var min_images : Int = 0
dynamic var moreTextSize : CGFloat = 0.0
func myMethod(){
self.setValue(value, forKey: "\(min_images)")
}
}
patrick dw's answer is right on.
For kicks and giggles I thought I would post a simple way to return an array of all the IDs.
var arrayOfIds = $.map($(".myClassName"), function(n, i){
return n.id;
});
alert(arrayOfIds);
Works finde for me:
$dom = new \DOMDocument;
$dom->loadHTML(utf8_decode($html));
...
return utf8_encode( $dom->saveHTML());
I know this is a very old thread but I was looking for a solution to the same problem and I came across this before eventually finding the answer and I wanted to just post it here so somebody else in my shoes would have a shorter trek across the internet.
****Note that you probably have to run cmd.exe as an administrator for this to work**
So here we go, open up the prompt (as an adminstrator) and go to your System32 directory. Then run
C:\Windows\System32>cd ras
Now you'll be in the ras directory. Now it's time to create a temporary file with our connection info that we will then append onto the rasphone.pbk file that will allow us to use the rasdial command.
So to create our temp file run:
C:\Windows\System32\ras>copy con temp.txt
Now it will let you type the contents of the file, which should look like this:
[CONNECTION NAME]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=vpn.server.address.com
So replace CONNECTION NAME and vpn.server.address.com with the desired connection name and the vpn server address you want.
Make a new line and press Ctrl+Z to finish and save.
Now we will append this onto the rasphone.pbk file that may or may not exist depending on if you already have network connections configured or not. To do this we will run the following command:
C:\Windows\System32\ras>type temp.txt >> rasphone.pbk
This will append the contents of temp.txt to the end of rasphone.pbk, or if rasphone.pbk doesn't exist it will be created. Now we might as well delete our temp file:
C:\Windows\System32\ras>del temp.txt
Now we can connect to our newly configured VPN server with the following command:
C:\Windows\System32\ras>rasdial "CONNECTION NAME" myUsername myPassword
When we want to disconnect we can run:
C:\Windows\System32\ras>rasdial /DISCONNECT
That should cover it! I've included a direct copy and past from the command line of me setting up a connection for and connecting to a canadian vpn server with this method:
Microsoft Windows [Version 6.2.9200]
(c) 2012 Microsoft Corporation. All rights reserved.
C:\Windows\system32>cd ras
C:\Windows\System32\ras>copy con temp.txt
[Canada VPN Connection]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=ca.justfreevpn.com
^Z
1 file(s) copied.
C:\Windows\System32\ras>type temp.txt >> rasphone.pbk
C:\Windows\System32\ras>del temp.txt
C:\Windows\System32\ras>rasdial "Canada VPN Connection" justfreevpn 2932
Connecting to Canada VPN Connection...
Verifying username and password...
Connecting to Canada VPN Connection...
Connecting to Canada VPN Connection...
Verifying username and password...
Registering your computer on the network...
Successfully connected to Canada VPN Connection.
Command completed successfully.
C:\Windows\System32\ras>rasdial /DISCONNECT
Command completed successfully.
C:\Windows\System32\ras>
Hope this helps.
Why not just
private double translateSlider(int sliderval) {
if(sliderval > 4 || sliderval < 0)
return 1.0d;
return (1.0d - ((double)sliderval/10.0d));
}
Or similar?
To send a variable value through URL in response.sendRedirect(). I have used it for one variable, you can also use it for two variable by proper concatenation.
String value="xyz";
response.sendRedirect("/content/test.jsp?var="+value);
Use itertools.chain:
itertools.chain(*iterables)
:Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.
from itertools import chain
A = [[1,2], [3,4]]
print list(chain(*A))
# or better: (available since Python 2.6)
print list(chain.from_iterable(A))
The output is:
[1, 2, 3, 4]
[1, 2, 3, 4]
This x-ms-format-detection="none" attribute handle the format phone.
https://msdn.microsoft.com/en-us/library/dn337007(v=vs.85).aspx
<p id="phone-text" x-ms-format-detection="none" >Call us on <strong>+44 (0)20 7194 8000</strong></p>
In my case I selected the error marker in the Problems tab and deleted it since the Java's file main method was being executed correctly. That is some glitch in Eclipse Neon with the multitude of plugins it has installed.
You can convert both the values to lower case and compare.
Here is an example:
If LCase(Range("J6").Value) = LCase("Tawi") Then
Range("J6").Value = "Tawi-Tawi"
End If
We moved our department's build chain to CMake, and we had a few internal roadbumps since other departments where using our project files and where accustomed to just importing them into their solutions. We also had some complaints about CMake not being fully integrated into the Visual Studio project/solution manager, so files had to be added manually to CMakeLists.txt; this was a major break in the workflow people were used to.
But in general, it was a quite smooth transition. We're very happy since we don't have to deal with project files anymore.
The concrete workflow for adding a new file to a project is really simple:
CMake 2.6 automatically reruns itself if any CMakeLists.txt files have changed (and (semi-)automatically reloads the solution/projects).
Remember that if you're doing out-of-source builds, you need to be careful not to create the source file in the build directory (since Visual Studio only knows about the build directory).
The final outcome of the conversion is that the number of elements in the final array is same as that of the initial array or data frame.
-1 corresponds to the unknown count of the row or column.
We can think of it as x
(unknown). x
is obtained by dividing the number of elements in the original array by the other value of the ordered pair with -1.
Examples:
12 elements with reshape(-1,1)
corresponds to an array with x
=12/1=12 rows and 1 column.
12 elements with reshape(1,-1)
corresponds to an array with 1 row and x
=12/1=12 columns.
msg = request.GET.get('q','default')
if (msg == default):
message = "YOU SUBMITTED NOTHING"
else:
message = "you submitted = %s" %msg"
return HttpResponse(message);
Just Change in build.gradle file
classpath 'com.android.tools.build:gradle:1.3.0'
To
classpath 'com.android.tools.build:gradle:2.0.0'
Now GoTo
-> menu choose File
-> Invalidate Caches/Restart
...
Choose first option: Invalidate and Restart
Android Studio would restart.
After this, it should work normally.
Path2D is supported by all major browsers now
You can now use ctx.drawImage
to draw HTMLImageElements that have a .svg source in some but not all browsers. Chrome, IE11, and Safari work, Firefox works with some bugs (but nightly has fixed them).
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg";
Live example here. You should see a green square in the canvas. The second green square on the page is the same <svg>
element inserted into the DOM for reference.
You can also use the new Path2D objects to draw SVG (string) paths. In other words, you can write:
var path = new Path2D('M 100,100 h 50 v 50 h 50');
ctx.stroke(path);
There's nothing native that allows you to natively use SVG paths in canvas. You must convert yourself or use a library to do it for you.
I'd suggest looking in to canvg:
Go to system preferences, then "MySQL". Click on "Start MySQL Server".
i had sometime ago the same issue. make sure that your ssh key doesn't have password and use not common user account (e.g. better to user account called jenkins or so).
check following article http://fourkitchens.com/blog/2011/09/20/trigger-jenkins-builds-pushing-github
The event has a property called event.path of the element which is a "static ordered list of all its ancestors in tree order". To check if an event originated from a specific DOM element or one of its children, just check the path for that specific DOM element. It can also be used to check multiple elements by logically OR
ing the element check in the some
function.
$("body").click(function() {_x000D_
target = document.getElementById("main");_x000D_
flag = event.path.some(function(el, i, arr) {_x000D_
return (el == target)_x000D_
})_x000D_
if (flag) {_x000D_
console.log("Inside")_x000D_
} else {_x000D_
console.log("Outside")_x000D_
}_x000D_
});
_x000D_
#main {_x000D_
display: inline-block;_x000D_
background:yellow;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="main">_x000D_
<ul>_x000D_
<li>Test-Main</li>_x000D_
<li>Test-Main</li>_x000D_
<li>Test-Main</li>_x000D_
<li>Test-Main</li>_x000D_
<li>Test-Main</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div id="main2">_x000D_
Outside Main_x000D_
</div>
_x000D_
So for your case It should be
$("body").click(function() {
target = $("#menuscontainer")[0];
flag = event.path.some(function(el, i, arr) {
return (el == target)
});
if (!flag) {
// Hide the menus
}
});
I got this problem too and I fixed it in this way. I was trying to run mapreduce job locally through Eclipse, after set the configurations, I met this error (in Linux, Virtual Box) To solve it,
file:/usr/lib/Hadoop/client-0.20
, choose the three jars named started
by "slf4j".Then you'll be able to run the job locally. Hope my experience will help someone.
Now it's an even bigger mess than it was when this question was first asked. From reading all the responses and blog posts I could find, here's a summary. I also set up this page to test all these methods of measuring the zoom level.
Edit (2011-12-12): I've added a project that can be cloned: https://github.com/tombigel/detect-zoom
screen.deviceXDPI / screen.logicalXDPI
(or, for the zoom level relative to default zoom, screen.systemXDPI / screen.logicalXDPI
)var body = document.body,r = body.getBoundingClientRect(); return (r.left-r.right)/body.offsetWidth;
(thanks to this example or this answer)screen.width
/ media query screen width (see below) (takes advantage of the fact that screen.width
uses device pixels but MQ width uses CSS pixels--thanks to Quirksmode widths)-webkit-text-size-adjust:none
.document.width / jQuery(document).width()
(thanks to Dirk van Oosterbosch above). To get ratio in terms of device pixels (instead of relative to default zoom), multiply by window.devicePixelRatio
.parseInt(getComputedStyle(document.documentElement,null).width) / document.documentElement.clientWidth
(from this answer)document.documentElement.offsetWidth
/ width of a position:fixed; width:100%
div. from here (Quirksmode's widths table says it's a bug; innerWidth should be CSS px). We use the position:fixed element to get the width of the viewport including the space where the scrollbars are; document.documentElement.clientWidth excludes this width. This is broken since sometime in 2011; I know no way to get the zoom level in Opera anymore.Here's a binary search for Firefox 4, since I don't know of any variable where it is exposed:
<style id=binarysearch></style>
<div id=dummyElement>Dummy element to test media queries.</div>
<script>
var mediaQueryMatches = function(property, r) {
var style = document.getElementById('binarysearch');
var dummyElement = document.getElementById('dummyElement');
style.sheet.insertRule('@media (' + property + ':' + r +
') {#dummyElement ' +
'{text-decoration: underline} }', 0);
var matched = getComputedStyle(dummyElement, null).textDecoration
== 'underline';
style.sheet.deleteRule(0);
return matched;
};
var mediaQueryBinarySearch = function(
property, unit, a, b, maxIter, epsilon) {
var mid = (a + b)/2;
if (maxIter == 0 || b - a < epsilon) return mid;
if (mediaQueryMatches(property, mid + unit)) {
return mediaQueryBinarySearch(
property, unit, mid, b, maxIter-1, epsilon);
} else {
return mediaQueryBinarySearch(
property, unit, a, mid, maxIter-1, epsilon);
}
};
var mozDevicePixelRatio = mediaQueryBinarySearch(
'min--moz-device-pixel-ratio', '', a, b, maxIter, epsilon);
var ff35DevicePixelRatio = screen.width / mediaQueryBinarySearch(
'min-device-width', 'px', 0, 6000, 25, .0001);
</script>
Here is a little code that is useful.
var uiHelper = function () {
var htmls = {};
var getHTML = function (url) {
/// <summary>Returns HTML in a string format</summary>
/// <param name="url" type="string">The url to the file with the HTML</param>
if (!htmls[url])
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, false);
xmlhttp.send();
htmls[url] = xmlhttp.responseText;
};
return htmls[url];
};
return {
getHTML: getHTML
};
}();
--Convert the HTML string into a DOM Element
String.prototype.toDomElement = function () {
var wrapper = document.createElement('div');
wrapper.innerHTML = this;
var df= document.createDocumentFragment();
return df.addChilds(wrapper.children);
};
--prototype helper
HTMLElement.prototype.addChilds = function (newChilds) {
/// <summary>Add an array of child elements</summary>
/// <param name="newChilds" type="Array">Array of HTMLElements to add to this HTMLElement</param>
/// <returns type="this" />
for (var i = 0; i < newChilds.length; i += 1) { this.appendChild(newChilds[i]); };
return this;
};
--Usage
thatHTML = uiHelper.getHTML('/Scripts/elevation/ui/add/html/add.txt').toDomElement();
Use juffrou-reflect's BeanWrapper. It is very performant.
Here is how you can transform a bean into a map:
public static Map<String, Object> getBeanMap(Object bean) {
Map<String, Object> beanMap = new HashMap<String, Object>();
BeanWrapper beanWrapper = new BeanWrapper(BeanWrapperContext.create(bean.getClass()));
for(String propertyName : beanWrapper.getPropertyNames())
beanMap.put(propertyName, beanWrapper.getValue(propertyName));
return beanMap;
}
I developed Juffrou myself. It's open source, so you are free to use it and modify. And if you have any questions regarding it, I'll be more than happy to respond.
Cheers
Carlos
Put simply
&
means the address-of, you will see that in placeholders for functions to modify the parameter variable as in C, parameter variables are passed by value, using the ampersand means to pass by reference.*
means the dereference of a pointer variable, meaning to get the value of that pointer variable.int foo(int *x){
*x++;
}
int main(int argc, char **argv){
int y = 5;
foo(&y); // Now y is incremented and in scope here
printf("value of y = %d\n", y); // output is 6
/* ... */
}
The above example illustrates how to call a function foo
by using pass-by-reference, compare with this
int foo(int x){
x++;
}
int main(int argc, char **argv){
int y = 5;
foo(y); // Now y is still 5
printf("value of y = %d\n", y); // output is 5
/* ... */
}
Here's an illustration of using a dereference
int main(int argc, char **argv){
int y = 5;
int *p = NULL;
p = &y;
printf("value of *p = %d\n", *p); // output is 5
}
The above illustrates how we got the address-of y
and assigned it to the pointer variable p
. Then we dereference p
by attaching the *
to the front of it to obtain the value of p
, i.e. *p
.
The error message suggests this is not a supported feature in the query language. But you can save a DataFrame in any format as usual through the RDD interface (df.rdd.saveAsTextFile
). Or you can check out https://github.com/databricks/spark-csv.
If you merged the branch, then reverted the merge using a pull request and merged that pull request to revert.
The easiest way I felt was to:
git revert -m 1 xxxxxx
(if the revert was merged using a branch) or using git revert xxxxxx
if it was a simple revertYou can try this
$i = 1
echo '<p class="paragraph'.$i.'"></p>';
++i;
myArray[j.x]
is logically incorrect.
Use (myArray[j].x);
instead
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
There are several answers here suggesting mail
or mailx
so this is more of a background to help you interpret these in context.
The origins of Unix mail
go back into the mists of the early history of Bell Labs Unix™ (1969?), and we probably cannot hope to go into its full genealogy here. Suffice it to say that there are many programs which inherit code from or reimplement (or inherit code from a reimplementation of) mail
and that there is no single code base which can be unambiguously identified as "the" mail
.
However, one of the contenders to that position is certainly "Berkeley Mail" which was originally called Mail
with an uppercase M in 2BSD (1978); but in 3BSD (1979), it replaced the lowercase mail
command as well, leading to some new confusion. SVR3 (1986) included a derivative which was called mailx
. The x
was presumably added to make it unique and distinct; but this, too, has now been copied, reimplemented, and mutilated so that there is no single individual version which is definitive.
Back in the day, the de facto standard for sending binaries across electronic mail was uuencode
. It still exists, but has numerous usability problems; if at all possible, you should send MIME attachments instead, unless you specifically strive to be able to communicate with the late 1980s.
MIME was introduced in the early 1990s to solve several problems with email, including support for various types of content other than plain text in a single character set which only really is suitable for a subset of English (and, we are told, Hawai'ian). This introduced support for multipart messages, internationalization, rich content types, etc, and quickly gained traction throughout the 1990s.
(The Heirloom mail
/mailx
history notes were most helpful when composing this, and are certainly worth a read if you're into that sort of thing.)
As of 2018, Debian has three packages which include a mail
or mailx
command. (You can search for Provides: mailx
.)
debian$ aptitude search ~Pmailx
i bsd-mailx - simple mail user agent
p heirloom-mailx - feature-rich BSD mail(1)
p mailutils - GNU mailutils utilities for handling mail
(I'm not singling out Debian as a recommendation; it's what I use, so I am familiar with it; and it provides a means of distinguishing the various alternatives unambiguously by referring to their respective package names. It is obviously also the distro from which Ubuntu gets these packages.)
bsd-mailx
is a relatively simple mailx
which does not appear to support sending MIME attachments. See its manual page and note that this is the one you would expect to find on a *BSD system, including MacOS, by default.heirloom-mailx
is now being called s-nail
and does support sending MIME attachments with -a
. See its manual page and more generally the Heirloom projectmailutils
aka GNU Mailutils includes a mail
/mailx
compatibility wrapper which does support sending MIME attachments with -A
With these concerns, if you need your code to be portable and can depend on a somewhat complex package, the simple way to portably send MIME attachments is to use mutt
.
echo "GenFiltEff=7.092200e-01" | cut -d "=" -f2
Spring framework itself handles json conversion when controller is annotated properly.
For eg:
@PutMapping(produces = {"application/json"})
@ResponseBody
public UpdateResponse someMethod(){ //do something
return UpdateResponseInstance;
}
Here spring internally converts the UpdateResponse object to corresponding json string and returns it. In order to do it spring internally uses Jackson library.
If you require a json representation of a model object anywhere apart from controller then you can use objectMapper provided by jackson. Model should be properly annotated for this to work.
Eg:
ObjectMapper mapper = new ObjectMapper();
SomeModelClass someModelObject = someModelRepository.findById(idValue).get();
mapper.writeValueAsString(someModelObject);
For td elements line-height will successfully allow you to resize the border-height as SPrince mentioned.
For other elements such as list items, you can control the border height with line-height and the height of the actual element with margin-top and margin-bottom.
Here is a working example of both: http://jsfiddle.net/byronj/gLcqu6mg/
An example with list items:
li {
list-style: none;
padding: 0 10px;
display: inline-block;
border-right: 1px solid #000;
line-height: 5px;
margin: 20px 0;
}
<ul>
<li>cats</li>
<li>dogs</li>
<li>birds</li>
<li>swine!</li>
</ul>
It looks like this issue has to do with the difference between the Content-Type
and Accept
headers. In HTTP, Content-Type
is used in request and response payloads to convey the media type of the current payload. Accept
is used in request payloads to say what media types the server may use in the response payload.
So, having a Content-Type
in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type
does matter.
If a server is not able to process the Content-Type
of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept
header, it will return a 406 error.)
In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.
You could fix this in one of two ways:
Include the DataServiceVersion header in the request and set it be less than v3. For example:
DataServiceVersion: 2.0;
(Option 2 assumes that you aren't using any v3 features in your request payload.)
It seems that the most common method of achieving this is to draw a GPolygon with enough points to simulate a circle. The example you referenced uses this method. This page has a good example - look for the function drawCircle in the source code.
Image.fromarray -> returns an image object
from PIL import Image
import numpy as np
PIL_image = Image.fromarray(np.uint8(numpy_image)).convert('RGB')
PIL_image = Image.fromarray(numpy_image.astype('uint8'), 'RGB')
SELECT from_unixtime( UNIX_TIMESTAMP(fild_with_timestamp) ) from "your_table"
This work for me
See the Maven - Users forum 'version' contains an expression but should be a constant. Better way to add a new version?:
here is why this is a bad plan.
the pom that gets deployed will not have the property value resolved, so anyone depending on that pom will pick up the dependency as being the string uninterpolated with the ${ } and much hilarity will ensue in your build process.
in maven 2.1.0 and/or 2.2.0 an attempt was made to deploy poms with resolved properties... this broke more than expected, which is why those two versions are not recommended, 2.2.1 being the recommended 2.x version.
How do I convert a list of dictionaries to a pandas DataFrame?
The other answers are correct, but not much has been explained in terms of advantages and limitations of these methods. The aim of this post will be to show examples of these methods under different situations, discuss when to use (and when not to use), and suggest alternatives.
DataFrame()
, DataFrame.from_records()
, and .from_dict()
Depending on the structure and format of your data, there are situations where either all three methods work, or some work better than others, or some don't work at all.
Consider a very contrived example.
np.random.seed(0)
data = pd.DataFrame(
np.random.choice(10, (3, 4)), columns=list('ABCD')).to_dict('r')
print(data)
[{'A': 5, 'B': 0, 'C': 3, 'D': 3},
{'A': 7, 'B': 9, 'C': 3, 'D': 5},
{'A': 2, 'B': 4, 'C': 7, 'D': 6}]
This list consists of "records" with every keys present. This is the simplest case you could encounter.
# The following methods all produce the same output.
pd.DataFrame(data)
pd.DataFrame.from_dict(data)
pd.DataFrame.from_records(data)
A B C D
0 5 0 3 3
1 7 9 3 5
2 2 4 7 6
orient='index'
/'columns'
Before continuing, it is important to make the distinction between the different types of dictionary orientations, and support with pandas. There are two primary types: "columns", and "index".
orient='columns'
Dictionaries with the "columns" orientation will have their keys correspond to columns in the equivalent DataFrame.
For example, data
above is in the "columns" orient.
data_c = [
{'A': 5, 'B': 0, 'C': 3, 'D': 3},
{'A': 7, 'B': 9, 'C': 3, 'D': 5},
{'A': 2, 'B': 4, 'C': 7, 'D': 6}]
pd.DataFrame.from_dict(data_c, orient='columns')
A B C D
0 5 0 3 3
1 7 9 3 5
2 2 4 7 6
Note: If you are using pd.DataFrame.from_records
, the orientation is assumed to be "columns" (you cannot specify otherwise), and the dictionaries will be loaded accordingly.
orient='index'
With this orient, keys are assumed to correspond to index values. This kind of data is best suited for pd.DataFrame.from_dict
.
data_i ={
0: {'A': 5, 'B': 0, 'C': 3, 'D': 3},
1: {'A': 7, 'B': 9, 'C': 3, 'D': 5},
2: {'A': 2, 'B': 4, 'C': 7, 'D': 6}}
pd.DataFrame.from_dict(data_i, orient='index')
A B C D
0 5 0 3 3
1 7 9 3 5
2 2 4 7 6
This case is not considered in the OP, but is still useful to know.
If you need a custom index on the resultant DataFrame, you can set it using the index=...
argument.
pd.DataFrame(data, index=['a', 'b', 'c'])
# pd.DataFrame.from_records(data, index=['a', 'b', 'c'])
A B C D
a 5 0 3 3
b 7 9 3 5
c 2 4 7 6
This is not supported by pd.DataFrame.from_dict
.
All methods work out-of-the-box when handling dictionaries with missing keys/column values. For example,
data2 = [
{'A': 5, 'C': 3, 'D': 3},
{'A': 7, 'B': 9, 'F': 5},
{'B': 4, 'C': 7, 'E': 6}]
# The methods below all produce the same output.
pd.DataFrame(data2)
pd.DataFrame.from_dict(data2)
pd.DataFrame.from_records(data2)
A B C D E F
0 5.0 NaN 3.0 3.0 NaN NaN
1 7.0 9.0 NaN NaN NaN 5.0
2 NaN 4.0 7.0 NaN 6.0 NaN
"What if I don't want to read in every single column"? You can easily specify this using the columns=...
parameter.
For example, from the example dictionary of data2
above, if you wanted to read only columns "A', 'D', and 'F', you can do so by passing a list:
pd.DataFrame(data2, columns=['A', 'D', 'F'])
# pd.DataFrame.from_records(data2, columns=['A', 'D', 'F'])
A D F
0 5.0 3.0 NaN
1 7.0 NaN 5.0
2 NaN NaN NaN
This is not supported by pd.DataFrame.from_dict
with the default orient "columns".
pd.DataFrame.from_dict(data2, orient='columns', columns=['A', 'B'])
ValueError: cannot use columns parameter with orient='columns'
Not supported by any of these methods directly. You will have to iterate over your data and perform a reverse delete in-place as you iterate. For example, to extract only the 0th and 2nd rows from data2
above, you can use:
rows_to_select = {0, 2}
for i in reversed(range(len(data2))):
if i not in rows_to_select:
del data2[i]
pd.DataFrame(data2)
# pd.DataFrame.from_dict(data2)
# pd.DataFrame.from_records(data2)
A B C D E
0 5.0 NaN 3 3.0 NaN
1 NaN 4.0 7 NaN 6.0
json_normalize
for Nested DataA strong, robust alternative to the methods outlined above is the json_normalize
function which works with lists of dictionaries (records), and in addition can also handle nested dictionaries.
pd.json_normalize(data)
A B C D
0 5 0 3 3
1 7 9 3 5
2 2 4 7 6
pd.json_normalize(data2)
A B C D E
0 5.0 NaN 3 3.0 NaN
1 NaN 4.0 7 NaN 6.0
Again, keep in mind that the data passed to json_normalize
needs to be in the list-of-dictionaries (records) format.
As mentioned, json_normalize
can also handle nested dictionaries. Here's an example taken from the documentation.
data_nested = [
{'counties': [{'name': 'Dade', 'population': 12345},
{'name': 'Broward', 'population': 40000},
{'name': 'Palm Beach', 'population': 60000}],
'info': {'governor': 'Rick Scott'},
'shortname': 'FL',
'state': 'Florida'},
{'counties': [{'name': 'Summit', 'population': 1234},
{'name': 'Cuyahoga', 'population': 1337}],
'info': {'governor': 'John Kasich'},
'shortname': 'OH',
'state': 'Ohio'}
]
pd.json_normalize(data_nested,
record_path='counties',
meta=['state', 'shortname', ['info', 'governor']])
name population state shortname info.governor
0 Dade 12345 Florida FL Rick Scott
1 Broward 40000 Florida FL Rick Scott
2 Palm Beach 60000 Florida FL Rick Scott
3 Summit 1234 Ohio OH John Kasich
4 Cuyahoga 1337 Ohio OH John Kasich
For more information on the meta
and record_path
arguments, check out the documentation.
Here's a table of all the methods discussed above, along with supported features/functionality.
* Use orient='columns'
and then transpose to get the same effect as orient='index'
.
The easiest way now is to add it as a module
This will create a new module containing the aar file, so you just need to include that module as a dependency afterwards
As mentioned by @jerry you can add services with the below command.
update-rc.d <service> defaults
update-rc.d <service> start 20 3 4 5
update-rc.d -f <service> remove
To validate them check the above commands you can check /etc/rc*.d/ directory where service start with "k" means it will not execute during the boot and service start with "S" will start during the boot.
# for runlevel symlinks:
ls /etc/rc*.d/
In the below screenshot you can see apache2 starting in runlevel2(S02apache2) and stopping in runlevel1(K01apache2)
You can also check the service status with the below command where "+" means service is in running state "-" is in stopped.
service --status-all
OR
install sysv-rc-conf utility.
apt-get install sysv-rc-conf
example
sysv-rc-conf --level 2345 apach22 on
man sysv-rc-conf
Instructions to install from private repo using ssh credentials:
$ pip install git+ssh://[email protected]/myuser/foo.git@my_version
await Future.delayed(Duration(milliseconds: 1000));
/// <summary>
/// Returns a new conContractorEntity instance filled with the DataReader's current record data
/// </summary>
protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
{
return new conContractorEntity()
{
ConId = reader["conId"].ToString().Length > 0 ? int.Parse(reader["conId"].ToString()) : 0,
ConEmail = reader["conEmail"].ToString(),
ConCopyAdr = reader["conCopyAdr"].ToString().Length > 0 ? bool.Parse(reader["conCopyAdr"].ToString()) : true,
ConCreateTime = reader["conCreateTime"].ToString().Length > 0 ? DateTime.Parse(reader["conCreateTime"].ToString()) : DateTime.MinValue
};
}
OR
/// <summary>
/// Returns a new conContractorEntity instance filled with the DataReader's current record data
/// </summary>
protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
{
return new conContractorEntity()
{
ConId = GetValue<int>(reader["conId"]),
ConEmail = reader["conEmail"].ToString(),
ConCopyAdr = GetValue<bool>(reader["conCopyAdr"], true),
ConCreateTime = GetValue<DateTime>(reader["conCreateTime"])
};
}
// Base methods
protected T GetValue<T>(object obj)
{
if (typeof(DBNull) != obj.GetType())
{
return (T)Convert.ChangeType(obj, typeof(T));
}
return default(T);
}
protected T GetValue<T>(object obj, object defaultValue)
{
if (typeof(DBNull) != obj.GetType())
{
return (T)Convert.ChangeType(obj, typeof(T));
}
return (T)defaultValue;
}
we are using below configuration to do something similar
var gulp = require('gulp'),
async = require("async"),
less = require('gulp-less'),
minifyCSS = require('gulp-minify-css'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
gulpDS = require("./gulpDS"),
del = require('del');
// CSS & Less
var jsarr = [gulpDS.jsbundle.mobile, gulpDS.jsbundle.desktop, gulpDS.jsbundle.common];
var cssarr = [gulpDS.cssbundle];
var generateJS = function() {
jsarr.forEach(function(gulpDSObject) {
async.map(Object.keys(gulpDSObject), function(key) {
var val = gulpDSObject[key]
execGulp(val, key);
});
})
}
var generateCSS = function() {
cssarr.forEach(function(gulpDSObject) {
async.map(Object.keys(gulpDSObject), function(key) {
var val = gulpDSObject[key];
execCSSGulp(val, key);
})
})
}
var execGulp = function(arrayOfItems, dest) {
var destSplit = dest.split("/");
var file = destSplit.pop();
del.sync([dest])
gulp.src(arrayOfItems)
.pipe(concat(file))
.pipe(uglify())
.pipe(gulp.dest(destSplit.join("/")));
}
var execCSSGulp = function(arrayOfItems, dest) {
var destSplit = dest.split("/");
var file = destSplit.pop();
del.sync([dest])
gulp.src(arrayOfItems)
.pipe(less())
.pipe(concat(file))
.pipe(minifyCSS())
.pipe(gulp.dest(destSplit.join("/")));
}
gulp.task('css', generateCSS);
gulp.task('js', generateJS);
gulp.task('default', ['css', 'js']);
sample GulpDS file is below:
{
jsbundle: {
"mobile": {
"public/javascripts/sample.min.js": ["public/javascripts/a.js", "public/javascripts/mobile/b.js"]
},
"desktop": {
'public/javascripts/sample1.js': ["public/javascripts/c.js", "public/javascripts/d.js"]},
"common": {
'public/javascripts/responsive/sample2.js': ['public/javascripts/n.js']
}
},
cssbundle: {
"public/stylesheets/a.css": "public/stylesheets/less/a.less",
}
}
What you are looking for is merging.
git merge master
With pull
you fetch changes from a remote repository and merge them into the current branch.
gcc 4.5 and 4.6 are not supported with CUDA - code won't compile and the rest of the toolchain, including cuda-gdb, won't work properly. You cannot use them, and the restriction is non-negotiable.
Your only solution is to install a gcc 4.4 version as a second compiler (most distributions will allow that). There is an option to nvcc --compiler-bindir
which can be used to point to an alternative compiler. Create a local directory and then make symbolic links to the supported gcc version executables. Pass that local directory to nvcc via the --compiler-bindir
option, and you should be able to compile CUDA code without affecting the rest of your system.
EDIT:
Note that this question, and answer, pertain to CUDA 4.
Since it was written, NVIDIA has continued to expand support for later gcc versions in newer CUDA toolchain release
There is presently (as of CUDA 11.1) no gcc 10 support in CUDA other than Fedora linux
Note that NVIDIA has recently added a very useful table here which contains the supported compiler and OS matrix for the current CUDA release.
First, don't do it that way. The best approach is to use find -exec
properly:
# this is safe
find test -type d -exec echo '{}' +
The other safe approach is to use NUL-terminated list, though this requires that your find support -print0
:
# this is safe
while IFS= read -r -d '' n; do
printf '%q\n' "$n"
done < <(find test -mindepth 1 -type d -print0)
You can also populate an array from find, and pass that array later:
# this is safe
declare -a myarray
while IFS= read -r -d '' n; do
myarray+=( "$n" )
done < <(find test -mindepth 1 -type d -print0)
printf '%q\n' "${myarray[@]}" # printf is an example; use it however you want
If your find doesn't support -print0
, your result is then unsafe -- the below will not behave as desired if files exist containing newlines in their names (which, yes, is legal):
# this is unsafe
while IFS= read -r n; do
printf '%q\n' "$n"
done < <(find test -mindepth 1 -type d)
If one isn't going to use one of the above, a third approach (less efficient in terms of both time and memory usage, as it reads the entire output of the subprocess before doing word-splitting) is to use an IFS
variable which doesn't contain the space character. Turn off globbing (set -f
) to prevent strings containing glob characters such as []
, *
or ?
from being expanded:
# this is unsafe (but less unsafe than it would be without the following precautions)
(
IFS=$'\n' # split only on newlines
set -f # disable globbing
for n in $(find test -mindepth 1 -type d); do
printf '%q\n' "$n"
done
)
Finally, for the command-line parameter case, you should be using arrays if your shell supports them (i.e. it's ksh, bash or zsh):
# this is safe
for d in "$@"; do
printf '%s\n' "$d"
done
will maintain separation. Note that the quoting (and the use of $@
rather than $*
) is important. Arrays can be populated in other ways as well, such as glob expressions:
# this is safe
entries=( test/* )
for d in "${entries[@]}"; do
printf '%s\n' "$d"
done
I separate it, and then use an identity comparison to dictate what is does next.
$("#selectField").change(function(){
if(this.value === 'textValue1'){ $(".contentClass1").fadeIn(); }
if(this.value === 'textValue2'){ $(".contentclass2").fadeIn(); }
});
After several hours of testing and trying things...
I solved this problem as simple as possible. I notice that they use "test pages" inside Facebook Developers Page that contains only the "og" tags and some text in the body tag that referals this og tags.
So what have i done?
I created a second view in my application, containing this same things they use.
And how i know is Facebook that is accessing my page so i can change the view? They have a unique User Agent: "facebookexternalhit/1.1"
The Request Payload - or to be more precise: payload body of a HTTP Request
- is the data normally send by a POST or PUT Request.
It's the part after the headers and the CRLF
of a HTTP Request.
A request with Content-Type: application/json
may look like this:
POST /some-path HTTP/1.1
Content-Type: application/json
{ "foo" : "bar", "name" : "John" }
If you submit this per AJAX the browser simply shows you what it is submitting as payload body. That’s all it can do because it has no idea where the data is coming from.
If you submit a HTML-Form with method="POST"
and Content-Type: application/x-www-form-urlencoded
or Content-Type: multipart/form-data
your request may look like this:
POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded
foo=bar&name=John
In this case the form-data is the request payload. Here the Browser knows more: it knows that bar is the value of the input-field foo of the submitted form. And that’s what it is showing to you.
So, they differ in the Content-Type
but not in the way data is submitted. In both cases the data is in the message-body. And Chrome distinguishes how the data is presented to you in the Developer Tools.
The accepted answer fairly definitively suggests using utf8_unicode_ci, and whilst for new projects that's great, I wanted to relate my recent contrary experience just in case it saves anyone some time.
Because utf8_general_ci is the default collation for Unicode in MySQL, if you want to use utf8_unicode_ci then you end up having to specify it in a lot of places.
For example, all client connections not only have a default charset (makes sense to me) but also a default collation (i.e. the collation will always default to utf8_general_ci for unicode).
Likely, if you use utf8_unicode_ci for your fields, your scripts that connect to the database will need to be updated to mention the desired collation explicitly -- otherwise queries using text strings can fail when your connection is using the default collation.
The upshot is that when converting an existing system of any size to Unicode/utf8, you may end up being forced to use utf8_general_ci because of the way MySQL handles defaults.
In python 3 you could use colorama - simple_colors:
(Simple Colours page: https://pypi.org/project/simple-colors/ - go to the heading 'Usage'.) Before you do what is below, make sure you pip install simple_colours
.
from simple_colors import *
print(green('hello', 'bold'))
You can do the following:
(SELECT
*
FROM
table1 t1
LEFT JOIN
table2 t2 ON t1.id = t2.id
WHERE
t2.id IS NULL)
UNION ALL
(SELECT
*
FROM
table1 t1
RIGHT JOIN
table2 t2 ON t1.id = t2.id
WHERE
t1.id IS NULL);
Have you tried using the concat() function?
ON tableTwo.query = concat('category_id=',tableOne.category_id)
You need to tell it which index in data
to use, or double loop through all.
E.g., to get the values in the 4th index in the outside array.:
foreach($user->data[3]->values as $values)
{
echo $values->value . "\n";
}
To go through all:
foreach($user->data as $mydata)
{
foreach($mydata->values as $values) {
echo $values->value . "\n";
}
}
I encountered this when using scrapy and fetching a zipped csvfile without having a correct middleware to unzip the response body before handing it to the csvreader. Hence the file was not really a csv file and threw the line contains NULL byte
error accordingly.
I had same issue, was due to multiple copies of ssl.conf In /etc/httpd/conf.d - There should only be one.
Date d1 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
getParameter(date1));
Date d2 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
getParameter(date2));
long diff = d2.getTime() - d1.getTime();
System.out.println("Difference between " + d1 + " and "+ d2+" is "
+ (diff / (1000 * 60 * 60 * 24)) + " days.");
Adding the following to the top of the .htaccess
RewriteEngine On
RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
Use the ToDictionary
method directly.
var result =
// as Jon Skeet pointed out, OrderBy is useless here, I just leave it
// show how to use OrderBy in a LINQ query
myClassCollection.OrderBy(mc => mc.SomePropToSortOn)
.ToDictionary(mc => mc.KeyProp.ToString(),
mc => mc.ValueProp.ToString(),
StringComparer.OrdinalIgnoreCase);
BEST
DECLARE @yourSpecialMark = '/';
select len(@yourString) - len(replace(@yourString,@yourSpecialMark,''))
It will count, how many times occours the special mark '/'
Ok. I found problem.
It was not on the Angular side. To be honest, there were no problem at all.
Reason why I was unable to perform my request succesfuly was that my server app was not properly handling OPTIONS request.
Why OPTIONS, not POST? My server app is on different host, then frontend. Because of CORS my browser was converting POST to OPTION: http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
With help of this answer: Standalone Spring OAuth2 JWT Authorization Server + CORS
I implemented proper filter on my server-side app.
Thanks to @Supamiu - the person which fingered me that I am not sending POST at all.
Frequently we deal with other fellow java programmers work which create these Stored Procedure. and we do not want to mess around with it. but there is possibility you get the result set where these exec sample return 0 (almost Stored procedure call returning zero).
check this sample :
public void generateINOUT(String USER, int DPTID){
try {
conUrl = JdbcUrls + dbServers +";databaseName="+ dbSrcNames+";instance=MSSQLSERVER";
con = DriverManager.getConnection(conUrl,dbUserNames,dbPasswords);
//stat = con.createStatement();
con.setAutoCommit(false);
Statement st = con.createStatement();
st.executeUpdate("DECLARE @RC int\n" +
"DECLARE @pUserID nvarchar(50)\n" +
"DECLARE @pDepartmentID int\n" +
"DECLARE @pStartDateTime datetime\n" +
"DECLARE @pEndDateTime datetime\n" +
"EXECUTE [AccessManager].[dbo].[SP_GenerateInOutDetailReportSimple] \n" +
""+USER +
"," +DPTID+
",'"+STARTDATE +
"','"+ENDDATE+"'");
ResultSet rs = st.getGeneratedKeys();
while (rs.next()){
String userID = rs.getString("UserID");
Timestamp timeIN = rs.getTimestamp("timeIN");
Timestamp timeOUT = rs.getTimestamp ("timeOUT");
int totTime = rs.getInt ("totalTime");
int pivot = rs.getInt ("pivotvalue");
timeINS = sdz.format(timeIN);
userIN.add(timeINS);
timeOUTS = sdz.format(timeOUT);
userOUT.add(timeOUTS);
System.out.println("User : "+userID+" |IN : "+timeIN+" |OUT : "+timeOUT+"| Total Time : "+totTime+" | PivotValue : "+pivot);
}
con.commit();
}catch (Exception e) {
e.printStackTrace();
System.out.println(e);
if (e.getCause() != null) {
e.getCause().printStackTrace();}
}
}
I came to this solutions after few days trial and error, googling and get confused ;) it execute below Stored Procedure :
USE [AccessManager]
GO
/****** Object: StoredProcedure [dbo].[SP_GenerateInOutDetailReportSimple]
Script Date: 04/05/2013 15:54:11 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SP_GenerateInOutDetailReportSimple]
(
@pUserID nvarchar(50),
@pDepartmentID int,
@pStartDateTime datetime,
@pEndDateTime datetime
)
AS
Declare @ErrorCode int
Select @ErrorCode = @@Error
Declare @TransactionCountOnEntry int
If @ErrorCode = 0
Begin
Select @TransactionCountOnEntry = @@TranCount
BEGIN TRANSACTION
End
If @ErrorCode = 0
Begin
-- Create table variable instead of SQL temp table because report wont pick up the temp table
DECLARE @tempInOutDetailReport TABLE
(
UserID nvarchar(50),
LogDate datetime,
LogDay varchar(20),
TimeIN datetime,
TimeOUT datetime,
TotalTime int,
RemarkTimeIn nvarchar(100),
RemarkTimeOut nvarchar(100),
TerminalIPTimeIn varchar(50),
TerminalIPTimeOut varchar(50),
TerminalSNTimeIn nvarchar(50),
TerminalSNTimeOut nvarchar(50),
PivotValue int
)
-- Declare variables for the while loop
Declare @LogUserID nvarchar(50)
Declare @LogEventID nvarchar(50)
Declare @LogTerminalSN nvarchar(50)
Declare @LogTerminalIP nvarchar(50)
Declare @LogRemark nvarchar(50)
Declare @LogTimestamp datetime
Declare @LogDay nvarchar(20)
-- Filter off userID, departmentID, StartDate and EndDate if specified, only process the remaining logs
-- Note: order by user then timestamp
Declare LogCursor Cursor For
Select distinct access_event_logs.USERID, access_event_logs.EVENTID,
access_event_logs.TERMINALSN, access_event_logs.TERMINALIP,
access_event_logs.REMARKS, access_event_logs.LOCALTIMESTAMP, Datename(dw,access_event_logs.LOCALTIMESTAMP) AS WkDay
From access_event_logs
Left Join access_user on access_user.User_ID = access_event_logs.USERID
Left Join access_user_dept on access_user.User_ID = access_user_dept.User_ID
Where ((Dept_ID = @pDepartmentID) OR (@pDepartmentID IS NULL))
And ((access_event_logs.USERID LIKE '%' + @pUserID + '%') OR (@pUserID IS NULL))
And ((access_event_logs.LOCALTIMESTAMP >= @pStartDateTime ) OR (@pStartDateTime IS NULL))
And ((access_event_logs.LOCALTIMESTAMP < DATEADD(day, 1, @pEndDateTime) ) OR (@pEndDateTime IS NULL))
And (access_event_logs.USERID != 'UNKNOWN USER') -- Ignore UNKNOWN USER
Order by access_event_logs.USERID, access_event_logs.LOCALTIMESTAMP
Open LogCursor
Fetch Next
From LogCursor
Into @LogUserID, @LogEventID, @LogTerminalSN, @LogTerminalIP, @LogRemark, @LogTimestamp, @LogDay
-- Temp storage for IN event details
Declare @InEventUserID nvarchar(50)
Declare @InEventDay nvarchar(20)
Declare @InEventTimestamp datetime
Declare @InEventRemark nvarchar(100)
Declare @InEventTerminalIP nvarchar(50)
Declare @InEventTerminalSN nvarchar(50)
-- Temp storage for OUT event details
Declare @OutEventUserID nvarchar(50)
Declare @OutEventTimestamp datetime
Declare @OutEventRemark nvarchar(100)
Declare @OutEventTerminalIP nvarchar(50)
Declare @OutEventTerminalSN nvarchar(50)
Declare @CurrentUser varchar(50) -- used to indicate when we change user group
Declare @CurrentDay varchar(50) -- used to indicate when we change day
Declare @FirstEvent int -- indicate the first event we received
Declare @ReceiveInEvent int -- indicate we have received an IN event
Declare @PivotValue int -- everytime we change user or day - we reset it (reporting purpose), if same user..keep increment its value
Declare @CurrTrigger varchar(50) -- used to keep track of the event of the current event log trigger it is handling
Declare @CurrTotalHours int -- used to keep track of total hours of the day of the user
Declare @FirstInEvent datetime
Declare @FirstInRemark nvarchar(100)
Declare @FirstInTerminalIP nvarchar(50)
Declare @FirstInTerminalSN nvarchar(50)
Declare @FirstRecord int -- indicate another day of same user
Set @PivotValue = 0 -- initialised
Set @CurrentUser = '' -- initialised
Set @FirstEvent = 1 -- initialised
Set @ReceiveInEvent = 0 -- initialised
Set @CurrTrigger = '' -- Initialised
Set @CurrTotalHours = 0 -- initialised
Set @FirstRecord = 1 -- initialised
Set @CurrentDay = '' -- initialised
While @@FETCH_STATUS = 0
Begin
-- use to track current log trigger
Set @CurrTrigger =LOWER(@LogEventID)
If (@CurrentUser != '' And @CurrentUser != @LogUserID) -- new batch of user
Begin
If @ReceiveInEvent = 1 -- previous IN event is not cleared (no OUT is found)
Begin
-- Check day
If (@CurrentDay != @InEventDay) -- change to another day
Set @PivotValue = 0 -- Reset
Else -- same day
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @InEventDay -- update the day
-- invalid row (only has IN event)
Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn,
TerminalSNTimeIn, PivotValue, LogDate )
values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP,
@InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
End
Set @FirstEvent = 1 -- Reset flag (we are having a new user group)
Set @ReceiveInEvent = 0 -- Reset
Set @PivotValue = 0 -- Reset
--Set @CurrentDay = '' -- Reset
End
If LOWER(@LogEventID) = 'in' -- IN event
Begin
If @ReceiveInEvent = 1 -- previous IN event is not cleared (no OUT is found)
Begin
-- Check day
If (@CurrentDay != @InEventDay) -- change to another day
Begin
Set @PivotValue = 0 -- Reset
--Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
-- RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
-- LogDate)
--values( @LogUserID, @CurrentDay, @FirstInEvent, @LogTimestamp, @CurrTotalHours,
-- @FirstInRemark, @LogRemark, @FirstInTerminalIP, @LogTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
-- DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
End
Else
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @InEventDay -- update the day
-- invalid row (only has IN event)
Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn,
TerminalSNTimeIn, PivotValue, LogDate )
values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP,
@InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
End
If((@CurrentDay != @LogDay And @CurrentDay != '') Or (@CurrentUser != @LogUserID And @CurrentUser != '') )
Begin
Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
LogDate)
values( @CurrentUser, @CurrentDay, @FirstInEvent, @OutEventTimestamp, @CurrTotalHours,
@FirstInRemark, @OutEventRemark, @FirstInTerminalIP, @OutEventTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
Set @FirstRecord = 1
End
-- Save it
Set @InEventUserID = @LogUserID
Set @InEventDay = @LogDay
Set @InEventTimestamp = @LogTimeStamp
Set @InEventRemark = @LogRemark
Set @InEventTerminalIP = @LogTerminalIP
Set @InEventTerminalSN = @LogTerminalSN
If (@FirstRecord = 1) -- save for first in event record of the day
Begin
Set @FirstInEvent = @LogTimestamp
Set @FirstInRemark = @LogRemark
Set @FirstInTerminalIP = @LogTerminalIP
Set @FirstInTerminalSN = @LogTerminalSN
Set @CurrTotalHours = 0 --initialise total hours for another day
End
Set @FirstRecord = 0 -- no more first record of the day
Set @ReceiveInEvent = 1 -- indicate we have received an "IN" event
Set @FirstEvent = 0 -- no more "first" event
End
Else If LOWER(@LogEventID) = 'out' -- OUT event
Begin
If @FirstEvent = 1 -- the first OUT record when change users
Begin
-- Check day
If (@CurrentDay != @LogDay) -- change to another day
Set @PivotValue = 0 -- Reset
Else
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @LogDay -- update the day
-- Only an OUT event (no IN event) - invalid record but we show it anyway
Insert into @tempInOutDetailReport( UserID, LogDay, TimeOUT, RemarkTimeOut, TerminalIPTimeOut, TerminalSNTimeOut,
PivotValue, LogDate )
values( @LogUserID, @LogDay, @LogTimestamp, @LogRemark, @LogTerminalIP, @LogTerminalSN, @PivotValue,
DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @LogTimestamp)))
Set @FirstEvent = 0 -- not "first" anymore
End
Else -- Not first event
Begin
If @ReceiveInEvent = 1 -- if there are IN event previously
Begin
-- Check day
If (@CurrentDay != @InEventDay) -- change to another day
Set @PivotValue = 0 -- Reset
Else
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @InEventDay -- update the day
Set @CurrTotalHours = @CurrTotalHours + DATEDIFF(second,@InEventTimestamp, @LogTimeStamp) -- update total time
Set @OutEventRemark = @LogRemark
Set @OutEventTerminalIP = @LogTerminalIP
Set @OutEventTerminalSN = @LogTerminalSN
Set @OutEventTimestamp = @LogTimestamp
-- valid row
--Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
-- RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
-- LogDate)
--values( @LogUserID, @InEventDay, @InEventTimestamp, @LogTimestamp, Datediff(second, @InEventTimestamp, @LogTimeStamp),
-- @InEventRemark, @LogRemark, @InEventTerminalIP, @LogTerminalIP, @InEventTerminalSN, @LogTerminalSN, @PivotValue,
-- DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
Set @ReceiveInEvent = 0 -- Reset
End
Else -- no IN event previously
Begin
-- Check day
If (@CurrentDay != @LogDay) -- change to another day
Set @PivotValue = 0 -- Reset
Else
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @LogDay -- update the day
-- invalid row (only has OUT event)
Insert into @tempInOutDetailReport( UserID, LogDay, TimeOUT, RemarkTimeOut, TerminalIPTimeOut, TerminalSNTimeOut,
PivotValue, LogDate )
values( @LogUserID, @LogDay, @LogTimestamp, @LogRemark, @LogTerminalIP, @LogTerminalSN, @PivotValue,
DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @LogTimestamp)) )
End
End
End
Set @CurrentUser = @LogUserID -- update user
Fetch Next
From LogCursor
Into @LogUserID, @LogEventID, @LogTerminalSN, @LogTerminalIP, @LogRemark, @LogTimestamp, @LogDay
End
-- Need to handle the last log if its IN log as it will not be processed by the while loop
if @CurrTrigger='in'
Begin
-- Check day
If (@CurrentDay != @InEventDay) -- change to another day
Set @PivotValue = 0 -- Reset
Else -- same day
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @InEventDay -- update the day
-- invalid row (only has IN event)
Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn,
TerminalSNTimeIn, PivotValue, LogDate )
values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP,
@InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
End
else if @CurrTrigger = 'out'
Begin
Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
LogDate)
values( @LogUserID, @CurrentDay, @FirstInEvent, @LogTimestamp, @CurrTotalHours,
@FirstInRemark, @LogRemark, @FirstInTerminalIP, @LogTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
End
Close LogCursor
Deallocate LogCursor
Select *
From @tempInOutDetailReport tempTable
Left Join access_user on access_user.User_ID = tempTable.UserID
Order By tempTable.UserID, LogDate
End
If @@TranCount > @TransactionCountOnEntry
Begin
If @ErrorCode = 0
COMMIT TRANSACTION
Else
ROLLBACK TRANSACTION
End
return @ErrorCode
you will get the "java SQL Code" by right click on stored procedure in your database. something like this :
DECLARE @RC int
DECLARE @pUserID nvarchar(50)
DECLARE @pDepartmentID int
DECLARE @pStartDateTime datetime
DECLARE @pEndDateTime datetime
-- TODO: Set parameter values here.
EXECUTE @RC = [AccessManager].[dbo].[SP_GenerateInOutDetailReportSimple]
@pUserID,@pDepartmentID,@pStartDateTime,@pEndDateTime
GO
check the query String I've done, that is your homework ;) so sorry answering this long, this is my first answer since I register few weeks ago to get answer.
Use this code:
var result=JsonConvert.DeserializeObject<List<yourObj>>(jsonString);
How about this?
CREATE FUNCTION dbo.StripWWWandCom (@input VARCHAR(250))
RETURNS VARCHAR(250)
AS BEGIN
DECLARE @Work VARCHAR(250)
SET @Work = @Input
SET @Work = REPLACE(@Work, 'www.', '')
SET @Work = REPLACE(@Work, '.com', '')
RETURN @work
END
and then use:
SELECT ID, dbo.StripWWWandCom (WebsiteName)
FROM dbo.YourTable .....
Of course, this is severely limited in that it will only strip www.
at the beginning and .com
at the end - nothing else (so it won't work on other host machine names like smtp.yahoo.com
and other internet domains such as .org
, .edu
, .de
and etc.)
My understanding is that arrays are stored more efficiently (i.e. as contiguous blocks of memory vs. pointers to Python objects), but I am not aware of any performance benefit. Additionally, with arrays you must store primitives of the same type, whereas lists can store anything.
I've had success with:
location.hash="myValue";
It just adds #myValue
to the current URL. If you need to trigger an event on page Load, you can use the same location.hash
to check for the relevant value. Just remember to remove the #
from the value returned by location.hash
e.g.
var articleId = window.location.hash.replace("#","");
Create repository on dockerhub :
$docker tag IMAGE_ID UsernameOnDockerhub/repoNameOnDockerhub:latest
$docker push UsernameOnDockerhub/repoNameOnDockerhub:latest
Note : here "repoNameOnDockerhub" : repository with the name you are mentioning has to be present on dockerhub
"latest" : is just tag
Quoting from No more 'unable to find valid certification path to requested target'
when trying to open an SSL connection to a host using JSSE. What this usually means is that the server is using a test certificate (possibly generated using keytool) rather than a certificate from a well known commercial Certification Authority such as Verisign or GoDaddy. Web browsers display warning dialogs in this case, but since JSSE cannot assume an interactive user is present it just throws an exception by default.
Certificate validation is a very important part of SSL security, but I am not writing this entry to explain the details. If you are interested, you can start by reading the Wikipedia blurb. I am writing this entry to show a simple way to talk to that host with the test certificate, if you really want to.
Basically, you want to add the server's certificate to the KeyStore with your trusted certificates
Try the code provided there. It might help.
You can follow this Google JavaScript Style Guide
In general, use functionNamesLikeThis, variableNamesLikeThis, ClassNamesLikeThis, EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.
EDIT: See nice collection of JavaScript Style Guides And Beautifiers.
According to the official documentation on sitemaps.org it needs to be a full URL:
You can specify the location of the Sitemap using a robots.txt file. To do this, simply add the following line including the full URL to the sitemap:
Sitemap: http://www.example.com/sitemap.xml
You can do it without setlocal
, because of the setlocal
command the variable won't survive an endlocal
because it was created in setlocal
. In this way the variable will be defined the right way.
To do that use this code:
set var1=A
set var2=B
set AB=hi
call set newvar=%%%var1%%var2%%%
echo %newvar%
Note: You MUST use call
before you set the variable or it won't work.
Additionally if you want to know which extensions are available on your server: SELECT * FROM pg_available_extensions
Check the MySQL Datetime Functions:
Try this:
SELECT *
FROM tableA
WHERE YEAR(columnName) = YEAR(CURRENT_DATE()) AND
MONTH(columnName) = MONTH(CURRENT_DATE());
itemIconTint, if u want to change icon color
android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:itemTextColor="@color/colorPrimary"
app:itemIconTint="@color/colorPrimary"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
I use this chrome extension. It'll give you the wget command for any download link you open.
You can use parseInt(string, radix) to convert string value to integer like this code below
var votevalue = parseInt($('button').data('votevalue'));
?
Let arrList
be the ArrayList
and newValue
the new String
, then just do:
arrList.set(5, newValue);
This can be found in the java api reference here.
Code :
var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);
document.cookie =
'username=' + value +
'; expires=' + now.toUTCString() +
'; path=/';
You have to define window type as actionbar before activity render its view.
use
requestWindowFeature(Window.FEATURE_ACTION_BAR);
before calling setContentView() method.
If you want to use special character in javascript variable value, Escape Character (\
) is required.
Backslash in your example is special character, too.
So you should do something like this,
var ttt = "aa ///\\\\\\"; // --> ///\\\
or
var ttt = "aa ///\\"; // --> ///\
But Escape Character not require for user input.
When you press /
in prompt box or input field then submit, that means single /
.
You need to use the change directory command 'cd' to change directory
cd C:\Users\MyName\Desktop
you can use cd \d
to change the drive as well.
link for additional resources http://ss64.com/nt/cd.html
You can use this:
List<Int32> sNumberslst = sNumbers.Split(',').ConvertIntoIntList();
If you want to write percent (%), duplicate it:
<string name="percent">%1$d%%</string>
label.text = getString(R.string.percent, 75) // Output: 75%.
If you write simply %1$d%
, you will get the error: Format string 'percent' is not a valid format string so it should not be passed to String.format
.
In the first case, there are two objects created.
In the second case, it's just one.
Although both ways str
is referring to "abc"
.
simplest thing to do; just add:
app:navigationIcon="@drawable/ic_action_navigation_menu">
to the <android.support.v7.widget.Toolbar
tag
where @drawable/ic_action_navigation_menu
is the name of icon
Simplest example using the Standard Library.
#include <iostream>
using namespace std;
int main()
{
char c = 'n';
cout << "HEX " << hex << (int)c << endl; // output in hexadecimal
cout << "ASC" << c << endl; // output in ascii
return 0;
}
To check the output, codepad returns: 6e
and an online ascii-to-hexadecimal conversion tool yields 6e as well. So it works.
You can also do this:
template<class T> std::string toHexString(const T& value, int width) {
std::ostringstream oss;
oss << hex;
if (width > 0) {
oss << setw(width) << setfill('0');
}
oss << value;
return oss.str();
}
you can make that using transform and transform origins.
Combining various transfroms gives similar result. I hope you find it helpful. :) See these examples for simpler transforms. this has left point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 100% 50%;_x000D_
-moz-transform-origin: 100% 50%;_x000D_
-o-transform-origin: 100% 50%;_x000D_
transform-origin: 100% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
This has right skew point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 0% 50%;_x000D_
-moz-transform-origin: 0% 50%;_x000D_
-o-transform-origin: 0% 50%;_x000D_
transform-origin: 0% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
what transform: 0% 50%;
does is it sets the origin to vertical middle and horizontal left of the element. so the perspective is not visible at the left part of the image, so it looks flat. Perspective effect is there at the right part, so it looks slanted.
I was the same problem and as Pengyy suggest, that is the fix. Thanks a lot.
My problem on the Browser Console:
PortafolioComponent.html:3 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed(…)
In my case my code fix was:
//productos.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class ProductosService {
productos:any[] = [];
cargando:boolean = true;
constructor( private http:Http) {
this.cargar_productos();
}
public cargar_productos(){
this.cargando = true;
this.http.get('https://webpage-88888a1.firebaseio.com/productos.json')
.subscribe( res => {
console.log(res.json());
this.cargando = false;
this.productos = res.json().productos; // Before this.productos = res.json();
});
}
}
Here is the solution steps:
I have ended up using ABCPdf from webSupergoo. It works really well and for about $350 it has saved me hours and hours based on your comments above. Thanks again Daniel and Bratch for your comments.
Solution for small array collections:
for (var obj in arr) {
var i = Object.keys(arr).indexOf(obj);
}
arr - ARRAY, obj - KEY of current element, i - COUNTER/INDEX
Notice: Method keys() is not available for IE version <9, you should use Polyfill code. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
On Latest Mac with Jio IP6 Configuration issue ,it block internet on android simulator ,so from Android Virtual Device Manager simulator list Actions column dropdown select the option "Cold Boot Now" fixed the issue.I faced this problem after i kept same its working for me.
For linux users, you should know the following:
$CLASSPATH is specifically what Java uses to look through multiple directories to find all the different classes it needs for your script (unless you explicitly tell it otherwise with the -cp override). Using -cp (--classpath) requires that you keep track of all the directories manually and copy-paste that line every time you run the program (not preferable IMO).
The colon (":") character separates the different directories. There is only one $CLASSPATH and it has all the directories in it. So, when you run "export CLASSPATH=...." you want to include the current value "$CLASSPATH" in order to append to it. For example:
export CLASSPATH=.
export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java-5.1.12.jar
In the first line above, you start CLASSPATH out with just a simple 'dot' which is the path to your current working directory. With that, whenever you run java it will look in the current working directory (the one you're in) for classes. In the second line above, $CLASSPATH grabs the value that you previously entered (.) and appends the path to a mysql dirver. Now, java will look for the driver AND for your classes.
echo $CLASSPATH
is super handy, and what it returns should read like a colon-separated list of all the directories you want java looking in for what it needs to run your script.
Tomcat does not use CLASSPATH. Read what to do about that here: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html
For simplicity I will use bytes:
byte a=250;
byte b=8;
byte c=a+b;
if a, b, and c were 'int', you would expect 258, but in the case of 'byte', the expected result would be 2 (258 & 0xFF), but in a Windows application you get an exception, in a console one you may not (I don't, but this may depend on IDE, I use SharpDevelop).
Sometimes, however, that behaviour is desired (e.g. you only care about the lower 8 bits of the result).
You could do the following:
byte a=250;
byte b=8;
byte c=(byte)((int)a + (int)b);
This way both 'a' and 'b' are converted to 'int', added, then casted back to 'byte'.
To be on the safe side, you may also want to try:
...
byte c=(byte)(((int)a + (int)b) & 0xFF);
Or if you really want that behaviour, the much simpler way of doing the above is:
unchecked
{
byte a=250;
byte b=8;
byte c=a+b;
}
Or declare your variables first, then do the math in the 'unchecked' section.
Alternately, if you want to force the checking of overflow, use 'checked' instead.
Hope this clears things up.
Nurchi
P.S.
Trust me, that exception is your friend :)
You can use this
@echo off
for /F %%i in ('dir /b "c:\test directory\*.*"') do (
echo Folder is NON empty
goto :EOF
)
echo Folder is empty or does not exist
Taken from here.
That should do what you need.
'a' in x
and a quick search reveals some nice information about it: http://docs.python.org/3/tutorial/datastructures.html#dictionaries
Try the following syntax:
document.body.innerHTML += "<p>My new content</p>";
numpy.random.randint
accepts a third argument (size
) , in which you can specify the size of the output array. You can use this to create your DataFrame
-
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
Here - np.random.randint(0,100,size=(100, 4))
- creates an output array of size (100,4)
with random integer elements between [0,100)
.
Demo -
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
which produces:
A B C D
0 45 88 44 92
1 62 34 2 86
2 85 65 11 31
3 74 43 42 56
4 90 38 34 93
5 0 94 45 10
6 58 23 23 60
.. .. .. .. ..
In case someone wants to do this in the programming way! Do the following: Update the color file in your values folder with this.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="transparent">#00ffffff</color> <!--This is the transparency line-->
</resources>
then call the transparency programitically
your_textview.setBackgroundResource(R.color.transparent);
Remove VALUES
from your SQL.
My problem was I was registering table view cell inside dispatch queue asynchronously. If you have registered table view source and delegate reference in storyboard then dispatch queue would delay the registration of cell as name suggests it will happen asynchronously and your table view is looking for the cells.
DispatchQueue.main.async {
self.tableView.register(CampaignTableViewCell.self, forCellReuseIdentifier: CampaignTableViewCell.identifier())
self.tableView.reloadData()
}
Either you shouldn't use dispatch queue for registration OR do this:
DispatchQueue.main.async {
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.register(CampaignTableViewCell.self, forCellReuseIdentifier: CampaignTableViewCell.identifier())
self.tableView.reloadData()
}
The 487 Response indicates that the previous request was terminated by user/application action. The most common occurrence is when the CANCEL happens as explained above. But it is also not limited to CANCEL. There are other cases where such responses can be relevant. So it depends on where you are seeing this behavior and whether its a user or application action that caused it.
15.1.2 UAS Behavior==> BYE Handling in RFC 3261
The UAS MUST still respond to any pending requests received for that dialog. It is RECOMMENDED that a 487 (Request Terminated) response be generated to those pending requests.
Here you have to just add jar file in lib jsoup in your application and then use this code.
import org.jsoup.Jsoup;
public class Encoder {
public static void main(String args[]) {
String s = Jsoup.parse("<Français>").text();
System.out.print(s);
}
}
Link to download jsoup: http://jsoup.org/download
As Praveen mentions above, when using the basic FileInputFormat
classes is just the number of input splits that constitute the data. The number of reducers is controlled by mapred.reduce.tasks
specified in the way you have it: -D mapred.reduce.tasks=10
would specify 10 reducers. Note that the space after -D
is required; if you omit the space, the configuration property is passed along to the relevant JVM, not to Hadoop.
Are you specifying 0
because there is no reduce work to do? In that case, if you're having trouble with the run-time parameter, you can also set the value directly in code. Given a JobConf
instance job
, call
job.setNumReduceTasks(0);
inside, say, your implementation of Tool.run
. That should produce output directly from the mappers. If your job actually produces no output whatsoever (because you're using the framework just for side-effects like network calls or image processing, or if the results are entirely accounted for in Counter values), you can disable output by also calling
job.setOutputFormat(NullOutputFormat.class);
An extension method for this which makes use of SemaphoreSlim and also allows to set maximum degree of parallelism
/// <summary>
/// Concurrently Executes async actions for each item of <see cref="IEnumerable<typeparamref name="T"/>
/// </summary>
/// <typeparam name="T">Type of IEnumerable</typeparam>
/// <param name="enumerable">instance of <see cref="IEnumerable<typeparamref name="T"/>"/></param>
/// <param name="action">an async <see cref="Action" /> to execute</param>
/// <param name="maxDegreeOfParallelism">Optional, An integer that represents the maximum degree of parallelism,
/// Must be grater than 0</param>
/// <returns>A Task representing an async operation</returns>
/// <exception cref="ArgumentOutOfRangeException">If the maxActionsToRunInParallel is less than 1</exception>
public static async Task ForEachAsyncConcurrent<T>(
this IEnumerable<T> enumerable,
Func<T, Task> action,
int? maxDegreeOfParallelism = null)
{
if (maxDegreeOfParallelism.HasValue)
{
using (var semaphoreSlim = new SemaphoreSlim(
maxDegreeOfParallelism.Value, maxDegreeOfParallelism.Value))
{
var tasksWithThrottler = new List<Task>();
foreach (var item in enumerable)
{
// Increment the number of currently running tasks and wait if they are more than limit.
await semaphoreSlim.WaitAsync();
tasksWithThrottler.Add(Task.Run(async () =>
{
await action(item).ContinueWith(res =>
{
// action is completed, so decrement the number of currently running tasks
semaphoreSlim.Release();
});
}));
}
// Wait for all tasks to complete.
await Task.WhenAll(tasksWithThrottler.ToArray());
}
}
else
{
await Task.WhenAll(enumerable.Select(item => action(item)));
}
}
Sample Usage:
await enumerable.ForEachAsyncConcurrent(
async item =>
{
await SomeAsyncMethod(item);
},
5);
I think we better adopt a new file inclusion syntax (so won't mess up with
code blocks, I think the C style inclusion is totally wrong), and I wrote a small tool in Perl, naming cat.pl
,
because it works like cat
(cat a.txt b.txt c.txt
will merge three
files), but it merges files in depth, not in width. How to use?
$ perl cat.pl <your file>
The syntax in detail is:
@include <-=path=
%include <-=path=
It can properly handle file inclusion loops (if a.txt <- b.txt, b.txt <- a.txt, then what you expect?).
Example:
a.txt:
a.txt
a <- b
@include <-=b.txt=
a.end
b.txt:
b.txt
b <- a
@include <-=a.txt=
b.end
perl cat.pl a.txt > c.txt
, c.txt:
a.txt
a <- b
b.txt
b <- a
a.txt
a <- b
@include <-=b.txt= (note:won't include, because it will lead to infinite loop.)
a.end
b.end
a.end
More examples at https://github.com/district10/cat/blob/master/tutorial_cat.pl_.md.
I also wrote a Java version having an identical effect (not the same, but close).
Alternatively, you could invert the image using the bitwise_not
function of OpenCV:
imagem = cv2.bitwise_not(imagem)
I liked this example.
Expanding on betabandido's answer, you could write a function to inject the attributes as constants into the module:
def module_register_class_constants(klass, attr_prefix):
globals().update(
(name, getattr(klass, name)) for name in dir(klass) if name.startswith(attr_prefix)
)
class Animal(object):
SIZE_HUGE = "Huge"
SIZE_BIG = "Big"
module_register_class_constants(Animal, "SIZE_")
class Horse(Animal):
def printSize(self):
print SIZE_BIG
The logic is wrong. Consider this:
x = ["a","b","c"]
x[0] // "a"
x["0"] // "a"
0 in x // true
"0" in x // true
x.hasOwnProperty(0) // true
x.hasOwnProperty("0") // true
There is no reason to loop to check for key (or indices for arrays) existence. Now, values are a different story...
Happy coding
SomeServiceClient client = new SomeServiceClient();
var endpointAddress = client.Endpoint.Address; //gets the default endpoint address
EndpointAddressBuilder newEndpointAddress = new EndpointAddressBuilder(endpointAddress);
newEndpointAddress.Uri = new Uri("net.tcp://serverName:8000/SomeServiceName/");
client = new SomeServiceClient("EndpointConfigurationName", newEndpointAddress.ToEndpointAddress());
I did it like this. The good thing is it still picks up the rest of your endpoint binding settings from the config and just replaces the URI.
ng-show
/ ng-hide
accepts only boolean
values.
For complex expressions it is good to use controller and scope to avoid complications.
Below one will work (It is not very complex expression)
ng-show="User=='admin' || User=='teacher'"
Here element will be shown in UI when any of the two condition return true (OR operation).
Like this you can use any expressions.
In my case, it is taking time in AM and PM but sending data in 00-24 hours format to the server on form submit. and when use that DB data in its value then it will automatically select the appropriate AM or PM to edit form value.
You might want to check out the angular-ui directive ui-if
if you just want to remove the ul
from the DOM when the list is empty:
<ul ui-if="!!events.length">
<li ng-repeat="event in events">{{event.title}}</li>
</ul>
From the Javadoc of Method.invoke()
Throws: InvocationTargetException - if the underlying method throws an exception.
This exception is thrown if the method called threw an exception.
First Solution
I developed this as a cleaned up version of .NET Win 7-style folder select dialog by Bill Seddon of lyquidity.com (I have no affiliation). (I learned of his code from another answer on this page). I wrote my own because his solution requires an additional Reflection class that isn't needed for this focused purpose, uses exception-based flow control, doesn't cache the results of its reflection calls. Note that the nested static VistaDialog
class is so that its static reflection variables don't try to get populated if the Show
method is never called. It falls back to the pre-Vista dialog if not in a high enough Windows version. Should work in Windows 7, 8, 9, 10 and higher (theoretically).
using System;
using System.Reflection;
using System.Windows.Forms;
namespace ErikE.Shuriken {
/// <summary>
/// Present the Windows Vista-style open file dialog to select a folder. Fall back for older Windows Versions
/// </summary>
public class FolderSelectDialog {
private string _initialDirectory;
private string _title;
private string _fileName = "";
public string InitialDirectory {
get { return string.IsNullOrEmpty(_initialDirectory) ? Environment.CurrentDirectory : _initialDirectory; }
set { _initialDirectory = value; }
}
public string Title {
get { return _title ?? "Select a folder"; }
set { _title = value; }
}
public string FileName { get { return _fileName; } }
public bool Show() { return Show(IntPtr.Zero); }
/// <param name="hWndOwner">Handle of the control or window to be the parent of the file dialog</param>
/// <returns>true if the user clicks OK</returns>
public bool Show(IntPtr hWndOwner) {
var result = Environment.OSVersion.Version.Major >= 6
? VistaDialog.Show(hWndOwner, InitialDirectory, Title)
: ShowXpDialog(hWndOwner, InitialDirectory, Title);
_fileName = result.FileName;
return result.Result;
}
private struct ShowDialogResult {
public bool Result { get; set; }
public string FileName { get; set; }
}
private static ShowDialogResult ShowXpDialog(IntPtr ownerHandle, string initialDirectory, string title) {
var folderBrowserDialog = new FolderBrowserDialog {
Description = title,
SelectedPath = initialDirectory,
ShowNewFolderButton = false
};
var dialogResult = new ShowDialogResult();
if (folderBrowserDialog.ShowDialog(new WindowWrapper(ownerHandle)) == DialogResult.OK) {
dialogResult.Result = true;
dialogResult.FileName = folderBrowserDialog.SelectedPath;
}
return dialogResult;
}
private static class VistaDialog {
private const string c_foldersFilter = "Folders|\n";
private const BindingFlags c_flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
private readonly static Assembly s_windowsFormsAssembly = typeof(FileDialog).Assembly;
private readonly static Type s_iFileDialogType = s_windowsFormsAssembly.GetType("System.Windows.Forms.FileDialogNative+IFileDialog");
private readonly static MethodInfo s_createVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("CreateVistaDialog", c_flags);
private readonly static MethodInfo s_onBeforeVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("OnBeforeVistaDialog", c_flags);
private readonly static MethodInfo s_getOptionsMethodInfo = typeof(FileDialog).GetMethod("GetOptions", c_flags);
private readonly static MethodInfo s_setOptionsMethodInfo = s_iFileDialogType.GetMethod("SetOptions", c_flags);
private readonly static uint s_fosPickFoldersBitFlag = (uint) s_windowsFormsAssembly
.GetType("System.Windows.Forms.FileDialogNative+FOS")
.GetField("FOS_PICKFOLDERS")
.GetValue(null);
private readonly static ConstructorInfo s_vistaDialogEventsConstructorInfo = s_windowsFormsAssembly
.GetType("System.Windows.Forms.FileDialog+VistaDialogEvents")
.GetConstructor(c_flags, null, new[] { typeof(FileDialog) }, null);
private readonly static MethodInfo s_adviseMethodInfo = s_iFileDialogType.GetMethod("Advise");
private readonly static MethodInfo s_unAdviseMethodInfo = s_iFileDialogType.GetMethod("Unadvise");
private readonly static MethodInfo s_showMethodInfo = s_iFileDialogType.GetMethod("Show");
public static ShowDialogResult Show(IntPtr ownerHandle, string initialDirectory, string title) {
var openFileDialog = new OpenFileDialog {
AddExtension = false,
CheckFileExists = false,
DereferenceLinks = true,
Filter = c_foldersFilter,
InitialDirectory = initialDirectory,
Multiselect = false,
Title = title
};
var iFileDialog = s_createVistaDialogMethodInfo.Invoke(openFileDialog, new object[] { });
s_onBeforeVistaDialogMethodInfo.Invoke(openFileDialog, new[] { iFileDialog });
s_setOptionsMethodInfo.Invoke(iFileDialog, new object[] { (uint) s_getOptionsMethodInfo.Invoke(openFileDialog, new object[] { }) | s_fosPickFoldersBitFlag });
var adviseParametersWithOutputConnectionToken = new[] { s_vistaDialogEventsConstructorInfo.Invoke(new object[] { openFileDialog }), 0U };
s_adviseMethodInfo.Invoke(iFileDialog, adviseParametersWithOutputConnectionToken);
try {
int retVal = (int) s_showMethodInfo.Invoke(iFileDialog, new object[] { ownerHandle });
return new ShowDialogResult {
Result = retVal == 0,
FileName = openFileDialog.FileName
};
}
finally {
s_unAdviseMethodInfo.Invoke(iFileDialog, new[] { adviseParametersWithOutputConnectionToken[1] });
}
}
}
// Wrap an IWin32Window around an IntPtr
private class WindowWrapper : IWin32Window {
private readonly IntPtr _handle;
public WindowWrapper(IntPtr handle) { _handle = handle; }
public IntPtr Handle { get { return _handle; } }
}
}
}
It is used like so in a Windows Form:
var dialog = new FolderSelectDialog {
InitialDirectory = musicFolderTextBox.Text,
Title = "Select a folder to import music from"
};
if (dialog.Show(Handle)) {
musicFolderTextBox.Text = dialog.FileName;
}
You can of course play around with its options and what properties it exposes. For example, it allows multiselect in the Vista-style dialog.
Second Solution
Simon Mourier gave an answer that shows how to do the exact same job using interop against the Windows API directly, though his version would have to be supplemented to use the older style dialog if in an older version of Windows. Unfortunately, I hadn't found his post yet when I worked up my solution. Name your poison!
Just delete module-info.java at your Project Explorer tab.
As said, to follow redirects you can use the flag -L
or --location
:
curl -L http://www.example.com
But, if you want limit the number of redirects, add the parameter --max-redirs
--max-redirs <num>
Set maximum number of redirection-followings allowed. If
-L
,--location
is used, this option can be used to prevent curl from following redirections "in absurdum". By default, the limit is set to 50 redirections. Set this option to -1 to make it limitless. If this option is used several times, the last one will be used.
Tralemonkey's solution almost worked for me as well ... but not quite. I ended up doing it this way:
echo -n '$#@password@#$' | passwd myusername --stdin
2 key details his solution didn't include, the -n
keeps echo from adding a \n
to the password that is getting encrypted, and the single quotes protect the contents from being interpreted by the shell (bash) in my case.
BTW I ran this command as root on a CentOS 5.6 system in case anyone is wondering.