I also was having this error when trying to clone a repository from Github on a Windows Subsystem from Linux console:
fatal: unable to access 'http://github.com/docker/getting-started.git/': server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none
The solution from @VonC on this thread didn't work for me.
The solution from this Fabian Lee's article solved it for me:
openssl s_client -showcerts -servername github.com -connect github.com:443 </dev/null 2>/dev/null | sed -n -e '/BEGIN\ CERTIFICATE/,/END\ CERTIFICATE/ p' > github-com.pem
cat github-com.pem | sudo tee -a /etc/ssl/certs/ca-certificates.crt
From the PHP Manual:
Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
use MySQLi
or PDO
<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');
You should use any()
In [98]: a['Names'].str.contains('Mel').any()
Out[98]: True
In [99]: if a['Names'].str.contains('Mel').any():
....: print "Mel is there"
....:
Mel is there
a['Names'].str.contains('Mel')
gives you a series of bool values
In [100]: a['Names'].str.contains('Mel')
Out[100]:
0 False
1 False
2 False
3 False
4 True
Name: Names, dtype: bool
Alexander Pavlov's answer gets the closest to what you want.
Due to the extensiveness of jQuery's abstraction and functionality, a lot of hoops have to be jumped in order to get to the meat of the event. I have set up this jsFiddle to demonstrate the work.
You were close on this one.
Chrome Dev Tools will pause script execution, and present you with this beautiful entanglement of minified code:
Now, the trick here is to not get carried away pressing the key, and keep an eye out on the screen.
I don't have the exact answer, or explanation as to why jQuery goes through the many layers of abstractions it does - all I can suggest is that it is because of the job it does to abstract away its usage from the browser executing the code.
Here is a jsFiddle with a debug version of jQuery (i.e., not minified). When you look at the code on the first (non-minified) breakpoint, you can see that the code is handling many things:
// ...snip...
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// ...snip...
The reason I think you missed it on your attempt when the "execution pauses and I jump line by line", is because you may have used the "Step Over" function, instead of Step In. Here is a StackOverflow answer explaining the differences.
Finally, the reason why your function is not directly bound to the click event handler is because jQuery returns a function that gets bound. jQuery's function in turn goes through some abstraction layers and checks, and somewhere in there, it executes your function.
In the above query when we are trying to combine two or more tables it is necessary to use joins and specify the alias name for description and date (that means, the table from which you are fetching the description and date values)
SELECT DISTINCT Description, Date as treatmentDate
FROM doothey.Patient P
INNER JOIN doothey.Account A ON P.PatientID = A.PatientID
INNER JOIN doothey.AccountLine AL ON A.AccountNo = AL.AccountNo
INNER JOIN doothey.Item I ON AL.ItemNo = I.ItemNo
WHERE p.FamilyName = 'Stange' AND p.GivenName = 'Jessie';
If you want case-insensitive comparison, use lower
or upper
:
if name.lower() == "jesse":
Here is a better way for doing it. Hope this helps
protected void onPostExecute(String result) {
Log.v(TAG + " result);
if (!result.equals("")) {
// Set up variables for API Call
ArrayList<String> list = new ArrayList<String>();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.get(i).toString());
}//end for
} catch (JSONException e) {
Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
e.printStackTrace();
}
adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText( ListViewData.this, "Position :" + itemPosition + " ListItem : " + itemValue, Toast.LENGTH_LONG).show();
}
});
adapter.notifyDataSetChanged();
...
You can use casting in the select clause like:
SELECT id, name, CAST(hide AS BOOLEAN) FROM table_name;
If you don't want to use the SQL syntax (which you are forced to), then switch to a framework like Entity Framework or Linq-to-SQL where you don't write the SQL statements yourself.
This might not really answer the question, but just in case someone just need to quickly send a string value to a function that require a NSArray parameter.
NSArray *data = @[@"The String Value"];
if you need to send more than just 1 string value, you could also use
NSArray *data = @[@"The String Value", @"Second String", @"Third etc"];
then you can send it to the function like below
theFunction(data);
OK it's 2019 now, and from Java 11 you have a constructor with Charset:
FileWriter?(String fileName, Charset charset)
Unfortunately, we still cannot modify the byte buffer size, and it's set to 8192. (https://www.baeldung.com/java-filewriter)
You were close. Add this code in the UserForm_Initialize()
event handler:
tbxDate.Value = Date
For this example you will need to create your own type, that would be an array. Then you create a bigger array which elements are of type you have just created.
To run my example you will need to fill columns A and B in Sheet1 with some values. Then run test(). It will read first two rows and add the values to the BigArr. Then it will check how many rows of data you have and read them all, from the place it has stopped reading, i.e., 3rd row.
Tested in Excel 2007.
Option Explicit
Private Type SmallArr
Elt() As Variant
End Type
Sub test()
Dim x As Long, max_row As Long, y As Long
'' Define big array as an array of small arrays
Dim BigArr() As SmallArr
y = 2
ReDim Preserve BigArr(0 To y)
For x = 0 To y
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Write what has been read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
'' Get the number of the last not empty row
max_row = Range("A" & Rows.Count).End(xlUp).Row
'' Change the size of the big array
ReDim Preserve BigArr(0 To max_row)
Debug.Print "new size of BigArr with old data = " & UBound(BigArr)
'' Check haven't we lost any data
For x = 0 To y
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
For x = y To max_row
'' We have to change the size of each Elt,
'' because there are some new for,
'' which the size has not been set, yet.
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Check what we have read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
End Sub
It looks like API level 11 has support for what you need. See WebViewClient.shouldInterceptRequest()
.
There are good instructions on the Virtualenv official site. https://pypi.python.org/pypi/virtualenv
Basically what I did, is install pip
with sudo easy_install pip
, then used sudo pip install virtualenv
then created an environment with: virtualenv my_env
(name it what you want), following that I did: virtualenv --distribute my_env
; which installed distribute
and pip
in my virtualenv.
Again, follow the instruction on the virtualenv
page.
Kind of a hassle, coming from Ruby ;P
This is my awesome solution for a div
with a dynamic (percentaged) height.
CSS
.vertical_placer{
background:red;
position:absolute;
height:43%;
width:100%;
display: table;
}
.inner_placer{
display: table-cell;
vertical-align: middle;
text-align:center;
}
.inner_placer svg{
position:relative;
color:#fff;
background:blue;
width:30%;
min-height:20px;
max-height:60px;
height:20%;
}
HTML
<div class="footer">
<div class="vertical_placer">
<div class="inner_placer">
<svg> some Text here</svg>
</div>
</div>
</div>
For at DataFrame one can simply type
head(data, num=10L)
to get the first 10 for example.
For a data.frame one can simply type
head(data, 10)
to get the first 10.
If you're using a UINavigationController
, you can use an extension like this:
extension UINavigationController {
private struct AssociatedKeys {
static var navigationBarBackgroundViewName = "NavigationBarBackground"
}
var navigationBarBackgroundView: UIView? {
get {
return objc_getAssociatedObject(self,
&AssociatedKeys.navigationBarBackgroundViewName) as? UIView
}
set(newValue) {
objc_setAssociatedObject(self,
&AssociatedKeys.navigationBarBackgroundViewName,
newValue,
.OBJC_ASSOCIATION_RETAIN)
}
}
func setNavigationBar(hidden isHidden: Bool, animated: Bool = false) {
if animated {
UIView.animate(withDuration: 0.3) {
self.navigationBarBackgroundView?.isHidden = isHidden
}
} else {
navigationBarBackgroundView?.isHidden = isHidden
}
}
func setNavigationBarBackground(color: UIColor, includingStatusBar: Bool = true, animated: Bool = false) {
navigationBarBackgroundView?.backgroundColor = UIColor.clear
navigationBar.backgroundColor = UIColor.clear
navigationBar.barTintColor = UIColor.clear
let setupOperation = {
if includingStatusBar {
self.navigationBarBackgroundView?.isHidden = false
if self.navigationBarBackgroundView == nil {
self.setupBackgroundView()
}
self.navigationBarBackgroundView?.backgroundColor = color
} else {
self.navigationBarBackgroundView?.isHidden = true
self.navigationBar.backgroundColor = color
}
}
if animated {
UIView.animate(withDuration: 0.3) {
setupOperation()
}
} else {
setupOperation()
}
}
private func setupBackgroundView() {
var frame = navigationBar.frame
frame.origin.y = 0
frame.size.height = 64
navigationBarBackgroundView = UIView(frame: frame)
navigationBarBackgroundView?.translatesAutoresizingMaskIntoConstraints = true
navigationBarBackgroundView?.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
navigationBarBackgroundView?.isUserInteractionEnabled = false
view.insertSubview(navigationBarBackgroundView!, aboveSubview: navigationBar)
}
}
It basically makes the navigation bar background transparent and uses another UIView as the background. You can call the setNavigationBarBackground
method of your navigation controller to set the navigation bar background color together with the status bar.
Keep in mind that you have to then use the setNavigationBar(hidden: Bool, animated: Bool)
method in the extension when you want to hide the navigation bar otherwise the view that was used as the background will still be visible.
The imshow()
function with parameters interpolation='nearest'
and cmap='hot'
should do what you want.
import matplotlib.pyplot as plt
import numpy as np
a = np.random.random((16, 16))
plt.imshow(a, cmap='hot', interpolation='nearest')
plt.show()
You should include the repository where you want to deploy in the distribution management section of the pom.xml
.
Example:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
...
<distributionManagement>
<repository>
<uniqueVersion>false</uniqueVersion>
<id>corp1</id>
<name>Corporate Repository</name>
<url>scp://repo/maven2</url>
<layout>default</layout>
</repository>
...
</distributionManagement>
...
</project>
If you don't mind importing the sklearn
library, I would recommend the method talked on this blog.
import pandas as pd
from sklearn import preprocessing
data = {'score': [234,24,14,27,-74,46,73,-18,59,160]}
cols = data.columns
df = pd.DataFrame(data)
df
min_max_scaler = preprocessing.MinMaxScaler()
np_scaled = min_max_scaler.fit_transform(df)
df_normalized = pd.DataFrame(np_scaled, columns = cols)
df_normalized
The best thing would be to link to the jQuery core is via google.
There are 3 reasons to do it this way,
see:
http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for-you/
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
Your code here.....
});
</script>
It's possible that you're not fetching the Joined Set. Be sure to include the set in your HQL:
public List<Node> getAll() {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("FROM Node as n LEFT JOIN FETCH n.nodeValues LEFT JOIN FETCH n.nodeStats");
return query.list();
}
Where your class has 2 sets like:
public class Node implements Serializable {
@OneToMany(fetch=FetchType.LAZY)
private Set<NodeValue> nodeValues;
@OneToMany(fetch=FetchType.LAZY)
private Set<NodeStat> nodeStats;
}
Basic Steps to Debug a Procedure in Toad
Reference:Toad Debugger
UPDATE: with the compact
command and WiredTiger it looks like the extra disk space will actually be released to the OS.
UPDATE: as of v1.9+ there is a compact
command.
This command will perform a compaction "in-line". It will still need some extra space, but not as much.
MongoDB compresses the files by:
You can do this "compression" by running mongod --repair
or by connecting directly and running db.repairDatabase()
.
In either case you need the space somewhere to copy the files. Now I don't know why you don't have enough space to perform a compress, however, you do have some options if you have another computer with more space.
mongoexport
) and then you can Import that same database (using mongoimport
). This will result in a new database that is more compressed. Now you can stop the original mongod
replace with the new database files and you're good to go.There is not currently a good way to "compact in place" using Mongo. And Mongo can definitely suck up a lot of space.
The best strategy right now for compaction is to run a Master-Slave setup. You can then compact the Slave, let it catch up and switch them over. I know still a little hairy. Maybe the Mongo team will come up with better in place compaction, but I don't think it's high on their list. Drive space is currently assumed to be cheap (and it usually is).
unsigned char c;
for( int i = 7; i >= 0; i-- ) {
printf( "%d", ( c >> i ) & 1 ? 1 : 0 );
}
printf("\n");
Explanation:
With every iteration, the most significant bit is being read from the byte by shifting it and binary comparing with 1.
For example, let's assume that input value is 128, what binary translates to 1000 0000. Shifting it by 7 will give 0000 0001, so it concludes that the most significant bit was 1. 0000 0001 & 1 = 1. That's the first bit to print in the console. Next iterations will result in 0 ... 0.
@JimBastard's accepted answer appears to be dated, I had a look and that mailer lib hasn't been touched in over 7 months, has several bugs listed, and is no longer registered in npm.
nodemailer certainly looks like the best option, however the url provided in other answers on this thread are all 404'ing.
nodemailer claims to support easy plugins into gmail, hotmail, etc. and also has really beautiful documentation.
You can simply delete this folder
/Library/Developer/CommandLineTools
Please note: This is the root /Library, not user's ~/Library).
buildscript {
project.ext {
supportLibVersion = '27.1.1'
compileVersion = 28
minSupportedVersion = 22
}
}
and set dependencies:
implementation "com.android.support:appcompat-v7:$project.supportLibVersion"
WebClient wb = new WebClient();
wb.Headers.Add(HttpRequestHeader.Cookie, "somecookie");
From Comments
How do you format the name and value of the cookie in place of "somecookie" ?
wb.Headers.Add(HttpRequestHeader.Cookie, "cookiename=cookievalue");
For multiple cookies:
wb.Headers.Add(HttpRequestHeader.Cookie,
"cookiename1=cookievalue1;" +
"cookiename2=cookievalue2");
If you got only one column in the range to clean, just add "(1)" to the end. It indicates in wich column of the range Excel will remove the duplicates. Something like:
Sub norepeat()
Range("C8:C16").RemoveDuplicates (1)
End Sub
Regards
You can make it easier in your code (if you're doing this a lot anyway) by using an extension on the DataRow object, like:
static class Extensions
{
public static string GetColumn(this DataRow Row, int Ordinal)
{
return Row.Table.Columns[Ordinal].ColumnName;
}
}
Then call it using:
string MyColumnName = MyRow.GetColumn(5);
Don't do this, but this is how you would do it:
$(".overdue").each(function() {
alert("Your book is overdue");
});
The reason I say "don't do it" is because nothing is more annoying to users, in my opinion, than repeated pop-ups that cannot be stopped. Instead, just use the length
property and let them know that "You have X books overdue".
EXISTS
will tell you whether a query returned any results. e.g.:
SELECT *
FROM Orders o
WHERE EXISTS (
SELECT *
FROM Products p
WHERE p.ProductNumber = o.ProductNumber)
IN
is used to compare one value to several, and can use literal values, like this:
SELECT *
FROM Orders
WHERE ProductNumber IN (1, 10, 100)
You can also use query results with the IN
clause, like this:
SELECT *
FROM Orders
WHERE ProductNumber IN (
SELECT ProductNumber
FROM Products
WHERE ProductInventoryQuantity > 0)
my table name is buyers which has a unique constraint column emp_id now iam going to drop the emp_id
step 1: exec sp_helpindex buyers, see the image file
step 2: copy the index address
step3: alter table buyers drop constraint [UQ__buyers__1299A860D9793F2E] alter table buyers drop column emp_id
note:
Blockquote
instead of buyers change it to your table name :)
Blockquote
thats all column name emp_id with constraints is dropped!
I had the same problem, when I used a inline-block on my menu I had the space between each "li" I found a simple solution, I don't remember where I found it, anyway here is what I did.
<li><a href="index.html" title="home" class="active">Home</a></li><!---->
<li><a href="news.html" title="news">News</a></li><!---->
<li><a href="about.html" title="about">About Us</a></li><!---->
<li><a href="contact.html" title="contact">Contact Us</a></li>
You add a comment sign between each end of, and start of : "li" Then the horizontal space disappear. Hope that answer to the question Thanks
Expanding on the answers provided here.
You can just do set idx = 1
to set a variable, but that syntax is not recommended because the variable name may clash with a set sub-command. As an example set w=1
would not be valid.
This means that you should prefer the syntax: set variable idx = 1
or set var idx = 1
.
Last but not least, you can just use your trusty old print command, since it evaluates an expression. The only difference being that he also prints the result of the expression.
(gdb) p idx = 1
$1 = 1
You can read more about gdb here.
var length = $('#mySelectList').children('option').length;
or
var length = $('#mySelectList > option').length;
This assumes your <select>
list has an ID of mySelectList
.
Well, there are plenty of database tutorials online for java (what you're looking for is called JDBC). But if you are using plain servlets, you will have a class that extends HttpServlet
and inside it you will have two methods that look like
public void doPost(HttpServletRequest req, HttpServletResponse resp){
}
and
public void doGet(HttpServletRequest req, HttpServletResponse resp){
}
One of them is called to handle GET
operations and another is used to handle POST
operations. You will then use the HttpServletRequest
object to get the parameters that were passed as part of the form like so:
String name = req.getParameter("name");
Then, once you have the data from the form, it's relatively easy to add it to a database using a JDBC tutorial that is widely available on the web. I also suggest searching for a basic Java servlet tutorial to get you started. It's very easy, although there are a number of steps that need to be configured correctly.
As far as I know this isn't currently possible in C++. However, there are plans to add a feature called "concepts" in the new C++0x standard that provide the functionality that you're looking for. This Wikipedia article about C++ Concepts will explain it in more detail.
I know this doesn't fix your immediate problem but there are some C++ compilers that have already started to add features from the new standard, so it might be possible to find a compiler that has already implemented the concepts feature.
I would just like to club all the answers given above and also relate Flush() method with Session.save() so as to give more importance
Hibernate save() can be used to save entity to database. We can invoke this method outside a transaction, that’s why I don’t like this method to save data. If we use this without transaction and we have cascading between entities, then only the primary entity gets saved unless we flush the session.
flush(): Forces the session to flush. It is used to synchronize session data with database.
When you call session.flush(), the statements are executed in database but it will not committed. If you don’t call session.flush() and if you call session.commit() , internally commit() method executes the statement and commits.
So commit()= flush+commit. So session.flush() just executes the statements in database (but not commits) and statements are NOT IN MEMORY anymore. It just forces the session to flush.
Few important points:
We should avoid save outside transaction boundary, otherwise mapped entities will not be saved causing data inconsistency. It’s very normal to forget flushing the session because it doesn’t throw any exception or warnings. By default, Hibernate will flush changes automatically for you: before some query executions when a transaction is committed Allowing to explicitly flush the Session gives finer control that may be required in some circumstances (to get an ID assigned, to control the size of the Session)
date
command didnt provide milli seconds on OS X, so used an alias from python
millis(){ python -c "import time; print(int(time.time()*1000))"; }
OR
alias millis='python -c "import time; print(int(time.time()*1000))"'
EDIT: following the comment from @CharlesDuffy. Forking any child process takes extra time.
$ time date +%s%N
1597103627N
date +%s%N 0.00s user 0.00s system 63% cpu 0.006 total
Python is still improving it's VM start time, and it is not as fast as ahead-of-time compiled code (such as date
).
On my machine, it took about 30ms - 60ms (that is 5x-10x of 6ms taken by date
)
$ time python -c "import time; print(int(time.time()*1000))"
1597103899460
python -c "import time; print(int(time.time()*1000))" 0.03s user 0.01s system 83% cpu 0.053 total
I figured awk
is lightweight than python
, so awk
takes in the range of 6ms to 12ms (i.e. 1x to 2x of date):
$ time awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}'
1597103729525
awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}' 0.00s user 0.00s system 74% cpu 0.010 total
Yes it is correct in Java there are several steps to make an array of objects:
Declaring and then Instantiating (Create memory to store '4' objects):
A[ ] arr = new A[4];
Initializing the Objects (In this case you can Initialize 4 objects of class A)
arr[0] = new A();
arr[1] = new A();
arr[2] = new A();
arr[3] = new A();
or
for( int i=0; i<4; i++ )
arr[i] = new A();
Now you can start calling existing methods from the objects you just made etc.
For example:
int x = arr[1].getNumber();
or
arr[1].setNumber(x);
Funny, I was just researching this yesterday!
I personally use Monaco 10 or 11 for the Mac, but a good cross platform font would have to be Droid Sans Mono: http://damieng.com/blog/2007/11/14/droid-sans-mono-great-coding-font Or DejaVu sans mono is another great one (goes under a lot of different names, will be Menlo on SNow leopard and is really just a repackaged Prima/Vera) check it out here: Prima/Vera... Check it out here: http://dejavu-fonts.org/wiki/index.php?title=Download
If you just want to see how your picture will look on the website without uploading it to the server or without running your website on a local server, I think a very simple solution will be to convert your picture into a Base64 and add the contents into an IMG tag or as a background-image with CSS.
By default X-Frame-Options
is set to denied, to prevent clickjacking attacks. To override this, you can add the following into your spring security config
<http>
<headers>
<frame-options policy="SAMEORIGIN"/>
</headers>
</http>
Here are available options for policy
For more information take a look here.
And here to check how you can configure the headers using either XML or Java configs.
Note, that you might need also to specify appropriate strategy
, based on needs.
For me the better approach is that:
s.split('mango', 1)[-1]
...because if happens that occurrence is not in the string you'll get "IndexError: list index out of range"
.
Therefore -1
will not get any harm cause number of occurrences is already set to one.
Another option using linq is
[TestMethod]
public void Test()
{
var input = "it's worth a lot of money, if you can find a buyer.";
var expected = "its worth a lot of money if you can find a buyer";
var removeList = new string[] { ".", ",", "'" };
var result = input;
removeList.ToList().ForEach(o => result = result.Replace(o, string.Empty));
Assert.AreEqual(expected, result);
}
git reset --hard origin/master
says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master
.
You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".
First of all, since Spring doesn't do persistence itself, it cannot specify what readOnly
should exactly mean. This attribute is only a hint to the provider, the behavior depends on, in this case, Hibernate.
If you specify readOnly
as true
, the flush mode will be set as FlushMode.NEVER
in the current Hibernate Session preventing the session from committing the transaction.
Furthermore, setReadOnly(true) will be called on the JDBC Connection, which is also a hint to the underlying database. If your database supports it (most likely it does), this has basically the same effect as FlushMode.NEVER
, but it's stronger since you cannot even flush manually.
Now let's see how transaction propagation works.
If you don't explicitly set readOnly
to true
, you will have read/write transactions. Depending on the transaction attributes (like REQUIRES_NEW
), sometimes your transaction is suspended at some point, a new one is started and eventually committed, and after that the first transaction is resumed.
OK, we're almost there. Let's see what brings readOnly
into this scenario.
If a method in a read/write transaction calls a method that requires a readOnly transaction, the first one should be suspended, because otherwise a flush/commit would happen at the end of the second method.
Conversely, if you call a method from within a readOnly transaction that requires read/write, again, the first one will be suspended, since it cannot be flushed/committed, and the second method needs that.
In the readOnly-to-readOnly, and the read/write-to-read/write cases the outer transaction doesn't need to be suspended (unless you specify propagation otherwise, obviously).
Use fabs
instead of abs
to find absolute value of double
(or float
) data types. Include the <math.h>
header for fabs
function.
double d1 = fabs(-3.8951);
Map:
Map transformation.
The map works on a single Row at a time.
Map returns after each input Row.
The map doesn’t hold the output result in Memory.
Map no way to figure out then to end the service.
// map example
val dfList = (1 to 100) toList
val df = dfList.toDF()
val dfInt = df.map(x => x.getInt(0)+2)
display(dfInt)
MapPartition:
MapPartition transformation.
MapPartition works on a partition at a time.
MapPartition returns after processing all the rows in the partition.
MapPartition output is retained in memory, as it can return after processing all the rows in a particular partition.
MapPartition service can be shut down before returning.
// MapPartition example
Val dfList = (1 to 100) toList
Val df = dfList.toDF()
Val df1 = df.repartition(4).rdd.mapPartition((int) => Iterator(itr.length))
Df1.collec()
//display(df1.collect())
For more details, please refer to the Spark map vs mapPartitions transformation article.
Hope this is helpful!
Try using Carbon's Install-User and Add-GroupMember functions:
Install-User -Username "User" -Description "LocalAdmin" -FullName "Local Admin by Powershell" -Password "Password01"
Add-GroupMember -Name 'Administrators' -Member 'User'
Disclaimer: I am the creator/maintainer of the Carbon project.
Instead of setting the @JsonSerialize on each member or getter you can configure a module that use a custome serializer for a certain type:
SimpleModule module = new SimpleModule();
module.addSerializer(BigInteger.class, new ToStringSerializer());
objectMapper.registerModule(module);
In the above example, I used the to string serializer to serialize BigIntegers (since javascript can not handle such numeric values).
Without explicitly defining the height
I determined I need to apply the flex
value to the parent and grandparent div
elements...
<div style="display: flex;">
<div style="display: flex;">
<img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>
If you're using a single element (e.g. dead-centered text in a single flex
element) use the following:
align-items: center;
display: flex;
justify-content: center;
The simple naive way that is slow because it opens and positions the file pointer to End-Of-File multiple times.
@echo off
command1 >output.txt
command2 >>output.txt
...
commandN >>output.txt
A better way - easier to write, and faster because the file is opened and positioned only once.
@echo off
>output.txt (
command1
command2
...
commandN
)
Another good and fast way that only opens and positions the file once
@echo off
call :sub >output.txt
exit /b
:sub
command1
command2
...
commandN
Edit 2020-04-17
Every now and then you may want to repeatedly write to two or more files. You might also want different messages on the screen. It is still possible to to do this efficiently by redirecting to undefined handles outside a parenthesized block or subroutine, and then use the &
notation to reference the already opened files.
call :sub 9>File1.txt 8>File2.txt
exit /b
:sub
echo Screen message 1
>&9 File 1 message 1
>&8 File 2 message 1
echo Screen message 2
>&9 File 1 message 2
>&8 File 2 message 2
exit /b
I chose to use handles 9 and 8 in reverse order because that way is more likely to avoid potential permanent redirection due to a Microsoft redirection implementation design flaw when performing multiple redirections on the same command. It is highly unlikely, but even that approach could expose the bug if you try hard enough. If you stage the redirection than you are guaranteed to avoid the problem.
3>File1.txt ( 4>File2.txt call :sub)
exit /b
:sub
etc.
And another useful command to do this (after git fetch) is:
git log origin/master ^master
This shows the commits that are in origin/master but not in master. You can also do it in opposite when doing git pull, to check what commits will be submitted to remote.
Strangely enough, from poking in the designer I find what seems to be a much simpler approach:
The image seems to be available from .Properties.Resources.
I'm simply using an image as all I'm interested in is pasting it into a control with an image on it.
(Net 4.0, VS2010.)
Plenty of good solutions exist for finding all the prime factors of not too large numbers. I just wanted to point out, that once you have them, no computation is required to get all the factors.
if N = p_1^{a}*p_{2}^{b}*p_{3}^{c}.....
Then the number of factors is clearly (a+1)(b+1)(c+1)....
since every factor can occur zero up to a times.
e.g. 12 = 2^2*3^1
so it has 3*2 = 6
factors. 1,2,3,4,6,12
======
I originally thought that you just wanted the number of distinct factors. But the same logic applies. You just iterate over the set of numbers corresponding to the possible combinations of exponents.
so int he example above:
00
01
10
11
20
21
gives you the 6
factors.
From ggplot 2.2.0
labels can easily be stacked by using position = position_stack(vjust = 0.5)
in geom_text
.
ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
geom_bar(stat = "identity") +
geom_text(size = 3, position = position_stack(vjust = 0.5))
Also note that "position_stack()
and position_fill()
now stack values in the reverse order of the grouping, which makes the default stack order match the legend."
Answer valid for older versions of ggplot
:
Here is one approach, which calculates the midpoints of the bars.
library(ggplot2)
library(plyr)
# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year),
transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)
# library(dplyr) ## If using dplyr...
# Data <- group_by(Data,Year) %>%
# mutate(pos = cumsum(Frequency) - (0.5 * Frequency))
# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
geom_bar(aes(fill = Category), stat="identity") +
geom_text(aes(label = Frequency, y = pos), size = 3)
i am using this method.
add a from that you want to pop up, add all controls you need. in the code you can handle the user input and return result to the caller. for pop up the form just create a new instance of the form and show method.
/* create new form instance. i am overriding constructor to allow the caller form to set the form header */
var t = new TextPrompt("Insert your message and click Send button");
// pop up the form
t.Show();
if (t.DialogResult == System.Windows.Forms.DialogResult.OK)
{
MessageBox.Show("RTP", "Message sent to user");
}
Note that you can also use the InOrder class to verify that various methods are called in order on a single mock, not just on two or more mocks.
Suppose I have two classes Foo
and Bar
:
public class Foo {
public void first() {}
public void second() {}
}
public class Bar {
public void firstThenSecond(Foo foo) {
foo.first();
foo.second();
}
}
I can then add a test class to test that Bar
's firstThenSecond()
method actually calls first()
, then second()
, and not second()
, then first()
. See the following test code:
public class BarTest {
@Test
public void testFirstThenSecond() {
Bar bar = new Bar();
Foo mockFoo = Mockito.mock(Foo.class);
bar.firstThenSecond(mockFoo);
InOrder orderVerifier = Mockito.inOrder(mockFoo);
// These lines will PASS
orderVerifier.verify(mockFoo).first();
orderVerifier.verify(mockFoo).second();
// These lines will FAIL
// orderVerifier.verify(mockFoo).second();
// orderVerifier.verify(mockFoo).first();
}
}
You can check the called
attribute, but if your assertion fails, the next thing you'll want to know is something about the unexpected call, so you may as well arrange for that information to be displayed from the start. Using unittest
, you can check the contents of call_args_list
instead:
self.assertItemsEqual(my_var.call_args_list, [])
When it fails, it gives a message like this:
AssertionError: Element counts were not equal: First has 0, Second has 1: call('first argument', 4)
This worked for me:
static void ClearLine(){
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, Console.CursorTop - 1);
}
As for ERRORCODE 39, you can definately just delete the physical table files on the disk. the location depends on your OS distribution and setup. On Debian its typically under /var/lib/mysql/database_name/ So do a:
rm -f /var/lib/mysql/<database_name>/
And then drop the database from your tool of choice or using the command:
DROP DATABASE <database_name>
There are at least two solutions:
How about using fontawesome icon for Indian Rupee (INR).
Add font awesome CSS from CDN in the Head section of your HTML page:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
And then using the font like this:
<i class="fa fa-inr" aria-hidden="true"></i>
<div onScrollCapture={() => this._onScrollEvent()}></div>
_onScrollEvent = (e)=>{
const top = e.nativeEvent.target.scrollTop;
console.log(top);
}
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
ABOVE CODE TO SELECT IMAGE FROM GALLERY
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
String filePath = getPath(selectedImage);
String file_extn = filePath.substring(filePath.lastIndexOf(".") + 1);
image_name_tv.setText(filePath);
try {
if (file_extn.equals("img") || file_extn.equals("jpg") || file_extn.equals("jpeg") || file_extn.equals("gif") || file_extn.equals("png")) {
//FINE
} else {
//NOT IN REQUIRED FORMAT
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String getPath(Uri uri) {
String[] projection = {MediaColumns.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
column_index = cursor
.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);
return cursor.getString(column_index);
}
NOW POST THE DATA USING MULTIPART FORM DATA
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("LINK TO SERVER");
Multipart FORM DATA
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (filePath != null) {
File file = new File(filePath);
Log.d("EDIT USER PROFILE", "UPLOAD: file length = " + file.length());
Log.d("EDIT USER PROFILE", "UPLOAD: file exist = " + file.exists());
mpEntity.addPart("avatar", new FileBody(file, "application/octet"));
}
FINALLY POST DATA TO SERVER
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
My best answer for this is to simply use format painter. This might be a bit of a pain, but it works rather well as the problem you are facing is that Gridlines are covered by fill and other effects that are layered on top. Imagine putting a piece of white paper on top of your grid, the grid lines are present underneath, but they just don't show.
So try:
From my experience this is the easiest way to do this quickly. Especially when pasting things in and out of excel.
Again this is not the programmatic way of solving this problem.
You can clear out their values by just setting value to an empty string:
var1.value = '';
var2.value = '';
You've started right - now you just need to fill the each student
structure in the array:
struct student
{
public int s_id;
public String s_name, c_name, dob;
}
class Program
{
static void Main(string[] args)
{
student[] arr = new student[4];
for(int i = 0; i < 4; i++)
{
Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
arr[i].s_id = Int32.Parse(Console.ReadLine());
arr[i].s_name = Console.ReadLine();
arr[i].c_name = Console.ReadLine();
arr[i].s_dob = Console.ReadLine();
}
}
}
Now, just iterate once again and write these information to the console. I will let you do that, and I will let you try to make program to take any number of students, and not just 4.
This worked for me to solve jpeg and zlib error :
C:\Windows\system32>pip3 install pillow --global-option="build_e
xt" --global-option="--disable-zlib" --global-option="--disable-jpeg"
select count(myCol)
from mytable
group by myCol
;
will group the 3 possible states of bool (false, true, 0) in three rows especially handy when grouping together with another column like day
You can also try setting the system variable path to the location of your nuget exe and restarting VS.
PATH
variable and add the location of your nuget.exe (for me this is: C:\Program Files (x86)\NuGet\Visual Studio 2013
)I would have posted this as a comment to your answer @done_merson but I didn't have the required reputation to do that.
First you have to define attribute in form2(child) you will update this attribute in form2 and also from form1(parent) :
public string Response { get; set; }
private void OkButton_Click(object sender, EventArgs e)
{
Response = "ok";
}
private void CancelButton_Click(object sender, EventArgs e)
{
Response = "Cancel";
}
Calling of form2(child) from form1(parent):
using (Form2 formObject= new Form2() )
{
formObject.ShowDialog();
string result = formObject.Response;
//to update response of form2 after saving in result
formObject.Response="";
// do what ever with result...
MessageBox.Show("Response from form2: "+result);
}
The following code creates a file Named "AllFilesInCurrentDirectorylist.txt" in the current Directory, which contains the list of all files (Only Files) in the current Directory. Check it out
dir /b /a-d > AllFilesInCurrentDirectorylist.txt
CREATE TABLE people (
first_name varchar(20),
age integer,
last_name varchar(20)
);
"first_name","age","last_name" Ivan,23,Poupkine Eugene,,Pirogov
copy people from 'file.csv'
with (delimiter ';', null '');
select * from people;
Just in first column.....
If you use EventBus, it is probably a far more simpler solution :
In your Fragment :
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
EventBus.getDefault().register(this);
}
@Override
public void onDetach() {
super.onDetach();
EventBus.getDefault().unregister(this);
}
// This method will be called when a MessageEvent is posted
public void onEvent(BackPressedMessage type){
getSupportFragmentManager().popBackStack();
}
and in your Activity class you can define :
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
// This method will be called when a MessageEvent is posted
public void onEvent(BackPressedMessage type){
super.onBackPressed();
}
@Override
public void onBackPressed() {
EventBus.getDefault().post(new BackPressedMessage(true));
}
BackPressedMessage.java is just a POJO object
This is super clean and there is no interface/implementation hassle.
As @PavelAnossov answered, the canonical answer, use the word_tokenize
function in nltk:
from nltk import word_tokenize
sent = "This is my text, this is a nice way to input text."
word_tokenize(sent)
If your sentence is truly simple enough:
Using the string.punctuation
set, remove punctuation then split using the whitespace delimiter:
import string
x = "This is my text, this is a nice way to input text."
y = "".join([i for i in x if not in string.punctuation]).split(" ")
print y
Try to putting this .htaccess file on subdomain folder:
RewriteEngine On
RewriteRule ^(.*)?$ ./subdomains/sub/$1
It redirects to http://domain.com/subdomains/sub/, when you only want it to show http://sub.domain.com/
I found the following in the site.css generated by VS2013
/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
max-width: 280px;
}
To override this behavior in a specific element, add the following...
style="max-width: none;"
For example:
<div class="col-md-6">
<textarea style="max-width: none;"
class="form-control"
placeholder="a col-md-6 multiline input box" />
</div>
Although not a merge per se, sometimes the entire contents of another file on another branch are needed. Jason Rudolph's blog post provides a simple way to copy files from one branch to another. Apply the technique as follows:
$ git checkout branch1 # ensure in branch1 is checked out and active
$ git checkout branch2 file.py
Now file.py
is now in branch1.
As @Hesham Eraqi suggested, it worked for me in this way (transfering from Ubuntu to Windows (I tried to add a comment in that answer but because of reputation, I couldn't)):
pscp -v -r -P 53670 [email protected]:/data/genetic_map/sample/P2_283/* \\Desktop-mojbd3n\d\cc_01-1940_data\
where:
-v
: show verbose messages.
-r
: copy directories recursively.
-P
: connect to specified port.
53670
: the port number to connect the Ubuntu server.
\\Desktop-mojbd3n\d\genetic_map_data\
: I needed to transfer to an external HDD, thus I had to give permissions of sharing to this device.
You're looking for the OpenFileDialog
class.
For example:
Sub SomeButton_Click(sender As Object, e As EventArgs) Handles SomeButton.Click
Using dialog As New OpenFileDialog
If dialog.ShowDialog() <> DialogResult.OK Then Return
File.Copy(dialog.FileName, newPath)
End Using
End Sub
With respect to other answers, it's not always there. Sometimes on setup process people forget to select the Web Developer Tools
.
In order to fix that, one should:
Programs and Features
find Visual Studios related version
there, click on it,Change
.
Then the setup window will appear, Web Developer Tools
there and continue to setup.It will download or use the setup media if exist. After the setup windows may restart, and you are ready to have fun with your Web Developer Tools
now.
//use css
.blue {
background-color:blue !important;
}
.blue th {
color:white !important;
}
//html
<table class="table blue">.....</table>
I will say before all that this will not always works, i have tested this with sans-serif
font and external fonts like open sans
Sometimes, when you use huge fonts, try to approximate to font-size:49px
and upper
This is a header text with a size of 48px (font-size:48px;
in the element that contains the text).
But, if you up the 48px to font-size:49px;
(and 50px, 60px, 80px, etc...), something interesting happens
The text automatically get smooth, and seems really good
If you are looking for small fonts, you can try this, but isn't very effective.
To the parent of the text, just apply the next css property: -webkit-backface-visibility: hidden;
You can transform something like this:
To this:
(the font is Kreon
)
Consider that when you are not putting that property, -webkit-backface-visibility: visible;
is inherit
But be careful, that practice will not give always good results, if you see carefully, Chrome just make the text look a little bit blurry.
-webkit-backface-visibility: hidden;
will works too when you transform a text in Chrome (with the -webkit-transform
property, that includes rotations, skews, etc)
Without -webkit-backface-visibility: hidden;
With -webkit-backface-visibility: hidden;
Well, I don't know why that practices works, but it does for me. Sorry for my weird english.
For completeness, in addition to previous answers (perform calculation of visible people inside controller) you can also perform that calculations in your HTML template as in the example below.
Assuming your list of people is in data
variable and you filter people using query
model, the following code will work for you:
<p>Number of visible people: {{(data|filter:query).length}}</p>
<p>Total number of people: {{data.length}}</p>
{{data.length}}
- prints total number of people{{(data|filter:query).length}}
- prints filtered number of peopleNote that this solution works fine if you want to use filtered data only once in a page. However, if you use filtered data more than once e.g. to present items and to show length of filtered list, I would suggest using alias expression (described below) for AngularJS 1.3+ or the solution proposed by @Wumms for AngularJS version prior to 1.3.
New Feature in Angular 1.3
AngularJS creators also noticed that problem and in version 1.3 (beta 17) they added "alias" expression which will store the intermediate results of the repeater after the filters have been applied e.g.
<div ng-repeat="person in data | filter:query as results">
<!-- template ... -->
</div>
<p>Number of visible people: {{results.length}}</p>
The alias expression will prevent multiple filter execution issue.
I hope that will help.
On ASP.net web forms use in the @page AspCompat="true", add the system.windows.forms to you project. At your web.config add:
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
</appSettings>
Then you can use:
Clipboard.SetText(CreateDescription());
https://stackoverflow.com/a/53251526/1282532 is the simplest way to serialize/deserialize property. I have two concerns regarding this approach - up to some point violation of DRY principle and high coupling between pojo and mapper.
public class Trade {
@JsonFormat(pattern = "yyyyMMdd")
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate tradeDate;
@JsonFormat(pattern = "yyyyMMdd")
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate maturityDate;
@JsonFormat(pattern = "yyyyMMdd")
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate entryDate;
}
In case you have POJO with multiple LocalDate fields it's better to configure mapper instead of POJO. It can be as simple as https://stackoverflow.com/a/35062824/1282532 if you are using ISO-8601 values ("2019-01-31")
In case you need to handle custom format the code will be like this:
ObjectMapper mapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyyMMdd")));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyyMMdd")));
mapper.registerModule(javaTimeModule);
The logic is written just once, it can be reused for multiple POJO
You can try this
SELECT * FROM Buses
WHERE BusID
in (1,2,3,4,...)
Namespace: using System.IO;
//use this to get file name dynamically
string filelocation = Properties.Settings.Default.Filelocation;
//use this to get file name statically
//string filelocation = @"D:\FileDirectory\";
string[] filesname = Directory.GetFiles(filelocation); //for multiple files
Your path configuration in App.config file if you are going to get file name dynamically -
<userSettings>
<ConsoleApplication13.Properties.Settings>
<setting name="Filelocation" serializeAs="String">
<value>D:\\DeleteFileTest</value>
</setting>
</ConsoleApplication13.Properties.Settings>
</userSettings>
I'd go for jpeg
. Read this post regarding image size reduction and after deciding on the technique, use ImageMagick
Hope this helps
Go here :
C:\Program Files (x86)\Windows Kits\10
and do whatever you were supposed to go in the given directory for VS 13.
in the lib folder, you will find some versions, I copied the 32-bit glut.lib files in amd and x86 and 64-bit glut.lib in arm64 and x64 directories in um
folder for every version that I could find.
That worked for me.
EDIT : I tried this in windows 10, maybe you need to go to C:\Program Files (x86)\Windows Kits\8.1
folder for windows 8/8.1.
I have modified the above answer, so you don't need to cast from Object
public static <T> List<T> safeClient( List<T> other ) {
return other == null ? Collections.EMPTY_LIST : other;
}
and then simply call the List by
for (MyOwnObject ownObject : safeClient(someList)) {
// do whatever
}
Explaination:
MyOwnObject: If List<Integer>
then MyOwnObject will be Integer in this case.
Oracle will throw ORA-00904
if executing user does not have proper permissions on objects involved in the query.
Android Studio supports SVG from 1.4 onwards
Here is a video on how to import.
You are trying to add an integer into an ArrayList
that takes an array of integers Integer[]
. It should be
ArrayList<Integer> list = new ArrayList<>();
or better
List<Integer> list = new ArrayList<>();
I felt the below approach is very easy.
I have declared an interface for callback
public interface AsyncResponse {
void processFinish(Object output);
}
Then created asynchronous Task for responding all type of parallel requests
public class MyAsyncTask extends AsyncTask<Object, Object, Object> {
public AsyncResponse delegate = null;//Call back interface
public MyAsyncTask(AsyncResponse asyncResponse) {
delegate = asyncResponse;//Assigning call back interfacethrough constructor
}
@Override
protected Object doInBackground(Object... params) {
//My Background tasks are written here
return {resutl Object}
}
@Override
protected void onPostExecute(Object result) {
delegate.processFinish(result);
}
}
Then Called the asynchronous task when clicking a button in activity Class.
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
Button mbtnPress = (Button) findViewById(R.id.btnPress);
mbtnPress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyAsyncTask asyncTask =new MyAsyncTask(new AsyncResponse() {
@Override
public void processFinish(Object output) {
Log.d("Response From Asynchronous task:", (String) output);
mbtnPress.setText((String) output);
}
});
asyncTask.execute(new Object[] { "Youe request to aynchronous task class is giving here.." });
}
});
}
}
Thanks
i also have a solution with standard inputs and outputs
#include<stdio.h>
#include<malloc.h>
int main()
{
char *str,ch;
int size=10,len=0;
str=realloc(NULL,sizeof(char)*size);
if(!str)return str;
while(EOF!=scanf("%c",&ch) && ch!="\n")
{
str[len++]=ch;
if(len==size)
{
str = realloc(str,sizeof(char)*(size+=10));
if(!str)return str;
}
}
str[len++]='\0';
printf("%s\n",str);
free(str);
}
Strings in C# are immutable and in some sense it means that they are fixed-size.
However you cannot constrain a string variable to only accept n-character strings. If you define a string variable, it can be assigned any string. If truncating strings (or throwing errors) is essential part of your business logic, consider doing so in your specific class' property setters (that's what Jon suggested, and it's the most natural way of creating constraints on values in .NET).
If you just want to make sure isn't too long (e.g. when passing it as a parameter to some legacy code), truncate it manually:
const int MaxLength = 5;
var name = "Christopher";
if (name.Length > MaxLength)
name = name.Substring(0, MaxLength); // name = "Chris"
sp_who2 will actually provide a list of connections for the database server, not a database. To view connections for a single database (YourDatabaseName in this example), you can use
DECLARE @AllConnections TABLE(
SPID INT,
Status VARCHAR(MAX),
LOGIN VARCHAR(MAX),
HostName VARCHAR(MAX),
BlkBy VARCHAR(MAX),
DBName VARCHAR(MAX),
Command VARCHAR(MAX),
CPUTime INT,
DiskIO INT,
LastBatch VARCHAR(MAX),
ProgramName VARCHAR(MAX),
SPID_1 INT,
REQUESTID INT
)
INSERT INTO @AllConnections EXEC sp_who2
SELECT * FROM @AllConnections WHERE DBName = 'YourDatabaseName'
(Adapted from SQL Server: Filter output of sp_who2.)
Just simply use this Style
of DataGridRow
:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
</Style>
</DataGrid.RowStyle>
the CDN link that you had posted i suppose is why it wasnt showing correctly, you can use this one below, it works perfectly for me.
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
_x000D_
Storing a list of strings in Django model:
class Bar(models.Model):
foo = models.TextField(blank=True)
def set_list(self, element):
if self.foo:
self.foo = self.foo + "," + element
else:
self.foo = element
def get_list(self):
if self.foo:
return self.foo.split(",")
else:
None
and you can call it like this:
bars = Bar()
bars.set_list("str1")
bars.set_list("str2")
list = bars.get_list()
if list is not None:
for bar in list:
print bar
else:
print "List is empty."
select to_char(date,'Mon') as mon,
extract(year from date) as yyyy,
sum("Sales") as "Sales"
from yourtable
group by 1,2
At the request of Radu, I will explain that query:
to_char(date,'Mon') as mon,
: converts the "date" attribute into the defined format of the short form of month.
extract(year from date) as yyyy
: Postgresql's "extract" function is used to extract the YYYY year from the "date" attribute.
sum("Sales") as "Sales"
: The SUM() function adds up all the "Sales" values, and supplies a case-sensitive alias, with the case sensitivity maintained by using double-quotes.
group by 1,2
: The GROUP BY function must contain all columns from the SELECT list that are not part of the aggregate (aka, all columns not inside SUM/AVG/MIN/MAX etc functions). This tells the query that the SUM() should be applied for each unique combination of columns, which in this case are the month and year columns. The "1,2" part is a shorthand instead of using the column aliases, though it is probably best to use the full "to_char(...)" and "extract(...)" expressions for readability.
The solution I have used is:
<svg>
<line x1="100" y1="100" x2="500" y2="100" style="stroke:black; stroke-width: 2"/>
<text x="150" y="105" style="stroke:white; stroke-width:0.6em">Hello World!</text>
<text x="150" y="105" style="fill:black">Hello World!</text>
</svg>
_x000D_
A duplicate text item is being placed, with stroke and stroke-width attributes. The stroke should match the background colour, and the stroke-width should be just big enough to create a "splodge" on which to write the actual text.
A bit of a hack and there are potential issues, but works for me!
Be careful with rebase. If you're sharing your develop branch with anybody, rebase can make a mess of things. Rebase is good only for your own local branches.
Rule of thumb, if you've pushed the branch to origin, don't use rebase. Instead, use merge.
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
I fixed the issue by right clicking the test and selecting 'Run Configurations' and changing the "Test runner:" selection to 'JUnit 4' as shown here:
I ran the test again and it worked.
I would recommend using an ArrayList
, which handles dynamic sizing, whereas an array will require a defined size up front, which you may not know. You can always turn the list back into an array.
BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;
List<String> list = new ArrayList<String>();
while((str = in.readLine()) != null){
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
Update: a better idea, set the "AppendDataBoundItems" property to true, then declare the "Choose item" declaratively. The databinding operation will add to the statically declared item.
<asp:DropDownList ID="ddl" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="0" Text="Please choose..."></asp:ListItem>
</asp:DropDownList>
-Oisin
"but does that mean it should just be an example of the sort of expression you could use, or should it be an actual expression, that can be executed (eval etc..) to recreate the object? Or... should it be just a rehasing of the actual expression which was used, for pure information purposes?"
Wow, that's a lot of hand-wringing.
An "an example of the sort of expression you could use" would not be a representation of a specific object. That can't be useful or meaningful.
What is the difference between "an actual expression, that can ... recreate the object" and "a rehasing of the actual expression which was used [to create the object]"? Both are an expression that creates the object. There's no practical distinction between these. A repr call could produce either a new expression or the original expression. In many cases, they're the same.
Note that this isn't always possible, practical or desirable.
In some cases, you'll notice that repr() presents a string which is clearly not an expression of any kind. The default repr() for any class you define isn't useful as an expression.
In some cases, you might have mutual (or circular) references between objects. The repr() of that tangled hierarchy can't make sense.
In many cases, an object is built incrementally via a parser. For example, from XML or JSON or something. What would the repr be? The original XML or JSON? Clearly not, since they're not Python. It could be some Python expression that generated the XML. However, for a gigantic XML document, it might not be possible to write a single Python expression that was the functional equivalent of parsing XML.
pyplot
is a sub-module of matplotlib
which doesn't get imported with a simple import matplotlib
.
>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>>
It seems customary to do: import matplotlib.pyplot as plt
at which time you can use the various functions and classes it contains:
p = plt.plot(...)
This worked for me: Connect to MySQL in Vagrant
username: vagrant password: vagrant
sudo apt-get update sudo apt-get install build-essential zlib1g-dev
git-core sqlite3 libsqlite3-dev sudo aptitude install mysql-server
mysql-client
sudo nano /etc/mysql/my.cnf change: bind-address = 0.0.0.0
mysql -u root -p
use mysql GRANT ALL ON *.* to root@'33.33.33.1' IDENTIFIED BY
'jarvis'; FLUSH PRIVILEGES; exit
sudo /etc/init.d/mysql restart
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant::Config.run do |config|
config.vm.box = "lucid32"
config.vm.box_url = "http://files.vagrantup.com/lucid32.box"
#config.vm.boot_mode = :gui
# Assign this VM to a host-only network IP, allowing you to access
it # via the IP. Host-only networks can talk to the host machine as
well as # any other machines on the same network, but cannot be
accessed (through this # network interface) by any external
networks. # config.vm.network :hostonly, "192.168.33.10"
# Assign this VM to a bridged network, allowing you to connect
directly to a # network using the host's network device. This makes
the VM appear as another # physical device on your network. #
config.vm.network :bridged
# Forward a port from the guest to the host, which allows for
outside # computers to access the VM, whereas host only networking
does not. # config.vm.forward_port 80, 8080
config.vm.forward_port 3306, 3306
config.vm.network :hostonly, "33.33.33.10"
end
As the others have said, it's all good, you can do it just fine. For me personally, I try to keep a form of hierarchical structure with my elements with a div
being the outer most parent element. I try to use only table
p
ul
and span
inside forms. Just makes it easier for me to keep track of parent/children relationships inside my webpages.
Strangely enough, I wrote some code to do this back when 1.1 came out (what was that, seven years ago?) and tweaked it a little when 2.0 came out. I haven't looked at it in years as we no longer manage our servers.
It's not foolproof, but I'm posting it anyway because I find it humorous; in that it's easier to do in .NET and easier still in power shell.
bool GetFileVersion(LPCTSTR filename,WORD *majorPart,WORD *minorPart,WORD *buildPart,WORD *privatePart)
{
DWORD dwHandle;
DWORD dwLen = GetFileVersionInfoSize(filename,&dwHandle);
if (dwLen) {
LPBYTE lpData = new BYTE[dwLen];
if (lpData) {
if (GetFileVersionInfo(filename,0,dwLen,lpData)) {
UINT uLen;
VS_FIXEDFILEINFO *lpBuffer;
VerQueryValue(lpData,_T("\\"),(LPVOID*)&lpBuffer,&uLen);
*majorPart = HIWORD(lpBuffer->dwFileVersionMS);
*minorPart = LOWORD(lpBuffer->dwFileVersionMS);
*buildPart = HIWORD(lpBuffer->dwFileVersionLS);
*privatePart = LOWORD(lpBuffer->dwFileVersionLS);
delete[] lpData;
return true;
}
}
}
return false;
}
int _tmain(int argc,_TCHAR* argv[])
{
_TCHAR filename[MAX_PATH];
_TCHAR frameworkroot[MAX_PATH];
if (!GetEnvironmentVariable(_T("systemroot"),frameworkroot,MAX_PATH))
return 1;
_tcscat_s(frameworkroot,_T("\\Microsoft.NET\\Framework\\*"));
WIN32_FIND_DATA FindFileData;
HANDLE hFind = FindFirstFile(frameworkroot,&FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
return 2;
do {
if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
_tcslen(FindFileData.cAlternateFileName) != 0) {
_tcsncpy_s(filename,frameworkroot,_tcslen(frameworkroot)-1);
filename[_tcslen(frameworkroot)] = 0;
_tcscat_s(filename,FindFileData.cFileName);
_tcscat_s(filename,_T("\\mscorlib.dll"));
WORD majorPart,minorPart,buildPart,privatePart;
if (GetFileVersion(filename,&majorPart,&minorPart,&buildPart,&privatePart )) {
_tprintf(_T("%d.%d.%d.%d\r\n"),majorPart,minorPart,buildPart,privatePart);
}
}
} while (FindNextFile(hFind,&FindFileData) != 0);
FindClose(hFind);
return 0;
}
In my case (Oracle), it's WHERE REGEXP_LIKE(column, 'regex.*')
. See here:
SQL Function
Description
REGEXP_LIKE
This function searches a character column for a pattern. Use this function in the WHERE clause of a query to return rows matching the regular expression you specify.
...
REGEXP_REPLACE
This function searches for a pattern in a character column and replaces each occurrence of that pattern with the pattern you specify.
...
REGEXP_INSTR
This function searches a string for a given occurrence of a regular expression pattern. You specify which occurrence you want to find and the start position to search from. This function returns an integer indicating the position in the string where the match is found.
...
REGEXP_SUBSTR
This function returns the actual substring matching the regular expression pattern you specify.
(Of course, REGEXP_LIKE only matches queries containing the search string, so if you want a complete match, you'll have to use '^$'
for a beginning (^
) and end ($
) match, e.g.: '^regex.*$'
.)
I see answers here that won't work in SQL Server's syntax. I would use:
select t.range as [score range], count(*) as [number of occurences]
from (
select case
when score between 0 and 9 then ' 0-9 '
when score between 10 and 19 then '10-19'
when score between 20 and 29 then '20-29'
...
else '90-99' end as range
from scores) t
group by t.range
EDIT: see comments
From your code it becomes apparent that you use POCO. Having another key is unnecessary: you can add an index as suggested by juFo.
If you use Fluent API instead of attributing UserName property your column annotation should look like this:
this.Property(p => p.UserName)
.HasColumnAnnotation("Index", new IndexAnnotation(new[] {
new IndexAttribute("Index") { IsUnique = true }
}
));
This will create the following SQL script:
CREATE UNIQUE NONCLUSTERED INDEX [Index] ON [dbo].[Users]
(
[UserName] ASC
)
WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
SORT_IN_TEMPDB = OFF,
IGNORE_DUP_KEY = OFF,
DROP_EXISTING = OFF,
ONLINE = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
If you attempt to insert multiple Users having the same UserName you'll get a DbUpdateException with the following message:
Cannot insert duplicate key row in object 'dbo.Users' with unique index 'Index'.
The duplicate key value is (...).
The statement has been terminated.
Again, column annotations are not available in Entity Framework prior to version 6.1.
This is a very simple code I use and you manipulate it to change the colour and size of the table as you see fit.
First connect to the database:
<?php
$connect=mysql_connect('localhost', 'root', 'password');
mysql_select_db("name");
//here u select the data you want to retrieve from the db
$query="select * from tablename";
$result= mysql_query($query);
//here you check to see if any data has been found and you define the width of the table
If($result){
echo "<table width ='340' align='left'>
<tr color ='#5D9951>";
$i=0;
If(mysql_num_rows($result)>0)
{
//here you fetch the data from the database and print it in the respective columns
while($i<mysql_num_fields($result))
{
echo "<th>".mysql_field_name($result, $i)."</th>";
$i++;
}
echo "</tr>";
$color=1;
while($rows=mysql_fetch_array($result, MYSQL_ASSOC))
{
If ($color==1){
echo "<tr color='#'#cccccc'>";
foreach ($rows as $data){
echo "<td align='center'>".$data. "</td>";
}
$color=2;
}
$color=1;
}
} else {
echo"no results found";
echo "</table>";
} else {
echo "error running query:".MYSQL_error();
}
?>
It's a very elementary piece of code but it helps if you are not used to using functions.
I have got the same error but I have resolved the issue in the following ways:
Try javascript into your Ajax
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
Reference link
Example 2:
document.getElementsByClassName('eStore_buy_now_button')[0].onclick = function(){
window.btn_clicked = true;
};
window.onbeforeunload = function(){
if(!window.btn_clicked){
return 'You must click "Buy Now" to make payment and finish your order. If you leave now your order will be canceled.';
}
};
Here it will alert the user every time he leaves the page, until he clicks on the button.
If I understand the situation correctly, you are just passing json data through the http body, instead of application/x-www-form-urlencoded
data.
You can fetch this data with this snippet:
$request_body = file_get_contents('php://input');
If you are passing json, then you can do:
$data = json_decode($request_body);
$data
then contains the json data is php array.
php://input
is a so called wrapper.
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".
Other users commenting that the Content-Type
is plain/text
when encoding. You have to set the Content-Type
first w.Header().Set
, then the HTTP response code w.WriteHeader
.
If you call w.WriteHeader
first then call w.Header().Set
after you will get plain/text
.
An example handler might look like this;
func SomeHandler(w http.ResponseWriter, r *http.Request) {
data := SomeStruct{}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(data)
}
I believe this should work for all browsers:
var event;
if (typeof (Event) === 'function') {
event = new Event('resize');
} else { /*IE*/
event = document.createEvent('Event');
event.initEvent('resize', true, true);
}
window.dispatchEvent(event);
Based on your comments in this answer, I do what you're trying to do like this:
module.exports = function (app, db) {
var module = {};
module.auth = function (req, res) {
// This will be available 'outside'.
// Authy stuff that can be used outside...
};
// Other stuff...
module.pickle = function(cucumber, herbs, vinegar) {
// This will be available 'outside'.
// Pickling stuff...
};
function jarThemPickles(pickle, jar) {
// This will be NOT available 'outside'.
// Pickling stuff...
return pickleJar;
};
return module;
};
I structure pretty much all my modules like that. Seems to work well for me.
This ScriptingGuy guest post links to a script by a Microsoft Powershell Expert can help you find this information, but to fully audit why it was locked and which machine triggered the lock you probably need to turn on additional levels of auditing via GPO.
https://gallery.technet.microsoft.com/scriptcenter/Get-LockedOutLocation-b2fd0cab#content
This should do the trick:
df[- grep("REVERSE", df$Name),]
Or a safer version would be:
df[!grepl("REVERSE", df$Name),]
If the question is: "Is it possible to add value on ESC" than the answer is yes. You can do something like that. For example with use of jQuery it would look like below.
HTML
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<input type="text" value="default!" id="myInput" />
JavaScript
$(document).ready(function (){
$('#myInput').keyup(function(event) {
// 27 is key code of ESC
if (event.keyCode == 27) {
$('#myInput').val('default!');
// Loose focus on input field
$('#myInput').blur();
}
});
});
Working source can be found here: http://jsfiddle.net/S3N5H/1/
Please let me know if you meant something different, I can adjust the code later.
jQuery's hasClass()
method returns a boolean (true/false) and not an element. Also, the parameter to be given to it is a class name and not a selector as such.
For ex: x.hasClass('error');
There are several solutions but they depend on HTML5 and haven't been implemented completely in some browsers yet. Examples below were tested in Chrome and Firefox (partly works).
document.location.href
to the data URI.<a href="your-data-uri" download="filename.txt">
to specify file name.You can directly add a constraint for table
ALTER TABLE TableName
ADD CONSTRAINT ConstraintName PRIMARY KEY(ColumnName)
GO
Make sure your primary key column should not have any null values.
Option 2:
you can change your SQL Management Studio Options like
To change this option, on the Tools menu, click Options, expand Designers, and then click Table and Database Designers. Select or clear the Prevent saving changes that require the table to be re-created check box.
+ theme(plot.title = element_text(size=22))
Here is the full set of things you can change in element_text
:
element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
color = NULL)
POSIX is:
POSIX (pronounced /'p?z?ks/) or "Portable Operating System Interface [for Unix]"1 is the name of a family of related standards specified by the IEEE to define the application programming interface (API), along with shell and utilities interfaces for software compatible with variants of the Unix operating system, although the standard can apply to any operating system.
Basically it was a set of measures to ease the pain of development and usage of different flavours of UNIX by having a (mostly) common API and utilities. Limited POSIX compliance also extended to various versions of Windows.
Tcl has a builtin for this
$ tclsh
% string map {ab bc bc ab} abbc
bcab
This works by walking the string a character at a time doing string comparisons starting at the current position.
In perl:
perl -E '
sub string_map {
my ($str, %map) = @_;
my $i = 0;
while ($i < length $str) {
KEYS:
for my $key (keys %map) {
if (substr($str, $i, length $key) eq $key) {
substr($str, $i, length $key) = $map{$key};
$i += length($map{$key}) - 1;
last KEYS;
}
}
$i++;
}
return $str;
}
say string_map("abbc", "ab"=>"bc", "bc"=>"ab");
'
bcab
The existing solutions fail when there are multiple parts to an extension. The function below works for multiple parts, a full path or just a a filename:
function removeExt($path)
{
$basename = basename($path);
return strpos($basename, '.') === false ? $path : substr($path, 0, - strlen($basename) + strlen(explode('.', $basename)[0]));
}
echo removeExt('https://example.com/file.php');
// https://example.com/file
echo removeExt('https://example.com/file.tar.gz');
// https://example.com/file
echo removeExt('file.tar.gz');
// file
echo removeExt('file');
// file
I had a similar problem, when I wanted to automatically remove temp files I had created. The solution I came up with was not to use command substitution, but rather to pass the name of the variable, that should take the final result, into the function. E.g.
#! /bin/bash
remove_later=""
new_tmp_file() {
file=$(mktemp)
remove_later="$remove_later $file"
eval $1=$file
}
remove_tmp_files() {
rm $remove_later
}
trap remove_tmp_files EXIT
new_tmp_file tmpfile1
new_tmp_file tmpfile2
So, in your case that would be:
#!/bin/bash
e=2
function test1() {
e=4
eval $1="hello"
}
test1 ret
echo "$ret"
echo "$e"
Works and has no restrictions on the "return value".
I've discovered that you can use eval to avoid using a subshell. Thus:
IFS=$'\n' eval 'echo "${my_array[*]}"'
jQuery .removeClass()
documentation.
One or more CSS classes to remove from the elements, these are separated by spaces.
if (mysql_query("INSERT INTO PEOPLE (NAME ) VALUES ('COLE')")or die(mysql_error())) {
echo 'Success';
} else {
echo 'Fail';
}
Although since you have or die(mysql_error())
it will show the mysql_error() on the screen when it fails. You should probably remove that if it isnt the desired result
Use the Maven debug option, ie mvn -X
:
Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...
In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml
.
with this simple code you can do that:
let el = $('<div></div>');
$(document.body).append(el);
el.html(`<html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html>`);
console.log(el.find('a[href="test0"]'));
No, you can't do this using Javascript alone. Client-side Javascript cannot read the contents of a directory the way I think you're asking about.
However, if you're able to add an index page to (or configure your web server to show an index page for) the images directory and you're serving the Javascript from the same server then you could make an AJAX call to fetch the index and then parse it.
i.e.
1) Enable indexes in Apache for the relevant directory on yoursite.com:
http://www.cyberciti.biz/faq/enabling-apache-file-directory-indexing/
2) Then fetch / parse it with jQuery. You'll have to work out how best to scrape the page and there's almost certainly a more efficient way of fetching the entire list, but an example:
$.ajax({
url: "http://yoursite.com/images/",
success: function(data){
$(data).find("td > a").each(function(){
// will loop through
alert("Found a file: " + $(this).attr("href"));
});
}
});
If you're using Rx, it's rather simple to plugin in rxjs-cluster to split work into parallel execution. (disclaimer: I'm the author)
onkeypress = > preventdefault ...
In Python 2.7 this might have worked fine:
>>> a = b = c = range(20)
>>> zip(a, b, c)
But in Python 3.4 it should be (otherwise, the result will be something like <zip object at 0x00000256124E7DC8>
):
>>> a = b = c = range(20)
>>> list(zip(a, b, c))
Is this what you are looking for.
$("input.address_field").on('click', function(){
$(this).css('border', '2px solid red');
});
I think your example is a sensible approach, although you could simplify it slightly as:
@title = tokens[Title].strip! || tokens[Title] if tokens[Title]
Alternative you could put it on two lines:
@title = tokens[Title] || ''
@title.strip!
While this isn't exactly specific to jQuery selectors/objects, in FireFox Quantum 58.x, you can find event handlers on an element using the Dev tools:
In page header, add
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-sacle=1, maximum-scale=1, user-scalable=no">
In page stylesheet, add
html, body {
overflow-x: hidden;
overflow-y: hidden;
}
It is both html and body!
You are reinventing the wheel. Normal PowerShell scripts have parameters starting with -
, like script.ps1 -server http://devserver
Then you handle them in param
section in the beginning of the file.
You can also assign default values to your params, read them from console if not available or stop script execution:
param (
[string]$server = "http://defaultserver",
[Parameter(Mandatory=$true)][string]$username,
[string]$password = $( Read-Host "Input password, please" )
)
Inside the script you can simply
write-output $server
since all parameters become variables available in script scope.
In this example, the $server
gets a default value if the script is called without it, script stops if you omit the -username
parameter and asks for terminal input if -password
is omitted.
Update: You might also want to pass a "flag" (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a "force" where the script runs in a more careful mode when force is not used.
The keyword for that is [switch]
parameter type:
param (
[string]$server = "http://defaultserver",
[string]$password = $( Read-Host "Input password, please" ),
[switch]$force = $false
)
Inside the script then you would work with it like this:
if ($force) {
//deletes a file or does something "bad"
}
Now, when calling the script you'd set the switch/flag parameter like this:
.\yourscript.ps1 -server "http://otherserver" -force
If you explicitly want to state that the flag is not set, there is a special syntax for that
.\yourscript.ps1 -server "http://otherserver" -force:$false
Links to relevant Microsoft documentation (for PowerShell 5.0; tho versions 3.0 and 4.0 are also available at the links):
having to pass context around everywhere is really annoying me. the code becomes too verbose and unmanageable. I do this in every project instead...
public class global {
public static Activity globalContext = null;
and set it in the main activity create
@Override
public void onCreate(Bundle savedInstanceState) {
Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
global.sdcardPath,
""));
super.onCreate(savedInstanceState);
//Start
//Debug.startMethodTracing("appname.Trace1");
global.globalContext = this;
also all preference keys should be language independent, I'm shocked nobody has mentioned that.
getText(R.string.yourPrefKeyName).toString()
now call it very simply like this in one line of code
global.globalContext.getSharedPreferences(global.APPNAME_PREF, global.MODE_PRIVATE).getBoolean("isMetric", true);
I had to edit ~/.subversion/servers
. I set store-plaintext-passwords = yes
(was no previously). That did the trick. It might be considered insecure though.
I had the same problem when I tried to install VS 2015 RC from ISO. It got stuck during Android SDK Setup (API Level 19 & 21, System Images). For me the problem was metered Wi-Fi connection. The installer didn't download necessary files.
Turning off the Internet connection resolved the problem. When installation finished, it said that some components were not installed and it will try to download and install them later.
Try to understand through this below function using python3
def floating_decimals(f_val, dec):
prc = "{:."+str(dec)+"f}" #first cast decimal as str
print(prc) #str format output is {:.3f}
return prc.format(f_val)
print(floating_decimals(50.54187236456456564, 3))
Output is : 50.542
Hope this helps you!
One option is to create a script file.
Right click on the database -> Tasks -> Generate Scripts
Then you can select all the stored procedures and generate the script with all the sps. So you can find the reference from there.
Or
-- Search in All Objects
SELECT OBJECT_NAME(OBJECT_ID),
definition
FROM sys.sql_modules
WHERE definition LIKE '%' + 'CreatedDate' + '%'
GO
-- Search in Stored Procedure Only
SELECT DISTINCT OBJECT_NAME(OBJECT_ID),
object_definition(OBJECT_ID)
FROM sys.Procedures
WHERE object_definition(OBJECT_ID) LIKE '%' + 'CreatedDate' + '%'
GO
Source SQL SERVER – Find Column Used in Stored Procedure – Search Stored Procedure for Column Name
You need to alias the subquery.
SELECT name FROM (SELECT name FROM agentinformation) a
or to be more explicit
SELECT a.name FROM (SELECT name FROM agentinformation) a
for me $('#element').val('...').change()
is the best way.
I work on Windows XP at work(state/gov), so I did my research and found this here and it worked for me. Hope this helps :)
The http_proxy Environment Variable
If you use a proxy server or firewall, you may need to set the http_proxy environment variable in order to access some url from commandline. Example : Installing ppm for perl or applying rpm in linux ,updating ubuntu
Set the http_proxy variable with the hostname or IP address of the proxy server: http_proxy=http:// [proxy.example.org]
If the proxy server requires a user name and password, include them in the following form: http_proxy=http:// [username:[email protected]]
If the proxy server uses a port other than 80, include the port number: http_proxy=http:// [username:[email protected]:8080]
Windows XP
- Open the Control Panel and click the System icon.
- On the Advanced tab, click on Environment Variables.
- Click New in the System variables panel.
- Add http_proxy with the appropriate proxy information (see examples above).
Linux, Solaris or HP-UX
Set the http_proxy environment variable using the command specific to your shell (e.g. set or export). To make this change persistent, add the command to the appropriate profile file for the shell. For example, in bash, add a line like the following to your .bash_profile or .bashrc file:
- http_proxy=http:// [username:password@hostname:port];
- export $http_proxy
sync
method first lists both source and destination paths and copies only differences (name, size etc.).
cp --recursive
method lists source path and copies (overwrites) all to the destination path.
If you have possible matches in the destination path, I would suggest sync
as one LIST request on the destination path will save you many unnecessary PUT requests - meaning cheaper and possibly faster.
I wrote this utility, it automatically generates the DSL code from a postgres database which you can then paste into dbdiagram.io/d website to get ER diagrams
The term "JPEG" is an acronym for the Joint Photographic Experts Group, which created the standard.
.jpeg
and .jpg
files are identical.
JPEG images are identified with 6 different standard file name extensions:
.jpg
.jpeg
.jpe
.jif
.jfif
.jfi
The jpg
was used in Microsoft Operating Systems when they only supported 3 chars-extensions.
The JPEG File Interchange Format (JFIF - last three extensions in my list) is an image file format standard for exchanging JPEG encoded files compliant with the JPEG Interchange Format (JIF) standard, solving some of JIF's limitations in regard. Image data in JFIF files is compressed using the techniques in the JPEG standard, hence JFIF is sometimes referred to as "JPEG/JFIF".
According to the error message, you declared myLoc
as a pointer to an NSInteger (NSInteger *myLoc
) rather than an actual NSInteger (NSInteger myLoc
). It needs to be the latter.
The serial communication manager library has many API and features targeted for the task you want. If the device is a USB-UART its VID/PID can be used. If the device is BT-SPP than platform specific APIs can be used. Take a look at this project for serial port programming: https://github.com/RishiGupta12/serial-communication-manager
In my case this error occured when I set up my environment adb path as ~/.android-sdk/platform-tools
(which happens when e.g. android-platform-tools is installed via homebrew), which version was 36, but Android Studio project has Android SDK next path ~/Library/Android/sdk
which adb version was 39.
I have changed my PATH to platform-tools to ~/Library/Android/sdk/platform-tools
and error was solved
put it in double quotes
echo "\t";
See: http://php.net/language.types.string#language.types.string.syntax.double
On macOS, one option is to install FUSE for macOS and use sshfs
to mount a remote directory:
mkdir local_dir
sshfs remote_user@remote_host:remote_dir/ local_dir
Some caveats apply with mounting network volumes, so YMMV.
Big O describes the fundamental scaling nature of an algorithm.
There is a lot of information that Big O does not tell you about a given algorithm. It cuts to the bone and gives only information about the scaling nature of an algorithm, specifically how the resource use (think time or memory) of an algorithm scales in response to the "input size".
Consider the difference between a steam engine and a rocket. They are not merely different varieties of the same thing (as, say, a Prius engine vs. a Lamborghini engine) but they are dramatically different kinds of propulsion systems, at their core. A steam engine may be faster than a toy rocket, but no steam piston engine will be able to achieve the speeds of an orbital launch vehicle. This is because these systems have different scaling characteristics with regards to the relation of fuel required ("resource usage") to reach a given speed ("input size").
Why is this so important? Because software deals with problems that may differ in size by factors up to a trillion. Consider that for a moment. The ratio between the speed necessary to travel to the Moon and human walking speed is less than 10,000:1, and that is absolutely tiny compared to the range in input sizes software may face. And because software may face an astronomical range in input sizes there is the potential for the Big O complexity of an algorithm, it's fundamental scaling nature, to trump any implementation details.
Consider the canonical sorting example. Bubble-sort is O(n2) while merge-sort is O(n log n). Let's say you have two sorting applications, application A which uses bubble-sort and application B which uses merge-sort, and let's say that for input sizes of around 30 elements application A is 1,000x faster than application B at sorting. If you never have to sort much more than 30 elements then it's obvious that you should prefer application A, as it is much faster at these input sizes. However, if you find that you may have to sort ten million items then what you'd expect is that application B actually ends up being thousands of times faster than application A in this case, entirely due to the way each algorithm scales.
In case the WebSocket server initiative disconnects the
ws
link after a few minutes there no messages sent between the server and client.
client sends a custom ping
message, to keep alive by using the keepAlive
function
server ignore the ping
message and response a custom pong
message
var timerID = 0;
function keepAlive() {
var timeout = 20000;
if (webSocket.readyState == webSocket.OPEN) {
webSocket.send('');
}
timerId = setTimeout(keepAlive, timeout);
}
function cancelKeepAlive() {
if (timerId) {
clearTimeout(timerId);
}
}
File.isFile()
is false
if the file / directory does not exist, so you can't use it to test whether you're trying to create a directory. But that's not the first issue here.
The issue is that the intermediate directories don't exist. You want to call f.mkdirs()
first.
contentType: 'application/x-www-form-urlencoded'
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");
You can check the size of an ArrayList
using the size()
method. This will return the maximum index +1
Your code would be like this:
int *p = (int *)0x28ff44;
int
needs to be the type of the object that you are referencing or it can be void
.
But be careful so that you don't try to access something that doesn't belong to your program.
Do right mouse click on your project, then select 'Open Module Settings' - then you can add modules to your project..
This will help
http://www.w3schools.com/php/func_array_unshift.asp
array_unshift();
I add the following code to /root/.bashrc to run the code only once,
Please commit the container to the image before run this script, otherwise the 'docker_services' file will be created in the images and no service will be run.
if [ ! -e /var/run/docker_services ]; then
echo "Starting services"
service mysql start
service ssh start
service nginx start
touch /var/run/docker_services
fi
To add on nathan gonzalez answer, please note you need to assign the replaced object after calling replace
function since it is not a mutator function:
myString = myString.replace('username1','');
The simple answer is to turn off async
. But that's the wrong thing to do. The correct answer is to re-think how you write the rest of your code.
Instead of writing this:
function functABC(){
$.ajax({
url: 'myPage.php',
data: {id: id},
success: function(data) {
return data;
}
});
}
function foo () {
var response = functABC();
some_result = bar(response);
// and other stuff and
return some_result;
}
You should write it like this:
function functABC(callback){
$.ajax({
url: 'myPage.php',
data: {id: id},
success: callback
});
}
function foo (callback) {
functABC(function(data){
var response = data;
some_result = bar(response);
// and other stuff and
callback(some_result);
})
}
That is, instead of returning result, pass in code of what needs to be done as callbacks. As I've shown, callbacks can be nested to as many levels as you have function calls.
A quick explanation of why I say it's wrong to turn off async:
Turning off async will freeze the browser while waiting for the ajax call. The user cannot click on anything, cannot scroll and in the worst case, if the user is low on memory, sometimes when the user drags the window off the screen and drags it in again he will see empty spaces because the browser is frozen and cannot redraw. For single threaded browsers like IE7 it's even worse: all websites freeze! Users who experience this may think you site is buggy. If you really don't want to do it asynchronously then just do your processing in the back end and refresh the whole page. It would at least feel not buggy.
Bill Burke has written a (nice article about class scanning] and then he wrote Scannotation.
Hibernate has this already written:
CDI might solve this, but don't know - haven't investigated fully yet
.
@Inject Instance< MyClass> x;
...
x.iterator()
Also for annotations:
abstract class MyAnnotationQualifier
extends AnnotationLiteral<Entity> implements Entity {}
I can confirm that there is no XPath support within Beautiful Soup.
To do this easily, the use of Stack
is better. Create a Stack
Then inside Stack add Align
or Positioned
and set position according to your needed, You can add multiple Container
.
Container
child: Stack(
children: <Widget>[
Align(
alignment: FractionalOffset.center,
child: Text(
"? 1000",
)
),
Positioned(
bottom: 0,
child: Container(
width: double.infinity,
height: 30,
child: Text(
"Balance", ,
)
),
)
],
)
)
Stack
a widget that positions its children relative to the edges of its box.
Stack
class is useful if you want to overlap several children in a simple way, for example having some text and an image, overlaid with a gradient and a button attached to the bottom.
This is the result from
library(scales)
show_col(hue_pal()(4))
show_col(hue_pal()(3))
You can specify an empty string as an argument to join, if no argument is specified a comma is used.
arr.join('');
You can do that using the gacutil
tool. In its simplest form:
gacutil /i yourdll.dll
You find the Visual Studio Command Prompt in the start menu under Programs -> Visual Studio -> Visual Studio Tools.
C++11 added alias declarations, which are generalization of typedef
, allowing templates:
template <size_t N>
using Vector = Matrix<N, 1>;
The type Vector<3>
is equivalent to Matrix<3, 1>
.
In C++03, the closest approximation was:
template <size_t N>
struct Vector
{
typedef Matrix<N, 1> type;
};
Here, the type Vector<3>::type
is equivalent to Matrix<3, 1>
.
I have been using python requests for async calls against github's gist API for some time.
For an example, see the code here:
https://github.com/davidthewatson/flasgist/blob/master/views.py#L60-72
This style of python may not be the clearest example, but I can assure you that the code works. Let me know if this is confusing to you and I will document it.
EasyFSM is a dynamic Java Library which can be used to implement an FSM.
You can find documentation for the same at : Finite State Machine in Java
Also, you can download the library at : Java FSM Library : DynamicEasyFSM
Thought I would add this module I found: https://www.npmjs.org/package/global-tunnel, which worked great for me (Worked immediately with all my code and third party modules with only the code below).
require('global-tunnel').initialize({
host: '10.0.0.10',
port: 8080
});
Do this once, and all http (and https) in your application goes through the proxy.
Alternately, calling
require('global-tunnel').initialize();
Will use the http_proxy
environment variable
=Join(Parameters!Product.Label, vbcrfl) for new line
Add the DLL as an existing item to one of the projects and it should be sorted
I read it like "When the iterable
is exhausted completely, and the execution is about to proceed to the next statement after finishing the for
, the else clause will be executed." Thus, when the iteration is broken by break
, this will not be executed.
Run
cordova -v
to see the currently running version. Run the npm info command
npm info cordova
for a longer listing that includes the current version along with other available version numbers
days
, years
, etc., are part of Active Support, So this won't work in irb
, but it should work in rails console
.
In some cases, doing it backwards could be sufficient. Add a class using javascript:
// Jquery
$('body').addClass('js-enabled');
/* CSS */
.menu-mobile {display:none;}
body.js-enabled .menu-mobile {display:block;}
This could create maintenance issues on anything complex, but it's a simple fix for some things. Rather than trying to detect when it's not loaded, just style according to when it is loaded.
I don't know if it will work on .NET 2.0, but it worked me on .NET 4.5.2. Here is the code:
using System;
using System.Drawing;
using System.Windows.Forms;
public partial class Your_Form_Name : Form
{
public Your_Form_Name()
{
InitializeComponent();
}
// CODE STARTS HERE
private System.Drawing.Size oldsize = new System.Drawing.Size(300, 300);
private System.Drawing.Point oldlocation = new System.Drawing.Point(0, 0);
private System.Windows.Forms.FormWindowState oldstate = System.Windows.Forms.FormWindowState.Normal;
private System.Windows.Forms.FormBorderStyle oldstyle = System.Windows.Forms.FormBorderStyle.Sizable;
private bool fullscreen = false;
/// <summary>
/// Goes to fullscreen or the old state.
/// </summary>
private void UpgradeFullscreen()
{
if (!fullscreen)
{
oldsize = this.Size;
oldstate = this.WindowState;
oldstyle = this.FormBorderStyle;
oldlocation = this.Location;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Bounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
fullscreen = true;
}
else
{
this.Location = oldlocation;
this.WindowState = oldstate;
this.FormBorderStyle = oldstyle;
this.Size = oldsize;
fullscreen = false;
}
}
// CODE ENDS HERE
}
Usage:
UpgradeFullscreen(); // Goes to fullscreen
UpgradeFullscreen(); // Goes back to normal state
// You don't need arguments.
Notice: You MUST place it inside your Form's class (Example:
partial class Form1 : Form { /* Code goes here */ }
) or it will not work because if you don't place it on any form, codethis
will create an exception.
I do it in a way that will cast any case insensitive version of the string "false" to the boolean FALSE, but will behave using the normal php casting rules for all other strings. I think this is the best way to prevent unexpected behavior.
$test_var = 'False';
$test_var = strtolower(trim($test_var)) == 'false' ? FALSE : $test_var;
$result = (boolean) $test_var;
Or as a function:
function safeBool($test_var){
$test_var = strtolower(trim($test_var)) == 'false' ? FALSE : $test_var;
return (boolean) $test_var;
}
Look at the WAITFOR command.
E.g.
-- wait for 1 minute
WAITFOR DELAY '00:01'
-- wait for 1 second
WAITFOR DELAY '00:00:01'
This command allows you a high degree of precision but is only accurate within 10ms - 16ms on a typical machine as it relies on GetTickCount. So, for example, the call WAITFOR DELAY '00:00:00:001'
is likely to result in no wait at all.
The best solution I have found is this:
function subtracMonth($currentMonth, $monthsToSubtract){
$finalMonth = $currentMonth;
for($i=0;$i<$monthsToSubtract;$i++) {
$finalMonth--;
if ($finalMonth=='0'){
$finalMonth = '12';
}
}
return $finalMonth;
}
So if we are in 3(March) and we want to subtract 5 months that would be
subtractMonth(3,5);
which would give 10(October). If the year is also desired, one could do this:
function subtracMonth($currentMonth, $monthsToSubtract){
$finalMonth = $currentMonth;
$totalYearsToSubtract = 0;
for($i=0;$i<$monthsToSubtract;$i++) {
$finalMonth--;
if ($finalMonth=='0'){
$finalMonth = '12';
$totalYearsToSubtract++;
}
}
//Get $currentYear
//Calculate $finalYear = $currentYear - $totalYearsToSubtract
//Put resulting $finalMonth and $finalYear into an object as attributes
//Return the object
}
or in a better way we can have like this
Let's say your primary key is an Integer and object you save is "ticket", then you can get it like this. When you save the object, id is always returned
//unboxing will occur here so that id here will be value type not the reference type. Now you can check id for 0 in case of save failure. like below:
int id = (Integer) session.save(ticket);
if(id==0)
your session.save call was not success.
else '
your call to session.save was successful.
Using 

