This deletes only files from ABC (sub-directories are untouched):
Arrays.stream(new File("C:/test/ABC/").listFiles()).forEach(File::delete);
This deletes only files from ABC (and sub-directories):
Files.walk(Paths.get("C:/test/ABC/"))
.filter(Files::isRegularFile)
.map(Path::toFile)
.forEach(File::delete);
^ This version requires handling the IOException
You should take a look at node-asyncEJS, which is explicitly designed to take the asynchronous nature of node.js into account. It even allows async code blocks inside of the template.
Here an example form the documentation:
<html>
<head>
<% ctx.hello = "World"; %>
<title><%= "Hello " + ctx.hello %></title>
</head>
<body>
<h1><%? setTimeout(function () { res.print("Async Header"); res.finish(); }, 2000) %></h1>
<p><%? setTimeout(function () { res.print("Body"); res.finish(); }, 1000) %></p>
</body>
</html>
I've just found a great tool for that need, it is called tabulate.
It prints tabular data and works with DataFrame
.
from tabulate import tabulate
import pandas as pd
df = pd.DataFrame({'col_two' : [0.0001, 1e-005 , 1e-006, 1e-007],
'column_3' : ['ABCD', 'ABCD', 'long string', 'ABCD']})
print(tabulate(df, headers='keys', tablefmt='psql'))
+----+-----------+-------------+
| | col_two | column_3 |
|----+-----------+-------------|
| 0 | 0.0001 | ABCD |
| 1 | 1e-05 | ABCD |
| 2 | 1e-06 | long string |
| 3 | 1e-07 | ABCD |
+----+-----------+-------------+
Note:
To suppress row indices for all types of data, pass
showindex="never"
orshowindex=False
.
just type ./a in the shell
A simple solution is to use BindingList<T>
instead of ObservableCollection<T>
. Indeed the BindingList relay item change notifications. So with a binding list, if the item implements the interface INotifyPropertyChanged
then you can simply get notifications using the ListChanged event.
See also this SO answer.
This is really linked to HotSpot and the default option values (Java HotSpot VM Options) which differ between client and server configuration.
From Chapter 2 of the whitepaper (The Java HotSpot Performance Engine Architecture):
The JDK includes two flavors of the VM -- a client-side offering, and a VM tuned for server applications. These two solutions share the Java HotSpot runtime environment code base, but use different compilers that are suited to the distinctly unique performance characteristics of clients and servers. These differences include the compilation inlining policy and heap defaults.
Although the Server and the Client VMs are similar, the Server VM has been specially tuned to maximize peak operating speed. It is intended for executing long-running server applications, which need the fastest possible operating speed more than a fast start-up time or smaller runtime memory footprint.
The Client VM compiler serves as an upgrade for both the Classic VM and the just-in-time (JIT) compilers used by previous versions of the JDK. The Client VM offers improved run time performance for applications and applets. The Java HotSpot Client VM has been specially tuned to reduce application start-up time and memory footprint, making it particularly well suited for client environments. In general, the client system is better for GUIs.
So the real difference is also on the compiler level:
The Client VM compiler does not try to execute many of the more complex optimizations performed by the compiler in the Server VM, but in exchange, it requires less time to analyze and compile a piece of code. This means the Client VM can start up faster and requires a smaller memory footprint.
The Server VM contains an advanced adaptive compiler that supports many of the same types of optimizations performed by optimizing C++ compilers, as well as some optimizations that cannot be done by traditional compilers, such as aggressive inlining across virtual method invocations. This is a competitive and performance advantage over static compilers. Adaptive optimization technology is very flexible in its approach, and typically outperforms even advanced static analysis and compilation techniques.
Note: The release of jdk6 update 10 (see Update Release Notes:Changes in 1.6.0_10) tried to improve startup time, but for a different reason than the hotspot options, being packaged differently with a much smaller kernel.
G. Demecki points out in the comments that in 64-bit versions of JDK, the -client
option is ignored for many years.
See Windows java
command:
-client
Selects the Java HotSpot Client VM.
A 64-bit capable JDK currently ignores this option and instead uses the Java Hotspot Server VM.
For Swift 3
Create a function for button action first and then add the function to your button target
func buttonAction(sender: UIButton!) {
print("Button tapped")
}
button.addTarget(self, action: #selector(buttonAction),for: .touchUpInside)
At this moment, 2020-10-17, if you select a text element and hit CTRL+SHIFT+ALT+M it will highlight every instance within the code chunk.
It is fairly risky to rely on javascript functions to compare and play with numbers. In javascript (0.1+0.2 == 0.3) will return false due to rounding errors. Use the math.js library.
I installed Bitnami WAMP Stack 7.1.29-0 and it asked for a password during installation. In this case it was
username: root
password: <password set by you during install>
A very easy way to understand typedef of function pointer:
int add(int a, int b)
{
return (a+b);
}
typedef int (*add_integer)(int, int); //declaration of function pointer
int main()
{
add_integer addition = add; //typedef assigns a new variable i.e. "addition" to original function "add"
int c = addition(11, 11); //calling function via new variable
printf("%d",c);
return 0;
}
The equivalent JPA mapping for the DDL ON DELETE CASCADE
is cascade=CascadeType.REMOVE
. Orphan removal means that dependent entities are removed when the relationship to their "parent" entity is destroyed. For example if a child is removed from a @OneToMany
relationship without explicitely removing it in the entity manager.
You can try @Rule
annotation. Here is the example from the docs:
public static class UsesExternalResource {
Server myServer = new Server();
@Rule public ExternalResource resource = new ExternalResource() {
@Override
protected void before() throws Throwable {
myServer.connect();
};
@Override
protected void after() {
myServer.disconnect();
};
};
@Test public void testFoo() {
new Client().run(myServer);
}
}
You just need to create FileResource
class extending ExternalResource
.
Full Example
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
public class TestSomething
{
@Rule
public ResourceFile res = new ResourceFile("/res.txt");
@Test
public void test() throws Exception
{
assertTrue(res.getContent().length() > 0);
assertTrue(res.getFile().exists());
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import org.junit.rules.ExternalResource;
public class ResourceFile extends ExternalResource
{
String res;
File file = null;
InputStream stream;
public ResourceFile(String res)
{
this.res = res;
}
public File getFile() throws IOException
{
if (file == null)
{
createFile();
}
return file;
}
public InputStream getInputStream()
{
return stream;
}
public InputStream createInputStream()
{
return getClass().getResourceAsStream(res);
}
public String getContent() throws IOException
{
return getContent("utf-8");
}
public String getContent(String charSet) throws IOException
{
InputStreamReader reader = new InputStreamReader(createInputStream(),
Charset.forName(charSet));
char[] tmp = new char[4096];
StringBuilder b = new StringBuilder();
try
{
while (true)
{
int len = reader.read(tmp);
if (len < 0)
{
break;
}
b.append(tmp, 0, len);
}
reader.close();
}
finally
{
reader.close();
}
return b.toString();
}
@Override
protected void before() throws Throwable
{
super.before();
stream = getClass().getResourceAsStream(res);
}
@Override
protected void after()
{
try
{
stream.close();
}
catch (IOException e)
{
// ignore
}
if (file != null)
{
file.delete();
}
super.after();
}
private void createFile() throws IOException
{
file = new File(".",res);
InputStream stream = getClass().getResourceAsStream(res);
try
{
file.createNewFile();
FileOutputStream ostream = null;
try
{
ostream = new FileOutputStream(file);
byte[] buffer = new byte[4096];
while (true)
{
int len = stream.read(buffer);
if (len < 0)
{
break;
}
ostream.write(buffer, 0, len);
}
}
finally
{
if (ostream != null)
{
ostream.close();
}
}
}
finally
{
stream.close();
}
}
}
Why can't it be the onResume() is invoked after onRestart() and onCreate() methods just excluding onStart()? What is its purpose?
OK, as my first answer was pretty long I won't extend it further so let's try this...
public DriveToWorkActivity extends Activity
implements onReachedGroceryStoreListener {
}
public GroceryStoreActivity extends Activity {}
PLEASE NOTE: I've deliberately left out the calls to things like super.onCreate(...)
etc. This is pseudo-code so give me some artistic licence here. ;)
The methods for DriveToWorkActivity
follow...
protected void onCreate(...) {
openGarageDoor();
unlockCarAndGetIn();
closeCarDoorAndPutOnSeatBelt();
putKeyInIgnition();
}
protected void onStart() {
startEngine();
changeRadioStation();
switchOnLightsIfNeeded();
switchOnWipersIfNeeded();
}
protected void onResume() {
applyFootbrake();
releaseHandbrake();
putCarInGear();
drive();
}
protected void onPause() {
putCarInNeutral();
applyHandbrake();
}
protected void onStop() {
switchEveryThingOff();
turnOffEngine();
removeSeatBeltAndGetOutOfCar();
lockCar();
}
protected void onDestroy() {
enterOfficeBuilding();
}
protected void onReachedGroceryStore(...) {
Intent i = new Intent(ACTION_GET_GROCERIES, ..., this, GroceryStoreActivity.class);
}
protected void onRestart() {
unlockCarAndGetIn();
closeDoorAndPutOnSeatBelt();
putKeyInIgnition();
}
OK, so it's another long one (sorry folks). But here's my explanation...
onResume()
is when I start driving and onPause()
is when I come to a temporary stop. So I drive then reach a red light so I pause...the light goes green and I resume. Another red light and I pause, then green so I resume. The onPause() -> onResume() -> onPause() -> onResume()
loop is a tight one and occurs many times through my journey.
The loop from being stopped back through a restart (preparing to carry on my journey) to starting again is perhaps less common. In one case, I spot the Grocery Store and the GroceryStoreActivity
is started (forcing my DriveToWorkActivity
to the point of onStop()
). When I return from the store, I go through onRestart()
and onStart()
then resume my journey.
I could put the code that's in onStart()
into both onCreate()
and onRestart()
and not bother to override onStart()
at all but the more that needs to be done between onCreate() -> onResume()
and onRestart() -> onResume()
, the more I'm duplicating things.
So, to requote once more...
Why can't it be the onResume() is invoked after onRestart() and onCreate() methods just excluding onStart()?
If you don't override onStart()
then this is effectively what happens. Although the onStart()
method of Activity
will be called implicitly, the effect in your code is effectively onCreate() -> onResume()
or onRestart() -> onResume()
.
You have to select "Refresh Dependencies" in the "Gradle" context menu that appears when you right-click the project in the Package Explorer.
There are a few things which new
does that malloc
doesn’t:
new
constructs the object by calling the constructor of that objectnew
doesn’t require typecasting of allocated memory.So, if you use malloc
, then you need to do above things explicitly, which is not always practical. Additionally, new
can be overloaded but malloc
can’t be.
In a word, if you use C++, try to use new
as much as possible.
You can do it using group by:
c_maxes = df.groupby(['A', 'B']).C.transform(max)
df = df.loc[df.C == c_maxes]
c_maxes
is a Series
of the maximum values of C
in each group but which is of the same length and with the same index as df
. If you haven't used .transform
then printing c_maxes
might be a good idea to see how it works.
Another approach using drop_duplicates
would be
df.sort('C').drop_duplicates(subset=['A', 'B'], take_last=True)
Not sure which is more efficient but I guess the first approach as it doesn't involve sorting.
EDIT:
From pandas 0.18
up the second solution would be
df.sort_values('C').drop_duplicates(subset=['A', 'B'], keep='last')
or, alternatively,
df.sort_values('C', ascending=False).drop_duplicates(subset=['A', 'B'])
In any case, the groupby
solution seems to be significantly more performing:
%timeit -n 10 df.loc[df.groupby(['A', 'B']).C.max == df.C]
10 loops, best of 3: 25.7 ms per loop
%timeit -n 10 df.sort_values('C').drop_duplicates(subset=['A', 'B'], keep='last')
10 loops, best of 3: 101 ms per loop
A work-around is to use @tvanfosson's answer (the selected answer) and use JQuery (or Javascript) to set the option's value to 0:
$(document).ready(function () {
$('#DropDownListId option:first').val('0');
});
Hope this helps.
From the help file about $
(See ?"$"
) you can read:
$ is only valid for recursive objects, and is only discussed in the section below on recursive objects.
Now, let's check whether x
is recursive
> is.recursive(x)
[1] FALSE
A recursive object has a list-like structure. A vector is not recursive, it is an atomic object instead, let's check
> is.atomic(x)
[1] TRUE
Therefore you get an error when applying $
to a vector (non-recursive object), use [
instead:
> x["ed"]
ed
2
You can also use getElement
> getElement(x, "ed")
[1] 2
Found this in another thread that helped me: Use xp_cmdshell and sqlcmd Is it possible to execute a text file from SQL query? - by Gulzar Nazim
EXEC xp_cmdshell 'sqlcmd -S ' + @DBServerName + ' -d ' + @DBName + ' -i ' + @FilePathName
$('#input').datepicker({autoclose:true});
Here are the steps I used to manually install python3 for anyone else who wants to do it as it's not super straight forward. EDIT: It's almost certainly easier to use the yum package manager (see other answers).
Note, you'll probably want to do sudo yum groupinstall 'Development Tools'
before doing this otherwise pip won't install.
wget https://www.python.org/ftp/python/3.4.2/Python-3.4.2.tgz
tar zxvf Python-3.4.2.tgz
cd Python-3.4.2
sudo yum install gcc
./configure --prefix=/opt/python3
make
sudo yum install openssl-devel
sudo make install
sudo ln -s /opt/python3/bin/python3 /usr/bin/python3
python3 (should start the interpreter if it's worked (quit() to exit)
Checkout intent properties like no history , clear back stack etc ... Intent.setFlags
Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
The simplest way to do this is with the onto
option to rebase
. Suppose that the branch which current finishes at a
is called mybranch and this is the branch that you want to move c
-f
onto.
# checkout mybranch
git checkout mybranch
# reset it to f (currently includes a)
git reset --hard f
# rebase every commit after b and transplant it onto a
git rebase --onto a b
Disable:
document.ontouchstart = function(e){ e.preventDefault(); }
Enable:
document.ontouchstart = function(e){ return true; }
Thread th = new Thread(function1);
th.Start();
th.Abort();
void function1(){
//code here
}
This may also be because you might have given classname with all letters in lowercase something which groovy (know of version 2.5.0) does not support.
class name - User is accepted but user is not.
Do it like this:
SSLSocket socket = (SSLSocket) sslFactory.createSocket(host, port);
socket.setEnabledProtocols(new String[]{"SSLv3", "TLSv1"});
Use the .Clear
method.
Sheets("Test").Range("A1:C3").Clear
Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.
That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...
What version of the SQL Server engine do you get from SELECT @@VERSION
??
In order to access project from the homepage you need to create a Virtual Host first.
Most easiest way to do this is to use Wamp's Add a Virtual Host Utility.
Just follow these steps:
<?php
echo "<h1>Hello World</h1>";
?>
Now you can access the projects from the localhost's homepage. Just click the project link and you'll see 'Hello World' printed on your screen.
class Second:
def __init__(self, data):
self.data = data
class First:
def SecondClass(self, data):
return Second(data)
FirstClass = First()
SecondClass = FirstClass.SecondClass('now you see me')
print SecondClass.data
$Group
is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string")
.
Change $Group.StartsWith("S_G_")
to $Group.samaccountname.StartsWith("S_G_")
.
I would like to answer your question, as there are various methods - here I’ll talk about the code that is widely used.
So, for hiding the sheet:
Sub try()
Worksheets("Sheet1").Visible = xlSheetHidden
End Sub
There are other methods also if you want to learn all Methods Click here
You can get the managed bean by passing the name:
public static Object getBean(String beanName){
Object bean = null;
FacesContext fc = FacesContext.getCurrentInstance();
if(fc!=null){
ELContext elContext = fc.getELContext();
bean = elContext.getELResolver().getValue(elContext, null, beanName);
}
return bean;
}
Just a very quick addition as I have been testing a few options and missed this along the way. Make sure your page has:
<meta name="viewport" content="initial-scale=1.0">
Solved, this is how your parse their html results:
table = soup.find("table", { "class" : "lineItemsTable" })
for row in table.findAll("tr"):
cells = row.findAll("td")
if len(cells) == 9:
summons = cells[1].find(text=True)
plateType = cells[2].find(text=True)
vDate = cells[3].find(text=True)
location = cells[4].find(text=True)
borough = cells[5].find(text=True)
vCode = cells[6].find(text=True)
amount = cells[7].find(text=True)
print amount
You can't read individual integers in a single line separately using BufferedReader
as you do using Scanner
class.
Although, you can do something like this in regard to your query :
import java.io.*;
class Test
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
for(int i=0;i<t;i++)
{
String str=br.readLine();
String num[]=br.readLine().split(" ");
int num1=Integer.parseInt(num[0]);
int num2=Integer.parseInt(num[1]);
//rest of your code
}
}
}
I hope this will help you.
This can also be done as follows. Put your commands in a script, let's name it commands-inc.sh
#!/bin/bash
ls some_folder
./someaction.sh
pwd
Save the file
Now run it on the remote server.
ssh user@remote 'bash -s' < /path/to/commands-inc.sh
Never failed for me.
import psutil
def check_process_status(process_name):
"""
Return status of process based on process name.
"""
process_status = [ proc.status() for proc in psutil.process_iter() if proc.name() == process_name ]
if process_status:
print("Process name %s and staus %s"%(process_name, process_status[0]))
else:
print("Process name not valid", process_name)
by using replaceChild():
<html>
<head>
</head>
<body>
<div>
<a id="myAnchor" href="http://www.stackoverflow.com">StackOverflow</a>
</div>
<script type="text/JavaScript">
var myAnchor = document.getElementById("myAnchor");
var mySpan = document.createElement("span");
mySpan.innerHTML = "replaced anchor!";
myAnchor.parentNode.replaceChild(mySpan, myAnchor);
</script>
</body>
</html>
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }
.
using zlib.h (http://refspecs.linuxbase.org/LSB_3.0.0/LSB-Core-generic/LSB-Core-generic/zlib-crc32-1.html):
#include <zlib.h>
unsigned long crc = crc32(0L, Z_NULL, 0);
crc = crc32(crc, (const unsigned char*)data_address, data_len);
Try this :
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Test {
public static void main(String[] args) {
JFrame f = new JFrame();
try {
f.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("test.jpg")))));
} catch (IOException e) {
e.printStackTrace();
}
f.pack();
f.setVisible(true);
}
}
By the way, this will result in the content pane not being a container. If you want to add things to it you have to subclass a JPanel and override the paintComponent method.
This worked for me (i wanted to make id primary and set auto increment)
ALTER TABLE table_name
CHANGE id
id
INT PRIMARY KEY AUTO_INCREMENT;
C++ supplies a string
class that can be used like this:
#include <string>
#include <iostream>
int main() {
std::string Something = "Some text";
std::cout << Something << std::endl;
}
The JPA 2.0 Specification states that:
- The entity class must have a no-arg constructor. It may have other constructors as well. The no-arg constructor must be public or protected.
- The entity class must a be top-level class. An enum or interface must not be designated as an entity.
- The entity class must not be final. No methods or persistent instance variables of the entity class may be final.
- If an entity instance is to be passed by value as a detached object (e.g., through a remote interface), the entity class must implement the Serializable interface.
- Both abstract and concrete classes can be entities. Entities may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes.
The specification contains no requirements about the implementation of equals and hashCode methods for entities, only for primary key classes and map keys as far as I know.
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPHONE_X (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 812.0f)
I'm not sure if this is what you wanted, but this is a very hackish way to include php. What you do is you put the php you want to run in another file, and then you include that file in an image. For example:
RunFromHTML.php
<?php
$file = fopen("file.txt", "w");
//This will create a file called file.txt,
//provided that it has write access to your filesystem
fwrite($file, "Hello World!");
//This will write "Hello World!" into file.txt
fclose($file);
//Always remember to close your files!
?>
RunPhp.html
<html>
<!--head should be here, but isn't for demonstration's sake-->
<body>
<img style="display: none;" src="RunFromHTML.php">
<!--This will run RunFromHTML.php-->
</body>
</html>
Now, after visiting RunPhp.html, you should find a file called file.txt in the same directory that you created the above two files, and the file should contain "Hello World!" inside of it.
I'm little late to the party, but for anyone like me that came from a Google search and didn't find the right answer. Don't get me wrong there are good answers here, but not exactly what I was looking for, without further ado, here is what I did:
$(document).ready(function() {
var $deleteButton = $('.deleteItem');
$deleteButton.on('click', function(event) {
event.preventDefault();
var $button = $(this);
if(confirm('Are you sure about this ?')) {
var $item = $button.closest('tr.item');
$item.addClass('removed-item')
.one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
$(this).remove();
});
}
});
});
_x000D_
/**
* Credit to Sara Soueidan
* @link https://github.com/SaraSoueidan/creative-list-effects/blob/master/css/styles-4.css
*/
.removed-item {
-webkit-animation: removed-item-animation .6s cubic-bezier(.55,-0.04,.91,.94) forwards;
-o-animation: removed-item-animation .6s cubic-bezier(.55,-0.04,.91,.94) forwards;
animation: removed-item-animation .6s cubic-bezier(.55,-0.04,.91,.94) forwards
}
@keyframes removed-item-animation {
from {
opacity: 1;
-webkit-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1)
}
to {
-webkit-transform: scale(0);
-ms-transform: scale(0);
-o-transform: scale(0);
transform: scale(0);
opacity: 0
}
}
@-webkit-keyframes removed-item-animation {
from {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1)
}
to {
-webkit-transform: scale(0);
transform: scale(0);
opacity: 0
}
}
@-o-keyframes removed-item-animation {
from {
opacity: 1;
-o-transform: scale(1);
transform: scale(1)
}
to {
-o-transform: scale(0);
transform: scale(0);
opacity: 0
}
}
_x000D_
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>id</th>
<th>firstname</th>
<th>lastname</th>
<th>@twitter</th>
<th>action</th>
</tr>
</thead>
<tbody>
<tr class="item">
<td>1</td>
<td>Nour-Eddine</td>
<td>ECH-CHEBABY</td>
<th>@__chebaby</th>
<td><button class="btn btn-danger deleteItem">Delete</button></td>
</tr>
<tr class="item">
<td>2</td>
<td>John</td>
<td>Doe</td>
<th>@johndoe</th>
<td><button class="btn btn-danger deleteItem">Delete</button></td>
</tr>
<tr class="item">
<td>3</td>
<td>Jane</td>
<td>Doe</td>
<th>@janedoe</th>
<td><button class="btn btn-danger deleteItem">Delete</button></td>
</tr>
</tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
_x000D_
Though they operate the same way, however, the mouseenter
event only triggers when the mouse pointer enters the selected element. The mouseover
event is triggered if a mouse pointer enters any child elements as well.
I had the same problem with bootstrap datetimepicker extension. Including moment.js before datetimepicker.js was the solution.
You are correct, memory is automatically freed when the process exits. Some people strive not to do extensive cleanup when the process is terminated, since it will all be relinquished to the operating system. However, while your program is running you should free unused memory. If you don't, you may eventually run out or cause excessive paging if your working set gets too big.
Dim sSheetName As String
Dim sConnection As String
Dim dtTablesList As DataTable
Dim oleExcelCommand As OleDbCommand
Dim oleExcelReader As OleDbDataReader
Dim oleExcelConnection As OleDbConnection
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Test.xls;Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
oleExcelConnection = New OleDbConnection(sConnection)
oleExcelConnection.Open()
dtTablesList = oleExcelConnection.GetSchema("Tables")
If dtTablesList.Rows.Count > 0 Then
sSheetName = dtTablesList.Rows(0)("TABLE_NAME").ToString
End If
dtTablesList.Clear()
dtTablesList.Dispose()
If sSheetName <> "" Then
oleExcelCommand = oleExcelConnection.CreateCommand()
oleExcelCommand.CommandText = "Select * From [" & sSheetName & "]"
oleExcelCommand.CommandType = CommandType.Text
oleExcelReader = oleExcelCommand.ExecuteReader
nOutputRow = 0
While oleExcelReader.Read
End While
oleExcelReader.Close()
End If
oleExcelConnection.Close()
Get items when the date is between fromdate and toDate.
where convert(date, fromdate, 103 ) <= '2016-07-26' and convert(date, toDate, 103) >= '2016-07-26'
In your Gradle app level file >> compileOptions add this two lines
android {
compileOptions {
...
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
...
}
}
To exit from an Android app, just simply use. in your Main Activity, or you can use Android manifest file to set
android:noHistory="true"
java.util.List
is an interface. How much data a list can hold is dependant on the specific implementation of List you choose to use.
Generally, a List implementation can hold any number of items (If you use an indexed List, it may be limited to Integer.MAX_VALUE
or Long.MAX_VALUE
). As long as you don't run out of memory, the List doesn't become "full" or anything.
Running the command, "sbt sbt-version" will simply output your current directory and the version number.
$ sbt sbt-version
[info] Set current project to spark (in build file:/home/morgan/code/spark/)
[info] 0.13.8
The player_api will be deprecated on Jun 25, 2015. For play youtube videos there is a new api IFRAME_API
It looks like the following code:
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
atan2(y,x)
is generally used if you want to convert cartesian coordinates to polar coordinates. It will give you the angle, while sqrt(x*x+y*y)
or, if available, hypot(y,x)
will give you the size.
atan(x)
is simply the inverse of tan. In the annoying case you have to use atan(y/x)
because your system doesn't provide atan2
, you would have to do additional checks for the signs of x
and y
, and for x=0
, in order to get the correct angle.
Note: atan2(y,x)
is defined for all real values of y
and x
, except for the case when both arguments are zero.
From my experience event.stopPropagation() is mostly used in CSS effect or animation works, for instance when you have hover effect for both card and button element, when you hover on the button both card and buttons hover effect will be triggered in this case, you can use event.stopPropagation() stop bubbling actions, and event.preventDefault() is for prevent default behaviour of browser actions. For instance, you have form but you only defined click event for the submit action, if the user submits the form by pressing enter, the browser triggered by keypress event, not your click event here you should use event.preventDefault() to avoid inappropriate behavior. I don't know what the hell is return false; sorry.For more clarification visit this link and play around with line #33 https://www.codecademy.com/courses/introduction-to-javascript/lessons/requests-i/exercises/xhr-get-request-iv
This is not the OP's problem, but I got the same Object is possibly 'null'
message when I had declared a parameter as the null type by accident:
something: null;
instead of assigning it the value of null:
something: string = null;
See: http://jsfiddle.net/thirtydot/EDp8R/
text-align: justify
combined with .stretch
is what's handling the positioning.display:inline-block; *display:inline; zoom:1
fixes inline-block
for IE6/7, see here.font-size: 0; line-height: 0
fixes a minor issue in IE6.#container {_x000D_
border: 2px dashed #444;_x000D_
height: 125px;_x000D_
text-align: justify;_x000D_
-ms-text-justify: distribute-all-lines;_x000D_
text-justify: distribute-all-lines;_x000D_
/* just for demo */_x000D_
min-width: 612px;_x000D_
}_x000D_
_x000D_
.box1,_x000D_
.box2,_x000D_
.box3,_x000D_
.box4 {_x000D_
width: 150px;_x000D_
height: 125px;_x000D_
vertical-align: top;_x000D_
display: inline-block;_x000D_
*display: inline;_x000D_
zoom: 1_x000D_
}_x000D_
_x000D_
.stretch {_x000D_
width: 100%;_x000D_
display: inline-block;_x000D_
font-size: 0;_x000D_
line-height: 0_x000D_
}_x000D_
_x000D_
.box1,_x000D_
.box3 {_x000D_
background: #ccc_x000D_
}_x000D_
_x000D_
.box2,_x000D_
.box4 {_x000D_
background: #0ff_x000D_
}
_x000D_
<div id="container">_x000D_
<div class="box1"></div>_x000D_
<div class="box2"></div>_x000D_
<div class="box3"></div>_x000D_
<div class="box4"></div>_x000D_
<span class="stretch"></span>_x000D_
</div>
_x000D_
The extra span
(.stretch
) can be replaced with :after
.
This still works in all the same browsers as the above solution. :after
doesn't work in IE6/7, but they're using distribute-all-lines
anyway, so it doesn't matter.
See: http://jsfiddle.net/thirtydot/EDp8R/3/
There's a minor downside to :after
: to make the last row work perfectly in Safari, you have to be careful with the whitespace in the HTML.
Specifically, this doesn't work:
<div id="container">
..
<div class="box3"></div>
<div class="box4"></div>
</div>
And this does:
<div id="container">
..
<div class="box3"></div>
<div class="box4"></div></div>
You can use this for any arbitrary number of child div
s without adding a boxN
class to each one by changing
.box1, .box2, .box3, .box4 { ...
to
#container > div { ...
This selects any div that is the first child of the #container
div, and no others below it. To generalize the background colors, you can use the CSS3 nth-order selector, although it's only supported in IE9+ and other modern browsers:
.box1, .box3 { ...
becomes:
#container > div:nth-child(odd) { ...
See here for a jsfiddle example.
The quickest fix for me was doing the following:
cd /usr/local
git reset --hard FETCH_HEAD
Then I retried brew install imagemagick
and it correctly pulled the package from the new mirror, instead of adamv.
If that does not work, ensure that /Library/Caches/Homebrew
does not contain any imagemagick files or folders. Delete them if it does.
no... Once u have executed the statement anotherList.addAll(list) and after that if u change some list data it does not carry to another list
Please note there are two very nice color schemes by default in IDEA 10.
The one that is included is named Railcasts. It is included with the Ruby plugin (free official plugin, install via plugin manager).
This is short and sweet method to add a month to a date using dateutil's relativedelta
.
from datetime import datetime
from dateutil.relativedelta import relativedelta
date_after_month = datetime.today()+ relativedelta(months=1)
print 'Today: ',datetime.today().strftime('%d/%m/%Y')
print 'After Month:', date_after_month.strftime('%d/%m/%Y')
Output:
Today: 01/03/2013
After Month: 01/04/2013
A word of warning: relativedelta(months=1)
and relativedelta(month=1)
have different meanings. Passing month=1
will replace the month in original date to January whereas passing months=1
will add one month to original date.
Note: this will requires python-dateutil
. To install it you need to run in Linux terminal.
sudo apt-get update && sudo apt-get install python-dateutil
Explanation : Add month value in python
Absolutely Yes, Python by itself don't have any static data member explicitly, but We can have by doing so
class A:
counter =0
def callme (self):
A.counter +=1
def getcount (self):
return self.counter
>>> x=A()
>>> y=A()
>>> print(x.getcount())
>>> print(y.getcount())
>>> x.callme()
>>> print(x.getcount())
>>> print(y.getcount())
output
0
0
1
1
explanation
here object (x) alone increment the counter variable
from 0 to 1 by not object y. But result it as "static counter"
You can use the version in Windows SDK but sometimes it might not be the same version of the .NET Framework your using, getting you the following error:
Microsoft (R) .NET Global Assembly Cache Utility. Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved. Failure adding assembly to the cache: This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
In .NET 4.0 you'll need to search inside Microsoft SDK v8.0A, e.g.: C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools (in my case I only have the 32 bit version installed by Visual Studio 2012).
It is working for me..
$show = mysql_query("SELECT data FROM wp_10_options WHERE
option_name='homepage' limit 1"); $row = mysql_fetch_assoc($show);
echo $row['data'];
For SQL Server 2008, I would imagine the procedure is similar...?
using System.IO;
...
foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml"))
{
string contents = File.ReadAllText(file);
}
Note the above uses a .NET 4.0 feature; in previous versions replace EnumerateFiles
with GetFiles
). Also, replace File.ReadAllText
with your preferred way of reading xml files - perhaps XDocument
, XmlDocument
or an XmlReader
.
You can use the accept attribute along with the . It doesn't work in IE and Safari.
Depending on your project scale and extensibility, you could use Struts. Struts offers two ways to limit the uploaded file type, declaratively and programmatically.
For more information: http://struts.apache.org/2.0.14/docs/file-upload.html#FileUpload-FileTypes
source myscript.sh
is also feasible.
Description for linux command source
:
source is a Unix command that evaluates the file following the command,
as a list of commands, executed in the current context
LIST="some string with a substring you want to match"
SOURCE="substring"
if echo "$LIST" | grep -q "$SOURCE"; then
echo "matched";
else
echo "no match";
fi
If your application is hosted on IIS/IIS Express try the following:
c.SwaggerEndpoint("../swagger/v1/swagger.json", "MyAPI V1");
In order to make more concise you can declare constructor parameters as public
which automatically create properties with same names and these properties are available via this
:
export class Environment {
constructor(public id:number, public name:string) {}
getProperties() {
return `${this.id} : ${this.name}`;
}
}
let serverEnv = new Environment(80, 'port');
console.log(serverEnv);
---result---
// Environment { id: 80, name: 'port' }
The Range object has both width and height properties, which are measured in points.
for file in *.dat ; do mv $file ${file//ABC/XYZ} ; done
No rename
or sed
needed. Just bash parameter expansion.
It says "POST not supported", so the request is not calling your servlet. If I were you, I will issue a GET (e.g. access using a browser) to the exact URL you are issuing your POST request, and see what you get. I bet you'll see something unexpected.
Set the project containing your DbContext
class as the startup project.
I was getting this error while calling enable-migrations
.
Even if in the Package Manager Console
I selected the right Default project
, it was still looking at the web.config file of that startup project, where the connection string wasn't present.
This happened to me on Ubuntu 18.04.2 after I tried to install Python3.7 from the deadsnakes repo.
Solution was this
1) cd /usr/lib/python3/dist-packages/
2) sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so
why make is sooooo hard people when it can be soooo easy :)
//here is the pull from the form
$your_form_text = $_POST['your_form_text'];
//line 1 fixes the line breaks - line 2 the slashes
$your_form_text = nl2br($your_form_text);
$your_form_text = stripslashes($your_form_text);
//email away
$message = "Comments: $your_form_text";
mail("[email protected]", "Website Form Submission", $message, $headers);
you will obviously need headers and likely have more fields, but this is your textarea take care of
The answer to your question is yes and no, depending on what you mean by "inline function". If you're using the term like it's used in C++ development then the answer is no, you can't do that - even a lambda expression is a function call. While it's true that you can define inline lambda expressions to replace function declarations in C#, the compiler still ends up creating an anonymous function.
Here's some really simple code I used to test this (VS2015):
static void Main(string[] args)
{
Func<int, int> incr = a => a + 1;
Console.WriteLine($"P1 = {incr(5)}");
}
What does the compiler generate? I used a nifty tool called ILSpy that shows the actual IL assembly generated. Have a look (I've omitted a lot of class setup stuff)
This is the Main function:
IL_001f: stloc.0
IL_0020: ldstr "P1 = {0}"
IL_0025: ldloc.0
IL_0026: ldc.i4.5
IL_0027: callvirt instance !1 class [mscorlib]System.Func`2<int32, int32>::Invoke(!0)
IL_002c: box [mscorlib]System.Int32
IL_0031: call string [mscorlib]System.String::Format(string, object)
IL_0036: call void [mscorlib]System.Console::WriteLine(string)
IL_003b: ret
See those lines IL_0026 and IL_0027? Those two instructions load the number 5 and call a function. Then IL_0031 and IL_0036 format and print the result.
And here's the function called:
.method assembly hidebysig
instance int32 '<Main>b__0_0' (
int32 a
) cil managed
{
// Method begins at RVA 0x20ac
// Code size 4 (0x4)
.maxstack 8
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
} // end of method '<>c'::'<Main>b__0_0'
It's a really short function, but it is a function.
Is this worth any effort to optimize? Nah. Maybe if you're calling it thousands of times a second, but if performance is that important then you should consider calling native code written in C/C++ to do the work.
In my experience readability and maintainability are almost always more important than optimizing for a few microseconds gain in speed. Use functions to make your code readable and to control variable scoping and don't worry about performance.
"Premature optimization is the root of all evil (or at least most of it) in programming." -- Donald Knuth
"A program that doesn't run correctly doesn't need to run fast" -- Me
In SQLDeveloper browse Tools --> Preferences
, as shown in below image.
In the Preferences options expand Database --> select Advanced --> under "Tnsnames Directory" --> Browse the directory
where tnsnames.ora present.
Then click on Ok.
as shown in below diagram.
You have Done!
Now you can connect via the TNSnames options.
function chkicon(num,allsize) {
var flagicon = document.getElementById("flagicon"+num).value;
if(flagicon=="plus"){
//alert("P== "+flagicon);
for (var i = 0; i < allsize; i++) {
if(document.getElementById("flagicon"+i).value !=""){
document.getElementById("flagicon"+i).value = "plus";
document.images["pic"+i].src = "../images/plus.gif";
}
}
document.images["pic"+num].src = "../images/minus.gif";
document.getElementById("flagicon"+num).value = "minus";
}else if(flagicon=="minus"){
//alert("M== "+flagicon);
document.images["pic"+num].src = "../images/plus.gif";
document.getElementById("flagicon"+num).value = "plus";
}else{
for (var i = 0; i < allsize; i++) {
if(document.getElementById("flagicon"+i).value !=""){
document.getElementById("flagicon"+i).value = "plus";
document.images["pic"+i].src = "../images/plus.gif";
}
}
}
}
For me - using Spring Boot with MongoDB, the following was the Problem:
In my POM.xml I had:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-starter-data-mongodb</artifactId>
</dependency>
but I needed the following:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
(Short: Add "spring-boot-..." instead of only "spring-...")
@EmailAddress varchar(200),
@NickName varchar(100),
@Password varchar(150),
@Sex varchar(50),
@Age int,
@EmailUpdates int,
@UserId int OUTPUT
DECLARE @AA INT
SET @AA=(SELECT COUNT(UserId) FROM RegUsers WHERE EmailAddress = @EmailAddress)
IF @AA> 0
BEGIN
SET @UserId = 0
END
ELSE
BEGIN
INSERT INTO RegUsers (EmailAddress,NickName,PassWord,Sex,Age,EmailUpdates) VALUES (@EmailAddress,@NickName,@Password,@Sex,@Age,@EmailUpdates)
SELECT SCOPE_IDENTITY()
END
END
If in addition you want to pipe the output to a separate file, you can do:
On a Sun JVM:
-Xloggc:C:\whereever\jvm.log -verbose:gc -XX:+PrintGCDateStamps
ON an IBM JVM:
-Xverbosegclog:C:\whereever\jvm.log
In Django 1.8, this is how I did mine.
from django.views.generic.base import RedirectView
url(r'^$', views.comingSoon, name='homepage'),
# whatever urls you might have in here
# make sure the 'catch-all' url is placed last
url(r'^.*$', RedirectView.as_view(pattern_name='homepage', permanent=False))
Instead of using url
, you can use the pattern_name
, which is a bit un-DRY, and will ensure you change your url, you don't have to change the redirect too.
$keys = array_keys($arr);
$keys = rsort($keys);
print $keys[0];
should print "10"
@JorgeGRC Thanks for your answer. One thing though, the "maybe" part is very important. If you do have parameter(s), you must include it/them on your template as well and be sure to specify your locals e.g. updateFn({msg: "Directive Args"}
.
There are several ways to do it This is the better way
res.download('/report-12345.pdf')
or in your case this might be
app.get('/download', function(req, res){
const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;
res.download(file); // Set disposition and send it.
});
Here's my solution.
I noticed that when I specify the listbox's rowsource via the properties window in the VBE, the headers pop up no problem. Its only when we try define the rowsource through VBA code that the headers get lost.
So I first went a defined the listboxes rowsource as a named range in the VBE for via the properties window, then I can reset the rowsource in VBA code after that. The headers still show up every time.
I am using this in combination with an advanced filter macro from a listobject, which then creates another (filtered) listobject on which the rowsource is based.
This worked for me
For simple structures you can either use memcpy
like you do, or just assign from one to the other:
RTCclk = RTCclkBuffert;
The compiler will create code to copy the structure for you.
An important note about the copying: It's a shallow copy, just like with memcpy
. That means if you have e.g. a structure containing pointers, it's only the actual pointers that will be copied and not what they point to, so after the copy you will have two pointers pointing to the same memory.
In fact, most compilers emit the same code for both functions calls, because references are generally implemented using pointers.
Following this logic, when an argument of (non-const) reference type is used in the function body, the generated code will just silently operate on the address of the argument and it will dereference it. In addition, when a call to such a function is encountered, the compiler will generate code that passes the address of the arguments instead of copying their value.
Basically, references and pointers are not very different from an implementation point of view, the main (and very important) difference is in the philosophy: a reference is the object itself, just with a different name.
References have a couple more advantages compared to pointers (e. g. they can't be NULL
, so they are safer to use). Consequently, if you can use C++, then passing by reference is generally considered more elegant and it should be preferred. However, in C, there's no passing by reference, so if you want to write C code (or, horribile dictu, code that compiles with both a C and a C++ compiler, albeit that's not a good idea), you'll have to restrict yourself to using pointers.
I solved this problem with using the following steps:
File -> Import
Click General then select Existing Projects into Workspace
Click Next
Browse the directory of the project
Click Finish!
It worked for me
The way Python indexing works is that it starts at 0, so the first number of your list would be [0]. You would have to print[52], as the starting index is 0 and
therefore line 53 is [52]
.
Subtract 1 from the value and you should be fine. :)
It is very complex to invoke Win32 from C#.
You should use the tool Handle.exe.
After that your C# code have to be the following:
string fileName = @"c:\aaa.doc";//Path to locked file
Process tool = new Process();
tool.StartInfo.FileName = "handle.exe";
tool.StartInfo.Arguments = fileName+" /accepteula";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();
string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach(Match match in Regex.Matches(outputTool, matchPattern))
{
Process.GetProcessById(int.Parse(match.Value)).Kill();
}
theView.post(new Runnable() {
String str;
@Override
public void run() {
par.Log(str);
}
public Runnable init(String pstr) {
this.str=pstr;
return(this);
}
}.init(str));
Create init function that returns object itself and initialize parameters with it.
Sounds like you're trying to execute the PHP code directly in your shell. Your shell doesn't speak PHP, so it interprets your PHP code as though it's in your shell's native language, as though you had literally run <?php
at the command line.
Shell scripts usually start with a "shebang" line that tells the shell what program to use to interpret the file. Begin your file like this:
#!/usr/bin/env php
<?php
//Connection
function connection () {
Besides that, the string you're passing to exec
doesn't make any sense. It starts with a slash all by itself, it uses too many periods in the path, and it has a stray right parenthesis.
Copy the contents of the command string and paste them at your command line. If it doesn't run there, then exec
probably won't be able to run it, either.
Another option is to change the command you execute. Instead of running the script directly, run php
and pass your script as an argument. Then you shouldn't need the shebang line.
exec('php name.php');
See .offset()
here in the jQuery doc. It gives the position relative to the document, not to the parent. You perhaps have .offset()
and .position()
confused. If you want the position in the window instead of the position in the document, you can subtract off the .scrollTop()
and .scrollLeft()
values to account for the scrolled position.
Here's an excerpt from the doc:
The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.
To combine these:
var offset = $("selector").offset();
var posY = offset.top - $(window).scrollTop();
var posX = offset.left - $(window).scrollLeft();
You can try it here (scroll to see the numbers change): http://jsfiddle.net/jfriend00/hxRPQ/
Use this for example:
cv2.namedWindow('finalImg', cv2.WINDOW_NORMAL)
cv2.imshow("finalImg",finalImg)
$ bundle update json
$ bundle install
Direct quote from MSDN: <xsd:import> Element, Remarks section
The difference between the include element and the import element is that import element allows references to schema components from schema documents with different target namespaces and the include element adds the schema components from other schema documents that have the same target namespace (or no specified target namespace) to the containing schema. In short, the import element allows you to use schema components from any schema; the include element allows you to add all the components of an included schema to the containing schema.
You are trying to execute an asynchronous function
in a synchronous way, which is unfortunately not possible in Javascript
.
As you guessed correctly, the roomId=results
.... is executed when the loading from the DB completes, which is done asynchronously, so AFTER the resto of your code is completed.
Look at this article, it talks about .insert and not .find
, but the idea is the same : http://metaduck.com/01-asynchronous-iteration-patterns.html
For completeness, though this probably would not work well given your particular setup (external program + Windows), one can also acquire Scipy hassle-free as part of the (large) SageMath download.
(This is already answered in comments, but since it lacks an actual answer, I'm writing this.)
This problem arises in newer versions of Visual C++ (the older versions usually just silently linked the program and it would crash and burn at run time.) It means that some of the libraries you are linking with your program (or even some of the source files inside your program itself) are using different versions of the CRT (the C RunTime library.)
To correct this error, you need to go into your Project Properties
(and/or those of the libraries you are using,) then into C/C++
, then Code Generation
, and check the value of Runtime Library
; this should be exactly the same for all the files and libraries you are linking together. (The rules are a little more relaxed for linking with DLLs, but I'm not going to go into the "why" and into more details here.)
There are currently four options for this setting:
Your particular problem seems to stem from you linking a library built with "Multithreaded Debug" (i.e. static multithreaded debug CRT) against a program that is being built using the "Multithreaded Debug DLL" setting (i.e. dynamic multithreaded debug CRT.) You should change this setting either in the library, or in your program. For now, I suggest changing this in your program.
Note that since Visual Studio projects use different sets of project settings for debug and release builds (and 32/64-bit builds) you should make sure the settings match in all of these project configurations.
For (some) more information, you can see these (linked from a comment above):
UPDATE: (This is in response to a comment that asks for the reason that this much care must be taken.)
If two pieces of code that we are linking together are themselves linking against and using the standard library, then the standard library must be the same for both of them, unless great care is taken about how our two code pieces interact and pass around data. Generally, I would say that for almost all situations just use the exact same version of the standard library runtime (regarding debug/release, threads, and obviously the version of Visual C++, among other things like iterator debugging, etc.)
The most important part of the problem is this: having the same idea about the size of objects on either side of a function call.
Consider for example that the above two pieces of code are called A
and B
. A is compiled against one version of the standard library, and B against another. In A's view, some random object that a standard function returns to it (e.g. a block of memory or an iterator or a FILE
object or whatever) has some specific size and layout (remember that structure layout is determined and fixed at compile time in C/C++.) For any of several reasons, B's idea of the size/layout of the same objects is different (it can be because of additional debug information, natural evolution of data structures over time, etc.)
Now, if A calls the standard library and gets an object back, then passes that object to B, and B touches that object in any way, chances are that B will mess that object up (e.g. write the wrong field, or past the end of it, etc.)
The above isn't the only kind of problems that can happen. Internal global or static objects in the standard library can cause problems too. And there are more obscure classes of problems as well.
All this gets weirder in some aspects when using DLLs (dynamic runtime library) instead of libs (static runtime library.)
This situation can apply to any library used by two pieces of code that work together, but the standard library gets used by most (if not almost all) programs, and that increases the chances of clash.
What I've described is obviously a watered down and simplified version of the actual mess that awaits you if you mix library versions. I hope that it gives you an idea of why you shouldn't do it!
You can also define case insensitive during the pattern compile:
pattern = re.compile('FIle:/+(.*)', re.IGNORECASE)
If you use ui-router you can use (on run)
$rootScope.$on("$stateChangeSuccess", function (event, currentState, previousState) {
$window.scrollTo(0, 0);
});
Double the backslashes in the path, like this:
driver.findElement(browsebutton).sendKeys("C:\\Users\\Desktop\\Training\\Training.jpg");
Here is how it works for me with no Servlet use.
Let's say I am trying to access web.xml in project/WebContent/WEB-INF/web.xml
In project property Source-tab add source folder by pointing to the parent container for WEB-INF folder (in my case WebContent )
Now let's use class loader:
InputStream inStream = class.getClass().getClassLoader().getResourceAsStream("Web-INF/web.xml")
Write the src tag for calling the js file as
<script type='text/javascript' src='../Users/myUserName/Desktop/myPage.js'></script>
This should work.
With the upcoming Xcode 7 it's now possible to install apps on your devices without an apple developer license, so now it is possible to skip the app store and you don't have to jailbreak your device.
Now everyone can get their app on their Apple device.
Xcode 7 and Swift now make it easier for everyone to build apps and run them directly on their Apple devices. Simply sign in with your Apple ID, and turn your idea into an app that you can touch on your iPad, iPhone, or Apple Watch. Download Xcode 7 beta and try it yourself today. Program membership is not required.
Quoted from: https://developer.apple.com/xcode/
Update:
XCode 7 is now released:
Free On-Device Development Now everyone can run and test their own app on a device—for free. You can run and debug your own creations on a Mac, iPhone, iPad, iPod touch, or Apple Watch without any fees, and no programs to join. All you need to do is enter your free Apple ID into Xcode. You can even use the same Apple ID you already use for the App Store or iTunes. Once you’ve perfected your app the Apple Developer Program can help you get it on the App Store.
See Launching Your App on Devices for detailed information about installing and running on devices.
Another issue you have to take care of: If your generated file names are not the default id_rsa
and id_rsa.pub
.
You have to create the .ssh/config file and define manually which id file you are going to use with the connection.
An example is here:
Host remote_host_name
HostName 172.xx.xx.xx
User my_user
IdentityFile /home/my_user/.ssh/my_user_custom
If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:
Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:
In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.
Source: http://blogs.msdn.com/b/ianhu/archive/2014/12/16/gpu-usage-for-directx-in-visual-studio.aspx
Yes, when you know you're dealing with objects, it's perfectly possible (and in many cases advisable) to use an explicit method call. However, sometimes you deal with code that expects callable objects - typically functions, but thanks to __call__
you can build more complex objects, with instance data and more methods to delegate repetitive tasks, etc. that are still callable.
Also, sometimes you're using both objects for complex tasks (where it makes sense to write a dedicated class) and objects for simple tasks (that already exist in functions, or are more easily written as functions). To have a common interface, you either have to write tiny classes wrapping those functions with the expected interface, or you keep the functions functions and make the more complex objects callable. Let's take threads as example. The Thread
objects from the standard libary module threading
want a callable as target
argument (i.e. as action to be done in the new thread). With a callable object, you are not restricted to functions, you can pass other objects as well, such as a relatively complex worker that gets tasks to do from other threads and executes them sequentially:
class Worker(object):
def __init__(self, *args, **kwargs):
self.queue = queue.Queue()
self.args = args
self.kwargs = kwargs
def add_task(self, task):
self.queue.put(task)
def __call__(self):
while True:
next_action = self.queue.get()
success = next_action(*self.args, **self.kwargs)
if not success:
self.add_task(next_action)
This is just an example off the top of my head, but I think it is already complex enough to warrant the class. Doing this only with functions is hard, at least it requires returning two functions and that's slowly getting complex. One could rename __call__
to something else and pass a bound method, but that makes the code creating the thread slightly less obvious, and doesn't add any value.
<span>
<img id="my_image" src="#" />
</span>
<span class="spanloader">
<span>set Loading Image Image</span>
</span>
<input type="button" id="btnnext" value="Next" />
<script type="text/javascript">
$('#btnnext').click(function () {
$(".spanloader").hide();
$("#my_image").attr("src", "1.jpg");
});
</script>
Blat:
blat -to [email protected] -server smtp.example.com -f [email protected] -subject "subject" -body "body"
You can use $locationChangeStart
event to store the previous value in $rootScope
or in a service. When you come back, just initialize all previously stored values. Here is a quick demo using $rootScope
.
var app = angular.module("myApp", ["ngRoute"]);_x000D_
app.controller("tab1Ctrl", function($scope, $rootScope) {_x000D_
if ($rootScope.savedScopes) {_x000D_
for (key in $rootScope.savedScopes) {_x000D_
$scope[key] = $rootScope.savedScopes[key];_x000D_
}_x000D_
}_x000D_
$scope.$on('$locationChangeStart', function(event, next, current) {_x000D_
$rootScope.savedScopes = {_x000D_
name: $scope.name,_x000D_
age: $scope.age_x000D_
};_x000D_
});_x000D_
});_x000D_
app.controller("tab2Ctrl", function($scope) {_x000D_
$scope.language = "English";_x000D_
});_x000D_
app.config(function($routeProvider) {_x000D_
$routeProvider_x000D_
.when("/", {_x000D_
template: "<h2>Tab1 content</h2>Name: <input ng-model='name'/><br/><br/>Age: <input type='number' ng-model='age' /><h4 style='color: red'>Fill the details and click on Tab2</h4>",_x000D_
controller: "tab1Ctrl"_x000D_
})_x000D_
.when("/tab2", {_x000D_
template: "<h2>Tab2 content</h2> My language: {{language}}<h4 style='color: red'>Now go back to Tab1</h4>",_x000D_
controller: "tab2Ctrl"_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>_x000D_
<body ng-app="myApp">_x000D_
<a href="#/!">Tab1</a>_x000D_
<a href="#!tab2">Tab2</a>_x000D_
<div ng-view></div>_x000D_
</body>_x000D_
</html>
_x000D_
Store a reference to the meter instance as a member in Production:
public class Production {
//The other members, properties etc...
private Meter m;
Production(Meter m) {
this.m = m;
}
}
And then in the Meter-class:
public class Meter
{
private int _powerRating = 0;
private Production _production;
public Meter()
{
_production = new Production(this);
}
}
Also note that you need to implement an accessor method/property so that the Production class can actually access the powerRating member of the Meter class.
You declare a function pointer variable for the given signature of your functions like this:
bool (* fnptr)();
you can assign it one of your functions:
fnptr = A;
and you can call it:
bool result = fnptr();
You might consider using typedefs to define a type for every distinct function signature you need. This will make the code easier to read and to maintain. i.e. for the signature of functions returning bool with no arguments this could be:
typdef bool (* BoolFn)();
and then you can use like this to declare the function pointer variable for this type:
BoolFn fnptr;
You can use OnClientClick event to call a JavaScript function:
<asp:Button ID="Button1" runat="server" Text="Button" onclientclick='redirect()' />
JavaScript code:
function redirect() {
location.href = 'page.aspx';
}
But i think the best would be to style a hyperlink with css.
Example :
.button {
display: block;
height: 25px;
background: #f1f1f1;
padding: 10px;
text-align: center;
border-radius: 5px;
border: 1px solid #e1e1e2;
color: #000;
font-weight: bold;
}
Have you looked at python-graph? I haven't used it myself, but the project page looks promising.
Or try to check your mainActivity.xml you make sure that this one
xmlns:app="http://schemas.android.com/apk/res-auto"here
is included
if u want to have multiple selection on select row..
import React from 'react';
import ReactTable from 'react-table';
import 'react-table/react-table.css';
import { ReactTableDefaults } from 'react-table';
import matchSorter from 'match-sorter';
class ThreatReportTable extends React.Component{
constructor(props){
super(props);
this.state = {
selected: [],
row: []
}
}
render(){
const columns = this.props.label;
const data = this.props.data;
Object.assign(ReactTableDefaults, {
defaultPageSize: 10,
pageText: false,
previousText: '<',
nextText: '>',
showPageJump: false,
showPagination: true,
defaultSortMethod: (a, b, desc) => {
return b - a;
},
})
return(
<ReactTable className='threatReportTable'
data= {data}
columns={columns}
getTrProps={(state, rowInfo, column) => {
return {
onClick: (e) => {
var a = this.state.selected.indexOf(rowInfo.index);
if (a == -1) {
// this.setState({selected: array.concat(this.state.selected, [rowInfo.index])});
this.setState({selected: [...this.state.selected, rowInfo.index]});
// Pass props to the React component
}
var array = this.state.selected;
if(a != -1){
array.splice(a, 1);
this.setState({selected: array});
}
},
// #393740 - Lighter, selected row
// #302f36 - Darker, not selected row
style: {background: this.state.selected.indexOf(rowInfo.index) != -1 ? '#393740': '#302f36'},
}
}}
noDataText = "No available threats"
/>
)
}
}
export default ThreatReportTable;
you can add class in anchor tag also like below
.a_class {font-size: 100px}
A solution that is viable for both Linux and Windows is to just get used to using console ffmpeg in your code. I stack up threads, write a simple thread controller class, then you can easily make use of what ever functionality of ffmpeg you want to use.
As an example, this contains sections use ffmpeg to create a thumbnail from a time that I specify.
In the thread controller you have something like
List<ThrdFfmpeg> threads = new List<ThrdFfmpeg>();
Which is the list of threads that you are running, I make use of a timer to Pole these threads, you can also set up an event if Pole'ing is not suitable for your application. In this case thw class Thrdffmpeg contains,
public class ThrdFfmpeg
{
public FfmpegStuff ffm { get; set; }
public Thread thrd { get; set; }
}
FFmpegStuff contains the various ffmpeg functionality, thrd is obviously the thread.
A property in FfmpegStuff is the class FilesToProcess, which is used to pass information to the called process, and receive information once the thread has stopped.
public class FileToProcess
{
public int videoID { get; set; }
public string fname { get; set; }
public int durationSeconds { get; set; }
public List<string> imgFiles { get; set; }
}
VideoID (I use a database) tells the threaded process which video to use taken from the database. fname is used in other parts of my functions that use FilesToProcess, but not used here. durationSeconds - is filled in by the threads that just collect video duration. imgFiles is used to return any thumbnails that were created.
I do not want to get bogged down in my code when the purpose of this is to encourage the use of ffmpeg in easily controlled threads.
Now we have our pieces we can add to our threads list, so in our controller we do something like,
AddThread()
{
ThrdFfmpeg thrd;
FileToProcess ftp;
foreach(FileToProcess ff in `dbhelper.GetFileNames(txtCategory.Text))`
{
//make a thread for each
ftp = new FileToProcess();
ftp = ff;
ftp.imgFiles = new List<string>();
thrd = new ThrdFfmpeg();
thrd.ffm = new FfmpegStuff();
thrd.ffm.filetoprocess = ftp;
thrd.thrd = new `System.Threading.Thread(thrd.ffm.CollectVideoLength);`
threads.Add(thrd);
}
if(timerNotStarted)
StartThreadTimer();
}
Now Pole'ing our threads becomes a simple task,
private void timerThreads_Tick(object sender, EventArgs e)
{
int runningCount = 0;
int finishedThreads = 0;
foreach(ThrdFfmpeg thrd in threads)
{
switch (thrd.thrd.ThreadState)
{
case System.Threading.ThreadState.Running:
++runningCount;
//Note that you can still view data progress here,
//but remember that you must use your safety checks
//here more than anywhere else in your code, make sure the data
//is readable and of the right sort, before you read it.
break;
case System.Threading.ThreadState.StopRequested:
break;
case System.Threading.ThreadState.SuspendRequested:
break;
case System.Threading.ThreadState.Background:
break;
case System.Threading.ThreadState.Unstarted:
//Any threads that have been added but not yet started, start now
thrd.thrd.Start();
++runningCount;
break;
case System.Threading.ThreadState.Stopped:
++finishedThreads;
//You can now safely read the results, in this case the
//data contained in FilesToProcess
//Such as
ThumbnailsReadyEvent( thrd.ffm );
break;
case System.Threading.ThreadState.WaitSleepJoin:
break;
case System.Threading.ThreadState.Suspended:
break;
case System.Threading.ThreadState.AbortRequested:
break;
case System.Threading.ThreadState.Aborted:
break;
default:
break;
}
}
if(flash)
{//just a simple indicator so that I can see
//that at least one thread is still running
lbThreadStatus.BackColor = Color.White;
flash = false;
}
else
{
lbThreadStatus.BackColor = this.BackColor;
flash = true;
}
if(finishedThreads >= threads.Count())
{
StopThreadTimer();
ShowSample();
MakeJoinedThumb();
}
}
Putting your own events onto into the controller class works well, but in video work, when my own code is not actually doing any of the video file processing, poling then invoking an event in the controlling class works just as well.
Using this method I have slowly built up just about every video and stills function I think I will ever use, all contained in the one class, and that class as a text file is useable on the Lunux and Windows version, with just a small number of pre-process directives.
The easiest way would be to use the readme.html
file that comes with every WordPress installation (unless you deleted it).
http://example.com/readme.html
Note: it looks like the readme.html
file no longer outputs the current WordPress version. So, there is no way, for now, to see the current WordPress version without logging into the dashboard.
The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('input[type=checkbox]').change(function () {
$('#test > tbody tr').each(function () {
if ($('input[type=checkbox]').is(':checked')) {
$('#btnexcellSelect').removeAttr('disabled');
} else {
$('#btnexcellSelect').attr('disabled', 'disabled');
}
if ($(this).is(':checked')){
console.log( $(this).attr('id'));
}else{
console.log($(this).attr('id'));
}
});
});
Here is demo in JSFiddle.
Here are a few points:
You could consider upgrading to HttpClient 4 (generally speaking, if you can, I don't think version 3 is still actively supported).
A 500 status code is a server error, so it might be useful to see what the server says (any clue in the response body you're printing?). Although it might be caused by your client, the server shouldn't fail this way (a 4xx error code would be more appropriate if the request is incorrect).
I think setDoAuthentication(true)
is the default (not sure). What could be useful to try is pre-emptive authentication works better:
client.getParams().setAuthenticationPreemptive(true);
Otherwise, the main difference between curl -d ""
and what you're doing in Java is that, in addition to Content-Length: 0
, curl also sends Content-Type: application/x-www-form-urlencoded
. Note that in terms of design, you should probably send an entity with your POST
request anyway.
'%.3f'%(1324343032.324325235)
It's OK just in this particular case.
Simply change the number a little bit:
1324343032.324725235
And then:
'%.3f'%(1324343032.324725235)
gives you 1324343032.325
Try this instead:
def trun_n_d(n,d):
s=repr(n).split('.')
if (len(s)==1):
return int(s[0])
return float(s[0]+'.'+s[1][:d])
Another option for trun_n_d:
def trun_n_d(n,d):
dp = repr(n).find('.') #dot position
if dp == -1:
return int(n)
return float(repr(n)[:dp+d+1])
Yet another option ( a oneliner one) for trun_n_d [this, assumes 'n' is a str and 'd' is an int]:
def trun_n_d(n,d):
return ( n if not n.find('.')+1 else n[:n.find('.')+d+1] )
trun_n_d gives you the desired output in both, Python 2.7 and Python 3.6
trun_n_d(1324343032.324325235,3) returns 1324343032.324
Likewise, trun_n_d(1324343032.324725235,3) returns 1324343032.324
Note 1 In Python 3.6 (and, probably, in Python 3.x) something like this, works just fine:
def trun_n_d(n,d):
return int(n*10**d)/10**d
But, this way, the rounding ghost is always lurking around.
Note 2 In situations like this, due to python's number internals, like rounding and lack of precision, working with n as a str is way much better than using its int counterpart; you can always cast your number to a float at the end.
You can add an option
tag on top of the others with no value and a prompt like this:
<select>
<option value="">Choose One</option>
<option value ="sydney">Sydney</option>
<option value ="melbourne">Melbourne</option>
<option value ="cromwell">Cromwell</option>
<option value ="queenstown">Queenstown</option>
</select>
Or leave it blank instead of saying Choose one if you want.
I don't believe Windows (as opposed to .NET) provides a direct way to get that.
The only way I know of is to enumerate all the top level windows with EnumWindows()
and then find what process each belongs to GetWindowThreadProcessID()
. This sounds indirect and inefficient, but it's not as bad as you might expect -- in a typical case, you might have a dozen top level windows to walk through...
Starting from C# 2.0, you can use the nullable generic type Nullable, and in C# there is a shorthand notation the type followed by ?
e.g.
private void Example(int? arg1, int? arg2)
{
if(arg1 == null)
{
//do something
}
if(arg2 == null)
{
//do something else
}
}
If you are working from a windows forms application this worked for me
"server=localhost; user id=dbuser; password=password; database=dbname; Use Procedure Bodies=false;"
Just add the "Use Procedure Bodies=false"
at the end of your connection string.
You don't need to convert to Calendar
for this, you can just use getTime()
/setTime()
instead.
getTime()
: Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
setTime(long time)
: Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT. )
There are 1000 milliseconds in a second, and 60 seconds in a minute. Just do the math.
Date now = new Date();
Date oneMinuteInFuture = new Date(now.getTime() + 1000L * 60);
System.out.println(now);
System.out.println(oneMinuteInFuture);
The L
suffix in 1000
signifies that it's a long
literal; these calculations usually overflows int
easily.
To receive the new commits
git fetch
Reset
You can reset the commit for a local branch using git reset
.
To change the commit of a local branch:
git reset origin/master --hard
Be careful though, as the documentation puts it:
Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.
If you want to actually keep whatever changes you've got locally - do a --soft
reset instead. Which will update the commit history for the branch, but not change any files in the working directory (and you can then commit them).
Rebase
You can replay your local commits on top of any other commit/branch using git rebase
:
git rebase -i origin/master
This will invoke rebase in interactive mode where you can choose how to apply each individual commit that isn't in the history you are rebasing on top of.
If the commits you removed (with git push -f
) have already been pulled into the local history, they will be listed as commits that will be reapplied - they would need to be deleted as part of the rebase or they will simply be re-included into the history for the branch - and reappear in the remote history on the next push.
Use the help git command --help
for more details and examples on any of the above (or other) commands.
First, follow the instructions in this question to squash everything to a single commit. Then make a forced push to the remote:
$ git push origin +master
And optionally delete all other branches both locally and remotely:
$ git push origin :<branch>
$ git branch -d <branch>
When you have replace: true
you get the following piece of DOM:
<div ng-controller="Ctrl" class="ng-scope">
<div class="ng-binding">hello</div>
</div>
whereas, with replace: false
you get this:
<div ng-controller="Ctrl" class="ng-scope">
<my-dir>
<div class="ng-binding">hello</div>
</my-dir>
</div>
So the replace
property in directives refer to whether the element to which the directive is being applied (<my-dir>
in that case) should remain (replace: false
) and the directive's template should be appended as its child,
OR
the element to which the directive is being applied should be replaced (replace: true
) by the directive's template.
In both cases the element's (to which the directive is being applied) children will be lost. If you wanted to perserve the element's original content/children you would have to translude it. The following directive would do it:
.directive('myDir', function() {
return {
restrict: 'E',
replace: false,
transclude: true,
template: '<div>{{title}}<div ng-transclude></div></div>'
};
});
In that case if in the directive's template you have an element (or elements) with attribute ng-transclude
, its content will be replaced by the element's (to which the directive is being applied) original content.
See example of translusion http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview
See this to read more about translusion.
DELIMITER //
CREATE TRIGGER contacts_after_insert
AFTER INSERT
ON contacts FOR EACH ROW
BEGIN
DECLARE vUser varchar(50);
-- Find username of person performing the INSERT into table
SELECT USER() INTO vUser;
-- Insert record into audit table
INSERT INTO contacts_audit
( contact_id,
deleted_date,
deleted_by)
VALUES
( NEW.contact_id,
SYSDATE(),
vUser );
END; //
DELIMITER ;
In my case, I opened SQL Server Management Studio and searched for SQLEXPRESS in my Database engine. It had two instances and I selected the correct one.
Using the following two settings does work.
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create
I use:
IF OBJECT_ID('[dbo].[myView]') IS NOT NULL
DROP VIEW [dbo].[myView]
GO
CREATE VIEW [dbo].[myView]
AS
...
Recently I added some utility procedures for this kind of stuff:
CREATE PROCEDURE dbo.DropView
@ASchema VARCHAR(100),
@AView VARCHAR(100)
AS
BEGIN
DECLARE @sql VARCHAR(1000);
IF OBJECT_ID('[' + @ASchema + '].[' + @AView + ']') IS NOT NULL
BEGIN
SET @sql = 'DROP VIEW ' + '[' + @ASchema + '].[' + @AView + '] ';
EXEC(@sql);
END
END
So now I write
EXEC dbo.DropView 'mySchema', 'myView'
GO
CREATE View myView
...
GO
I think it makes my changescripts a bit more readable
For short notes, providing an anchor element with a title attribute creates a "tooltip".
<a title="Note text goes here."><sup>n</sup></a>
Otherwise, for more involved notes, it looks like your best bet is maintaining named links manually.
My solution
jQuery code
$('#my_form_id').on('submit', function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
var msg_error = 'An error has occured. Please try again later.';
var msg_timeout = 'The server is not responding';
var message = '';
var form = $('#my_form_id');
$.ajax({
data: formData,
async: false,
cache: false,
processData: false,
contentType: false,
url: form.attr('action'),
type: form.attr('method'),
error: function(xhr, status, error) {
if (status==="timeout") {
alert(msg_timeout);
} else {
alert(msg_error);
}
},
success: function(response) {
alert(response);
},
timeout: 7000
});
});
<script type="text/javascript">
document.write(document.referrer);
</script>
document.referrer
serves your purpose, but it doesn't work for Internet Explorer versions earlier than IE9.
It will work for other popular browsers, like Chrome, Mozilla, Opera, Safari etc.
This is an old question but it has a high view count, so I think some new information should be added: In the mean time a lot has changed, and you can now also use Microsoft's own .NET Core on linux. It's also available in ARM builds, 32 and 64 bit.
:sp %:h
- directory listing / file-chooser using the current file's directory
(belongs as a comment under rampion's cd
tip, but I don't have commenting-rights yet)
the .data()
method is from jQuery. If you want to use this method you need to include the jQuery library and access the method like this:
function doStuff(item) {
var id = $(item).data('id');
}
I also updated your jsFiffle
UPDATE
with pure angularjs and the jqlite you can achieve the goal like this:
function doStuff(item) {
var id = angular.element(item).data('id');
}
You must not access the element with []
because then you get the pure DOM element without all the jQuery or jqlite extra methods.
In Jupyter Notebook,
SHIFT+ TAB(to move left) and TAB(to move right) movement is perfectly working.
I created a program with hibernate, in which I created two POJO classes, both with an object of each other as data members. When in the main method I tried to save them in the database I also got this error.
This happens because both of the classes are referring each other, hence creating a loop which causes this error.
So, check whether any such kind of relationships exist in your program.
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
Are you missing the 'SET' statement when assigning to your variables in the IF .. ELSE block?
Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.
Let me explain using step-by-step guidance.
First, download the source code from https://github.com/rmtheis/tess-two.
Import all three projects. After importing you will get an error.
To solve the error you have to create a res
folder in the tess-two project
First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"
After doing this in all three project the error should be gone.
Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.
Now you just need to import it into your workspace, but first you have to download android-ndk from this site:
http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file
Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable
Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture
done it
Now open cmd and go to on D:\Android Workspace\tess-two like below
If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:
Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest
Import test-two in this and run OCRTest and run it; you will get the best example of OCR.
PreparedStatement ps=con.prepareStatement("select * from stud");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
Adrian's answer threw "fatal: This operation must be run in a work tree." The following is what worked for us.
git worktree add <new-dir> --no-checkout --detach
cd <new-dir>
git checkout <some-ref> -- <existing-dir>
Notes:
--no-checkout
Do not checkout anything into the new worktree.--detach
Do not create a new branch for the new worktree.<some-ref>
works with any ref, for instance, it works with HEAD~1
.git worktree prune
. one could also convert wchar_t --> wstring --> string --> char
wchar_t wide;
wstring wstrValue;
wstrValue[0] = wide
string strValue;
strValue.assign(wstrValue.begin(), wstrValue.end()); // convert wstring to string
char char_value = strValue[0];
string col1Value = rdr["ColumnOneName"].ToString();
or
string col1Value = rdr[0].ToString();
These are object
s, so you need to either cast them or .ToString()
.
Go to your functions.php
page and delete any spaces immediately above or below your PHP tags.
OIDs basically give you a built-in id for every row, contained in a system column (as opposed to a user-space column). That's handy for tables where you don't have a primary key, have duplicate rows, etc. For example, if you have a table with two identical rows, and you want to delete the oldest of the two, you could do that using the oid column.
OIDs are implemented using 4-byte unsigned integers. They are not unique–OID counter will wrap around at 2³²-1. OID are also used to identify data types (see /usr/include/postgresql/server/catalog/pg_type_d.h
).
In my experience, the feature is generally unused in most postgres-backed applications (probably in part because they're non-standard), and their use is essentially deprecated:
In PostgreSQL 8.1 default_with_oids is off by default; in prior versions of PostgreSQL, it was on by default.
The use of OIDs in user tables is considered deprecated, so most installations should leave this variable disabled. Applications that require OIDs for a particular table should specify WITH OIDS when creating the table. This variable can be enabled for compatibility with old applications that do not follow this behavior.
First of all, the term generator originally was somewhat ill-defined in Python, leading to lots of confusion. You probably mean iterators and iterables (see here). Then in Python there are also generator functions (which return a generator object), generator objects (which are iterators) and generator expressions (which are evaluated to a generator object).
According to the glossary entry for generator it seems that the official terminology is now that generator is short for "generator function". In the past the documentation defined the terms inconsistently, but fortunately this has been fixed.
It might still be a good idea to be precise and avoid the term "generator" without further specification.
I'm in the same spot myself (or was), FWIW I ended up checking out to a samba share on the Linux host and editing that share locally on the Windows machine with notepad++, then I compiled on the Linux box via PuTTY. (We weren't allowed to update the ten y/o versions of the editors on the Linux host and it didn't have Java, so I gave up on X11 forwarding)
Now... I run modern Linux in a VM on my Windows host, add all the tools I want (e.g. CDT) to the VM and then I checkout and build in a chroot jail that closely resembles the RTE.
It's a clunky solution but I thought I'd throw it in to the mix.
I started seeing this problem on Monday 2018-06-04. Our tests run each weekday. It appears that the only thing that changed was the google-chrome version (which had been updated to current) JVM and Selenium were recent versions on Linux box ( Java 1.8.0_151, selenium 3.12.0, google-chrome 67.0.3396.62, and xvfb-run).
Specifically adding the arguments "--no-sandbox" and "--disable-dev-shm-usage" stopped the error.
I'll look into these issues to find more info about the effect, and other questions as in what triggered google-chrome to update.
ChromeOptions options = new ChromeOptions();
...
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
Something along these lines worked for me. Starting with a bit of code taken from Joe, this method modifies the window width to automatically fit a legend to the right of the figure.
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
for i in xrange(5):
ax.plot(x, i * x, label='$y = %ix$'%i)
# Put a legend to the right of the current axis
leg = ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.draw()
# Get the ax dimensions.
box = ax.get_position()
xlocs = (box.x0,box.x1)
ylocs = (box.y0,box.y1)
# Get the figure size in inches and the dpi.
w, h = fig.get_size_inches()
dpi = fig.get_dpi()
# Get the legend size, calculate new window width and change the figure size.
legWidth = leg.get_window_extent().width
winWidthNew = w*dpi+legWidth
fig.set_size_inches(winWidthNew/dpi,h)
# Adjust the window size to fit the figure.
mgr = plt.get_current_fig_manager()
mgr.window.wm_geometry("%ix%i"%(winWidthNew,mgr.window.winfo_height()))
# Rescale the ax to keep its original size.
factor = w*dpi/winWidthNew
x0 = xlocs[0]*factor
x1 = xlocs[1]*factor
width = box.width*factor
ax.set_position([x0,ylocs[0],x1-x0,ylocs[1]-ylocs[0]])
plt.draw()
On OSX, I used the following, and it worked:
sudo chown -R _www:_www {path to wordpress folder}
_www is the user that PHP runs under on the Mac.
(You may also need to chmod some folders too. I had done that first and it didn't fix it. It wasn't until I did the chown command that it worked, so I'm not sure if it was the chown command alone, or a combination of chmod and chown.)
after 5 long years I'm sure not much attention is going to be received for this answer, But still to make all options complete, here is the one with data.table
library(data.table)
setDT(df)[ , list(mean_gr = mean(dt), sum_gr = sum(dt)) , by = .(group)]
# group mean_gr sum_gr
#1: A 61 244
#2: B 66 396
#3: C 68 408
#4: D 61 488
Here is how you can add an icon while creating an exe file from a Python file
open command prompt at the place where Python file exist
type:
pyinstaller --onefile -i"path of icon" path of python file
Example-
pyinstaller --onefile -i"C:\icon\Robot.ico" C:\Users\Jarvis.py
This is the easiest way to add an icon.
I recommend using boost serialization as described by other posters. Here is a good detailed tutorial on how to use it which complements the boost tutorials nicely: http://www.ocoudert.com/blog/2011/07/09/a-practical-guide-to-c-serialization/
Firstly there is an extra }
after every array object
.
Secondly "geodata" is a JSONArray
. So instead of JSONObject geoObject = jObject.getJSONObject("geodata");
you have to get it as JSONArray geoObject = jObject.getJSONArray("geodata");
Once you have the JSONArray
you can fetch each entry in the JSONArray
using geoObject.get(<index>)
.
I am using org.codehaus.jettison.json
.
You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).
You must login to have a valid session before downloading anything below.
*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)
*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.
Xcode 12
12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)
12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)
12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)
Xcode 11
11.7 (Latest as of Sept 02 2020)
11.4.1 (Requires macOS 10.15.2 or later)
11 (Requires macOS 10.14.4 or later)
Xcode 10 (unsupported for iTunes Connect)
Xcode 9
Xcode 8
Xcode 7
Xcode 6
Even Older Versions (unsupported for iTunes Connect)
You might want to run python manage.py collectstatic
after you set DEBUG = False
and ALLOWED_HOSTS = ['127.0.0.1']
in settings.py
. After these two steps my web application ran well in my local server even with DEBUG=False mode.
BTW I have these settings in settings.py
.
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', # what i added
'django.middleware.common.CommonMiddleware', # and so on...
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
I assume maybe whitenoise setting has something to do with collectstatic command.
A tried a slight variation on Luca's answer and it worked for me.
diff file1 file2 | grep ">" | sed 's/^> //g' > diff_file
Note that the searched pattern in sed is a >
followed by a space.
git remote add origin <remote_repo_url>
git push --all origin
If you want to set all of your branches to automatically use this remote repo when you use git pull
, add --set-upstream
to the push:
git push --all --set-upstream origin
For some reason, the above answer did not work for me; I did not return to the command prompt after running it as I expected with the trailing &. Instead, I simply tried with
nohup some_command > nohup2.out&
and it works just as I want it to. Leaving this here in case someone else is in the same situation. Running Bash 4.3.8 for reference.
If it doesn't stop even after unchecking SKIP ALL BREAKPOINTS
, you can add this android.os.debug.waitfordebugger
just before your breakpoint.
If you do this,your app will definitely wait for debugger at that point everytime,even if you are just running your app,which it will only find when your device is connected to eclipse.
After debugging you must remove this line for app to run properly or else android will just keep waiting for the debugger.
env.OrderByDescending(x => x.ReportDate)
If you're using .NET Framework 4.5 then you use use the MimeMapping.GetMimeMapping(string FileName) to get the MIME-Type for your file. This is how I've used it in my action.
return File(Path.Combine(@"c:\path", fileFromDB.FileNameOnDisk), MimeMapping.GetMimeMapping(fileFromDB.FileName), fileFromDB.FileName);
I used the construction of $.each (data [i], function (key, value)
But you must pre-match the names of the selection fields with the names of the form elements. Then, in the loop after "success", autocomplete elements from the "data" array. Did this: autocomplete form with ajax success
According to Oracle integration of OpenJDK & javaFX will be on Q1-2014 ( see roadmap : http://www.oracle.com/technetwork/java/javafx/overview/roadmap-1446331.html ). So, for the 1st question the answer is that you have to wait until then. For the 2nd question there is no other way. So, for now go with java swing or start javaFX and wait
Because default parameters are resolved at compile time, not runtime. So the default values does not belong to the object being called, but to the reference type that it is being called through.
Please try going to the last commit and then do git push origin HEAD:master
.
say you have a dict
with tuples as keys, e.g: labels = {(1,2,0): 'label_1'}
you can modify the elements of the tuple keys as follows:
formatted_labels = {(elem[0],elem[1]):labels[elem] for elem in labels}
Here, we ignore the last elements.
You can hit the key q (for quit) and it should take you to the prompt.
Please see this link.
There is a simple method which you could use with html class attribute and shorthand if/else. No need to make it so complex. Just use following method.
<div class="{{expression == true ? 'class_if_expression_true' : 'class_if_expression_false' }}">Your Content</div>
Happy Coding, Nimantha Perera
The following script will help u to go to a process if that script exist in a specified variable,
cat > waitfor.csh
#!/bin/csh
while !( -e $1 )
sleep 10m
end
ctrl+D
here -e
is for working with files,
$1
is a shell variable,
sleep for 10 minutes
u can execute the script by ./waitfor.csh ./temp ; echo "the file exits"
If you want to put multiple conditions in filter
, you can use &&
and ||
operator.
var product= Object.values(arr_products).filter(x => x.Status==status && x.email==user)
you don't need to specify a "SimpleDateFormat", it's simple: You must do specify the constant "DatatypeConstants.FIELD_UNDEFINED" where you don't want to show
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date());
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED);
This solution will do the trick in Chrome and Opera by setting margin to 0 in a css @page directive. It will not (currently) work for other browsers though...
I tried most of methods mentioned above but they didn't work for me, after some searches I found these points:
-n [number]
del
but if there are thousands or millions of keys it's better to use unlink
because unlink is non-blocking while del is blocking, for more information visit this page unlink vs delkeys
are like del and is blockingso I used this code to delete keys by pattern:
redis-cli -n 2 --scan --pattern '[your pattern]' | xargs redis-cli -n 2 unlink
Other answers sort of hint at it, but the problem may arise from expecting a bytes object. In Python 3, decode is valid when you have an object of class bytes. Running encode before decode may "fix" the problem, but it is a useless pair of operations that suggest the problem us upstream.
I'll throw this out there and then duck. The usual reason to check if a file exists is to avoid an error when attempting to open it. How about using the error handler to deal with that:
Function openFileTest(filePathName As String, ByRef wkBook As Workbook, _
errorHandlingMethod As Long) As Boolean
'Returns True if filePathName is successfully opened,
' False otherwise.
Dim errorNum As Long
'***************************************************************************
' Open the file or determine that it doesn't exist.
On Error Resume Next:
Set wkBook = Workbooks.Open(fileName:=filePathName)
If Err.Number <> 0 Then
errorNum = Err.Number
'Error while attempting to open the file. Maybe it doesn't exist?
If Err.Number = 1004 Then
'***************************************************************************
'File doesn't exist.
'Better clear the error and point to the error handler before moving on.
Err.Clear
On Error GoTo OPENFILETEST_FAIL:
'[Clever code here to cope with non-existant file]
'...
'If the problem could not be resolved, invoke the error handler.
Err.Raise errorNum
Else
'No idea what the error is, but it's not due to a non-existant file
'Invoke the error handler.
Err.Clear
On Error GoTo OPENFILETEST_FAIL:
Err.Raise errorNum
End If
End If
'Either the file was successfully opened or the problem was resolved.
openFileTest = True
Exit Function
OPENFILETEST_FAIL:
errorNum = Err.Number
'Presumabley the problem is not a non-existant file, so it's
'some other error. Not sure what this would be, so...
If errorHandlingMethod < 2 Then
'The easy out is to clear the error, reset to the default error handler,
'and raise the error number again.
'This will immediately cause the code to terminate with VBA's standard
'run time error Message box:
errorNum = Err.Number
Err.Clear
On Error GoTo 0
Err.Raise errorNum
Exit Function
ElseIf errorHandlingMethod = 2 Then
'Easier debugging, generate a more informative message box, then terminate:
MsgBox "" _
& "Error while opening workbook." _
& "PathName: " & filePathName & vbCrLf _
& "Error " & errorNum & ": " & Err.Description & vbCrLf _
, vbExclamation _
, "Failure in function OpenFile(), IO Module"
End
Else
'The calling function is ok with a false result. That is the point
'of returning a boolean, after all.
openFileTest = False
Exit Function
End If
End Function 'openFileTest()
Easy one for me ! I got it few weeks ago :
This goes in getBody()
method, not in getParams()
for a post request.
Here is mine :
@Override
/**
* Returns the raw POST or PUT body to be sent.
*
* @throws AuthFailureError in the event of auth failure
*/
public byte[] getBody() throws AuthFailureError {
// Map<String, String> params = getParams();
Map<String, String> params = new HashMap<String, String>();
params.put("id","1");
params.put("name", "myname");
if (params != null && params.size() > 0) {
return encodeParameters(params, getParamsEncoding());
}
return null;
}
(I assumed you want to POST the params you wrote in your getParams)
I gave the params to the request inside the constructor, but since you are creating the request on the fly, you can hard coded them inside your override of the getBody() method.
This is what my code looks like :
Bundle param = new Bundle();
param.putString(HttpUtils.HTTP_CALL_TAG_KEY, tag);
param.putString(HttpUtils.HTTP_CALL_PATH_KEY, url);
param.putString(HttpUtils.HTTP_CALL_PARAM_KEY, params);
switch (type) {
case RequestType.POST:
param.putInt(HttpUtils.HTTP_CALL_TYPE_KEY, RequestType.POST);
SCMainActivity.mRequestQueue.add(new SCRequestPOST(Method.POST, url, this, tag, receiver, params));
and if you want even more this last string params comes from :
param = JsonUtils.XWWWUrlEncoder.encode(new JSONObject(paramasJObj)).toString();
and the paramasJObj is something like this : {"id"="1","name"="myname"}
the usual JSON string.
try this
open the build.gradle
file
android {
dexOptions {
javaMaxHeapSize = "4g"
}
}
A variation on some of the answers above but this is how I got the value of a specific tag from the user-data script on an instance
REGION=$(curl http://instance-data/latest/meta-data/placement/availability-zone | sed 's/.$//')
INSTANCE_ID=$(curl -s http://instance-data/latest/meta-data/instance-id)
TAG_VALUE=$(aws ec2 describe-tags --region $REGION --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values='<TAG_NAME_HERE>'" | jq -r '.Tags[].Value')