Download proxy script and check last line for return statement Proxy IP and Port.
Add this IP and Port using these step.
1. Windows -->Preferences-->General -->Network Connection
2. Select Active Provider : Manual
3. Proxy entries select HTTP--> Click on Edit button
4. Then add Host as a proxy IP and port left Required Authentication blank.
5. Restart eclipse
6. Now Eclipse Marketplace... working.
public LatLang getLatLangFromAddress(String strAddress){
Geocoder coder = new Geocoder(this, Locale.getDefault());
List<Address> address;
try {
address = coder.getFromLocationName(strAddress,5);
if (address == null) {
return new LatLang(-10000, -10000);
}
Address location = address.get(0);
return new LatLang(location.getLatitude(), location.getLongitude());
} catch (IOException e) {
return new LatLang(-10000, -10000);
}
}
LatLang
is a pojo class in this case.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
permission is not required.
Daniel A. White Solution works great for classes.
I've got a situation where I had to find input fields like donee_1_card where 1 is an index.
My solution has been
$("input[name^='donee']" && "input[name*='card']")
Though I am not sure how optimal it is.
Try:
dashboard_df = pd.read_csv(p_file, sep=',', error_bad_lines=False, index_col=False, dtype='unicode')
According to the pandas documentation:
dtype : Type name or dict of column -> type
As for low_memory, it's True by default and isn't yet documented. I don't think its relevant though. The error message is generic, so you shouldn't need to mess with low_memory anyway. Hope this helps and let me know if you have further problems
it could be done when the RowDataBound
event fires
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Hide the edit button when some condition is true
// for example, the row contains a certain property
if (someCondition)
{
Button btnEdit = (Button)e.Row.FindControl("btnEdit");
btnEdit.Visible = false;
}
}
}
Here's a demo page
markup
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DropDownDemo._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>GridView OnRowDataBound Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Name" DataField="name" />
<asp:BoundField HeaderText="Age" DataField="age" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="BtnEdit" runat="server" Text="Edit" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
Code Behind
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
namespace GridViewDemo
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = GetCustomers();
GridView1.DataBind();
}
protected override void OnInit(EventArgs e)
{
GridView1.RowDataBound += new GridViewRowEventHandler(GridView1_RowDataBound);
base.OnInit(e);
}
void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow) return;
int age;
if (int.TryParse(e.Row.Cells[1].Text, out age))
if (age == 30)
{
Button btnEdit = (Button) e.Row.FindControl("btnEdit");
btnEdit.Visible = false;
}
}
private static List<Customer> GetCustomers()
{
List<Customer> results = new List<Customer>();
results.Add(new Customer("Steve", 30));
results.Add(new Customer("Brian", 40));
results.Add(new Customer("Dave", 50));
results.Add(new Customer("Bill", 25));
results.Add(new Customer("Rich", 22));
results.Add(new Customer("Bert", 30));
return results;
}
}
public class Customer
{
public string Name {get;set;}
public int Age { get; set; }
public Customer(string name, int age)
{
Name = name;
Age = age;
}
}
}
In the demo, the Edit Button is not Visible (the HTML markup is not sent to the client) in those rows where the Customer's age is 30.
Thanks for the suggestions in the comments. I made a bit of a dirty hack to get what I want without having to create my own image. With javascript I first hide the default tag that's being used for the down arrow, like so:
$('b[role="presentation"]').hide();
I then included font-awesome in my page and add my own down arrow, again with a line of javascript, to replace the default one:
$('.select2-arrow').append('<i class="fa fa-angle-down"></i>');
Then with CSS I style the select boxes. I set the height, change the background color of the arrow area to a gradient black, change the width, font-size and also the color of the down arrow to white:
.select2-container .select2-choice {
padding: 5px 10px;
height: 40px;
width: 132px;
font-size: 1.2em;
}
.select2-container .select2-choice .select2-arrow {
background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
background-image: -moz-linear-gradient(top, #424242, #030303);
background-image: -ms-linear-gradient(top, #424242, #030303);
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
background-image: -webkit-linear-gradient(top, #424242, #030303);
background-image: -o-linear-gradient(top, #424242, #030303);
background-image: linear-gradient(#424242, #030303);
width: 40px;
color: #fff;
font-size: 1.3em;
padding: 4px 12px;
}
The result is the styling the way I want it:
Update 5/6/2015 As @Katie Lacy mentioned in the other answer the classnames have been changed in version 4 of Select2. The updated CSS with the new classnames should look like this:
.select2-container--default .select2-selection--single{
padding:6px;
height: 37px;
width: 148px;
font-size: 1.2em;
position: relative;
}
.select2-container--default .select2-selection--single .select2-selection__arrow {
background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
background-image: -moz-linear-gradient(top, #424242, #030303);
background-image: -ms-linear-gradient(top, #424242, #030303);
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
background-image: -webkit-linear-gradient(top, #424242, #030303);
background-image: -o-linear-gradient(top, #424242, #030303);
background-image: linear-gradient(#424242, #030303);
width: 40px;
color: #fff;
font-size: 1.3em;
padding: 4px 12px;
height: 27px;
position: absolute;
top: 0px;
right: 0px;
width: 20px;
}
JS:
$('b[role="presentation"]').hide();
$('.select2-selection__arrow').append('<i class="fa fa-angle-down"></i>');
Try this one: http://www.asp.net/downloads/essential This has web developer and VS2008 express
You should not be operating the state at all. At least, not directly. If you want to update your array, you'll want to do something like this.
var newStateArray = this.state.myArray.slice();
newStateArray.push('new value');
this.setState(myArray: newStateArray);
Working on the state object directly is not desirable. You can also take a look at React's immutability helpers.
There are several reasons this can happen. Some of these I found here, others I discovered on my own.
Id
, you need to add the [Key]
attribute to it.public
uint
, ulong
etc. are not allowed.from sklearn.metrics import mean_squared_error
rmse = mean_squared_error(y_actual, y_predicted, squared=False)
or
import math
from sklearn.metrics import mean_squared_error
rmse = math.sqrt(mean_squared_error(y_actual, y_predicted))
In this two queries, you are using JOIN to query all employees that have at least one department associated.
But, the difference is: in the first query you are returning only the Employes for the Hibernate. In the second query, you are returning the Employes and all Departments associated.
So, if you use the second query, you will not need to do a new query to hit the database again to see the Departments of each Employee.
You can use the second query when you are sure that you will need the Department of each Employee. If you not need the Department, use the first query.
I recomend read this link if you need to apply some WHERE condition (what you probably will need): How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?
Update
If you don't use fetch
and the Departments continue to be returned, is because your mapping between Employee and Department (a @OneToMany
) are setted with FetchType.EAGER
. In this case, any HQL (with fetch
or not) query with FROM Employee
will bring all Departments. Remember that all mapping *ToOne (@ManyToOne
and @OneToOne
) are EAGER by default.
You can do it using JavaScript by triggering an ajax request to server to destroy the session on onbeforeunload event fired when we closes the browse tab or window or browser.
For me the easiest way to get it to work, is to put the component.requestFocus();
line, after the setVisible(true);
line, at the bottom of your frame or panel constructor.
This probably has something to do with asking for the focus, after all components have been created, because creating a new component, after asking for the focus request, will make your component loose te focus, and make the focus go to your newly created component. At least, that's what I assume.
As mentioned by Klap "android.R.layout.simple_list_item_1 is a reference to an built-in XML layout document that is part of the Android OS"
All the layouts are located in: sdk\platforms\android-xx\data\res\layout
To view the XML of layout :
Eclipse: Simply type android.R.layout.simple_list_item_1 somewhere in code, hold Ctrl, hover over simple_list_item_1, and from the dropdown that appears select "Open declaration in layout/simple_list_item_1.xml". It'll direct you to the contents of the XML.
Android Studio: Project Window -> External Libraries -> Android X Platform -> res -> layout, and here you will see a list of available layouts.
You can do it with PHP:
header("Refresh:0");
It refreshes your current page, and if you need to redirect it to another page, use following:
header("Refresh:0; url=page2.php");
application
because .js
-Files aren't something a user wants to read but something that should get executed.
Use SimpleDateFormat
to format any Date
object you want:
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
Using a new Date()
as shown above will format the current time.
I was having a similar issue but none of these fixes worked. The problem was that my button was not yet on the page. The fix for this ended up being going from this:
//Bad code.
var btn = document.createElement('button');
btn.onClick = function() { console.log("hey"); }
to this:
//Working Code. I don't like it, but it works.
var btn = document.createElement('button');
var wrapper = document.createElement('div');
wrapper.appendChild(btn);
document.body.appendChild(wrapper);
var buttons = wrapper.getElementsByTagName("BUTTON");
buttons[0].onclick = function(){ console.log("hey"); }
I have no clue at all why this works. Adding the button to the page and referring to it any other way did not work.
If you install just the JRE, it seems to be put at:
/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
extern template
is only needed if the template declaration is complete
This was hinted at in other answers, but I don't think enough emphasis was given to it.
What this means is that in the OPs examples, the extern template
has no effect because the template definitions on the headers were incomplete:
void f();
: just declaration, no bodyclass foo
: declares method f()
but has no definitionSo I would recommend just removing the extern template
definition in that particular case: you only need to add them if the classes are completely defined.
For example:
TemplHeader.h
template<typename T>
void f();
TemplCpp.cpp
template<typename T>
void f(){}
// Explicit instantiation for char.
template void f<char>();
Main.cpp
#include "TemplHeader.h"
// Commented out from OP code, has no effect.
// extern template void f<T>(); //is this correct?
int main() {
f<char>();
return 0;
}
compile and view symbols with nm
:
g++ -std=c++11 -Wall -Wextra -pedantic -c -o TemplCpp.o TemplCpp.cpp
g++ -std=c++11 -Wall -Wextra -pedantic -c -o Main.o Main.cpp
g++ -std=c++11 -Wall -Wextra -pedantic -o Main.out Main.o TemplCpp.o
echo TemplCpp.o
nm -C TemplCpp.o | grep f
echo Main.o
nm -C Main.o | grep f
output:
TemplCpp.o
0000000000000000 W void f<char>()
Main.o
U void f<char>()
and then from man nm
we see that U
means undefined, so the definition did stay only on TemplCpp
as desired.
All this boils down to the tradeoff of complete header declarations:
extern template
on every includer, which programmers will likely forget to doFurther examples of those are shown at: Explicit template instantiation - when is it used?
Since compilation time is so critical in large projects, I would highly recommend incomplete template declarations, unless external parties absolutely need to reuse your code with their own complex custom classes.
And in that case, I would first try to use polymorphism to avoid the build time problem, and only use templates if noticeable performance gains can be made.
Tested in Ubuntu 18.04.
I just had to implement a RESTfull api where I need to pass parameters. I did this by passing the parameters in the query string in the same style as described by Mark's first example "api/controller?start=date1&end=date2"
In the controller I used a tip from URL split in C#?
// uri: /api/courses
public IEnumerable<Course> Get()
{
NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query);
var system = nvc["System"];
// BL comes here
return _courses;
}
In my case I was calling the WebApi via Ajax looking like:
$.ajax({
url: '/api/DbMetaData',
type: 'GET',
data: { system : 'My System',
searchString: '123' },
dataType: 'json',
success: function (data) {
$.each(data, function (index, v) {
alert(index + ': ' + v.name);
});
},
statusCode: {
404: function () {
alert('Failed');
}
}
});
I hope this helps...
You can do this:
function Sleep(seconds)
local endTime = os.time() + seconds
while os.time() < endTime do
end
end
print("This is printed first!")
Sleep(5)
print("This is printed 5 seconds later!")
if via a batch file use:
set SHORT_DIR=%~dsp0%
you can use the echo command to check:
echo %SHORT_DIR%
Why use the rewrite module if you can do return
? Technically speaking, return
is part of the rewrite module as you can read here but this snippet is easier to read imho.
server {
server_name .domain.com;
return 302 $scheme://forwarded-domain.com;
}
You can also give it a 301 redirect.
Answering this has been good, as the comments have led to an improvement in my own understanding of Python variables.
As noted in the comments, when you loop over a list with something like for member in my_list
the member
variable is bound to each successive list element. However, re-assigning that variable within the loop doesn't directly affect the list itself. For example, this code won't change the list:
my_list = [1,2,3]
for member in my_list:
member = 42
print my_list
Output:
[1, 2, 3]
If you want to change a list containing immutable types, you need to do something like:
my_list = [1,2,3]
for ndx, member in enumerate(my_list):
my_list[ndx] += 42
print my_list
Output:
[43, 44, 45]
If your list contains mutable objects, you can modify the current member
object directly:
class C:
def __init__(self, n):
self.num = n
def __repr__(self):
return str(self.num)
my_list = [C(i) for i in xrange(3)]
for member in my_list:
member.num += 42
print my_list
[42, 43, 44]
Note that you are still not changing the list, simply modifying the objects in the list.
You might benefit from reading Naming and Binding.
atan2(y,x)
is generally used if you want to convert cartesian coordinates to polar coordinates. It will give you the angle, while sqrt(x*x+y*y)
or, if available, hypot(y,x)
will give you the size.
atan(x)
is simply the inverse of tan. In the annoying case you have to use atan(y/x)
because your system doesn't provide atan2
, you would have to do additional checks for the signs of x
and y
, and for x=0
, in order to get the correct angle.
Note: atan2(y,x)
is defined for all real values of y
and x
, except for the case when both arguments are zero.
I think you are asking two things which are not necessarily the same
I want to extract every 6th element of the original
You can do this by indexing a sequence:
foo <- 1:120
foo[1:20*6]
I would like to create a vector in which each element is the i+6th element of another vector.
An easy way to do this is to supplement a logical factor with FALSEs until i+6
:
foo <- 1:120
i <- 1
foo[1:(i+6)==(i+6)]
[1] 7 14 21 28 35 42 49 56 63 70 77 84 91 98 105 112 119
i <- 10
foo[1:(i+6)==(i+6)]
[1] 16 32 48 64 80 96 112
Nobody mentioned how to dump HTTP headers correctly under any circumstances.
From CGI specification rfc3875, section 4.1.18:
Meta-variables with names beginning with "HTTP_" contain values read from the client request header fields, if the protocol used is HTTP. The HTTP header field name is converted to upper case, has all occurrences of "-" replaced with "" and has "HTTP" prepended to give the meta-variable name.
foreach ($_SERVER as $key => $value) {
if (strpos($key, 'HTTP_') === 0) {
$chunks = explode('_', $key);
$header = '';
for ($i = 1; $y = sizeof($chunks) - 1, $i < $y; $i++) {
$header .= ucfirst(strtolower($chunks[$i])).'-';
}
$header .= ucfirst(strtolower($chunks[$i])).': '.$value;
echo $header.'<br>';
}
}
Details: http://cmyker.blogspot.com/2012/10/how-to-dump-http-headers-with-php.html
Press Ctrl - C it will stop
if not check
Solution (not the best, but still working for some cases) for non-dinamic text with fixed width.Usefull for situations when there are a little space to "stretch" text to the end of the penultimate line. Make some symbols in the end of the paragraph (experiment with their length) and hide it; apply to the paragraph absolute position or just correct free space with padding/marging.
Good compabitity/crossbrowser way for center-justifying text.
Example (paragraph before):
.paragraph {_x000D_
width:455px;_x000D_
text-align:justify;_x000D_
}_x000D_
_x000D_
.center{_x000D_
display:block;_x000D_
text-align:center;_x000D_
margin-top:-17px;_x000D_
}
_x000D_
<div class="paragraph">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna,<br><center>vel scelerisque nisl consectetur et.</center></div>
_x000D_
And after the fix:
.paragraph {_x000D_
width:455px;_x000D_
text-align:justify;_x000D_
position:relative;_x000D_
}_x000D_
.center{_x000D_
display:block;_x000D_
text-align:center;_x000D_
margin-top:-17px;_x000D_
}_x000D_
.paragraph b{_x000D_
opacity:0;_x000D_
_x000D_
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
filter: alpha(opacity=0);_x000D_
-moz-opacity: 0;_x000D_
-khtml-opacity: 0;_x000D_
}
_x000D_
<div class="paragraph">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna, <b>__</b><br><div class="center">vel scelerisque nisl consectetur et.</div></div>
_x000D_
Git is distributed version control system, while Subversion is centralized (client-server) version control system. They work differently; get used to that. Please read my answer explaining the consequences of that difference to git equivalent of svn status -u
question at StackOverflow.
Repeating myself a bit: in centralized version control system (like CVS or Subversion) almost all commands are processed on server, and involve network. Very few commands are performed locally. Note that to have good performance of "svn status" and "svn diff" Subversion stores 'pristine copy' of checked-out version on client, to not have to involve network transfer for those common operations (this means that Subversion checkout = 2 x size of working directory at least).
In distributed version control system (like Git, Mercurial or Bazaar), where you have local copy (clone) of a whole repository, almost all commands are performed on client. Very few commands require network connection to other repository (to server).
The number of command you can perform on server is limited.
ResultSet rs = Sstatement.executeQuery("SELECT * FROM Table Name");
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
System.out.println("resultSet MetaData column Count=" + numberOfColumns);
for (int i = 1; i <= numberOfColumns; i++) {
System.out.println("column number " + i);
System.out.println(rsMetaData.getColumnTypeName(i));
}
The symbol you posted is the placeholder symbol for a broken byte sequence. Basically, it's not a real symbol but an error in your string.
What is the exact byte value of the symbol? Blindly applying utf8_encode is not a good idea, it's better to find out first where the byte(s) came from and what they mean.
This works for me:
$.get("data.php", function(data){
var expected = ['justIn', 'recent', 'old'];
var outString = '';
$.each(expected, function(i, val){
var contentArray = data[val];
outString += '<ul><li><b>' + val + '</b>: ';
$.each(contentArray, function(i1, val2){
var textID = val2.textId;
var text = val2.text;
var textType = val2.textType;
outString += '<br />('+textID+') '+'<i>'+text+'</i> '+textType;
});
outString += '</li></ul>';
});
$('#contentHere').append(outString);
}, 'json');
This produces this output:
<div id="contentHere"><ul>
<li><b>justIn</b>:
<br />
(123) <i>Hello</i> Greeting<br>
(514) <i>What's up?</i> Question<br>
(122) <i>Come over here</i> Order</li>
</ul><ul>
<li><b>recent</b>:
<br />
(1255) <i>Hello</i> Greeting<br>
(6564) <i>What's up?</i> Question<br>
(0192) <i>Come over here</i> Order</li>
</ul><ul>
<li><b>old</b>:
<br />
(5213) <i>Hello</i> Greeting<br>
(9758) <i>What's up?</i> Question<br>
(7655) <i>Come over here</i> Order</li>
</ul></div>
And looks like this:
Also, remember to set the contentType
as 'json'
//XAML Code
// ViewModel code
private CategoryModel _SelectedCategory;
public CategoryModel SelectedCategory
{
get { return _SelectedCategory; }
set
{
_SelectedCategory = value;
OnPropertyChanged("SelectedCategory");
}
}
private ObservableCollection<CategoryModel> _Categories;
public ObservableCollection<CategoryModel> Categories
{
get { return _Categories; }
set
{
_Categories = value;
_Categories.Insert(0, new CategoryModel()
{
CategoryId = 0,
CategoryName = " -- Select Category -- "
});
SelectedCategory = _Categories[0];
OnPropertyChanged("Categories");
}
}
I would suggest following extension methods for string parsing into int value with ability to define default value in case parsing is not possible:
public static int ParseInt(this string value, int defaultIntValue = 0)
{
return int.TryParse(value, out var parsedInt) ? parsedInt : defaultIntValue;
}
public static int? ParseNullableInt(this string value)
{
if (string.IsNullOrEmpty(value))
return null;
return value.ParseInt();
}
If you have ruby installed
cat FileWithColumnOfNumbers.txt | xargs ruby -e "puts ARGV.map(&:to_i).inject(&:+)"
Try this
function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
//var values = rows.getValues();
var Names = sheet.getRange("A2:A7");
var Name = [
Names.getCell(1, 1).getValue(),
Names.getCell(2, 1).getValue(),
.....
Names.getCell(5, 1).getValue()]
You can define arrays simply as follows, instead of allocating and then assigning.
var arr = [1,2,3,5]
Your initial error was because of the following line, and ones like it
var Name[0] = Name_cell.getValue();
Since Name
is already defined and you are assigning the values to its elements, you should skip the var
, so just
Name[0] = Name_cell.getValue();
Pro tip: For most issues that, like this one, don't directly involve Google services, you are better off Googling for the way to do it in javascript in general.
Native paste / bracketed paste is the best and simplest way since vim 8
(released in 2016). It even works over ssh! (Bracketed paste works on Linux and Mac, but not Windows Git Bash)
Make sure you have vim 8+ (you don't need the +clipboard
or +xterm_clipboard
options).
vim --version | head -1
Simply use the OS native paste command (e.g. ctrl+shift+V
or cmd+V
) in Normal Mode. Do not press i
for Insert Mode.
Test
Copy (ctrl+shift+C
or cmd+C
) the output of this (2 lines with a tab indent) to the system clipboard:
echo -e '\ta\n\tb'
Launch a clean vim 8+ with autoindent:
vim -u NONE --noplugin -c 'set autoindent'
Paste from the system clipboard (ctrl+shift+V
or cmd+V
) in Normal Mode. Do not press i
for Insert Mode. The a
and b
should be aligned with a single tab indent. You can even do this while ssh-ing to a remote machine (the remote machine will need vim 8+).
Now try the old way, which will autoindent the second line with an extra tab: Press i
for Insert Mode. Then paste using ctrl+shift+V
or cmd+V
. The a
and b
are misaligned now.
Installing Vim 8
Ubuntu 18.04 - comes with Vim 8 by default.
Ubuntu 16.04 - install from a PPA.
sudo add-apt-repository ppa:jonathonf/vim
sudo apt update
sudo apt install vim
brew install vim
Well, your code worked for me (running Chrome 5.0.307.9 and Firefox 3.5.8 on Ubuntu 9.10), though I switched
overflow-y: scroll;
to
overflow-y: auto;
Demo page over at: http://davidrhysthomas.co.uk/so/tableDiv.html.
xhtml below:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Div in table</title>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css" />
<style type="text/css" media="all">
th {border-bottom: 2px solid #ccc; }
th,td {padding: 0.5em 1em;
margin: 0;
border-collapse: collapse;
}
tr td:first-child
{border-right: 2px solid #ccc; }
td > div {width: 249px;
height: 299px;
background-color:Gray;
overflow-y: auto;
max-width:230px;
max-height:100px;
}
</style>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<div>
<table>
<thead>
<tr><th>This is column one</th><th>This is column two</th><th>This is column three</th>
</thead>
<tbody>
<tr><td>This is row one</td><td>data point 2.1</td><td>data point 3.1</td>
<tr><td>This is row two</td><td>data point 2.2</td><td>data point 3.2</td>
<tr><td>This is row three</td><td>data point 2.3</td><td>data point 3.3</td>
<tr><td>This is row four</td><td><div><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies mattis dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum a accumsan purus. Vivamus semper tempus nisi et convallis. Aliquam pretium rutrum lacus sed auctor. Phasellus viverra elit vel neque lacinia ut dictum mauris aliquet. Etiam elementum iaculis lectus, laoreet tempor ligula aliquet non. Mauris ornare adipiscing feugiat. Vivamus condimentum luctus tortor venenatis fermentum. Maecenas eu risus nec leo vehicula mattis. In nisi nibh, fermentum vitae tincidunt non, mattis eu metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc vel est purus. Ut accumsan, elit non lacinia porta, nibh magna pretium ligula, sed iaculis metus tortor aliquam urna. Duis commodo tincidunt aliquam. Maecenas in augue ut ligula sodales elementum quis vitae risus. Vivamus mollis blandit magna, eu fringilla velit auctor sed.</p></div></td><td>data point 3.4</td>
<tr><td>This is row five</td><td>data point 2.5</td><td>data point 3.5</td>
<tr><td>This is row six</td><td>data point 2.6</td><td>data point 3.6</td>
<tr><td>This is row seven</td><td>data point 2.7</td><td>data point 3.7</td>
</body>
</table>
</div>
</body>
</html>
On PostgreSQL you can use:
SELECT * FROM table_name WHERE (boolean_column IS NULL OR NOT boolean_column)
This solution has been working for me:
?
+ /
)This will dump out all of the debug data and also your NSLogs.
To filter just your NSLog statements:
NSLog(@"^ Test Log")
This is what you should get:
You can declare an event with the following code:
public event EventHandler MyOwnEvent;
A custom delegate type instead of EventHandler can be used if needed.
You can find detailed information/tutorials on the use of events in .NET in the article Events Tutorial (MSDN).
According to the Wordpress documentation, you should use wp_localize_script()
in your functions.php file. This will create a Javascript Object in the header, which will be available to your scripts at runtime.
See Codex
Example:
<?php wp_localize_script('mylib', 'WPURLS', array( 'siteurl' => get_option('siteurl') )); ?>
To access this variable within in Javascript, you would simply do:
<script type="text/javascript">
var url = WPURLS.siteurl;
</script>
There is no simple command available to find out the largest files/directories on a Linux/UNIX/BSD filesystem. However, combination of following three commands (using pipes) you can easily find out list of largest files:
# du -a /var | sort -n -r | head -n 10
If you want more human readable output try:
$ cd /path/to/some/var
$ du -hsx * | sort -rh | head -10
Where,
Here are 535 ways to reload a page using javascript, very cool:
Here are the first 20:
location = location
location = location.href
location = window.location
location = self.location
location = window.location.href
location = self.location.href
location = location['href']
location = window['location']
location = window['location'].href
location = window['location']['href']
location = window.location['href']
location = self['location']
location = self['location'].href
location = self['location']['href']
location = self.location['href']
location.assign(location)
location.replace(location)
window.location.assign(location)
window.location.replace(location)
self.location.assign(location)
and the last 10:
self['location']['replace'](self.location['href'])
location.reload()
location['reload']()
window.location.reload()
window['location'].reload()
window.location['reload']()
window['location']['reload']()
self.location.reload()
self['location'].reload()
self.location['reload']()
self['location']['reload']()
#childRightCol_x000D_
{_x000D_
float:right;_x000D_
}_x000D_
#childLeftCol_x000D_
{_x000D_
float:left;_x000D_
}_x000D_
#parent_x000D_
{_x000D_
display:inline;_x000D_
}
_x000D_
the best way i found was to set the image you want to view responsively as a background image and sent a css property for the div as cover.
background-image : url('YOUR URL');
background-size : cover
I would recommend storing these as numbers in columns of type varchar - one column per "field" (like contry code etc.).
The format should be applied when you interact with a user... that makes it easier to account for format changes for example and will help esp. when your application goes international...
Here is the code you need:
start cmd.exe @cmd /k "Command"
I understand where the problem lies and when I look at the specs its clear that unescaped single quotes should be parsed correctly.
I am using jquery`s jQuery.parseJSON function to parse the JSON string but still getting the parse error when there is a single quote in the data that is prepared with json_encode.
Could it be a mistake in my implementation that looks like this (PHP - server side):
$data = array();
$elem = array();
$elem['name'] = 'Erik';
$elem['position'] = 'PHP Programmer';
$data[] = json_encode($elem);
$elem = array();
$elem['name'] = 'Carl';
$elem['position'] = 'C Programmer';
$data[] = json_encode($elem);
$jsonString = "[" . implode(", ", $data) . "]";
The final step is that I store the JSON encoded string into an JS variable:
<script type="text/javascript">
employees = jQuery.parseJSON('<?=$marker; ?>');
</script>
If I use "" instead of '' it still throws an error.
SOLUTION:
The only thing that worked for me was to use bitmask JSON_HEX_APOS to convert the single quotes like this:
json_encode($tmp, JSON_HEX_APOS);
Is there another way of tackle this issue? Is my code wrong or poorly written?
Thanks
You cannot read text strings with csvread. Here is another solution:
fid1 = fopen('test.csv','r'); %# open csv file for reading
fid2 = fopen('new.csv','w'); %# open new csv file
while ~feof(fid1)
line = fgets(fid1); %# read line by line
A = sscanf(line,'%*[^,],%f,%f'); %# sscanf can read only numeric data :(
if A(2)<4.185 %# test the values
fprintf(fid2,'%s',line); %# write the line to the new file
end
end
fclose(fid1);
fclose(fid2);
Here's one way in XSLT 2
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="text()"> <xsl:value-of select="translate(.,'"','''')"/> </xsl:template> </xsl:stylesheet>
Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:variable name="apos">'</xsl:variable> <xsl:template match="text()"> <xsl:value-of select="translate(.,'"',$apos)"/> </xsl:template> </xsl:stylesheet>
Not recommended for serious deployments, but here is essentially a "wait x seconds" command.
With docker-compose
version 3.4
a start_period
instruction has been added to healthcheck
. This means we can do the following:
docker-compose.yml
:
version: "3.4"
services:
# your server docker container
zmq_server:
build:
context: ./server_router_router
dockerfile: Dockerfile
# container that has to wait
zmq_client:
build:
context: ./client_dealer/
dockerfile: Dockerfile
depends_on:
- zmq_server
healthcheck:
test: "sh status.sh"
start_period: 5s
status.sh
:
#!/bin/sh
exit 0
What happens here is that the healthcheck
is invoked after 5 seconds. This calls the status.sh
script, which always returns "No problem".
We just made zmq_client
container wait 5 seconds before starting!
Note: It's important that you have version: "3.4"
. If the .4
is not there, docker-compose complains.
assign
is good, but I have not found a function for referring back to the variable you've created in an automated script. (as.name
seems to work the opposite way). More experienced coders will doubtless have a better solution, but this solution works and is slightly humorous perhaps, in that it gets R to write code for itself to execute.
Say I have just assigned value 5 to x
(var.name <- "x"; assign(var.name, 5)
) and I want to change the value to 6. If I am writing a script and don't know in advance what the variable name (var.name
) will be (which seems to be the point of the assign
function), I can't simply put x <- 6
because var.name
might have been "y"
. So I do:
var.name <- "x"
#some other code...
assign(var.name, 5)
#some more code...
#write a script file (1 line in this case) that works with whatever variable name
write(paste0(var.name, " <- 6"), "tmp.R")
#source that script file
source("tmp.R")
#remove the script file for tidiness
file.remove("tmp.R")
x
will be changed to 6, and if the variable name was anything other than "x"
, that variable will similarly have been changed to 6.
Just think about the jquery-ui menu as being the verticle dropdown when you hover over a topic on your main horizonal menu. That way, you have a separate jquery ui menu for each topic on your main menu. The horizonal main menu is just a collection of float:left divs wrapped in a mainmenu div. You then use the hover in and hover out to pop up each menu.
$('.mainmenuitem').hover(
function(){
$(this).addClass('ui-state-focus');
$(this).addClass('ui-corner-all');
$(this).addClass('ui-state-hover');
$(this).addClass('ui-state-active');
$(this).addClass('mainmenuhighlighted');
// trigger submenu
var position=$(this).offset();
posleft=position.left;
postop=position.top;
submenu=$(this).attr('submenu');
showSubmenu(posleft,postop,submenu);
},
function(){
$(this).removeClass('ui-state-focus');
$(this).removeClass('ui-corner-all');
$(this).removeClass('ui-state-hover');
$(this).removeClass('ui-state-active');
$(this).removeClass('mainmenuhighlighted');
// remove submenu
$('.submenu').hide();
}
);
The showSubmenu function is simple - it just positions the submenu and shows it.
function showSubmenu(left,top,submenu){
var tPosX=left;
var tPosY=top+28;
$('#'+submenu).css({left:tPosX, top:tPosY,position:'absolute'});
$('#'+submenu).show();
}
You then need to make sure the submenu is visible while your cursor is on it and disappears when you leave (this should be in your document.ready function.
$('.submenu').hover(
function(){
$(this).show();
},
function(){
$(this).hide();
}
);
Also don't forget to hide your submenus to start with - in the document.ready function
$(".submenu" ).hide();
See the full code here
I believe an UPDATE FROM
with a JOIN
will help:
UPDATE
Sales_Import
SET
Sales_Import.AccountNumber = RAN.AccountNumber
FROM
Sales_Import SI
INNER JOIN
RetrieveAccountNumber RAN
ON
SI.LeadID = RAN.LeadID;
UPDATE
Sales_Import SI,
RetrieveAccountNumber RAN
SET
SI.AccountNumber = RAN.AccountNumber
WHERE
SI.LeadID = RAN.LeadID;
You could get the days in the date by using the DAY() function:
dateadd(day, -1, dateadd(month, 1, dateadd(day, 1 - day(date), date)))
I've seen scripts just use variable assignment to do the job:
$ xyz=`echo -e 'foo \n bar'`
$ echo $xyz
foo bar
Whitespace is automatically coalesced and trimmed. One has to be careful of shell metacharacters (potential injection risk).
I would also recommend always double-quoting variable substitutions in shell conditionals:
if [ -n "$var" ]; then
since something like a -o or other content in the variable could amend your test arguments.
The other answers were not completely satisfying to me. Here's what worked for postgresql-9.1 on Xubuntu 12.04.1 LTS.
Connect to the default database with user postgres:
sudo -u postgres psql template1
Set the password for user postgres, then exit psql (Ctrl-D):
ALTER USER postgres with encrypted password 'xxxxxxx';
Edit the pg_hba.conf
file:
sudo vim /etc/postgresql/9.1/main/pg_hba.conf
and change "peer" to "md5" on the line concerning postgres:
local all postgres
peermd5
To know what version of postgresql you are running, look for the version folder under /etc/postgresql
. Also, you can use Nano or other editor instead of VIM.
Restart the database :
sudo /etc/init.d/postgresql restart
(Here you can check if it worked with psql -U postgres
).
Create a user having the same name as you (to find it, you can type whoami
):
sudo createuser -U postgres -d -e -E -l -P -r -s
<my_name>
The options tell postgresql to create a user that can login, create databases, create new roles, is a superuser, and will have an encrypted password. The really important ones are -P -E, so that you're asked to type the password that will be encrypted, and -d so that you can do a createdb
.
Beware of passwords: it will first ask you twice the new password (for the new user), repeated, and then once the postgres password (the one specified on step 2).
Again, edit the pg_hba.conf
file (see step 3 above), and change "peer" to "md5" on the line concerning "all" other users:
local all all
peermd5
Restart (like in step 4), and check that you can login without -U postgres:
psql template1
Note that if you do a mere psql
, it will fail since it will try to connect you to a default database having the same name as you (i.e. whoami
). template1 is the admin database that is here from the start.
Now createdb <dbname>
should work.
You could do $stmt->queryString
to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0
. The last element is at index n-1
, where n
is the Size
of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1
, you're going to get an error.
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1
because index
is no longer less than Length
.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <=
there? index
will now be out of range in the last loop iteration, because the loop thinks that Length
is a valid index, but it is not.
Lists work the same way, except that you generally use Count
instead of Length
. They still start at zero, and end at Count - 1
.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach
, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
This little example shows how the $rootScope
emit a event that will be listen by a children scope in another controller.
(function(){
angular
.module('ExampleApp',[]);
angular
.module('ExampleApp')
.controller('ExampleController1', Controller1);
Controller1.$inject = ['$rootScope'];
function Controller1($rootScope) {
var vm = this,
message = 'Hi my children scope boy';
vm.sayHi = sayHi;
function sayHi(){
$rootScope.$broadcast('greeting', message);
}
}
angular
.module('ExampleApp')
.controller('ExampleController2', Controller2);
Controller2.$inject = ['$scope'];
function Controller2($scope) {
var vm = this;
$scope.$on('greeting', listenGreeting)
function listenGreeting($event, message){
alert(['Message received',message].join(' : '));
}
}
})();
http://codepen.io/gpincheiraa/pen/xOZwqa
The answer of @gayathri bottom explain technically the differences of all those methods in the scope angular concept and their implementations $scope
and $rootScope
.
this.props.history.goBack();
This is the correct solution for react-router v4
But one thing you should keep in mind is that you need to make sure this.props.history is existed.
That means you need to call this function this.props.history.goBack();
inside the component that is wrapped by < Route/>
If you call this function in a component that deeper in the component tree, it will not work.
EDIT:
If you want to have history object in the component that is deeper in the component tree (which is not wrapped by < Route>), you can do something like this:
...
import {withRouter} from 'react-router-dom';
class Demo extends Component {
...
// Inside this you can use this.props.history.goBack();
}
export default withRouter(Demo);
I think Pandas is the best way to go. There is already one answer here with Pandas using ExcelFile
function, but it did not work properly for me. From here I found the read_excel
function which works just fine:
import pandas as pd
dfs = pd.read_excel("your_file_name.xlsx", sheet_name="your_sheet_name")
print(dfs.head(10))
P.S. You need to have the xlrd
installed for read_excel
function to work
Update 21-03-2020: As you may see here, there are issues with the xlrd
engine and it is going to be deprecated. The openpyxl
is the best replacement. So as described here, the canonical syntax should be:
dfs = pd.read_excel("your_file_name.xlsx", sheet_name="your_sheet_name", engine="openpyxl")
You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend
import matplotlib.pyplot as plt
plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)
plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
Used the Accepted Answer to do a check for IE and convert the dataURI to UInt8Array; an accepted form by PDFJS
Ext.isIE ? pdfAsDataUri = me.convertDataURIToBinary(pdfAsDataUri): '';_x000D_
_x000D_
convertDataURIToBinary: function(dataURI) {_x000D_
var BASE64_MARKER = ';base64,',_x000D_
base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length,_x000D_
base64 = dataURI.substring(base64Index),_x000D_
raw = window.atob(base64),_x000D_
rawLength = raw.length,_x000D_
array = new Uint8Array(new ArrayBuffer(rawLength));_x000D_
_x000D_
for (var i = 0; i < rawLength; i++) {_x000D_
array[i] = raw.charCodeAt(i);_x000D_
}_x000D_
return array;_x000D_
},
_x000D_
The basic technique (on most modern systems) is to subtract the two numbers and then to check the sign bit of the result, i.e. see if the result is greater than/equal to/less than zero. In the assembly code instead of getting the result directly (into a register), you normally just branch depending on the state:
; Compare r1 and r2
CMP $r1, $r2
JLT lessthan
greater_or_equal:
; print "r1 >= r2" somehow
JMP l1
lessthan:
; print "r1 < r2" somehow
l1:
You can use unset
:
unset($array['key-here']);
Example:
$array = array("key1" => "value1", "key2" => "value2");
print_r($array);
unset($array['key1']);
print_r($array);
unset($array['key2']);
print_r($array);
Output:
Array
(
[key1] => value1
[key2] => value2
)
Array
(
[key2] => value2
)
Array
(
)
To expand on Ryan's answer, when you are declaring variables (using Dim) you can cheat a little bit by using the predictive text feature in the VBE, as in the image below.
If it shows up in that list, then you can assign an object of that type to a variable. So not just a Worksheet, as Ryan pointed out, but also a Chart, Range, Workbook, Series and on and on.
You set that variable equal to the object you want to manipulate and then you can call methods, pass it to functions, etc, just like Ryan pointed out for this example. You might run into a couple snags when it comes to collections vs objects (Chart or Charts, Range or Ranges, etc) but with trial and error you'll get it for sure.
Most of these answers are either far too complicated or don't seem to work for me (e.g. System.Windows.Input doesn't seem to exist). Then I found some sample code which works fine: http://www.switchonthecode.com/tutorials/winforms-accessing-mouse-and-keyboard-state
In case the page disappears in the future I am posting the relevant source code below:
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace MouseKeyboardStateTest
{
public abstract class Keyboard
{
[Flags]
private enum KeyStates
{
None = 0,
Down = 1,
Toggled = 2
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern short GetKeyState(int keyCode);
private static KeyStates GetKeyState(Keys key)
{
KeyStates state = KeyStates.None;
short retVal = GetKeyState((int)key);
//If the high-order bit is 1, the key is down
//otherwise, it is up.
if ((retVal & 0x8000) == 0x8000)
state |= KeyStates.Down;
//If the low-order bit is 1, the key is toggled.
if ((retVal & 1) == 1)
state |= KeyStates.Toggled;
return state;
}
public static bool IsKeyDown(Keys key)
{
return KeyStates.Down == (GetKeyState(key) & KeyStates.Down);
}
public static bool IsKeyToggled(Keys key)
{
return KeyStates.Toggled == (GetKeyState(key) & KeyStates.Toggled);
}
}
}
IRIs do not replace URIs, because only URIs (effectively, ASCII) are permissible in some contexts -- including HTTP.
Instead, you specify an IRI and it gets transformed into a URI when going out on the wire.
You should have a look into JSON-P - that was a perfect solution for me when I had that problem:
https://en.wikipedia.org/wiki/JSONP
You basically define a javascript file that loads all your data and another javascript file that processes and displays it. That gets rid of the ugly scrollbar of iframes.
A combination of @Jack's answer and @ranierbit's answer should do the trick.
Set the ng build flag for --output-hashing so:
ng build --output-hashing=all
Then add this class either in a service or in your app.module
@Injectable()
export class NoCacheHeadersInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const authReq = req.clone({
setHeaders: {
'Cache-Control': 'no-cache',
Pragma: 'no-cache'
}
});
return next.handle(authReq);
}
}
Then add this to your providers in your app.module
:
providers: [
... // other providers
{
provide: HTTP_INTERCEPTORS,
useClass: NoCacheHeadersInterceptor,
multi: true
},
... // other providers
]
This should prevent caching issues on live sites for client machines
It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.
Simply Try this:
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("data is: {0}", Convert.ToChar(n));
I have the problem anyway with -lm added
gcc -Wall -lm mtest.c -o mtest.o
mtest.c: In function 'f1':
mtest.c:6:12: warning: unused variable 'res' [-Wunused-variable]
/tmp/cc925Nmf.o: In function `f1':
mtest.c:(.text+0x19): undefined reference to `sin'
collect2: ld returned 1 exit status
I discovered recently that it does not work if you first specify -lm. The order matters:
gcc mtest.c -o mtest.o -lm
Just link without problems
So you must specify the libraries after.
Sample code:
public static '<'T'>' boolean isListDifferent(List'<'T'>' previousList,
List'<'T'>' newList) {
int sizePrevoisList = -1;
int sizeNewList = -1;
if (previousList != null && !previousList.isEmpty()) {
sizePrevoisList = previousList.size();
}
if (newList != null && !newList.isEmpty()) {
sizeNewList = newList.size();
}
if ((sizePrevoisList == -1) && (sizeNewList == -1)) {
return false;
}
if (sizeNewList != sizePrevoisList) {
return true;
}
List n_prevois = new ArrayList(previousList);
List n_new = new ArrayList(newList);
try {
Collections.sort(n_prevois);
Collections.sort(n_new);
} catch (ClassCastException exp) {
return true;
}
for (int i = 0; i < sizeNewList; i++) {
Object obj_prevois = n_prevois.get(i);
Object obj_new = n_new.get(i);
if (obj_new.equals(obj_prevois)) {
// Object are same
} else {
return true;
}
}
return false;
}
Why not try using the following:
$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');
To resolve I did the following:
sqljdbc_auth.dll
into dir: C:\Windows\System32
To retrieve data from database:
private SqlConnection Conn;
private void CreateConnection()
{
string ConnStr =
ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
Conn = new SqlConnection(ConnStr);
}
public DataTable getData()
{
CreateConnection();
string SqlString = "SELECT * FROM TableName WHERE SomeID = @SomeID;";
SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
DataTable dt = new DataTable();
try
{
Conn.Open();
sda.Fill(dt);
}
catch (SqlException se)
{
DBErLog.DbServLog(se, se.ToString());
}
finally
{
Conn.Close();
}
return dt;
}
You can simply do it with train_test_split()
method available in Scikit learn:
from sklearn.model_selection import train_test_split
train, test = train_test_split(X, test_size=0.25, stratify=X['YOUR_COLUMN_LABEL'])
I have also prepared a short GitHub Gist which shows how stratify
option works:
https://gist.github.com/SHi-ON/63839f3a3647051a180cb03af0f7d0d9
I had the missing separator file in Makefiles generated by qmake. I was porting Qt code to a different platform. I didn't have QMAKESPEC nor MAKE set. Here's the link I found the answer:
https://forum.qt.io/topic/3783/missing-separator-error-in-makefile/5
Apache/2.4.33 (Win64) PHP/7.2.4 myHomeBrew stack
At end of php.ini I use the following to manage Xdebug for use with PhpStorm
; jch ~ Sweet analizer at https://xdebug.org/wizard.php for matching xdebug to php version.
; jch ~ When upgrading php versions check if newer xdebug.dll is needed in ext directory.
; jch Renamed... zend_extension = E:\x64Stack\PHP\php7.2.4\ext\php_xdebug-2.6.0-7.2-vc15-x86_64.dll
zend_extension = E:\x64Stack\PHP\php7.2.4\ext\php_xdebug.dll
; jch !!!! Added the following for Xdebug with PhpStorm
[Xdebug]
; zend_extension=<full_path_to_xdebug_extension>
; xdebug.remote_host=<the host where PhpStorm is running (e.g. localhost)>
; xdebug.remote_port=<the port to which Xdebug tries to connect on the host where PhpStorm is running (default 9000)>
xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.profiler_enable=1
xdebug.profiler_output_dir="E:\x64Stack\Xdebug_profiler_output"
xdebug.idekey=PHPSTORM
xdebug.remote_autostart=1
; jch ~~~~~~~~~To turn Xdebug off(disable) uncomment the following 3 lines restart Apache~~~~~~~~~
;xdebug.remote_autostart=0
;xdebug.remote_enable=0
;xdebug.profiler_enable=0
; !!! Might get a little more speed by also commenting out this line above...
;;; zend_extension = E:\x64Stack\PHP\php7.2.4\ext\php_xdebug.dll
; so that Xdebug is both disabled AND not loaded
git-cola is a great GUI and also has this feature built-in. Just select the lines to stage and press S. If no selection is made, the complete hunk is staged.
var customView = UIView()
@IBAction func drawView(_ sender: AnyObject) {
customView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 200)
customView.backgroundColor = UIColor.black //give color to the view
customView.center = self.view.center
self.view.addSubview(customView)
}
I'VE SOLVED THIS WAY:
In my Windows8 64 bit, just restart
ing the service: postgresql-x64-9.5
Windows batch log file name in 2018-02-08_14.32.06.34.log format:
setlocal
set d=%DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%
set t=%time::=.%
set t=%t: =%
set logfile="%d%_%t%.log"
ping localhost -n 11>%1/%logfile%
endlocal
Here is what I ended up doing to work around the error.
First, I set up the database recovery model as SIMPLE. More information here.
Then, by deleting some old files I was able to make 5GB of free space which gave the log file more space to grow.
I reran the DELETE statement sucessfully without any warning.
I thought that by running the DELETE statement the database would inmediately become smaller thus freeing space in my hard drive. But that was not true. The space freed after a DELETE statement is not returned to the operating system inmediatedly unless you run the following command:
DBCC SHRINKDATABASE (MyDb, 0);
GO
More information about that command here.
I have adapted the solution of Biju:
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonPathArgumentResolver implements HandlerMethodArgumentResolver{
private static final String JSONBODYATTRIBUTE = "JSON_REQUEST_BODY";
private ObjectMapper om = new ObjectMapper();
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(JsonArg.class);
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
String jsonBody = getRequestBody(webRequest);
JsonNode rootNode = om.readTree(jsonBody);
JsonNode node = rootNode.path(parameter.getParameterName());
return om.readValue(node.toString(), parameter.getParameterType());
}
private String getRequestBody(NativeWebRequest webRequest){
HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
String jsonBody = (String) webRequest.getAttribute(JSONBODYATTRIBUTE, NativeWebRequest.SCOPE_REQUEST);
if (jsonBody==null){
try {
jsonBody = IOUtils.toString(servletRequest.getInputStream());
webRequest.setAttribute(JSONBODYATTRIBUTE, jsonBody, NativeWebRequest.SCOPE_REQUEST);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return jsonBody;
}
}
What's the different:
BR
The reason in my case was completely different. I was trying to open a Feed dialog automatically after page load. And 9 times of 10 it displayed this error. First, I added show_error: true
parameter as suggested by @Peter Roome, but it didn't help, displaying 104: Invalid signature
, not descriptive at all.
Then I figured out the reason. The code was in $(document).ready
jQuery function. And it seems that some facebook stuff had not yet been loaded at the point the code was to be executed. I moved the code to $(window).load
block (which is executed after all page content is loaded), and the problem has been solved.
Yes I got the trick.
public void onClick(View v) {
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH ){
imgDisplay.setSystemUiVisibility( View.SYSTEM_UI_FLAG_HIDE_NAVIGATION );
}
else if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB )
imgDisplay.setSystemUiVisibility( View.STATUS_BAR_HIDDEN );
else{}
}
But it didn't solve my problem completely. I want to hide the horizontal scrollview too, which is in front of the imageView (below), which can't be hidden in this.
I added @Component
annotation from import org.springframework.stereotype.Component
and the problem was solved.
You have to use getStackTrace ()
method instead of printStackTrace()
. Here is a good example:
import java.io.*;
/**
* Simple utilities to return the stack trace of an
* exception as a String.
*/
public final class StackTraceUtil {
public static String getStackTrace(Throwable aThrowable) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
aThrowable.printStackTrace(printWriter);
return result.toString();
}
/**
* Defines a custom format for the stack trace as String.
*/
public static String getCustomStackTrace(Throwable aThrowable) {
//add the class name and any message passed to constructor
final StringBuilder result = new StringBuilder( "BOO-BOO: " );
result.append(aThrowable.toString());
final String NEW_LINE = System.getProperty("line.separator");
result.append(NEW_LINE);
//add each element of the stack trace
for (StackTraceElement element : aThrowable.getStackTrace() ){
result.append( element );
result.append( NEW_LINE );
}
return result.toString();
}
/** Demonstrate output. */
public static void main (String... aArguments){
final Throwable throwable = new IllegalArgumentException("Blah");
System.out.println( getStackTrace(throwable) );
System.out.println( getCustomStackTrace(throwable) );
}
}
Another version which is simple
BiFunction<TreeSet<Employee>,List<Employee> ,TreeSet<Employee>> appendTree = (y,x) -> (y.addAll(x))? y:y;
TreeSet<Employee> outputList = appendTree.apply(new TreeSet<Employee>(Comparator.comparing(p->p.getId())),personList);
Adding the following gem to my Gemfile solved the issue:
gem 'therubyracer'
Then bundle your new dependencies:
$ bundle install
Following @Daniel's comment and thanks to @Tom's answer, I found out that Git bash was indeed using the PATH but not the latest paths I recently installed. To work around this problem, I added a file in my home (windows) directory named:
.bashrc
and the content as follow:
PATH=$PATH:/c/Go/bin
because I was installing Go and this path contained the executable go.exe
Now Git bash was able to recognize the command:
go
Perhaps just a system reboot would have been enough in my case, but I'm happy that this solution work in any case.
I had the same requirement in my development so I did research on this. I have read many articles and tried many solutions during last two days like jQuery.tabNext() plugin.
I had some trouble with IE11 (all IE version has this bug). When an input text followed by non text input the selection was not cleared. So I have created my own tabNext() method based on @Sarfraz solution suggestion. I was also thinking on how it should behave (only circle in the current form or maybe through the full document). I still did not take care of the tabindex property mostly because I am using it occasionally. But I will not forget it.
In order to my contribution can be useful for everybody easily I have created jsfiddle example here https://jsfiddle.net/mkrivan/hohx4nes/
I include also the JavaScript part of the example here:
function clearSelection() {
if (document.getSelection) { // for all new browsers (IE9+, Chrome, Firefox)
document.getSelection().removeAllRanges();
document.getSelection().addRange(document.createRange());
console.log("document.getSelection");
} else if (window.getSelection) { // equals with the document.getSelection (MSDN info)
if (window.getSelection().removeAllRanges) { // for all new browsers (IE9+, Chrome, Firefox)
window.getSelection().removeAllRanges();
window.getSelection().addRange(document.createRange());
console.log("window.getSelection.removeAllRanges");
} else if (window.getSelection().empty) { // maybe for old Chrome
window.getSelection().empty();
console.log("window.getSelection.empty");
}
} else if (document.selection) { // IE8- deprecated
document.selection.empty();
console.log("document.selection.empty");
}
}
function focusNextInputElement(node) { // instead of jQuery.tabNext();
// TODO: take the tabindex into account if defined
if (node !== null) {
// stay in the current form
var inputs = $(node).parents("form").eq(0).find(":input:visible:not([disabled]):not([readonly])");
// if you want through the full document (as TAB key is working)
// var inputs = $(document).find(":input:visible:not([disabled]):not([readonly])");
var idx = inputs.index(node) + 1; // next input element index
if (idx === inputs.length) { // at the end start with the first one
idx = 0;
}
var nextInputElement = inputs[idx];
nextInputElement.focus(); // handles submit buttons
try { // if next input element does not support select()
nextInputElement.select();
} catch (e) {
}
}
}
function tabNext() {
var currentActiveNode = document.activeElement;
clearSelection();
focusNextInputElement(currentActiveNode);
}
function stopReturnKey(e) {
var e = (e) ? e : ((event) ? event : null);
if (e !== null) {
var node = (e.target) ? e.target : ((e.srcElement) ? e.srcElement : null);
if (node !== null) {
var requiredNode = $(node).is(':input')
// && !$(node).is(':input[button]')
// && !$(node).is(':input[type="submit"]')
&& !$(node).is('textarea');
// console.log('event key code ' + e.keyCode + '; required node ' + requiredNode);
if ((e.keyCode === 13) && requiredNode) {
try {
tabNext();
// clearSelection();
// focusNextInputElement(node);
// jQuery.tabNext();
console.log("success");
} catch (e) {
console.log("error");
}
return false;
}
}
}
}
document.onkeydown = stopReturnKey;
I left commented rows as well so my thinking can be followed.
If you take a look at the bootstraps fade
class used with the modal window you will find, that all it does, is to set the opacity
value to 0
and adds a transition for the opacity
rule.
Whenever you launch a modal the in
class is added and will change the opacity
to a value of 1
.
Knowing that you can easily build your own fade-scale
class.
Here is an example.
@import url("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css");_x000D_
_x000D_
.fade-scale {_x000D_
transform: scale(0);_x000D_
opacity: 0;_x000D_
-webkit-transition: all .25s linear;_x000D_
-o-transition: all .25s linear;_x000D_
transition: all .25s linear;_x000D_
}_x000D_
_x000D_
.fade-scale.in {_x000D_
opacity: 1;_x000D_
transform: scale(1);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
<!-- Button trigger modal -->_x000D_
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">_x000D_
Launch demo modal_x000D_
</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade-scale" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">_x000D_
<div class="modal-dialog" role="document">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>_x000D_
<h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
..._x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
<button type="button" class="btn btn-primary">Save changes</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
-- UPDATE --
This answer is getting more up votes lately so i figured i add an update to show how easy it is to customize the BS modal in and out animations with the help of the great Animate.css library by
Daniel Eden.
All that needs to be done is to include the stylesheet to your <head></head>
section. Now you simply need to add the animated
class, plus one of the entrance classes of the library to the modal element.
<div class="modal animated fadeIn" id="myModal" tabindex="-1" role="dialog" ...>
...
</div>
But there is also a way to add an out animation to the modal window and since the library has a bunch of cool animations that will make an element disappear, why not use them. :)
To use them you will need to toggle the classes on the modal element, so it is actually better to call the modal window via JavaScript, which is described here.
You will also need to listen for some of the modal events to know when it's time to add or remove the classes from the modal element. The events being fired are described here.
To trigger a custom out animation you can't use the data-dismiss="modal"
attribute on a button
inside the modal window that's suppose to close the modal. You can simply add your own attribute like data-custom-dismiss="modal"
and use that to call the $('selector').modal.('hide')
method on it.
Here is an example that shows all the different possibilities.
/* -------------------------------------------------------_x000D_
| This first part can be ignored, it is just getting_x000D_
| all the different entrance and exit classes of the_x000D_
| animate-config.json file from the github repo._x000D_
--------------------------------------------------------- */_x000D_
_x000D_
var animCssConfURL = 'https://api.github.com/repos/daneden/animate.css/contents/animate-config.json';_x000D_
var selectIn = $('#animation-in-types');_x000D_
var selectOut = $('#animation-out-types');_x000D_
var getAnimCSSConfig = function ( url ) { return $.ajax( { url: url, type: 'get', dataType: 'json' } ) };_x000D_
var decode = function ( data ) {_x000D_
var bin = Uint8Array.from( atob( data['content'] ), function( char ) { return char.charCodeAt( 0 ) } );_x000D_
var bin2Str = String.fromCharCode.apply( null, bin );_x000D_
return JSON.parse( bin2Str )_x000D_
}_x000D_
var buildSelect = function ( which, name, animGrp ) {_x000D_
var grp = $('<optgroup></optgroup>');_x000D_
grp.attr('label', name);_x000D_
$.each(animGrp, function ( idx, animType ) {_x000D_
var opt = $('<option></option>')_x000D_
opt.attr('value', idx)_x000D_
opt.text(idx)_x000D_
grp.append(opt);_x000D_
})_x000D_
which.append(grp) _x000D_
}_x000D_
getAnimCSSConfig( animCssConfURL )_x000D_
.done (function ( data ) {_x000D_
var animCssConf = decode ( data );_x000D_
$.each(animCssConf, function(name, animGrp) {_x000D_
if ( /_entrances/.test(name) ) {_x000D_
buildSelect(selectIn, name, animGrp);_x000D_
}_x000D_
if ( /_exits/.test(name) ) {_x000D_
buildSelect(selectOut, name, animGrp);_x000D_
}_x000D_
})_x000D_
})_x000D_
_x000D_
_x000D_
/* -------------------------------------------------------_x000D_
| Here is were the fun begins._x000D_
--------------------------------------------------------- */_x000D_
_x000D_
var modalBtn = $('button');_x000D_
var modal = $('#myModal');_x000D_
var animInClass = "";_x000D_
var animOutClass = "";_x000D_
_x000D_
modalBtn.on('click', function() {_x000D_
animInClass = selectIn.find('option:selected').val();_x000D_
animOutClass = selectOut.find('option:selected').val();_x000D_
if ( animInClass == '' || animOutClass == '' ) {_x000D_
alert("Please select an in and out animation type.");_x000D_
} else {_x000D_
modal.addClass(animInClass);_x000D_
modal.modal({backdrop: false});_x000D_
}_x000D_
})_x000D_
_x000D_
modal.on('show.bs.modal', function () {_x000D_
var closeModalBtns = modal.find('button[data-custom-dismiss="modal"]');_x000D_
closeModalBtns.one('click', function() {_x000D_
modal.on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function( evt ) {_x000D_
modal.modal('hide')_x000D_
});_x000D_
modal.removeClass(animInClass).addClass(animOutClass);_x000D_
})_x000D_
})_x000D_
_x000D_
modal.on('hidden.bs.modal', function ( evt ) {_x000D_
var closeModalBtns = modal.find('button[data-custom-dismiss="modal"]');_x000D_
modal.removeClass(animOutClass)_x000D_
modal.off('webkitAnimationEnd oanimationend msAnimationEnd animationend')_x000D_
closeModalBtns.off('click')_x000D_
})
_x000D_
@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');_x000D_
@import url('https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css');_x000D_
_x000D_
select, button:not([data-custom-dismiss="modal"]) {_x000D_
margin: 10px 0;_x000D_
width: 220px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-xs-4 col-xs-offset-4 col-sm-4 col-sm-offset-4">_x000D_
<select id="animation-in-types">_x000D_
<option value="" selected>Choose animation-in type</option>_x000D_
</select>_x000D_
</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-xs-4 col-xs-offset-4 col-sm-4 col-sm-offset-4">_x000D_
<select id="animation-out-types">_x000D_
<option value="" selected>Choose animation-out type</option>_x000D_
</select>_x000D_
</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-xs-4 col-xs-offset-4 col-sm-4 col-sm-offset-4">_x000D_
<button class="btn btn-default">Open Modal</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal animated" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">_x000D_
<div class="modal-dialog" role="document">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-custom-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>_x000D_
<h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
..._x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-custom-dismiss="modal">Close</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
public List<State> GetcountryCodeStates(List<string> countryCodes)
{
List<State> states = new List<State>();
states = (from a in _objdatasources.StateList.AsEnumerable()
where countryCodes.Any(c => c.Contains(a.CountryCode))
select a).ToList();
return states;
}
Since none of the answers have covered an asynchronous way of copying from one stream to another, here is a pattern that I've successfully used in a port forwarding application to copy data from one network stream to another. It lacks exception handling to emphasize the pattern.
const int BUFFER_SIZE = 4096;
static byte[] bufferForRead = new byte[BUFFER_SIZE];
static byte[] bufferForWrite = new byte[BUFFER_SIZE];
static Stream sourceStream = new MemoryStream();
static Stream destinationStream = new MemoryStream();
static void Main(string[] args)
{
// Initial read from source stream
sourceStream.BeginRead(bufferForRead, 0, BUFFER_SIZE, BeginReadCallback, null);
}
private static void BeginReadCallback(IAsyncResult asyncRes)
{
// Finish reading from source stream
int bytesRead = sourceStream.EndRead(asyncRes);
// Make a copy of the buffer as we'll start another read immediately
Array.Copy(bufferForRead, 0, bufferForWrite, 0, bytesRead);
// Write copied buffer to destination stream
destinationStream.BeginWrite(bufferForWrite, 0, bytesRead, BeginWriteCallback, null);
// Start the next read (looks like async recursion I guess)
sourceStream.BeginRead(bufferForRead, 0, BUFFER_SIZE, BeginReadCallback, null);
}
private static void BeginWriteCallback(IAsyncResult asyncRes)
{
// Finish writing to destination stream
destinationStream.EndWrite(asyncRes);
}
using System;
using System.Net;
namespace IPADDRESS
{
class Program
{
static void Main(string[] args)
{
String strHostName = string.Empty;
if (args.Length == 0)
{
/* First get the host name of local machine.*/
strHostName = Dns.GetHostName();
Console.WriteLine("Local Machine's Host Name: " + strHostName);
}
else
{
strHostName = args[0];
}
/* Then using host name, get the IP address list..*/
IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
IPAddress[] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
}
Console.ReadLine();
}
}
}
Using .net core jwt packages, the Claims are available:
[Route("api/[controller]")]
[ApiController]
[Authorize(Policy = "Bearer")]
public class AbstractController: ControllerBase
{
protected string UserId()
{
var principal = HttpContext.User;
if (principal?.Claims != null)
{
foreach (var claim in principal.Claims)
{
log.Debug($"CLAIM TYPE: {claim.Type}; CLAIM VALUE: {claim.Value}");
}
}
return principal?.Claims?.SingleOrDefault(p => p.Type == "username")?.Value;
}
}
For those who are still coming for solution here, the easiest solution would be to use <wsdlLocation>
, without changing any code. Working steps are given below:
src/main/resource
In pom file, add both wsdlDirectory and wsdlLocation(don't miss / at the beginning of wsdlLocation), like below. While wsdlDirectory is used to generate code and wsdlLocation is used at runtime to create dynamic proxy.
<wsdlDirectory>src/main/resources/mydir</wsdlDirectory>
<wsdlLocation>/mydir/my.wsdl</wsdlLocation>
Then in your java code(with no-arg constructor):
MyPort myPort = new MyPortService().getMyPort();
For completeness, I am providing here full code generation part, with fluent api in generated code.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>2.5</version>
<dependencies>
<dependency>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-fluent-api</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-tools</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>wsdl-to-java-generator</id>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<xjcArgs>
<xjcArg>-Xfluent-api</xjcArg>
</xjcArgs>
<keep>true</keep>
<wsdlDirectory>src/main/resources/package</wsdlDirectory>
<wsdlLocation>/package/my.wsdl</wsdlLocation>
<sourceDestDir>${project.build.directory}/generated-sources/annotations/jaxb</sourceDestDir>
<packageName>full.package.here</packageName>
</configuration>
</execution>
</executions>
Use the end() function.
$array = [1,2,3,4,5];
$last = end($array); // 5
I did also stumble upon this error. In my case the problem was I was using JRE6, with support for TLS1.0. The server only supported TLS1.2, so this error was thrown.
the easiest way would be
which means you could just do:
new File(filename).text
Note need root than:
adb root
adb pull /data/data/com.google.android.apps.nexuslauncher/databases/launcher.db launcher.db
This links might be helpful to convert.
https://code.google.com/p/flying-saucer/
https://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html
If it is a college Project, you can even go for these, http://pd4ml.com/examples.htm
Example is given to convert HTML to PDF
You don't encode the entire URL, only parts of it that come from "unreliable sources".
Java:
String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "http://stackoverflow.com/search?q=" + query;
Kotlin:
val query: String = URLEncoder.encode("apples oranges", "utf-8")
val url = "http://stackoverflow.com/search?q=$query"
Alternatively, you can use Strings.urlEncode(String str) of DroidParts that doesn't throw checked exceptions.
Or use something like
String uri = Uri.parse("http://...")
.buildUpon()
.appendQueryParameter("key", "val")
.build().toString();
Properties can't be changed but antContrib vars (http://ant-contrib.sourceforge.net/tasks/tasks/variable_task.html ) can.
Here is a macro to do a find/replace on a var:
<macrodef name="replaceVarText">
<attribute name="varName" />
<attribute name="from" />
<attribute name="to" />
<sequential>
<local name="replacedText"/>
<local name="textToReplace"/>
<local name="fromProp"/>
<local name="toProp"/>
<property name="textToReplace" value = "${@{varName}}"/>
<property name="fromProp" value = "@{from}"/>
<property name="toProp" value = "@{to}"/>
<script language="javascript">
project.setProperty("replacedText",project.getProperty("textToReplace").split(project.getProperty("fromProp")).join(project.getProperty("toProp")));
</script>
<ac:var name="@{varName}" value = "${replacedText}"/>
</sequential>
</macrodef>
Then call the macro like:
<ac:var name="updatedText" value="${oldText}"/>
<current:replaceVarText varName="updatedText" from="." to="_" />
<echo message="Updated Text will be ${updatedText}"/>
Code above uses javascript split then join, which is faster than regex. "local" properties are passed to JavaScript so no property leakage.
For quick reference, all the following methods will add a new key 'a' if it does not exist already or it will update the existing key value pair with the new value offered:
data['a']=1
data.update({'a':1})
data.update(dict(a=1))
data.update(a=1)
You can also mixing them up, for example, if key 'c' is in data but 'd' is not, the following method will updates 'c' and adds 'd'
data.update({'c':3,'d':4})
Cmd] and Cmd[ navigates among split panes in order of use.
You can use fetch to do that:
fetch('some_url')
.then(function (response) {
switch (response.status) {
// status "OK"
case 200:
return response.text();
// status "Not Found"
case 404:
throw response;
}
})
.then(function (template) {
console.log(template);
})
.catch(function (response) {
// "Not Found"
console.log(response.statusText);
});
Asynchronous with arrow function version:
(async () => {
var response = await fetch('some_url');
switch (response.status) {
// status "OK"
case 200:
var template = await response.text();
console.log(template);
break;
// status "Not Found"
case 404:
console.log('Not Found');
break;
}
})();
I know this is an old thread, but it needs a better answer. You shouldn't need to set the permissions to 777, that is a security problem as it gives read and write access to the world. It may be that your apache user does not have read/write permissions on the directory.
Here's what you do in Ubuntu
Make sure all files are owned by the Apache group and user. In Ubuntu it is the www-data group and user
chown -R www-data:www-data /path/to/webserver/www
Next enabled all members of the www-data group to read and write files
chmod -R g+rw /path/to/webserver/www
The php mkdir()
function should now work without returning errors
Just iterate over the transposed of your array:
for column in array.T:
some_function(column)
(Update: If I could delete this answer I would, although since it's accepted, I can't. I'm updating the description to provide better guidance and discourage folks from using the poor practice I outlined in the original answer).
You can specify these parameters via context or environment parameters, such as in context.xml. See the sections titled "Context Parameters" and "Environment Entries" on this page:
http://tomcat.apache.org/tomcat-5.5-doc/config/context.html
As @netjeff points out, these values will be available via the Context.lookup(String) method and not as System parameters.
Another way to do specify these values is to define variables inside of the web.xml file of the web application you're deploying (see below). As @Roberto Lo Giacco points out, this is generally considered a poor practice since a deployed artifact should not be environment specific. However, below is the configuration snippet if you really want to do this:
<env-entry>
<env-entry-name>SMTP_PASSWORD</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>abc123ftw</env-entry-value>
</env-entry>
if you want to find it in MB do this
SELECT table_schema "DB Name",
Round(Sum(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB"
FROM information_schema.tables
GROUP BY table_schema;
import json
def writeToFile(logData, fileName, openOption="w"):
file = open(fileName, openOption)
file.write(json.dumps(json.loads(logData), indent=4))
file.close()
Here's a C# method to do this. Remember to add your own error handling - this mostly assumes that things work for the sake of brevity. It's 4.0+ framework only, but that's mostly because of the optional worksheetNumber
parameter. You can overload the method if you need to support earlier versions.
static void ConvertExcelToCsv(string excelFilePath, string csvOutputFile, int worksheetNumber = 1) {
if (!File.Exists(excelFilePath)) throw new FileNotFoundException(excelFilePath);
if (File.Exists(csvOutputFile)) throw new ArgumentException("File exists: " + csvOutputFile);
// connection string
var cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;IMEX=1;HDR=NO\"", excelFilePath);
var cnn = new OleDbConnection(cnnStr);
// get schema, then data
var dt = new DataTable();
try {
cnn.Open();
var schemaTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (schemaTable.Rows.Count < worksheetNumber) throw new ArgumentException("The worksheet number provided cannot be found in the spreadsheet");
string worksheet = schemaTable.Rows[worksheetNumber - 1]["table_name"].ToString().Replace("'", "");
string sql = String.Format("select * from [{0}]", worksheet);
var da = new OleDbDataAdapter(sql, cnn);
da.Fill(dt);
}
catch (Exception e) {
// ???
throw e;
}
finally {
// free resources
cnn.Close();
}
// write out CSV data
using (var wtr = new StreamWriter(csvOutputFile)) {
foreach (DataRow row in dt.Rows) {
bool firstLine = true;
foreach (DataColumn col in dt.Columns) {
if (!firstLine) { wtr.Write(","); } else { firstLine = false; }
var data = row[col.ColumnName].ToString().Replace("\"", "\"\"");
wtr.Write(String.Format("\"{0}\"", data));
}
wtr.WriteLine();
}
}
}
Until we get SERVER-863 keeping the field names as short as possible is advisable especially where you have a lot of records.
Depending on your use case, field names can have a huge impact on storage. Cant understand why this is not a higher priority for MongoDb, as this will have a positive impact on all users. If nothing else, we can start being more descriptive with our field names, without thinking twice about bandwidth & storage costs.
Please do vote.
You can use native function Date.toLocaleTimeString()
:
var d = new Date();
var n = d.toLocaleTimeString();
This will display e.g.:
"11:33:01"
I found it on http://www.w3schools.com/jsref/jsref_tolocaletimestring.asp
var d = new Date();_x000D_
var n = d.toLocaleTimeString();_x000D_
alert("The time is: \n"+n);
_x000D_
For future reference, you can get help for any command by using the /?
switch, which should explain what switches do what.
According to the set /?
screen, the format for set /p
is SET /P variable=[promptString]
which would indicate that the p in /p
is "prompt." It just prints in your example because <nul
passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.
/L
in for /L
generates a List of numbers.
From ping /?
:
Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
[-r count] [-s count] [[-j host-list] | [-k host-list]]
[-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name
Options:
-t Ping the specified host until stopped.
To see statistics and continue - type Control-Break;
To stop - type Control-C.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-l size Send buffer size.
-f Set Don't Fragment flag in packet (IPv4-only).
-i TTL Time To Live.
-v TOS Type Of Service (IPv4-only. This setting has been deprecated
and has no effect on the type of service field in the IP Header).
-r count Record route for count hops (IPv4-only).
-s count Timestamp for count hops (IPv4-only).
-j host-list Loose source route along host-list (IPv4-only).
-k host-list Strict source route along host-list (IPv4-only).
-w timeout Timeout in milliseconds to wait for each reply.
-R Use routing header to test reverse route also (IPv6-only).
-S srcaddr Source address to use.
-4 Force using IPv4.
-6 Force using IPv6.
Simplest way
"Mr.".split('.').join("");
..............
Console
You could use the UPPER keyword:
SELECT *
FROM Customers
WHERE UPPER(LastName) = UPPER('AnGel')
You are writing to memory you do not own:
int board[2][50]; //make an array with 3 columns (wrong)
//(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
board[2][i] = 'O';
^
Change this line:
int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
^
To:
int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
^
When creating an array, the value used to initialize: [3]
indicates array size.
However, when accessing existing array elements, index values are zero based.
For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]
EDIT To address bad output comment and initialization comment
add an additional "\n" for formatting output:
Change:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
}
...
To:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
printf("\n");//at the end of every row, print a new line
}
...
Initialize board variable:
int board[3][50] = {0};//initialize all elements to zero
Probably a maximized Form helps, or you can do this manually upon form load:
Code Block
this.Location = new Point(0, 0);
this.Size = Screen.PrimaryScreen.WorkingArea.Size;
And then, play with anchoring, so the child controls inside your form automatically fit in your form's new size.
Hope this helps,
as date_format uses the same format as date ( http://www.php.net/manual/en/function.date.php ) the "Numeric representation of a month, without leading zeros" is a lowercase n .. so
echo date('n'); // "9"
As a supplement to above answers - I'm just bumping into a similar problem, and working completely of the default installed python.
When I call the example of the shared object library I'm looking for with LD_LIBRARY_PATH
, I get something like this:
$ LD_LIBRARY_PATH=/path/to/mysodir:$LD_LIBRARY_PATH python example-so-user.py
python: can't open file 'example-so-user.py': [Errno 2] No such file or directory
Notably, it doesn't even complain about the import - it complains about the source file!
But if I force loading of the object using LD_PRELOAD
:
$ LD_PRELOAD=/path/to/mysodir/mypyobj.so python example-so-user.py
python: error while loading shared libraries: libtiff.so.5: cannot open shared object file: No such file or directory
... I immediately get a more meaningful error message - about a missing dependency!
Just thought I'd jot this down here - cheers!
Q. What is Artifact in maven?
ANS: ARTIFACT is a JAR,(WAR or EAR), but it could be also something else. Each artifact has,
Q.Why does Maven need them?
Ans: Maven is used to make them available for our applications.
The function Correlate of numpy works with 2 1D arrays that you want to correlate and returns one correlation value.
Try RGBA, e.g.
div { background-color: rgba(255, 255, 255, 0.5); }
As always, this won't work in every single browser ever written.
In a very rare case, with custom segue, the top most view controller is not in a navigation stack or tab bar controller or presented, but its view is inserted to the top of key windown's subviews.
In such situation, it's necessary to check if UIApplication.shared.keyWindow.subviews.last == self.view
to determine if the current view controller is the top most.
Gradle looks for gradle.properties
files in these places:
GRADLE_USER_HOME
environment variable, which if not set defaults to USER_HOME/.gradle
)Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).
Reference: https://gradle.org/docs/current/userguide/build_environment.html
try to break your large data as much as possible because I already faced number of times this types of problem. In which I have above 10 Lakh records with 15 columns.
I case your observations are classes from Real numbers and you expect that the mode to be 2.5 when your observations are 2, 2, 3, and 3 then you could estimate the mode with mode = l1 + i * (f1-f0) / (2f1 - f0 - f2)
where l1..lower limit of most frequent class, f1..frequency of most frequent class, f0..frequency of classes before most frequent class, f2..frequency of classes after most frequent class and i..Class interval as given e.g. in 1, 2, 3:
#Small Example
x <- c(2,2,3,3) #Observations
i <- 1 #Class interval
z <- hist(x, breaks = seq(min(x)-1.5*i, max(x)+1.5*i, i), plot=F) #Calculate frequency of classes
mf <- which.max(z$counts) #index of most frequent class
zc <- z$counts
z$breaks[mf] + i * (zc[mf] - zc[mf-1]) / (2*zc[mf] - zc[mf-1] - zc[mf+1]) #gives you the mode of 2.5
#Larger Example
set.seed(0)
i <- 5 #Class interval
x <- round(rnorm(100,mean=100,sd=10)/i)*i #Observations
z <- hist(x, breaks = seq(min(x)-1.5*i, max(x)+1.5*i, i), plot=F)
mf <- which.max(z$counts)
zc <- z$counts
z$breaks[mf] + i * (zc[mf] - zc[mf-1]) / (2*zc[mf] - zc[mf-1] - zc[mf+1]) #gives you the mode of 99.5
In case you want the most frequent level and you have more than one most frequent level you can get all of them e.g. with:
x <- c(2,2,3,5,5)
names(which(max(table(x))==table(x)))
#"2" "5"
The easiest way is to use a for loop template tag.
Given the view:
def MyView(request):
...
query_results = YourModel.objects.all()
...
#return a response to your template and add query_results to the context
You can add a snippet like this your template...
<table>
<tr>
<th>Field 1</th>
...
<th>Field N</th>
</tr>
{% for item in query_results %}
<tr>
<td>{{ item.field1 }}</td>
...
<td>{{ item.fieldN }}</td>
</tr>
{% endfor %}
</table>
This is all covered in Part 3 of the Django tutorial. And here's Part 1 if you need to start there.
// inVisible
TabPage page2 = tabControl1.TabPages[0];
page2.Visible= false;
//Visible
page2.Visible= true;
// disable
TabPage page2 = tabControl1.TabPages[0];
page2.Enabled = false;
// enable
page2.Enabled = true;
//Hide
tabCtrlTagInfo.TabPages(0).Hide()
tabCtrlTagInfo.TabPages(0).Show()
Just copy paste and try it,the above code has been tested in vs2010, it works.
try staring jboss with ./standalone.sh -c standalone-full.xml or any other alternative that allows you to start with the full profile
In general terms I would recommend the following:
Return IQueryable<T>
if you want to enable the developer using your method to refine the query you return before executing.
Return IEnumerable
if you want to transport a set of Objects to enumerate over.
Imagine an IQueryable
as that what it is - a "query" for data (which you can refine if you want to). An IEnumerable
is a set of objects (which has already been received or was created) over which you can enumerate.
Excerpt:-
try
{
cnt++;scnt++;now=System.currentTimeMillis();r=rand.nextInt(6);r++;
loc=lm.getLastKnownLocation(best);
if(loc!=null){lat=loc.getLatitude();lng=loc.getLongitude();}
Thread.sleep(100);
handler.sendMessage(handler.obtainMessage());
}
catch (InterruptedException e)
{
Toast.makeText(this, "Error="+e.toString(), Toast.LENGTH_LONG).show();
}
As you can see above, a thread is running alongside main thread of user-interface activity which continuously displays GPS lat,long alongwith current time and a random dice throw.
IF you are curious then just check the full code: GPS Location with a randomized dice throw & current time in separate thread
8B 5D 32
is machine code
mov ebx, [ebp+32h]
is assembly
lmylib.so
containing 8B 5D 32
is object code
I was searching for the same but for Linux shell.
The topic brought me to an answer, -thanks-
Maybe more pythonic manner :
import os
beep = lambda x: os.system("echo -n '\a';sleep 0.2;" * x)
beep(3)
Notes :
os.system
rather then subprocess.Popen
for simplicity (it could be bad)echo
is to have no more displaysleep
is necessary for the resulting text sequence (*x)Use the CSS Flexbox align-items
property to achieve this.
html, body {
height: 100%;
}
body {
display: flex;
align-items: center;
}
_x000D_
<div>This is centered vertically</div>
_x000D_
While the accepted answer by afraisse is absolutely correct in terms of using @RequestParam
, I would further suggest to use an Optional<> as you cannot always ensure the right parameter is used. Also, if you need an Integer or Long just use that data type to avoid casting types later on in the DAO.
@RequestMapping(value="/data", method = RequestMethod.GET)
public @ResponseBody
Item getItem(@RequestParam("itemid") Optional<Integer> itemid) {
if( itemid.isPresent()){
Item i = itemDao.findOne(itemid.get());
return i;
} else ....
}
The solution which worked for me was to upgrade my setuptools:
python3 -m pip install --upgrade pip setuptools wheel
Driver for Huawei was not found. So I've been using the universal ADB driver:
ADBDriverInstaller
and Run the file. Make sure you have connected your device through USB to your computer.Restart
button. Before doing that read this link:
(The above. in brief, says to press Restart button in the dialog box. Select Troubleshoot. Select Advance Option. Select Startup Setting. Press Restart. After system's been restarted, on the appearing screen press 7)
ADBDriverInstaller
file again. Select your device from the options. Press install. And it's done :)
This thread has a good discussion and a useful solution:
function pause( iMilliseconds )
{
var sDialogScript = 'window.setTimeout( function () { window.close(); }, ' + iMilliseconds + ');';
window.showModalDialog('javascript:document.writeln ("<script>' + sDialogScript + '<' + '/script>")');
}
Unfortunately it appears that this doesn't work in some versions of IE, but the thread has many other worthy proposals if that proves to be a problem for you.
Yes you are right. You have placed WHERE
clause wrong. You can only use one WHERE
clause in single query so try AND
for multiple conditions like this:
SELECT table1.f_id FROM table1
INNER JOIN table2
ON table2.f_id = table1.f_id
WHERE table2.f_type = 'InProcess'
AND f_com_id = '430'
AND f_status = 'Submitted'
# Doesn't handle whitespace
for x in `find . -name "*.txt" -print`; do
process_one $x
done
or
# Handles whitespace and newlines
find . -name "*.txt" -print0 | xargs -0 -n 1 process_one
Issue: Tomcat (7.0.88) is throwing below exception which leads to 400 – Bad Request.
java.lang.IllegalArgumentException: Invalid character found in the request target.
The valid characters are defined in RFC 7230 and RFC 3986.
This issue is occurring most of the tomcat versions from 7.0.88 onwards.
Solution: (Suggested by Apache team):
Tomcat increased their security and no longer allows raw square brackets in the query string. In the request we have [,] (Square brackets) so the request is not processed by the server.
Add relaxedQueryChars
attribute under tag under server.xml (%TOMCAT_HOME%/conf):
<Connector port="80"
protocol="HTTP/1.1"
maxThreads="150"
connectionTimeout="20000"
redirectPort="443"
compression="on"
compressionMinSize="2048"
noCompressionUserAgents="gozilla, traviata"
compressableMimeType="text/html,text/xml"
relaxedQueryChars="[,]"
/>
If application needs more special characters that are not supported by tomcat by default, then add those special characters in relaxedQueryChars
attribute, comma-separated as above.
SELECT * FROM ( SELECT *, Row_Number()
OVER(ORDER BY country_gid) AS sdfg FROM eka_mst_tcountry ) t
WHERE t.country_gid % 2 = 0
<div style="text-align:center">
<span>Short text</span><br />
<span>This is long text</span>
</div>
Delegates always confused me until I realized that a delegate is just a class that does some work for another class. It's like having someone else there to do all the dirty work for you that you don't want to do yourself.
I wrote a little story to illustrate this. Read it in a Playground if you like.
// MARK: Background to the story
// A protocol is like a list of rules that need to be followed.
protocol OlderSiblingDelegate: class {
// The following command (ie, method) must be obeyed by any
// underling (ie, delegate) of the older sibling.
func getYourNiceOlderSiblingAGlassOfWater()
}
// MARK: Characters in the story
class BossyBigBrother {
// I can make whichever little sibling is around at
// the time be my delegate (ie, slave)
weak var delegate: OlderSiblingDelegate?
func tellSomebodyToGetMeSomeWater() {
// The delegate is optional because even though
// I'm thirsty, there might not be anyone nearby
// that I can boss around.
delegate?.getYourNiceOlderSiblingAGlassOfWater()
}
}
// Poor little sisters have to follow (or at least acknowledge)
// their older sibling's rules (ie, protocol)
class PoorLittleSister: OlderSiblingDelegate {
func getYourNiceOlderSiblingAGlassOfWater() {
// Little sis follows the letter of the law (ie, protocol),
// but no one said exactly how she had to respond.
print("Go get it yourself!")
}
}
// MARK: The Story
// Big bro is laying on the couch watching basketball on TV.
let bigBro = BossyBigBrother()
// He has a little sister named Sally.
let sally = PoorLittleSister()
// Sally walks into the room. How convenient! Now big bro
// has someone there to boss around.
bigBro.delegate = sally
// So he tells her to get him some water.
bigBro.tellSomebodyToGetMeSomeWater()
// Unfortunately no one lived happily ever after...
// The end.
In review, there are three key parts to making and using the delegate pattern.
In comparison to our Bossy Big Brother story above, delegates are often used for the following practical applications:
The great part is that these classes don't need to know anything about each other beforehand except that the delegate class conforms to the required protocol.
I highly recommend reading the following two articles. They helped me understand delegates even better than the documentation did.
One more note
Delegates that reference other classes that they do not own should use the weak
keyword to avoid strong reference cycles. See this answer for more details.
I had the same problem, what I did to solve it was ran the cmd.exe as administrator even though my account was already set as an administrator.
Use MultiDataTrigger type
<Style TargetType="ListBoxItem">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=State}" Value="WA">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Path=Name}" Value="Portland" />
<Condition Binding="{Binding Path=State}" Value="OR" />
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Cyan" />
</MultiDataTrigger>
</Style.Triggers>
</Style>
If you're on OSX you can also find it your keychain. Your developer and distribution certificates have your Team ID in them.
Applications -> Utilities -> Keychain Access.
Under the 'login' Keychain, go into the 'Certificates' category.
Scroll to find your development or distribution certificate. They will read:
iPhone Distribution: Team Name (certificate id)
or
iPhone Developer: Team Name (certificate id)
Simply double-click on the item, and the
is the "Team ID"
Note that this is the only way to find your
You can not find the "Personal team" ID on the Apple web interface.
For example, if you are automating a build from say Unity, during development you'll want it to appear in Xcode as your "Personal team" - this is the only way to get that value.
If you are trying to access the variable from another PHP file directly, you can include that file with include()
or include_once()
, giving you access to that variable. Note that this will include the entire first file in the second file.
This example shows how to convert from string to ip, and viceversa:
struct sockaddr_in sa;
char ip_saver[INET_ADDRSTRLEN];
// store this IP address in sa:
inet_pton(AF_INET, "192.0.1.10", &(sa.sin_addr));
// now get it back
sprintf(ip_saver, "%s", sa.sin_addr));
// prints "192.0.2.10"
printf("%s\n", ip_saver);
Very close! In your select
expression, you have to use a pipe (|
) before contains
.
This filter produces the expected output.
. - map(select(.Names[] | contains ("data"))) | .[] .Id
The jq Cookbook has an example of the syntax.
Filter objects based on the contents of a key
E.g., I only want objects whose genre key contains "house".
$ json='[{"genre":"deep house"}, {"genre": "progressive house"}, {"genre": "dubstep"}]' $ echo "$json" | jq -c '.[] | select(.genre | contains("house"))' {"genre":"deep house"} {"genre":"progressive house"}
Colin D asks how to preserve the JSON structure of the array, so that the final output is a single JSON array rather than a stream of JSON objects.
The simplest way is to wrap the whole expression in an array constructor:
$ echo "$json" | jq -c '[ .[] | select( .genre | contains("house")) ]'
[{"genre":"deep house"},{"genre":"progressive house"}]
You can also use the map function:
$ echo "$json" | jq -c 'map(select(.genre | contains("house")))'
[{"genre":"deep house"},{"genre":"progressive house"}]
map unpacks the input array, applies the filter to every element, and creates a new array. In other words, map(f)
is equivalent to [.[]|f]
.
Let's suppose you have this url path:
http://localhost:4200/landing?query=1#2
So, you can serve yourself by the location values, as follow:
window.location.hash: "#2"
?
window.location.host: "localhost:4200"
?
window.location.hostname: "localhost"
?
window.location.href: "http://localhost:4200/landing?query=1#2"
?
window.location.origin: "http://localhost:4200"
?
window.location.pathname: "/landing"
?
window.location.port: "4200"
?
window.location.protocol: "http:"
window.location.search: "?query=1"
Now we can conclude you're looking for:
window.location.hostname
Try adding a reference to the missing dll's from your service/web project directly. Adding the references to a different project didn't work for me.
I only had to do this when publishing my web app because it wasn't copying all the required dll's.
If you're using React function components, and you don't like to work with labels or IDs, you can also use a reference.
const uploadInputRef = useRef(null);
return (
<Fragment>
<input
ref={uploadInputRef}
type="file"
accept="image/*"
style={{ display: "none" }}
onChange={onChange}
/>
<Button
onClick={() => uploadInputRef.current && uploadInputRef.current.click()}
variant="contained"
>
Upload
</Button>
</Fragment>
);
For those who mentioned Stringify()
and toString()
as solution, I will say that worked for me but we have to understand the problem and why did it occur. In my code it was simple issue. I had 2 buttons which call same function but one button was not passing the argument to that function properly.
There is a React module called react-client-session
that makes storing client side session data very easy. The git repo is here.
This is implemented in a similar way as the closure approach in my other answer, however it also supports persistence using 3 different persistence stores. The default store is memory(not persistent).
After installing, just set the desired store type where you mount the root component ...
import ReactSession from 'react-client-session';
ReactSession.setStoreType("localStorage");
... and set/get key value pairs from anywhere in your app:
import ReactSession from 'react-client-session';
ReactSession.set("username", "Bob");
ReactSession.get("username"); // Returns "Bob"
I think you are confused about how the compiler puts things together. When you use -c
flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o
files thus don't mix with -c
, and compiler warns you about that. Symbols from object file are not moved to other object files like that.
All object files should be on the final linker invocation, which is not the case here, so linker (called via g++
front-end) complains about missing symbols.
Here's a small example (calling g++
explicitly for clarity):
PROG ?= myprog
OBJS = worker.o main.o
all: $(PROG)
.cpp.o:
g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<
$(PROG): $(OBJS)
g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)
There's also makedepend
utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M
gcc
option for building make
rules.
As others have mentioned, try stopPropagation()
.
And there is a second handler to try: event.cancelBubble = true;
It's a IE specific handler, but it is supported in at least FF. Don't really know much about it, as I haven't used it myself, but it might be worth a shot, if all else fails.
Use the following query:
SELECT E.I_EmpID AS EMPID,
E.I_EMPCODE AS EMPCODE,
E.I_EmpName AS EMPNAME,
REPLACE(TO_CHAR(A.I_REQDATE, 'DD-Mon-YYYY'), ' ', '') AS FROMDATE,
REPLACE(TO_CHAR(A.I_ENDDATE, 'DD-Mon-YYYY'), ' ', '') AS TODATE,
TO_CHAR(NOD) AS NOD,
DECODE(A.I_DURATION,
'FD',
'FullDay',
'FN',
'ForeNoon',
'AN',
'AfterNoon') AS DURATION,
L.I_LeaveType AS LEAVETYPE,
REPLACE(TO_CHAR((SELECT max(C.I_WORKDATE)
FROM T_COMPENSATION C
WHERE C.I_COMPENSATEDDATE = A.I_REQDATE
AND C.I_EMPID = A.I_EMPID),
'DD-Mon-YYYY'),
' ',
'') AS WORKDATE,
A.I_REASON AS REASON,
AP.I_REJECTREASON AS REJECTREASON
FROM T_LEAVEAPPLY A
INNER JOIN T_EMPLOYEE_MS E
ON A.I_EMPID = E.I_EmpID
AND UPPER(E.I_IsActive) = 'YES'
AND A.I_STATUS = '1'
INNER JOIN T_LeaveType_MS L
ON A.I_LEAVETYPEID = L.I_LEAVETYPEID
LEFT OUTER JOIN T_APPROVAL AP
ON A.I_REQDATE = AP.I_REQDATE
AND A.I_EMPID = AP.I_EMPID
AND AP.I_APPROVALSTATUS = '1'
WHERE E.I_EMPID <> '22'
ORDER BY A.I_REQDATE DESC
The trick is to force the inner query return only one record by adding an aggregate function (I have used max() here). This will work perfectly as far as the query is concerned, but, honestly, OP should investigate why the inner query is returning multiple records by examining the data. Are these multiple records really relevant business wise?
Could you try something like this for example I think what you are wanting to utilize is the port.ReadExisting() Method
using System;
using System.IO.Ports;
class SerialPortProgram
{
// Create the serial port with basic settings
private SerialPort port = new SerialPort("COM1",
9600, Parity.None, 8, StopBits.One);
[STAThread]
static void Main(string[] args)
{
// Instatiate this
SerialPortProgram();
}
private static void SerialPortProgram()
{
Console.WriteLine("Incoming Data:");
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
// Enter an application loop to keep this thread alive
Console.ReadLine();
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer
Console.WriteLine(port.ReadExisting());
}
}
Or is you want to do it based on what you were trying to do , you can try this
public class MySerialReader : IDisposable
{
private SerialPort serialPort;
private Queue<byte> recievedData = new Queue<byte>();
public MySerialReader()
{
serialPort = new SerialPort();
serialPort.Open();
serialPort.DataReceived += serialPort_DataReceived;
}
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[serialPort.BytesToRead];
serialPort.Read(data, 0, data.Length);
data.ToList().ForEach(b => recievedData.Enqueue(b));
processData();
}
void processData()
{
// Determine if we have a "packet" in the queue
if (recievedData.Count > 50)
{
var packet = Enumerable.Range(0, 50).Select(i => recievedData.Dequeue());
}
}
public void Dispose()
{
if (serialPort != null)
{
serialPort.Dispose();
}
}
If you are looking for a self-invoking transition then you should use CSS 3 Animations. They aren't supported either, but this is exactly the kind of thing they were made for.
#test p {
margin-top: 25px;
font-size: 21px;
text-align: center;
-webkit-animation: fadein 2s; /* Safari, Chrome and Opera > 12.1 */
-moz-animation: fadein 2s; /* Firefox < 16 */
-ms-animation: fadein 2s; /* Internet Explorer */
-o-animation: fadein 2s; /* Opera < 12.1 */
animation: fadein 2s;
}
@keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Firefox < 16 */
@-moz-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Internet Explorer */
@-ms-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Opera < 12.1 */
@-o-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
All modern browsers and Internet Explorer 10 (and later): http://caniuse.com/#feat=css-animation
Alternatively, you can use jQuery (or plain JavaScript; see the third code block) to change the class on load:
$("#test p").addClass("load");?
#test p {
opacity: 0;
font-size: 21px;
margin-top: 25px;
text-align: center;
-webkit-transition: opacity 2s ease-in;
-moz-transition: opacity 2s ease-in;
-ms-transition: opacity 2s ease-in;
-o-transition: opacity 2s ease-in;
transition: opacity 2s ease-in;
}
#test p.load {
opacity: 1;
}
document.getElementById("test").children[0].className += " load";
All modern browsers and Internet Explorer 10 (and later): http://caniuse.com/#feat=css-transitions
Or, you can use the method that .Mail uses:
$("#test p").delay(1000).animate({ opacity: 1 }, 700);?
#test p {
opacity: 0;
font-size: 21px;
margin-top: 25px;
text-align: center;
}
jQuery 1.x: All modern browsers and Internet Explorer 6 (and later): http://jquery.com/browser-support/
jQuery 2.x: All modern browsers and Internet Explorer 9 (and later): http://jquery.com/browser-support/
This method is the most cross-compatible as the target browser does not need to support CSS 3 transitions or animations.
The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:
function getMachine(color, qty) {
var returnValue = null;
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
returnValue = thisArray[3];
return false; // this breaks out of the each
}
});
return returnValue;
}
var retval = getMachine(color, qty);
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class Stopwatch {
static int interval;
static Timer timer;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Input seconds => : ");
String secs = sc.nextLine();
int delay = 1000;
int period = 1000;
timer = new Timer();
interval = Integer.parseInt(secs);
System.out.println(secs);
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println(setInterval());
}
}, delay, period);
}
private static final int setInterval() {
if (interval == 1)
timer.cancel();
return --interval;
}
}
Try this.
that syntax is now deprecated, you will get this error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 14: Expected a stage @ line 14, column 9.
parallel firstTask: {
^
WorkflowScript: 14: Stage does not have a name @ line 14, column 9.
parallel secondTask: {
^
2 errors
You should do something like:
stage("Parallel") {
steps {
parallel (
"firstTask" : {
//do some stuff
},
"secondTask" : {
// Do some other stuff in parallel
}
)
}
}
Just to add the use of node here, to distribute jobs across multiple build servers/ VMs:
pipeline {
stages {
stage("Work 1"){
steps{
parallel ( "Build common Library":
{
node('<Label>'){
/// your stuff
}
},
"Build Utilities" : {
node('<Label>'){
/// your stuff
}
}
)
}
}
All VMs should be labelled as to use as a pool.
The existing answers show a possible solution for single files or file types. However, you can define the charset standard in VS Code by following this path:
File > Preferences > Settings > Encoding > Choose your option
This will define a character set as default. Besides that, you can always change the encoding in the lower right corner of the editor (blue symbol line) for the current project.
Go to Files->Options->Formulas-> Calculation Options / Set Workbook calculation to Automatic
The primary flag seems to only work for vagrant ssh
for me.
In the past I have used the following method to hack around the issue.
# stage box intended for configuration closely matching production if ARGV[1] == 'stage' config.vm.define "stage" do |stage| box_setup stage, \ "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml" end end
On Linux/OS X/Unix to display the groups to which you (or the optionally specified user) belong, use:
id -Gn [user]
which is equivalent to groups [user]
utility which has been obsoleted on Unix.
On OS X/Unix, the command id -p [user]
is suggested for normal interactive.
Explanation on the parameters:
-G
,--groups
- print all group IDs
-n
,--name
- print a name instead of a number, for-ugG
-p
- Make the output human-readable.
A quick tip that tripped me up: if you're invoking the linker as "gcc" or "g++", then using "--start-group" and "--end-group" won't pass those options through to the linker -- nor will it flag an error. It will just fail the link with undefined symbols if you had the library order wrong.
You need to write them as "-Wl,--start-group" etc. to tell GCC to pass the argument through to the linker.
Depending on what style attributes you'd like to change you may be able to use the Paris library:
Button view = (Button) LayoutInflater.from(this).inflate(R.layout.section_button, null);
Paris.style(view).apply(R.style.YourStyle);
Many attributes like background, padding, textSize, textColor, etc. are supported.
Disclaimer: I authored the library.
big=small=values[0]; //assigns element to be highest or lowest value
Should be AFTER
fill loop
//counts to 20 and prompts user for value and stores it
for ( int i = 0; i < 20; i++ )
{
cout << "Enter value " << i << ": ";
cin >> values[i];
}
big=small=values[0]; //assigns element to be highest or lowest value
since when you declare array - it's unintialized
(store some undefined values) and so, your big
and small
after assigning would store undefined
values too.
And of course, you can use std::min_element
, std::max_element
, or std::minmax_element
from C++11
, instead of writing your loops.
You are reinventing the wheel. Normal PowerShell scripts have parameters starting with -
, like script.ps1 -server http://devserver
Then you handle them in param
section in the beginning of the file.
You can also assign default values to your params, read them from console if not available or stop script execution:
param (
[string]$server = "http://defaultserver",
[Parameter(Mandatory=$true)][string]$username,
[string]$password = $( Read-Host "Input password, please" )
)
Inside the script you can simply
write-output $server
since all parameters become variables available in script scope.
In this example, the $server
gets a default value if the script is called without it, script stops if you omit the -username
parameter and asks for terminal input if -password
is omitted.
Update: You might also want to pass a "flag" (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a "force" where the script runs in a more careful mode when force is not used.
The keyword for that is [switch]
parameter type:
param (
[string]$server = "http://defaultserver",
[string]$password = $( Read-Host "Input password, please" ),
[switch]$force = $false
)
Inside the script then you would work with it like this:
if ($force) {
//deletes a file or does something "bad"
}
Now, when calling the script you'd set the switch/flag parameter like this:
.\yourscript.ps1 -server "http://otherserver" -force
If you explicitly want to state that the flag is not set, there is a special syntax for that
.\yourscript.ps1 -server "http://otherserver" -force:$false
Links to relevant Microsoft documentation (for PowerShell 5.0; tho versions 3.0 and 4.0 are also available at the links):
This worked for me:
mycomponent.component.ts:
action(event): void {
event.stopPropagation();
}
mycomponent.component.html:
<button mat-icon-button (click)="action($event);false">Click me !<button/>
make sure your properties file exist in classpath directory but not in sub folder of your classpath directory. if it is exist in sub folder then write as below classpath:subfolder/idm.properties
I doubt anything is killing the process just because it takes a long time. Killed generically means something from the outside terminated the process, but probably not in this case hitting Ctrl-C since that would cause Python to exit on a KeyboardInterrupt exception. Also, in Python you would get MemoryError exception if that was the problem. What might be happening is you're hitting a bug in Python or standard library code that causes a crash of the process.
You can use onkeyup when you have more input field. Suppose you have four or input.then
document.getElementById('something').value
is annoying. we need to write 4 lines to fetch value of input field.
So, you can create a function that store value in object on keyup or keydown event.
Example :
<div class="container">
<div>
<label for="">Name</label>
<input type="text" name="fname" id="fname" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Age</label>
<input type="number" name="age" id="age" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Email</label>
<input type="text" name="email" id="email" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Mobile</label>
<input type="number" name="mobile" id="number" onkeyup=handleInput(this)>
</div>
<div>
<button onclick=submitData()>Submit</button>
</div>
</div>
javascript :
<script>
const data={ };
function handleInput(e){
data[e.name] = e.value;
}
function submitData(){
console.log(data.fname); //get first name from object
console.log(data); //return object
}
</script>
What’s the difference between \n (newline) and \r (carriage return)?
In particular, are there any practical differences between
\n
and\r
? Are there places where one should be used instead of the other?
I would like to make a short experiment with the respective escape sequences of \n
for newline and \r
for carriage return to illustrate where the distinct difference between them is.
I know, that this question was asked as language-independent. Nonetheless, We need a language at least in order to fulfill the experiment. In my case, I`ve chosen C++, but the experiment shall generally be applicable in any programming language.
The program simply just iterates to print a sentence into the console, done by a for-loop iteration.
Newline program:
#include <iostream>
int main(void)
{
for(int i = 0; i < 7; i++)
{
std::cout << i + 1 <<".Walkthrough of the for-loop \n"; // Notice `\n` at the end.
}
return 0;
}
Output:
1.Walkthrough of the for-loop
2.Walkthrough of the for-loop
3.Walkthrough of the for-loop
4.Walkthrough of the for-loop
5.Walkthrough of the for-loop
6.Walkthrough of the for-loop
7.Walkthrough of the for-loop
Notice, that this result will not be provided on any system, you are executing this C++ code. But it shall work for the most modern systems. Read below for more details.
Now, the same program, but with the difference, that \n
is replaced by \r
at the end of the print sequence.
Carriage return program:
#include <iostream>
int main(void)
{
for(int i = 0; i < 7; i++)
{
std::cout << i + 1 <<".Walkthrough of the for-loop \r"; // Notice `\r` at the end.
}
return 0;
}
Output:
7.Walkthrough of the for-loop
Noticed where the difference is? The difference is simply as that, when you using the Carriage return escape sequence \r
at the end of each print sequence, the next iteration of this sequence do not getting into the following text line - At the end of each print sequence, the cursor did not jumped to the *beginning of the next line.
Instead, the cursor jumped back to the beginning of the line, on which he has been at the end of, before using the \r
character. - The result is that each following iteration of the print sequence is replacing the previous one.
*Note: A \n
do not necessarily jump to the beginning of following text line. On some, in general more elder, operation systems the result of the \n
newline character can be, that it jumps to anywhere in the following line, not just to the beginning. That is why, they rquire to use \r \n
to get at the start of the next text line.
This experiment showed us the difference between newline and carriage return in the context of the output of the iteration of a print sequence.
When discussing about the input in a program, some terminals/consoles may convert a carriage return into a newline implicitly for better portability, compatibility and integrity.
But if you have the choice to choose one for another or want or need to explicitly use only a specific one, you should always operate with the one, which fits to its purpose and strictly distinguish between.
Check your code man....
In the main method you are trying to remove the 4th element which is not there and hence the error. In the remove() method you are trying to remove the 3rd element which is there and hence no error.
Write your <span>
in <h1>
or <h2>
:
<h1> <span class="glyphicon glyphicon-th-list"></span></h1>
Since there is no native way to do this ,Here is less intrusive solution i found (dont add any 'old' prototype methods):
var ListenerTracker=new function(){
var is_active=false;
// listener tracking datas
var _elements_ =[];
var _listeners_ =[];
this.init=function(){
if(!is_active){//avoid duplicate call
intercep_events_listeners();
}
is_active=true;
};
// register individual element an returns its corresponding listeners
var register_element=function(element){
if(_elements_.indexOf(element)==-1){
// NB : split by useCapture to make listener easier to find when removing
var elt_listeners=[{/*useCapture=false*/},{/*useCapture=true*/}];
_elements_.push(element);
_listeners_.push(elt_listeners);
}
return _listeners_[_elements_.indexOf(element)];
};
var intercep_events_listeners = function(){
// backup overrided methods
var _super_={
"addEventListener" : HTMLElement.prototype.addEventListener,
"removeEventListener" : HTMLElement.prototype.removeEventListener
};
Element.prototype["addEventListener"]=function(type, listener, useCapture){
var listeners=register_element(this);
// add event before to avoid registering if an error is thrown
_super_["addEventListener"].apply(this,arguments);
// adapt to 'elt_listeners' index
useCapture=useCapture?1:0;
if(!listeners[useCapture][type])listeners[useCapture][type]=[];
listeners[useCapture][type].push(listener);
};
Element.prototype["removeEventListener"]=function(type, listener, useCapture){
var listeners=register_element(this);
// add event before to avoid registering if an error is thrown
_super_["removeEventListener"].apply(this,arguments);
// adapt to 'elt_listeners' index
useCapture=useCapture?1:0;
if(!listeners[useCapture][type])return;
var lid = listeners[useCapture][type].indexOf(listener);
if(lid>-1)listeners[useCapture][type].splice(lid,1);
};
Element.prototype["getEventListeners"]=function(type){
var listeners=register_element(this);
// convert to listener datas list
var result=[];
for(var useCapture=0,list;list=listeners[useCapture];useCapture++){
if(typeof(type)=="string"){// filtered by type
if(list[type]){
for(var id in list[type]){
result.push({"type":type,"listener":list[type][id],"useCapture":!!useCapture});
}
}
}else{// all
for(var _type in list){
for(var id in list[_type]){
result.push({"type":_type,"listener":list[_type][id],"useCapture":!!useCapture});
}
}
}
}
return result;
};
};
}();
ListenerTracker.init();
Use it inside a label
. Use vertical-align
to set it to various values -- bottom
, baseline
, middle
etc.
SELECT COUNT(*), table1.category_id, table2.category_name
FROM table1
INNER JOIN table2 ON table1.category_id=table2.category_id
WHERE table1.colour <> 'red'
GROUP BY table1.category_id, table2.category_name
you can use my project i create bootstrap 3 rtl with sass and gulp so you can easely customize it https://github.com/z-avanes/bootstrap3-rtl
Advantages of this solution
Disadvantages - Mutation. Being internal only I don't care, maybe some others will not either.
Examples and Code
times(5, 3) // 15 (3+3+3+3+3)
times(5, (i) => Math.pow(2,i) ) // 31 (1+2+4+8+16)
times(5, '<br/>') // <br/><br/><br/><br/><br/>
times(3, (i, count) => { // name[0], name[1], name[2]
let n = 'name[' + i + ']'
if (i < count-1)
n += ', '
return n
})
function times(count, callbackOrScalar) {
let type = typeof callbackOrScalar
let sum
if (type === 'number') sum = 0
else if (type === 'string') sum = ''
for (let j = 0; j < count; j++) {
if (type === 'function') {
const callback = callbackOrScalar
const result = callback(j, count)
if (typeof result === 'number' || typeof result === 'string')
sum = sum === undefined ? result : sum + result
}
else if (type === 'number' || type === 'string') {
const scalar = callbackOrScalar
sum = sum === undefined ? scalar : sum + scalar
}
}
return sum
}
TypeScipt version
https://codepen.io/whitneyland/pen/aVjaaE?editors=0011
In the Atom IDE:
I typically perform the validation on the client side:
<asp:checkbox id="chkTerms" text=" I agree to the terms" ValidationGroup="vg" runat="Server" />
<asp:CustomValidator id="vTerms"
ClientValidationFunction="validateTerms"
ErrorMessage="<br/>Terms and Conditions are required."
ForeColor="Red"
Display="Static"
EnableClientScript="true"
ValidationGroup="vg"
runat="server"/>
<asp:Button ID="btnSubmit" OnClick="btnSubmit_Click" CausesValidation="true" Text="Submit" ValidationGroup="vg" runat="server" />
<script>
function validateTerms(source, arguments) {
var $c = $('#<%= chkTerms.ClientID %>');
if($c.prop("checked")){
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
</script>
This work for me now and today at Angular version 9
The built in clean function can also be helpful...
git clean -fd
If you also want it to be a command you can reference without remembering the arguments, you could simply alias it:
alias df-gb='df -BG'
So if you type:
df-gb
into a terminal, you'll get your intended output of the disk usage in GB.
EDIT: or even use just df -h
to get it in a standard, human readable format.
You are trying to clone the repository over ssh: git@arobotdev...
, and your SSH keys are not properly set on server. There are multiple reasons to this:
If all 3 above are untrue then my only conclusion can be to try:
git@arobotdev:AlfaRobot.git
Assuming AlfaRobot.git is in HOMEDIR of git user and not inside a folder called git which resides in HOMEDIR of user git.