Works in Chrome to create separate lines in a tooltip.
To change the default encoding used for all workspaces you can do the following:
Create a defaults.ini file in the Eclipse configuration folder. For example, if Eclipse is installed in C:/Eclipse
create C:/Eclipse/configuration/defaults.ini
. The file should contain:
org.eclipse.core.resources/encoding=UTF-8
If you want to set the line terminator to UNIX values you can also add:
org.eclipse.core.runtime/line.separator=\n
In eclipse.ini in the Eclipse install folder (e.g., C:/Eclipse
) add the following lines:
-plugincustomization
D:/Java/Eclipse/configuration/defaults.ini
You might need to play around with where you put it. Inserting it before the "-product" option seemed to work.
You have invoked Ant with the verbose (-v) mode but the default buildfile build.xml
does not exist. Nor have you specified any other buildfile
for it to use.
I would say your Ant installation is fine.
There are multiple ways to get the last inserted ID after insert command.
@@IDENTITY
: It returns the last Identity value generated on a Connection in current session, regardless of Table and the scope of statement that produced the valueSCOPE_IDENTITY()
: It returns the last identity value generated by the insert statement in the current scope in the current connection regardless of the table.IDENT_CURRENT(‘TABLENAME’)
: It returns the last identity value generated on the specified table regardless of Any connection, session or scope. IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. Now it seems more difficult to decide which one will be exact match for my requirement.
I mostly prefer SCOPE_IDENTITY().
If you use select SCOPE_IDENTITY() along with TableName in insert statement, you will get the exact result as per your expectation.
Source : CodoBee
There is definitely a way to do this -- use X() macros. These macros use the C preprocessor to construct enums, arrays and code blocks from a list of source data. You only need to add new items to the #define containing the X() macro. The switch statement would expand automatically.
Your example can be written as follows:
// Source data -- Enum, String
#define X_NUMBERS \
X(ONE, "one") \
X(TWO, "two") \
X(THREE, "three")
...
// Use preprocessor to create the Enum
typedef enum {
#define X(Enum, String) Enum,
X_NUMBERS
#undef X
} Numbers;
...
// Use Preprocessor to expand data into switch statement cases
switch(num)
{
#define X(Enum, String) \
case Enum: strcpy(num_str, String); break;
X_NUMBERS
#undef X
default: return 0; break;
}
return 1;
There are more efficient ways (i.e. using X Macros to create an string array and enum index), but this is the simplest demo.
In .Net Core (as of v2.2) it should be:
new Process
{
StartInfo = new ProcessStartInfo(@"file path")
{
UseShellExecute = true
}
}.Start();
Related github issue can be found here
You can encapsulate your block of code with a try ... catch statement, and when you run your code, if the column doesn't exist it will throw an exception. You can then figure out what specific exception it throws and have it handle that specific exception in a different way if you so desire, such as returning "Column Not Found".
If you are using variables, you can use
first_var="Hello"
second_var="How are you"
If you want to concat both string and write it to file, then use below
echo "${first_var} - ${second_var}" > ./file_name.txt
Your file_name.txt content will be "Hello - How are you"
You can KILL the processid.
mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id | User | Host | db | Command | Time | State | Info |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www | Sleep | 25946 | | NULL |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
mysql> kill 1193777;
But:
Or you configure your mysql-server by setting a shorter timeout on wait_timeout
and interactive_timeout
mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| connect_timeout | 5 |
| delayed_insert_timeout | 300 |
| innodb_lock_wait_timeout | 50 |
| interactive_timeout | 28800 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| slave_net_timeout | 3600 |
| table_lock_wait_timeout | 50 |
| wait_timeout | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)
Set with:
set global wait_timeout=3;
set global interactive_timeout=3;
(and also set in your configuration file, for when your server restarts)
But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...
Incase you're using pandas and your read_excel reads in Date formatted as Excel numbers improperly and need to recover the real dates behind...
The lambda function
applied on the column uses xlrd to recover the date back
import xlrd
df['possible_intdate'] = df['possible_intdate'].apply(lambda s: xlrd.xldate.xldate_as_datetime(s, 0))
>> df['possible_intdate']
dtype('<M8[ns]')
This line is the problem:
int estimatedPopulation (int currentPopulation,
float growthRate (birthRate, deathRate))
Make it:
int estimatedPopulation (int currentPopulation, float birthRate, float deathRate)
instead and invoke the function with three arguments like
estimatePopulation( currentPopulation, birthRate, deathRate );
OR declare it with two arguments like:
int estimatedPopulation (int currentPopulation, float growthrt ) { ... }
and call it as
estimatedPopulation( currentPopulation, growthRate (birthRate, deathRate));
Probably more important here - C++ (and C) names have scope. You can have two things named the same but not at the same time. In your particular case your grouthRate
variable in the main()
hides the function with the same name. So within main()
you can only access grouthRate
as float
. On the other hand, outside of the main()
you can only access that name as a function, since that automatic variable is only visible within the scope of main()
.
Just hope I didn't confuse you further :)
Your regex looks correct, but you're splitting
with it instead of matching
with it. You want something like this:
// Untested code
Matcher matcher = Pattern.compile("<%=(.*?)%>").matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}