I would choose Sequelize because of it's excellent documentation. It's just a honest opinion (I never really used MySQL with Node that much).
You can use MSSQL Server Auditing feature. From version SQL Server 2012 you will find this feature in all editions:
Use Entry.insert
. For example:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()
Or use textvariable
option:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()
Reason of the error: Package name left blank while creating a class. This make use of default package. Thus causes this error.
Quick fix:
helloWorld
inside the src
folder.helloWorld.java
file in that package. Just drag and drop on
the package. Error should disappear.Explanation:
Latest version of Eclipse required java11 or above. The module
feature is introduced in java9 and onward. It was proposed in 2005 for Java7 but later suspended. Java is object oriented based. And module is the moduler approach which can be seen in language like C. It was harder to implement it, due to which it took long time for the release. Source: Understanding Java 9 Modules
When you create a new project in Eclipse then by default module feature is selected. And in Eclipse-2020-09-R, a pop-up appears which ask for creation of module-info.java
file. If you select don't create
then module-info.java
will not create and your project will free from this issue.
Best practice is while crating project, after giving project name. Click on next
button instead of finish
. On next page at the bottom it ask for creation of module-info.java
file. Select or deselect as per need.
If selected: (by default) click on finish
button and give name for module. Now while creating a class don't forget to give package name. Whenever you create a class just give package name. Any name, just don't left it blank.
If deselect: No issue
I don't know about your Spring/JAXB combination, but the average REST webservice won't return a response body on POST/PUT, just a response status. You'd like to determine it instead of the body.
Replace
InputStream response = con.getInputStream();
by
int status = con.getResponseCode();
All available status codes and their meaning are available in the HTTP spec, as linked before. The webservice itself should also come along with some documentation which overviews all status codes supported by the webservice and their special meaning, if any.
If the status starts with 4nn
or 5nn
, you'd like to use getErrorStream()
instead to read the response body which may contain the error details.
InputStream error = con.getErrorStream();
I used the solution below to export all datagrid values to a text file, rather than using the column names you can use the column index instead.
foreach (DataGridViewRow row in xxxCsvDG.Rows)
{
File.AppendAllText(csvLocation, row.Cells[0].Value + "," + row.Cells[1].Value + "," + row.Cells[2].Value + "," + row.Cells[3].Value + Environment.NewLine);
}
If you use Eclipse you can visually compare your current branch on the workspace with another tag/branch:
You can load the text file into a textfile Hive table and then insert the data from this table into your sequencefile.
Start with a tab delimited file:
% cat /tmp/input.txt
a b
a2 b2
create a sequence file
hive> create table test_sq(k string, v string) stored as sequencefile;
try to load; as expected, this will fail:
hive> load data local inpath '/tmp/input.txt' into table test_sq;
But with this table:
hive> create table test_t(k string, v string) row format delimited fields terminated by '\t' stored as textfile;
The load works just fine:
hive> load data local inpath '/tmp/input.txt' into table test_t;
OK
hive> select * from test_t;
OK
a b
a2 b2
Now load into the sequence table from the text table:
insert into table test_sq select * from test_t;
Can also do load/insert with overwrite to replace all.
This is useful to check the status of autocommit;
select @@autocommit;
You will get this error when you call any of the setXxx()
methods on PreparedStatement
, while the SQL query string does not have any placeholders ?
for this.
For example this is wrong:
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (val1, val2, val3)";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1); // Fail.
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);
You need to fix the SQL query string accordingly to specify the placeholders.
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1);
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);
Note the parameter index starts with 1
and that you do not need to quote those placeholders like so:
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES ('?', '?', '?')";
Otherwise you will still get the same exception, because the SQL parser will then interpret them as the actual string values and thus can't find the placeholders anymore.
I know this is an old post, but I just found this piece of gold. This is old (2006), but still works with IE9. I personnally added a bookmark with this.
Just copy paste this in your browser's address bar:
javascript:void(window.open("javascript:document.open(\"text/plain\");document.write(opener.document.body.parentNode.outerHTML)"))
As for firefox, web developper tool bar does the job. I usually use this, but sometimes, some dirty 3rd party asp.net controls generates differents markups based on the user agent...
EDIT
As Bryan pointed in the comment, some browser remove the javascript:
part when copy/pasting in url bar. I just tested and that's the case with IE10.
Well, apparently I had to change my PUT calling function updateUser
. I removed the @Consumes
, the @RequestMapping
and also added a @ResponseBody
to the function. So my method looked like this:
@RequestMapping(value="/{id}",method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public void updateUser(@PathVariable int id, @RequestBody User temp){
Set<User> set1= obj2.getUsers();
for(User a:set1)
{
if(id==a.getId())
{
set1.remove(a);
a.setId(temp.getId());
a.setName(temp.getName());
set1.add(a);
}
}
Userlist obj3=new Userlist(set1);
obj2=obj3;
}
And it worked!!! Thank you all for the response.
if(getResult.Key.Equals(default(T)) && getResult.Value.Equals(default(U)))
try to use proper tags for HTML5 controls Like for Number(integers)
<input type='number' min='0' pattern ='[0-9]*' step='1'/>
for Decimals or float
<input type='number' min='0' step='Any'/>
step='Any' Without this you cannot submit your form entering any decimal or float value like 3.5 or 4.6 in the above field.
Try fixing the pattern , type for HTML5 controls to fix this issue.
Try restarting the system! You will be able to find the navigator once you restart the system after installation.
I don't think it is necessary to "host" the content using the way from the accepted answer. It is too complicated for a normal user with limited developing skills.
Google actually has provided hosting feature without using Drive SDK/API, what you need is just few clicks. Check this out:
http://support.google.com/drive/bin/answer.py?hl=en&answer=2881970
It is the same to the answer of user1557669. However, in step 4, the URL is not correct, it is like:
https://drive.google.com/#folders/...
To get the correct host URL. Right click on the html file (you have to finish 1-3 steps first and put the html in the public shared folder), and select "Details" from the context menu. You will find the hosting URL right close to the bottom of the details panel. It should look like:
https://googledrive.com/host/.../abc.html
Then you can share the link to anyone. Happy sharing.
If you're developing something more complicated and want multiple columns to be fixed/stuck to the left, you'll probably need something like this.
.wrapper {_x000D_
overflow-x: scroll;_x000D_
}_x000D_
_x000D_
td {_x000D_
min-width: 50px;_x000D_
}_x000D_
_x000D_
.fixed {_x000D_
position: absolute;_x000D_
background: #aaa;_x000D_
}
_x000D_
<div class="content" style="width: 400px">_x000D_
_x000D_
<div class="wrapper" style="margin-left: 100px">_x000D_
_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th class="fixed" style="left: 0px">aaa</th>_x000D_
<th class="fixed" style="left: 50px">aaa2</th>_x000D_
<th>a</th>_x000D_
<th>b</th>_x000D_
<th>c</th>_x000D_
<th>d</th>_x000D_
<th>e</th>_x000D_
<th>f</th>_x000D_
<th>a</th>_x000D_
<th>b</th>_x000D_
<th>c</th>_x000D_
<th>d</th>_x000D_
<th>e</th>_x000D_
<th>f</th>_x000D_
<th>a</th>_x000D_
<th>b</th>_x000D_
<th>c</th>_x000D_
<th>d</th>_x000D_
<th>e</th>_x000D_
<th>f</th>_x000D_
<th>a</th>_x000D_
<th>b</th>_x000D_
<th>c</th>_x000D_
<th>d</th>_x000D_
<th>e</th>_x000D_
<th>f</th> _x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td class="fixed" style="left: 0px">aaa</td>_x000D_
<td class="fixed" style="left: 50px">aaa2</td>_x000D_
<td>a</td>_x000D_
<td>b</td>_x000D_
<td>c</td>_x000D_
<td>d</td>_x000D_
<td>e</td>_x000D_
<td>f</td>_x000D_
<td>a</td>_x000D_
<td>b</td>_x000D_
<td>c</td>_x000D_
<td>d</td>_x000D_
<td>e</td>_x000D_
<td>f</td>_x000D_
<td>a</td>_x000D_
<td>b</td>_x000D_
<td>c</td>_x000D_
<td>d</td>_x000D_
<td>e</td>_x000D_
<td>f</td>_x000D_
<td>a</td>_x000D_
<td>b</td>_x000D_
<td>c</td>_x000D_
<td>d</td>_x000D_
<td>e</td>_x000D_
<td>f</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="fixed" style="left: 0">bbb</td>_x000D_
<td class="fixed" style="left: 50px">bbb2</td>_x000D_
<td>a</td>_x000D_
<td>b</td>_x000D_
<td>c</td>_x000D_
<td>d</td>_x000D_
<td>e</td>_x000D_
<td>f</td>_x000D_
<td>a</td>_x000D_
<td>b</td>_x000D_
<td>c</td>_x000D_
<td>d</td>_x000D_
<td>e</td>_x000D_
<td>f</td>_x000D_
<td>a</td>_x000D_
<td>b</td>_x000D_
<td>c</td>_x000D_
<td>d</td>_x000D_
<td>e</td>_x000D_
<td>f</td>_x000D_
<td>a</td>_x000D_
<td>b</td>_x000D_
<td>c</td>_x000D_
<td>d</td>_x000D_
<td>e</td>_x000D_
<td>f</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
They are user-defined signals, so they aren't triggered by any particular action. You can explicitly send them programmatically:
#include <signal.h>
kill(pid, SIGUSR1);
where pid
is the process id of the receiving process. At the receiving end, you can register a signal handler for them:
#include <signal.h>
void my_handler(int signum)
{
if (signum == SIGUSR1)
{
printf("Received SIGUSR1!\n");
}
}
signal(SIGUSR1, my_handler);
Just use CR to go to beginning of the line.
import time
for x in range (0,5):
b = "Loading" + "." * x
print (b, end="\r")
time.sleep(1)
I had a similar issue and ended up with this:
For me this has the advantage that data and annotation are not overlapping.
from matplotlib import pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54
plt.plot(A,B)
# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
x = A[ind]
y = B[ind]
xPos = x1 + .02 * (x1 - x0)
yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
ax.annotate('',#label,
xy=(x, y), xycoords='data',
xytext=(xPos, yPos), textcoords='data',
arrowprops=dict(
connectionstyle="arc3,rad=0.",
shrinkA=0, shrinkB=10,
arrowstyle= '-|>', ls= '-', linewidth=2
),
va='bottom', ha='left', zorder=19
)
ax.text(xPos + .01 * (x1 - x0), yPos,
'({:.2f}, {:.2f})'.format(x,y),
transform=ax.transData, va='center')
plt.grid()
plt.show()
Using the text argument in .annotate
ended up with unfavorable text positions.
Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.
If you have a std::wstring object, you can call c_str()
on it to get a wchar_t*
:
std::wstring name( L"Steve Nash" );
const wchar_t* szName = name.c_str();
Since you are operating on a narrow string, however, you would first need to widen it. There are various options here; one is to use Windows' built-in MultiByteToWideChar
routine. That will give you an LPWSTR
, which is equivalent to wchar_t*
.
If you want greater control you can use javascript rather than use the meta tag. This would allow you to have a visual of some kind, e.g. a countdown.
Here is a very basic approach using setTimeout()
<html>_x000D_
<body>_x000D_
<p>You will be redirected in 3 seconds</p>_x000D_
<script>_x000D_
var timer = setTimeout(function() {_x000D_
window.location='http://example.com'_x000D_
}, 3000);_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
In Visual Studio .NET you can do Ctrl + K then C to comment, Crtl + K then U to uncomment a block.
Create a restart.bat file like this
@echo on
set once="C:\Program Files\MyService\once.bat"
set taskname=Restart_MyService
set service=MyService
echo rem %time% >%once%
echo net stop %service% >>%once%
echo net start %service% >>%once%
echo del %once% >>%once%
schtasks /create /ru "System" /tn %taskname% /tr '%once%' /sc onstart /F /V1 /Z
schtasks /run /tn %taskname%
Then delete the task %taskname% when your %service% starts
Just a note in addition to the other answers.
If an initial value is supplied to reduce then sometimes its type must be specified, viz:-
a.reduce(fn, [])
may have to be
a.reduce<string[]>(fn, [])
or
a.reduce(fn, <string[]>[])
Config file:
worker_processes 4; # 2 * Number of CPUs
events {
worker_connections 19000; # It's the key to high performance - have a lot of connections available
}
worker_rlimit_nofile 20000; # Each connection needs a filehandle (or 2 if you are proxying)
# Total amount of users you can serve = worker_processes * worker_connections
more info: Optimizing nginx for high traffic loads
Here is what you are looking for:
Service hangs up at WaitForExit after calling batch file
It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.
Apache Commons has a great StringUtils class (org.apache.commons.lang.StringUtils). In StringUtils
there is a strip(String, String)
method that will do what you want.
I highly recommend using Apache Commons anyway, especially the Collections and Lang libraries.
You should never use * + !important
. What if you want to change font in some parts your HTML document? You should always use body without important. Use !important
only if there is no other option.
Here you go.
DataTable defaultDataTable = defaultDataSet.Tables[0];
var list = (from x in defaultDataTable.AsEnumerable()
where x.Field<string>("column1") == something
select x.Field<string>("column2")).ToList();
If you need the first column
var list = (from x in defaultDataTable.AsEnumerable()
where x.Field<string>(1) == something
select x.Field<string>(1)).ToList();
if all you need is the names, use xpath instead. No need to do the iteration yourself and check for null.
string xml = @"
<root>
<Employee name=""an"" />
<Employee name=""nobyd"" />
<Employee/>
</root>
";
var doc = new XmlDocument();
//doc.Load(path);
doc.LoadXml(xml);
var names = doc.SelectNodes("//Employee/@name");
If you're using the NVIDIA closed-source drivers you can vary the vertical sync mode on the fly using the __GL_SYNC_TO_VBLANK
environment variable:
~$ __GL_SYNC_TO_VBLANK=1 glxgears
Running synchronized to the vertical refresh. The framerate should be
approximately the same as the monitor refresh rate.
299 frames in 5.0 seconds = 59.631 FPS
~$ __GL_SYNC_TO_VBLANK=0 glxgears
123259 frames in 5.0 seconds = 24651.678 FPS
This works for me on Ubuntu 14.04 using the 346.46 NVIDIA drivers.
UITextAlignmentCenter
is deprecated in iOS6
Instead you can use this code:
btn.titleLabel.textAlignment=NSTextAlinmentCenter;
Only install the Service Pack (VS10sp1-KB983509.msp) wasn't enough to me.
I had to uninstall the Visual Studio Team Explorer 2010 to continue the installation :)
I would rather use plt.clf()
after every plt.show()
to just clear the current figure instead of closing and reopening it, keeping the window size and giving you a better performance and much better memory usage.
Similarly, you could do plt.cla()
to just clear the current axes.
To clear a specific axes, useful when you have multiple axes within one figure, you could do for example:
fig, axes = plt.subplots(nrows=2, ncols=2)
axes[0, 1].clear()
The simplest fix is to make the comparator function be static:
static int comparator (const Bar & first, const Bar & second);
^^^^^^
When invoking it in Count
, its name will be Foo::comparator
.
The way you have it now, it does not make sense to be a non-static member function because it does not use any member variables of Foo
.
Another option is to make it a non-member function, especially if it makes sense that this comparator might be used by other code besides just Foo
.
You must realize what options Jackson has available for deserialization. In Java, method argument names are not present in the compiled code. That's why Jackson can't generally use constructors to create a well-defined object with everything already set.
So, if there is an empty constructor and there are also setters, it uses the empty constructor and setters. If there are no setters, some dark magic (reflections) is used to do it.
If you want to use a constructor with Jackson, you must use the annotations as mentioned by @PiersyP in his answer. You can also use a builder pattern. If you encounter some exceptions, good luck. Error handling in Jackson sucks big time, it's hard to understand that gibberish in error messages.
For android 19+ you can get it in Telephony.Sms.Intents.SMS_RECEIVED_ACTION)
. There are more in the Intent
s class that 're worth looking
at
This can be done in three simple steps:
1) Add item id with url
tag:
{% for item in post %}
<tr>
<th>{{ item.id }}</th>
<td>{{ item.title }}</td>
<td>{{ item.body }}</td>
<td>
<a href={% url 'edit' id=item.id %}>Edit</a>
<a href={% url 'delete' id=item.id %}>Delete</a>
</td>
</tr>
{% endfor %}
2) Add path to urls.py:
path('edit/<int:id>', views.edit, name='edit')
path('delete/<int:id>', views.delete, name='delete')
3) Use the id on views.py:
def delete(request, id):
obj = post.objects.get(id=id)
obj.delete()
return redirect('dashboard')
I always think simply if(p != NULL){..} will do the job.
It will.
There is a way of displaying 3 Y axis see here.
Excel supports Secondary Axis, i.e. only 2 Y axis. Other way would be to chart the 3rd one separately, and overlay on top of the main chart.
You can pass a variable to a function by reference. This function will be able to modify the original variable.
You can define the passage by reference in the function definition:
<?php
function changeValue(&$var)
{
$var++;
}
$result=5;
changeValue($result);
echo $result; // $result is 6 here
?>
You might be able to resize the image with canvas
and export it using dataURI. Not sure about compression, though.
Take a look at this: Resizing an image in an HTML5 canvas
From your comments,
the tax amount rounded to the 4th decimal and the total price rounded to the 2nd decimal.
Using the example in the comments, I might foresee a case where you have 400 sales of $1.47. Sales-before-tax would be $588.00, and sales-after-tax would sum to $636.51 (accounting for $48.51 in taxes). However, the sales tax of $0.121275 * 400 would be $48.52.
This was one way, albeit contrived, to force a penny's difference.
I would note that there are payroll tax forms from the IRS where they do not care if an error is below a certain amount (if memory serves, $0.50).
Your big question is: does anybody care if certain reports are off by a penny? If the your specs say: yes, be accurate to the penny, then you should go through the effort to convert to DECIMAL.
I have worked at a bank where a one-penny error was reported as a software defect. I tried (in vain) to cite the software specifications, which did not require this degree of precision for this application. (It was performing many chained multiplications.) I also pointed to the user acceptance test. (The software was verified and accepted.)
Alas, sometimes you just have to make the conversion. But I would encourage you to A) make sure that it's important to someone and then B) write tests to show that your reports are accurate to the degree specified.
combobox1.SelectedValue = x;
I suspect you may want yo hear something else, but this is what you asked for.
//lat=3434&lon=yy38&rd=1.0&|
in that format o/p is displaying
public class ReadText {
public static void main(String[] args) throws Exception {
FileInputStream f= new FileInputStream("D:/workplace/sample/bookstore.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(f));
String strline;
StringBuffer sb = new StringBuffer();
while ((strline = br.readLine()) != null)
{
String[] arraylist=StringUtils.split(strline, ",");
if(arraylist.length == 2){
sb.append("lat=").append(StringUtils.trim(arraylist[0])).append("&lon=").append(StringUtils.trim(arraylist[1])).append("&rt=1.0&|");
} else {
System.out.println("Error: "+strline);
}
}
System.out.println("Data: "+sb.toString());
}
}
Just go to the combo box properties - DropDownStyle and change it to "DropDownList"
This will make visible the first item.
If I understand you right, we talk about a text file attachment. Thats unfortunate because if it was the email's message body, you could always use "\r\n", referring to http://www.faqs.org/rfcs/rfc822.html
But as it's an attachment, you must live with system differences. If I were in your shoes, I would choose one of those options:
a) only support windows clients by using "\r\n" as line end.
b) provide two attachment files, one with linux format and one with windows format.
c) I don't know if the attachment is to be read by people or machines, but if it is people I would consider attaching an HTML file instead of plain text. more portable and much prettier, too :)
Here is a really simple solution using SASS/SCSS and a math formula style:
/* frame circle */
.container {
position: relative;
border-radius: 50%;
background-color: white;
overflow: hidden;
width: 400px;
height: 400px; }
/* circle sectors */
.menu-frame-sector {
position: absolute;
width: 50%;
height: 50%;
z-index: 10000;
transform-origin: 100% 100%;
}
$sector_count: 8;
$sector_width: 360deg / $sector_count;
.sec0 {
transform: rotate(0 * $sector_width) skew($sector_width);
background-color: red; }
.sec1 {
transform: rotate(1 * $sector_width) skew($sector_width);
background-color: blue; }
.sec2 {
transform: rotate(2 * $sector_width) skew($sector_width);
background-color: red; }
.sec3 {
transform: rotate(3 * $sector_width) skew($sector_width);
background-color: blue; }
.sec4 {
transform: rotate(4 * $sector_width) skew($sector_width);
background-color: red; }
.sec5 {
transform: rotate(5 * $sector_width) skew($sector_width);
background-color: blue; }
.sec6 {
transform: rotate(6 * $sector_width) skew($sector_width);
background-color: red; }
.sec7 {
transform: rotate(7 * $sector_width) skew($sector_width);
background-color: blue; }
To conclude, I strongly suggest you to understand transform-origin
, rotate()
and skew()
:
https://tympanus.net/codrops/2013/08/09/building-a-circular-navigation-with-css-transforms/
These assemblies are available as NuGet packages, which is much easier than my original answer.
You can install by either right clicking on References in your project and selecting Manage NuGet packages... and searching for one of the packages listed below, or install using the Package Manager Console:
PM> Install-Package Microsoft.Office.Interop.Excel
These are available as "Primary Interop Assemblies", which can be installed with Office, or downloaded and installed separately. How to: Install Office Primary Interop Assemblies.
Once those are installed, you can reference them in your project in the Add Reference dialog, under .NET. If you do not see those Microsoft.Office.Interop assemblies listed, then they have not been installed yet. Install them from your setup, or download and install them separately (see my link above for the downloads).
I would prefere
if (!myStr.empty())
{
//do something
}
Also you don't have to write std::string a = "";
. You can just write std::string a;
- it will be empty by default
To demonstrate, consider the following set, which holds different Person objects:
Set<Person> people = new HashSet<Person>();
people.add(new Person("Tharindu", 10));
people.add(new Person("Martin", 20));
people.add(new Person("Fowler", 30));
Person Model Class
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//TODO - getters,setters ,overridden toString & compareTo methods
}
for(Person p:people){ System.out.println(p.getName()); }
people.forEach(p -> System.out.println(p.getName()));
default void forEach(Consumer<? super T> action)
Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller. Implementation Requirements:
The default implementation behaves as if:
for (T t : this)
action.accept(t);
Parameters: action - The action to be performed for each element
Throws: NullPointerException - if the specified action is null
Since: 1.8
Many answers are outdated (pre-Microsoft acquisition/free private repos). This one was written after the announcement of free private repos.
Github pages are not available on free private repos for individuals, as shown in the repo settings:
2020 (most basic plan is now "Team"):
All pages are public, even if you upgrade. Upgrading only enables the Pages feature on private repos, just like it enables other features. The Pages feature is publicly available static web hosting.
I think the following may work
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
I've used it for this sort of thing before.
> mtcars %>%
+ summarise_all(typeof) %>%
+ gather
key value
1 mpg double
2 cyl double
3 disp double
4 hp double
5 drat double
6 wt double
7 qsec double
8 vs double
9 am double
10 gear double
11 carb double
I try class
and typeof
functions, but all fails.
You could use toPrecision() and toFixed() methods of Number type. Check this link How can I format numbers as money in JavaScript?
Oh no no! That's not how you redirect. It's far more simpler:
public class ModHelloWorld extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
response.sendRedirect("http://www.google.com");
}
}
Also, it's a bad practice to write HTML code within a servlet. You should consider putting all that markup into a JSP and invoking the JSP using:
response.sendRedirect("/path/to/mynewpage.jsp");
In addition to MediaWiki that was mentioned by Kenny, you might also look at MoinMoin.
Choosing between MediaWiki and MoinMoin can be a bit tough. Here are some points to consider:
Fairly easy to set up.
Made soley for wikipedia. Thus it can be a bit of a pain to customize how you like it.
Huge amount of plugins and third party modules available.
Can be a pain to install.
There are a huge amount of other wikis available, but those are the main two I would consider.
You need to use brackets when using the fileExists
step in an if
condition or assign the returned value to a variable
Using variable:
def exists = fileExists 'file'
if (exists) {
echo 'Yes'
} else {
echo 'No'
}
Using brackets:
if (fileExists('file')) {
echo 'Yes'
} else {
echo 'No'
}
i agree with you about alternative solutions which you mentioned above
1. Use POST instead of GET;
2. Transform the List into a JSON string and pass it to the service.
and its true that you can't add List
to MultiValuedMap
because of its impl class MultivaluedMapImpl
have capability to accept String Key and String Value. which is shown in following figure
still you want to do that things than try following code.
Controller Class
package net.yogesh.test;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import com.google.gson.Gson;
@Path("test")
public class TestController {
@Path("testMethod")
@GET
@Produces("application/text")
public String save(
@QueryParam("list") List<String> list) {
return new Gson().toJson(list) ;
}
}
Client Class
package net.yogesh.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;
public class Client {
public static void main(String[] args) {
String op = doGet("http://localhost:8080/JerseyTest/rest/test/testMethod");
System.out.println(op);
}
private static String doGet(String url){
List<String> list = new ArrayList<String>();
list = Arrays.asList(new String[]{"string1,string2,string3"});
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
String lst = (list.toString()).substring(1, list.toString().length()-1);
params.add("list", lst);
ClientConfig config = new DefaultClientConfig();
com.sun.jersey.api.client.Client client = com.sun.jersey.api.client.Client.create(config);
WebResource resource = client.resource(url);
ClientResponse response = resource.queryParams(params).type("application/x-www-form-urlencoded").get(ClientResponse.class);
String en = response.getEntity(String.class);
return en;
}
}
hope this'll help you.
SELECT DISTINCT dbo.Table.Email,dbo.Table.FirstName dbo.Table.LastName, dbo.Table.DateOfBirth (etc) FROM dbo.Table.Contacts WHERE Email = 'name@email';
This could be useful. Like another answer it is just CSS.
td {
word-wrap: break-word;
}
Actually, all of those examples on the web wherein the common content/file type like "js", "css", "img", etc is been used as library name are misleading.
To start, let's look at how existing JSF implementations like Mojarra and MyFaces and JSF component libraries like PrimeFaces and OmniFaces use it. No one of them use resource libraries this way. They use it (under the covers, by @ResourceDependency
or UIViewRoot#addComponentResource()
) the following way:
<h:outputScript library="javax.faces" name="jsf.js" />
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<h:outputScript library="omnifaces" name="omnifaces.js" />
<h:outputScript library="omnifaces" name="fixviewstate.js" />
<h:outputScript library="omnifaces.combined" name="[dynamicname].js" />
<h:outputStylesheet library="primefaces" name="primefaces.css" />
<h:outputStylesheet library="primefaces-aristo" name="theme.css" />
<h:outputStylesheet library="primefaces-vader" name="theme.css" />
It should become clear that it basically represents the common library/module/theme name where all of those resources commonly belong to.
This way it's so much easier to specify and distinguish where those resources belong to and/or are coming from. Imagine that you happen to have a primefaces.css
resource in your own webapp wherein you're overriding/finetuning some default CSS of PrimeFaces; if PrimeFaces didn't use a library name for its own primefaces.css
, then the PrimeFaces own one wouldn't be loaded, but instead the webapp-supplied one, which would break the look'n'feel.
Also, when you're using a custom ResourceHandler
, you can also apply more finer grained control over resources coming from a specific library when library
is used the right way. If all component libraries would have used "js" for all their JS files, how would the ResourceHandler
ever distinguish if it's coming from a specific component library? Examples are OmniFaces CombinedResourceHandler
and GraphicResourceHandler
; check the createResource()
method wherein the library is checked before delegating to next resource handler in chain. This way they know when to create CombinedResource
or GraphicResource
for the purpose.
Noted should be that RichFaces did it wrong. It didn't use any library
at all and homebrewed another resource handling layer over it and it's therefore impossible to programmatically identify RichFaces resources. That's exactly the reason why OmniFaces CombinedResourceHander
had to introduce a reflection-based hack in order to get it to work anyway with RichFaces resources.
Your own webapp does not necessarily need a resource library. You'd best just omit it.
<h:outputStylesheet name="css/style.css" />
<h:outputScript name="js/script.js" />
<h:graphicImage name="img/logo.png" />
Or, if you really need to have one, you can just give it a more sensible common name, like "default" or some company name.
<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />
Or, when the resources are specific to some master Facelets template, you could also give it the name of the template, so that it's easier to relate each other. In other words, it's more for self-documentary purposes. E.g. in a /WEB-INF/templates/layout.xhtml
template file:
<h:outputStylesheet library="layout" name="css/style.css" />
<h:outputScript library="layout" name="js/script.js" />
And a /WEB-INF/templates/admin.xhtml
template file:
<h:outputStylesheet library="admin" name="css/style.css" />
<h:outputScript library="admin" name="js/script.js" />
For a real world example, check the OmniFaces showcase source code.
Or, when you'd like to share the same resources over multiple webapps and have created a "common" project for that based on the same example as in this answer which is in turn embedded as JAR in webapp's /WEB-INF/lib
, then also reference it as library (name is free to your choice; component libraries like OmniFaces and PrimeFaces also work that way):
<h:outputStylesheet library="common" name="css/style.css" />
<h:outputScript library="common" name="js/script.js" />
<h:graphicImage library="common" name="img/logo.png" />
Another main advantage is that you can apply resource library versioning the right way on resources provided by your own webapp (this doesn't work for resources embedded in a JAR). You can create a direct child subfolder in the library folder with a name in the \d+(_\d+)*
pattern to denote the resource library version.
WebContent
|-- resources
| `-- default
| `-- 1_0
| |-- css
| | `-- style.css
| |-- img
| | `-- logo.png
| `-- js
| `-- script.js
:
When using this markup:
<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />
This will generate the following HTML with the library version as v
parameter:
<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&v=1_0" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&v=1_0"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&v=1_0" alt="" />
So, if you have edited/updated some resource, then all you need to do is to copy or rename the version folder into a new value. If you have multiple version folders, then the JSF ResourceHandler
will automatically serve the resource from the highest version number, according to numerical ordering rules.
So, when copying/renaming resources/default/1_0/*
folder into resources/default/1_1/*
like follows:
WebContent
|-- resources
| `-- default
| |-- 1_0
| | :
| |
| `-- 1_1
| |-- css
| | `-- style.css
| |-- img
| | `-- logo.png
| `-- js
| `-- script.js
:
Then the last markup example would generate the following HTML:
<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&v=1_1" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&v=1_1"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&v=1_1" alt="" />
This will force the webbrowser to request the resource straight from the server instead of showing the one with the same name from the cache, when the URL with the changed parameter is been requested for the first time. This way the endusers aren't required to do a hard refresh (Ctrl+F5 and so on) when they need to retrieve the updated CSS/JS resource.
Please note that library versioning is not possible for resources enclosed in a JAR file. You'd need a custom ResourceHandler
. See also How to use JSF versioning for resources in jar.
You can use Intent.ACTION_DIAL
instead of Intent.ACTION_CALL
. This shows the dialer with the number already entered, but allows the user to decide whether to actually make the call or not. ACTION_DIAL
does not require the CALL_PHONE
permission.
To make the text on the tick labels fully visible and read in the same direction as the y-axis label, change the last line to
q + theme(axis.text.x=element_text(angle=90, hjust=1))
I had the same problem with my chromedriver using Python and options.add_argument("headless") did not work for me, but then I realized how to fix it so I bring it in the code below:
opt = webdriver.ChromeOptions()
opt.arguments.append("headless")
The title attribute also works well with other html elements, for example a link...
<a title="hover text" ng-href="{{getUrl()}}"> download link
</a>
from command prompt:
set ANDROID_SDK_HOME=C:\[wherever your sdk folder is]
should do the trick.
If you just want to run some code when an element becomes visible in the viewport:
function onVisible(element, callback) {
new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if(entry.intersectionRatio > 0) {
callback(element);
observer.disconnect();
}
});
}).observe(element);
}
When the element has become visible the intersection observer calls callback
and then destroys itself with .disconnect()
.
Use it like this:
onVisible(document.querySelector("#myElement"), () => console.log("it's visible"));
If you are passing data to a DOM element from the server, you should set the data on the element:
<a id="foo" data-foo="bar" href="#">foo!</a>
The data can then be accessed using .data()
in jQuery:
console.log( $('#foo').data('foo') );
//outputs "bar"
However when you store data on a DOM node in jQuery using data, the variables are stored on the node object. This is to accommodate complex objects and references as storing the data on the node element as an attribute will only accommodate string values.
Continuing my example from above:$('#foo').data('foo', 'baz');
console.log( $('#foo').attr('data-foo') );
//outputs "bar" as the attribute was never changed
console.log( $('#foo').data('foo') );
//outputs "baz" as the value has been updated on the object
Also, the naming convention for data attributes has a bit of a hidden "gotcha":
HTML:<a id="bar" data-foo-bar-baz="fizz-buzz" href="#">fizz buzz!</a>
JS:
console.log( $('#bar').data('fooBarBaz') );
//outputs "fizz-buzz" as hyphens are automatically camelCase'd
The hyphenated key will still work:
HTML:<a id="bar" data-foo-bar-baz="fizz-buzz" href="#">fizz buzz!</a>
JS:
console.log( $('#bar').data('foo-bar-baz') );
//still outputs "fizz-buzz"
However the object returned by .data()
will not have the hyphenated key set:
$('#bar').data().fooBarBaz; //works
$('#bar').data()['fooBarBaz']; //works
$('#bar').data()['foo-bar-baz']; //does not work
It's for this reason I suggest avoiding the hyphenated key in javascript.
For HTML, keep using the hyphenated form. HTML attributes are supposed to get ASCII-lowercased automatically, so <div data-foobar></div>
, <DIV DATA-FOOBAR></DIV>
, and <dIv DaTa-FoObAr></DiV>
are supposed to be treated as identical, but for the best compatibility the lower case form should be preferred.
The .data()
method will also perform some basic auto-casting if the value matches a recognized pattern:
<a id="foo"
href="#"
data-str="bar"
data-bool="true"
data-num="15"
data-json='{"fizz":["buzz"]}'>foo!</a>
JS:
$('#foo').data('str'); //`"bar"`
$('#foo').data('bool'); //`true`
$('#foo').data('num'); //`15`
$('#foo').data('json'); //`{fizz:['buzz']}`
This auto-casting ability is very convenient for instantiating widgets & plugins:
$('.widget').each(function () {
$(this).widget($(this).data());
//-or-
$(this).widget($(this).data('widget'));
});
If you absolutely must have the original value as a string, then you'll need to use .attr()
:
<a id="foo" href="#" data-color="ABC123"></a>
<a id="bar" href="#" data-color="654321"></a>
JS:
$('#foo').data('color').length; //6
$('#bar').data('color').length; //undefined, length isn't a property of numbers
$('#foo').attr('data-color').length; //6
$('#bar').attr('data-color').length; //6
This was a contrived example. For storing color values, I used to use numeric hex notation (i.e. 0xABC123), but it's worth noting that hex was parsed incorrectly in jQuery versions before 1.7.2, and is no longer parsed into a Number
as of jQuery 1.8 rc 1.
jQuery 1.8 rc 1 changed the behavior of auto-casting. Before, any format that was a valid representation of a Number
would be cast to Number
. Now, values that are numeric are only auto-cast if their representation stays the same. This is best illustrated with an example.
<a id="foo"
href="#"
data-int="1000"
data-decimal="1000.00"
data-scientific="1e3"
data-hex="0x03e8">foo!</a>
JS:
// pre 1.8 post 1.8
$('#foo').data('int'); // 1000 1000
$('#foo').data('decimal'); // 1000 "1000.00"
$('#foo').data('scientific'); // 1000 "1e3"
$('#foo').data('hex'); // 1000 "0x03e8"
If you plan on using alternative numeric syntaxes to access numeric values, be sure to cast the value to a Number
first, such as with a unary +
operator.
+$('#foo').data('hex'); // 1000
I like to separate my filters from other portions of the code and test those as I outline on my blog here http://coding.grax.com/2013/08/testing-custom-linq-filter-operators.html
That being said, the filter logic being tested is not identical to the filter logic executed when the program is run due to the translation between the LINQ expression and the underlying query language, such as T-SQL. Still, this allows me to validate the logic of the filter. I don't worry too much about the translations that happen and things such as case-sensitivity and null-handling until I test the integration between the layers.
While the other answers got it right when it comes to add comments, in my case only the following worked.
Multi-line comment
select the lines to be commented + Ctrl + 4
Multi-line uncomment
select the lines to be uncommented + Ctrl + 1
You can decorate the decorator:
import decorator
class Test(object):
@decorator.decorator
def _decorator(foo, self):
foo(self)
@_decorator
def bar(self):
pass
How about this:
from pandas import *
idx = Int64Index([171, 174, 173])
df = DataFrame(index = idx, data =([1,2,3]))
print df
It gives me:
0
171 1
174 2
173 3
Is this what you are looking for?
A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.
It's an old thread, but I'll add some info for other people.
I experienced a similar issue with a program that writes PDF files, sometimes they take 30 seconds to render.. which is the same period that my watcher_FileCreated class waits before copying the file.
The files were not locked.
In this case I checked the size of the PDF and then waited 2 seconds before comparing the new size, if they were unequal the thread would sleep for 30 seconds and try again.
You seem a bit confused as to how numpy arrays work behind the scenes. Each item in an array must be the same size.
The string representation of a float doesn't work this way. For example, repr(1.3)
yields '1.3'
, but repr(1.33)
yields '1.3300000000000001'
.
A accurate string representation of a floating point number produces a variable length string.
Because numpy arrays consist of elements that are all the same size, numpy requires you to specify the length of the strings within the array when you're using string arrays.
If you use x.astype('str')
, it will always convert things to an array of strings of length 1.
For example, using x = np.array(1.344566)
, x.astype('str')
yields '1'
!
You need to be more explict and use the '|Sx'
dtype syntax, where x
is the length of the string for each element of the array.
For example, use x.astype('|S10')
to convert the array to strings of length 10.
Even better, just avoid using numpy arrays of strings altogether. It's usually a bad idea, and there's no reason I can see from your description of your problem to use them in the first place...
<form name="input" action="some.php" method="post">
<input type="text" name="user" id="mytext">
<input type="submit" value="Submit">
</form>
<script>
var w = someValue;
document.getElementById("mytext").value = w;
</script>
//php on some.php page
echo $_POST['user'];
The other plus of using RecycleView
is animation, it can be done in two lines of code
RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
recyclerView.setItemAnimator(itemAnimator);
But the widget is still raw, e.g you can't create header and footer.
This change worked for me:
// The size returned by CGImageGetWidth(imgRef) & CGImageGetHeight(imgRef) is incorrect as it doesn't respect the image orientation!
// CGImageRef imgRef = [image CGImage];
// CGFloat width = CGImageGetWidth(imgRef);
// CGFloat height = CGImageGetHeight(imgRef);
//
// This returns the actual width and height of the photo (and hence solves the problem
CGFloat width = image.size.width;
CGFloat height = image.size.height;
CGRect bounds = CGRectMake(0, 0, width, height);
The answer from Tanoh could use some clarification. VersionCode is the equivalent of a build number. So typically an app will go through many iterations before release. Some of these iterations may make it to the Google Play store in the form of alpha, beta, and actual releases. Each successive iteration must have an incremented versionCode. However, typically you only increase the versionName when between public releases. Both numbers are significant. Your users need to know if the version they have on their phone is the latest or not (versionName) and the Play Store and CI systems such as bitrise rely on and/or update the build number (versionCode)
This is a modern approach and it utilizes the CSS Flexbox functionality.
You can now vertically align the content within your parent container by just adding these styles to the .main
container
.main {
display: flex;
flex-direction: column;
justify-content: center;
}
And you are good to go!
Having had this same problem myself I'd like to post my perspective. I think that there are a couple motivating factors for doing something like this:
Using an interface doesn't really cut it: you can accidentally get duplicate enum values. Not desirable.
I ended up just combining the enums: this ensures that there cannot be any duplicate values, at the expense of being less tightly tied to its associated class. But, I figured the duplicate issue was my main concern...
make sure you have these permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Then make some activity and register a LocationListener
package com.example.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class LocationActivity extends SherlockFragmentActivity implements LocationListener {
private GoogleMap map;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); //You can also use LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER
}
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
@Override
public void onProviderEnabled(String provider) { }
@Override
public void onProviderDisabled(String provider) { }
}
map.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
As a more systematic and structured solution you could define folders where your classes are stored and create an autoloader (__autoload()
) which will search the class files in defined places:
require_once("../settings.php");
define('DIR_CLASSES', '/path/to/the/classes/folder/'); // this can be inside your settings.php
$user = new User();
$user->createUser($_POST["username"], $_POST["email"], $_POST["password"]);
function __autoload($classname) {
if(file_exists(DIR_CLASSES . 'class' . $classname . '.php')) {
include_once(DIR_CLASSES . 'class' . $classname . '.php'); // looking for the class in the project's classes folder
} else {
include_once($classname . '.php'); // looking for the class in include_path
}
}
I didn't like any of the implementations (because they use a Regex which is an expensive operation, or a library which is an overkill if you only need one method), so I ended up using the java.net.URI class with some extra checks, and limiting the protocols to: http, https, file, ftp, mailto, news, urn.
And yes, catching exceptions can be an expensive operation, but probably not as bad as Regular Expressions:
final static Set<String> protocols, protocolsWithHost;
static {
protocolsWithHost = new HashSet<String>(
Arrays.asList( new String[]{ "file", "ftp", "http", "https" } )
);
protocols = new HashSet<String>(
Arrays.asList( new String[]{ "mailto", "news", "urn" } )
);
protocols.addAll(protocolsWithHost);
}
public static boolean isURI(String str) {
int colon = str.indexOf(':');
if (colon < 3) return false;
String proto = str.substring(0, colon).toLowerCase();
if (!protocols.contains(proto)) return false;
try {
URI uri = new URI(str);
if (protocolsWithHost.contains(proto)) {
if (uri.getHost() == null) return false;
String path = uri.getPath();
if (path != null) {
for (int i=path.length()-1; i >= 0; i--) {
if ("?<>:*|\"".indexOf( path.charAt(i) ) > -1)
return false;
}
}
}
return true;
} catch ( Exception ex ) {}
return false;
}
If you are using Ruby on Rails there is a squish
> @title = " abc "
=> " abc "
> @title.squish
=> "abc"
> @title
=> " abc "
> @title.squish!
=> "abc"
> @title
=> "abc"
If you are using just Ruby you want to use strip
Herein lies the gotcha.. in your case you want to use strip without the bang !
while strip! certainly does return nil if there was no action it still updates the variable so strip! cannot be used inline. If you want to use strip inline you can use the version without the bang !
strip! using multi line approach
> tokens["Title"] = " abc "
=> " abc "
> tokens["Title"].strip!
=> "abc"
> @title = tokens["Title"]
=> "abc"
strip single line approach... YOUR ANSWER
> tokens["Title"] = " abc "
=> " abc "
> @title = tokens["Title"].strip if tokens["Title"].present?
=> "abc"
Modern browsers support a Content Security Policy or CSP. This is the highest level of web security and strongly recommended if you can apply it because it completely blocks all XSS attacks.
Both of your suggestions break with CSP enabled because they allow inline Javascript (which could be injected by a hacker) to execute in your page.
The best practice is to subscribe to the event in Javascript, as in Konrad Rudolph's answer.
In bootstrap 3, this works well for me:
.btn-link.btn-anchor {
outline: none !important;
padding: 0;
border: 0;
vertical-align: baseline;
}
Used like:
<button type="button" class="btn-link btn-anchor">My Button</button>
gradlew
(On Windows gradlew.bat
)
adb install -r exampleApp.apk
(The -r
makes it replace the existing copy, add an -s
if installing on an emulator)
I set up an alias in my ~/.bash_profile
, to make it a 2char command.
alias bi="gradlew && adb install -r exampleApp.apk"
(Short for Build and Install)
As an alternative to copying the data you can make a wrapper that gives you access to a part of the original array as if it was a copy of the part of the array. The advantage is that you don't get another copy of the data in memory, and the drawback is a slight overhead when accessing the data.
public class SubArray<T> : IEnumerable<T> {
private T[] _original;
private int _start;
public SubArray(T[] original, int start, int len) {
_original = original;
_start = start;
Length = len;
}
public T this[int index] {
get {
if (index < 0 || index >= Length) throw new IndexOutOfRangeException();
return _original[_start + index];
}
}
public int Length { get; private set; }
public IEnumerator<T> GetEnumerator() {
for (int i = 0; i < Length; i++) {
yield return _original[_start + i];
}
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
Usage:
int[] original = { 1, 2, 3, 4, 5 };
SubArray<int> copy = new SubArray<int>(original, 2, 2);
Console.WriteLine(copy.Length); // shows: 2
Console.WriteLine(copy[0]); // shows: 3
foreach (int i in copy) Console.WriteLine(i); // shows 3 and 4
The ONESHELL directive allows to write multiple line recipes to be executed in the same shell invocation.
all: foo
SOURCE_FILES = $(shell find . -name '*.c')
.ONESHELL:
foo: ${SOURCE_FILES}
FILES=()
for F in $^; do
FILES+=($${F})
done
gcc "$${FILES[@]}" -o $@
There is a drawback though : special prefix characters (‘@’, ‘-’, and ‘+’) are interpreted differently.
https://www.gnu.org/software/make/manual/html_node/One-Shell.html
You may try:
settings = s.merge_environment_settings(prepped.url, None, None, None, None)
You can read more here: http://docs.python-requests.org/en/master/user/advanced/
Use
git config --global core.pager cat
to get rid of a pager for all commands for all repositories.
You can also disable paging for single Git subcommands by using pager.<cmd>
setting instead of core.pager
, and you can change your settings per Git repository (omit --global
).
See man git-config
and search for pager.<cmd>
for details.
PHP manual has a good read on the question here.
The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.
You can use gcc, in Terminal, by doing gcc -c tat.c -o tst
however, it doesn't come installed by default. You have to install the XCode package from tour install disc or download from http://developer.apple.com
Here is where to download past developer tools from, which includes XCode 3.1, 3.0, 2.5 ...
http://connect.apple.com/cgi-bin/WebObjects/MemberSite.woa/wo/5.1.17.2.1.3.3.1.0.1.1.0.3.3.3.3.1
An alternative to the answer from sergey_mo is to create multiple ssh keys on the jenkins server.
(Though as the first commenter to sergey_mo's answer said, this may end up being more painful than managing a single key-pair.)
As per the Android documentation for XML Attributes of android:layout_gravity, we can do it easily :)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton android:id="@+id/btnFindMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/findme"></ImageButton>
</LinearLayout>
11.11.2017
Since Instagram changed the way they provide this data, none of above methods work nowadays. Here is the new way to get user's media:
GET https://instagram.com/graphql/query/?query_id=17888483320059182&variables={"id":"1951415043","first":20,"after":null}
Where:
query_id
- permanent value: 17888483320059182 (note it might be changed in future).
id
- id of the user. It may come with list of users. To get the list of users you can use following request: GET https://www.instagram.com/web/search/topsearch/?context=blended&query=YOUR_QUERY
first
- amount of items to get.
after
- id of the last item if you want to get items from that id.
Besides the redundant )
this expression will always be true
because currentStatus
will always match one of these two conditions:
currentStatus !== 'open' || currentStatus !== 'reopen'
perhaps you mean one of
!(currentStatus === 'open' || currentStatus === 'reopen')
(currentStatus !== 'open' && currentStatus !== 'reopen')
Since people will be coming from Google, make sure you're in the right database.
Running SQL in the 'master' database will often return this error.
If it is going to be a web based application, you can also use the ServletContextListener interface.
public class SLF4JBridgeListener implements ServletContextListener {
@Autowired
ThreadPoolTaskExecutor executor;
@Autowired
ThreadPoolTaskScheduler scheduler;
@Override
public void contextInitialized(ServletContextEvent sce) {
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
scheduler.shutdown();
executor.shutdown();
}
}
I solved this warning changing "Configuration Manager" to Release (Mixed Plataform).
Yes you only need $()
when you're using jQuery. If you want jQuery's help to do DOM things just keep this in mind.
$(this)[0] === this
Basically every time you get a set of elements back jQuery turns it into a jQuery object. If you know you only have one result, it's going to be in the first element.
$("#myDiv")[0] === document.getElementById("myDiv");
And so on...
Version 25.2.3 (and higher) of Android SDK Tools
package contains new tool - sdkmanager - which simplifies this task of installing build-tools from the command line.
It is located in android_sdk/tools/bin
folder.
Usage (from documentation):
sdkmanager packages [options]
The
packages
argument is an SDK-style path, wrapped in quotes (for example,"build-tools;25.0.0"
or"platforms;android-25"
). You can pass multiple package paths, separated with a space, but they must each be wrapped in their own set of quotes.
Example usage (on my Mac):
alex@mbpro:~/sdk/tools/bin$ ls ../../build-tools/
25.0.0/
alex@mbpro:~/sdk/tools/bin$ ./sdkmanager "build-tools;25.0.2"
done
alex@mbpro:~/sdk/tools/bin$ ls ../../build-tools/
25.0.0/ 25.0.2/
You can also specify various options, for example to force all connections to use HTTP (--no_https
), or in order to use proxy server (--proxy_host=address
and --proxy_port=port
).
To check the available options, use the --help
flag. On my machine (Mac), the output is as following:
alex@mbpro:~/sdk/tools/bin$ ./sdkmanager --help
Usage:
sdkmanager [--uninstall] [<common args>] \
[--package_file <package-file>] [<packages>...]
sdkmanager --update [<common args>]
sdkmanager --list [<common args>]
In its first form, installs, or uninstalls, or updates packages.
<package> is a sdk-style path (e.g. "build-tools;23.0.0" or
"platforms;android-23").
<package-file> is a text file where each line is a sdk-style path
of a package to install or uninstall.
Multiple --package_file arguments may be specified in combination
with explicit paths.
In its second form (with --update), currently installed packages are
updated to the latest version.
In its third form, all installed and available packages are printed out.
Common Arguments:
--sdk_root=<sdkRootPath>: Use the specified SDK root instead of the SDK containing this tool
--channel=<channelId>: Include packages in channels up to <channelId>.
Common channels are:
0 (Stable), 1 (Beta), 2 (Dev), and 3 (Canary).
--include_obsolete: With --list, show obsolete packages in the
package listing. With --update, update obsolete
packages as well as non-obsolete.
--no_https: Force all connections to use http rather than https.
--proxy=<http | socks>: Connect via a proxy of the given type.
--proxy_host=<IP or DNS address>: IP or DNS address of the proxy to use.
--proxy_port=<port #>: Proxy port to connect to.
* If the env var REPO_OS_OVERRIDE is set to "windows",
"macosx", or "linux", packages will be downloaded for that OS.
->DECLARE co_id INT ;
->DECLARE sname VARCHAR(10) ;
->SELECT course_id INTO co_id FROM course_details ;
->SELECT student_name INTO sname FROM course_details;
->DECLARE val1 int;
->DECLARE val2 int;
->SELECT student__id,student_name INTO val1,val2 FROM student_details;
--HAPPY CODING--
For adding prefix or suffix for files(directories), you could use the simple and powerful way by xargs:
ls | xargs -I {} mv {} PRE_{}
ls | xargs -I {} mv {} {}_SUF
It is using the paramerter-replacing option of xargs: -I. And you can get more detail from the man page.
var votevalue = $.map($(this).data('votevalue'), Number);
You don't need to call DateTime.Today
multiple times, just use it single time and format the date object in your desire format.. like that
string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");
OR
string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
Multiple posted answer here, but probably this can help who is newly using PowerShell
SO if any space is there in your directory path do not forgot to add double inverted commas "".
This works by exploiting the % properties of the list rather than the increments.
for num in range(1,100):
if num % 4 == 1 or num % 4 ==2:
n.append(num)
continue
pass
Try using following command. I haven't tried it but I think it should work.
openssl pkcs8 -topk8 -inform PEM -outform DER -in filename -out filename -nocrypt
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
You may have some "plain text" somewhere in php files that is interpreted as script output. It may be even a newline before or after the php script tag specifier (less-than + question mark + "php").
Besides, if I remember correctly, according to http specification, the "Location" header accepts only full URLs, not relative locations. Have that in mind too.
The 'new' way to install tensorflow GPU if you have Nvidia, is with Anaconda. Works on Windows too. With 1 line.
conda create --name tf_gpu tensorflow-gpu
This is a shortcut for 3 commands, which you can execute separately if you want or if you already have a conda environment and do not need to create one.
Create an anaconda environment conda create --name tf_gpu
Activate the environment activate tf_gpu
Install tensorflow-GPU conda install tensorflow-gpu
You can use the conda environment.
I had the same on my project.
I tried " super.setIntegerProperty("loadUrlTimeoutValue", 70000); " but to no avail.
I ensured all files were linked properly [ CSS, JS files etc ], validated the HTML using w3c validator [ http://validator.w3.org/#validate_by_upload ] , and cleaned the project [ Project -> Clean ]
It now loads and executes without the same error.
Hope this helps
@DougW has clearly answered this question, but I still like to add some codes here to explain Doug's points. (And correct errors in the code above)
Solution 1: URL-encode the POST data with a content-type header :application/x-www-form-urlencoded .
Note: you do not need to urlencode $_POST[] fields one by one, http_build_query() function can do the urlencoding job nicely.
$fields = array(
'mediaupload'=>$file_field,
'username'=>$_POST["username"],
'password'=>$_POST["password"],
'latitude'=>$_POST["latitude"],
'longitude'=>$_POST["longitude"],
'datetime'=>$_POST["datetime"],
'category'=>$_POST["category"],
'metacategory'=>$_POST["metacategory"],
'caption'=>$_POST["description"]
);
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
Solution 2: Pass the array directly as the post data without URL-encoding, while the Content-Type header will be set to multipart/form-data.
$fields = array(
'mediaupload'=>$file_field,
'username'=>$_POST["username"],
'password'=>$_POST["password"],
'latitude'=>$_POST["latitude"],
'longitude'=>$_POST["longitude"],
'datetime'=>$_POST["datetime"],
'category'=>$_POST["category"],
'metacategory'=>$_POST["metacategory"],
'caption'=>$_POST["description"]
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
Both code snippets work, but using different HTTP headers and bodies.
I'm the one supporting CairoPlot and I'm very proud it came up here. Surely matplotlib is great, but I believe CairoPlot is better looking. So, for presentations and websites, it's a very good choice.
Today I released version 1.1. If interested, check it out at CairoPlot v1.1
EDIT: After a long and cold winter, CairoPlot is being developed again. Check out the new version on GitHub.
OutputDebugString function will do it.
example code
void CClass::Output(const char* szFormat, ...)
{
char szBuff[1024];
va_list arg;
va_start(arg, szFormat);
_vsnprintf(szBuff, sizeof(szBuff), szFormat, arg);
va_end(arg);
OutputDebugString(szBuff);
}
I used MyActivity.class and getCanonicalName method and I got answer.
protected Boolean isActivityRunning(Class activityClass)
{
ActivityManager activityManager = (ActivityManager) getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (ActivityManager.RunningTaskInfo task : tasks) {
if (activityClass.getCanonicalName().equalsIgnoreCase(task.baseActivity.getClassName()))
return true;
}
return false;
}
Follow one of below approaches.
submit
on ExecutorService
and check the status with blocking call get()
on Future
object as suggested by Kiran
invokeAll()
on ExecutorServiceshutdown, awaitTermination, shutdownNow
APIs of ThreadPoolExecutor in proper sequence Related SE questions:
How is it a keyword and an instance of a type?
This isn't surprising. Both true
and false
are keywords and as literals they have a type ( bool
). nullptr
is a pointer literal of type std::nullptr_t
, and it's a prvalue (you cannot take the address of it using &
).
4.10
about pointer conversion says that a prvalue of type std::nullptr_t
is a null pointer constant, and that an integral null pointer constant can be converted to std::nullptr_t
. The opposite direction is not allowed. This allows overloading a function for both pointers and integers, and passing nullptr
to select the pointer version. Passing NULL
or 0
would confusingly select the int
version.
A cast of nullptr_t
to an integral type needs a reinterpret_cast
, and has the same semantics as a cast of (void*)0
to an integral type (mapping implementation defined). A reinterpret_cast
cannot convert nullptr_t
to any pointer type. Rely on the implicit conversion if possible or use static_cast
.
The Standard requires that sizeof(nullptr_t)
be sizeof(void*)
.
If you used Create React App, you can set an environment variable using a .env file. The documentation is here:
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
Basically do something like this in the .env file at the project root.
REACT_APP_NOT_SECRET_CODE=abcdef
Note that the variable name must start with REACT_APP_
You can access it from your component with
process.env.REACT_APP_NOT_SECRET_CODE
If you use NetBeans IDE right click form then
Properties ->Code -> check out Generate Center
Here is a complete test case that simulates the click
event, calls all handlers attached (however they have been attached), maintains the "target"
attribute ("srcElement"
in IE), bubbles like a normal event would, and emulates IE's recursion-prevention. Tested in FF 2, Chrome 2.0, Opera 9.10 and of course IE (6):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function fakeClick(event, anchorObj) {
if (anchorObj.click) {
anchorObj.click()
} else if(document.createEvent) {
if(event.target !== anchorObj) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var allowDefault = anchorObj.dispatchEvent(evt);
// you can check allowDefault for false to see if
// any handler called evt.preventDefault().
// Firefox will *not* redirect to anchorObj.href
// for you. However every other browser will.
}
}
}
</script>
</head>
<body>
<div onclick="alert('Container clicked')">
<a id="link" href="#" onclick="alert((event.target || event.srcElement).innerHTML)">Normal link</a>
</div>
<button type="button" onclick="fakeClick(event, document.getElementById('link'))">
Fake Click on Normal Link
</button>
<br /><br />
<div onclick="alert('Container clicked')">
<div onclick="fakeClick(event, this.getElementsByTagName('a')[0])"><a id="link2" href="#" onclick="alert('foo')">Embedded Link</a></div>
</div>
<button type="button" onclick="fakeClick(event, document.getElementById('link2'))">Fake Click on Embedded Link</button>
</body>
</html>
It avoids recursion in non-IE browsers by inspecting the event object that is initiating the simulated click, by inspecting the target
attribute of the event (which remains unchanged during propagation).
Obviously IE does this internally holding a reference to its global event
object. DOM level 2 defines no such global variable, so for that reason the simulator must pass in its local copy of event
.
According to the documentation AnimationSet
Represents a group of Animations that should be played together. The transformation of each individual animation are composed together into a single transform. If AnimationSet sets any properties that its children also set (for example, duration or fillBefore), the values of AnimationSet override the child values
AnimationSet mAnimationSet = new AnimationSet(false); //false means don't share interpolators
Pass true if all of the animations in this set should use the interpolator associated with this AnimationSet. Pass false if each animation should use its own interpolator.
ImageView imageView= (ImageView)findViewById(R.id.imageView);
Animation fadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
Animation fadeOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
mAnimationSet.addAnimation(fadeInAnimation);
mAnimationSet.addAnimation(fadeOutAnimation);
imageView.startAnimation(mAnimationSet);
I hope this will help you.
The &&
function is not vectorized. You need the &
function:
EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]
In my case, I am not using the built in ajax api to feed Json to the table (this is due to some formatting that was rather difficult to implement inside the datatable's render callback).
My solution was to create the variable in the outer scope of the onload functions and the function that handles the data refresh (var table = null
, for example).
Then I instantiate my table in the on load method
$(function () {
//.... some code here
table = $("#detailReportTable").DataTable();
.... more code here
});
and finally, in the function that handles the refresh, i invoke the clear() and destroy() method, fetch the data into the html table, and re-instantiate the datatable, as such:
function getOrderDetail() {
table.clear();
table.destroy();
...
$.ajax({
//.....api call here
});
....
table = $("#detailReportTable").DataTable();
}
I hope someone finds this useful!
>>> k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
>>> import itertools
>>> k.sort()
>>> list(k for k,_ in itertools.groupby(k))
[[1, 2], [3], [4], [5, 6, 2]]
itertools
often offers the fastest and most powerful solutions to this kind of problems, and is well worth getting intimately familiar with!-)
Edit: as I mention in a comment, normal optimization efforts are focused on large inputs (the big-O approach) because it's so much easier that it offers good returns on efforts. But sometimes (essentially for "tragically crucial bottlenecks" in deep inner loops of code that's pushing the boundaries of performance limits) one may need to go into much more detail, providing probability distributions, deciding which performance measures to optimize (maybe the upper bound or the 90th centile is more important than an average or median, depending on one's apps), performing possibly-heuristic checks at the start to pick different algorithms depending on input data characteristics, and so forth.
Careful measurements of "point" performance (code A vs code B for a specific input) are a part of this extremely costly process, and standard library module timeit
helps here. However, it's easier to use it at a shell prompt. For example, here's a short module to showcase the general approach for this problem, save it as nodup.py
:
import itertools
k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
def doset(k, map=map, list=list, set=set, tuple=tuple):
return map(list, set(map(tuple, k)))
def dosort(k, sorted=sorted, xrange=xrange, len=len):
ks = sorted(k)
return [ks[i] for i in xrange(len(ks)) if i == 0 or ks[i] != ks[i-1]]
def dogroupby(k, sorted=sorted, groupby=itertools.groupby, list=list):
ks = sorted(k)
return [i for i, _ in itertools.groupby(ks)]
def donewk(k):
newk = []
for i in k:
if i not in newk:
newk.append(i)
return newk
# sanity check that all functions compute the same result and don't alter k
if __name__ == '__main__':
savek = list(k)
for f in doset, dosort, dogroupby, donewk:
resk = f(k)
assert k == savek
print '%10s %s' % (f.__name__, sorted(resk))
Note the sanity check (performed when you just do python nodup.py
) and the basic hoisting technique (make constant global names local to each function for speed) to put things on equal footing.
Now we can run checks on the tiny example list:
$ python -mtimeit -s'import nodup' 'nodup.doset(nodup.k)'
100000 loops, best of 3: 11.7 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.dosort(nodup.k)'
100000 loops, best of 3: 9.68 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.dogroupby(nodup.k)'
100000 loops, best of 3: 8.74 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.donewk(nodup.k)'
100000 loops, best of 3: 4.44 usec per loop
confirming that the quadratic approach has small-enough constants to make it attractive for tiny lists with few duplicated values. With a short list without duplicates:
$ python -mtimeit -s'import nodup' 'nodup.donewk([[i] for i in range(12)])'
10000 loops, best of 3: 25.4 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.dogroupby([[i] for i in range(12)])'
10000 loops, best of 3: 23.7 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.doset([[i] for i in range(12)])'
10000 loops, best of 3: 31.3 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.dosort([[i] for i in range(12)])'
10000 loops, best of 3: 25 usec per loop
the quadratic approach isn't bad, but the sort and groupby ones are better. Etc, etc.
If (as the obsession with performance suggests) this operation is at a core inner loop of your pushing-the-boundaries application, it's worth trying the same set of tests on other representative input samples, possibly detecting some simple measure that could heuristically let you pick one or the other approach (but the measure must be fast, of course).
It's also well worth considering keeping a different representation for k
-- why does it have to be a list of lists rather than a set of tuples in the first place? If the duplicate removal task is frequent, and profiling shows it to be the program's performance bottleneck, keeping a set of tuples all the time and getting a list of lists from it only if and where needed, might be faster overall, for example.
You can do this without a module:
characters = list(map(chr, range(97,123)))
Type characters
and it should print ["a","b","c", ... ,"x","y","z"]
. For uppercase use:
characters=list(map(chr,range(65,91)))
Any range (including the use of range steps) can be used for this, because it makes use of Unicode. Therefore, increase the range()
to add more characters to the list.
map()
calls chr()
every iteration of the range()
.
SELECT IDENT_CURRENT('Table')
You can use one of these examples:
SELECT * FROM Table
WHERE ID = (
SELECT IDENT_CURRENT('Table'))
SELECT * FROM Table
WHERE ID = (
SELECT MAX(ID) FROM Table)
SELECT TOP 1 * FROM Table
ORDER BY ID DESC
But the first one will be more efficient because no index scan is needed (if you have index on Id column).
The second one solution is equivalent to the third (both of them need to scan table to get max id).
One way is to use a setter for the ngIf property and set the state as part of updating the value.
fade.component.ts
import {
animate,
AnimationEvent,
state,
style,
transition,
trigger
} from '@angular/animations';
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
export type FadeState = 'visible' | 'hidden';
@Component({
selector: 'app-fade',
templateUrl: './fade.component.html',
styleUrls: ['./fade.component.scss'],
animations: [
trigger('state', [
state(
'visible',
style({
opacity: '1'
})
),
state(
'hidden',
style({
opacity: '0'
})
),
transition('* => visible', [animate('500ms ease-out')]),
transition('visible => hidden', [animate('500ms ease-out')])
])
],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class FadeComponent {
state: FadeState;
// tslint:disable-next-line: variable-name
private _show: boolean;
get show() {
return this._show;
}
@Input()
set show(value: boolean) {
if (value) {
this._show = value;
this.state = 'visible';
} else {
this.state = 'hidden';
}
}
animationDone(event: AnimationEvent) {
if (event.fromState === 'visible' && event.toState === 'hidden') {
this._show = false;
}
}
}
fade.component.html
<div
*ngIf="show"
class="fade"
[@state]="state"
(@state.done)="animationDone($event)"
>
<button mat-raised-button color="primary">test</button>
</div>
example.component.css
:host {
display: block;
}
.fade {
opacity: 0;
}
$('html, body').animate({scrollTop:1200},'50');
You can do this!
This should do what you want:
<div class="comeBack_up" *ngIf="(previous_info | json) != ({} | json)">
or shorter
<div class="comeBack_up" *ngIf="(previous_info | json) != '{}'">
Each {}
creates a new instance and ====
comparison of different objects instances always results in false
. When they are convert to strings ===
results to true
Using jquery
var favicon = $("link[rel='shortcut icon']").attr("href") ||
$("link[rel='icon']").attr("href") || "";
$this->db->where('accommodation BETWEEN '' . $sdate . '' AND '' . $edate . ''');
this is my solution
This is a simplified variation of Fernando's answer. This is for Linux and either Python 2 or 3. No external library is needed, and no external process is run.
import glob
def get_command_pid(command):
for path in glob.glob('/proc/*/comm'):
if open(path).read().rstrip() == command:
return path.split('/')[2]
Only the first matching process found will be returned, which works well for some purposes. To get the PIDs of multiple matching processes, you could just replace the return
with yield
, and then get a list with pids = list(get_command_pid(command))
.
Alternatively, as a single expression:
For one process:
next(path.split('/')[2] for path in glob.glob('/proc/*/comm') if open(path).read().rstrip() == command)
For multiple processes:
[path.split('/')[2] for path in glob.glob('/proc/*/comm') if open(path).read().rstrip() == command]
You want sys.exit()
. From Python's docs:
>>> import sys
>>> print sys.exit.__doc__
exit([status])
Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).
So, basically, you'll do something like this:
from sys import exit
# Code!
exit(0) # Successful exit
Want to center an image? Very easy, Bootstrap comes with two classes, .center-block
and text-center
.
Use the former in the case of your image being a BLOCK
element, for example, adding img-responsive
class to your img
makes the img
a block element. You should know this if you know how to navigate in the web console and see applied styles to an element.
Don't want to use a class? No problem, here is the CSS bootstrap uses. You can make a custom class or write a CSS rule for the element to match the Bootstrap class.
// In case you're dealing with a block element apply this to the element itself
.center-block {
margin-left:auto;
margin-right:auto;
display:block;
}
// In case you're dealing with a inline element apply this to the parent
.text-center {
text-align:center
}
<RatingBar
android:rating="3.5"
android:stepSize="0.5"
android:numStars="5"
style = "?android:attr/ratingBarStyleSmall"
android:theme="@style/RatingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
// if you want to style
<style name="RatingBar" parent="Theme.AppCompat">
<item name="colorControlNormal">@color/colorPrimary</item>
<item name="colorControlActivated">@color/colorAccent</item>
</style>
// add these line for small rating bar
style = "?android:attr/ratingBarStyleSmall"
@media print { a[href]:after { content: none !important; } }
Complement of information for those people who use .on() to listen to events bound on inputs inside lately loaded table cells; I managed to bind event handlers to such table cells by using delegate(), but .on() wouldn't work.
I bound the table id to .delegate() and used a selector that describes the inputs.
e.g.
HTML
<table id="#mytable">
<!-- These three lines below were loaded post-DOM creation time, using a live callback for example -->
<tr><td><input name="qty_001" /></td></tr>
<tr><td><input name="qty_002" /></td></tr>
<tr><td><input name="qty_003" /></td></tr>
</table>
jQuery
$('#mytable').delegate('click', 'name^=["qty_"]', function() {
console.log("you clicked cell #" . $(this).attr("name"));
});
I've used OAuth a few times, and also used some other methods (BASIC/DIGEST). I wholeheartedly suggest OAuth. The following link is the best tutorial I've seen on using OAuth:
In case you update the image multiple times and it gets CACHED and does not update, add a random string at the end:
// update image in dom
$('#target').attr('src', 'https://example.com/img.jpg?rand=' + Math.random());
cell.imageView.image = [UIImage imageNamed:@"image.png"];
UPDATE: Like Steven Fisher said, this should only work for cells with style UITableViewCellStyleDefault which is the default style. For other styles, you'd need to add a UIImageView to the cell's contentView.
According to my understanding to your question, as an example: you had a style at the beginning in style sheet (ex. background-color: red), then using java script you changed it to another style (ex. background-color: green), now you want to reset the style to its original value in style sheet (background-color: red) without mentioning or even knowing its value (ex. element.style.backgroundColor = 'red')...!
If I'm correct, I have a good solution for you which is using another class name for the element:
steps:
if you want to edit or set a new style, get the element by the new class name and edit the style as desired.
I hope this helps. Regards!
We can also focus webelement using below code:
public focusElement(WebElement element){
String javaScript = "var evObj = document.createEvent('MouseEvents');"
+ "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"
+ "arguments[0].dispatchEvent(evObj);";
((JavascriptExecutor) getDriver()).executeScript(javaScript, element);
}
Hope it helps :)
A simple way to convert arbitrary NSData to NSString is to base64 encode it.
NSString *base64EncodedKey = [keydata base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];
You can then store it into your database for reuse later. Just decode it back to NSData.
2015 answer: we have this out of the box on modern browsers, just use the HTML5 CheckValidity API from jQuery. I've also made a jquery-html5-validity module to do this:
npm install jquery-html5-validity
Then:
var $ = require('jquery')
require("jquery-html5-validity")($);
then you can run:
$('.some-class').isValid()
true
I do the following:
from selenium import webdriver
browser = webdriver.Chrome('C:\chromedriver.exe')
browser.maximize_window()
If you wish to create a pdf from php, pdflib will help you (as some others suggested).
Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.
So, the options I know are:
DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.
HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.
Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:
wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.
htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.
You can get all keys in the Request.Form and then compare and get your desired values.
Your method body will look like this: -
List<int> listValues = new List<int>();
foreach (string key in Request.Form.AllKeys)
{
if (key.StartsWith("List"))
{
listValues.Add(Convert.ToInt32(Request.Form[key]));
}
}
I do not think you can do it in CSS, but you can calculate a pixel perfect width with javascript. Let's say you use jQuery:
HTML code:
<div id="container">
<div id="col1"></div>
<div id="col2"></div>
<div id="col3"></div>
</div>
JS Code:
$(function(){
var total = $("#container").width();
$("#col1").css({width: Math.round(total/3)+"px"});
$("#col2").css({width: Math.round(total/3)+"px"});
$("#col3").css({width: Math.round(total/3)+"px"});
});
It works fine if you follow the official documentation:
import setuptools
setuptools.setup(...)
Source: https://packaging.python.org/tutorials/packaging-projects/#creating-setup-py
IMO it's the different way to resolve a name from the OS and PHP.
Try:
echo gethostbyname("host.name.tld");
and
var_export (dns_get_record ( "host.name.tld") );
or
$dns=array("8.8.8.8","8.8.4.4");
var_export (dns_get_record ( "host.name.tld" , DNS_ALL , $dns ));
You should found some DNS/resolver error.
Use this ..
$str = rawurldecode($_SERVER['REQUEST_URI']);
$arr = explode("{",$str);
$arr1 = explode("}", $arr[1]);
$jsS = '{'.$arr1[0].'}';
$data = json_decode($jsS,true);
Now ..
use $data['elemname']
to access the values.
send jsonp request with JSON Object.
Request format :
$.ajax({
method : 'POST',
url : 'xxx.com',
data : JSONDataObj, //Use JSON.stringfy before sending data
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
success : function(response){
console.log(response);
}
})
>>> from str2bool import str2bool
>>> str2bool('Yes')
True
>>> str2bool('FaLsE')
False
If you are intending on passing those integers to a function or method, consider this example:
sum(int(x) for x in numbers)
This construction is intentionally remarkably similar to list comprehensions mentioned by adamk. Without the square brackets, it's called a generator expression, and is a very memory-efficient way of passing a list of arguments to a method. A good discussion is available here: Generator Expressions vs. List Comprehension
let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let regexp = /[a-d]/gi;
console.log(str.match(regexp));
A class based clean to use solution:
import signal
import time
class GracefulKiller:
kill_now = False
def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
def exit_gracefully(self,signum, frame):
self.kill_now = True
if __name__ == '__main__':
killer = GracefulKiller()
while not killer.kill_now:
time.sleep(1)
print("doing something in a loop ...")
print("End of the program. I was killed gracefully :)")
change Settings Manager >> Preferred Applications >> Utilities
And if you want to retain any of the aggregation info from the second level of the multiindex you can try this:
In [1]: new_cols = [''.join(t) for t in df.columns]
Out[1]:
['USAF',
'WBAN',
'day',
'month',
's_CDsum',
's_CLsum',
's_CNTsum',
's_PCsum',
'tempfamax',
'tempfamin',
'year']
In [2]: df.columns = new_cols
The JavaScript Object()
constructor makes an Object that you can assign members to.
myObj = new Object()
myObj.key = value;
myObj[key2] = value2; // Alternative
Multiple commands can be put in parenthesis and spread over numerous lines; so something like echo hi && echo hello
can be put like this:
( echo hi
echo hello )
Also variables can help:
set AFILEPATH="C:\SOME\LONG\PATH\TO\A\FILE"
if exist %AFILEPATH% (
start "" /b %AFILEPATH% -option C:\PATH\TO\SETTING...
) else (
...
Also I noticed with carets (^
) that the if
conditionals liked them to follow only if a space was present:
if exist ^
One thing not mentioned in other answers is checking the text size. It is often needed to make sure the text fits the image (e.g. shorten the text if oversized) or to determine location to draw the text (e.g. aligned text top center). Pillow/PIL offers two methods to check the text size, one via ImageFont and one via ImageDraw. As shown below, the font doesn't handle multiple lined, while ImageDraw does.
In [28]: im = Image.new(mode='RGB',size=(240,240))
In [29]: font = ImageFont.truetype('arial')
In [30]: draw = ImageDraw.Draw(im)
In [31]: t1 = 'hello world!'
In [32]: t2 = 'hello \nworld!'
In [33]: font.getsize(t1), font.getsize(t2) # the height is the same
Out[33]: ((52, 10), (60, 10))
In [35]: draw.textsize(t1, font), draw.textsize(t2, font) # handles multi-lined text
Out[35]: ((52, 10), (27, 24))
You can use a function like this to do the conversion:
function toDegrees (angle) {
return angle * (180 / Math.PI);
}
Note that functions like sin
, cos
, and so on do not return angles, they take angles as input. It seems to me that it would be more useful to you to have a function that converts a degree input to radians, like this:
function toRadians (angle) {
return angle * (Math.PI / 180);
}
which you could use to do something like tan(toRadians(45))
.
You are probably missing sqlite or the specific DB driver you are trying to migrate.
Install the DB driver and you'd be fine. You don't necessarily need to edit your php.ini file (it's one way to fix it too though).
For sqlite do --> sudo apt-get install php-sqlite3
Then php artisan migrate
NB: I assume you have PHP and MySql already installed
Use any method described in the previous post to somehow catch the mysql error.
Most common is:
$res = mysql_query('bla');
if ($res===false) {
//error
die();
}
//normal page
This would also work:
function error() {
//error
die()
}
$res = mysql_query('bla') or error();
//normal page
try { ... } catch {Exception $e) { .... }
will not work!
Note: Not directly related to you question but I think it would much more better if you display something usefull to the user. I would never revisit a website that just displays a blank screen or any mysterious error message.
**Merging objects is simple using Object.assign
or the spread ...
operator **
var obj1 = { food: 'pizza', car: 'ford' }_x000D_
var obj2 = { animal: 'dog', car: 'BMW' }_x000D_
var obj3 = {a: "A"}_x000D_
_x000D_
_x000D_
var mergedObj = Object.assign(obj1,obj2,obj3)_x000D_
// or using the Spread operator (...)_x000D_
var mergedObj = {...obj1,...obj2,...obj3}_x000D_
_x000D_
console.log(mergedObj);
_x000D_
The objects are merged from right to left, this means that objects which have identical properties as the objects to their right will be overriden.
In this example obj2.car
overrides obj1.car
The return
statement sets the exit code of the function, much the same as exit
will do for the entire script.
The exit code for the last command is always available in the $?
variable.
function fun1(){
return 34
}
function fun2(){
local res=$(fun1)
echo $? # <-- Always echos 0 since the 'local' command passes.
res=$(fun1)
echo $? #<-- Outputs 34
}
I tried following code, which works for me.
private boolean executeCommand(){
System.out.println("executeCommand");
Runtime runtime = Runtime.getRuntime();
try
{
Process mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int mExitValue = mIpAddrProcess.waitFor();
System.out.println(" mExitValue "+mExitValue);
if(mExitValue==0){
return true;
}else{
return false;
}
}
catch (InterruptedException ignore)
{
ignore.printStackTrace();
System.out.println(" Exception:"+ignore);
}
catch (IOException e)
{
e.printStackTrace();
System.out.println(" Exception:"+e);
}
return false;
}
Just to expand on @T.J. Crowder's answer.
json_encode
does well with simple html strings, in my experience however json_encode
often becomes confused by, (or it becomes quite difficult to properly escape) longer complex nested html mixed with php. Two options to consider if you are in this position are: encoding/decoding the markup first with something like [base64_encode][1]
/ decode (quite a bit of a performance hit), or (and perhaps preferably) be more selective in what you are passing via json, and generate the necessary markup on the client side instead.
You can set executionTimeout
in web.config to support the longer execution time.
executionTimeout
specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. MSDN
<httpRuntime executionTimeout = "300" />
This make execution timeout to five minutes.
Optional Int32 attribute.
Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.
This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging. The default is 110 seconds, Reference.
$fruit = array('apple', 'banana', 'pear', 'grape');
$commasaprated = implode(',' , $fruit);
You are not subscribing to any success callback in your $.post AJAX call. Meaning that the request is executed, but you do nothing with the results. If you want to do something useful with the results, try:
$.post('/Branch/Details/' + id, function(result) {
// Do something with the result like for example inject it into
// some placeholder and update the DOM.
// This obviously assumes that your controller action returns
// a partial view otherwise you will break your markup
});
On the other hand if you want to redirect, you absolutely do not need AJAX. You use AJAX only when you want to stay on the same page and update only a portion of it.
So if you only wanted to redirect the browser:
function foo(id) {
window.location.href = '/Branch/Details/' + id;
}
As a side note: You should never be hardcoding urls like this. You should always be using url helpers when dealing with urls in an ASP.NET MVC application. So:
function foo(id) {
var url = '@Url.Action("Details", "Branch", new { id = "__id__" })';
window.location.href = url.replace('__id__', id);
}
I`m posting here because I didn't want to post a new question. Assuming there aren't any single character declarations in the code, you can eval() the character to cause an error and check the type of the character. Something like:
function testForLetter(character) {_x000D_
try {_x000D_
//Variable declarations can't start with digits or operators_x000D_
//If no error is thrown check for dollar or underscore. Those are the only nonletter characters that are allowed as identifiers_x000D_
eval("let " + character + ";");_x000D_
let regExSpecial = /[^\$_]/;_x000D_
return regExSpecial.test(character);_x000D_
} catch (error) {_x000D_
return false;_x000D_
}_x000D_
}_x000D_
_x000D_
console.log(testForLetter("!")); //returns false;_x000D_
console.log(testForLetter("5")); //returns false;_x000D_
console.log(testForLetter("?")); //returns true;_x000D_
console.log(testForLetter("_")); //returns false;
_x000D_
You should be able to generate your own button code here: http://developers.facebook.com/docs/reference/plugins/like/
Almost there. In your predicate, you want a relative path, so change
./book[/author/name = 'John']
to either
./book[author/name = 'John']
or
./book[./author/name = 'John']
and you will match your element. Your current predicate goes back to the root of the document to look for an author
.
I wanted to post this answer as an update for users of more recent Android builds (CM11/KitKat/4.4.4). I have not tested any of this with TouchWiz or older Android releases so YMMV.
The following commands can be run in all the usual places (ADB, Terminal Emulator, shell scripts, Tasker).
List all available properties:
getprop
Get WiFi interface:
getprop wifi.interface
WiFi properties:
getprop dhcp.wlan0.dns1
getprop dhcp.wlan0.dns2
getprop dhcp.wlan0.dns3
getprop dhcp.wlan0.dns4
getprop dhcp.wlan0.domain
getprop dhcp.wlan0.gateway
getprop dhcp.wlan0.ipaddress
getprop dhcp.wlan0.mask
The above commands will output information regardless of whether WiFi is actually connected at the time.
Use either of the following to check whether wlan0 is on or not:
ifconfig wlan0
netcfg | awk '{if ($2=="UP" && $3 != "0.0.0.0/0") isup=1} END {if (! isup) exit 1}'
Use either of the following to get the IP address of wlan0 (only if it is connected):
ifconfig wlan0 | awk '{print $3}'
netcfg | awk '/^wlan0/ {sub("(0\\.0\\.0\\.0)?/[0-9]*$", "", $3); print $3}'
Just for thoroughness, to get your public Internet-facing IP address, you're going to want to use an external service. To obtain your public IP:
wget -qO- 'http://ipecho.net/plain'
To obtain your public hostname:
wget -qO- 'http://ifconfig.me/host'
Or to obtain your public hostname directly from your IP address:
(nslookup "$(wget -qO- http://ipecho.net/plain)" | awk '/^Address 1: / { if ($NF != "0.0.0.0") {print $NF; exit}}; /name =/ {sub("\\.$", "", $NF); print $NF; exit}') 2>/dev/null
Note: The aforementioned awk
command seems overly complicated only because is able to handle output from various versions of nslookup
. Android includes a minimal version of nslookup
as part of busybox
but there is a standalone version as well (often included in dnsutils
).
git show somebranch:path/to/your/file
you can also do multiple files and have them concatenated:
git show branchA~10:fileA branchB^^:fileB
You do not have to provide the full path to the file, relative paths are acceptable e.g.:
git show branchA~10:../src/hello.c
If you want to get the file in the local directory (revert just one file) you can checkout:
git checkout somebranch^^^ -- path/to/file
Such unexpected problems can appear when you copy the code from a web page or email and the text contains unprintable characters like individual CR or LF and non-breaking spaces.
Got the same error when using curl on https site like
curl https://api.dis...
as pointed out by ganesh, it was because my version of curl wasn't ssl enabled. went back and downloaded the version with ssl and it worked fine.
Found this on OzGrid courtesy of Mr. Aaron Blood - simple direct and works.
Code:
Cells(1, 3).Copy Cells(1, 1)
Cells(1, 1).Value = Cells(1, 3).Value
However, I kinda suspect you were just providing us with an oversimplified example to ask the question. If you just want to copy formats from one range to another it looks like this...
Code:
Cells(1, 3).Copy
Cells(1, 1).PasteSpecial (xlPasteFormats)
Application.CutCopyMode = False
There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT
does exist in PDW. In SQL Server you can use this query to create an empty table:
SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;
(If you want to make a copy of the table including all of the data, then leave out the WHERE
clause.)
Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.
If you want to be able to return to the precise version of the repository at the time you do a build it is best to tag the commit from which you make the build.
The other answers provide techniques to return the repository to the most recent commit in a branch as of a certain time-- but they might not always suffice. For example, if you build from a branch, and later delete the branch, or build from a branch that is later rebased, the commit you built from can become "unreachable" in git from any current branch. Unreachable objects in git may eventually be removed when the repository is compacted.
Putting a tag on the commit means it never becomes unreachable, no matter what you do with branches afterwards (barring removing the tag).
Option 1 is to use display:table-cell
. You need to unfloat the Bootstrap col-* using float:none
..
.center {
display:table-cell;
vertical-align:middle;
float:none;
}
Option 2 is display:flex
to vertical align the row with flexbox:
.row.center {
display: flex;
align-items: center;
}
http://www.bootply.com/7rAuLpMCwr
Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4 https://stackoverflow.com/a/41464397/171456
You may be looking for auto-fill
:
grid-template-columns: repeat(auto-fill, 186px);
Demo: http://codepen.io/alanbuchanan/pen/wJRMox
To use up the available space more efficiently, you could use minmax
, and pass in auto
as the second argument:
grid-template-columns: repeat(auto-fill, minmax(186px, auto));
Demo: http://codepen.io/alanbuchanan/pen/jBXWLR
If you don't want the empty columns, you could use auto-fit
instead of auto-fill
.
How are you setting up the SqlParameter
? You should set the SqlDbType
property to SqlDbType.DateTime
and then pass the DateTime
directly to the parameter (do NOT convert to a string, you are asking for a bunch of problems then).
You should be able to get the value into the DB. If not, here is a very simple example of how to do it:
static void Main(string[] args)
{
// Create the connection.
using (SqlConnection connection = new SqlConnection(@"Data Source=..."))
{
// Open the connection.
connection.Open();
// Create the command.
using (SqlCommand command = new SqlCommand("xsp_Test", connection))
{
// Set the command type.
command.CommandType = System.Data.CommandType.StoredProcedure;
// Add the parameter.
SqlParameter parameter = command.Parameters.Add("@dt",
System.Data.SqlDbType.DateTime);
// Set the value.
parameter.Value = DateTime.Now;
// Make the call.
command.ExecuteNonQuery();
}
}
}
I think part of the issue here is that you are worried that the fact that the time is in UTC is not being conveyed to SQL Server. To that end, you shouldn't, because SQL Server doesn't know that a particular time is in a particular locale/time zone.
If you want to store the UTC value, then convert it to UTC before passing it to SQL Server (unless your server has the same time zone as the client code generating the DateTime
, and even then, that's a risk, IMO). SQL Server will store this value and when you get it back, if you want to display it in local time, you have to do it yourself (which the DateTime
struct will easily do).
All that being said, if you perform the conversion and then pass the converted UTC date (the date that is obtained by calling the ToUniversalTime
method, not by converting to a string) to the stored procedure.
And when you get the value back, call the ToLocalTime
method to get the time in the local time zone.
Another option,especially useful if you have many items you need to pivot is to let mysql build the query for you:
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'ifnull(SUM(case when itemname = ''',
itemname,
''' then itemvalue end),0) AS `',
itemname, '`'
)
) INTO @sql
FROM
history;
SET @sql = CONCAT('SELECT hostid, ', @sql, '
FROM history
GROUP BY hostid');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
FIDDLE Added some extra values to see it working
GROUP_CONCAT
has a default value of 1000 so if you have a really big query change this parameter before running it
SET SESSION group_concat_max_len = 1000000;
Test:
DROP TABLE IF EXISTS history;
CREATE TABLE history
(hostid INT,
itemname VARCHAR(5),
itemvalue INT);
INSERT INTO history VALUES(1,'A',10),(1,'B',3),(2,'A',9),
(2,'C',40),(2,'D',5),
(3,'A',14),(3,'B',67),(3,'D',8);
hostid A B C D
1 10 3 0 0
2 9 0 40 5
3 14 67 0 8
Problem occurs because of the entry mapping class="annotations.Users"
in hibernate.cfg.xml
remove that line then it will be work.
I had the same issue. When I removed the above line then it was working fine for me.
In manifiest file add to each activity this. This will help
android:configChanges = "orientation|keyboard|keyboardHidden|screenLayout|screenSize"
Using an escaped string (a.k.a. escaped value):
width: ~"calc(100% - 200px)";
Also, in case you need to mix Less math with escaped strings:
width: calc(~"100% - 15rem +" (10px+5px) ~"+ 2em");
Compiles to:
width: calc(100% - 15rem + 15px + 2em);
This works as Less concatenates values (the escaped strings and math result) with a space by default.
You have to give the values between 0 and 1.0. So divide the RGB values by 255.
myLabel.textColor= [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1] ;
Update:
You can also use this macro
#define Rgb2UIColor(r, g, b) [UIColor colorWithRed:((r) / 255.0) green:((g) / 255.0) blue:((b) / 255.0) alpha:1.0]
and you can call in any of your class like this
myLabel.textColor = Rgb2UIColor(160, 97, 5);
This is the normal color synax
myLabel.textColor = UIColor(red: (160/255.0), green: (97/255.0), blue: (5/255.0), alpha: 1.0)
//The values should be between 0 to 1
Swift is not much friendly with macros
Complex macros are used in C and Objective-C but have no counterpart in Swift. Complex macros are macros that do not define constants, including parenthesized, function-like macros. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.
So we use extension for this
extension UIColor {
convenience init(_ r: Double,_ g: Double,_ b: Double,_ a: Double) {
self.init(red: r/255, green: g/255, blue: b/255, alpha: a)
}
}
You can use it like
myLabel.textColor = UIColor(160.0, 97.0, 5.0, 1.0)
[EDIT]
The expected output of the pluck
function has changed from Laravel 5.1 to 5.2. Hence why it is marked as deprecated in 5.1
In Laravel 5.1, pluck
gets a single column's value from the first result of a query.
In Laravel 5.2, pluck
gets an array with the values of a given column. So it's no longer deprecated, but it no longer do what it used to.
So short answer is use the value
function if you want one column from the first row and you are using Laravel 5.1 or above.
Thanks to Tomas Buteler for pointing this out in the comments.
[ORIGINAL] For anyone coming across this question who is using Laravel 5.1, pluck() has been deprecated and will be removed completely in Laravel 5.2.
Consider future proofing your code by using value()
instead.
return DB::table('users')->where('username', $username)->value('groupName');
This looks like a behavior difference in the handling of \s
between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).
Note:
GNU grep 2.5.4
echo "foo bar" | grep "\s"
(doesn't match)
whereas
GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar
Probably less trouble (as \s
is not documented):
Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar
My advice is to avoid using \s
... use [ \t]*
or [[:space:]]
or something like it instead.
This will return all the values matching your key valueTitle
subList.SelectMany(m => m).Where(kvp => kvp.Key == "valueTitle").Select(k => k.Value).ToList();
For text:
[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
For cell background
[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);