You are not getting value of $id=$_GET['id'];
And you are using it (before it gets initialised).
Use php's in built isset() function to check whether the variable is defied or not.
So, please update the line to:
$id = isset($_GET['id']) ? $_GET['id'] : '';
Right click 'libraries' in the project list, then click add.
I had this problem as well and only really started to hone in on the root cause after opening up the browser's web console. Until that, I was unable to get any error messages (even with <p:messages>
). The web console showed an HTTP 405 status code coming back from the <h:commandButton type="submit" action="#{myBean.submit}">
.
In my case, I have a mix of vanilla HttpServlet's providing OAuth authentication via Auth0 and JSF facelets and beans carrying out my application views and business logic.
Once I refactored my web.xml, and removed a middle-man-servlet, it then "magically" worked.
Bottom line, the problem was that the middle-man-servlet was using RequestDispatcher.forward(...) to redirect from the HttpServlet environment to the JSF environment whereas the servlet being called prior to it was redirecting with HttpServletResponse.sendRedirect(...).
Basically, using sendRedirect() allowed the JSF "container" to take control whereas RequestDispatcher.forward() was obviously not.
What I don't know is why the facelet was able to access the bean properties but could not set them, and this clearly screams for doing away with the mix of servlets and JSF, but I hope this helps someone avoid many hours of head-to-table-banging.
Edit: actually I'm not sure - line 6186 gives an example in .ics naming format, but it also states you can use url parameters. I don't think it matters, so long as the MIME type is correct.
Edit: Example from wikipedia: http://en.wikipedia.org/wiki/ICalendar
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
BEGIN:VEVENT
DTSTART:19970714T170000Z
DTEND:19970715T035959Z
SUMMARY:Bastille Day Party
END:VEVENT
END:VCALENDAR
MIME type is configured on the server.
Yes this is happening because you are accessing mi
variable from within your anonymous inner class, what happens deep inside is that another copy of your variable is created and will be use inside the anonymous inner class, so for data consistency the compiler will try restrict you from changing the value of mi
so that's why its telling you to set it to final.
I had the exact same problem after updating m2e and solved it by reinstalling Maven Integration for Eclipse WTP.
As it turns out, I uninstalled it trying to update m2e from version 0.x to 1.x
I have done some work on a pretty complete port of the Django template language for Simon Willisons djangode project (Utilities functions for node.js that borrow some useful concepts from Django).
See the documentation here.
check out this link and then help yourself out.
the basic code is
#create a temp. file
echo "hi " > t.tmp
# set the file time to 2 hours ago
touch -t 200405121120 t.tmp
# then check for files
find /admin//dump -type f -newer t.tmp -print -exec ls -lt {} \; | pg
$(document).ready(function () {
$("#tbl_Customer tbody tr .companyname").click(function () {
var comapnyname = $(this).closest(".trclass").find(".companyname").text();
var CompanyAddress = $(this).closest(".trclass").find(".CompanyAddress").text();
var CompanyEmail = $(this).closest(".trclass").find(".CompanyEmail").text();
var CompanyContactNumber = $(this).closest(".trclass").find(".CompanyContactNumber").text();
var CompanyContactPerson = $(this).closest(".trclass").find(".CompanyContactPerson").text();
// var clickedCell = $(this);
alert(comapnyname);
alert(CompanyAddress);
alert(CompanyEmail);
alert(CompanyContactNumber);
alert(CompanyContactPerson);
//alert(clickedCell.text());
});
});
Here is how I would do it if working with a large number of "to remove" values that would take a long time to manually remove.
You need to compare, not assign:
if (strcmp("hello", "hello") == 0)
^
Because you want to check if the result of strcmp("hello", "hello")
equals to 0
.
About the error:
lvalue required as left operand of assignment
lvalue
means an assignable value (variable), and in assignment the left value to the =
has to be lvalue
(pretty clear).
Both function results and constants are not assignable (rvalue
s), so they are rvalue
s. so the order doesn't matter and if you forget to use ==
you will get this error. (edit:)I consider it a good practice in comparison to put the constant in the left side, so if you write =
instead of ==
, you will get a compilation error. for example:
int a = 5;
if (a = 0) // Always evaluated as false, no error.
{
//...
}
vs.
int a = 5;
if (0 = a) // Generates compilation error, you cannot assign a to 0 (rvalue)
{
//...
}
(see first answer to this question: https://stackoverflow.com/questions/2349378/new-programming-jargon-you-coined)
What you describe is the correct way to handle this.
You said that you want to stay in the GUI. You can usually set the execute bit through the file properties menu. You could also learn how to create a custom action for the context menu to do this for you if you're so inclined. This depends on your desktop environment of course.
If you use a more advanced editor, you can script the action to happen when the file is saved. For example (I'm only really familiar with vim), you could add this to your .vimrc to make any new file that starts with "#!/*/bin/*
" executable.
au BufWritePost * if getline(1) =~ "^#!" | if getline(1) =~ "/bin/" | silent !chmod +x <afile> | endif | endif
caution : It is not recommended to remove the default Python from Ubuntu, it may cause GDM(Graphical Display Manager, that provide graphical login capabilities) failed.
To completely uninstall Python2.x.x and everything depends on it. use this command:
sudo apt purge python2.x-minimal
As there are still a lot of packages that depend on Python2.x.x. So you should have a close look at the packages that apt wants to remove before you let it proceed.
Thanks, I hope it will be helpful for you.
While @opaxdiablo answer is totally correct I would like to point out that the usage scenario of both things is quite different. The mutex is used for protecting parts of code from running concurrently, semaphores are used for one thread to signal another thread to run.
/* Task 1 */
pthread_mutex_lock(mutex_thing);
// Safely use shared resource
pthread_mutex_unlock(mutex_thing);
/* Task 2 */
pthread_mutex_lock(mutex_thing);
// Safely use shared resource
pthread_mutex_unlock(mutex_thing); // unlock mutex
The semaphore scenario is different:
/* Task 1 - Producer */
sema_post(&sem); // Send the signal
/* Task 2 - Consumer */
sema_wait(&sem); // Wait for signal
See http://www.netrino.com/node/202 for further explanations
As explained in the documentation, by using an @RequestParam
annotation:
public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
+ foo;
}
You need to get id from:
youtube.com/watch?v=VIDEO_ID
And put this in:
i.ytimg.com/vi/VIDEO_ID/maxresdefault.jpg
I hope that I helped :D
I use a very old java. Jdk 1.4.08 and I had the same issue. The Node
class for me did not had the getTextContent()
method. I had to use Node.getFirstChild().getNodeValue()
instead of Node.getNodeValue()
to get the value of the node. This fixed for me.
based on fortran's answer, this is a recusive version that uses a StringBuilder:
public static void repeat(StringBuilder stringBuilder, String s, int times) {
if (times > 0) {
repeat(stringBuilder.append(s), s, times - 1);
}
}
public static String repeat(String s, int times) {
StringBuilder stringBuilder = new StringBuilder(s.length() * times);
repeat(stringBuilder, s, times);
return stringBuilder.toString();
}
I would make a very simple VBScript file and call it using CScript to parse the command line parameters.
Something like the following saved in MessageBox.vbs
:
Set objArgs = WScript.Arguments
messageText = objArgs(0)
MsgBox messageText
Which you would call like:
cscript MessageBox.vbs "This will be shown in a popup."
MsgBox
reference if you are interested in going this route.
The best practice is to explicitly list the columns:
Insert Into TableName(col1, col2,col2) Values(?, ?, ?)
Otherwise, your original insert will break if you add another column to your table.
Another solution (but it requires jQueryUI as pointed out by Richard Neil Ilagan in comments) :-
addClass, removeClass and toggleClass also accepts a second argument; the time duration to go from one state to the other.
$(this).addClass('abc',1000);
See jsfiddle:- http://jsfiddle.net/6hvZT/1/
I recommend you take a look at the list of editors on Python's wiki, as well as these related questions:
If using Java8 you can get the average of the values from a List as follows:
List<Integer> intList = Arrays.asList(1,2,2,3,1,5);
Double average = intList.stream().mapToInt(val -> val).average().orElse(0.0);
This has the advantage of having no moving parts. It can be easily adapted to work with a List of other types of object by changing the map method call.
For example with Doubles:
List<Double> dblList = Arrays.asList(1.1,2.1,2.2,3.1,1.5,5.3);
Double average = dblList.stream().mapToDouble(val -> val).average().orElse(0.0);
NB. mapToDouble is required because it returns a DoubleStream which has an average
method, while using map
does not.
or BigDecimals:
@Test
public void bigDecimalListAveragedCorrectly() {
List<BigDecimal> bdList = Arrays.asList(valueOf(1.1),valueOf(2.1),valueOf(2.2),valueOf(3.1),valueOf(1.5),valueOf(5.3));
Double average = bdList.stream().mapToDouble(BigDecimal::doubleValue).average().orElse(0.0);
assertEquals(2.55, average, 0.000001);
}
using orElse(0.0)
removes problems with the Optional object returned from the average
being 'not present'.
Both will work but xhtml standard requires you to specify the type
too:
<script type="text/javascript">..</script>
<!ELEMENT SCRIPT - - %Script; -- script statements -->
<!ATTLIST SCRIPT
charset %Charset; #IMPLIED -- char encoding of linked resource --
type %ContentType; #REQUIRED -- content type of script language --
src %URI; #IMPLIED -- URI for an external script --
defer (defer) #IMPLIED -- UA may defer execution of script --
>
type = content-type [CI] This attribute specifies the scripting language of the element's contents and overrides the default scripting language. The scripting language is specified as a content type (e.g., "text/javascript"). Authors must supply a value for this attribute. There is no default value for this attribute.
Notices the emphasis above.
http://www.w3.org/TR/html4/interact/scripts.html
Note: As of HTML5 (far away), the type
attribute is not required and is default.
I had similar problem with regex = "?"
. It happens for all special characters that have some meaning in a regex. So you need to have "\\"
as a prefix to your regex.
String [] separado = line.split("\\*");
Using a pure javascript, you can handle the reference to the object that dispatched the event.
function (event) {
console.log(event.target.value);
}
I personally like to create libs with extensions to the classes
public static List<TTo> Cast<TFrom, TTo>(List<TFrom> fromlist)
where TFrom : class
where TTo : class
{
return fromlist.ConvertAll(x => x as TTo);
}
There is indeed no such thing as a forward declaration of enum. As an enum's definition doesn't contain any code that could depend on other code using the enum, it's usually not a problem to define the enum completely when you're first declaring it.
If the only use of your enum is by private member functions, you can implement encapsulation by having the enum itself as a private member of that class. The enum still has to be fully defined at the point of declaration, that is, within the class definition. However, this is not a bigger problem as declaring private member functions there, and is not a worse exposal of implementation internals than that.
If you need a deeper degree of concealment for your implementation details, you can break it into an abstract interface, only consisting of pure virtual functions, and a concrete, completely concealed, class implementing (inheriting) the interface. Creation of class instances can be handled by a factory or a static member function of the interface. That way, even the real class name, let alone its private functions, won't be exposed.
I wrote a bash script to do this. Check the link[1]
#!/bin/bash
# Imports pictures into all iOS simulators.
path_to_pic="src/ios/pictures/"
mkdir -p /Users/$(whoami)/Library/Application\ Support/iPhone\ Simulator/{5.0,5.1,6.0,6.1}/Media/DCIM/100APPLE/
find ~/Library/Application\ Support/iPhone\ Simulator/ -type d -name '100APPLE' -exec cp /Users/$(whoami)/$path_to_pic/* {} \;
If you have anaconda install than you just need to use command: conda install PyAudio
.
In order to execute this command you must set thePYTHONPATH
environment variable in anaconda.
From Wikipedia:
Add an id column to the csv file and leave it blank:
id,Name,Address
,name1,addr test 1
,name2,addr test 2
Remove KEEPIDENTITY keyword from query:
BULK INSERT Employee FROM 'path\tempFile.csv '
WITH (FIRSTROW = 2,FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n');
The id identity field will be auto-incremented.
If you assign values to the id field in the csv, they'll be ignored unless you use the KEEPIDENTITY keyword, then they'll be used instead of auto-increment.
The nature of arrays is that their length is immutable. You can't add or delete any of the array items.
You will have to create a new array that is one element shorter and copy the old items to the new array, excluding the element you want to delete.
So it is probably better to use a List instead of an array.
CREATE PROCEDURE [dbo].[sp_Myforeach_Date]
-- Add the parameters for the stored procedure here
@SatrtDate as DateTime,
@EndDate as dateTime,
@DatePart as varchar(2),
@OutPutFormat as int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
Declare @DateList Table
(Date varchar(50))
WHILE @SatrtDate<= @EndDate
BEGIN
INSERT @DateList (Date) values(Convert(varchar,@SatrtDate,@OutPutFormat))
IF Upper(@DatePart)='DD'
SET @SatrtDate= DateAdd(dd,1,@SatrtDate)
IF Upper(@DatePart)='MM'
SET @SatrtDate= DateAdd(mm,1,@SatrtDate)
IF Upper(@DatePart)='YY'
SET @SatrtDate= DateAdd(yy,1,@SatrtDate)
END
SELECT * FROM @DateList
END
Just put this Code and call the SP in This way
exec sp_Myforeach_Date @SatrtDate='03 Jan 2010',@EndDate='03 Mar 2010',@DatePart='dd',@OutPutFormat=106
git checkout -b NEW_BRANCH_NAME COMMIT_ID
This will create a new branch called 'NEW_BRANCH_NAME' and check it out.
("check out" means "to switch to the branch")
git branch NEW_BRANCH_NAME COMMIT_ID
This just creates the new branch without checking it out.
in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:
git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME
My simple solution:
$("form").children('input[type="submit"]').click();
It is work for me.
To get the most recent tag (example output afterwards):
git describe --tags --abbrev=0 # 0.1.0-dev
To get the most recent tag, with the number of additional commits on top of the tagged object & more:
git describe --tags # 0.1.0-dev-93-g1416689
To get the most recent annotated tag:
git describe --abbrev=0
Execute Exec DBMS_XDB.SETHTTPPORT(8181);
as SYS/SYSTEM. Replace 8181 with the port you'd like changing to. Tested this with Oracle 10g.
Source : http://hodentekhelp.blogspot.com/2008/08/my-oracle-10g-xe-is-on-port-8080-can-i.html
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z"));
You could also check out the PLINQO set of code generation templates, based on CodeSmith, which allow you to do a lot of neat things for and with Linq-to-SQL:
Check out the PLINQO site at http://www.plinqo.com and have a look at the intro videos.
The second tool I know of are the Huagati DBML/EDMX tools, which allow update of DBML (Linq-to-SQL) and EDMX (Entity Framework) mapping files, and more (like naming conventions etc.).
Marc
Reread the error message. It says:
sh: mysql_config: not found
If you are on Ubuntu Natty, mysql_config
belongs to package libmysqlclient-dev
NOTE calling parent method via super will only work on parent class,
If your parent is interface, and wants to call the default methods then need to add interfaceName before super like IfscName.super.method();
interface Vehicle {
//Non abstract method
public default void printVehicleTypeName() { //default keyword can be used only in interface.
System.out.println("Vehicle");
}
}
class FordFigo extends FordImpl implements Vehicle, Ford {
@Override
public void printVehicleTypeName() {
System.out.println("Figo");
Vehicle.super.printVehicleTypeName();
}
}
Interface name is needed because same default methods can be available in multiple interface name that this class extends. So explicit call to a method is required.
If you NPM those modules you can serve them using static redirect.
First install the packages:
npm install jquery
npm install bootstrap
Then on the server.js:
var express = require('express');
var app = express();
// prepare server
app.use('/api', api); // redirect API calls
app.use('/', express.static(__dirname + '/www')); // redirect root
app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect bootstrap JS
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); // redirect JS jQuery
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect CSS bootstrap
Then, finally, at the .html:
<link rel="stylesheet" href="/css/bootstrap.min.css">
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
I would not serve pages directly from the folder where your server.js file is (which is usually the same as node_modules) as proposed by timetowonder, that way people can access your server.js file.
Of course you can simply download and copy & paste on your folder, but with NPM you can simply update when needed... easier, I think.
My current choice is Razor. It is very clean and easy to read and keeps the view pages very easy to maintain. There is also intellisense support which is really great. ALos, when used with web helpers it is really powerful too.
To provide a simple sample:
@Model namespace.model
<!Doctype html>
<html>
<head>
<title>Test Razor</title>
</head>
<body>
<ul class="mainList">
@foreach(var x in ViewData.model)
{
<li>@x.PropertyName</li>
}
</ul>
</body>
And there you have it. That is very clean and easy to read. Granted, that's a simple example but even on complex pages and forms it is still very easy to read and understand.
As for the cons? Well so far (I'm new to this) when using some of the helpers for forms there is a lack of support for adding a CSS class reference which is a little annoying.
Thanks Nathj07
Try this :
ImageView imageview = (ImageView)findViewById(R.id.your_imageview_id);
Bitmap bmp = BitmapFactory.decodeFile(new java.net.URL(your_url).openStream());
imageview.setImageBitmap(bmp);
You can also try this : Android-Universal-Image-Loader for efficiently loading your image from URL
How about something like this...
Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")
Do While Not rs.EOF
Debug.Print rs("PictureLocation") & " - " & rs("ID")
rs.MoveNext
Loop
In Python 3, raw_input()
doesn't exist which was already mentioned by Sven.
In Python 2, the input()
function evaluates your input.
Example:
name = input("what is your name ?")
what is your name ?harsha
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
name = input("what is your name ?")
File "<string>", line 1, in <module>
NameError: name 'harsha' is not defined
In the example above, Python 2.x is trying to evaluate harsha as a variable rather than a string. To avoid that, we can use double quotes around our input like "harsha":
>>> name = input("what is your name?")
what is your name?"harsha"
>>> print(name)
harsha
raw_input()
The raw_input()` function doesn't evaluate, it will just read whatever you enter.
Example:
name = raw_input("what is your name ?")
what is your name ?harsha
>>> name
'harsha'
Example:
name = eval(raw_input("what is your name?"))
what is your name?harsha
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
name = eval(raw_input("what is your name?"))
File "<string>", line 1, in <module>
NameError: name 'harsha' is not defined
In example above, I was just trying to evaluate the user input with the eval
function.
For only acept files with extension doc and docx in the explorer window try this
<input type="file" id="docpicker"
accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
Smoke testing is about checking if the requirements are satisfied or not. Smoke testing is a general health check up.
Sanity testing is about checking if a particular module is completely working or not. Sanity testing is specialized in particular health check up.
I'm using the following simple custom CSS I wrote to achieve this.
.col-xs-offset-right-12 {
margin-right: 100%;
}
.col-xs-offset-right-11 {
margin-right: 91.66666667%;
}
.col-xs-offset-right-10 {
margin-right: 83.33333333%;
}
.col-xs-offset-right-9 {
margin-right: 75%;
}
.col-xs-offset-right-8 {
margin-right: 66.66666667%;
}
.col-xs-offset-right-7 {
margin-right: 58.33333333%;
}
.col-xs-offset-right-6 {
margin-right: 50%;
}
.col-xs-offset-right-5 {
margin-right: 41.66666667%;
}
.col-xs-offset-right-4 {
margin-right: 33.33333333%;
}
.col-xs-offset-right-3 {
margin-right: 25%;
}
.col-xs-offset-right-2 {
margin-right: 16.66666667%;
}
.col-xs-offset-right-1 {
margin-right: 8.33333333%;
}
.col-xs-offset-right-0 {
margin-right: 0;
}
@media (min-width: 768px) {
.col-sm-offset-right-12 {
margin-right: 100%;
}
.col-sm-offset-right-11 {
margin-right: 91.66666667%;
}
.col-sm-offset-right-10 {
margin-right: 83.33333333%;
}
.col-sm-offset-right-9 {
margin-right: 75%;
}
.col-sm-offset-right-8 {
margin-right: 66.66666667%;
}
.col-sm-offset-right-7 {
margin-right: 58.33333333%;
}
.col-sm-offset-right-6 {
margin-right: 50%;
}
.col-sm-offset-right-5 {
margin-right: 41.66666667%;
}
.col-sm-offset-right-4 {
margin-right: 33.33333333%;
}
.col-sm-offset-right-3 {
margin-right: 25%;
}
.col-sm-offset-right-2 {
margin-right: 16.66666667%;
}
.col-sm-offset-right-1 {
margin-right: 8.33333333%;
}
.col-sm-offset-right-0 {
margin-right: 0;
}
}
@media (min-width: 992px) {
.col-md-offset-right-12 {
margin-right: 100%;
}
.col-md-offset-right-11 {
margin-right: 91.66666667%;
}
.col-md-offset-right-10 {
margin-right: 83.33333333%;
}
.col-md-offset-right-9 {
margin-right: 75%;
}
.col-md-offset-right-8 {
margin-right: 66.66666667%;
}
.col-md-offset-right-7 {
margin-right: 58.33333333%;
}
.col-md-offset-right-6 {
margin-right: 50%;
}
.col-md-offset-right-5 {
margin-right: 41.66666667%;
}
.col-md-offset-right-4 {
margin-right: 33.33333333%;
}
.col-md-offset-right-3 {
margin-right: 25%;
}
.col-md-offset-right-2 {
margin-right: 16.66666667%;
}
.col-md-offset-right-1 {
margin-right: 8.33333333%;
}
.col-md-offset-right-0 {
margin-right: 0;
}
}
@media (min-width: 1200px) {
.col-lg-offset-right-12 {
margin-right: 100%;
}
.col-lg-offset-right-11 {
margin-right: 91.66666667%;
}
.col-lg-offset-right-10 {
margin-right: 83.33333333%;
}
.col-lg-offset-right-9 {
margin-right: 75%;
}
.col-lg-offset-right-8 {
margin-right: 66.66666667%;
}
.col-lg-offset-right-7 {
margin-right: 58.33333333%;
}
.col-lg-offset-right-6 {
margin-right: 50%;
}
.col-lg-offset-right-5 {
margin-right: 41.66666667%;
}
.col-lg-offset-right-4 {
margin-right: 33.33333333%;
}
.col-lg-offset-right-3 {
margin-right: 25%;
}
.col-lg-offset-right-2 {
margin-right: 16.66666667%;
}
.col-lg-offset-right-1 {
margin-right: 8.33333333%;
}
.col-lg-offset-right-0 {
margin-right: 0;
}
}
Thanks for sharing this. It helped a lot. The one difference in my applicationHost.config was
<add name="SharePoint14Module" image="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\isapi\owssvr.dll" preCondition="appPoolName=SharePoint Central Administration v4,bitness64;SharePoint - 80" />
Note the multiple semicolon seperated entries. This is probably because I have a single box install of SPS.
I have hit this issue, and have a case where I needed to hit pause() then play() but when using pause().then() I get undefined.
I found that if I started play 150ms after pause it resolved the issue. (Hopefully Google fixes soon)
playerMP3.volume = 0;
playerMP3.pause();
//Avoid the Promise Error
setTimeout(function () {
playerMP3.play();
}, 150);
If you frequently need to access the Nth element of a sequence, std::list
, which is implemented as a doubly linked list, is probably not the right choice. std::vector
or std::deque
would likely be better.
That said, you can get an iterator to the Nth element using std::advance
:
std::list<Object> l;
// add elements to list 'l'...
unsigned N = /* index of the element you want to retrieve */;
if (l.size() > N)
{
std::list<Object>::iterator it = l.begin();
std::advance(it, N);
// 'it' points to the element at index 'N'
}
For a container that doesn't provide random access, like std::list
, std::advance
calls operator++
on the iterator N
times. Alternatively, if your Standard Library implementation provides it, you may call std::next
:
if (l.size() > N)
{
std::list<Object>::iterator it = std::next(l.begin(), N);
}
std::next
is effectively wraps a call to std::advance
, making it easier to advance an iterator N
times with fewer lines of code and fewer mutable variables. std::next
was added in C++11.
If anyone is looking for a simple solution in Laravel 5.3:
timestamps()
be saved as is i.e. '2016-11-14 12:19:49'In your views, format the field as below (or as required):
date('F d, Y', strtotime($list->created_at))
It worked for me very well for me.
Your code: path = ActiveWorkbook.Path
returns blank because you haven't saved your workbook yet.
To overcome your problem, go back to the Excel sheet, save your sheet, and run your code again.
This time it will not show blank, but will show you the path where it is located (current folder)
I hope that helped.
I'm resurrecting the dead here, but because a range can be defined as "A:A", using a for each loop ends up with a potential infinite loop. The solution, as far as I know, is to use the Do Until
loop.
Do Until Selection.Value = ""
Rem Do things here...
Loop
I feel it is worth adding that a static variable is not the same as a constant variable.
using a constant variable in a class
struct Foo{
const int a;
Foo(int b) : a(b){}
}
and we would declare it like like so
fooA = new Foo(5);
fooB = new Foo(10);
// fooA.a = 5;
// fooB.a = 10;
For a static variable
struct Bar{
static int a;
Foo(int b){
a = b;
}
}
Bar::a = 0; // set value for a
which is used like so
barA = new Bar(5);
barB = new Bar(10);
// barA.a = 10;
// barB.a = 10;
// Bar::a = 10;
You see what happens here. The constant variable, which is instanced along with each instance of Foo, as Foo is instanced has a separate value for each instance of Foo, and it can't be changed by Foo at all.
Where as with Bar, their is only one value for Bar::a no matter how many instances of Bar are made. They all share this value, you can also access it with their being any instances of Bar. The static variable also abides rules for public/private, so you could make it that only instances of Bar can read the value of Bar::a;
There is a class, Class
, that can do this:
Class c = Class.forName("MyClass"); // if you want to specify a class
Class c = this.getClass(); // if you want to use the current class
System.out.println("Package: "+c.getPackage()+"\nClass: "+c.getSimpleName()+"\nFull Identifier: "+c.getName());
If c
represented the class MyClass
in the package mypackage
, the above code would print:
Package: mypackage
Class: MyClass
Full Identifier: mypackage.MyClass
You can take this information and modify it for whatever you need, or go check the API for more information.
Change the user to postgres :
su - postgres
Create User for Postgres
$ createuser testuser
Create Database
$ createdb testdb
Acces the postgres Shell
psql ( enter the password for postgressql)
Provide the privileges to the postgres user
$ alter user testuser with encrypted password 'qwerty';
$ grant all privileges on database testdb to testuser;
socket.disconnect()
is a synonym to socket.close()
which disconnect the socket manually.
When you type in client side :
const socket = io('http://localhost');
this will open a connection with autoConnect: true
, so the lib will try to reconnect again when you disconnect the socket from server, to disable the autoConnection:
const socket = io('http://localhost', {autoConnect: false});
socket.open();// synonym to socket.connect()
And if you want you can manually reconnect:
socket.on('disconnect', () => {
socket.open();
});
Working Solution :
For Resize image with size lower then 100Kb
WriteableBitmap bitmap = new WriteableBitmap(140,140);
bitmap.SetSource(dlg.File.OpenRead());
image1.Source = bitmap;
Image img = new Image();
img.Source = bitmap;
WriteableBitmap i;
do
{
ScaleTransform st = new ScaleTransform();
st.ScaleX = 0.3;
st.ScaleY = 0.3;
i = new WriteableBitmap(img, st);
img.Source = i;
} while (i.Pixels.Length / 1024 > 100);
More Reference at http://net4attack.blogspot.com/
First You have to use this code in MainActivity.java class
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(),NextActivity.class);
startActivity(i);
}
You can pass intent this way.
Second
add proper entry into manifest.xml
file.
<activity android:name=".NextActivity" />
Now see what happens.
MediaWiki's API is running on Wikipedia (docs). You can also use the Special:Export feature to dump data and parse it yourself.
Building up on Shavy Levy answer:
[bool]($var -as [int])
Because $null is evaluated to false (in bool), this statement Will give you true or false depending if the casting succeeds or not.
Sure, just add &
after the command:
read_cfg cfgA &
read_cfg cfgB &
read_cfg cfgC &
wait
all those jobs will then run in the background simultaneously. The optional wait
command will then wait for all the jobs to finish.
Each command will run in a separate process, so it's technically not "multithreading", but I believe it solves your problem.
For question #1, let's break it into two parts. First, increment any document that has "items.item_name" equal to "my_item_two". For this you'll have to use the positional "$" operator. Something like:
db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } ,
{$inc : {"items.$.price" : 1} } ,
false ,
true);
Note that this will only increment the first matched subdocument in any array (so if you have another document in the array with "item_name" equal to "my_item_two", it won't get incremented). But this might be what you want.
The second part is trickier. We can push a new item to an array without a "my_item_two" as follows:
db.bar.update( {user_id : 123456, "items.item_name" : {$ne : "my_item_two" }} ,
{$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
false ,
true);
For your question #2, the answer is easier. To increment the total and the price of item_three in any document that contains "my_item_three," you can use the $inc operator on multiple fields at the same time. Something like:
db.bar.update( {"items.item_name" : {$ne : "my_item_three" }} ,
{$inc : {total : 1 , "items.$.price" : 1}} ,
false ,
true);
How about this?
var people = [
{
name: 'a75',
item1: false,
item2: false
},
{
name: 'z32',
item1: true,
item2: false
},
{
name: 'e77',
item1: false,
item2: false
}];
function sort_by_key(array, key)
{
return array.sort(function(a, b)
{
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
people = sort_by_key(people, 'name');
This allows you to specify the key by which you want to sort the array so that you are not limited to a hard-coded name sort. It will work to sort any array of objects that all share the property which is used as they key. I believe that is what you were looking for?
And here is a jsFiddle: http://jsfiddle.net/6Dgbu/
Unless I'm misunderstanding, you lost your .ssh
directory containing your private key on your local machine and so you want to remove the public key which was on a server and which allowed key-based login.
In that case, it will be stored in the .ssh/authorized_keys
file in your home directory on the server. You can just edit this file with a text editor and delete the relevant line if you can identify it (even easier if it's the only entry!).
I hope that key wasn't your only method of access to the server and you have some other way of logging in and editing the file. You can either manually add a new public key to authorised_keys
file or use ssh-copy-id
. Either way, you'll need password authentication set up for your account on the server, or some other identity or access method to get to the authorized_keys
file on the server.
ssh-add
adds identities to your SSH agent which handles management of your identities locally and "the connection to the agent is forwarded over SSH remote logins, and the user can thus use the privileges given by the identities anywhere in the network in a secure way." (man page), so I don't think it's what you want in this case. It doesn't have any way to get your public key onto a server without you having access to said server via an SSH login as far as I know.
The length of an array in Java is immutable. So, you need to copy the desired part as a new array.
Use copyOfRange
method from java.util.Arrays class:
int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);
startIndex is the initial index of the range to be copied, inclusive.
endIndex is the final index of the range to be copied, exclusive. (This index may lie outside the array)
E.g.:
//index 0 1 2 3 4
int[] arr = {10, 20, 30, 40, 50};
Arrays.copyOfRange(arr, 0, 2); // returns {10, 20}
Arrays.copyOfRange(arr, 1, 4); // returns {20, 30, 40}
Arrays.copyOfRange(arr, 2, arr.length); // returns {30, 40, 50} (length = 5)
You can use this construct:
export class AppComponent {
title:string;
myHero:string;
heroes: any[];
constructor() {
this.title = 'Tour of Heros';
this.heroes=['Windstorm','Bombasto','Magneta','Tornado']
this.myHero = this.heroes[0];
}
}
The simplest solution I have found is to wrap your Font Awesome Icon in an <a></a>
tag:
<Tooltip title="Node.js" >
<a>
<FontAwesomeIcon icon={faNode} size="2x" />
</a>
</Tooltip>
CompareStrings with equals(..)
not with ==
if (operation.equals("+")
{
System.out.println("your answer is" + (num1 + num2));
}
if (operation.equals("-"))
{
System.out.println("your answer is" + (num1 - num2));
}
if (operation.equals("/"))
{
System.out.println("your answer is" + (num1 / num2));
}
if (operation .equals( "*"))
{
System.out.println("your answer is" + (num1 * num2));
}
And the ;
after the conditions was an empty statement so the conditon had no effect at all.
If you use java 7 you can also replace the if statements with a switch
.
In java <7 you can test, if operation
has length 1 and than make a switch for the char
[switch (operation.charAt(0))
]
Here is a simplistic example of streaming a file:
using System.IO;
using Microsoft.AspNetCore.Mvc;
[HttpGet("{id}")]
public async Task<FileStreamResult> Download(int id)
{
var path = "<Get the file path using the ID>";
var stream = File.OpenRead(path);
return new FileStreamResult(stream, "application/octet-stream");
}
Note:
Be sure to use FileStreamResult
from Microsoft.AspNetCore.Mvc
and not from System.Web.Mvc
.
After tirelessly trying every solution on this page, my work around was to use and SSH key instead!
You should use Merge: For example:
MERGE INTO employees e
USING (SELECT * FROM hr_records WHERE start_date > ADD_MONTHS(SYSDATE, -1)) h
ON (e.id = h.emp_id)
WHEN MATCHED THEN
UPDATE SET e.address = h.address
WHEN NOT MATCHED THEN
INSERT (id, address)
VALUES (h.emp_id, h.address);
or
MERGE INTO employees e
USING hr_records h
ON (e.id = h.emp_id)
WHEN MATCHED THEN
UPDATE SET e.address = h.address
WHEN NOT MATCHED THEN
INSERT (id, address)
VALUES (h.emp_id, h.address);
I use AngularJS v1.3.4
HTML:
<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>
JS controller:
'use strict';
angular.module('xxxxxxxxApp')
.controller('xxxxController', function ($scope, xxxxServicePDF) {
$scope.downloadPdf = function () {
var fileName = "test.pdf";
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
xxxxServicePDF.downloadPdf().then(function (result) {
var file = new Blob([result.data], {type: 'application/pdf'});
var fileURL = window.URL.createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
});
};
});
JS services:
angular.module('xxxxxxxxApp')
.factory('xxxxServicePDF', function ($http) {
return {
downloadPdf: function () {
return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
return response;
});
}
};
});
Java REST Web Services - Spring MVC:
@RequestMapping(value = "/downloadPDF", method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity<byte[]> getPDF() {
FileInputStream fileStream;
try {
fileStream = new FileInputStream(new File("C:\\xxxxx\\xxxxxx\\test.pdf"));
byte[] contents = IOUtils.toByteArray(fileStream);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "test.pdf";
headers.setContentDispositionFormData(filename, filename);
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
return response;
} catch (FileNotFoundException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
return null;
}
It's called a Favicon, have a read.
<link rel="shortcut icon" href="http://www.example.com/myicon.ico"/>
You can use this neat tool to generate cross-browser compatible Favicons.
Use compareTo()
Return Values
0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.
Like
if(date1.compareTo(date2)>0)
Zend framework
public function verifyTablesExists($tablesName)
{
$db = $this->getDefaultAdapter();
$config_db = $db->getConfig();
$sql = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{$config_db['dbname']}' AND table_name = '{$tablesName}'";
$result = $db->fetchRow($sql);
return $result;
}
This is my contribution in javascript (no recursion)
set = ["q0", "q1", "q2", "q3"]
collector = []
function comb(num) {
results = []
one_comb = []
for (i = set.length - 1; i >= 0; --i) {
tmp = Math.pow(2, i)
quotient = parseInt(num / tmp)
results.push(quotient)
num = num % tmp
}
k = 0
for (i = 0; i < results.length; ++i)
if (results[i]) {
++k
one_comb.push(set[i])
}
if (collector[k] == undefined)
collector[k] = []
collector[k].push(one_comb)
}
sum = 0
for (i = 0; i < set.length; ++i)
sum += Math.pow(2, i)
for (ii = sum; ii > 0; --ii)
comb(ii)
cnt = 0
for (i = 1; i < collector.length; ++i) {
n = 0
for (j = 0; j < collector[i].length; ++j)
document.write(++cnt, " - " + (++n) + " - ", collector[i][j], "<br>")
document.write("<hr>")
}
It works in user-style, and it seems not to work in web pages. I have not found official direction from Mozilla on this. While it may have worked at some point, Firefox does not have official support for this. This bug is still open https://bugzilla.mozilla.org/show_bug.cgi?id=77790
scrollbar {
/* clear useragent default style*/
-moz-appearance: none !important;
}
/* buttons at two ends */
scrollbarbutton {
-moz-appearance: none !important;
}
/* the sliding part*/
thumb{
-moz-appearance: none !important;
}
scrollcorner {
-moz-appearance: none !important;
resize:both;
}
/* vertical or horizontal */
scrollbar[orient="vertical"] {
color:silver;
}
check http://codemug.com/html/custom-scrollbars-using-css/ for details.
Shorter version:
db.row_factory = lambda c, r: dict([(col[0], r[idx]) for idx, col in enumerate(c.description)])
I had the same problem with Pool()
in Python 3.6.3.
Error received: TypeError: can't pickle _thread.RLock objects
Let's say we want to add some number num_to_add
to each element of some list num_list
in parallel. The code is schematically like this:
class DataGenerator:
def __init__(self, num_list, num_to_add)
self.num_list = num_list # e.g. [4,2,5,7]
self.num_to_add = num_to_add # e.g. 1
self.run()
def run(self):
new_num_list = Manager().list()
pool = Pool(processes=50)
results = [pool.apply_async(run_parallel, (num, new_num_list))
for num in num_list]
roots = [r.get() for r in results]
pool.close()
pool.terminate()
pool.join()
def run_parallel(self, num, shared_new_num_list):
new_num = num + self.num_to_add # uses class parameter
shared_new_num_list.append(new_num)
The problem here is that self
in function run_parallel()
can't be pickled as it is a class instance. Moving this parallelized function run_parallel()
out of the class helped. But it's not the best solution as this function probably needs to use class parameters like self.num_to_add
and then you have to pass it as an argument.
Solution:
def run_parallel(num, shared_new_num_list, to_add): # to_add is passed as an argument
new_num = num + to_add
shared_new_num_list.append(new_num)
class DataGenerator:
def __init__(self, num_list, num_to_add)
self.num_list = num_list # e.g. [4,2,5,7]
self.num_to_add = num_to_add # e.g. 1
self.run()
def run(self):
new_num_list = Manager().list()
pool = Pool(processes=50)
results = [pool.apply_async(run_parallel, (num, new_num_list, self.num_to_add)) # num_to_add is passed as an argument
for num in num_list]
roots = [r.get() for r in results]
pool.close()
pool.terminate()
pool.join()
Other suggestions above didn't help me.
Based on Kyle's answer, here's my c# implementation.
/// <summary>
/// Picks random selection of available game ID's
/// </summary>
private static List<int> GetRandomGameIDs(int count)
{
var gameIDs = (int[])HttpContext.Current.Application["NonDeletedArcadeGameIDs"];
var totalGameIDs = gameIDs.Count();
if (count > totalGameIDs) count = totalGameIDs;
var rnd = new Random();
var leftToPick = count;
var itemsLeft = totalGameIDs;
var arrPickIndex = 0;
var returnIDs = new List<int>();
while (leftToPick > 0)
{
if (rnd.Next(0, itemsLeft) < leftToPick)
{
returnIDs .Add(gameIDs[arrPickIndex]);
leftToPick--;
}
arrPickIndex++;
itemsLeft--;
}
return returnIDs ;
}
Q. List the name of each show, and the number of different times it has been held. List the show which has been held most often first.
event_id show_id event_name judge_id
0101 01 Dressage 01
0102 01 Jumping 02
0103 01 Led in 01
0201 02 Led in 02
0301 03 Led in 01
0401 04 Dressage 04
0501 05 Dressage 01
0502 05 Flag and Pole 02
Ans:
select event_name, count(show_id) as held_times from event
group by event_name
order by count(show_id) desc
try this:
function grab_image($url,$saveto){
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw=curl_exec($ch);
curl_close ($ch);
if(file_exists($saveto)){
unlink($saveto);
}
$fp = fopen($saveto,'x');
fwrite($fp, $raw);
fclose($fp);
}
and ensure that in php.ini allow_url_fopen is enable
$.each(top_brands, function(index, el) {
for (var key in el) {
if (el.hasOwnProperty(key)) {
brand_options.append($("<option />").val(key).text(key+ " " + el[key]));
}
}
});
But if your data structure is var top_brands = {'Adidas': 100, 'Nike': 50};
, then thing will be much more simple.
for (var key in top_brands) {
if (top_brands.hasOwnProperty(key)) {
brand_options.append($("<option />").val(key).text(key+ " " + el[key]));
}
}
Or use the jquery each:
$.each(top_brands, function(key, value) {
brand_options.append($("<option />").val(key).text(key + " " + value));
});
If you are on mac try this :
cd Users/<Your name>
Make sure that you are on the right path by looking for .gradle with
ls -la
then run that to delete .gradle
rm -rf .gradle
This will remove everything. Then launch your commande again and it will work !
Add newWin.document.close();, like so:
function printDiv() {
var divToPrint = document.getElementById('printArea');
var newWin = window.open();
newWin.document.write(divToPrint.innerHTML);
newWin.document.close();
newWin.print();
newWin.close();
}
This makes IE happy. HTH, -Ted
The best way is you should destroy the slick slider after reinitializing it.
function slickCarousel() {
$('.skills_section').slick({
infinite: true,
slidesToShow: 3,
slidesToScroll: 1
});
}
function destroyCarousel() {
if ($('.skills_section').hasClass('slick-initialized')) {
$('.skills_section').slick('destroy');
}
}
$.ajax({
type: 'get',
url: '/public/index',
dataType: 'script',
data: data_send,
success: function() {
destroyCarousel()
slickCarousel();
}
});
255 characters.
@Html.EnumDropDownListFor(
x => x.YourEnumField,
"Select My Type",
new { @class = "form-control" })
@Html.DropDownList("MyType",
EnumHelper.GetSelectList(typeof(MyType)) ,
"Select My Type",
new { @class = "form-control" })
I rolled Rune's answer into an extension method:
namespace MyApp.Common
{
public static class MyExtensions{
public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
where TEnum : struct, IComparable, IFormattable, IConvertible
{
var values = from TEnum e in Enum.GetValues(typeof(TEnum))
select new { Id = e, Name = e.ToString() };
return new SelectList(values, "Id", "Name", enumObj);
}
}
}
This allows you to write:
ViewData["taskStatus"] = task.Status.ToSelectList();
by using MyApp.Common
Try this
val intent = Intent(this, Page2::class.java)
startActivity(intent)
For those searching this error, another thing that can trigger AtributeError: can't set attribute
is if you try to set a decorated @property
that has no setter method. Not the problem in the OP's question, but I'm putting it here to help any searching for the error message directly. (if you don't like it, go edit the question's title :)
class Test:
def __init__(self):
self._attr = "original value"
# This will trigger an error...
self.attr = "new value"
@property
def attr(self):
return self._attr
Test()
Design code using Bootstrap
<div class="dropdown-menu" id="demolist">_x000D_
<a class="dropdown-item" h ref="#">Cricket</a>_x000D_
<a class="dropdown-item" href="#">UFC</a>_x000D_
<a class="dropdown-item" href="#">Football</a>_x000D_
<a class="dropdown-item" href="#">Basketball</a>_x000D_
</div>
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function () {_x000D_
$('#demolist a').on('click', function () {_x000D_
var txt= ($(this).text());_x000D_
alert("Your Favourite Sports is "+txt);_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
The self answer given by MagngooSasa did the trick, but for anyone else trying to understand the answer, here are a few bit more details:
When developing Cordova apps with Visual Studio, I tried to import a remote JavaScript file [located here http://Guess.What.com/MyScript.js], but I have the error mentioned in the title.
Here is the meta tag before, in the index.html file of the project:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
Here is the corrected meta tag, to allow importing a remote script:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *;**script-src 'self' http://onlineerp.solution.quebec 'unsafe-inline' 'unsafe-eval';** ">
And no more error!
You can use:
db.foo.update({}, {$rename:{"name.additional":"name.last"}}, false, true);
Or to just update the docs which contain the property:
db.foo.update({"name.additional": {$exists: true}}, {$rename:{"name.additional":"name.last"}}, false, true);
The false, true
in the method above are: { upsert:false, multi:true }
. You need the multi:true
to update all your records.
Or you can use the former way:
remap = function (x) {
if (x.additional){
db.foo.update({_id:x._id}, {$set:{"name.last":x.name.additional}, $unset:{"name.additional":1}});
}
}
db.foo.find().forEach(remap);
In MongoDB 3.2 you can also use
db.students.updateMany( {}, { $rename: { "oldname": "newname" } } )
The general syntax of this is
db.collection.updateMany(filter, update, options)
https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/
You need to declare the variable before you include the helpers.js file. Simply create a script tag above the include for helpers.js and define it there.
<script type='text/javascript' >
var myFunctionTag = false;
</script>
<script type='text/javascript' src='js/helpers.js'></script>
...
<script type='text/javascript' >
// rest of your code, which may depend on helpers.js
</script>
Not possible in Java.
Here's the Scala way:
val m = List(5, 4, 2, 89)
for((el, i) <- m.zipWithIndex)
println(el +" "+ i)
Here are some more examples
Run every 6 hours at 46 mins past the hour:
46 */6 * * *
Run at 2:10 am:
10 2 * * *
Run at 3:15 am:
15 3 * * *
Run at 4:20 am:
20 4 * * *
Run at 5:31 am:
31 5 * * *
Run at 5:31 pm:
31 17 * * *
You can use this
<a onClick={() => {window.location.href="/something"}}>Something</a>
use this code to only First letter capitalization for EditText
MainActivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:tag="true">
</EditText>
</RelativeLayout>
MainActivity.java
EditText et = findViewById(R.id.et);
et.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
if (et.getText().toString().length() == 1 && et.getTag().toString().equals("true"))
{
et.setTag("false");
et.setText(et.getText().toString().toUpperCase());
et.setSelection(et.getText().toString().length());
}
if(et.getText().toString().length() == 0)
{
et.setTag("true");
}
}
public void afterTextChanged(Editable editable) {
}
});
If you are asking whether there's shorthand version of operator ..
- no there isn't. You cannot write a ..= b
. You'll have to type it in full: filename = filename .. ".tmp"
I often fix that problem with calc()
. You just give the textarea a width of 100% and a certain amount of padding, but you have to subtract the total left and right padding of the 100% width you have given to the textarea:
textarea {
border: 0px;
width: calc(100% -10px);
padding: 5px;
}
Or if you want to give the textarea a border:
textarea {
border: 1px;
width: calc(100% -12px); /* plus the total left and right border */
padding: 5px;
}
You can use the name property for that particular element. For example to set a border of 2px around an input element with name xyz, you can use;
$(function() {
$("input[name = 'xyz']").css("border","2px solid red");
})
I had to clear
C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files
Only then did the issue get resolved.
You have tried the wrong variable, ints
is not the correct name of the argument.
public int Sum(params int[] customerssalary)
{
return customerssalary.Sum();
}
public double Avg(params int[] customerssalary)
{
return customerssalary.Average();
}
But do you think that these methods are really needed?
Now Update word-wrap is replace by :
overflow-wrap:break-word;
Compatible old navigator and css 3 it's good alternative !
it's evolution of word-wrap ( since 2012... )
See more information : https://www.w3.org/TR/css-text-3/#overflow-wrap
See compatibility full : http://caniuse.com/#search=overflow-wrap
If you want to set specific learning rates for intervals of epochs like 0 < a < b < c < ...
. Then you can define your learning rate as a conditional tensor, conditional on the global step, and feed this as normal to the optimiser.
You could achieve this with a bunch of nested tf.cond
statements, but its easier to build the tensor recursively:
def make_learning_rate_tensor(reduction_steps, learning_rates, global_step):
assert len(reduction_steps) + 1 == len(learning_rates)
if len(reduction_steps) == 1:
return tf.cond(
global_step < reduction_steps[0],
lambda: learning_rates[0],
lambda: learning_rates[1]
)
else:
return tf.cond(
global_step < reduction_steps[0],
lambda: learning_rates[0],
lambda: make_learning_rate_tensor(
reduction_steps[1:],
learning_rates[1:],
global_step,)
)
Then to use it you need to know how many training steps there are in a single epoch, so that we can use the global step to switch at the right time, and finally define the epochs and learning rates you want. So if I want the learning rates [0.1, 0.01, 0.001, 0.0001]
during the epoch intervals of [0, 19], [20, 59], [60, 99], [100, \infty]
respectively, I would do:
global_step = tf.train.get_or_create_global_step()
learning_rates = [0.1, 0.01, 0.001, 0.0001]
steps_per_epoch = 225
epochs_to_switch_at = [20, 60, 100]
epochs_to_switch_at = [x*steps_per_epoch for x in epochs_to_switch_at ]
learning_rate = make_learning_rate_tensor(epochs_to_switch_at , learning_rates, global_step)
Maybe you should try LocallyDB it's easy-to-use and lightweight in addition to the with advanced selecting system similar to javascript conditional expression...
Have the.htaccess file in the application root directory, along with the index.php file. (Check if the htaccess extension is correct , Bz htaccess.txt did not work for me.)
And Add the following rules to .htaccess file,
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
Then find the following line in your application/config/config.php file
$config['index_page'] = 'index.php';
Set the variable empty as below.
$config['index_page'] = '';
That's it, it worked for me.
If it doesn't work further try to replace following variable with these parameters ('AUTO', 'PATH_INFO', 'QUERY_STRING', 'REQUEST_URI', and 'ORIG_PATH_INFO') one by one
$config['uri_protocol'] = 'AUTO';
Use named parameters for readability and to avoid confusions.
@Html.ActionLink(
linkText: "Click Here",
actionName: "Action",
controllerName: "Home",
routeValues: new { Identity = 2577 },
htmlAttributes: null)
Add:
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
To server{} in nginx.conf
Works for me.
Thx for the answer!
raiserror()
works fine but you shouldn't forget the return
statement otherwise the script continues without error! (hense the raiserror isn't a "throwerror" ;-)) and of course doing a rollback if necessary!
raiserror()
is nice to tell the person who executes the script that something went wrong.
I encounter this error when I'm querying an entry of another domain of the forrest and this entry have some custom attribut of the other domain.
To solve this error, I only need to specify the server in the url LDAP :
Path with error = LDAP://CN=MyObj,DC=DOMAIN,DC=COM
Path without error : LDAP://domain.com:389/CN=MyObj,DC=Domain,DC=COM
Another possible option would be to use Datejs
Then you can do
Date.getDaysInMonth(2009, 9)
Although adding a library just for this function is overkill, it's always nice to know all the options you have available to you :)
something like so might work:
<script type="text/javascript">
$(document).ready(function(){
var $input = $("<input name='myField' type='text'>");
$('#section2').append($input);
});
</script>
<form>
<div id="section1"><!-- some controls--></div>
<div id="section2"><!-- for dynamic controls--></div>
</form>
Check the default superclass's constructor. It need be public or protected.
You can open a command prompt and do a
route print
and see your current routing table.
You can modify it by
route add d.d.d.d mask m.m.m.m g.g.g.g
route delete d.d.d.d mask m.m.m.m g.g.g.g
route change d.d.d.d mask m.m.m.m g.g.g.g
these seem to work
I run a ping d.d.d.d -t change the route and it changes. (my test involved routing to a dead route and the ping stopped)
I had this problem and was able to resolve it with the declaration below.
$.fn.bootstrapBtn = $.fn.button.noConflict();
Your error shows you are not compiling file with the definition of the insert
function. Update your command to include the file which contains the definition of that function and it should work.
If column A contains the amounts to be reimbursed, and column B contains the "yes/no" indicating whether the reimbursement has been made, then either of the following will work, though the first option is recommended:
=SUMIF(B:B,"No",A:A)
or
=SUMIFS(A:A,B:B,"No")
Here is an example that will display the amounts paid and outstanding for a small set of sample data.
A B C D
Amount Reimbursed? Total Paid: =SUMIF(B:B,"Yes",A:A)
$100 Yes Total Outstanding: =SUMIF(B:B,"No",A:A)
$200 No
$300 No
$400 Yes
$500 No
I would use lambda
function on a Series
of a DataFrame
like this:
f = lambda x: 0 if x>100 else 1
df['my_column'] = df['my_column'].map(f)
I do not assert that this is an efficient way, but it works fine.
According to the docs of setState()
the new state might not get reflected in the callback function findRoutes()
. Here is the extract from React docs:
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.
There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
So here is what I propose you should do. You should pass the new states input
in the callback function findRoutes()
.
handleFormSubmit: function(input){
// Form Input
this.setState({
originId: input.originId,
destinationId: input.destinationId,
radius: input.radius,
search: input.search
});
this.findRoutes(input); // Pass the input here
}
The findRoutes()
function should be defined like this:
findRoutes: function(me = this.state) { // This will accept the input if passed otherwise use this.state
if (!me.originId || !me.destinationId) {
alert("findRoutes!");
return;
}
var p1 = new Promise(function(resolve, reject) {
directionsService.route({
origin: {'placeId': me.originId},
destination: {'placeId': me.destinationId},
travelMode: me.travelMode
}, function(response, status){
if (status === google.maps.DirectionsStatus.OK) {
// me.response = response;
directionsDisplay.setDirections(response);
resolve(response);
} else {
window.alert('Directions config failed due to ' + status);
}
});
});
return p1
}
No jQuery:
// Return an array of the selected opion values
// select is an HTML select element
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
Quick example:
<select multiple>
<option>opt 1 text
<option value="opt 2 value">opt 2 text
</select>
<button onclick="
var el = document.getElementsByTagName('select')[0];
alert(getSelectValues(el));
">Show selected values</button>
similar to KNaito's answer, the following does the trick for me
function simulateClick() {
var event = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
var cb = document.getElementById('player');
var canceled = !cb.dispatchEvent(event);
if (canceled) {
// A handler called preventDefault.
alert("canceled");
} else {
// None of the handlers called preventDefault.
alert("not canceled");
}
}
Use:
$filelist = @(11, 1, 2)
$filelist | sort @{expression={$_[0]}} |
% {$newName = [string]([int]$($_[0]) + 1)}
New-Item $newName -ItemType Directory
Since link to this question shows up on very top of returned results when you search for "php MSVCR110.dll" (not to mention it got 100k+ views and growing), here're some additional notes that you may find handy in your quest to solve MSVCR110.dll mistery...
The approach described in the answer is valid not only for MSVCR110.dll case but also applies when you are looking for other versions, like newer MSVCR71.dll
and I updated the answer to include VC15 even it's beyond scope of the original question.
On http://windows.php.net/ you can read:
VC9, VC11 and VC15
More recent versions of PHP are built with VC9, VC11 or VC15 (Visual Studio 2008, 2012 or 2015 compiler respectively) and include improvements in performance and stability.
The VC9 builds require you to have the Visual C++ Redistributable for Visual Studio 2008 SP1 x86 or x64 installed.
The VC11 builds require to have the Visual C++ Redistributable for Visual Studio 2012 x86 or x64 installed.
The VC15 builds require to have the Visual C++ Redistributable for Visual Studio 2015 x86 or x64 installed.
This is quite crucial as you not only need to get Visual C++ Redistributable installed but you also need the right version of it, and which one is right and correct, depends on what PHP build you are actually going to use. Pay attention to what version of PHP for Windows you are fetching, especially pay attention to this "VCxx" suffix, because if you install PHP that requires VC9 while having redistributables VC11 installed it is not going to work as run-time dependency is simply not fulfilled. Contrary to what some may think, you need exactly the version required, as newer (higher) releases does NOT cover older (lower) versions. so i.e. VC11 is not providing VC9 compatibility. Also VC15 is neither fulfilling VC11 nor VC9 dependency. It is just VC15 and NOTHING ELSE. Deal with it :)
For example, archive name php-5.6.4-nts-Win32-VC11-x86
tells us the following
Most searches I did lead to VC9 of redistributables, so in case of constant failures to make thing works, if possible, try installing different PHP build, to see if you by any chance do not face mismatching versions.
Download links
Note that you are using 32-bit version of PHP, so you need 32-bit redistributable (x86) even if your version of Windows is 64-bit!
The KILL SESSION
command doesn't actually kill the session. It merely asks the session to kill itself. In some situations, like waiting for a reply from a remote database or rolling back transactions, the session will not kill itself immediately and will wait for the current operation to complete. In these cases the session will have a status of "marked for kill". It will then be killed as soon as possible.
Check the status to confirm:
SELECT sid, serial#, status, username FROM v$session;
You could also use IMMEDIATE clause:
ALTER SYSTEM KILL SESSION 'sid,serial#' IMMEDIATE;
The IMMEDIATE
clause does not affect the work performed by the command, but it returns control back to the current session immediately, rather than waiting for confirmation of the kill. Have a look at Killing Oracle Sessions.
Update If you want to kill all the sessions, you could just prepare a small script.
SELECT 'ALTER SYSTEM KILL SESSION '''||sid||','||serial#||''' IMMEDIATE;' FROM v$session;
Spool the above to a .sql
file and execute it, or, copy paste the output and run it.
You can download the xgboost package to your local computer, and you better place the xgboost source file under D:\ or C:\ (ps: download address: http://www.lfd.uci.edu/~gohlke/pythonlibs/#xgboost, and select "xgboost-0.6-cp35-cp35m-win_amd64.whl",but it is up to your operation system), and you open the Anaconda prompt, type in pip install D:\xgboost-0.6-cp35-cp35m-win_amd64.whl
, then you can successful install xgboost into your anaconda
A[A==NDV]=numpy.nan
A==NDV will produce a boolean array that can be used as an index for A
ProxyCommand nc -proxy xxx.com:8080 %h %p
remove -X connect
and use -proxy
instead.
Worked for me.
Reinstall node, then update npm.
First I removed node
apt-get purge node
Then install node according to the distibution. Docs here .
Then
npm install npm@latest -g
function closeWindow() {
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
alert("This will close the window");
window.open('','_self');
window.close();
}
closeWindow();
I have tried &, but it didn't work. Based on Wim ten Brink's answer I tried &amp and it worked.
One of my fellow developers suggested me to use & and that worked regardless of how many times it may be rendered.
Eclipse -> Preferences -> Java -> Build Path -> User Libraries -> New(Name it) -> Add external Jars
(I recommend dragging your new libraries into the eclipse folder before any of these steps to keep everything together, that way if you reinstall Eclipse or your OS you won't have to rwlink anything except the JDK) Now select the jar files you want. Click OK.
Right click on your project and choose Build Path -> Add Library
FYI just code and then right click and Source->Organize Imports
select sum(qty), name
from (
select count(m.owner_id) as qty, o.name
from transport t,owner o,motorbike m
where t.type='motobike' and o.owner_id=m.owner_id
and t.type_id=m.motorbike_id
group by m.owner_id
union all
select count(c.owner_id) as qty, o.name,
from transport t,owner o,car c
where t.type='car' and o.owner_id=c.owner_id and t.type_id=c.car_id
group by c.owner_id
) t
group by name
$user->data
is an array of objects. Each element in the array has a name
and value
property (as well as others).
Try putting the 2nd foreach
inside the 1st.
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}
Simple way - you can specify .* in the beginning because find matches the whole path.
$ find . -regextype egrep -regex '.*[a-f0-9\-]{36}\.jpg$'
find version
$ find --version
find (GNU findutils) 4.6.0
Copyright (C) 2015 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
<http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Eric B. Decker, James Youngman, and Kevin Dalley.
Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION
FTS(FTS_CWDFD) CBO(level=2)
daniele3004's answer is already pretty good.
Just a quick and dirty formula for people like me who mixes up run
and start
from time to time:
docker run [...]
= docker pull [...]
+ docker start [...]
This example program illustrates initialization of an array of C strings.
#include <stdio.h>
const char * array[] = {
"First entry",
"Second entry",
"Third entry",
};
#define n_array (sizeof (array) / sizeof (const char *))
int main ()
{
int i;
for (i = 0; i < n_array; i++) {
printf ("%d: %s\n", i, array[i]);
}
return 0;
}
It prints out the following:
0: First entry
1: Second entry
2: Third entry
robocopy also tends to print empty lines even if it does not do anything. I'm filtering empty lines away using command like this:
robocopy /NDL /NJH /NJS /NP /NS /NC %fromDir% %toDir% %filenames% | findstr /r /v "^$"
Both
SuperClass.__init__(self, x)
or
super(SubClass,self).__init__( x )
will work (I prefer the 2nd one, as it adheres more to the DRY principle).
See here: http://docs.python.org/reference/datamodel.html#basic-customization
Use the requests library, pretty print the results so you can better locate the keys/values you want to extract, and then use nested for loops to parse the data. In the example I extract step by step driving directions.
import json, requests, pprint
url = 'http://maps.googleapis.com/maps/api/directions/json?'
params = dict(
origin='Chicago,IL',
destination='Los+Angeles,CA',
waypoints='Joplin,MO|Oklahoma+City,OK',
sensor='false'
)
data = requests.get(url=url, params=params)
binary = data.content
output = json.loads(binary)
# test to see if the request was valid
#print output['status']
# output all of the results
#pprint.pprint(output)
# step-by-step directions
for route in output['routes']:
for leg in route['legs']:
for step in leg['steps']:
print step['html_instructions']
hash {}
hash[:a] = 'a'
hash[:b] = 'b'
hash = {:a => 'a' , :b = > b}
You might get your key and value from user input, so you can use Ruby .to_sym can convert a string to a symbol, and .to_i will convert a string to an integer.
For example:
movies ={}
movie = gets.chomp
rating = gets.chomp
movies[movie.to_sym] = rating.to_int
# movie will convert to a symbol as a key in our hash, and
# rating will be an integer as a value.
This below-given commands worked for me.
npm cache clean --force
npm install -g webpack
Note - Run these commands as administrator. Once installed then close your command prompt and restart it to see the applied changes.
For set tint for an image view programmatically in android
I have two methods for android :
1)
imgView.setColorFilter(context.getResources().getColor(R.color.blue));
2)
DrawableCompat.setTint(imgView.getDrawable(),
ContextCompat.getColor(context, R.color.blue));
I hope I helped anyone out :-)
Here's one: (check out http://hongouru.blogspot.ie/2011/09/c-ocr-optical-character-recognition.html or http://www.codeproject.com/Articles/41709/How-To-Use-Office-2007-OCR-Using-C for more info)
using MODI;
static void Main(string[] args)
{
DocumentClass myDoc = new DocumentClass();
myDoc.Create(@"theDocumentName.tiff"); //we work with the .tiff extension
myDoc.OCR(MiLANGUAGES.miLANG_ENGLISH, true, true);
foreach (Image anImage in myDoc.Images)
{
Console.WriteLine(anImage.Layout.Text); //here we cout to the console.
}
}
You can try to use the following code instead:
$pro= model_name::where('col_name', '=', 'value')->get();
I got this working with Bitbucket's Markdown by using a empty link:
[]() |
------|------
Row 1 | row 2
I have used an emulator for API Level 23, which does not take keyboard input for installed apk. So I have created new emulator for API Level 29, and then it works. Following is the step to install new emulator.
The window
is the actual global object.
The screen
is the screen, it contains properties about the user's display.
The document
is where the DOM is.
import platform
platform.architecture()
From the Python docs:
Queries the given executable (defaults to the Python interpreter binary) for various architecture information.
Returns a tuple (bits, linkage) which contain information about the bit architecture and the linkage format used for the executable. Both values are returned as strings.
For better understanding I have written similar MySQL query.
Selecting specific fields
MongoDB : db.collection_name.find({},{name:true,email:true,phone:true});
MySQL : SELECT name,email,phone FROM table_name;
Selecting specific fields with where clause
MongoDB : db.collection_name.find({email:'[email protected]'},{name:true,email:true,phone:true});
MySQL : SELECT name,email,phone FROM table_name WHERE email = '[email protected]';
You should \usepackage{longtable}
.
For my case it was due to Intellij IDEA by default set Java 11 as default project SDK, but project was implemented in Java 8. I've changed "Project SDK" in File -> Project Structure -> Project (in Project Settings)
That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.
The HTML in your example will be:
<tr>
<td>TEST</td>
</tr>
Read the PHP documentation that explains it.
Apparently, the compiler thinks NSSearchPathDirectory:0
is an array, and of course it expects the type NSSearchPathDirectory
instead. Certainly not a helpful error message.
But as to the reasons:
First, you are confusing the argument names and types. Take a look at the function definition:
func NSSearchPathForDirectoriesInDomains(
directory: NSSearchPathDirectory,
domainMask: NSSearchPathDomainMask,
expandTilde: Bool) -> AnyObject[]!
directory
and domainMask
are the names, you are using the types, but you should leave them out for functions anyway. They are used primarily in methods.So that leaves us with (updated for Swift 2.0):
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
and for Swift 3:
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
Here's a minimalist way to do it.
System.out.print("Please enter an integer: ");
while(!scan.hasNextInt()) scan.next();
int demoInt = scan.nextInt();
Just sort the array in ascending order and print it backwards.
Arrays.sort(arr);
for(int i = arr.length-1; i >= 0 ; i--) {
//print arr[i]
}
read filename ;
sed -i 's/letter/newletter/g' "$filename" #letter
^use as many of these as you need, and you can make your own BASIC encryption
No need for a plugin to check if outside of view port.
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
var d = $(document).scrollTop();
$.each($("div"),function(){
p = $(this).position();
//vertical
if (p.top > h + d || p.top > h - d){
console.log($(this))
}
//horizontal
if (p.left < 0 - $(this).width() || p.left > w){
console.log($(this))
}
});
JSONP is essentially, JSON with extra code, like a function call wrapped around the data. It allows the data to be acted on during parsing.
To check if a grammar is LL(1), one option is to construct the LL(1) parsing table and check for any conflicts. These conflicts can be
Let's try this on your grammar by building the FIRST and FOLLOW sets for each of the nonterminals. Here, we get that
FIRST(X) = {a, b, z}
FIRST(Y) = {b, epsilon}
FIRST(Z) = {epsilon}
We also have that the FOLLOW sets are
FOLLOW(X) = {$}
FOLLOW(Y) = {z}
FOLLOW(Z) = {z}
From this, we can build the following LL(1) parsing table:
a b z $
X a Yz Yz
Y bZ eps
Z eps
Since we can build this parsing table with no conflicts, the grammar is LL(1).
To check if a grammar is LR(0) or SLR(1), we begin by building up all of the LR(0) configurating sets for the grammar. In this case, assuming that X is your start symbol, we get the following:
(1)
X' -> .X
X -> .Yz
X -> .a
Y -> .
Y -> .bZ
(2)
X' -> X.
(3)
X -> Y.z
(4)
X -> Yz.
(5)
X -> a.
(6)
Y -> b.Z
Z -> .
(7)
Y -> bZ.
From this, we can see that the grammar is not LR(0) because there are shift/reduce conflicts in states (1) and (6). Specifically, because we have the reduce items Z → . and Y → ., we can't tell whether to reduce the empty string to these symbols or to shift some other symbol. More generally, no grammar with ε-productions is LR(0).
However, this grammar might be SLR(1). To see this, we augment each reduction with the lookahead set for the particular nonterminals. This gives back this set of SLR(1) configurating sets:
(1)
X' -> .X
X -> .Yz [$]
X -> .a [$]
Y -> . [z]
Y -> .bZ [z]
(2)
X' -> X.
(3)
X -> Y.z [$]
(4)
X -> Yz. [$]
(5)
X -> a. [$]
(6)
Y -> b.Z [z]
Z -> . [z]
(7)
Y -> bZ. [z]
Now, we don't have any more shift-reduce conflicts. The conflict in state (1) has been eliminated because we only reduce when the lookahead is z, which doesn't conflict with any of the other items. Similarly, the conflict in (6) is gone for the same reason.
Hope this helps!
There are 5 6 NINE (or 63*, depending how you count) different ways to write multi-line strings in YAML.
Use >
most of the time: interior line breaks are stripped out, although you get one at the end:
key: >
Your long
string here.
Use |
if you want those linebreaks to be preserved as \n
(for instance, embedded markdown with paragraphs).
key: |
### Heading
* Bullet
* Points
Use >-
or |-
instead if you don't want a linebreak appended at the end.
Use "..."
if you need to split lines in the middle of words or want to literally type linebreaks as \n
:
key: "Antidisestab\
lishmentarianism.\n\nGet on it."
YAML is crazy.
>
, |
)These allow characters such as \
and "
without escaping, and add a new line (\n
) to the end of your string.
>
Folded style removes single newlines within the string (but adds one at the end, and converts double newlines to singles):
Key: >
this is my very very very
long string
? this is my very very very long string\n
|
Literal style turns every newline within the string into a literal newline, and adds one at the end:
Key: |
this is my very very very
long string
? this is my very very very\nlong string\n
Here's the official definition from the YAML Spec 1.2
Scalar content can be written in block notation, using a literal style (indicated by “|”) where all line breaks are significant. Alternatively, they can be written with the folded style (denoted by “>”) where each line break is folded to a space unless it ends an empty or a more-indented line.
>-
, |-
, >+
, |+
)You can control the handling of the final new line in the string, and any trailing blank lines (\n\n
) by adding a block chomping indicator character:
>
, |
: "clip": keep the line feed, remove the trailing blank lines.>-
, |-
: "strip": remove the line feed, remove the trailing blank lines.>+
, |+
: "keep": keep the line feed, keep trailing blank lines.
, "
, '
)These have limited escaping, and construct a single-line string with no new line characters. They can begin on the same line as the key, or with additional newlines first.
plain style (no escaping, no #
or :
combinations, limits on first character):
Key: this is my very very very
long string
double-quoted style (\
and "
must be escaped by \
, newlines can be inserted with a literal \n
sequence, lines can be concatenated without spaces with trailing \
):
Key: "this is my very very \"very\" loooo\
ng string.\n\nLove, YAML."
→ "this is my very very \"very\" loooong string.\n\nLove, YAML."
single-quoted style (literal '
must be doubled, no special characters, possibly useful for expressing strings starting with double quotes):
Key: 'this is my very very "very"
long string, isn''t it.'
→ "this is my very very \"very\" long string, isn't it."
In this table, _
means space character
. \n
means "newline character" (\n
in JavaScript), except for the "in-line newlines" row, where it means literally a backslash and an n).
> | " ' >- >+ |- |+
-------------------------|------|-----|-----|-----|------|------|------|------
Trailing spaces | Kept | Kept | | | | Kept | Kept | Kept | Kept
Single newline => | _ | \n | _ | _ | _ | _ | _ | \n | \n
Double newline => | \n | \n\n | \n | \n | \n | \n | \n | \n\n | \n\n
Final newline => | \n | \n | | | | | \n | | \n
Final dbl nl's => | | | | | | | Kept | | Kept
In-line newlines | No | No | No | \n | No | No | No | No | No
Spaceless newlines| No | No | No | \ | No | No | No | No | No
Single quote | ' | ' | ' | ' | '' | ' | ' | ' | '
Double quote | " | " | " | \" | " | " | " | " | "
Backslash | \ | \ | \ | \\ | \ | \ | \ | \ | \
" #", ": " | Ok | Ok | No | Ok | Ok | Ok | Ok | Ok | Ok
Can start on same | No | No | Yes | Yes | Yes | No | No | No | No
line as key |
Note the trailing spaces on the line before "spaces."
- >
very "long"
'string' with
paragraph gap, \n and
spaces.
- |
very "long"
'string' with
paragraph gap, \n and
spaces.
- very "long"
'string' with
paragraph gap, \n and
spaces.
- "very \"long\"
'string' with
paragraph gap, \n and
s\
p\
a\
c\
e\
s."
- 'very "long"
''string'' with
paragraph gap, \n and
spaces.'
- >-
very "long"
'string' with
paragraph gap, \n and
spaces.
[
"very \"long\" 'string' with\nparagraph gap, \\n and spaces.\n",
"very \"long\"\n'string' with\n\nparagraph gap, \\n and \nspaces.\n",
"very \"long\" 'string' with\nparagraph gap, \\n and spaces.",
"very \"long\" 'string' with\nparagraph gap, \n and spaces.",
"very \"long\" 'string' with\nparagraph gap, \\n and spaces.",
"very \"long\" 'string' with\nparagraph gap, \\n and spaces."
]
Just in case the above isn't enough for you, you can add a "block indentation indicator" (after your block chomping indicator, if you have one):
- >8
My long string
starts over here
- |+1
This one
starts here
If you insert extra spaces at the start of not-the-first lines in Folded style, they will be kept, with a bonus newline. This doesn't happen with flow styles:
- >
my long
string
- my long
string
? ["my long\n string\n", "my long string"]
I can't even.
*
2 block styles, each with 2 possible block chomping indicators (or none), and with 9 possible indentation indicators (or none), 1 plain style and 2 quoted styles: 2 x (2 + 1) x (9 + 1) + 1 + 2 = 63
Some of this information has also been summarised here.
Static Typing: The languages such as Java and Scala are static typed.
The variables have to be defined and initialized before they are used in a code.
for ex. int x; x = 10;
System.out.println(x);
Dynamic Typing: Perl is an dynamic typed language.
Variables need not be initialized before they are used in code.
y=10; use this variable in the later part of code
Made a tiny program that accomplishes that:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[8192] = "string"; // string
size_t len = strlen(str)-1; // get string length and reduce 1
while(len+1 > 0) // Loop for every character on string
{
printf("%c",str[len--]); // Print string reversed and reducing len by one
}
return 0; // Quit program
}
Explanation:
We take the length of the string, and then we start looping by the last position until we arrive to index 0 quit program.
As a hack, you could consider having a special handling on the client side, converting 'Null' string to something that will never occur, for example, XXNULLXX and converting back on the server.
It is not pretty, but it may solve the issue for such a boundary case.
I think I see your problem, you need to use the @
syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?
This is what I can suggest based on what I see so far:
.factory('MagComments', function ($resource) {
return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
loginID : organEntity,
password : organCommpassword,
id : '@magId'
});
})
The @magId
string will tell the resource to replace :id
with the property magId
on the object you pass it as parameters.
I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.
To get upper case version of a string you can use str.upper
:
s = 'sdsd'
s.upper()
#=> 'SDSD'
On the other hand string.ascii_uppercase
is a string containing all ASCII letters in upper case:
import string
string.ascii_uppercase
#=> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Check this out:
XAML:
<DataGrid Name="DataGrid1">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Click="ChangeText">Show/Hide</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Method:
private void ChangeText(object sender, RoutedEventArgs e)
{
DemoModel model = (sender as Button).DataContext as DemoModel;
model.DynamicText = (new Random().Next(0, 100).ToString());
}
Class:
class DemoModel : INotifyPropertyChanged
{
protected String _text;
public String Text
{
get { return _text; }
set { _text = value; RaisePropertyChanged("Text"); }
}
protected String _dynamicText;
public String DynamicText
{
get { return _dynamicText; }
set { _dynamicText = value; RaisePropertyChanged("DynamicText"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(String propertyName)
{
PropertyChangedEventHandler temp = PropertyChanged;
if (temp != null)
{
temp(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Initialization Code:
ObservableCollection<DemoModel> models = new ObservableCollection<DemoModel>();
models.Add(new DemoModel() { Text = "Some Text #1." });
models.Add(new DemoModel() { Text = "Some Text #2." });
models.Add(new DemoModel() { Text = "Some Text #3." });
models.Add(new DemoModel() { Text = "Some Text #4." });
models.Add(new DemoModel() { Text = "Some Text #5." });
DataGrid1.ItemsSource = models;
You can do it like this:
using System.IO;
static void Main(string[] args)
{
using(var reader = new StreamReader(@"C:\test.csv"))
{
List<string> listA = new List<string>();
List<string> listB = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
listA.Add(values[0]);
listB.Add(values[1]);
}
}
}
Okay, so if you don't have LINQ, you could hard-code it:
public int FindMaxAge(List<MyType> list)
{
if (list.Count == 0)
{
throw new InvalidOperationException("Empty list");
}
int maxAge = int.MinValue;
foreach (MyType type in list)
{
if (type.Age > maxAge)
{
maxAge = type.Age;
}
}
return maxAge;
}
Or you could write a more general version, reusable across lots of list types:
public int FindMaxValue<T>(List<T> list, Converter<T, int> projection)
{
if (list.Count == 0)
{
throw new InvalidOperationException("Empty list");
}
int maxValue = int.MinValue;
foreach (T item in list)
{
int value = projection(item);
if (value > maxValue)
{
maxValue = value;
}
}
return maxValue;
}
You can use this with:
// C# 2
int maxAge = FindMaxValue(list, delegate(MyType x) { return x.Age; });
// C# 3
int maxAge = FindMaxValue(list, x => x.Age);
Or you could use LINQBridge :)
In each case, you can return the if block with a simple call to Math.Max
if you want. For example:
foreach (T item in list)
{
maxValue = Math.Max(maxValue, projection(item));
}
cursor are used because in sub query we can fetch record row by row so we use cursor to fetch records
Example of cursor:
DECLARE @eName varchar(50), @job varchar(50)
DECLARE MynewCursor CURSOR -- Declare cursor name
FOR
Select eName, job FROM emp where deptno =10
OPEN MynewCursor -- open the cursor
FETCH NEXT FROM MynewCursor
INTO @eName, @job
PRINT @eName + ' ' + @job -- print the name
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM MynewCursor
INTO @ename, @job
PRINT @eName +' ' + @job -- print the name
END
CLOSE MynewCursor
DEALLOCATE MynewCursor
OUTPUT:
ROHIT PRG
jayesh PRG
Rocky prg
Rocky prg
I encountered this error using IIS 7.0 with a custom 404 error page, although I suspect this will happen with any 404 page. The server returned an html 404 response with a text/html mime type which could not (rightly) be executed.
In my case the site that I'm connecting to has upgraded to TLS 1.2. As a result I had to install .net 4.5.2 on my web server in order to support it.
BEGIN;
INSERT INTO test_b (price_sum)
SELECT price
FROM test_a;
INSERT INTO test_c (price_summ)
SELECT price
FROM test_a;
COMMIT;
For Python 3, I'm using this function:
def user_prompt(question: str) -> bool:
""" Prompt the yes/no-*question* to the user. """
from distutils.util import strtobool
while True:
user_input = input(question + " [y/n]: ")
try:
return bool(strtobool(user_input))
except ValueError:
print("Please use y/n or yes/no.\n")
The strtobool()
function converts a string into a bool. If the string cant be parsed it will raise a ValueError.
In Python 3 raw_input()
has been renamed to input()
.
As Geoff said, strtobool actually returns 0 or 1, therefore the result has to be cast to bool.
This is the implementation of strtobool
, if you want special words to be recognized as true
, you can copy the code and add your own cases.
def strtobool (val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ('y', 'yes', 't', 'true', 'on', '1'):
return 1
elif val in ('n', 'no', 'f', 'false', 'off', '0'):
return 0
else:
raise ValueError("invalid truth value %r" % (val,))
You can add option using following syntax, Also you can visit to way handle option in jQuery for more details.
$('#select').append($('<option>', {value:1, text:'One'}));
$('#select').append('<option value="1">One</option>');
var option = new Option(text, value); $('#select').append($(option));
with a form, just set method
to "post"
<form action="blah.php" method="post">
<input type="text" name="data" value="mydata" />
<input type="submit" />
</form>
1) Go to C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A for VS2013
2) Copy the folders Include
and Lib
(you should check where are your folders in folder windows such as v7.1
, v8
, v6
, etc.)
3) Paste them into C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC
I solved my problems like:
error lnk1104: cannot open file 'kernel32.lib'.
error c1083: Cannot open Windows.h
Thanks.
Just did this on Solaris and ran into this identical problem where even "java -version" does not work. There is a reason that the 64 bit versions of the distro are WAY smaller than the 32-bit. It is indeed as stated above:
In other words, to get a fully working 64-bit installation, you must first run the 32-bit installation, and follow that up with a 64-bit installation if you have a 64bit capable machine...
So I ran the installer for the 32-bit:
sh jdk-6u131-solaris-sparc.sh
Then I ran the installer for the 64-bit:
sh jdk-6u131-solaris-sparcv9.sh
This gives me several java executables to choose from:
The sparcv9 java's are the 64bit versions and they work with "-version" when installed alongside the 32bit JDK.
-Dan
You can use y.count()
.
It will return the integer value of the number of times a sub string appears in a string.
For example:
string.count("bah") >> 0
string.count("Hello") >> 1
I have used the following procedure.
Procedure to install the apk files in Android Emulator(AVD):
Check your installed directory(ex: C:\Program Files (x86)\Android\android-sdk\platform-tools), whether it has the adb.exe or not). If not present in this folder, then download the attachment here, extract the zip files. You will get adb files, copy and paste those three files inside tools folder
Run AVD manager from C:\Program Files (x86)\Android\android-sdk and start the Android Emulator.
Copy and paste the apk file inside the C:\Program Files (x86)\Android\android-sdk\platform-tools
Go to Start -> Run -> cmd
Type cd “C:\Program Files (x86)\Android\android-sdk\platform-tools”
Type adb install example.apk
After getting success command
Go to Application icon in Android emulator, we can see the your application
I think you can try to firstly select all the text in the field and then send the new sequence:
from selenium.webdriver.common.keys import Keys
element.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");
Create a scope property called selectedIndex, and an itemClicked function:
function MyController ($scope) {
$scope.collection = ["Item 1", "Item 2"];
$scope.selectedIndex = 0; // Whatever the default selected index is, use -1 for no selection
$scope.itemClicked = function ($index) {
$scope.selectedIndex = $index;
};
}
Then my template would look something like this:
<div>
<span ng-repeat="item in collection"
ng-class="{ 'selected-class-name': $index == selectedIndex }"
ng-click="itemClicked($index)"> {{ item }} </span>
</div>
Just for reference $index is a magic variable available within ng-repeat directives.
You can use this same sample within a directive and template as well.
Here is a working plnkr:
If you prefer not to use regex, you might try
''.join([i for i in s if i.isalpha()])
For me, fny answers really got it all. since fetch is not throwing error, we need to throw/handle the error ourselves. Posting my solution with async/await. I think it's more strait forward and readable
Solution 1: Not throwing an error, handle the error ourselves
async _fetch(request) {
const fetchResult = await fetch(request); //Making the req
const result = await fetchResult.json(); // parsing the response
if (fetchResult.ok) {
return result; // return success object
}
const responseError = {
type: 'Error',
message: result.message || 'Something went wrong',
data: result.data || '',
code: result.code || '',
};
const error = new Error();
error.info = responseError;
return (error);
}
Here if we getting an error, we are building an error object, plain JS object and returning it, the con is that we need to handle it outside. How to use:
const userSaved = await apiCall(data); // calling fetch
if (userSaved instanceof Error) {
debug.log('Failed saving user', userSaved); // handle error
return;
}
debug.log('Success saving user', userSaved); // handle success
Solution 2: Throwing an error, using try/catch
async _fetch(request) {
const fetchResult = await fetch(request);
const result = await fetchResult.json();
if (fetchResult.ok) {
return result;
}
const responseError = {
type: 'Error',
message: result.message || 'Something went wrong',
data: result.data || '',
code: result.code || '',
};
let error = new Error();
error = { ...error, ...responseError };
throw (error);
}
Here we are throwing and error that we created, since Error ctor approve only string, Im creating the plain Error js object, and the use will be:
try {
const userSaved = await apiCall(data); // calling fetch
debug.log('Success saving user', userSaved); // handle success
} catch (e) {
debug.log('Failed saving user', userSaved); // handle error
}
Solution 3: Using customer error
async _fetch(request) {
const fetchResult = await fetch(request);
const result = await fetchResult.json();
if (fetchResult.ok) {
return result;
}
throw new ClassError(result.message, result.data, result.code);
}
And:
class ClassError extends Error {
constructor(message = 'Something went wrong', data = '', code = '') {
super();
this.message = message;
this.data = data;
this.code = code;
}
}
Hope it helped.
For Xcode 4 and higher, open the preferences (command+,) and check "Show: Line numbers" in the "Text Editing" section.
Xcode 8 and below
Read the Request.Form NameValueCollection and process your logic accordingly:
NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
userName = nvc["txtUserName"];
}
if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
password = nvc["txtPassword"];
}
//Process login
CheckLogin(userName, password);
... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.
The fastest way that I've found is:
// Open the file
$fp = @fopen($filename, 'r');
// Add each line to an array
if ($fp) {
$array = explode("\n", fread($fp, filesize($filename)));
}
where $filename is going to be the path & name of your file, eg. ../filename.txt.
Depending how you've set up your text file, you'll have might have to play around with the \n bit.
Another good approach and one that is a bit more elegant is as follows:
watch:{
'item.someOtherProp': function (newVal, oldVal){
//to work with changes in someOtherProp
},
'item.prop': function(newVal, oldVal){
//to work with changes in prop
}
}
(I learned this approach from @peerbolte in the comment here)
The other answers are totally fine:
However, if you still want a typed variant, there is a built-in solution since Python 3.5.
Generic classes:
from typing import TypeVar, Generic
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
# Create an empty list with items of type T
self.items: List[T] = []
def push(self, item: T) -> None:
self.items.append(item)
def pop(self) -> T:
return self.items.pop()
def empty(self) -> bool:
return not self.items
# Construct an empty Stack[int] instance
stack = Stack[int]()
stack.push(2)
stack.pop()
stack.push('x') # Type error
Generic functions:
from typing import TypeVar, Sequence
T = TypeVar('T') # Declare type variable
def first(seq: Sequence[T]) -> T:
return seq[0]
def last(seq: Sequence[T]) -> T:
return seq[-1]
n = first([1, 2, 3]) # n has type int.
Reference: mypy documentation about generics.
git log --full-history -- [file path]
shows the changes of a file and works even if the file was deleted.
Example:
git log --full-history -- myfile
If you want to see only the last commit, which deleted the file, use -1
in addition to the command above. Example:
git log --full-history -1 -- [file path]
See also my article: Which commit deleted a file.
It cannot be done. It is impossible.
I had to install the older versions of gcc, g++.
sudo apt-get install gcc-4.4
sudo apt-get install g++-4.4
Check that gcc-4.4 is in /usr/bin/, and same for g++ Then I could use the solution above:
sudo ln -s /usr/bin/gcc-4.4 /opt/cuda/bin/gcc
sudo ln -s /usr/bin/g++-4.4 /opt/cuda/bin/g++
You can take a snapshot of the complete status of your cluster (including all data indices) and restore them (using the restore API) in the new cluster or server.