Use $('textarea').val('')
.
The problem with using
$('textarea').text('')
, or
$('textarea').html('')
for that matter is that it will only erase what was in the original DOM sent by the server. If a user clears it and then enters new input, the clear button will no longer work. Using .val('')
handles the user input case properly.
jQuery has a resize event handler which you can attach to the window, .resize(). So, if you put $(window).resize(function(){/* YOUR CODE HERE */})
then your code will be run every time the window is resized.
So, what you want is to run the code after the first page load and whenever the window is resized. Therefore you should pull the code into its own function and run that function in both instances.
// This function positions the footer based on window size
function positionFooter(){
var $containerHeight = $(window).height();
if ($containerHeight <= 818) {
$('.footer').css({
position: 'static',
bottom: 'auto',
left: 'auto'
});
}
else {
$('.footer').css({
position: 'absolute',
bottom: '3px',
left: '0px'
});
}
}
$(document).ready(function () {
positionFooter();//run when page first loads
});
$(window).resize(function () {
positionFooter();//run on every window resize
});
See: Cross-browser window resize event - JavaScript / jQuery
In regards to problems with Qt4, I couldn't use the qmake moc option mentioned above. But that wasn't the problem anyway. I had the following code in the class definition:
class ScreenWidget : public QGLWidget
{
Q_OBJECT // must include this if you use Qt signals/slots
...
};
I had to remove the line "Q_OBJECT" because I had no signals or slots defined.
Yes, you want to use tee
:
tee - read from standard input and write to standard output and files
Just pipe your command to tee and pass the file as an argument, like so:
exec 1 | tee ${LOG_FILE}
exec 2 | tee ${LOG_FILE}
This both prints the output to the STDOUT and writes the same output to a log file. See man tee
for more information.
Note that this won't write stderr to the log file, so if you want to combine the two streams then use:
exec 1 2>&1 | tee ${LOG_FILE}
Let's take a look at the list of Docker's technical features, and check which ones are provided by LXC and which ones aren't.
1) Filesystem isolation: each process container runs in a completely separate root filesystem.
Provided with plain LXC.
2) Resource isolation: system resources like cpu and memory can be allocated differently to each process container, using cgroups.
Provided with plain LXC.
3) Network isolation: each process container runs in its own network namespace, with a virtual interface and IP address of its own.
Provided with plain LXC.
4) Copy-on-write: root filesystems are created using copy-on-write, which makes deployment extremely fast, memory-cheap and disk-cheap.
This is provided by AUFS, a union filesystem that Docker depends on. You could set up AUFS yourself manually with LXC, but Docker uses it as a standard.
5) Logging: the standard streams (stdout/stderr/stdin) of each process container is collected and logged for real-time or batch retrieval.
Docker provides this.
6) Change management: changes to a container's filesystem can be committed into a new image and re-used to create more containers. No templating or manual configuration required.
"Templating or manual configuration" is a reference to LXC, where you would need to learn about both of these things. Docker allows you to treat containers in the way that you're used to treating virtual machines, without learning about LXC configuration.
7) Interactive shell: docker can allocate a pseudo-tty and attach to the standard input of any container, for example to run a throwaway interactive shell.
LXC already provides this.
I only just started learning about LXC and Docker, so I'd welcome any corrections or better answers.
You can actually chain multiple $lookup stages. Based on the names of the collections shared by profesor79, you can do this :
db.sivaUserInfo.aggregate([
{
$lookup: {
from: "sivaUserRole",
localField: "userId",
foreignField: "userId",
as: "userRole"
}
},
{
$unwind: "$userRole"
},
{
$lookup: {
from: "sivaUserInfo",
localField: "userId",
foreignField: "userId",
as: "userInfo"
}
},
{
$unwind: "$userInfo"
}
])
This will return the following structure :
{
"_id" : ObjectId("56d82612b63f1c31cf906003"),
"userId" : "AD",
"phone" : "0000000000",
"userRole" : {
"_id" : ObjectId("56d82612b63f1c31cf906003"),
"userId" : "AD",
"role" : "admin"
},
"userInfo" : {
"_id" : ObjectId("56d82612b63f1c31cf906003"),
"userId" : "AD",
"phone" : "0000000000"
}
}
Maybe this could be considered an anti-pattern because MongoDB wasn't meant to be relational but it is useful.
class Program
{
static void Main(string[] args)
{
string method = args[0]; // get name method
CallMethod(method);
}
public static void CallMethod(string method)
{
try
{
Type type = typeof(Program);
MethodInfo methodInfo = type.GetMethod(method);
methodInfo.Invoke(method, null);
}
catch(Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
Console.ReadKey();
}
}
public static void Hello()
{
string a = "hello world!";
Console.WriteLine(a);
Console.ReadKey();
}
}
You can also use Microsoft Visual Studio compiler instead of Cygwin or MinGW in Windows environment as the compiler for CLion.
Just go to find Actions in Help and type "Registry" without " and enable CLion.enable.msvc Now configure toolchain with Microsoft Visual Studio Compiler. (You need to download it if not already downloaded)
follow this link for more details: https://www.jetbrains.com/help/clion/quick-tutorial-on-configuring-clion-on-windows.html
setAutoSize method must come before setWidth:
$objPHPExcel->getActiveSheet()->getColumnDimensionByColumn('C')->setAutoSize(false);
$objPHPExcel->getActiveSheet()->getColumnDimensionByColumn('C')->setWidth('10');
Following are few libraries to create PDF with Java:
I have used iText for genarating PDF's with a little bit of pain in the past.
Or you can try using FOP: FOP is an XSL formatter written in Java. It is used in conjunction with an XSLT transformation engine to format XML documents into PDF.
git tag -l --format='%(contents)'
or
git for-each-ref refs/tags/ --format='%(contents)'
will output full annotation message for every tag (including signature if its signed).
%(contents:subject)
will output only first line%(contents:body)
will output annotation without first line and signature (useful text only)%(contents:signature)
will output only PGP-signatureSee more in man git-for-each-ref
“Field names” section.
Format with Currency format string
=Format(Fields!Price.Value, "C")
It will give you 2 decimal places with "$" prefixed.
You can find other format strings on MSDN: Adding Style and Formatting to a ReportViewer Report
Note: The MSDN article has been archived to the "VS2005_General" document, which is no longer directly accessible online. Here is the excerpt of the formatting strings referenced:
Formatting Numbers
The following table lists common .NET Framework number formatting strings.
Format string, Name
C or c Currency
D or d Decimal
E or e Scientific
F or f Fixed-point
G or g General
N or n Number
P or p Percentage
R or r Round-trip
X or x Hexadecimal
You can modify many of the format strings to include a precision specifier that defines the number of digits to the right of the
decimal point. For example, a formatting string of D0 formats the number so that it has no digits after the decimal point. You
can also use custom formatting strings, for example, #,###.
Formatting Dates
The following table lists common .NET Framework date formatting strings.
Format string, Name
d Short date
D Long date
t Short time
T Long time
f Full date/time (short time)
F Full date/time (long time)
g General date/time (short time)
G General date/time (long time)
M or m Month day
R or r RFC1123 pattern
Y or y Year month
You can also a use custom formatting strings; for example, dd/MM/yy. For more information about .NET Framework formatting strings, see Formatting Types.
This is how it should be:
Code:
$(function(){
$("button").mouseover(function(){
var $p = $("#P44");
$p.stop()
.css("background-color","yellow")
.hide(1500, function() {
$p.css("background-color","red")
.show(1500);
});
});
});
Demo: http://jsfiddle.net/p7w9W/2/
Explanation:
You have to wait for the callback on the animating functions before you switch background color. You should also not use only numeric ID:s, and if you have an ID of your <p>
there you shouldn't include a class in your selector.
I also enhanced your code (caching of the jQuery object, chaining, etc.)
Update: As suggested by VKolev the color is now changing when the item is hidden.
One option is just to use the regex |
character to try to match each of the substrings in the words in your Series s
(still using str.contains
).
You can construct the regex by joining the words in searchfor
with |
:
>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0 cat
1 hat
2 dog
3 fog
dtype: object
As @AndyHayden noted in the comments below, take care if your substrings have special characters such as $
and ^
which you want to match literally. These characters have specific meanings in the context of regular expressions and will affect the matching.
You can make your list of substrings safer by escaping non-alphanumeric characters with re.escape
:
>>> import re
>>> matches = ['$money', 'x^y']
>>> safe_matches = [re.escape(m) for m in matches]
>>> safe_matches
['\\$money', 'x\\^y']
The strings with in this new list will match each character literally when used with str.contains
.
I faced this same issue on CentOS 7 years later
Posting hoping that it may help others...
Steps:
FIRST, configure the php-fpm settings:
-> systemctl stop php-fpm.service
-> cd /etc/php-fpm.d
-> ls -hal
(should see a www.conf file)
-> cp www.conf www.conf.backup
(back file up just in case)
-> vi www.conf
-> :/listen =
(to get to the line we need to change)
-> i
(to enter VI's text insertion mode)
-> change from listen = 127.0.0.1:9000
TO listen = /var/run/php-fpm/php-fpm.sock
-> Esc
then :/listen.owner
(to find it) then i
(to change)
-> UNCOMMENT the listen.owner = nobody
AND listen.group = nobody
lines
-> Hit Esc
then type :/user =
then i
-> change user = apache
TO user = nginx
-> AND change group = apache
TO group = nginx
-> Hit Esc
then :wq
(to save and quit)
-> systemctl start php-fpm.service
(now you will have a php-fpm.sock file)
SECOND, you configure your server {}
block in your /etc/nginx/nginx.conf
file. Then run:systemctl restart nginx.service
FINALLY, create a new .php file in your /usr/share/nginx/html directory for your Nginx server to serve up via the internet browser as a test.
-> vi /usr/share/nginx/html/mytest.php
-> type o
-> <?php echo date("Y/m/d-l"); ?>
(PHP page will print date and day in browser)
-> Hit Esc
-> type :wq
(to save and quite VI editor)
-> open up a browser and go to: http://yourDomainOrIPAddress/mytest.php
(you should see the date and day printed)
Port: 25 or 587 (some providers block port 25)
I work by changing the port after deploying the app to the server.
$mail->Port = 25;
$mail->Port = 587;
GL
The simplest that helped me:
rm -rf _dir_in_question_
svn up
If you have changes in the problematic dir, then this is not a good solution for you.
Use SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d
.
I choose to use both methods. Cellpadding on the table as a fallback in case the inline style doesn't stick and inline style for most clients.
<table cellpadding="5">_x000D_
<tr>_x000D_
<td style='padding:5px 10px 5px 5px'>Content</td>_x000D_
<td style='padding:5px 10px 5px 5px'>Content</td>_x000D_
</tr>_x000D_
</table>
_x000D_
For Mac:
Click on the first cell having the formula and press Ctrl + Shift + down_arrow. This will select the last cell in the column used on the worksheet.
command + D. (don't use ctrl) This will fill the formula in the remaining cells.
check available Java versions on your Linux system by using update-alternatives command:
$ sudo update-alternatives --display java
Now that there are suitable candidates to change to, you can switch the default Java version among available Java JREs by running the following command:
$ sudo update-alternatives --config java
When prompted, select the Java version you would like to use.1 or 2 or 3 or etc..
Now you can verify the default Java version changed as follows.
$ java -version
Both isVisible()
and isAdded()
return true
as soon as the Fragment
is created, and not even actually visible. The only solution that actually works is:
if (isAdded() && isVisible() && getUserVisibleHint()) {
// ... do your thing
}
This does the job. Period.
NOTICE: getUserVisibleHint() is now deprecated. be careful.
Have you tried not setting the responseType and just type casting the response?
This is what worked for me:
/**
* Client for consuming recordings HTTP API endpoint.
*/
@Injectable({
providedIn: 'root'
})
export class DownloadUrlClientService {
private _log = Log.create('DownloadUrlClientService');
constructor(
private _http: HttpClient,
) {}
private async _getUrl(url: string): Promise<string> {
const httpOptions = {headers: new HttpHeaders({'auth': 'false'})};
// const httpOptions = {headers: new HttpHeaders({'auth': 'false'}), responseType: 'text'};
const res = await (this._http.get(url, httpOptions) as Observable<string>).toPromise();
// const res = await (this._http.get(url, httpOptions)).toPromise();
return res;
}
}
Another way of doing it is by using the read.table()
argument colClasses
to specify the column type by making colClasses=c(*column class types*)
.
If there are 6 columns whose members you want as numeric, you need to repeat the character string "numeric"
six times separated by commas, importing the data frame, and as.matrix()
the data frame.
P.S. looks like you have headers, so I put header=T
.
as.matrix(read.table(SFI.matrix,header=T,
colClasses=c("numeric","numeric","numeric","numeric","numeric","numeric"),
sep=","))
Although this is a old thread, I have come across the same error recently while running nslookup in CentOS 7 and google search led me to some of the discussions in SO including this one. However, adding the nameservers entries to /etc/resolv.conf alone did not help as the nameserver values in resolv.conf were overwritten by the NetworkManager with the default DNS nameservers that are in the eth profile associated to the ethernet IP config.
As mentioned by @m-canvar, set the following entries in /etc/resolv.conf
search yourdomain.com
nameserver 8.8.8.8
nameserver 4.2.2.1
nameserver 8.8.4.4
To prevent overwriting these entries by NetworkManager, there are two two approaches:
Option 1: Either set NM_CONTROLLED=no in the eth profile associated to the IPv4/IPv6 profile.
Option 2: Disable NetworkManager service from running.
chkconfig NetworkManager off
service NetworkManager stop
More details can be referred in my post about this error and solution.
You want to replace the Backslash?
Try stripcslashes:
Also, I add to do the following steps so that the git repo would be correctly linked with the IDE:
$ git reset <commit #>
$ git checkout <file/path>
I hope this was helpful!!
This was pretty well answered over here: How to make a YouTube embedded video a full page width one?
If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)
<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
of the video it should play on load. Here's a demo over at jsfiddle.
I had same issue after importing maven project consisting of nested micro services. This is how I got it resolved in Eclipse:
I just solved this error happening in my tests.
Just make sure your test class has all dependencies in the attributes of the class being tested annotated with @MockBean
so SpringBoot test context can wire your classes correctly.
Only if you are testing controller: you need also class annotations to load the Controller context propertly.
Check it out:
@DisplayName("UserController Adapter Test")
@WebMvcTest(UserController.class)
@AutoConfigureMockMvc(addFilters = false)
@Import(TestConfig.class)
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@MockBean
private CreateUserCommand createUserCommand;
@MockBean
private GetUserListQuery getUserListQuery;
@MockBean
private GetUserQuery getUserQuery;
Suppose you have Vue project created with vue-cli (e.g. vue init webpack my-project). Go to project dir and run
npm install jquery --save
Open file build/webpack.base.conf.js
and add plugins
:
module.exports = {
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jquery: 'jquery',
'window.jQuery': 'jquery',
jQuery: 'jquery'
})
]
...
}
Also at top of file add:
const webpack = require('webpack')
If you are using ESLint, open .eslintrc.js
and add next globals: {
module.exports = {
globals: {
"$": true,
"jQuery": true
},
...
Now you are ready to go. Use $ anywhere in your js.
NOTE You don't need to include expose loader or any other stuff to use this.
Originally from https://maketips.net/tip/223/how-to-include-jquery-into-vuejs
In Android studio 0.8 and after
Right click on app folder then New > Image Asset
Browse for best resolution image you have in "Image file" field
hit Next The rest will be generated
Try shutil.rmtree
:
import shutil
shutil.rmtree('/path/to/your/dir/')
If .NET 4 is available to you, check out: http://visitmix.com/writings/the-rise-of-json (archive.org)
Here is a snippet from that site:
WebClient webClient = new WebClient();
dynamic result = JsonValue.Parse(webClient.DownloadString("https://api.foursquare.com/v2/users/self?oauth_token=XXXXXXX"));
Console.WriteLine(result.response.user.firstName);
That last Console.WriteLine is pretty sweet...
The -fpermissive
flag causes the compiler to report some things that are actually errors (but are permitted by some compilers) as warnings, to permit code to compile even if it doesn't conform to the language rules. You really should fix the underlying problem. Post the smallest, compilable code sample that demonstrates the problem.
-fpermissive
Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using-fpermissive
will allow some nonconforming code to compile.
remember to set you username and password if required:
http://USERNAME:[email protected]:8080
Example:
npm config set proxy http://USERNAME:[email protected]:8080
Both .ics and .vcs files are in ASCII. If you use "Save As" option to save a calendar entry (Appt, Meeting Request/Response/Postpone/Cancel and etc) in both .ics and .vcs format and use vimdiff, you can easily see the difference.
Both .vcs (vCal) and .ics (iCal) belongs to the same VCALENDAR camp, but .vcs file shows "VERSION:1.0" whereas .ics file uses "VERSION:2.0".
The spec for vCalendar v1.0 can be found at http://www.imc.org/pdi/pdiproddev.html. The spec for iCalendar (vCalendar v2.0) is in RFC5545. In general, the newer is better, and that is true for Outlook 2007 and onward, but not for Outlook 2003.
For Outlook 2003, the behavior is peculiar. It can save the same calendar entry in both .ics and .vcs format, but it only read & display .vcs file correctly. It can read .ics file but it omits some fields and does not display it in calendar mode. My guess is that back then Microsoft wanted to provide .ics to be compatible with Mac's iCal but not quite committed to v2.0 yet.
So I would say for Outlook 2003, .vcs is the native format.
Yes, to answer your question, it is possible to use JavaScript as a "regular" scripting language from the command line, without a browser. Since others have not mentioned it yet, I see that it is worth mentioning:
On Debian-based systems (and this includes Ubuntu, Linux Mint, and aptosid/sidux, at least), besides the options of installing Rhino and others already mentioned, you have have other options:
Install the libmozjs-24-bin
package, which will provide you with Mozilla's Spidermonkey engine on the command line as a simple js24
, which can be used also as an interactive interpreter. (The 24
in the name means that it corresponds to version 24 of Firefox).
Install the libv8-dev
package, which will provide you Google's V8 engine. It has, as one of its examples, the file /usr/share/doc/libv8-dev/examples/shell.cc.gz
which you can uncompress and compile very simply (e.g., g++ -Os shell.cc -o shell -lv8
).
Install the package nodejs
and it will be available both as the executable nodejs
and as an alternative (in the Debian-sense) to provide the js
executable. JIT compilation is provided as a courtesy of V8.
Install the package libjavascriptcoregtk-3.0-bin
and use WebKit's JavaScriptCore interpreter (jsc
) as a regular interpreter from the command-line. And this is without needing to have access to a Mac. On many platforms (e.g., x86 and x86_64), this interpreter will come with a JIT compiler.
So, with almost no compilation you will have three of the heavy-weight JavaScript engines at your disposal.
Once you have things installed, you can simply create files with the #!/usr/bin/js
shebang line and things will just work:
$ cat foo.js
#!/usr/bin/js
console.log("Hello, world!");
$ ls -lAF /usr/bin/js /etc/alternatives/js /usr/bin/nodejs
lrwxrwxrwx 1 root root 15 Jul 16 04:26 /etc/alternatives/js -> /usr/bin/nodejs*
lrwxrwxrwx 1 root root 20 Jul 16 04:26 /usr/bin/js -> /etc/alternatives/js*
-rwxr-xr-x 1 root root 1422004 Apr 28 20:31 /usr/bin/nodejs*
$ chmod a+x foo.js
$ ./foo.js
Hello, world!
$ js ./foo.js
Hello, world!
$
We do this kind of XML parsing all the time. The key is defining where the parsing method will leave the reader on exit. If you always leave the reader on the next element following the element that was first read then you can safely and predictably read in the XML stream. So if the reader is currently indexing the <Account>
element, after parsing the reader will index the </Accounts>
closing tag.
The parsing code looks something like this:
public class Account
{
string _accountId;
string _nameOfKin;
Statements _statmentsAvailable;
public void ReadFromXml( XmlReader reader )
{
reader.MoveToContent();
// Read node attributes
_accountId = reader.GetAttribute( "accountId" );
...
if( reader.IsEmptyElement ) { reader.Read(); return; }
reader.Read();
while( ! reader.EOF )
{
if( reader.IsStartElement() )
{
switch( reader.Name )
{
// Read element for a property of this class
case "NameOfKin":
_nameOfKin = reader.ReadElementContentAsString();
break;
// Starting sub-list
case "StatementsAvailable":
_statementsAvailable = new Statements();
_statementsAvailable.Read( reader );
break;
default:
reader.Skip();
}
}
else
{
reader.Read();
break;
}
}
}
}
The Statements
class just reads in the <StatementsAvailable>
node
public class Statements
{
List<Statement> _statements = new List<Statement>();
public void ReadFromXml( XmlReader reader )
{
reader.MoveToContent();
if( reader.IsEmptyElement ) { reader.Read(); return; }
reader.Read();
while( ! reader.EOF )
{
if( reader.IsStartElement() )
{
if( reader.Name == "Statement" )
{
var statement = new Statement();
statement.ReadFromXml( reader );
_statements.Add( statement );
}
else
{
reader.Skip();
}
}
else
{
reader.Read();
break;
}
}
}
}
The Statement
class would look very much the same
public class Statement
{
string _satementId;
public void ReadFromXml( XmlReader reader )
{
reader.MoveToContent();
// Read noe attributes
_statementId = reader.GetAttribute( "statementId" );
...
if( reader.IsEmptyElement ) { reader.Read(); return; }
reader.Read();
while( ! reader.EOF )
{
....same basic loop
}
}
}
For me following worked:
in directive declare it like this:
.directive('myDirective', function() {
return {
restrict: 'E',
replace: true,
scope: {
myFunction: '=',
},
templateUrl: 'myDirective.html'
};
})
In directive template use it in following way:
<select ng-change="myFunction(selectedAmount)">
And then when you use the directive, pass the function like this:
<data-my-directive
data-my-function="setSelectedAmount">
</data-my-directive>
You pass the function by its declaration and it is called from directive and parameters are populated.
try:
string.decode('utf-8') # or:
unicode(string, 'utf-8')
edit:
'(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'.decode('utf-8')
gives u'(\uff61\uff65\u03c9\uff65\uff61)\uff89'
, which is correct.
so your problem must be at some oter place, possibly if you try to do something with it were there is an implicit conversion going on (could be printing, writing to a stream...)
to say more we'll need to see some code.
I got the error "The table/view 'dbo.vMyView' does not have a primary key defined" after I created a view in SQL server query designer. I solved the problem by using ISNULL on a column to force entity framework to use it as a primary key. You might have to restart visual studio to get the warnings to go away.
CREATE VIEW [dbo].[vMyView]
AS
SELECT ISNULL(Id, -1) AS IdPrimaryKey, Name
FROM dbo.MyTable
If you prefer console snippet, raser, than filename, you can do this:
window.open(URL.createObjectURL(
new Blob([JSON.stringify(JSON)], {
type: 'application/binary'}
)
))
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')
The column STATUS tells you whether the object is VALID or INVALID. If it is invalid, you have to try a recompile, ORACLE can't tell you if it will work before.
Just use the gcloud projects list
to get the project you have . Get the PROJECT_ID of the poject to use
After that use gcloud set project --project=PROJECT_ID
to set the project.
First off, avoid using a cursor if at all possible. Here are some resources for rooting it out when it seems you can't do without:
There Must Be 15 Ways To Lose Your Cursors... part 1, Introduction
Row-By-Row Processing Without Cursor
That said, though, you may be stuck with one after all--I don't know enough from your question to be sure that either of those apply. If that's the case, you've got a different problem--the select statement for your cursor must be an actual SELECT statement, not an EXECUTE statement. You're stuck.
But see the answer from cmsjr (which came in while I was writing) about using a temp table. I'd avoid global cursors even more than "plain" ones....
For me no work i need upgrade pip....
Debian/Ubuntu
install dependencies
sudo apt-get install libpython-dev libssl-dev libffi-dev
upgrade pip and install packages
sudo pip install -U pip
sudo pip install -U pyopenssl ndg-httpsclient pyasn1
If you want remove dependencies
sudo apt-get remove --purge libpython-dev libssl-dev libffi-dev
sudo apt-get autoremove
You can change axis text and label size with arguments axis.text=
and axis.title=
in function theme()
. If you need, for example, change only x axis title size, then use axis.title.x=
.
g+theme(axis.text=element_text(size=12),
axis.title=element_text(size=14,face="bold"))
There is good examples about setting of different theme()
parameters in ggplot2 page.
Adding on, you can turn off the creation of vshost files for your Release build configuration and have it enabled for Debug.
Steps
Reference
Excerpt from MSDN How to: Disable the Hosting Process
Calls to certain APIs can be affected when the hosting process is enabled. In these cases, it is necessary to disable the hosting process to return the correct results.
To disable the hosting process
When the hosting process is disabled, several debugging features are unavailable or experience decreased performance. For more information, see Debugging and the Hosting Process.
In general, when the hosting process is disabled:
- The time needed to begin debugging .NET Framework applications increases.
- Design-time expression evaluation is unavailable.
- Partial trust debugging is unavailable.
I met the same problem, the error message and OS info are as follows
OS info:
CentOS release 6.5 (Final)
Linux 192-168-30-213 2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
error info:
Initialized empty Git repository in /home/techops/pyenv/.git/ Password: error: while accessing https://[email protected]/pyenv/pyenv.git/info/refs
fatal: HTTP request failed
git & curl version info
git info :git version 1.7.1
curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2 Protocols: tftp ftp telnet dict ldap ldaps http file https ftps scp sftp Features: GSS-Negotiate IDN IPv6 Largefile NTLM SSL libz
debugging
$ curl --verbose https://github.com
- About to connect() to github.com port 443 (#0)
- Trying 13.229.188.59... connected
- Connected to github.com (13.229.188.59) port 443 (#0)
- Initializing NSS with certpath: sql:/etc/pki/nssdb
- CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none
- NSS error -12190
Error in TLS handshake, trying SSLv3... GET / HTTP/1.1 User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2 Host: github.com Accept: /
Connection died, retrying a fresh connect
- Closing connection #0
- Issue another request to this URL: 'https://github.com'
- About to connect() to github.com port 443 (#0)
- Trying 13.229.188.59... connected
- Connected to github.com (13.229.188.59) port 443 (#0)
- TLS disabled due to previous handshake failure
- CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none
- NSS error -12286
- Closing connection #0
- SSL connect error curl: (35) SSL connect error
after upgrading curl , libcurl and nss , git clone works fine again, so here it is. the update command is as follows
sudo yum update -y nss curl libcurl
If you're on a Mac and have XCode, then you have FileMerge installed. The terminal command is opendiff, so you can just do git difftool -t opendiff
Have a look at Java ANPR. Free license plate recognition...
There is an important detail that has been omitted in the answer above.
MySQL imposes a limit of 65,535 bytes for the max size of each row.
The size of a VARCHAR
column is counted towards the maximum row size, while TEXT
columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR
field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.
Also note that the actual number of bytes required by a VARCHAR
field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4
(which you almost certainly should) it will use up even more of your maximum row size.
Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR
/TEXT
field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)
Reasons to use TEXT
:
Reasons to use VARCHAR
:
One issue could be that if either make, model, or [serial number] were null, values would never get returned. Because string concatenations with null values always result in null, and not in () with null will always return nothing. The remedy for this is to use an operator such as IsNull(make, '') + IsNull(Model, ''), etc.
Go to project properties -> configurations properties -> C/C++ -> treats warning as error -> No (/WX-)
.
In Windows server 2012. Go to ISS -> Modules -> Remove the ServiceModel3-0.
There are two obvious issues with the set literal syntax:
my_set = {'foo', 'bar', 'baz'}
It's not available before Python 2.7
There's no way to express an empty set using that syntax (using {}
creates an empty dict)
Those may or may not be important to you.
The section of the docs outlining this syntax is here.
Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable
to true) on all brokers first.
Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable
is by default true
.
Follow this step by step process for manual deletion of topics
logs.dirs
and log.dir
properties) with rm -rf
commandzookeeper-shell.sh host:port
ls /brokers/topics
rmr /brokers/topics/yourtopic
kafka-topics.sh --list --zookeeper host:port
Local variables are automatically freed when the function ends, you don't need to free them by yourself. You only free dynamically allocated memory (e.g using malloc
) as it's allocated on the heap:
char *arr = malloc(3 * sizeof(char));
strcpy(arr, "bo");
// ...
free(arr);
More about dynamic memory allocation: http://en.wikipedia.org/wiki/C_dynamic_memory_allocation
That is correct behaviour, it's up to you to create the contents for the 404 page.
The 404 header is used by spiders and download-managers to determine if the file exists.
(A page with a 404 header won't be indexed by google or other search-engines)
Normal users however don't look at http-headers and use the page as a normal page.
If you want the latest file in the directory and you are using only the LastWriteTime
to determine the latest file, you can do something like below:
gci path | sort LastWriteTime | select -last 1
On the other hand, if you want to only rely on the names that have the dates in them, you should be able to something similar
gci path | select -last 1
Also, if there are directories in the directory, you might want to add a ?{-not $_.PsIsContainer}
Use substring method like this::
str.substring(str.length()-2);
<ul>
<li><strong>This text will be bold.</strong>This text will NOT be bold.
</li>
</ul>
Try bellow code with jquery :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<script>
$(document).ready(function(){
$('#myForm').on('change', "input#MyFile", function (e) {
e.preventDefault();
$("#myForm").submit();
});
});
</script>
<body>
<div id="content">
<form id="myForm" action="action.php" method="POST" enctype="multipart/form-data">
<input type="file" id="MyFile" value="Upload" />
</form>
</div>
</body>
</html>
Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.
-
is the 'binary operator' your error is referencing, and either CurrentDay
or MA
(or both) are non-numeric.
A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). +
is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).
R only knows how to apply +
(and other binary operators, such as -
) to numeric arguments:
> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator
When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.
EDIT:
Your error lies in the use of [
instead of [[
. Because Day
is a list, subsetting with [
will return a list, not a numeric vector. [[
, however, returns an object of the class of the item contained in the list:
> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator
> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3
Transaction
, as you've defined it, returns a list of two vectors. Above, Day
is a list contain one vector. Day2
, however, is simply a vector.
According to the source code, the maximum size of a list is PY_SSIZE_T_MAX/sizeof(PyObject*)
.
PY_SSIZE_T_MAX
is defined in pyport.h to be ((size_t) -1)>>1
On a regular 32bit system, this is (4294967295 / 2) / 4 or 536870912.
Therefore the maximum size of a python list on a 32 bit system is 536,870,912 elements.
As long as the number of elements you have is equal or below this, all list functions should operate correctly.
If you are using Count, or have created your own Count-style dict and want to show the name of the item and the count of it, you can iterate around the dictionary like so:
top_10_words = Counter(my_long_list_of_words)
# Iterate around the dictionary
for word in top_10_words:
# print the word
print word[0]
# print the count
print word[1]
or to iterate through this in a template:
{% for word in top_10_words %}
<p>Word: {{ word.0 }}</p>
<p>Count: {{ word.1 }}</p>
{% endfor %}
Hope this helps someone
System.Diagnostics.Debug.WriteLine()
will work, but you have to be looking in the right place for the output. In Visual Studio 2010, on the menu bar, click Debug -> Windows -> Output. Now, at the bottom of the screen docked next to your error list, there should be an output tab. Click it and double check it's showing output from the debug stream on the dropdown list.
P.S.: I think the output window shows on a fresh install, but I can't remember. If it doesn't, or if you closed it by accident, follow these instructions.
Here is the classical Bank Account Balance example which will help newbies to understand Threads in Java easily w.r.t. race conditions:
public class BankAccount {
/**
* @param args
*/
int accountNumber;
double accountBalance;
public synchronized boolean Deposit(double amount){
double newAccountBalance=0;
if(amount<=0){
return false;
}
else {
newAccountBalance = accountBalance+amount;
accountBalance=newAccountBalance;
return true;
}
}
public synchronized boolean Withdraw(double amount){
double newAccountBalance=0;
if(amount>accountBalance){
return false;
}
else{
newAccountBalance = accountBalance-amount;
accountBalance=newAccountBalance;
return true;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
BankAccount b = new BankAccount();
b.accountBalance=2000;
System.out.println(b.Withdraw(3000));
}
I was a little bit worried about using only touchmove for my project, since it only seems to fire when your touch moves from one location to another (and not on the initial touch). So I combined it with touchstart, and this seems to work very well for the initial touch and any movements.
<script>
function doTouch(e) {
e.preventDefault();
var touch = e.touches[0];
document.getElementById("xtext").innerHTML = touch.pageX;
document.getElementById("ytext").innerHTML = touch.pageY;
}
document.addEventListener('touchstart', function(e) {doTouch(e);}, false);
document.addEventListener('touchmove', function(e) {doTouch(e);}, false);
</script>
X: <div id="xtext">0</div>
Y: <div id="ytext">0</div>
/^((([a-zA-Z]{1,2})|([0-9]{1,2})|([a-zA-Z0-9]{1,2})|([a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]))\.)+[a-zA-Z]{2,6}$/
([a-zA-Z]{1,2})
-> for accepting only two characters.
([0-9]{1,2})
-> for accepting two numbers only
if anything exceeds beyond two ([a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9])
this regex will take care of that.
If we want to do the matching for at least one time +
will be used.
Kotlin syntax:
lateinit var binding: MartianDataBinding
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.martian_data, container, false)
return binding.root
}
You need to first find iframe
. You can do so using following statement.
WebElement iFrame= driver.findElement(By.tagName("iframe"));
Then, you can swith to it using switchTo
method on you WebDriver
object.
driver.switchTo().frame(iFrame);
And to move back to the parent frame, you can either use switchTo().parentFrame()
or if you want to get back to the main (or most parent) frame, you can use switchTo().defaultContent();
.
driver.switchTo().parentFrame(); // to move back to parent frame
driver.switchTo().defaultContent(); // to move back to most parent or main frame
Hope it helps.
The solutions above will work if you're looking to convert a single value for "seconds since midnight" on a date to a datetime object or a string with HH:MM:SS, but I landed on this page because I wanted to do this on a whole dataframe column in pandas. If anyone else is wondering how to do this for more than a single value at a time, what ended up working for me was:
mydate='2015-03-01'
df['datetime'] = datetime.datetime(mydate) + \
pandas.to_timedelta(df['seconds_since_midnight'], 's')
From your post I gather that you want to compare dates, not arrays. If this is the case, then use the appropriate object: a datetime
object.
Please check the documentation for the datetime module. Dates are a tough cookie. Use reliable algorithms.
Oh my God. not need to do anything special. only in your post section do as follows:
$.post(yourURL,{ '': results})(function(e){ ...}
In server use this:
public ActionResult MethodName(List<yourViewModel> model){...}
this link help you to done ...
<input type="text" id="text" name="search">
<table id="table_data">
<tr class="listR"><td>PHP</td></tr>
<tr class="listR"><td>MySql</td></tr>
<tr class="listR"><td>AJAX</td></tr>
<tr class="listR"><td>jQuery</td></tr>
<tr class="listR"><td>JavaScript</td></tr>
<tr class="listR"><td>HTML</td></tr>
<tr class="listR"><td>CSS</td></tr>
<tr class="listR"><td>CSS3</td></tr>
</table>
$("#textbox").on('keyup',function(){
var f = $(this).val();
$("#table_data tr.listR").each(function(){
if ($(this).text().search(new RegExp(f, "i")) < 0) {
$(this).fadeOut();
} else {
$(this).show();
}
});
});
Demo You can perform by search() method with use RegExp matching text
This is story from my workplace:
- We try to upload multiply images and document files use Struts 1 and Tomcat 7.x.
- We try to write uploaded files to file system, filename and full path to database records.
- We try to separate file folders outside web app directory. (*)
The below solution is pretty simple, effective for requirement (*):
In file META-INF/context.xml
file with the following content:
(Example, my application run at http://localhost:8080/ABC
, my application / project named ABC
).
(this is also full content of file context.xml
)
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/ABC" aliases="/images=D:\images,/docs=D:\docs"/>
(works with Tomcat version 7 or later)
Result: We have been created 2 alias. For example, we save images at: D:\images\foo.jpg
and view from link or using image tag:
<img src="http://localhost:8080/ABC/images/foo.jsp" alt="Foo" height="142" width="142">
or
<img src="/images/foo.jsp" alt="Foo" height="142" width="142">
(I use Netbeans 7.x, Netbeans seem auto create file WEB-INF\context.xml
)
Have you considered fetching the HTML separately, and then loading it into a webview?
String fetchContent(WebView view, String url) throws IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = httpClient.execute(get);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
HttpEntity entity = response.getEntity();
String html = EntityUtils.toString(entity); // assume html for simplicity
view.loadDataWithBaseURL(url, html, "text/html", "utf-8", url); // todo: get mime, charset from entity
if (statusCode != 200) {
// handle fail
}
return html;
}
look at this
https://codepen.io/bagdaulet/pen/bzdKjL
getElementById fastest than querySelector on 25%
jquery is slowest
var q = time_my_script(function() {
for (i = 0; i < 1000000; i++) {
var w = document.querySelector('#ll');
}
});
console.log('querySelector: '+q+'ms');
There seems to be some debate whether using StringBuilder is still needed with current compilers. So I thought I'll give my 2 cents of experience.
I have a JDBC
result set of 10k records (yes, I need all of them in one batch.) Using the + operator takes about 5 minutes on my machine with Java 1.8
. Using stringBuilder.append("")
takes less than a second for the same query.
So the difference is huge. Inside a loop StringBuilder
is much faster.
Simple 'docker' command knows nothing about 'worker' container. Use command like this
docker-compose -f docker-compose.yml restart worker
Not to High-Jack this question but the note needs to be made that you need to use (N)VARCHAR instead of (N)CHAR data-type.
RIGHT('000' + CAST(@number1 AS NCHAR(3)), 3 )
Above segment, will not produce the correct response from SQL 2005
RIGHT('000' + CAST(@number1 AS NVARCHAR(3)), 3 )
Above segment, will produce the desired response from SQL 2005
The the varchar will provide you with the desired prefix length on the fly. Where as the fixed length data type will require length designation and adjustments.
As a spin off from some other answers here, I offer a really simple and flexible way to define a set of characters that you want to limit a string's content to. In this case, I'm allowing alphanumerics PLUS dash and underscore. Just add or remove characters from my PERMITTED_CHARS
as suits your use case.
PERMITTED_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"
someString = "".join(c for c in someString if c in PERMITTED_CHARS)
All your problems are that you are mixing content type negotiation with parameter passing. They are things at different levels. More specific, for your question 2, you constructed the response header with the media type your want to return. The actual content negotiation is based on the accept media type in your request header, not response header. At the point the execution reaches the implementation of the method getPersonFormat, I am not sure whether the content negotiation has been done or not. Depends on the implementation. If not and you want to make the thing work, you can overwrite the request header accept type with what you want to return.
return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);
That is because you are opening , writing and closing the file 10 times inside your for loop
myfile = open('xyz.txt', 'w')
myfile.writelines(var1)
myfile.close()
You should open and close your file outside for loop.
myfile = open('xyz.txt', 'w')
for line in lines:
var1, var2 = line.split(",");
myfile.write("%s\n" % var1)
myfile.close()
text_file.close()
You should also notice to use write and not writelines.
writelines
writes a list of lines to your file.
Also you should check out the answers posted by folks here that uses with
statement. That is the elegant way to do file read/write operations in Python
If you have a polyfill for URLSearchParams
or simply don't have to support Internet Explorer, that's what I would use like suggested in other answers here. If you don't want to depend on URLSearchParams
, that's how I would do it:
function removeParameterFromUrl(url, parameter) {
const replacer = (m, p1, p2) => (p1 === '?' && p2 === '&' ? '?' : p2 || '')
return url.replace(new RegExp(`([?&])${parameter}=[^&#]+([&#])?`), replacer)
}
It will replace a parameter preceded by ?
(p1
) and followed by &
(p2
) with ?
to make sure the list of parameters still starts with a question mark, otherwise, it will replace it with the next separator (p2
): could be &
, or #
, or undefined
which falls back to an empty string.
WebKit is a layout engine designed to allow web browsers to render web pages. The WebKit engine provides a set of classes to display web content in windows, and implements browser features such as following links when clicked by the user, managing a back-forward list, and managing a history of pages recently visited.
WebKit was originally created as a fork of KHTML as the layout engine for Apple's Safari; it is portable to many other computing platforms. It is also used in Google's Chrome Browser.
WebKit's WebCore and JavaScriptCore components are available under the GNU Lesser General Public License, and the rest of WebKit is available under a BSD-style license.
Source Wikipedia
For further information about layout engines you can look here
memory mapping is not only used to map files into memory but is also a tool to request RAM from kernel. These are those inode 0 entries - your stack, heap, bss segments and more
I've uploaded a simple java program which takes your project location and the dimension file you want as input. Based on that, it would output the corresponding dimension file in the console. Here's the link to it:
https://github.com/akeshwar/Dimens-for-different-screens-in-Android/blob/master/Main.java
Here's the full code for the reference:
public class Main {
/**
* You can change your factors here. The current factors are in accordance with the official documentation.
*/
private static final double LDPI_FACTOR = 0.375;
private static final double MDPI_FACTOR = 0.5;
private static final double HDPI_FACTOR = 0.75;
private static final double XHDPI_FACTOR = 1.0;
private static final double XXHDPI_FACTOR = 1.5;
private static final double XXXHDPI_FACTOR = 2.0;
private static double factor;
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter the location of the project/module");
String projectPath = in.nextLine();
System.out.println("Which of the following dimension file do you want?\n1. ldpi \n2. mdpi \n3. hdpi \n4. xhdpi \n5. xxhdpi \n6. xxxhdpi");
int dimenType = in.nextInt();
switch (dimenType) {
case 1: factor = LDPI_FACTOR;
break;
case 2: factor = MDPI_FACTOR;
break;
case 3: factor = HDPI_FACTOR;
break;
case 4: factor = XHDPI_FACTOR;
break;
case 5: factor = XXHDPI_FACTOR;
break;
case 6: factor = XXXHDPI_FACTOR;
break;
default:
factor = 1.0;
}
//full path = "/home/akeshwar/android-sat-bothIncluded-notintegrated/code/tpr-5-5-9/princetonReview/src/main/res/values/dimens.xml"
//location of the project or module = "/home/akeshwar/android-sat-bothIncluded-notintegrated/code/tpr-5-5-9/princetonReview/"
/**
* In case there is some I/O exception with the file, you can directly copy-paste the full path to the file here:
*/
String fullPath = projectPath + "/src/main/res/values/dimens.xml";
FileInputStream fstream = new FileInputStream(fullPath);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
modifyLine(strLine);
}
br.close();
}
private static void modifyLine(String line) {
/**
* Well, this is how I'm detecting if the line has some dimension value or not.
*/
if(line.contains("p</")) {
int endIndex = line.indexOf("p</");
//since indexOf returns the first instance of the occurring string. And, the actual dimension would follow after the first ">" in the screen
int begIndex = line.indexOf(">");
String prefix = line.substring(0, begIndex+1);
String root = line.substring(begIndex+1, endIndex-1);
String suffix = line.substring(endIndex-1,line.length());
/**
* Now, we have the root. We can use it to create different dimensions. Root is simply the dimension number.
*/
double dimens = Double.parseDouble(root);
dimens = dimens*factor*1000;
dimens = (double)((int)dimens);
dimens = dimens/1000;
root = dimens + "";
System.out.println(prefix + " " + root + " " + suffix );
}
System.out.println(line);
}
}
error_reporting(E_ALL ^ E_WARNING);
:)
You should change subject to "How to fix warning from date() in PHP"...
The options object can be added to the chart when the new Chart object is created.
var chart1 = new Chart(canvas, {
type: "pie",
data: data,
options: {
legend: {
display: false
},
tooltips: {
enabled: false
}
}
});
var fileInput = $('#uploadCaptureInputFile');
fileInput.replaceWith(fileInput.val('').clone(true));
$(this).find("select").each(function () {
$(this).find('option:selected').text();
});
first, extract ids from the collection where condition
List<int> indexes_Yes = this.Contenido.Where(x => x.key == 'TEST').Select(x => x.Id).ToList();
second, use "compare" estament to select ids diffent to the selection
List<int> indexes_No = this.Contenido.Where(x => !indexes_Yes.Contains(x.Id)).Select(x => x.Id).ToList();
Obviously you can use x.key != "TEST", but is only a example
Warning, Chrome (and other browsers) will complain that multiple ACAO headers are set if you follow some of the other answers.
The error will be something like XMLHttpRequest cannot load ____. The 'Access-Control-Allow-Origin' header contains multiple values '____, ____, ____', but only one is allowed. Origin '____' is therefore not allowed access.
Try this:
$http_origin = $_SERVER['HTTP_ORIGIN'];
$allowed_domains = array(
'http://domain1.com',
'http://domain2.com',
);
if (in_array($http_origin, $allowed_domains))
{
header("Access-Control-Allow-Origin: $http_origin");
}
first, create a class to hold your parameters:
public class PkRk {
public int pk { get; set; }
public int rk { get; set; }
}
then, use the Html.Action
passing the parameters:
Html.Action("PkRkAction", new { pkrk = new PkRk { pk=400, rk=500} })
and use in Controller:
public ActionResult PkRkAction(PkRk pkrk) {
return PartialView(pkrk);
}
Yes, in near future (i write this in june 2012) you can define native css variables, without using less/sass etc ! The Webkit engine just implemented first css variable rules, so cutting edge versions of Chrome and Safari are already to work with them. See the Official Webkit (Chrome/Safari) development log with a onsite css browser demo.
Hopefully we can expect widespread browser support of native css variables in the next few months.
You probably want to have something like this:
this.sendRequest(...)
.map(...)
.catch((err) => {
//handle your error here
})
It highly depends also how do you use your service but this is the basic case.
Here is my code. It'll open given url in default browser (cross platform solution).
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class Browser {
public static void main(String[] args) {
String url = "http://www.google.com";
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("xdg-open " + url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Partial classes recently helped with source control where multiple developers were adding to one file where new methods were added into the same part of the file (automated by Resharper).
These pushes to git caused merge conflicts. I found no way to tell the merge tool to take the new methods as a complete code block.
Partial classes in this respect allows for developers to stick to a version of their file, and we can merge them back in later by hand.
example -
There are two main routes here:
1: listBox1.DataSource = yourList;
Do any manipulation (Add/Delete) to yourList and Rebind.
Set DisplayMember and ValueMember to control what is shown.
2: listBox1.Items.AddRange(yourList.ToArray());
(or use a for-loop to do Items.Add(...)
)
You can control Display by overloading ToString() of the list objects or by implementing the listBox1.Format event.
PHP 7.1.0 has introduced the iterable
pseudo-type and the is_iterable()
function, which is specially designed for such a purpose:
This […] proposes a new
iterable
pseudo-type. This type is analogous tocallable
, accepting multiple types instead of one single type.
iterable
accepts anyarray
or object implementingTraversable
. Both of these types are iterable usingforeach
and can be used withyield
from within a generator.
function foo(iterable $iterable) {
foreach ($iterable as $value) {
// ...
}
}
This […] also adds a function
is_iterable()
that returns a boolean:true
if a value is iterable and will be accepted by theiterable
pseudo-type,false
for other values.
var_dump(is_iterable([1, 2, 3])); // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(is_iterable((function () { yield 1; })())); // bool(true)
var_dump(is_iterable(1)); // bool(false)
var_dump(is_iterable(new stdClass())); // bool(false)
You can also use the function is_array($var)
to check if the passed variable is an array:
<?php
var_dump( is_array(array()) ); // true
var_dump( is_array(array(1, 2, 3)) ); // true
var_dump( is_array($_SERVER) ); // true
?>
Read more in How to check if a variable is an array in PHP?
If you can't use "viewWillDisappear" or similar method, try to subclass UINavigationController. This is the header class:
#import <Foundation/Foundation.h>
@class MyViewController;
@interface CCNavigationController : UINavigationController
@property (nonatomic, strong) MyViewController *viewController;
@end
Implementation class:
#import "CCNavigationController.h"
#import "MyViewController.h"
@implementation CCNavigationController {
}
- (UIViewController *)popViewControllerAnimated:(BOOL)animated {
@"This is the moment for you to do whatever you want"
[self.viewController doCustomMethod];
return [super popViewControllerAnimated:animated];
}
@end
In the other hand, you need to link this viewController to your custom NavigationController, so, in your viewDidLoad method for your regular viewController do this:
@implementation MyViewController {
- (void)viewDidLoad
{
[super viewDidLoad];
((CCNavigationController*)self.navigationController).viewController = self;
}
}
Based on a link to Apache HTTP Components on this SO thread, I came across the Fluent facade API for HTTP Components. An example there shows how to set up a queue of asynchronous HTTP requests (and get notified of their completion/failure/cancellation). In my case, I didn't need a queue, just one async request at a time.
Here's where I ended up (also using URIBuilder from HTTP Components, example here).
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.http.client.fluent.Async;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.concurrent.FutureCallback;
//...
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("myhost.com").setPath("/folder")
.setParameter("query0", "val0")
.setParameter("query1", "val1")
...;
URI requestURL = null;
try {
requestURL = builder.build();
} catch (URISyntaxException use) {}
ExecutorService threadpool = Executors.newFixedThreadPool(2);
Async async = Async.newInstance().use(threadpool);
final Request request = Request.Get(requestURL);
Future<Content> future = async.execute(request, new FutureCallback<Content>() {
public void failed (final Exception e) {
System.out.println(e.getMessage() +": "+ request);
}
public void completed (final Content content) {
System.out.println("Request completed: "+ request);
System.out.println("Response:\n"+ content.asString());
}
public void cancelled () {}
});
For me This was the solution on macOS ReInstall the psql
brew install postgres
Start PostgreSQL server
pg_ctl -D /usr/local/var/postgres start
Initialize DB
initdb /usr/local/var/postgres
If this command throws an error the rm the old database file and re-run the above command
rm -r /usr/local/var/postgres
Create a new database
createdb postgres_test
psql -W postegres_test
You will be logged into this db and can create a user in here to login
Wait and Sleep functions lock Excel and you can't do anything else until the delay finishes. On the other hand Loop delays doesn't give you an exact time to wait.
So, I've made this workaround joining a little bit of both concepts. It loops until the time is the time you want.
Private Sub Waste10Sec()
target = (Now + TimeValue("0:00:10"))
Do
DoEvents 'keeps excel running other stuff
Loop Until Now >= target
End Sub
You just need to call Waste10Sec where you need the delay
The python libs are obsolete with this function. I've done one that works correctly:
import os
import shutil
def copydirectorykut(src, dst):
os.chdir(dst)
list=os.listdir(src)
nom= src+'.txt'
fitx= open(nom, 'w')
for item in list:
fitx.write("%s\n" % item)
fitx.close()
f = open(nom,'r')
for line in f.readlines():
if "." in line:
shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
else:
if not os.path.exists(dst+'/'+line[:-1]):
os.makedirs(dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
f.close()
os.remove(nom)
os.chdir('..')
Just copy and paste the code in HTML file. and enjoy the happy coding. Using Youtube api to manage the thumbnail of youtube embedded video.
<!DOCTYPE html>
<html>
<body>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
}
});
}
function onPlayerReady(event) {
$('#play_vid').click(function() {
event.target.playVideo();
});
}
$(document).ready(function() {
$('#player').hide();
$('#play_vid').click(function() {
$('#player').show();
$('#play_vid').hide();
});
});
</script>
<div id="player"></div>
<img id="play_vid" src="YOUR_IMAGE_PATH" />
</body>
</html>
You have to create one Context Class.
public class Context {
private final static Context instance = new Context();
public static Context getInstance() {
return instance;
}
private Connection con;
public void setConnection(Connection con)
{
this.con=con;
}
public Connection getConnection() {
return con;
}
private TabRoughController tabRough;
public void setTabRough(TabRoughController tabRough) {
this.tabRough=tabRough;
}
public TabRoughController getTabRough() {
return tabRough;
}
}
You have to just set instance of controller in initialization using
Context.getInstance().setTabRough(this);
and you can use it from your whole application just using
TabRoughController cont=Context.getInstance().getTabRough();
Now you can pass parameter to any controller from whole application.
The plain python version of partizanos's answer.
import os
[os.system("jupyter nbconvert --to pdf " + f) for f in os.listdir(".") if f.endswith("ipynb")]
I use the tail
function:
tail(vector, n=1)
The nice thing with tail
is that it works on dataframes too, unlike the x[length(x)]
idiom.
The easiest way to do it, at least for me, is:
Conditional format-> Add new rule->Set your own formula:
=ISNA(MATCH(A2;$B:$B;0))
Where A2 is the first element in column A to be compared and B is the column where A's element will be searched.
Once you have set the formula and picked the format, apply this rule to all elements in the column.
Hope this helps
Here's another converted to Ruby code:
include Math
#Note: from/to = [lat, long]
def get_distance_in_km(from, to)
radians = lambda { |deg| deg * Math.PI / 180 }
radius = 6371 # Radius of the earth in kilometer
dLat = radians[to[0]-from[0]]
dLon = radians[to[1]-from[1]]
cosines_product = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(radians[from[0]]) * Math.cos(radians[to[1]]) * Math.sin(dLon/2) * Math.sin(dLon/2)
c = 2 * Math.atan2(Math.sqrt(cosines_product), Math.sqrt(1-cosines_product))
return radius * c # Distance in kilometer
end
Update: This will create a second context same as in applicationContext.xml
or you can add this code snippet to your web.xml
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
instead of
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
All of the current answers on this thread must have been a bit dated. As of pandas
version 0.24.0, the .to_flat_index()
does what you need.
From panda's own documentation:
MultiIndex.to_flat_index()
Convert a MultiIndex to an Index of Tuples containing the level values.
A simple example from its documentation:
import pandas as pd
print(pd.__version__) # '0.23.4'
index = pd.MultiIndex.from_product(
[['foo', 'bar'], ['baz', 'qux']],
names=['a', 'b'])
print(index)
# MultiIndex(levels=[['bar', 'foo'], ['baz', 'qux']],
# codes=[[1, 1, 0, 0], [0, 1, 0, 1]],
# names=['a', 'b'])
Applying to_flat_index()
:
index.to_flat_index()
# Index([('foo', 'baz'), ('foo', 'qux'), ('bar', 'baz'), ('bar', 'qux')], dtype='object')
pandas
columnAn example of how you'd use it on dat
, which is a DataFrame with a MultiIndex
column:
dat = df.loc[:,['name','workshop_period','class_size']].groupby(['name','workshop_period']).describe()
print(dat.columns)
# MultiIndex(levels=[['class_size'], ['count', 'mean', 'std', 'min', '25%', '50%', '75%', 'max']],
# codes=[[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6, 7]])
dat.columns = dat.columns.to_flat_index()
print(dat.columns)
# Index([('class_size', 'count'), ('class_size', 'mean'),
# ('class_size', 'std'), ('class_size', 'min'),
# ('class_size', '25%'), ('class_size', '50%'),
# ('class_size', '75%'), ('class_size', 'max')],
# dtype='object')
git branch -f <branch-name> [<new-tip-commit>]
If new-tip-commit
is omitted it defaults to the current commit.
This problem will solve when we change the version of apache-maven
I faced it and it was solved when i used apache-maven-2.2.1
From Tomcat documentation, For blocking I/O (BIO), the default value of maxConnections
is the value of maxThreads
unless Executor (thread pool) is used in which case, the value of 'maxThreads' from Executor will be used instead. For Non-blocking IO, it doesn't seem to be dependent on maxThreads
.
This is how I've implemented this in my project.
function array_map_associative(callable $callback, $array) {
/* map original array keys, and call $callable with $key and value of $key from original array. */
return array_map(function($key) use ($callback, $array){
return $callback($key, $array[$key]);
}, array_keys($array));
}
I found a combination of these answers gave me the best outcome - allowing me to still position the tooltip and attach it to the relevant container:
$('body').on('mouseenter', '[rel=tooltip]', function(){
var el = $(this);
if (el.data('tooltip') === undefined) {
el.tooltip({
placement: el.data("placement") || "top",
container: el.data("container") || false
});
}
el.tooltip('show');
});
$('body').on('mouseleave', '[rel=tooltip]', function(){
$(this).tooltip('hide');
});
Relevant HTML:
<button rel="tooltip" class="btn" data-placement="bottom" data-container=".some-parent" title="Show Tooltip">
<i class="icon-some-icon"></i>
</button>
For me, something different worked, that I found in on this answer from a similar question. Probably won't help OP, but maybe someone like me that had a similar problem.
You should indeed use rvm, but as no one explained to you how to do this without rvm, here you go:
sudo gem install tzinfo builder memcache-client rack rack-test rack-mount \
abstract erubis activesupport mime-types mail text-hyphen text-format \
thor i18n rake bundler arel railties rails --prerelease --force
Roughly you can do it like that :
try
{
//do something
}
catch (Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
if (!Page.IsStartupScriptRegistered("myErrorScript"))
{
Page.ClientScript.RegisterStartupScript("myErrorScript", script);
}
}
But I recommend you to define your custom Exception and throw it anywhere you need. At your page catch this custom exception and register your message box script.
A LITTLE NOTE: Be careful about loaders and minimize (Rails env.):
After seeing this error and trying every solution out there, i realised there was something wrong with my html loader.
I've set my Rails environment up to import HTML paths for my components successfully with this loader (config/loaders/html.js.
):
module.exports = {
test: /\.html$/,
use: [ {
loader: 'html-loader?exportAsEs6Default',
options: {
minimize: true
}
}]
}
After some hours efforts and countless of ReactiveFormsModule imports i saw that my formGroup
was small letters: formgroup
.
This led me to the loader and the fact that it downcased my HTML on minimize.
After changing the options, everything worked as it should, and i could go back to crying again.
I know that this is not an answer to the question, but for future Rails visitors (and other with custom loaders) i think this could be helpfull.
package be.fery.annotation;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.PrePersist;
@Entity
public class User {
@Id
private Long id;
@Column(name = "ADDRESS_ID")
private Address address;
@PrePersist
public void doStuff(){
}
}
And a testing class:
package be.fery.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class AnnotationIntrospector {
public AnnotationIntrospector() {
super();
}
public Annotation[] findClassAnnotation(Class<?> clazz) {
return clazz.getAnnotations();
}
public Annotation[] findMethodAnnotation(Class<?> clazz, String methodName) {
Annotation[] annotations = null;
try {
Class<?>[] params = null;
Method method = clazz.getDeclaredMethod(methodName, params);
if (method != null) {
annotations = method.getAnnotations();
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return annotations;
}
public Annotation[] findFieldAnnotation(Class<?> clazz, String fieldName) {
Annotation[] annotations = null;
try {
Field field = clazz.getDeclaredField(fieldName);
if (field != null) {
annotations = field.getAnnotations();
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return annotations;
}
/**
* @param args
*/
public static void main(String[] args) {
AnnotationIntrospector ai = new AnnotationIntrospector();
Annotation[] annotations;
Class<User> userClass = User.class;
String methodDoStuff = "doStuff";
String fieldId = "id";
String fieldAddress = "address";
// Find class annotations
annotations = ai.findClassAnnotation(be.fery.annotation.User.class);
System.out.println("Annotation on class '" + userClass.getName()
+ "' are:");
showAnnotations(annotations);
// Find method annotations
annotations = ai.findMethodAnnotation(User.class, methodDoStuff);
System.out.println("Annotation on method '" + methodDoStuff + "' are:");
showAnnotations(annotations);
// Find field annotations
annotations = ai.findFieldAnnotation(User.class, fieldId);
System.out.println("Annotation on field '" + fieldId + "' are:");
showAnnotations(annotations);
annotations = ai.findFieldAnnotation(User.class, fieldAddress);
System.out.println("Annotation on field '" + fieldAddress + "' are:");
showAnnotations(annotations);
}
public static void showAnnotations(Annotation[] ann) {
if (ann == null)
return;
for (Annotation a : ann) {
System.out.println(a.toString());
}
}
}
Hope it helps...
;-)
You can use in-place operator new. This would be a bit horrible, and I'd recommend keeping in a factory.
Car* createCars(unsigned number)
{
if (number == 0 )
return 0;
Car* cars = reinterpret_cast<Car*>(new char[sizeof(Car)* number]);
for(unsigned carId = 0;
carId != number;
++carId)
{
new(cars+carId) Car(carId);
}
return cars;
}
And define a corresponding destroy so as to match the new used in this.
I did not get it. I had a similar problem but in my nav bar.
What I was doing is I kept my navBar code in this way: nav>div.navlinks>ul>li*3>a
In order to put hover effects on a I positioned a to relative and designed a::before
and a::after
then i put a gray background on before and after elements and kept hover effects in such way that as one hovers on <a>
they will pop from outside a to fill <a>
.
The problem is that the overflow hidden is not working on <a>
.
What i discovered is if i removed <li>
and simply put <a>
without <ul>
and <li>
then it worked.
What may be the problem?
Improving @J. Frankenstein answear
@HostListener('click')
clickInside($event) {
this.text = "clicked inside";
$event.stopPropagation();
}
@HostListener('document:click')
clickOutside() {
this.text = "clicked outside";
}
_x000D_
Use the UNC path rather than HTTP. This code works:
Public Sub ListFiles()
Dim folder As folder
Dim f As File
Dim fs As New FileSystemObject
Dim RowCtr As Integer
RowCtr = 1
Set folder = fs.GetFolder("\\SharePointServer\Path\MorePath\DocumentLibrary\Folder")
For Each f In folder.Files
Cells(RowCtr, 1).Value = f.Name
RowCtr = RowCtr + 1
Next f
End Sub
To get the UNC path to use, go into the folder in the document library, drop down the Actions menu and choose Open in Windows Explorer. Copy the path you see there and use that.
I got fed up with trying to get zeroes, NULLS, and '' accurately round a loop of PHP, MySql and POST values, so I just use 'Yes' and 'No'.
This works flawlessly and needs no special treatment that isn't obvious and easy to do.
A BLOB
can be 65535 bytes (64 KB) maximum.
If you need more consider using:
a MEDIUMBLOB
for 16777215 bytes (16 MB)
a LONGBLOB
for 4294967295 bytes (4 GB).
See Storage Requirements for String Types for more info.
If we wanted to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute
and setAttribute
methods as shown below:
JavaScript
<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'
// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>
Through jQuery
// Fetching data
var fruitCount = $(this).data('fruit');
// Above does not work in firefox. So use below to get attribute value.
var fruitCount = $(this).attr('data-fruit');
// Assigning data
$(this).data('fruit','7');
// But when you get the value again, it will return old value.
// You have to set it as below to update value. Then you will get updated value.
$(this).attr('data-fruit','7');
Read this documentation for vanilla js or this documentation for jquery
Your path includes " at the beginning and at the end. Drop the quotes, and it'll be ok.
The \" at the beginning and end of what you see in VS Debugger is what tells us that the quotes are literally in the string.
Use <br />
OR <br>
-
<li>Post by<br /><a>Author</a></li>
OR
<li>Post by<br><a>Author</a></li>
or
make the a
element display:block;
<li>Post by <a style="display:block;">Author</a></li>
For future viewers, there is a line in my /etc/nanorc file close to line 153 that says "set tabsize 8". The word might need to be tabsize instead of tabspace. After I replaced 8 with 4 and uncommented the line, it solved my problem.
public class AssemblyLoader<T> where T:class
{
public void(){
var res = Load(@"C:\test\paquete.uno.dos.test.dll", "paquete.uno.dos.clasetest.dll")
}
public T Load(string assemblyFile, string objectToInstantiate)
{
var loaded = Activator.CreateInstanceFrom(assemblyFile, objectToInstantiate).Unwrap();
return loaded as T;
}
}
Ok...Ok... Don't worry i am also ruined by this error and fatal and when i got it i was so serious even i was not giving an attention to other work, but i got it, Simply first of all copy this code and paste in your system variable Under path ...
C:\Program Files;C:\Winnt;C:\Winnt\System32;C:\Program Files\Java\jre6\bin\javaw.exe
Now copy the "jre" folder from your path like i have have "jre" under this path
C:\Program Files\Java
and paste it in your eclipse folder means where your eclipse.exe file is placed. like i have my eclipse set up in this location
F:\Softwares\LANGUAGES SOFTEARE\Android Setup\eclipse
So inside the eclipse Folder paste the "jre" FOLDER . If you have "jre6" then rename it as "jre"....and run your eclipse you will got the solution...
//<<<<<<<<<<<<<<----------------------------->>>>>>>>>>>>>>>>>>>
OTHER SOLUTION: 2
If the problem could't solve with the above steps, then follow these steps
-vmF:\Softwares\LANGUAGES SOFTEARE\Android Setup\eclipse Indigo version 32 Bit\jre\bin/javaw.exe
Now this time when you will start eclipse it will search for javaw.exe, so it will search the path in the eclipse.ini, as it is now in the same folder so, it will start the javaw.exe and it will start working.
If You still have any query you can ask it again, just go on my profile and find out my email id. because i love stack overflow forum, and it made me a programmer.*
Using ensure_ascii=False in json.dumps is the right direction to solve this problem, as pointed out by Martijn. However, this may raise an exception:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 1: ordinal not in range(128)
You need extra settings in either site.py or sitecustomize.py to set your sys.getdefaultencoding() correct. site.py is under lib/python2.7/ and sitecustomize.py is under lib/python2.7/site-packages.
If you want to use site.py, under def setencoding(): change the first if 0: to if 1: so that python will use your operation system's locale.
If you prefer to use sitecustomize.py, which may not exist if you haven't created it. simply put these lines:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
Then you can do some Chinese json output in utf-8 format, such as:
name = {"last_name": u"?"}
json.dumps(name, ensure_ascii=False)
You will get an utf-8 encoded string, rather than \u escaped json string.
To verify your default encoding:
print sys.getdefaultencoding()
You should get "utf-8" or "UTF-8" to verify your site.py or sitecustomize.py settings.
Please note that you could not do sys.setdefaultencoding("utf-8") at interactive python console.
You need to wrap button click handler to match the pattern
public void klik(object sender, EventArgs e)
For python, use the
from selenium.webdriver import ActionChains
and
ActionChains(browser).click(element).perform()
I found it. Perl has multi-line comments:
#!/usr/bin/perl
use strict;
use warnings;
=for comment
Example of multiline comment.
Example of multiline comment.
=cut
print "Multi Line Comment Example \n";
You should do it like this:
\i path_to_sql_file
See:
A cleaner way to handle file open/close and avoid memory leaks:
Prep:
import numpy as np
import h5py
data_to_write = np.random.random(size=(100,20)) # or some such
Write:
with h5py.File('name-of-file.h5', 'w') as hf:
hf.create_dataset("name-of-dataset", data=data_to_write)
Read:
with h5py.File('name-of-file.h5', 'r') as hf:
data = hf['name-of-dataset'][:]
What worked for me was just typing the command passive and ftp went into passive mode from active mode.
This is a cool solution that works perfectly
const array = [{"title":"tile hgfgfgfh"},{"title":"Wise cool"},{"title":"titlr DEytfd ftgftgfgtgtf gtftftft"},{"title":"This is the title"},{"title":"yeah this is cool"},{"title":"tile hfyf"},{"title":"tile ehey"}];
var item = array.filter(item=>item.title.toLowerCase().includes('this'));
alert(JSON.stringify(item))
EDITED
const array = [{"title":"tile hgfgfgfh"},{"title":"Wise cool"},{"title":"titlr DEytfd ftgftgfgtgtf gtftftft"},{"title":"This is the title"},{"title":"yeah this is cool"},{"title":"tile hfyf"},{"title":"tile ehey"}];_x000D_
_x000D_
_x000D_
// array.filter loops through your array and create a new array returned as Boolean value given out "true" from eachIndex(item) function _x000D_
_x000D_
var item = array.filter((item)=>eachIndex(item));_x000D_
_x000D_
//var item = array.filter();_x000D_
_x000D_
_x000D_
_x000D_
function eachIndex(e){_x000D_
console.log("Looping each index element ", e)_x000D_
return e.title.toLowerCase().includes("this".toLowerCase())_x000D_
}_x000D_
_x000D_
console.log("New created array that returns \"true\" value by eachIndex ", item)
_x000D_
If constraint on column STATUS was created without a name during creating a table, Oracle will assign a random name for it. Unfortunately, we cannot modify the constraint directly.
Steps involved of dropping unnamed constraint linked to column STATUS
Rename STATUS2 to STATUS
ALTER TABLE MY_TABLE ADD STATUS2 NVARCHAR2(10) DEFAULT 'OPEN';
ALTER TABLE MY_TABLE ADD CONSTRAINT MY_TABLE_CHECK_STATUS CHECK (STATUS2 IN ('OPEN', 'CLOSED'));
UPDATE MY_TABLE SET STATUS2 = STATUS;
ALTER TABLE MY_TABLE DROP COLUMN STATUS;
ALTER TABLE MY_TABLE RENAME COLUMN STATUS2 TO STATUS;
it depends on how you actually order your data,if its on a channel first basis then you should reshape your data: x_train=x_train.reshape(x_train.shape[0],channel,width,height)
if its channel last: x_train=s_train.reshape(x_train.shape[0],width,height,channel)
The first thing you need to do is to set the level of verification. Such levels is not so much:
Although the method setHostnameVerifier() is obsolete for new library apache, but for version in Android SDK is normal.
And so we take ALLOW_ALL_HOSTNAME_VERIFIER
and set it in the method factory SSLSocketFactory.setHostnameVerifier()
.
Next, You need set our factory for the protocol to https. To do this, simply call the SchemeRegistry.register()
method.
Then you need to create a DefaultHttpClient
with SingleClientConnManager
.
Also in the code below you can see that on default will also use our flag (ALLOW_ALL_HOSTNAME_VERIFIER
) by the method HttpsURLConnection.setDefaultHostnameVerifier()
Below code works for me:
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient client = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
// Set verifier
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
// Example send http request
final String url = "https://encrypted.google.com/";
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost);
I think its simpler:
$('submit').click(function(e){
if (e.isValid())
e.preventDefault();
//your code.
}
this will stop the submit until form is valid.
Try using the .frame modifier with the following options:
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading)
struct ContentView: View {
var body: some View {
VStack(alignment: .leading) {
Text("Hello World").font(.title)
Text("Another").font(.body)
Spacer()
}.frame(minWidth: 0,
maxWidth: .infinity,
minHeight: 0,
maxHeight: .infinity,
alignment: .topLeading
).background(Color.red)
}
}
This is described as being a flexible frame (see the documentation), which will stretch to fill the whole screen, and when it has extra space it will center its contents inside of it.
public static String simSearchByImgURL(int catid ,String imgurl) throws IOException{
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String result =null;
try {
HttpPost httppost = new HttpPost("http://api0.visualsearchapi.com:8084/vsearchtech/api/v1.0/apisim_search");
StringBody catidBody = new StringBody(catid+"" , ContentType.TEXT_PLAIN);
StringBody keyBody = new StringBody(APPKEY , ContentType.TEXT_PLAIN);
StringBody langBody = new StringBody(LANG , ContentType.TEXT_PLAIN);
StringBody fmtBody = new StringBody(FMT , ContentType.TEXT_PLAIN);
StringBody imgurlBody = new StringBody(imgurl , ContentType.TEXT_PLAIN);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("apikey", keyBody).addPart("catid", catidBody)
.addPart("lang", langBody)
.addPart("fmt", fmtBody)
.addPart("imgurl", imgurlBody);
HttpEntity reqEntity = builder.build();
httppost.setEntity(reqEntity);
response = httpClient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
// result = ConvertStreamToString(resEntity.getContent(), "UTF-8");
String charset = "UTF-8";
String content=EntityUtils.toString(response.getEntity(), charset);
System.out.println(content);
}
EntityUtils.consume(resEntity);
}catch(Exception e){
e.printStackTrace();
}finally {
response.close();
httpClient.close();
}
return result;
}
Java Language Specification says that
Program Exit
A program terminates all its activity and exits when one of two things happens:
All the threads that are not daemon threads terminate.
Some thread invokes the exit method of class Runtime or class System, and the exit operation is not forbidden by the security manager.
It means that You should use it when You have big program (well, at lest bigger than this one) and want to finish its execution.
Just Remove your .framework from the list of "Your Project->General->Linked Framework & Libraries".
In my case the problem was I implemented the same library twice in my build.gradle file. Removing the duplicate entry worked for me. And did not even needed to clean, rebuild the project.
I use Strongloop's cli tools for that; see https://strongloop.com/strongblog/switch-between-configure-public-and-private-npm-registry/ for more information
Switching between repositories is as easy as : slc registry use <name>
Timer for jQuery - smaller, working, tested.
var sec = 0;_x000D_
function pad ( val ) { return val > 9 ? val : "0" + val; }_x000D_
setInterval( function(){_x000D_
$("#seconds").html(pad(++sec%60));_x000D_
$("#minutes").html(pad(parseInt(sec/60,10)));_x000D_
}, 1000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span id="minutes"></span>:<span id="seconds"></span>
_x000D_
Pure JavaScript:
var sec = 0;_x000D_
function pad ( val ) { return val > 9 ? val : "0" + val; }_x000D_
setInterval( function(){_x000D_
document.getElementById("seconds").innerHTML=pad(++sec%60);_x000D_
document.getElementById("minutes").innerHTML=pad(parseInt(sec/60,10));_x000D_
}, 1000);
_x000D_
<span id="minutes"></span>:<span id="seconds"></span>
_x000D_
Update:
This answer shows how to pad.
Stopping setInterval MDN is achieved with clearInterval MDN
var timer = setInterval ( function(){...}, 1000 );
...
clearInterval ( timer );
If you're currently on the branch you want to rename:
git branch -m new_name
Or else:
git branch -m old_name new_name
You can check with:
git branch -a
As you can see, only the local name changed Now, to change the name also in the remote you must do:
git push origin :old_name
This removes the branch, then upload it with the new name:
git push origin new_name
The /P
switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.
Two ways I've used it... first:
SET /P variable=
When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.
And second:
SET /P variable=<%temp%\filename.txt
Will set variable to contents (the first line) of the txt file. This method won't work unless the /P
is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.
Python doesn't have built-in eof detection function but that functionality is available in two ways: f.read(1)
will return b''
if there are no more bytes to read. This works for text as well as binary files. The second way is to use f.tell()
to see if current seek position is at the end. If you want EOF testing not to change the current file position then you need bit of extra code.
Below are both implementations.
Using tell() method
import os
def is_eof(f):
cur = f.tell() # save current position
f.seek(0, os.SEEK_END)
end = f.tell() # find the size of file
f.seek(cur, os.SEEK_SET)
return cur == end
Using read() method
def is_eof(f):
s = f.read(1)
if s != b'': # restore position
f.seek(-1, os.SEEK_CUR)
return s == b''
How to use this
while not is_eof(my_file):
val = my_file.read(10)
https://developer.mozilla.org/en-US/docs/Web/API/Location/assign
window.location.assign("../");
// one level upwindow.location.assign("/path");
// relative to domainIt is due to mismatched blacklist file configuration.
To resolve that,
We have to move to the project folder.
Open \node_modules\metro-config\src\defaults\blacklist.js
Replace the following.
From
var sharedBlacklist = [
/node_modules[/\\]react[/\\]dist[/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
To
var sharedBlacklist = [
/node_modules[\/\\]react[\/\\]dist[\/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
check your build directory gracefully all the files will be available in the build folder.
asset-manifest.json
favicon.ico
manifest.json
robots.txt
static assets
index.html
precache-manifest.ddafca92870314adfea99542e1331500.js service-worker.js
4.copy the build folder to your apache server i.e /var/www/html
sudo cp -rf build /var/www/html
go to sites-available directory
cd /etc/apache2/sites-available/
open 000-default.conf file
sudo vi 000-default.conf and rechange the DocumentRoot path
Now goto apache conf.
cd /etc/aapche2
sudo vi apache2.conf
add the given snippet
<Directory /var/www/html>_x000D_
_x000D_
Options Indexes FollowSymLinks_x000D_
_x000D_
AllowOverride All_x000D_
_x000D_
Require all granted_x000D_
_x000D_
</Directory>
_x000D_
make a file inside /var/www/html/build
sudo vi .htaccess
Options -MultiViews_x000D_
_x000D_
RewriteEngine On_x000D_
_x000D_
RewriteCond %{REQUEST_FILENAME} !-f_x000D_
_x000D_
RewriteRule ^ index.html [QSA,L]
_x000D_
9.sudo a2enmod rewrite
10.sudo systemctl restart apache2
restart apache server
sudo service apache2 restart
thanks, enjoy your day
One simple way to do that is:
String url = "http://test.com/Services/rest/{id}/Identifier"
UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
uriComponents = uriComponents.expand(Collections.singletonMap("id", "1234"));
and then adds the query params.
Enter this path in your System environment variable.
C:\Program Files\PostgreSQL\[YOUR PG VERSION]\bin
In this case i'm using version 10. If you check the postgres folder you are going to see your current versions.
In my own case i used the following on separate lines:
C:\Program Files\PostgreSQL\10\bin
C:\Program Files\PostgreSQL\10\lib
From the grep(1)
man page:
-l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match. (-l is specified by POSIX.)
It's probably a typo. Look for the places in your code where you call [schema].[TableName] (basically anywhere you reference a field) and make sure everything is spelled correctly.
Personally, I try to avoid this by using aliases for all my tables. It helps tremendously when you can shorten a long table name to an acronym of it's description (i.e. WorkOrderParts -> WOP), and also makes your query more readable.
Edit: As an added bonus, you'll save TONS of keystrokes when all you have to type is a three or four-letter alias vs. the schema, table, and field names all together.
Encountering the same problem, I solved this by reconverting the file with default mp4 settings in iMovie.
You need to use \" for escaping " character (\ escape the following character
sed -i 's/\"http://www.fubar.com\"/URL_FUBAR/g'
I can't repro, but I suspect that in your actual code there is a constraint somewhere that T : class
- you need to propagate that to make the compiler happy, for example (hard to say for sure without a repro example):
public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
^^^^^
see this bit
for n in 1..6
h{n}
font: 32px/42px trajan-pro-1,trajan-pro-2;
You can use event.key
function Input({onKeyPress}) {_x000D_
return (_x000D_
<div>_x000D_
<h2>Input</h2>_x000D_
<input type="text" onKeyPress={onKeyPress}/>_x000D_
</div>_x000D_
)_x000D_
}_x000D_
_x000D_
class Form extends React.Component {_x000D_
state = {value:""}_x000D_
_x000D_
handleKeyPress = (e) => {_x000D_
if (e.key === 'Enter') {_x000D_
this.setState({value:e.target.value})_x000D_
}_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<section>_x000D_
<Input onKeyPress={this.handleKeyPress}/>_x000D_
<br/>_x000D_
<output>{this.state.value}</output>_x000D_
</section>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
<Form />,_x000D_
document.getElementById("react")_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
<div id="react"></div>
_x000D_
When I printed response.read()
I noticed that b
was preprended to the string (e.g. b'{"a":1,..
). The "b" stands for bytes and serves as a declaration for the type of the object you're handling. Since, I knew that a string could be converted to a dict by using json.loads('string')
, I just had to convert the byte type to a string type. I did this by decoding the response to utf-8 decode('utf-8')
. Once it was in a string type my problem was solved and I was easily able to iterate over the dict
.
I don't know if this is the fastest or most 'pythonic' way of writing this but it works and theres always time later of optimization and improvement! Full code for my solution:
from urllib.request import urlopen
import json
# Get the dataset
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)
# Convert bytes to string type and string type to dict
string = response.read().decode('utf-8')
json_obj = json.loads(string)
print(json_obj['source_name']) # prints the string with 'source_name' key
In Bootstrap 4 you can use the form-check-inline class.
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="queryFieldName" id="option1" value="1">
<label class="form-check-label" for="option1">First</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="queryFieldName" id="option2" value="2">
<label class="form-check-label" for="option2">Second</label>
</div>
Maybe you could do
SELECT * FROM table LIMIT 10000 OFFSET FLOOR(RAND() * 190000)
If you work with SpringBoot you can add specifying the environmental variable in the following property:
was.app.config.properties.toSystemProperties
Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image. In one of my tries i use
String pathToImageSortBy = "resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
But correct way was use name of my project in path to resource
String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
Well, defaultdict can also raise keyerror in the following case:
from collections import defaultdict
d = defaultdict()
print(d[3]) #raises keyerror
Always remember to give argument to the defaultdict like defaultdict(int).
Your range value is incorrect. You are referencing cell "75" which does not exist. You might want to use the R1C1 notation to use numeric columns easily without needing to convert to letters.
http://www.bettersolutions.com/excel/EED883/YI416010881.htm
Range("R" & DataImportRow & "C" & DataImportColumn).Offset(0, 2).Value = iFirstCustomerSales
This should fix your problem.
System.Diagnostics.Process.Start can be used to print a document. Set UseShellExecute to True and set the Verb to "print".
public class StructMain implements Serializable {
public int id;
public String name;
public String lastName;
}
this my item . implement Serializable and create ArrayList
ArrayList<StructMain> items =new ArrayList<>();
and put in Bundle
Bundle bundle=new Bundle();
bundle.putSerializable("test",items);
and create a new Intent that put Bundle to Intent
Intent intent=new Intent(ActivityOne.this,ActivityTwo.class);
intent.putExtras(bundle);
startActivity(intent);
for receive bundle insert this code
Bundle bundle = getIntent().getExtras();
ArrayList<StructMain> item = (ArrayList<StructMain>) bundle.getSerializable("test");
Although Clayton's answer will get you there (eventually), in SQL2005/2008/R2/2012 you have a far easier option:
Right-click on the Database, select Tasks
and then Generate Scripts
, which will launch the Script Wizard. This allows you to generate a single script that can recreate the full database including table/indexes & constraints/stored procedures/functions/users/etc. There are a multitude of options that you can configure to customise the output, but most of it is self explanatory.
If you are happy with the default options, you can do the whole job in a matter of seconds.
If you want to recreate the data in the database (as a series of INSERTS) I'd also recommend SSMS Tools Pack (Free for SQL 2008 version, Paid for SQL 2012 version).
I have had to unpack a .ab
-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.
Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab
-file is password-protected.
Usage:java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]
Example:
Let's say, you've got a file test.ab
, which is not password-protected, you're using Windows and want the resulting .tar
-Archive to be called test.tar
. Then your command should be:
java.exe -jar abe.jar unpack test.ab test.tar ""
Create a new variable Count
with a value of 1 for each row:
df1["Count"] <-1
Then aggregate dataframe, summing by the Count
column:
df2 <- aggregate(df1[c("Count")], by=list(Year=df1$Year, Month=df1$Month), FUN=sum, na.rm=TRUE)
Did you try using t.Text
?
tr ' ' ',' <input >output
Substitutes each space with a comma, if you need you can make a pass with the -s flag (squeeze repeats), that replaces each input sequence of a repeated character that is listed in SET1 (the blank space) with a single occurrence of that character.
Use of squeeze repeats used to after substitute tabs:
tr -s '\t' <input | tr '\t' ',' >output
I've already posted
GetItemValue
extension method in this post Get the value for a listbox item by index. This extension method will work for allListControl
classes includingCheckedListBox
,ListBox
andComboBox
.
None of the existing answers are general enough, but there is a general solution for the problem.
In all cases, the underlying Value
of an item should be calculated regarding to ValueMember
, regardless of the type of data source.
The data source of the CheckedListBox
may be a DataTable
or it may be a list which contains objects, like a List<T>
, so the items of a CheckedListBox
control may be DataRowView
, Complex Objects, Anonymous types, primary types and other types.
GetItemValue Extension Method
We need a GetItemValue
which works similar to GetItemText
, but return an object, the underlying value of an item, regardless of the type of object you added as item.
We can create GetItemValue
extension method to get item value which works like GetItemText
:
using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
public static object GetItemValue(this ListControl list, object item)
{
if (item == null)
throw new ArgumentNullException("item");
if (string.IsNullOrEmpty(list.ValueMember))
return item;
var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
if (property == null)
throw new ArgumentException(
string.Format("item doesn't contain '{0}' property or column.",
list.ValueMember));
return property.GetValue(item);
}
}
Using above method you don't need to worry about settings of ListBox
and it will return expected Value
for an item. It works with List<T>
, Array
, ArrayList
, DataTable
, List of Anonymous Types, list of primary types and all other lists which you can use as data source. Here is an example of usage:
//Gets underlying value at index 2 based on settings
this.checkedListBox.GetItemValue(this.checkedListBox.Items[2]);
Since we created the GetItemValue
method as an extension method, when you want to use the method, don't forget to include the namespace in which you put the class.
This method is applicable on ComboBox
and CheckedListBox
too.
You can just put a pause
command in the last line of your batch file:
@echo off
echo Hey, I'm just doing some work for you.
pause
Will give you something like this as output:
Hey, I'm just doing some work for you.
Press any key to continue ...
Note: Using the @echo prevents to output the command before the output is printed.
Try this:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
Source: https://www.ndchost.com/wiki/apache/redirect-http-to-https
(I tried so many different blocks of code, this 3 liner worked flawlessly)
c:\ProgramData\Java\javapath
is used for symlinks. You can of course add the full path to your Java Path to %PATH%
, but equally you can create a symlink to the path to the above location.
CMD
as Administrator.mklink java.exe
(full path to your Java.exe)
egmklink java.exe "C:\Program Files\Java\jdk1.8.0_25\bin\java.exe"
Load Testing: Load testing is meant to test the system by constantly and steadily increasing the load on the system till the time it reaches the threshold limit.
Example For example, to check the email functionality of an application, it could be flooded with 1000 users at a time. Now, 1000 users can fire the email transactions (read, send, delete, forward, reply) in many different ways. If we take one transaction per user per hour, then it would be 1000 transactions per hour. By simulating 10 transactions/user, we could load test the email server by occupying it with 10000 transactions/hour.
Stress Testing: Under stress testing, various activities to overload the existing resources with excess jobs are carried out in an attempt to break the system down.
Example: As an example, a word processor like Writer1.1.0 by OpenOffice.org is utilized in development of letters, presentations, spread sheets etc… Purpose of our stress testing is to load it with the excess of characters.
To do this, we will repeatedly paste a line of data, till it reaches its threshold limit of handling large volume of text. As soon as the character size reaches 65,535 characters, it would simply refuse to accept more data. The result of stress testing on Writer 1.1.0 produces the result that, it does not crash under the stress and that it handle the situation gracefully, which make sure that application is working correctly even under rigorous stress conditions.
If you are intending on passing those integers to a function or method, consider this example:
sum(int(x) for x in numbers)
This construction is intentionally remarkably similar to list comprehensions mentioned by adamk. Without the square brackets, it's called a generator expression, and is a very memory-efficient way of passing a list of arguments to a method. A good discussion is available here: Generator Expressions vs. List Comprehension
This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC
This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.
Here is another way of doing it.
class Parameter(models.Model):
def __init__(self, *args, **kwargs):
super(Parameter, self).__init__(*args, **kwargs)
self.__original_value = self.value
def clean(self,*args,**kwargs):
if self.__original_value == self.value:
print("igual")
else:
print("distinto")
def save(self,*args,**kwargs):
self.full_clean()
return super(Parameter, self).save(*args, **kwargs)
self.__original_value = self.value
key = models.CharField(max_length=24, db_index=True, unique=True)
value = models.CharField(max_length=128)
As per documentation: validating objects
"The second step full_clean() performs is to call Model.clean(). This method should be overridden to perform custom validation on your model. This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field:"
SELECT field1,
field2,
'example' AS newfield
FROM TABLE1
This will add a column called "newfield" to the output, and its value will always be "example".
Click \Build\Select Build Variant...
in Android Studio.
And choose release
.
another way would be to use dplyr
package:
x = c(1,1,2,3,4,4,4)
dplyr::distinct(as.data.frame(x))
In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size
like this:
#include <vector>
int main () {
std::vector<int> v;
auto size = v.size();
}
Your third call
int size = v.size();
triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.
int size = static_cast<int>(v.size());
would always compile cleanly and also explicitly states that your conversion from std::vector::size_type
to int
was intended.
Note that if the size of the vector
is greater than the biggest number an int
can represent, size
will contain an implementation defined (de facto garbage) value.
In Robins's answer ends-with is not supported in xpath 1.0 too.. Only starts-with is supported... So if your condition is not very specific..You can Use like this which worked for me
//*[starts-with(@id,'sometext') and contains(@name,'_text')]`\