The following functions (modified BFS with a recursive path-finding function between two nodes) will do the job for an acyclic graph:
from collections import defaultdict
# modified BFS
def find_all_parents(G, s):
Q = [s]
parents = defaultdict(set)
while len(Q) != 0:
v = Q[0]
Q.pop(0)
for w in G.get(v, []):
parents[w].add(v)
Q.append(w)
return parents
# recursive path-finding function (assumes that there exists a path in G from a to b)
def find_all_paths(parents, a, b):
return [a] if a == b else [y + b for x in list(parents[b]) for y in find_all_paths(parents, a, x)]
For example, with the following graph (DAG) G
given by
G = {'A':['B','C'], 'B':['D'], 'C':['D', 'F'], 'D':['E', 'F'], 'E':['F']}
if we want to find all paths between the nodes 'A'
and 'F'
(using the above-defined functions as find_all_paths(find_all_parents(G, 'A'), 'A', 'F')
), it will return the following paths:
Below is the pseudocode that may help you:
public String getBase64FromFile(String path)
{
Bitmap bmp = null;
ByteArrayOutputStream baos = null;
byte[] baat = null;
String encodeString = null;
try
{
bmp = BitmapFactory.decodeFile(path);
baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
baat = baos.toByteArray();
encodeString = Base64.encodeToString(baat, Base64.DEFAULT);
}
catch (Exception e)
{
e.printStackTrace();
}
return encodeString;
}
You can select every column from that sub-query by aliasing it and adding the alias before the *
:
SELECT t.*, a+b AS total_sum
FROM
(
SELECT SUM(column1) AS a, SUM(column2) AS b
FROM table
) t
I was given access to a database, but not the table where my query was being stored in.
Inspired by @marc_s answer, I had a look at HeidiSQL which is a Windows program that can deal with MySQL, SQL Server, and PostgreSQL.
I found that it can also search a database for a string.
It will search each table and give you how many times it found the string per table!
You could add
cd /some/directory/somewhere/named/Foo
to your .bashrc
file (or .profile
or whatever you call it) at the other host. That way, no matter what you do or where you ssh
from, whenever you log onto that server, it will cd
to the proper directory for you, and all you have to do is use ssh
like normal.
Of curse, rogeriopvl's solution works too, but it's a tad bit more verbose, and you have to remember to do it every time (unless you make an alias) so it seems a bit less "fun".
It's called an initialization list. An initializer list is how you pass arguments to your member variables' constructors and for passing arguments to the parent class's constructor.
If you use =
to assign in the constructor body, first the default constructor is called, then the assignment operator is called. This is a bit wasteful, and sometimes there's no equivalent assignment operator.
Had the exact same issue. I installed curl 7.19 to /opt/curl/ to make sure that I would not affect current curl on our production servers. Once I linked libcurl.so.4 to /usr/lib:
sudo ln -s /opt/curl/lib/libcurl.so /usr/lib/libcurl.so.4
I still got the same error! Durf.
But running ldconfig make the linkage for me and that worked. No need to set the LD_RUN_PATH or LD_LIBRARY_PATH at all. Just needed to run ldconfig.
Invoking an empty time.Time
struct literal will return Go's zero date. Thus, for the following print statement:
fmt.Println(time.Time{})
The output is:
0001-01-01 00:00:00 +0000 UTC
For the sake of completeness, the official documentation explicitly states:
The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.
The EOF pattern needs a prime read to 'bootstrap' the EOF checking process. Consider the empty file will not initially have its EOF set until the first read. The prime read will catch the EOF in this instance and properly skip the loop completely.
What you need to remember here is that you don't get the EOF until the first attempt to read past the available data of the file. Reading the exact amount of data will not flag the EOF.
I should point out if the file was empty your given code would have printed since the EOF will have prevented a value from being set to x on entry into the loop.
So add a prime read and move the loop's read to the end:
int x;
iFile >> x; // prime read here
while (!iFile.eof()) {
cerr << x << endl;
iFile >> x;
}
You should post a message from frame to parent, after loaded.
frame script:
$(document).ready(function() {
window.parent.postMessage("I'm loaded", "*");
});
And listen it in parent:
function listenMessage(msg) {
alert(msg);
}
if (window.addEventListener) {
window.addEventListener("message", listenMessage, false);
} else {
window.attachEvent("onmessage", listenMessage);
}
Use this link for more info: http://en.wikipedia.org/wiki/Web_Messaging
You can use IIF for a similar result.
Note that you can nest the IIF statements to handle multiple cases. There is an example here: http://forums.devshed.com/database-management-46/query-ms-access-iif-statement-multiple-conditions-358130.html
SELECT IIf([Combinaison] = "Mike", 12, IIf([Combinaison] = "Steve", 13)) As Answer
FROM MyTable;
It's also worth checking out this bug report, which was closed with reason "Not a defect" and the following text:
"Autoboxing of entire arrays is not specified behavior, for good reason. It can be prohibitively expensive for large arrays."
ok, here's another option, if you want a relative include...
<script> window.$ = window.jQuery = require('./assets/scripts/jquery-3.2.1.min.js') </script>
I was using something along the lines of the currently accepted answer in order to send emails with an attached binary error log file. GMail and K-9 send it just fine and it also arrives fine on my mail server. The only problem was my mail client of choice Thunderbird which had troubles with opening / saving the attached log file. In fact it simply didn't save the file at all without complaining.
I took a look at one of these mail's source codes and noticed that the log file attachment had (understandably) the mime type message/rfc822
. Of course that attachment is not an attached email. But Thunderbird cannot cope with that tiny error gracefully. So that was kind of a bummer.
After a bit of research and experimenting I came up with the following solution:
public Intent createEmailOnlyChooserIntent(Intent source,
CharSequence chooserTitle) {
Stack<Intent> intents = new Stack<Intent>();
Intent i = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",
"[email protected]", null));
List<ResolveInfo> activities = getPackageManager()
.queryIntentActivities(i, 0);
for(ResolveInfo ri : activities) {
Intent target = new Intent(source);
target.setPackage(ri.activityInfo.packageName);
intents.add(target);
}
if(!intents.isEmpty()) {
Intent chooserIntent = Intent.createChooser(intents.remove(0),
chooserTitle);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
intents.toArray(new Parcelable[intents.size()]));
return chooserIntent;
} else {
return Intent.createChooser(source, chooserTitle);
}
}
It can be used as follows:
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("*/*");
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(crashLogFile));
i.putExtra(Intent.EXTRA_EMAIL, new String[] {
ANDROID_SUPPORT_EMAIL
});
i.putExtra(Intent.EXTRA_SUBJECT, "Crash report");
i.putExtra(Intent.EXTRA_TEXT, "Some crash report details");
startActivity(createEmailOnlyChooserIntent(i, "Send via email"));
As you can see, the createEmailOnlyChooserIntent method can be easily fed with the correct intent and the correct mime type.
It then goes through the list of available activities that respond to an ACTION_SENDTO mailto
protocol intent (which are email apps only) and constructs a chooser based on that list of activities and the original ACTION_SEND intent with the correct mime type.
Another advantage is that Skype is not listed anymore (which happens to respond to the rfc822 mime type).
The selected answer does not work.
declare @str varchar(50)='79D136'
select 1 where @str NOT LIKE '%[^0-9]%'
I don't have a solution but know of this potential pitfall. The same goes if you substitute the letter 'D' for 'E' which is scientific notation.
Notification mNotification = new Notification.Builder(this)
.setContentTitle("A message from: " + fromUser)
.setContentText(msg)
.setAutoCancel(true)
.setSmallIcon(R.drawable.app_icon)
.setContentIntent(pIntent)
.build();
.setAutoCancel(true)
when you click on notification, open corresponding activity and remove notification from notification bar
''' Set Range you want to export to the folder
Workbooks("your workbook name").Sheets("yoursheet name").Select
Dim rgExp As Range: Set rgExp = Range("A1:H31")
''' Copy range as picture onto Clipboard
rgExp.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
''' Create an empty chart with exact size of range copied
With ActiveSheet.ChartObjects.Add(Left:=rgExp.Left, Top:=rgExp.Top, _
Width:=rgExp.Width, Height:=rgExp.Height)
.Name = "ChartVolumeMetricsDevEXPORT"
.Activate
End With
''' Paste into chart area, export to file, delete chart.
ActiveChart.Paste
ActiveSheet.ChartObjects("ChartVolumeMetricsDevEXPORT").Chart.Export "C:\ExportmyChart.jpg"
ActiveSheet.ChartObjects("ChartVolumeMetricsDevEXPORT").Delete
For Linux users (I'm using a Debian Distro, Kali) Here's how I resolved mine.
If you don't already have jdk-8, you want to get it at oracle's site
https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
I got the jdk-8u191-linux-x64.tar.gz
Step 1 - Installing Java Move and unpack it at a suitable location like so
$ mv jdk-8u191-linux-x64.tar.gz /suitablelocation/
$ tar -xzvf /suitablelocation/jdk-8u191-linux-x64.tar.gz
You should get an unzipped folder like jdk1.8.0_191 You can delete the tarball afterwards to conserve space
Step 2 - Setting up alternatives to the default java location
$ update-alternatives --install /usr/bin/java java /suitablelocation/jdk1.8.0_191/bin/java 1
$ update-alternatives --install /usr/bin/javac javac /suitablelocation/jdk1.8.0_191/bin/javac 1
Step 3 - Selecting your alternatives as default
$ update-alternatives --set java /suitablelocation/jdk1.8.0_191/bin/java
$ update-alternatives --set javac /suitablelocation/jdk1.8.0_191/bin/javac
Step 4 - Confirming default java version
$ java -version
Notes
Since Python 3.3, you can use the class ExitStack
from the contextlib
module to safely
open an arbitrary number of files.
It can manage a dynamic number of context-aware objects, which means that it will prove especially useful if you don't know how many files you are going to handle.
In fact, the canonical use-case that is mentioned in the documentation is managing a dynamic number of files.
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# All opened files will automatically be closed at the end of
# the with statement, even if attempts to open files later
# in the list raise an exception
If you are interested in the details, here is a generic example in order to explain how ExitStack
operates:
from contextlib import ExitStack
class X:
num = 1
def __init__(self):
self.num = X.num
X.num += 1
def __repr__(self):
cls = type(self)
return '{cls.__name__}{self.num}'.format(cls=cls, self=self)
def __enter__(self):
print('enter {!r}'.format(self))
return self.num
def __exit__(self, exc_type, exc_value, traceback):
print('exit {!r}'.format(self))
return True
xs = [X() for _ in range(3)]
with ExitStack() as stack:
print(len(stack._exit_callbacks)) # number of callbacks called on exit
nums = [stack.enter_context(x) for x in xs]
print(len(stack._exit_callbacks))
print(len(stack._exit_callbacks))
print(nums)
Output:
0
enter X1
enter X2
enter X3
3
exit X3
exit X2
exit X1
0
[1, 2, 3]
the "title"
attribute will be used as the text for tooltip by the browser, if you want to apply style to it consider using some plugins
You can use the following line of code in the activity's onCreate method to make sure the keyboard only pops up when a user clicks into an EditText
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
In express.js (since version 3) you should use that syntax:
var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey = fs.readFileSync('sslcert/server.key', 'utf8');
var certificate = fs.readFileSync('sslcert/server.crt', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();
// your express configuration here
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
httpServer.listen(8080);
httpsServer.listen(8443);
In that way you provide express middleware to the native http/https server
If you want your app running on ports below 1024, you will need to use sudo
command (not recommended) or use a reverse proxy (e.g. nginx, haproxy).
With Perl, use Encode::Detect.
The following code can be used to read the input string from a user. But it's space is limited to 64.
char word[64] = { '\0' }; //initialize all elements with '\0'
int i = 0;
while ((word[i] != '\n')&& (i<64))
{
scanf_s("%c", &word[i++], 1);
}
According to WikiPedia, you can specify which favicon file to load using the link
tag in the head
section, with a parameter of rel="icon"
.
For example:
<link rel="icon" type="image/png" href="/path/image.png">
I imagine if you wanted to write some dynamic content for that call, you would have access to cookies so you could retrieve your session information that way and present appropriate content.
You may fall foul of file formats (IE reportedly only supports it's .ICO format, whilst most everyone else supports PNG and GIF images) and possibly caching issues, both on the browser and through proxies. This would be because of the original itention of favicon, specifically, for marking a bookmark with a site's mini-logo.
Try this as root (maybe you can use sudo
or su
):
/etc/init.d/postgresql restart
Without any argument the script also gives you a hint on how to restart a specific version
[Uqbar@Feynman ~] /etc/init.d/postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force-reload|status} [version ...]
Similarly, in case you have it, you can also use the service
tool:
[Uqbar@Feynman ~] service postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force reload|status} [version ...]
Please, pay attention to the optional [version ...]
trailing argument.
That's meant to allow you, the user, to act on a specific version, in case you were running multiple ones. So you can restart version X while keeping version Y and Z untouched and running.
Finally, in case you are running systemd, then you can use systemctl
like this:
[support@Feynman ~] systemctl status postgresql
? postgresql.service - PostgreSQL database server
Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: disabled)
Active: active (running) since Wed 2017-11-14 12:33:35 CET; 7min ago
...
You can replace status
with stop
, start
or restart
as well as other actions. Please refer to the documentation for full details.
In order to operate on multiple concurrent versions, the syntax is slightly different. For example to stop v12
and reload v13
you can run:
systemctl stop postgresql-12.service
systemctl reload postgresql-13.service
Thanks to @Jojo for pointing me to this very one.
Finally Keep in mind that root
permissions may be needed for non-informative tasks as in the other cases seen earlier.
I think for pretty-printing something, it's very helpful to know its structure.
To get the structure you have to parse it. Because of this, I don't think it gets much easier than first parsing the JSON string you have and then using the pretty-printing method toString mentioned in the comments above.
Of course you can do similar with any JSON library you like.
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
.Net framework of the referencing dll should be same as the .Net framework version of the Project in which dll is referred
In C++ you can create conversion operators, operators that allow the compiler to convert between your types and other defined types. There are two types of conversion operators, implicit and explicit ones.
An implicit conversion operator allows the compiler to implicitly convert (like the conversion between int
and long
) the value of a user-defined type to some other type.
The following is a simple class with an implicit conversion operator:
class my_string {
public:
operator const char*() const {return data_;} // This is the conversion operator
private:
const char* data_;
};
Implicit conversion operators, like one-argument constructors, are user-defined conversions. Compilers will grant one user-defined conversion when trying to match a call to an overloaded function.
void f(const char*);
my_string str;
f(str); // same as f( str.operator const char*() )
At first this seems very helpful, but the problem with this is that the implicit conversion even kicks in when it isn’t expected to. In the following code, void f(const char*)
will be called because my_string()
is not an lvalue, so the first does not match:
void f(my_string&);
void f(const char*);
f(my_string());
Beginners easily get this wrong and even experienced C++ programmers are sometimes surprised because the compiler picks an overload they didn’t suspect. These problems can be mitigated by explicit conversion operators.
Unlike implicit conversion operators, explicit conversion operators will never kick in when you don't expect them to. The following is a simple class with an explicit conversion operator:
class my_string {
public:
explicit operator const char*() const {return data_;}
private:
const char* data_;
};
Notice the explicit
. Now when you try to execute the unexpected code from the implicit conversion operators, you get a compiler error:
prog.cpp: In function ‘int main()’: prog.cpp:15:18: error: no matching function for call to ‘f(my_string)’ prog.cpp:15:18: note: candidates are: prog.cpp:11:10: note: void f(my_string&) prog.cpp:11:10: note: no known conversion for argument 1 from ‘my_string’ to ‘my_string&’ prog.cpp:12:10: note: void f(const char*) prog.cpp:12:10: note: no known conversion for argument 1 from ‘my_string’ to ‘const char*’
To invoke the explicit cast operator, you have to use static_cast
, a C-style cast, or a constructor style cast ( i.e. T(value)
).
However, there is one exception to this: The compiler is allowed to implicitly convert to bool
. In addition, the compiler is not allowed to do another implicit conversion after it converts to bool
(a compiler is allowed to do 2 implicit conversions at a time, but only 1 user-defined conversion at max).
Because the compiler will not cast "past" bool
, explicit conversion operators now remove the need for the Safe Bool idiom. For example, smart pointers before C++11 used the Safe Bool idiom to prevent conversions to integral types. In C++11, the smart pointers use an explicit operator instead because the compiler is not allowed to implicitly convert to an integral type after it explicitly converted a type to bool.
Continue to Overloading new
and delete
.
The underlying issue is using max-device-width
vs plain old max-width
.
Using the "device" keyword targets physical dimension of the screen, not the width of the browser window.
For example:
@media only screen and (max-device-width: 480px) {
/* STYLES HERE for DEVICES with physical max-screen width of 480px */
}
Versus
@media only screen and (max-width: 480px) {
/* STYLES HERE for BROWSER WINDOWS with a max-width of 480px.
This will work on desktops when the window is narrowed. */
}
I have to say your workflow is not in a standard Android way. In Android, you don't need to finish()
your activity if you want to open another activity from Intent. As for user's convenience, Android allows user to use 'back' key to go back from the activity that you opened to your app.
So just let the system stop you activity and save anything need to when you activity is called back.
You should use django methods, like exists. Its there for you to use it.
if qs.exists():
return qs[0]
return None
The accepted answer didn't work for me for two reasons:
BackColor
set so setting AutoSize = false
and Dock = Fill
causes the background color to fill the whole formAutoSize
set to false anyway because my label text was dynamicInstead, I simply used the form's width and the width of the label to calculate the left offset:
MyLabel.Left = (this.Width - MyLabel.Width) / 2;
ajavascript have two type of annotation for fetching javascript Object properties:
Obj = {};
1) (.) annotation eg. Obj.id this will only work if the object already have a property with name 'id'
2) ([]) annotation eg . Obj[id] here if the object does not have any property with name 'id',it will create a new property with name 'id'.
so for below example:
A new property will be created always when you write Obj[name]. And if the property already exist with the same name it will override it.
const obj = {}
jQuery(itemsFromDom).each(function() {
const element = jQuery(this)
const name = element.attr('id')
const value = element.attr('value')
// This will work
obj[name]= value;
})
The following command gives me all the files that do not contain the pattern foo
:
find . -not -ipath '.*svn*' -exec grep -H -E -o -c "foo" {} \; | grep 0
There isn’t really an ideal conversion, but I would like to supply a couple of options.
java.time
First, you should use LocalDate
from java.time, the modern Java date and time API, for parsing and holding your date. Avoid Date
and SimpleDateFormat
since they have design problems and also are long outdated. The latter in particular is notoriously troublesome.
DateTimeFormatter originalDateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
String dateString = "13/06/1983";
LocalDate date = LocalDate.parse(dateString, originalDateFormatter);
System.out.println(date);
The output is:
1983-06-13
Do you need to go any further? LocalDate.toString()
produces the format you asked about.
Format and parse
Assuming that you do require an XMLGregorianCalendar
the first and easy option for converting is:
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(date.toString());
System.out.println(xmlDate);
1983-06-13
Formatting to a string and parsing it back feels like a waste to me, but as I said, it’s easy and I don’t think that there are any surprises about the result being as expected.
Pass year, month and day of month individually
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
.newXMLGregorianCalendarDate(date.getYear(), date.getMonthValue(),
date.getDayOfMonth(), DatatypeConstants.FIELD_UNDEFINED);
The result is the same as before. We need to make explicit that we don’t want a time zone offset (this is what DatatypeConstants.FIELD_UNDEFINED
specifies). In case someone is wondering, both LocalDate
and XMLGregorianCalendar
number months the way humans do, so there is no adding or subtracting 1.
Convert through GregorianCalendar
I only show you this option because I somehow consider it the official way: convert LocalDate
to ZonedDateTime
, then to GregorianCalendar
and finally to XMLGregorianCalendar
.
ZonedDateTime dateTime = date.atStartOfDay(ZoneOffset.UTC);
GregorianCalendar gregCal = GregorianCalendar.from(dateTime);
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(gregCal);
xmlDate.setTime(DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED,
DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED);
xmlDate.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
I like the conversion itself since we neither need to use strings nor need to pass individual fields (with care to do it in the right order). What I don’t like is that we have to pass a time of day and a time zone offset and then wipe out those fields manually afterwards.
Try the following:
import time
timeout = time.time() + 60*5 # 5 minutes from now
while True:
test = 0
if test == 5 or time.time() > timeout:
break
test = test - 1
You may also want to add a short sleep here so this loop is not hogging CPU (for example time.sleep(1)
at the beginning or end of the loop body).
The core idea given here seems to me to be the best approach for this problem. Unfortunately, it has received less votes while the later answer that has more votes is not complete (as observed in the comments). Hopefully, the implementation below provides a short and complete solution for truncation.
def trunc(num, digits):_x000D_
l = str(float(num)).split('.')_x000D_
digits = min(len(l[1]), digits)_x000D_
return (l[0]+'.'+l[1][:digits])
_x000D_
which should take care of all corner cases found here and here.
ALTER TABLE TableName
ADD NewColumnName INTEGER,
FOREIGN KEY(NewColumnName) REFERENCES [ForeignKey_TableName](Foreign_Key_Column)
It is not necessary to have two routes.
Simply add
(/*)?
at the end of yourpath
string.For example,
app.get('/hello/world(/*)?' /* ... */)
Here is a fully working example, feel free to copy and paste this into a .js file to run with node, and play with it in a browser (or curl):
const app = require('express')()
// will be able to match all of the following
const test1 = 'http://localhost:3000/hello/world'
const test2 = 'http://localhost:3000/hello/world/'
const test3 = 'http://localhost:3000/hello/world/with/more/stuff'
// but fail at this one
const failTest = 'http://localhost:3000/foo/world'
app.get('/hello/world(/*)?', (req, res) => res.send(`
This will match at example endpoints: <br><br>
<pre><a href="${test1}">${test1}</a></pre>
<pre><a href="${test2}">${test2}</a></pre>
<pre><a href="${test3}">${test3}</a></pre>
<br><br> Will NOT match at: <pre><a href="${failTest}">${failTest}</a></pre>
`))
app.listen(3000, () => console.log('Check this out in a browser at http://localhost:3000/hello/world!'))
I think this is the syntax you are looking for:
if [ -z != $errorstatus ]
then
commands
else
commands
fi
I did it using String map (if you're working with String Map).
for (Object obj : dados.entrySet()) {
Map.Entry<String, String> entry = (Map.Entry) obj;
System.out.print("Key: " + entry.getKey());
System.out.println(", Value: " + entry.getValue());
}
You can use this jquery select change event for get selected option value
$(document).ready(function () { _x000D_
$('body').on('change','#select', function() {_x000D_
$('#show_selected').val(this.value);_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html> _x000D_
<html> _x000D_
<title>Learn Jquery value Method</title>_x000D_
<head> _x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> _x000D_
</head> _x000D_
<body> _x000D_
<select id="select">_x000D_
<option value="">Select One</option>_x000D_
<option value="PHP">PHP</option>_x000D_
<option value="jAVA">JAVA</option>_x000D_
<option value="Jquery">jQuery</option>_x000D_
<option value="Python">Python</option>_x000D_
<option value="Mysql">Mysql</option>_x000D_
</select>_x000D_
<br><br> _x000D_
<input type="text" id="show_selected">_x000D_
</body> _x000D_
</html>
_x000D_
I know, it is too late, but for others: I highly recommended use PURL jquery plugin. Motivation for PURL is that url can be segmented by '#' too (example: angular.js links), i.e. url could looks like
http://test.com/#/about/us/
or
http://test.com/#sky=blue&grass=green
And with PURL you can easy decide (segment/fsegment) which segment you want to get.
For "classic" last segment you could write:
var url = $.url('http://test.com/dir/index.html?key=value');
var lastSegment = url.segment().pop(); // index.html
A scroll pane is a container which contains another component. You can't add your text area to two different scroll panes. The scroll pane takes care of the horizontal and vertical scroll bars.
And if you never add the scroll pane to the frame, it will never be visible.
Read the swing tutorial about scroll panes.
I am using rails 4.0 and ran into the same problem
Here is my solution that passed test
add to Gemfile
gem 'bootstrap-sass'
run
bundle install
then add to app/assets/javascripts/application.js
//= require bootstrap
Then the dropdown should work
By the way, Chris's solution also work for me.
But I think it is less conform to the asset pipeline idea
Now, back to your questions:
Q1. Does this sequence generator make use of the database's increasing numeric value generating capability or generates the number on its own?
By using the GenerationType.SEQUENCE
strategy on the @GeneratedValue
annotation, the JPA provider will try to use a database sequence object of the underlying database that supports this feature (e.g., Oracle, SQL Server, PostgreSQL, MariaDB).
If you are using MySQL, which doesn't support database sequence objects, then Hibernate is going to fall back to using the GenerationType.TABLE
instead, which is undesirable since the TABLE generation performs badly.
So, don't use the GenerationType.SEQUENCE
strategy with MySQL.
Q2. If JPA uses a database auto-increment feature, then will it work with datastores that don't have auto-increment feature?
I assume you are talking about the GenerationType.IDENTITY
when you say database auto-increment feature
.
To use an AUTO_INCREMENT
or IDENTITY
column, you need to use the GenerationType.IDENTITY
strategy on the @GeneratedValue
annotation.
Q3. If JPA generates numeric value on its own, then how does the JPA implementation know which value to generate next? Does it consult with the database first to see what value was stored last in order to generate the value (last + 1)?
The only time when the JPA provider generates values on its own is when you are using the sequence-based optimizers, like:
These optimizers are meat to reduce the number of database sequence calls, so they multiply the number of identifier values that can be generated using a single database sequence call.
To avoid conflicts between Hibernate identifier optimizers and other 3rd-party clients, you should use pooled
or pooled-lo
instead of hi/lo
. Even if you are using a legacy application that was designed to use hi/lo, you can migrate to the pooled
or pooled-lo
optimizers.
Q4. Please also shed some light on
sequenceName
andallocationSize
properties of@SequenceGenerator
annotation.
The sequenceName
attribute defines the database sequence object to be used to generate the identifier values. IT's the object you created using the CREATE SEQUENCE
DDL statement.
So, if you provide this mapping:
@Id
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "seq_post"
)
@SequenceGenerator(
name = "seq_post"
)
private Long id;
Hibernate is going to use the seq_post
database object to generate the identifier values:
SELECT nextval('hibernate_sequence')
The allocationSize
defines the identifier value multiplier, and if you provide a value that's greater than 1, then Hibernate is going to use the pooled
optimizer, to reduce the number of database sequence calls.
So, if you provide this mapping:
@Id
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "seq_post"
)
@SequenceGenerator(
name = "seq_post",
allocationSize = 5
)
private Long id;
Then, when you persist 5 entities:
for (int i = 1; i <= 5; i++) {
entityManager.persist(
new Post().setTitle(
String.format(
"High-Performance Java Persistence, Part %d",
i
)
)
);
}
Only 2 database sequence calls will be executed, instead of 5:
SELECT nextval('hibernate_sequence')
SELECT nextval('hibernate_sequence')
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 1', 1)
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 2', 2)
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 3', 3)
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 4', 4)
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 5', 5)
The easiest way to understand the difference is to think of the different possibilities. There are two objects to consider, the pointer and the object pointed to (in this case 'a' is the name of the pointer, the object pointed to is unnamed, of type char). The possibilities are:
These different possibilities can be expressed in C as follows:
I hope this illustrates the possible differences
You should use profiles.
<profiles>
<profile>
<id>otherOutputDir</id>
<build>
<directory>yourDirectory</directory>
</build>
</profile>
</profiles>
And start maven with your profile
mvn compile -PotherOutputDir
If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :
<properties>
<buildDirectory>${project.basedir}/target</buildDirectory>
</properties>
<build>
<directory>${buildDirectory}</directory>
</build>
And compile like this :
mvn compile -DbuildDirectory=test
That's because you can't change the target directory by using -Dproject.build.directory
Quick/Easy Fix:
Use JQuery .toggle() to show/hide the rows onclick of either Row or an Anchor.
A function will need to be written to identify the rows you would like hidden, but toggle creates the functionality you are looking for.
what is the way to retrieve a Date object so that its always in GMT?
Instant.now()
You are using troublesome confusing old date-time classes that are now supplanted by the java.time classes.
Instant
= UTCThe Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ; // Current moment in UTC.
To exchange this data as text, use the standard ISO 8601 formats exclusively. These formats are sensibly designed to be unambiguous, easy to process by machine, and easy to read across many cultures by people.
The java.time classes use the standard formats by default when parsing and generating strings.
String output = instant.toString() ;
2017-01-23T12:34:56.123456789Z
If you want to see that same moment as presented in the wall-clock time of a particular region, apply a ZoneId
to get a ZonedDateTime
.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Asia/Singapore" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same simultaneous moment, same point on the timeline.
See this code live at IdeOne.com.
Notice the eight hour difference, as the time zone of Asia/Singapore
currently has an offset-from-UTC of +08:00. Same moment, different wall-clock time.
instant.toString(): 2017-01-23T12:34:56.123456789Z
zdt.toString(): 2017-01-23T20:34:56.123456789+08:00[Asia/Singapore]
Avoid the legacy java.util.Date
class. But if you must, you can convert. Look to new methods added to the old classes.
java.util.Date date = Date.from( instant ) ;
…going the other way…
Instant instant = myJavaUtilDate.toInstant() ;
For date-only, use LocalDate
.
LocalDate ld = zdt.toLocalDate() ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
To get date and time of your zone.
Date date = new Date();
DateFormat df = new SimpleDateFormat("MM/dd/YYYY HH:mm a");
df.setTimeZone(TimeZone.getDefault());
df.format(date);
I tried the solutions given here while working on an application that used Bluetooth Low Energy(BLE). I tried,
all of these failed.
What I did was debug the points where I thought I was getting the warning, I still got the warning but the application was working fine. You can disregard the warning.
I had a NavLink that I wanted to when clicked will scroll to that element like named anchor does. I implemented it this way.
<NavLink onClick={() => this.scrollToHref('plans')}>Our Plans</NavLink>
scrollToHref = (element) =>{
let node;
if(element === 'how'){
node = ReactDom.findDOMNode(this.refs.how);
console.log(this.refs)
}else if(element === 'plans'){
node = ReactDom.findDOMNode(this.refs.plans);
}else if(element === 'about'){
node = ReactDom.findDOMNode(this.refs.about);
}
node.scrollIntoView({block: 'start', behavior: 'smooth'});
}
I then give the component I wanted to scroll to a ref like this
<Investments ref="plans"/>
After researching a little bit all of the answers, I came up with a solution that worked just fine with my JavaScript functions across browsers (Including consoles / Dev Tools) :
<?php
// PHP Version 7.2.1 (Windows 10 x86)
function json2xml( $domNode ) {
foreach( $domNode -> childNodes as $node) {
if ( $node -> hasChildNodes() ) { json2xml( $node ); }
else {
if ( $domNode -> hasAttributes() && strlen( $domNode -> nodeValue ) ) {
$domNode -> setAttribute( "nodeValue", $node -> textContent );
$node -> nodeValue = "";
}
}
}
}
function jsonOut( $file ) {
$dom = new DOMDocument();
$dom -> loadXML( file_get_contents( $file ) );
json2xml( $dom );
header( 'Content-Type: application/json' );
return str_replace( "@", "", json_encode( simplexml_load_string( $dom -> saveXML() ), JSON_PRETTY_PRINT ) );
}
$output = jsonOut( 'https://boxelizer.com/assets/a1e10642e9294f39/b6f30987f0b66103.xml' );
echo( $output );
/*
Or simply
echo( jsonOut( 'https://boxelizer.com/assets/a1e10642e9294f39/b6f30987f0b66103.xml' ) );
*/
?>
It basically creates a new DOMDocument, loads and XML file into it and traverses through each one of the nodes and children getting the data / parameters and exporting it into JSON without the annoying "@" signs.
Link to the XML file.
If you're using jQuery then there are a few different ways to set the disabled attribute.
var $element = $(...);
$element.prop('disabled', true);
$element.attr('disabled', true);
// The following do not require jQuery
$element.get(0).disabled = true;
$element.get(0).setAttribute('disabled', true);
$element[0].disabled = true;
$element[0].setAttribute('disabled', true);
This is like passing a pointer to a pointer in C. In .NET this will allow you to change what the original T refers to, personally though I think if you are doing that in .NET you have probably got a design issue!
You could do it as follows - with validation just to ensure that the datepicker is bound to the element.
var dt;
if ($("div#someID").is('.hasDatepicker')) {
dt = $("div#someID").datepicker('getDate');
}
IF you want to install Maven in Eclipse(Java EE) Indigo Then follow these Steps :
Eclipse -> Help -> Install New Software.
Type " http://download.eclipse.org/releases/indigo/ " & Hit Enter.
Expand " Collaboration " tag.
Select Maven plugin from there.
Click on next .
Accept the agreement & click finish.
After installing the maven it will ask for restarting the Eclipse,So restart the eclipse again to see the changes.
Go to Phone Settings --> Developer Options --> Simulate Secondary Displays
and turn it to None
.
If you don't see Developer Options
in the settings menu
(it should be at the bottom, go Settings ==> About phone
and tap on the Build number
a lot of times)
It seems that your server fails to establish a connection to Gmail SMTP server. Here are some hints to troubleshoot this: 1) check if SSL correctly configured on your PHP (module that handle it isn't installed by default on PHP. You have to check your configuration in phph.ini). 2) check if your firewall let outgoing calls to the required port (here 465 or 587). Use telnet to do so. If the port isn't opened, you'll then require some support from sysdmin to setup the config. I hope you'll sort this out quickly!
Your issue here is that you're not understanding the scope that you're setting.
You are passing the ready
function a function itself. Within this function, you're creating another function called codeAddress
. This one exists within the scope that created it and not within the window object (where everything and its uncle could call it).
For example:
var myfunction = function(){
var myVar = 12345;
};
console.log(myVar); // 'undefined' - since it is within
// the scope of the function only.
Have a look here for a bit more on anonymous functions: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
Another thing is that I notice you're using jQuery on that page. This makes setting click handlers much easier and you don't need to go into the hassle of setting the 'onclick' attribute in the HTML. You also don't need to make the codeAddress
method available to all:
$(function(){
$("#imgid").click(function(){
var address = $("#formatedAddress").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
}
});
});
});
(You should remove the existing onclick
and add an ID to the image element that you want to handle)
Note that I've replaced $(document).ready()
with its shortcut of just $()
(http://api.jquery.com/ready/). Then the click method is used to assign a click handler to the element. I've also replaced your document.getElementById
with the jQuery object.
I like to parse HTML with regular expressions. I don't attempt to parse idiot HTML that is deliberately broken. This code is my main parser (Perl edition):
$_ = join "",<STDIN>; tr/\n\r \t/ /s; s/</\n</g; s/>/>\n/g; s/\n ?\n/\n/g;
s/^ ?\n//s; s/ $//s; print
It's called htmlsplit, splits the HTML into lines, with one tag or chunk of text on each line. The lines can then be processed further with other text tools and scripts, such as grep, sed, Perl, etc. I'm not even joking :) Enjoy.
It is simple enough to rejig my slurp-everything-first Perl script into a nice streaming thing, if you wish to process enormous web pages. But it's not really necessary.
Some better regular expressions:
/(<.*?>|[^<]+)\s*/g # Get tags and text
/(\w+)="(.*?)"/g # Get attibutes
They are good for XML / XHTML.
With minor variations, it can cope with messy HTML... or convert the HTML -> XHTML first.
The best way to write regular expressions is in the Lex / Yacc style, not as opaque one-liners or commented multi-line monstrosities. I didn't do that here, yet; these ones barely need it.
/n
and /r
usage depends on the platform (Window, Mac, Linux) which you are using.
But there are some platform independent separators too:
System.lineSeparator()
System.getProperty("line.separator")
If someone is sniffing your plain-text HTTP traffic (or cache/cookies) for passwords just turning the password into a hash won't help - The hash password can be "replayed" just as well as plain-text. The client would need to hash the password with something somewhat random (like the date and time) See the section on "AUTH CRAM-MD5" here: http://www.fehcom.de/qmail/smtpauth.html
Yes sure, provided you have its context. (See how to get canvas context here.)
var imgData = context.getImageData(0,0,canvas.width,canvas.height);
// { data: [r,g,b,a,r,g,b,a,r,g,..], ... }
function getPixel(imgData, index) {
var i = index*4, d = imgData.data;
return [d[i],d[i+1],d[i+2],d[i+3]] // Returns array [R,G,B,A]
}
// AND/OR
function getPixelXY(imgData, x, y) {
return getPixel(imgData, y*imgData.width+x);
}
PS: If you plan to mutate the data and draw them back on the canvas, you can use subarray
var
idt = imgData, // See previous code snippet
a = getPixel(idt, 188411), // Array(4) [0, 251, 0, 255]
b = idt.data.subarray(188411*4, 188411*4 + 4) // Uint8ClampedArray(4) [0, 251, 0, 255]
a[0] = 255 // Does nothing
getPixel(idt, 188411), // Array(4) [0, 251, 0, 255]
b[0] = 255 // Mutates the original imgData.data
getPixel(idt, 188411), // Array(4) [255, 251, 0, 255]
// Or use it in the function
function getPixel(imgData, index) {
var i = index*4, d = imgData.data;
return imgData.data.subarray(index, index+4) // Returns subarray [R,G,B,A]
}
You can experiment with this on http://qry.me/xyscope/, the code for this is in the source, just copy/paste it in the console.
In Python 2:
data = raw_input('Enter something: ')
print data
In Python 3:
data = input('Enter something: ')
print(data)
List to Tuple and back can be done as below
import ast, sys
input_str = sys.stdin.read()
input_tuple = ast.literal_eval(input_str)
l = list(input_tuple)
l.append('Python')
#print(l)
tuple_2 = tuple(l)
# Make sure to name the final tuple 'tuple_2'
print(tuple_2)
In Eclipse: right-click
on your project -> Export
-> JAR file
At last page with options (when there will be no Next
button active) you will see settings for Main class:
. You need to set here class with main
method which should be executed by default (like when JAR file will be double-clicked).
You can't selectively escape %
, as %
always has a special meaning depending on the following character.
In the documentation of Python, at the bottem of the second table in that section, it states:
'%' No argument is converted, results in a '%' character in the result.
Therefore you should use:
selectiveEscape = "Print percent %% in sentence and not %s" % (test, )
(please note the expicit change to tuple as argument to %
)
Without knowing about the above, I would have done:
selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)
with the knowledge you obviously already had.
Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument. Here's an example in JavaScript:
function add (a, b) {
return a + b;
}
add(3, 4); // returns 7
This is a function that takes two arguments, a and b, and returns their sum. We will now curry this function:
function add (a) {
return function (b) {
return a + b;
}
}
This is a function that takes one argument, a, and returns a function that takes another argument, b, and that function returns their sum.
add(3)(4);
var add3 = add(3);
add3(4);
The first statement returns 7, like the add(3, 4) statement. The second statement defines a new function called add3 that will add 3 to its argument. This is what some people may call a closure. The third statement uses the add3 operation to add 3 to 4, again producing 7 as a result.
In addition to Harry's answer, I think it's crucial to add/emphasize that :last-child will not work if the element is not the VERY LAST element in a container. For whatever reason it took me hours to realize that, and even though Harry's answer is very thorough I couldn't extract that information from "The last-child selector is used to select the last child element of a parent."
Suppose this is my selector: a:last-child {}
This works:
<div>
<a></a>
<a>This will be selected</a>
</div>
This doesn't:
<div>
<a></a>
<a>This will no longer be selected</a>
<div>This is now the last child :'( </div>
</div>
It doesn't because the a
element is not the last element inside its parent.
It may be obvious, but it was not for me...
@doc_180 had the right concept, except he is focused on numbers, whereas the original poster had issues with strings.
The solution is to change the mx.rpc.xml.XMLEncoder
file. This is line 121:
if (content != null)
result += content;
(I looked at Flex 4.5.1 SDK; line numbers may differ in other versions.)
Basically, the validation fails because 'content is null' and therefore your argument is not added to the outgoing SOAP Packet; thus causing the missing parameter error.
You have to extend this class to remove the validation. Then there is a big snowball up the chain, modifying SOAPEncoder to use your modified XMLEncoder, and then modifying Operation to use your modified SOAPEncoder, and then moidfying WebService to use your alternate Operation class.
I spent a few hours on it, but I need to move on. It'll probably take a day or two.
You may be able to just fix the XMLEncoder line and do some monkey patching to use your own class.
I'll also add that if you switch to using RemoteObject/AMF with ColdFusion, the null is passed without problems.
11/16/2013 update:
I have one more recent addition to my last comment about RemoteObject/AMF. If you are using ColdFusion 10; then properties with a null value on an object are removed from the server-side object. So, you have to check for the properties existence before accessing it or you will get a runtime error.
Check like this:
<cfif (structKeyExists(arguments.myObject,'propertyName')>
<!--- no property code --->
<cfelse>
<!--- handle property normally --->
</cfif>
This is a change in behavior from ColdFusion 9; where the null properties would turn into empty strings.
Edit 12/6/2013
Since there was a question about how nulls are treated, here is a quick sample application to demonstrate how a string "null" will relate to the reserved word null.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" initialize="application1_initializeHandler(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
protected function application1_initializeHandler(event:FlexEvent):void
{
var s :String = "null";
if(s != null){
trace('null string is not equal to null reserved word using the != condition');
} else {
trace('null string is equal to null reserved word using the != condition');
}
if(s == null){
trace('null string is equal to null reserved word using the == condition');
} else {
trace('null string is not equal to null reserved word using the == condition');
}
if(s === null){
trace('null string is equal to null reserved word using the === condition');
} else {
trace('null string is not equal to null reserved word using the === condition');
}
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
</s:Application>
The trace output is:
null string is not equal to null reserved word using the != condition
null string is not equal to null reserved word using the == condition
null string is not equal to null reserved word using the === condition
The Scanner class is bases on logic implemented in String next(Pattern)
method. The additional API method like nextDouble()
or nextFloat()
. Provide the pattern inside.
Then class description says:
A simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
From the description it can be sad that someone has forgot about char as it is a primitive type for sure.
But the concept of class is to find patterns, a char has no pattern is just next character. And this logic IMHO caused that nextChar has not been implemented.
If you need to read a filed char by char you can used more efficient class.
I had the same problem, Here is my code before modification :
package com.asagaama
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import org.apache.spark.rdd.RDD
/**
* Created by asagaama on 16/02/2017.
*/
object Word {
def countWords(sc: SparkContext) = {
// Load our input data
val input = sc.textFile("/Users/Documents/spark/testscase/test/test.txt")
// Split it up into words
val words = input.flatMap(line => line.split(" "))
// Transform into pairs and count
val counts = words.map(word => (word, 1)).reduceByKey { case (x, y) => x + y }
// Save the word count back out to a text file, causing evaluation.
counts.saveAsTextFile("/Users/Documents/spark/testscase/test/result.txt")
}
def main(args: Array[String]) = {
val conf = new SparkConf().setAppName("wordCount")
val sc = new SparkContext(conf)
countWords(sc)
}
}
And after replacing :
val conf = new SparkConf().setAppName("wordCount")
With :
val conf = new SparkConf().setAppName("wordCount").setMaster("local[*]")
It worked fine !
I had the same issue. In my case I was using digitalocean and nginx.
I have first setup a domain example.app and a subdomain dev.exemple.app in digitalocean.
Second,I purchased two ssl certificat from godaddy.
And finaly, I configured two domain in nginx to use those two ssl certificat with the following snipet
My example.app domain config
server {
listen 7000 default_server;
listen [::]:7000 default_server;
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
root /srv/nodejs/echantillonnage1;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name echantillonnage.app;
ssl_certificate /srv/nodejs/certificatSsl/widcardcertificate/echantillonnage.app.chained.crt;
ssl_certificate_key /srv/nodejs/certificatSsl/widcardcertificate/echantillonnage.app.key;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
proxy_pass http://127.0.0.1:8090;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
#try_files $uri $uri/ =404;
}
}
My dev.example.app
server {
listen 7000 default_server;
listen [::]:7000 default_server;
listen 444 ssl default_server;
listen [::]:444 ssl default_server;
root /srv/nodejs/echantillonnage1;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name dev.echantillonnage.app;
ssl_certificate /srv/nodejs/certificatSsl/dev/dev.echantillonnage.app.chained.crt;
ssl_certificate_key /srv/nodejs/certificatSsl/dev/dev.echantillonnage.app.key;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
proxy_pass http://127.0.0.1:8091;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
#try_files $uri $uri/ =404;
}
}
When I was launching https://dev.echantillonnage.app , I was getting
Fix CURL (51) SSL error: no alternative certificate subject name matches
My mistake was the two lines bellow
listen 444 ssl default_server;
listen [::]:444 ssl default_server;
I had to change this to:
listen 443 ssl;
listen [::]:443 ssl;
For getting around day-light saving, etc.
None of the above answers particularly helped me. The code below works for GMT.
def get_utc_from_local(date_time, local_tz=None):
assert date_time.__class__.__name__ == 'datetime'
if local_tz is None:
local_tz = pytz.timezone(settings.TIME_ZONE) # Django eg, "Europe/London"
local_time = local_tz.normalize(local_tz.localize(date_time))
return local_time.astimezone(pytz.utc)
import pytz
from datetime import datetime
summer_11_am = datetime(2011, 7, 1, 11)
get_utc_from_local(summer_11_am)
>>>datetime.datetime(2011, 7, 1, 10, 0, tzinfo=<UTC>)
winter_11_am = datetime(2011, 11, 11, 11)
get_utc_from_local(winter_11_am)
>>>datetime.datetime(2011, 11, 11, 11, 0, tzinfo=<UTC>)
From Microsoft documentation:
PAGEIOLATCH_SH
Occurs when a task is waiting on a latch for a buffer that is in an
I/O
request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.
In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.
If your query is like this:
Select * from <table> where <col1> = <value> order by <PrimaryKey>
, check that you have a composite index on (col1, col_primary_key)
.
If you don't have one, then you'll need either a full INDEX SCAN
if the PRIMARY KEY
is chosen, or a SORT
if an index on col1
is chosen.
Both of them are very disk I/O
consuming operations on large tables.
A handle can be anything from an integer index to a pointer to a resource in kernel space. The idea is that they provide an abstraction of a resource, so you don't need to know much about the resource itself to use it.
For instance, the HWND in the Win32 API is a handle for a Window. By itself it's useless: you can't glean any information from it. But pass it to the right API functions, and you can perform a wealth of different tricks with it. Internally you can think of the HWND as just an index into the GUI's table of windows (which may not necessarily be how it's implemented, but it makes the magic make sense).
EDIT: Not 100% certain what specifically you were asking in your question. This is mainly talking about pure C/C++.
For read-only controls they are the same. For 2 way databinding, using a datasource in which you want to update, insert, etc with declarative databinding, you'll need to use Bind
.
Imagine for example a GridView with a ItemTemplate
and EditItemTemplate
. If you use Bind
or Eval
in the ItemTemplate
, there will be no difference. If you use Eval
in the EditItemTemplate
, the value will not be able to be passed to the Update
method of the DataSource
that the grid is bound to.
UPDATE: I've come up with this example:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Data binding demo</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView
ID="grdTest"
runat="server"
AutoGenerateEditButton="true"
AutoGenerateColumns="false"
DataSourceID="mySource">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox
ID="edtName"
runat="server"
Text='<%# Bind("Name") %>'
/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
<asp:ObjectDataSource
ID="mySource"
runat="server"
SelectMethod="Select"
UpdateMethod="Update"
TypeName="MyCompany.CustomDataSource" />
</body>
</html>
And here's the definition of a custom class that serves as object data source:
public class CustomDataSource
{
public class Model
{
public string Name { get; set; }
}
public IEnumerable<Model> Select()
{
return new[]
{
new Model { Name = "some value" }
};
}
public void Update(string Name)
{
// This method will be called if you used Bind for the TextBox
// and you will be able to get the new name and update the
// data source accordingly
}
public void Update()
{
// This method will be called if you used Eval for the TextBox
// and you will not be able to get the new name that the user
// entered
}
}
There is no error in the following piece of code:
float arr[4];
arr[0] = 6.28;
arr[1] = 2.50;
arr[2] = 9.73;
arr[3] = 4.364;
std::vector<float*> vec = std::vector<float*>();
vec.push_back(arr);
float* ptr = vec.front();
for (int i = 0; i < 3; i++)
printf("%g\n", ptr[i]);
OUTPUT IS:
6.28
2.5
9.73
4.364
IN CONCLUSION:
std::vector<double*>
is another possibility apart from
std::vector<std::array<double, 4>>
that James McNellis suggested.
Following ae the steps i followed to uninstall and reinstall. Which worked for me.
First remove the installed postgres :-
sudo apt-get purge postgr*
sudo apt-get autoremove
Then install 'synaptic':
sudo apt-get install synaptic
sudo apt-get update
Then install postgres
sudo apt-get install postgresql postgresql-contrib
In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.
It turned out to be the anti forgery token.
$.ajax({
url: "/Cart/AddProduct/",
data: {
__RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
productId: $(this).data("productcode")
},
The problem was that the .Net controller wasn't set up correctly.
I needed to add the attributes to the controller:
[AllowAnonymous]
[IgnoreAntiforgeryToken]
[DisableCors]
[HttpPost]
public async Task<JsonResult> AddProduct(int productId)
{
The code needs review but for now at least I know what was causing it. 400 error not helpful at all.
According to the API, the headers can all be passed in using requests.get
:
import requests
r=requests.get("http://www.example.com/", headers={"content-type":"text"})
Without Installing python-docx
docx
is basically is a zip file with several folders and files within it. In the link below you can find a simple function to extract the text from docx
file, without the need to rely on python-docx
and lxml
the latter being sometimes hard to install:
http://etienned.github.io/posts/extract-text-from-word-docx-simply/
If you want to reset everything, go to %userprofile%\AppData\Roaming\Code
and delete the whole folder after you uninstall the VS code, then install it again.
Also in %userprofile%\.vscode
delete extensions folder in case you want to delete all extensions.
Here Response.Write():to display only string and you can not display any other data type values like int,date,etc.Conversion(from one data type to another) is not allowed. whereas Response .Output .Write(): you can display any type of data like int, date ,string etc.,by giving index values.
Here is example:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write ("hi good morning!"+"is it right?");//only strings are allowed
Response.Write("Scott is {0} at {1:d}", "cool", DateTime.Now);//this will give error(conversion is not allowed)
Response.Output.Write("\nhi goood morning!");//works fine
Response.Output.Write("Jai is {0} on {1:d}", "cool", DateTime.Now);//here the current date will be converted into string and displayed
}
use zzz instead of TZD
Example:
DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");
Response:
2011-08-09T11:50:00:02+02:00
If you're looking for a method that's easy, then you might want to try this.
I for myself can hardly remember commandlines for all of my tools, so I tend to do it using the UI:
1. First, select "commit"
2. Then, display ignored files. If you have uncommitted changes, hide them.
3. Now, select all of them and click "Delete Unversioned".
Done. It's a procedure that is far easier to remember than commandline stuff.
After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
$(window).resize(function(){
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
map.fitBounds(group1.getBounds());
});
Source Code for Label - How to change Color and Font (in Netbeans)
jLabel1.setFont(new Font("Serif", Font.BOLD, 12));
jLabel1.setForeground(Color.GREEN);
I copied over .svn folder from my peer worker's directory and that fixed the issue.
The easiest way to open an admin Powershell window in Windows 10 (and Windows 8) is to add a "Windows Powershell (Admin)" option to the "Power User Menu". Once this is done, you can open an admin powershell window via Win+X,A or by right-clicking on the start button and selecting "Windows Powershell (Admin)":
[
Here's where you replace the "Command Prompt" option with a "Windows Powershell" option:
[
You need to upgrade npm.
// Do this first, or the upgrade will fail
npm config set ca ""
npm install npm -g
// Undo the previous config change
npm config delete ca
You may need to prefix those commands with sudo
.
Source: http://blog.npmjs.org/post/78085451721/npms-self-signed-certificate-is-no-more
The difference is that an EXE has an entry point, a "main" method that will run on execution.
The code within a DLL needs to be called from another application.
var ReCaptchaCallback = function() {_x000D_
$('.g-recaptcha').each(function(){_x000D_
var el = $(this);_x000D_
grecaptcha.render(el.get(0), {'sitekey' : el.data("sitekey")});_x000D_
}); _x000D_
};
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://www.google.com/recaptcha/api.js?onload=ReCaptchaCallback&render=explicit" async defer></script>_x000D_
_x000D_
_x000D_
ReCaptcha 1_x000D_
<div class="g-recaptcha" data-sitekey="6Lc8WQcUAAAAABQKSITdXbc6p9HISCQhZIJwm2Zw"></div>_x000D_
_x000D_
ReCaptcha 2_x000D_
<div class="g-recaptcha" data-sitekey="6Lc8WQcUAAAAABQKSITdXbc6p9HISCQhZIJwm2Zw"></div>_x000D_
_x000D_
ReCaptcha 3_x000D_
<div class="g-recaptcha" data-sitekey="6Lc8WQcUAAAAABQKSITdXbc6p9HISCQhZIJwm2Zw"></div>
_x000D_
The variable name you're looking for is ansible_ssh_private_key_file
.
You should set it at 'vars' level:
in the inventory file:
myHost ansible_ssh_private_key_file=~/.ssh/mykey1.pem
myOtherHost ansible_ssh_private_key_file=~/.ssh/mykey2.pem
in the host_vars
:
# hosts_vars/myHost.yml
ansible_ssh_private_key_file: ~/.ssh/mykey1.pem
# hosts_vars/myOtherHost.yml
ansible_ssh_private_key_file: ~/.ssh/mykey2.pem
in a group_vars
file if you use the same key for a group of hosts
in the vars
section of your play:
- hosts: myHost
remote_user: ubuntu
vars_files:
- vars.yml
vars:
ansible_ssh_private_key_file: "{{ key1 }}"
tasks:
- name: Echo a hello message
command: echo hello
Why don't you use the Modulus Operator?
Try this:
while ($s % 6 != 0) $s++;
Or is this what you meant?
<?
$s= <some_number>;
$k= $s % 6;
if($k !=0) $s=$s+6-$k;
?>
Create object of date and simply print it down.
Date d = new Date(System.currentTimeMillis());
System.out.print(d);
I think the problem is given in the error message, although it is not very easy to spot:
IndexError: too many indices for array
xs = data[:, col["l1" ]]
'Too many indices' means you've given too many index values. You've given 2 values as you're expecting data to be a 2D array. Numpy is complaining because data
is not 2D (it's either 1D or None).
This is a bit of a guess - I wonder if one of the filenames you pass to loadfile() points to an empty file, or a badly formatted one? If so, you might get an array returned that is either 1D, or even empty (np.array(None)
does not throw an Error
, so you would never know...). If you want to guard against this failure, you can insert some error checking into your loadfile
function.
I highly recommend in your for
loop inserting:
print(data)
This will work in Python 2.x or 3.x and might reveal the source of the issue. You might well find it is only one value of your outputs_l1
list (i.e. one file) that is giving the issue.
What are you trying to do?
The InterruptedException
is thrown when a thread is waiting or sleeping and another thread interrupts it using the interrupt
method in class Thread
. So if you catch this exception, it means that the thread has been interrupted. Usually there is no point in calling Thread.currentThread().interrupt();
again, unless you want to check the "interrupted" status of the thread from somewhere else.
Regarding your other option of throwing a RuntimeException
, it does not seem a very wise thing to do (who will catch this? how will it be handled?) but it is difficult to tell more without additional information.
If you want to change ng-view you'll have to use the '#'
$window.location.href= "#operation";
I've found that the ''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m)) method is pretty slow. Instead, I've been doing this:
fmt = '%dB' % len(source)
s = struct.unpack(fmt, source)
m = struct.unpack(fmt, xor_data)
final = struct.pack(fmt, *(a ^ b for a, b in izip(s, m)))
use
select 1/3.0
This will do the job.
Since std::string
in C++ is mutable you can use that. It has a += operator
and an append
function.
If you need to append numerical data use the std::to_string
functions.
If you want even more flexibility in the form of being able to serialise any object to a string then use the std::stringstream
class. But you'll need to implement your own streaming operator functions for it to work with your own custom classes.
The Picup app is a way to take pictures from an HTML5 page and upload them to your server. It requires some extra programming on the server, but apart from PhoneGap, I have not found another way.
In Doctrine 2.x you can't pass multiple order by using doctrine 'orderBy' or 'addOrderBy' as above examples. Because, it automatically adds the 'ASC' at the end of the last column name when you left the second parameter blank, such as in the 'orderBy' function.
For an example ->orderBy('a.fist_name ASC, a.last_name ASC')
will output SQL something like this 'ORDER BY first_name ASC, last_name ASC ASC'. So this is SQL syntax error. Simply because default of the orderBy or addOrderBy is 'ASC'.
To add multiple order by's you need to use 'add' function. And it will be like this.
->add('orderBy','first_name ASC, last_name ASC')
. This will give you the correctly formatted SQL.
More info on add() function. https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/query-builder.html#low-level-api
Hope this helps. Cheers!
If i go by Grodriguez's answer
System.out.println("" + value);
value = value.setScale(0, BigDecimal.ROUND_HALF_UP);
System.out.println("" + value);
This is the output
100.23 -> 100
100.77 -> 101
Which isn't quite what i want, so i ended up doing this..
System.out.println("" + value);
value = value.setScale(0, BigDecimal.ROUND_HALF_UP);
value = value.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("" + value);
This is what i get
100.23 -> 100.00
100.77 -> 101.00
This solves my problem for now .. : ) Thank you all.
The very same. A C string is nothing but an array of characters, so a pointer to a string is a pointer to an array of characters. And a pointer to an array is the very same as a pointer to its first element.
I think this should depend on the situation.Take the following container as an example:
# docker run -it -d ubuntu
91262536f7c9a3060641448120bda7af5ca812b0beb8f3c9fe72811a61db07fc
# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
91262536f7c9 ubuntu "/bin/bash" 5 seconds ago Up 4 seconds serene_goldstine
(1) Use "docker attach
" to attach the container:
Since "docker attach
" will not allocate a new tty, but reuse the original running tty, so if you run exit
command, it will cause the running container exit:
# docker attach 91262536f7c9
exit
exit
# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
91262536f7c9 ubuntu "/bin/bash" 39 minutes ago Exited (0) 3 seconds ago serene_goldstine
So unless you really want to make running container exit, you should use Ctrl+p + Ctrl+q.
(2) Use "docker exec
"
Since "docker exec
" will allocate a new tty, so I think you should use exit
instead of Ctrl+p + Ctrl+q.
The following is executing Ctrl+p + Ctrl+q to quit the container:
# docker exec -it 91262536f7c9 bash
root@91262536f7c9:/# ps -aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 18160 1908 ? Ss+ 04:03 0:00 /bin/bash
root 15 0.0 0.0 18164 1892 ? Ss 04:03 0:00 bash
root 28 0.0 0.0 15564 1148 ? R+ 04:03 0:00 ps -aux
root@91262536f7c9:/# echo $$
15
Then login container again, you will see the bash
process in preavious docker exec
command is still alive (PID is 15):
# docker exec -it 91262536f7c9 bash
root@91262536f7c9:/# ps -aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 18160 1908 ? Ss+ 04:03 0:00 /bin/bash
root 15 0.0 0.0 18164 1892 ? Ss+ 04:03 0:00 bash
root 29 0.0 0.0 18164 1888 ? Ss 04:04 0:00 bash
root 42 0.0 0.0 15564 1148 ? R+ 04:04 0:00 ps -aux
root@91262536f7c9:/# echo $$
29
So, __init__
is called when you are creating an instance of any class and initializing the instance variable also.
Example:
class User:
def __init__(self,first_n,last_n,age):
self.first_n = first_n
self.last_n = last_n
self.age = age
user1 = User("Jhone","Wrick","40")
And __call__
is called when you call the object like any other function.
Example:
class USER:
def __call__(self,arg):
"todo here"
print(f"I am in __call__ with arg : {arg} ")
user1=USER()
user1("One") #calling the object user1 and that's gonna call __call__ dunder functions
To spool from a BEGIN
END
block is pretty simple. For example if you need to spool result from two tables into a file, then just use the for loop
. Sample code is given below.
BEGIN
FOR x IN
(
SELECT COLUMN1,COLUMN2 FROM TABLE1
UNION ALL
SELECT COLUMN1,COLUMN2 FROM TABLEB
)
LOOP
dbms_output.put_line(x.COLUMN1 || '|' || x.COLUMN2);
END LOOP;
END;
/
If you want to change environment variables permanently on macOS, set them in /etc/paths
. Note, this file is read-only by default, so you'll have to chmod for write permissions.
There are two main things on keeping a forked repository always update for good.
1. Create the branches from the fork master and do changes there.
So when your Pull Request is accepted then you can safely delete the branch as your contributed code will be then live in your master of your forked repository when you update it with the upstream. By this your master will always be in clean condition to create a new branch to do another change.
2. Create a scheduled job for the fork master to do update automatically.
This can be done with cron. Here is for an example code if you do it in linux.
$ crontab -e
put this code on the crontab file
to execute the job in hourly basis.
0 * * * * sh ~/cron.sh
then create the cron.sh
script file and a git interaction with ssh-agent and/or expect as below
#!/bin/sh
WORKDIR=/path/to/your/dir
REPOSITORY=<name of your repo>
MASTER="[email protected]:<username>/$REPOSITORY.git"
[email protected]:<upstream>/<name of the repo>.git
cd $WORKDIR && rm -rf $REPOSITORY
eval `ssh-agent` && expect ~/.ssh/agent && ssh-add -l
git clone $MASTER && cd $REPOSITORY && git checkout master
git remote add upstream $UPSTREAM && git fetch --prune upstream
if [ `git rev-list HEAD...upstream/master --count` -eq 0 ]
then
echo "all the same, do nothing"
else
echo "update exist, do rebase!"
git reset --hard upstream/master
git push origin master --force
fi
cd $WORKDIR && rm -rf $REPOSITORY
eval `ssh-agent -k`
Check your forked repository. From time to time it will always show this notification:
This branch is even with
<upstream>
:master.
It is easy with css, just use display:block
and z-index
property
Here is an example:
HTML:
<body>
<div class="wrapper">
<div class="header">
header
</div>
<div class="content">
content
</div>
</div>
</body>
CSS:
.wrapper
{
[...]
}
.header
{
[...]
z-index:9001;
display:block;
[...]
}
.content
{
[...]
z-index:9000;
[...]
}
Edit: It is good to set some background-color
to the div-s
to see things properly.
Create an Ant file and tell Eclipse to build it. There are only two steps and each is easy with the step-by-step instructions below.
Step 1 Create a build.xml file and add to package explorer:
<?xml version="1.0" ?>
<!-- Configuration of the Ant build system to generate a Jar file -->
<project name="TestMain" default="CreateJar">
<target name="CreateJar" description="Create Jar file">
<jar jarfile="Test.jar" basedir="." includes="*.class" />
</target>
</project>
Eclipse should looks something like the screenshot below. Note the Ant icon on build.xml.
Step 2 Right-click on the root node in the project. - Select Properties - Select Builders - Select New - Select Ant Build - In the Main tab, complete the path to the build.xml file in the bin folder.
Check the Output
The Eclipse output window (named Console) should show the following after a build:
Buildfile: /home/<user>/src/Test/build.xml
CreateJar:
[jar] Building jar: /home/<user>/src/Test/Test.jar
BUILD SUCCESSFUL
Total time: 152 milliseconds
EDIT: Some helpful comments by @yeoman and @betlista
@yeoman I think the correct include would be /.class, not *.class, as most people use packages and thus recursive search for class files makes more sense than flat inclusion
@betlista I would recomment to not to have build.xml in src folder
I also stumpled accross the ClassNotFoundException:javax.xml.bind.DatatypeConverter using Java 11 and
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
I tried all this stuff around adding javax.xml.bind:jaxb-api or spring boot jakarta.xml.bind-api .. I found a hint for fixes in jjwt version 0.10.0 .. but most importantly, the jjwt package is now split !
Thus, check this reference: https://github.com/jwtk/jjwt/issues/510
Simply, if you use
Java11 and jjwt 0.9.x and you face the ClassNotFoundException:javax.xml.bind.DatatypeConverter issue,
go for
jjwt version 0.11.x, but use the splitted packages: https://github.com/jwtk/jjwt#install
You maven wont find a higher version for jjwt dependency, since they split the packages.
Cheers.
For a Mac it is the following combination: Cmd + /
[Update]
As noted by other answers and commenters, as of Java 8 you can simply call Map#getOrDefault(...)
.
[Original]
There's no Map implementation that does this exactly but it would be trivial to implement your own by extending HashMap:
public class DefaultHashMap<K,V> extends HashMap<K,V> {
protected V defaultValue;
public DefaultHashMap(V defaultValue) {
this.defaultValue = defaultValue;
}
@Override
public V get(Object k) {
return containsKey(k) ? super.get(k) : defaultValue;
}
}
You cannot insert a class into a vector, you can insert an object (provided that it is of the proper type or convertible) of a class though.
If the type Player
has a default constructor, you can create a temporary object by doing Player()
, and that should work for your case:
vectorOfGamers.push_back(Player());
I don't think there is a way to ignore adding DEFINER
s to the dump. But there are ways to remove them after the dump file is created.
Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost
with an empty string ""
Edit the dump (or pipe the output) using perl
:
perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
Since these are member functions, call it as a member function on the instance, self
.
def isNear(self, p):
self.distToPoint(p)
...
If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.
Yes, \
in Python string literals denotes the start of an escape sequence. In your path you have a valid two-character escape sequence \a
, which is collapsed into one character that is ASCII Bell:
>>> '\a'
'\x07'
>>> len('\a')
1
>>> 'C:\meshes\as'
'C:\\meshes\x07s'
>>> print('C:\meshes\as')
C:\meshess
Other common escape sequences include \t
(tab), \n
(line feed), \r
(carriage return):
>>> list('C:\test')
['C', ':', '\t', 'e', 's', 't']
>>> list('C:\nest')
['C', ':', '\n', 'e', 's', 't']
>>> list('C:\rest')
['C', ':', '\r', 'e', 's', 't']
As you can see, in all these examples the backslash and the next character in the literal were grouped together to form a single character in the final string. The full list of Python's escape sequences is here.
There are a variety of ways to deal with that:
Python will not process escape sequences in string literals prefixed with r
or R
:
>>> r'C:\meshes\as'
'C:\\meshes\\as'
>>> print(r'C:\meshes\as')
C:\meshes\as
Python on Windows should handle forward slashes, too.
You could use os.path.join
...
>>> import os
>>> os.path.join('C:', os.sep, 'meshes', 'as')
'C:\\meshes\\as'
... or the newer pathlib
module
>>> from pathlib import Path
>>> Path('C:', '/', 'meshes', 'as')
WindowsPath('C:/meshes/as')
I was able to figure out the solution:
start notepad "myfile.txt"
"myshortcut.lnk"
exit
If I understand correctly, you can use the module operator for this. For example, in Java (and a lot of other languages), you could do:
//j is a multiple of four if
j % 4 == 0
The module operator performs division and gives you the remainder.
Here is my script to measure average time
<?php
$times = [];
$nbrOfLoops = 4;
for ($i = 0; $i < $nbrOfLoops; ++$i) {
$start = microtime(true);
sleep(1);
$times[] = microtime(true) - $start;
}
echo 'Average: ' . (array_sum($times) / count($times)) . 'seconds';
I might have even a simpler explanation to this question compared to the accepted answer so I'm going to give it a go: Assume this is the structure of the files and directories of a project:
Project root directory:
file1.php
file3.php
dir1/
file2.php
(dir1
is a directory and file2.php
is inside it)
And this is the content of each of the three files above:
//file1.php:
<?php include "dir1/file2.php"
//file2.php:
<?php include "../file3.php"
//file3.php:
<?php echo "Hello, Test!";
Now run file1.php
and try to guess what should happen. You might expect to see "Hello, Test!", however, it won't be shown! What you'll get instead will be an error indicating that the file you have requested(file3.php
) does not exist!
The reason is that, inside file1.php
when you include file2.php
, the content of it is getting copied and then pasted back directly into file1.php
which is inside the root directory, thus this part "../file3.php"
runs from the root directory and thus goes one directory up the root! (and obviously it won't find the file3.php
).
Now, what should we do ?!
Relative paths of course have the problem above, so we have to use absolute paths. However, absolute paths have also one problem. If you (for example) copy the root folder (containing your whole project) and paste it in anywhere else on your computer, the paths will be invalid from that point on! And that'll be a REAL MESS!
So we kind of need paths that are both absolute and dynamic(Each file dynamically finds the absolute path of itself wherever we place it)!
The way we do that is by getting help from PHP, and dirname()
is the function to go for, which gives the absolute path to the directory in which a file exists in. And each file name could also be easily accessed using the __FILE__
constant. So dirname(__FILE__)
would easily give you the absolute (while dynamic!) path to the file we're typing in the above code. Now move your whole project to a new place, or even a new system, and tada! it works!
So now if we turn the project above to this:
//file1.php:
<?php include(dirname(__FILE__)."/dir1/file2.php");
//file2.php:
<?php include(dirname(__FILE__)."/../file3.php");
//file3.php:
<?php echo "Hello, Test!";
if you run it, you'll see the almighty Hello, Test!
! (hopefully, if you've not done anything else wrong).
It's also worth mentioning that from PHP5, a nicer way(with regards to readability and preventing eye boilage!) has been provided by PHP as well which is the constant __DIR__
which does exactly the same thing as dirname(__FILE__)
!
Hope that helps.
There's always Cygwin.
1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math
2: Yes: But you already know it:
`^`(x,y)
#[1] 1024
In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math
.
Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply
and sapply
:
> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4
I found very good explanation about .la files here http://openbooks.sourceforge.net/books/wga/dealing-with-libraries.html
Summary (The way I understood): Because libtool deals with static and dynamic libraries internally (through --diable-shared or --disable-static) it creates a wrapper on the library files it builds. They are treated as binary library files with in libtool supported environment.
Yes, you can use a script like this to generate another script
SET NOCOUNT ON;
DECLARE @NewRole varchar(100), @SourceRole varchar(100);
-- Change as needed
SELECT @SourceRole = 'Giver', @NewRole = 'Taker';
SELECT
state_desc + ' ' + permission_name + ' ON ' + OBJECT_NAME(major_id) + ' TO ' + @NewRole
FROM
sys.database_permissions
WHERE
grantee_principal_id = DATABASE_PRINCIPAL_ID(@SourceRole) AND
-- 0 = DB, 1 = object/column, 3 = schema. 1 is normally enough
class <= 3
Don’t inherit from Python built-in dict, ever! for example update
method woldn't use __setitem__
, they do a lot for optimization. Use UserDict.
from collections import UserDict
class MyDict(UserDict):
def __delitem__(self, key):
pass
def __setitem__(self, key, value):
pass
If you're referring to the URL in the address bar, then
window.location.search
will give you just the query string part. Note that this includes the question mark at the beginning.
If you're referring to any random URL stored in (e.g.) a string, you can get at the query string by taking a substring beginning at the index of the first question mark by doing something like:
url.substring(url.indexOf("?"))
That assumes that any question marks in the fragment part of the URL have been properly encoded. If there's a target at the end (i.e., a # followed by the id of a DOM element) it'll include that too.
alter table your_table
alter column LoginDate datetime;
On Window, sometimes I feel hard to click through many steps to find platform-tools
and open Environment Variables Prompt
, so the below steps maybe help
platform-tools
pathcd C:\
dir /s adb.exe
rundll32 sysdm.cpl,EditEnvironmentVariables
more, the command to open environment variables can not remember, so I often make an alias for it (eg: editenv
), if you need to work with environment variables multiple time, you can use a permanent doskey to make alias
You should use abstract class to initialize a property. You can't inititalize in Inteface .
This helped to me (in ionic, but idea is the same) https://mhartington.io/post/setting-input-focus/
in template:
<ion-item>
<ion-label>Home</ion-label>
<ion-input #input type="text"></ion-input>
</ion-item>
<button (click)="focusInput(input)">Focus</button>
in controller:
focusInput(input) {
input.setFocus();
}
I have a rotating image using the same thing as you:
.knoop1 img{
position:absolute;
width:114px;
height:114px;
top:400px;
margin:0 auto;
margin-left:-195px;
z-index:0;
-webkit-transition-duration: 0.8s;
-moz-transition-duration: 0.8s;
-o-transition-duration: 0.8s;
transition-duration: 0.8s;
-webkit-transition-property: -webkit-transform;
-moz-transition-property: -moz-transform;
-o-transition-property: -o-transform;
transition-property: transform;
overflow:hidden;
}
.knoop1:hover img{
-webkit-transform:rotate(360deg);
-moz-transform:rotate(360deg);
-o-transform:rotate(360deg);
}
Use substring function
Check this out http://jsfiddle.net/kuc5as83/
var string = "1234567890"
var substr=string.substr(-8);
document.write(substr);
Output >> 34567890
substr(-8)
will keep last 8 chars
var substr=string.substr(8);
document.write(substr);
Output >> 90
substr(8)
will keep last 2 chars
var substr=string.substr(0, 8);
document.write(substr);
Output >> 12345678
substr(0, 8)
will keep first 8 chars
Check this out string.substr(start,length)
You can use SQL Compact Query Analyzer
http://sqlcequery.codeplex.com/
SQL Compact Query Analyzer is really snappy. 3 MB download, requires an install but really snappy and works.
Although there are already many good answers I'd like to add an option that hasn't been mentioned. Using the command:
php bin/console about
you can get many details about the current project. The first section is about Symfony itself and looks like this:
-------------------- -------------------------------------------
Symfony
-------------------- -------------------------------------------
Version 4.2.3
End of maintenance 07/2019
End of life 01/2020
-------------------- -------------------------------------------
I find the other information besides the version number very useful.
There are also other sections providing details about the (framework) Kernel, PHP, Environment.
.clearfix
is defined in less/mixins.less
. Right above its definition is a comment with a link to this article:
The article explains how it all works.
UPDATE: Yes, link-only answers are bad. I knew this even at the time that I posted this answer, but I didn't feel like copying and pasting was OK due to copyright, plagiarism, and what have you. However, I now feel like it's OK since I have linked to the original article. I should also mention the author's name, though, for credit: Nicolas Gallagher. Here is the meat of the article (note that "Thierry’s method" is referring to Thierry Koblentz’s “clearfix reloaded”):
This “micro clearfix” generates pseudo-elements and sets their
display
totable
. This creates an anonymous table-cell and a new block formatting context that means the:before
pseudo-element prevents top-margin collapse. The:after
pseudo-element is used to clear the floats. As a result, there is no need to hide any generated content and the total amount of code needed is reduced.Including the
:before
selector is not necessary to clear the floats, but it prevents top-margins from collapsing in modern browsers. This has two benefits:
It ensures visual consistency with other float containment techniques that create a new block formatting context, e.g.,
overflow:hidden
It ensures visual consistency with IE 6/7 when
zoom:1
is applied.N.B.: There are circumstances in which IE 6/7 will not contain the bottom margins of floats within a new block formatting context. Further details can be found here: Better float containment in IE using CSS expressions.
The use of
content:" "
(note the space in the content string) avoids an Opera bug that creates space around clearfixed elements if thecontenteditable
attribute is also present somewhere in the HTML. Thanks to Sergio Cerrutti for spotting this fix. An alternative fix is to usefont:0/0 a
.Legacy Firefox
Firefox < 3.5 will benefit from using Thierry’s method with the addition of
visibility:hidden
to hide the inserted character. This is because legacy versions of Firefox needcontent:"."
to avoid extra space appearing between thebody
and its first child element, in certain circumstances (e.g., jsfiddle.net/necolas/K538S/.)Alternative float-containment methods that create a new block formatting context, such as applying
overflow:hidden
ordisplay:inline-block
to the container element, will also avoid this behaviour in legacy versions of Firefox.
As per the docs:
You can set annotation processor argument (room.schemaLocation) to tell Room to export the schema into a folder. Even though it is not mandatory, it is a good practice to have version history in your codebase and you should commit that file into your version control system (but don't ship it with your app!).
So if you don't need to check the schema and you want to get rid of the warning, just add exportSchema = false
to your RoomDatabase
, as follows.
@Database(entities = { YourEntity.class }, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
//...
}
If you follow @mikejonesguy answer below, you will follow the good practice mentioned in the docs :).
Basically you will get a .json
file in your ../app/schemas/
folder.
And it looks something like this:
{
"formatVersion": 1,
"database": {
"version": 1,
"identityHash": "53db508c5248423325bd5393a1c88c03",
"entities": [
{
"tableName": "sms_table",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `message` TEXT, `date` INTEGER, `client_id` INTEGER)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER"
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT"
},
{
"fieldPath": "date",
"columnName": "date",
"affinity": "INTEGER"
},
{
"fieldPath": "clientId",
"columnName": "client_id",
"affinity": "INTEGER"
}
],
"primaryKey": {
"columnNames": [
"id"
],
"autoGenerate": true
},
"indices": [],
"foreignKeys": []
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"53db508c5248423325bd5393a1c88c03\")"
]
}
}
If my understanding is correct, you will get such a file with every database version update, so that you can easily follow the history of your db.
I would use serialize()
or json_encode()
.
While it won't give your the exact result string you want, it would be much easier to encode/store/retrieve/decode later on.
Hi i also come across same problem, i try many options ,but finally the most easy way is,click of down arrow present inside ProjectExplorer-> customize View->filter-> unchecked close project.
And will able to see all closed projects.
Just to add that from SQL Server 2008, there is a TIME datatype so from then on you can do:
SELECT CONVERT(TIME, GETDATE())
Might be useful for those that use SQL 2008+ and find this question.
Tried it out. ResponseHeaders do not include status code.
If I'm not mistaken, WebClient
is capable of abstracting away multiple distinct requests in a single method call (e.g. correctly handling 100 Continue responses, redirects, and the like). I suspect that without using HttpWebRequest
and HttpWebResponse
, a distinct status code may not be available.
It occurs to me that, if you are not interested in intermediate status codes, you can safely assume the final status code is in the 2xx (successful) range, otherwise, the call would not be successful.
The status code unfortunately isn't present in the ResponseHeaders
dictionary.
If it is 70% inserts and 30% reads then it is more like on the InnoDB side.
Your class has a base class, and this base class also has a property (which is not virtual or abstract) called Events which is being overridden by your class. If you intend to override it put the "new" keyword after the public modifier. E.G.
public new EventsDataTable Events
{
..
}
If you don't wish to override it change your properties' name to something else.
Really late reply for me, but I just suffered the pain of this problem as well.
What fixed it for me (after trying the Axis label settings and intervals from those screens, none of which worked!) was select the Horizontal Axis, then when you can see all the properties find Labels, and change LabelInterval to 1.
For some reason when I set this from the pop up properties screens it either never 'stuck' or it changes a slightly different value that didn't fix my issue.
for Ubuntu / Debian :
# sudo apt-get install build-essential
For RHEL/CentOS
#rpm -qa | grep gcc
# yum install gcc glibc glibc-common gd gd-devel -y
or
# yum groupinstall "Development tools" -y
More details refer the link
It is possible of course, use -l:
instead of -l
. For example -l:libXYZ.a
to link with libXYZ.a
. Notice the lib
written out, as opposed to -lXYZ
which would auto expand to libXYZ
.
You can also get this error if the objects you're passing to the method are out of order. In other words say your method takes, in order, a string, an integer, and a date. If you pass a date, then a string, then an integer you will get the same error message.
you can do this easily by using jquery using .css property... try this one: http://api.jquery.com/css/
Use a TreeMap with a custom comparator.
class MyComparator implements Comparator<String>
{
public int compare(String o1,String o2)
{
// Your logic for comparing the key strings
}
}
TreeMap<String, Float> tm = new TreeMap<String , Float>(new MyComparator());
As you add new elements, they will be automatically sorted.
In your case, it might not even be necessary to implement a comparator because String ordering might be sufficient. But if you want to implement special cases, like lower case alphas appear before upper case, or treat the numbers a certain way, use the comparator.
public static <T> Set<T> intersectCollections(Collection<T> col1, Collection<T> col2) {
Set<T> set1, set2;
if (col1 instanceof Set) {
set1 = (Set) col1;
} else {
set1 = new HashSet<>(col1);
}
if (col2 instanceof Set) {
set2 = (Set) col2;
} else {
set2 = new HashSet<>(col2);
}
Set<T> intersection = new HashSet<>(Math.min(set1.size(), set2.size()));
for (T t : set1) {
if (set2.contains(t)) {
intersection.add(t);
}
}
return intersection;
}
JDK8+ (Probably Best Performance)
public static <T> Set<T> intersectCollections(Collection<T> col1, Collection<T> col2) {
boolean isCol1Larger = col1.size() > col2.size();
Set<T> largerSet;
Collection<T> smallerCol;
if (isCol1Larger) {
if (col1 instanceof Set) {
largerSet = (Set<T>) col1;
} else {
largerSet = new HashSet<>(col1);
}
smallerCol = col2;
} else {
if (col2 instanceof Set) {
largerSet = (Set<T>) col2;
} else {
largerSet = new HashSet<>(col2);
}
smallerCol = col1;
}
return smallerCol.stream()
.filter(largerSet::contains)
.collect(Collectors.toSet());
}
If you don't care about performance and prefer smaller code just use:
col1.stream().filter(col2::contains).collect(Collectors.toList());
The easiest way to do it is using Storyboard and a Segue.
Just create a Segue from the FirstViewController (not the Navigation Controller) of your TabBarController to a LoginViewController with the login UI and name it "showLogin".
Create a method that returns a BOOL to validate if the user logged in and/or his/her session is valid... preferably on the AppDelegate. Call it isSessionValid.
On your FirstViewController.m override the method viewDidAppear as follows:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if([self isSessionValid]==NO){
[self performSegueWithIdentifier:@"showLogin" sender:self];
}
}
Then if the user logged in successfully, just dismiss or pop-out the LoginViewController to show your tabs.
Works 100%!
Hope it helps!
Dog
Cat
Example in Swift, picturing the foundry's explanation above and the Apple's documentation:
ViewController.swift
import UIKit
protocol ViewControllerProtocol {
func dismissViewController1AndPresentViewController2()
}
class ViewController: UIViewController, ViewControllerProtocol {
@IBAction func goToViewController1BtnPressed(sender: UIButton) {
let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
vc1.delegate = self
vc1.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal
self.presentViewController(vc1, animated: true, completion: nil)
}
func dismissViewController1AndPresentViewController2() {
self.dismissViewControllerAnimated(false, completion: { () -> Void in
let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
self.presentViewController(vc2, animated: true, completion: nil)
})
}
}
ViewController1.swift
import UIKit
class ViewController1: UIViewController {
var delegate: protocol<ViewControllerProtocol>!
@IBAction func goToViewController2(sender: UIButton) {
self.delegate.dismissViewController1AndPresentViewController2()
}
}
ViewController2.swift
import UIKit
class ViewController2: UIViewController {
}
ViewController.swift
import UIKit
protocol ViewControllerProtocol {
func popViewController1AndPushViewController2()
}
class ViewController: UIViewController, ViewControllerProtocol {
@IBAction func goToViewController1BtnPressed(sender: UIButton) {
let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
vc1.delegate = self
self.navigationController?.pushViewController(vc1, animated: true)
}
func popViewController1AndPushViewController2() {
self.navigationController?.popViewControllerAnimated(false)
let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
self.navigationController?.pushViewController(vc2, animated: true)
}
}
ViewController1.swift
import UIKit
class ViewController1: UIViewController {
var delegate: protocol<ViewControllerProtocol>!
@IBAction func goToViewController2(sender: UIButton) {
self.delegate.popViewController1AndPushViewController2()
}
}
ViewController2.swift
import UIKit
class ViewController2: UIViewController {
}
A combination of the regex and SimpleDateFormat is the right answer i believe. SimpleDateFormat does not catch exception if the individual components are invalid meaning, Format Defined: yyyy-mm-dd input: 201-0-12 No exception will be thrown.This case should have been handled. But with the regex as suggested by Sok Pomaranczowy and Baby will take care of this particular case.
If that's all what you want to do, you don't need to convert it into an array. You can just access it as:
string myData=yourDataTable.Rows[0][1].ToString();//Gives you USA
Our solution avoids mucking with the UITextView
text
and textColor
properties, which is handy if you're maintaining a character counter.
It's simple:
1) Create a dummy UITextView
in Storyboard with the same properties as the master UITextView
. Assign placeholder text to the dummy text.
2) Align the top, left, and right edges of the two UITextViews.
3) Place the dummy behind the master.
4) Override the textViewDidChange(textView:)
delegate function of the master, and show the dummy if the master has 0 characters. Otherwise, show the master.
This assumes both UITextViews
have transparent backgrounds. If they do not, place the dummy on top when there are 0 characters, and push it underneath when there are > 0 characters. You will also have to swap responders to make sure the cursor follows the right UITextView
.
From MSDN
To execute a stored procedure returning rows programmatically using a command object
Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
sqlConnection1.Open()
reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.
' Use Read method (true/false) to see if reader has records and advance to next record
' You can use a While loop for multiple records (While reader.Read() ... End While)
If reader.Read() Then
someVar = reader(0)
someVar2 = reader(1)
someVar3 = reader("NamedField")
End If
sqlConnection1.Close()
When you want to make your php value storable, you have to turn it to be a string value, that is what serialize() does. And unserialize() does the reverse thing.
The correct answer is, that, because the '%'
-sign is part of your search expression, it should be part of your VALUE, so whereever you SET @LastName
(be it from a programming language or from TSQL) you should set it to '%' + [userinput] + '%'
or, in your example:
DECLARE @LastName varchar(max)
SET @LastName = 'ning'
SELECT Employee WHERE LastName LIKE '%' + @LastName + '%'
Using standard Ajax call to achieve same result
$.ajax({
url: '@Url.Action("_SearchStudents")?NationalId=' + $('#NationalId').val(),
type: 'GET',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
$('#divSearchResult').html(result);
}
});
public ActionResult _SearchStudents(string NationalId)
{
//.......
return PartialView("_SearchStudents", model);
}
One solution is to set tis widget color property to Colors.transparent. For instance:
IconButton(
icon: Image.asset("myImage.png",
color: Colors.transparent,
),
onPressed: () {},
),
process.stdin.pipe(process.stdout);
127.0.0.1
is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1
for connections will only receive local connections on that socket.
"localhost" is normally the hostname for the 127.0.0.1
IP address. It's usually set in /etc/hosts
(or the Windows equivalent named "hosts" somewhere under %WINDIR%
). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1
.
0.0.0.0
has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0
that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1
from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0
will accept connections on that interface too.
That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000
is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1
I think you need to make the .holder
position:relative;
and .popup
position:absolute;
As some people indicated, the officially accepted answer does not quite return the external removable SD card. And i ran upon the following thread that proposes a method I've tested on some Android devices and seems to work reliably, so i thought of re-sharing here as i don't see it in the other responses:
http://forums.androidcentral.com/samsung-galaxy-s7/668364-whats-external-sdcard-path.html
Kudos to paresh996 for coming up with the answer itself, and i can attest I've tried on Samsung S7 and S7edge and seems to work.
Now, i needed a method that returned a valid path where to read files, and that considered the fact that there might not be an external SD, in which case the internal storage should be returned, so i modified the code from paresh996 to this :
File getStoragePath() {
String removableStoragePath;
File fileList[] = new File("/storage/").listFiles();
for (File file : fileList) {
if(!file.getAbsolutePath().equalsIgnoreCase(Environment.getExternalStorageDirectory().getAbsolutePath()) && file.isDirectory() && file.canRead()) {
return file;
}
}
return Environment.getExternalStorageDirectory();
}
We have been solving the same problem just today, and all you need to do is to increase the runtime version of .NET
4.5.2 didn't work for us with the above problem, while 4.6.1 was OK
If you need to keep the .NET version, then set
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
The time problem has to do with the ID3 headers of the MP3 files, which is something your method isn't taking into account as the entire file is copied.
Do you have a language of choice that you want to use or doesn't it matter? That will affect what libraries are available that support the operations you want.
After many painful experiences with Struts, Tapestry 3/4, JSF, JBoss Seam, GWT I will stick with Wicket for now. Wicket Bench for Eclipse is handy but not 100% complete, still useful though. MyEclipse plugin for deploying to Tomcat is ace. No Maven just deploy once, changes are automatically copied to Tomcat. Magic.
My suggestion: Wicket 1.4, MyEclipse, Subclipse, Wicket Bench, Tomcat 6. It will take an hour or so to setup but most of that will be downloading tomcat and the Eclipse plugins.
Hint: Don't use the Wicket Bench libs, manually install Wicket 1.4 libs into project.
This site took me about 2 hours to write http://ratearear.co.uk - don't go there from work!! And this one is about 3 days work http://tnwdb.com
Good luck. Tim
You can also get the page count using
$im->getNumberImages();
Then you can can create thumbs of all the pages using a loop, eg.
'file.pdf['.$x.']'
As Tim Pietzcker said ECMAScript 2018 introduces named capturing groups into JavaScript regexes. But what I did not find in the above answers was how to use the named captured group in the regex itself.
you can use named captured group with this syntax: \k<name>
.
for example
var regexObj = /(?<year>\d{4})-(?<day>\d{2})-(?<month>\d{2}) year is \k<year>/
and as Forivin said you can use captured group in object result as follow:
let result = regexObj.exec('2019-28-06 year is 2019');
// result.groups.year === '2019';
// result.groups.month === '06';
// result.groups.day === '28';
var regexObj = /(?<year>\d{4})-(?<day>\d{2})-(?<month>\d{2}) year is \k<year>/mgi;_x000D_
_x000D_
function check(){_x000D_
var inp = document.getElementById("tinput").value;_x000D_
let result = regexObj.exec(inp);_x000D_
document.getElementById("year").innerHTML = result.groups.year;_x000D_
document.getElementById("month").innerHTML = result.groups.month;_x000D_
document.getElementById("day").innerHTML = result.groups.day;_x000D_
}
_x000D_
td, th{_x000D_
border: solid 2px #ccc;_x000D_
}
_x000D_
<input id="tinput" type="text" value="2019-28-06 year is 2019"/>_x000D_
<br/>_x000D_
<br/>_x000D_
<span>Pattern: "(?<year>\d{4})-(?<day>\d{2})-(?<month>\d{2}) year is \k<year>";_x000D_
<br/>_x000D_
<br/>_x000D_
<button onclick="check()">Check!</button>_x000D_
<br/>_x000D_
<br/>_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>_x000D_
<span>Year</span>_x000D_
</th>_x000D_
<th>_x000D_
<span>Month</span>_x000D_
</th>_x000D_
<th>_x000D_
<span>Day</span>_x000D_
</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>_x000D_
<span id="year"></span>_x000D_
</td>_x000D_
<td>_x000D_
<span id="month"></span>_x000D_
</td>_x000D_
<td>_x000D_
<span id="day"></span>_x000D_
</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
I also had this issue and what I did was create an AlertDialog and use the setItems() method along with the DialogInterface listener:
AlertDialog.Builder getImageFrom = new AlertDialog.Builder(Fotos.this);
getImageFrom.setTitle("Select:");
final CharSequence[] opsChars = {getResources().getString(R.string.takepic), getResources().getString(R.string.opengallery)};
getImageFrom.setItems(opsChars, new android.content.DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
if(which == 0){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}else
if(which == 1){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
getResources().getString(R.string.pickgallery)), SELECT_PICTURE);
}
dialog.dismiss();
}
});
Jumping off from Alex Montoya's approach for multiple file input elements
const inputFiles = document.querySelectorAll('input[type="file"]');
const formData = new FormData();
for (const file of inputFiles) {
formData.append(file.name, file.files[0]);
}
fetch(url, {
method: 'POST',
body: formData })
In general, I use nohup CMD &
to run a nohup background process. However, when the command is in a form that nohup
won't accept then I run it through bash -c "..."
.
For example:
nohup bash -c "(time ./script arg1 arg2 > script.out) &> time_n_err.out" &
stdout from the script gets written to script.out
, while stderr and the output of time
goes into time_n_err.out
.
So, in your case:
nohup bash -c "(time bash executeScript 1 input fileOutput > scrOutput) &> timeUse.txt" &
(setq tab-width 4)
(setq tab-stop-list '(4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80))
(setq indent-tabs-mode nil)
Actually whether there are digits or not is irrelevant. The . (dot) is forbidden if you want to cast to int. Dot can't - logically - be part of Integer definition, so even:
select cast ('7.0' as int)
select cast ('7.' as int)
will fail but both are fine for floats.
Set oShell = CreateObject ("WScript.Shell")
oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "
I think this is the best way:
this.stops.stream().filter(s -> Objects.equals(s.getStation().getName(), this.name)).findFirst().orElse(null);
The simple method is to share the mysql unix socket to host machine. Then connect through the socket
Steps:
mkdir /host
docker run -it -v /host:/shared <mysql image>
./etc/my.cnf
and change socket entry in the file to socket=/shared/mysql.sock
service mysql restart
in dockermysql -u root --socket=/host/mysql.sock
. If password use -p optionFunctional Testing: Application of test data derived from the specified functional requirements without regard to the final program structure. Also known as black-box testing.
Acceptance Testing: Formal testing conducted to determine whether or not a system satisfies its acceptance criteria—enables an end user to determine whether or not to accept the system.
As @Richard pointed out above, the onClick needs to have a capital 'C'.
$('#stop').click(function() {
$('next').attr('onClick','stopMoving()');
}
For [1], you can't: these operators are made to return a value, not perform operations.
The expression
a ? b : c
evaluates to b
if a
is true and evaluates to c
if a
is false.
The expression
b ?? c
evaluates to b
if b
is not null and evaluates to c
if b
is null.
If you write
return a ? b : c;
or
return b ?? c;
they will always return something.
For [2], you can write a function that returns the right value that performs your "multiple operations", but that's probably worse than just using if/else
.
If I understand what you're asking, this should do the trick:
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use
// window.innerWidth and window.innerHeight
var windowHeight;
if (typeof window.innerWidth != 'undefined')
{
windowHeight = window.innerHeight;
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first
// line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth != 'undefined'
&& document.documentElement.clientWidth != 0)
{
windowHeight = document.documentElement.clientHeight;
}
// older versions of IE
else
{
windowHeight = document.getElementsByTagName('body')[0].clientHeight;
}
document.getElementById("yourDiv").height = windowHeight - 300 + "px";
Using sets
will be screaming fast if you have any volume of data
If you are willing to use sets, you have the isdisjoint()
method which will check to see if the intersection between your operator list and your other list is empty.
MyOper = set(['AND', 'OR', 'NOT'])
MyList = set(['c1', 'c2', 'NOT', 'c3'])
while not MyList.isdisjoint(MyOper):
print "No boolean Operator"
You're near :)
First, the batch (%%variable) and Windows CMD (%variable) uses different variable naming. Second, i dont figure out how do you use zip from CMD. This is from Linux users i think. Use built-in zip manipulation is not like easy on Win, and even harder with batch scripting.
But you're lucky anyway. I got (extracted to target folder) zip.exe and cygwin1.dll from the cygwin package (3mb filesize both together) and start play with it right now.
Of course, i use CMD for better/faster testing instead batch. Only remember modify the %varname to %%varname before blame me :P
for /d %d in (*) do zip -r %d %d
Explanation:
for /d ...
that matches any folder inside. Only folder ignoring files. (use for /f to filesmatch)
for /d %d in ...
the %d tells cmd wich name do you wanna assign to your variable. I put d to match widh d (directory meaning).
for /d %d in (*) ...
Very important. That suposses that I CD
to desired folder, or run from. (*)
this will mean all on THIS dir, because we use /d
the files are not processed so no need to set a pattern, even if you can get only some folders if you need. You can use absolute paths. Not sure about issues with relatives from batch.
for /d %d in (*) do zip -r ...
Do ZIP is obvious. (exec zip itself and see the help display to use your custom rules). r- is for recursive, so anyting will be added.
for /d %d in (*) do zip -r %d %d
The first %d is the zip name. You can try with myzip.zip, but if will fail because if you have 2 or more folders the second cannot gave the name of the first and will not try to overwrite without more params. So, we pass %d to both, wich is the current for iteration folder name zipped into a file with the folder name. Is not neccesary to append ".zip" to name.
Is pretty short than i expected when start to play with.
<div class="text-align" style="text-align: center; ">
<img class="img-responsive" style="margin: auto;" alt="" src="images/x.png ?>">
</div>
you can try this.
Use plt.text() to put text in the plot.
Example:
import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
ind = np.arange(N)
#Creating a figure with some fig size
fig, ax = plt.subplots(figsize = (10,5))
ax.bar(ind,menMeans,width=0.4)
#Now the trick is here.
#plt.text() , you need to give (x,y) location , where you want to put the numbers,
#So here index will give you x pos and data+1 will provide a little gap in y axis.
for index,data in enumerate(menMeans):
plt.text(x=index , y =data+1 , s=f"{data}" , fontdict=dict(fontsize=20))
plt.tight_layout()
plt.show()
This will show the figure as:
I tried the solutions above yet the value that goes to the model were the formatted value then returning and giving me currencyPipe errors. So i had to
[ngModel]="transfer.amount | currency:'USD':true"
(blur)="addToAmount($event.target.value)"
(keypress)="validateOnlyNumbers($event)"
And on the function of addToAmount -> change on blur cause the ngModelChange was giving me cursor issues.
removeCurrencyPipeFormat(formatedNumber){
return formatedNumber.replace(/[$,]/g,"")
}
And removing the other non numeric values.
validateOnlyNumbers(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
You can use Postgres' SIMILAR TO
operator which supports alternations, i.e.
select * from table where lower(value) similar to '%(foo|bar|baz)%';
Commit merge changes solved my problem:
git commit -m "commit message"
If you're using data binding, then you need to use the ContentRendered event.
For the code below, the Header is NULL when the Loaded event is raised. However, Header gets its value when the ContentRendered event is raised.
<MenuItem Header="{Binding NewGame_Name}" Command="{Binding NewGameCommand}" />
In my experience all the files which i have downloaded from internet,gmail
are stored in
/sdcard/download
on ics
/sdcard/Download
You can access it using
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
In bash, we use
declare -A name_of_dictonary_variable
so that Bash understands it is a dictionary.
For e.g. you want to create sounds
dictionary then,
declare -A sounds
sounds[dog]="Bark"
sounds[wolf]="Howl"
where dog
and wolf
are "keys"
, and Bark
and Howl
are "values"
.
You can access all values using : echo ${sounds[@]}
OR echo ${sounds[*]}
You can access all keys only using: echo ${!sounds[@]}
And if you want any value for a particular key, you can use:
${sounds[dog]}
this will give you value (Bark
) for key (Dog
).