I don't have enough rep points to vote up froadie's answer. But I have to disagree with the comments on Kris's answer. The following answer:
SELECT name
FROM table2
WHERE name NOT IN
(SELECT name
FROM table1)
Is FAR more efficient in practice. I don't know why, but I'm running it against 800k+ records and the difference is tremendous with the advantage given to the 2nd answer posted above. Just my $0.02.
The bash script should be something like this:
#!/bin/bash
/usr/bin/php /path/to/php/file.php
You need the php executable (usually found in /usr/bin) and the path of the php script to be ran. Now you only have to put this bash script on crontab and you're done!
Check that there isn't a firewall that is ending the connection after certain period of time (this was the cause of a similar problem we had)
For me was because I put the animation name inside square brackets.
<div [@animation]></div>
But after I removed the bracket all worked fine (In Angular 9.0.1):
<div @animation></div>
You can use try-catch block to check for integer value
for eg:
User inputs in form of string
try
{
int num=Integer.parseInt("Some String Input");
}
catch(NumberFormatException e)
{
//If number is not integer,you wil get exception and exception message will be printed
System.out.println(e.getMessage());
}
Implement the HandlerInterceptor
interface, and then inject the UserDetails
into each request that has a Model, as follows:
@Component
public class UserInterceptor implements HandlerInterceptor {
....other methods not shown....
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if(modelAndView != null){
modelAndView.addObject("user", (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal());
}
}
The key is calling the parent's method using super.methodName();
class A {
// A protected method
protected doStuff()
{
alert("Called from A");
}
// Expose the protected method as a public function
public callDoStuff()
{
this.doStuff();
}
}
class B extends A {
// Override the protected method
protected doStuff()
{
// If we want we can still explicitly call the initial method
super.doStuff();
alert("Called from B");
}
}
var a = new A();
a.callDoStuff(); // Will only alert "Called from A"
var b = new B()
b.callDoStuff(); // Will alert "Called from A" then "Called from B"
the thing that kept on killing me was that i didn't know that this app was installed for my guest account (although I had uninstalled it for the other accounts..)
so i searched for the app in the app manager, and simply clicked on uninstall for all users
Good way to solve this in Jquery manner
$("#dropDownMenuKategorie option:selected").index()
As in @deinonychusaur's reply, but even more compact:
In [7]: np.where((a >= 6) & (a <=10))
Out[7]: (array([3, 4, 5]),)
You've just answered your own question :) You can do something like this:
$query = $this->db->get();
$ret = $query->row();
return $ret->campaign_id;
You can read more about it here: http://www.codeigniter.com/user_guide/database/results.html
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public static String get_match(String s, String p) {
// returns first match of p in s for first group in regular expression
Matcher m = Pattern.compile(p).matcher(s);
return m.find() ? m.group(1) : "";
}
get_match("FOO[BAR]", "\\[(.*?)\\]") // returns "BAR"
public static List<String> get_matches(String s, String p) {
// returns all matches of p in s for first group in regular expression
List<String> matches = new ArrayList<String>();
Matcher m = Pattern.compile(p).matcher(s);
while(m.find()) {
matches.add(m.group(1));
}
return matches;
}
get_matches("FOO[BAR] FOO[CAT]", "\\[(.*?)\\]")) // returns [BAR, CAT]
taking original db to offline worked for me
A of couple things that need to happen...
The view controller needs to extend the type UITableViewDelegate
The view controller needs to include the didSelectRowAt
function.
The table view must have the view controller assigned as its delegate.
Below is one place where assigning the delegate could take place (within the view controller).
override func loadView() {
tableView.dataSource = self
tableView.delegate = self
view = tableView
}
And a simple implementation of the didSelectRowAt
function.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("row: \(indexPath.row)")
}
There is an open source offline package deployer for Windows which I wrote:
http://siddharthbarman.com/apd/
You can try this out to see if it meets your needs.
Use splatting.
$CurlArgument = '-u', '[email protected]:yyyy',
'-X', 'POST',
'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
'--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument
This can happen if you have a newline (or other control character) in a JSON string literal.
{"foo": "bar
baz"}
If you are the one producing the data, replace actual newlines with escaped ones "\\n"
when creating your string literals.
{"foo": "bar\nbaz"}
I find the most simple is
shell "explorer.exe URL"
This also works to open local folders.
Using CentOS 7's default mailx (appears as heirloom-mailx), I've simplified this to just using a text file with your required headers and a static boundary for multipart/mixed and multipart/alternative setup.
I'm sure you can figure out multipart/related if you want with the same setup.
test.txt:
--000000000000f3b2150570186a0e
Content-Type: multipart/alternative; boundary="000000000000f3b2130570186a0c"
--000000000000f3b2130570186a0c
Content-Type: text/plain; charset="UTF-8"
This is my plain text stuff here, in case the email client does not support HTML or is blocking it purposely
My Link Here <http://www.example.com>
--000000000000f3b2130570186a0c
Content-Type: text/html; charset="UTF-8"
<div dir="ltr">
<div>This is my HTML version of the email</div>
<div><br></div>
<div><a href="http://www.example.com">My Link Here</a><br></div>
</div>
--000000000000f3b2130570186a0c--
--000000000000f3b2150570186a0e
Content-Type: text/csv; charset="US-ASCII"; name="test.csv"
Content-Disposition: attachment; filename="test.csv"
Content-Transfer-Encoding: base64
X-Attachment-Id: f_jj5qmzqz0
The boundaries define multipart segments.
The boundary ID that has no dashes at the end is a start point of a segment.
The one with the two dashes at the end is the end point.
In this example, there's a subpart within the multipart/mixed main section, for multipart/alternative.
The multipart/alternative method basically says "Fallback to this, IF the priority part does not succeed" - in this example HTML is taken as priority normally by email clients. If an email client won't display the HTML, it falls back to the plain text.
The multipart/mixed method which encapsulates this whole message, is basically saying there's different content here, display both.
In this example, I placed a CSV file attachment on the email. You'll see the attachment get plugged in using base64 in the command below.
I threw in the attachment as an example, you'll have to set your content type appropriately for your attachment and specify whether inline or not.
The X-Attachment-Id is necessary for some providers, randomize the ID you set.
The command to mail this is:
echo -e "`cat test.txt; openssl base64 -e < test.csv`\n--000000000000f3b2150570186a0e--\n" | mailx -s "Test 2 $( echo -e "\nContent-Type: multipart/mixed; boundary=\"000000000000f3b2150570186a0e\"" )" -r [email protected] [email protected]
As you can see in the mailx Subject line I insert the multipart boundary statically, this is the first header the email client will see.
Then comes the test.txt contents being dumped.
Regarding the attachment, I use openssl (which is pretty standard on systems) to convert the file attachment to base64.
Additionally, I added the boundary close statement at the end of this echo, to signify the end of the message.
This works around heirloom-mailx problems and is virtually script-less.
The echo can be a feed instead, or any other number of methods.
Yes use NOT NULL
in your query like this below.
SELECT *
FROM table
WHERE col IS NOT NULL;
I use Node version manager (called n) for it.
npm install -g n
then
n latest
OR
n stable
Here's a simple method to do it: The (ip >> 8)
, (ip >> 16)
and (ip >> 24)
moves the 2nd, 3rd and 4th bytes into the lower order byte, while the & 0xFF
isolates the least significant byte at each step.
void print_ip(unsigned int ip)
{
unsigned char bytes[4];
bytes[0] = ip & 0xFF;
bytes[1] = (ip >> 8) & 0xFF;
bytes[2] = (ip >> 16) & 0xFF;
bytes[3] = (ip >> 24) & 0xFF;
printf("%d.%d.%d.%d\n", bytes[3], bytes[2], bytes[1], bytes[0]);
}
There is an implied bytes[0] = (ip >> 0) & 0xFF;
at the first step.
Use snprintf()
to print it to a string.
Since in css3 one might set multiple background images setting "none" will only create a new layer and hide nothing.
http://www.css3.info/preview/multiple-backgrounds/ http://www.w3.org/TR/css3-background/#backgrounds
I have not found a solution yet...
It looks easier for me to clear all TabPages add add those wished:
PropertyTabControl.TabPages.Clear();
PropertyTabControl.TabPages.Add(AspectTabPage);
PropertyTabControl.TabPages.Add(WerkstattTabPage);
or
PropertyTabControl.TabPages.Clear();
PropertyTabControl.TabPages.Add(TerminTabPage);
You can add element to arrayList using add() method in Kotlin. For example,
arrayList.add(10)
Above code will add element 10 to arrayList.
However, if you are using Array or List, then you can not add element. This is because Array and List are Immutable. If you want to add element, you will have to use MutableList.
Several workarounds:
toMutableList()
method. Then, add element into it.System.arraycopy()
method.Here's something based on accepted answer. I removed the try/catch to make sure all the exceptions are not swallowed and not dealt with. Also made sure that the return variable (in accepted answer) is never initialized twice for nothing.
public static Nullable<T> ToNullable<T>(this string s) where T: struct
{
if (!string.IsNullOrWhiteSpace(s))
{
TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
return (T)conv.ConvertFrom(s);
}
return default(Nullable<T>);
}
Below is a example of Enum Struct that is Objective-C friendly in the event you need to use Swift Code in Legacy projects written in Objective-C.
Example:
contentType.filename. toString()
returns "filename"
contentType.filename. rawValue
returns the Int Value, 1 (since its the second item on struct)
@objc enum contentType:Int {
//date when content was created [RFC2183]
case creationDate
//name to be used when creating file [RFC2183]
case filename
//whether or not processing is required [RFC3204]
case handling
//date when content was last modified [RFC2183]
case modificationDate
//original field name in form [RFC7578]
case name
//Internet media type (and parameters) of the preview output desired from a processor by the author of the MIME content [RFC-ietf-appsawg-text-markdown-12]
case previewType
//date when content was last read [RFC2183]
case readDate
//approximate size of content in octets [RFC2183]
case size
//type or use of audio content [RFC2421]
case voice
func toString() -> String {
switch self {
case .creationDate:
return "creation-date"
case .filename:
return "filename"
case .handling:
return "handling"
case .modificationDate:
return "modification-date"
case .name:
return "name"
case .previewType:
return "preview-type"
case .readDate:
return "read-date"
case .size:
return "size"
case .voice:
return "voice"
}
}//eom
}//eo-enum
The following takes any valid datetime value and returns the number of days in the associated month... it eliminates the ambiguity of both other answers...
// pass in any date as parameter anyDateInMonth
function daysInMonth(anyDateInMonth) {
return new Date(anyDateInMonth.getFullYear(),
anyDateInMonth.getMonth()+1,
0).getDate();}
iconView = (ImageView) itemLayoutView .findViewById(R.id.iconId);
itemLayoutView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), SecondPage.class);
v.getContext().startActivity(intent);
Toast.makeText(v.getContext(), "os version is: " + feed.getTitle(), Toast.LENGTH_SHORT).show();
}
});
You may want to try the following:
SELECT CONCAT(title, ' ', forename, ' ', surname) AS name
FROM customer c
JOIN (
SELECT MAX(id) max_id, customer_id
FROM customer_data
GROUP BY customer_id
) c_max ON (c_max.customer_id = c.customer_id)
JOIN customer_data cd ON (cd.id = c_max.max_id)
WHERE CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%'
LIMIT 10, 20;
Note that a JOIN
is just a synonym for INNER JOIN
.
Test case:
CREATE TABLE customer (customer_id int);
CREATE TABLE customer_data (
id int,
customer_id int,
title varchar(10),
forename varchar(10),
surname varchar(10)
);
INSERT INTO customer VALUES (1);
INSERT INTO customer VALUES (2);
INSERT INTO customer VALUES (3);
INSERT INTO customer_data VALUES (1, 1, 'Mr', 'Bobby', 'Smith');
INSERT INTO customer_data VALUES (2, 1, 'Mr', 'Bob', 'Smith');
INSERT INTO customer_data VALUES (3, 2, 'Mr', 'Jane', 'Green');
INSERT INTO customer_data VALUES (4, 2, 'Miss', 'Jane', 'Green');
INSERT INTO customer_data VALUES (5, 3, 'Dr', 'Jack', 'Black');
Result (query without the LIMIT
and WHERE
):
SELECT CONCAT(title, ' ', forename, ' ', surname) AS name
FROM customer c
JOIN (
SELECT MAX(id) max_id, customer_id
FROM customer_data
GROUP BY customer_id
) c_max ON (c_max.customer_id = c.customer_id)
JOIN customer_data cd ON (cd.id = c_max.max_id);
+-----------------+
| name |
+-----------------+
| Mr Bob Smith |
| Miss Jane Green |
| Dr Jack Black |
+-----------------+
3 rows in set (0.00 sec)
Here is the code to check whether value is present or not.
If Trim(textbox1.text) <> "" Then
'Your code goes here
Else
'Nothing
End If
I think this will help.
One possible situation where this might be needed:
If you are using finally
block to close connections but in the try
block, the program exits with sys.exit()
before the connection is defined. In this case, the finally
block will be called and the connection closing statement will fail since no connection was created.
I used this method and managed to get the desired output. my script
x = "{'inner-temperature': 31.73, 'outer-temperature': 28.38, 'keys-value': 0}"
x = x.replace("'", '"')
j = json.loads(x)
print(j['keys-value'])
output
>>> 0
The following code can be used:
DWORD FindProcessId(const std::wstring& processName)
{
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(processInfo);
HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (processesSnapshot == INVALID_HANDLE_VALUE) {
return 0;
}
Process32First(processesSnapshot, &processInfo);
if (!processName.compare(processInfo.szExeFile))
{
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
while (Process32Next(processesSnapshot, &processInfo))
{
if (!processName.compare(processInfo.szExeFile))
{
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
}
CloseHandle(processesSnapshot);
return 0;
}
Usage:
auto processId = FindProcessId(L"blabla.exe");
Getting a handle should be obvious, just call OpenProcess()
or similar on it.
This can get more complicated depending on where PHP sits in your environment, since your question is quite broad. This may depend on whether there's a load-balancer and how it's configured. Here are are a few related questions:
Virtual functions basically provide polymorphic behavior. That is, when you work with an object whose dynamic type is different than the static (compile time) type with which it is referred to, it provides behavior that is appropriate for the actual type of object instead of the static type of the object.
Now try to apply that sort of behavior to a constructor. When you construct an object the static type is always the same as the actual object type since:
To construct an object, a constructor needs the exact type of the object it is to create [...] Furthermore [...]you cannot have a pointer to a constructor
(Bjarne Stroustup (P424 The C++ Programming Language SE))
Here is an alternative that is an incremental improvement on several other answers. Assuming settings.aLengthMenu is not multi-dimensional (it can be when DataTables has row lengths and labels) and the data will not change after page load (for simple DOM-loaded DataTables), this function can be inserted to eliminate paging. It hides several paging-related classes.
Perhaps more robust would be setting paging to false inside the function below, however I don't see an API call for that off-hand.
$('#myTable').on('init.dt', function(evt, settings) {
if (settings && settings.aLengthMenu && settings.fnRecordsTotal && settings.fnRecordsTotal() < settings.aLengthMenu[0]) {
// hide pagination controls, fewer records than minimum length
$(settings.nTableWrapper).find('.dataTables_paginate, .dataTables_length, .dataTables_info').hide();
}
}).DataTable();
Thank you guys for the help,
When I asked at first I didn't think it's even possible, but after your answers I googled and found this amazing tutorial:
Based on this answer, one-liner for simple cases (Python 3 code):
from urllib.parse import urlparse, urlencode
url = "https://stackoverflow.com/search?q=question"
params = {'lang':'en','tag':'python'}
url += ('&' if urlparse(url).query else '?') + urlencode(params)
or:
url += ('&', '?')[urlparse(url).query == ''] + urlencode(params)
editText.setEnabled(false);
editText.setFilters(new InputFilter[] { new InputFilter() {
public CharSequence filter(CharSequence src, int start, int end,
Spanned dst, int dstart, int dend) {
return src.length() < 1 ? dst.subSequence(dstart, dend) : "";
}
} });
This will give you uneditable EditText filter. you first need to put the text you want on the editText field and then apply this filter.
You want to follow the same pattern as before:
for (Type curInstance: CollectionOf<Type>) {
// use currInstance
}
In this case it would be:
for (Bullet bullet : gunList.get(2).getBullet()) {
System.out.println(bullet);
}
For the question
How can i run a jar file in command prompt but with arguments
.
To pass arguments to the jar file at the time of execution
java -jar myjar.jar arg1 arg2
In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:
String arg1 = args[0];
String arg2 = args[1];
Kinda late to the party, but in case anyone else is struggling. None of the Google searches I've found for the past two days have come up with anything that works, but I came up with a concise and elegant solution that will always work no matter how many nested tags you have:
function cursor_position() {_x000D_
var sel = document.getSelection();_x000D_
sel.modify("extend", "backward", "paragraphboundary");_x000D_
var pos = sel.toString().length;_x000D_
if(sel.anchorNode != undefined) sel.collapseToEnd();_x000D_
_x000D_
return pos;_x000D_
}_x000D_
_x000D_
// Demo:_x000D_
var elm = document.querySelector('[contenteditable]');_x000D_
elm.addEventListener('click', printCaretPosition)_x000D_
elm.addEventListener('keydown', printCaretPosition)_x000D_
_x000D_
function printCaretPosition(){_x000D_
console.log( cursor_position(), 'length:', this.textContent.trim().length )_x000D_
}
_x000D_
<div contenteditable>some text here <i>italic text here</i> some other text here <b>bold text here</b> end of text</div>
_x000D_
It selects all the way back to the beginning of the paragraph and then counts the length of the string to get the current position and then undoes the selection to return the cursor to the current position. If you want to do this for an entire document (more than one paragraph), then change paragraphboundary
to documentboundary
or whatever granularity for your case. Check out the API for more details. Cheers! :)
Look at the following commands (especially the commented block).
DROP TABLE foo;
DROP TABLE bar;
CREATE TABLE foo (a int, b text);
CREATE TABLE bar (a serial, b text);
INSERT INTO foo (a, b) SELECT i, 'foo ' || i::text FROM generate_series(1, 5) i;
INSERT INTO bar (b) SELECT 'bar ' || i::text FROM generate_series(1, 5) i;
-- blocks of commands to turn foo into bar
CREATE SEQUENCE foo_a_seq;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
ALTER TABLE foo ALTER COLUMN a SET NOT NULL;
ALTER SEQUENCE foo_a_seq OWNED BY foo.a; -- 8.2 or later
SELECT MAX(a) FROM foo;
SELECT setval('foo_a_seq', 5); -- replace 5 by SELECT MAX result
INSERT INTO foo (b) VALUES('teste');
INSERT INTO bar (b) VALUES('teste');
SELECT * FROM foo;
SELECT * FROM bar;
Check this question. The correct answer has great explanation on how to terminate threads the right way: Is there any way to kill a Thread in Python?
To make the thread stop on Keyboard Interrupt signal (ctrl+c) you can catch the exception "KeyboardInterrupt" and cleanup before exiting. Like this:
try:
start_thread()
except (KeyboardInterrupt, SystemExit):
cleanup_stop_thread()
sys.exit()
This way you can control what to do whenever the program is abruptly terminated.
You can also use the built-in signal module that lets you setup signal handlers (in your specific case the SIGINT signal): http://docs.python.org/library/signal.html
Update February 2016:
www.javadecompilers.com lists JAD as being:
the most popular Java decompiler, but primarily of this age only. Written in C++, so very fast.
Outdated, unsupported and does not decompile correctly Java 5 and later
So your mileage may vary with recent jdk (7, 8).
The same site list other tools.
And javadecompiler, as noted by Salvador Valencia in the comments (Sept 2017), offers a SaaS where you upload the .class
file to the cloud and it returns you the decompiled code.
Original answer: Oct. 2008
Java Decompiler (Yet another Fast Java decompiler) has:
It works with compilers from JDK 1.1.8 up to JDK 1.7.0, and others (Jikes, JRockit, etc.).
It features an online live demo version that is actually fully functional! You can just drop a jar file on the page and see the decompiled source code without installing anything.
The question has already been answered but I thought I would also let you know that rather than using the native PHP $_POST I reccomend you use the CodeIgniter input class so your controller code would be
function post_action()
{
if($this->input->post('textbox') == "")
{
$message = "You can't send empty text";
}
else
{
$message = $this->input->post('textbox');
}
echo $message;
}
I created an angularjs directive using @Russ's and @Alex's answers
Could be interesting in 2014 and beyond :P
html
<div ng-app="croppy">
<cropped-image src="http://placehold.it/200x200" width="100" height="100"></cropped-image>
</div>
js
angular.module('croppy', [])
.directive('croppedImage', function () {
return {
restrict: "E",
replace: true,
template: "<div class='center-cropped'></div>",
link: function(scope, element, attrs) {
var width = attrs.width;
var height = attrs.height;
element.css('width', width + "px");
element.css('height', height + "px");
element.css('backgroundPosition', 'center center');
element.css('backgroundRepeat', 'no-repeat');
element.css('backgroundImage', "url('" + attrs.src + "')");
}
}
});
Unfortunately there is no way to initialize array members till C++0x.
You could use a std::vector and push_back the Foo instances in the constructor body.
You could give Foo a default constructor (might be private and making Baz a friend).
You could use an array object that is copyable (boost or std::tr1) and initialize from a static array:
#include <boost/array.hpp>
struct Baz {
boost::array<Foo, 3> foo;
static boost::array<Foo, 3> initFoo;
Baz() : foo(initFoo)
{
}
};
boost::array<Foo, 3> Baz::initFoo = { 4, 5, 6 };
We can also use postgresql-easy. It is built on node-postgres and sqlutil. Note: pg_connection.js & your_handler.js are in the same folder. db.js is in the config folder placed.
pg_connection.js
const PgConnection = require('postgresql-easy');
const dbConfig = require('./config/db');
const pg = new PgConnection(dbConfig);
module.exports = pg;
./config/db.js
module.exports = {
database: 'your db',
host: 'your host',
port: 'your port',
user: 'your user',
password: 'your pwd',
}
your_handler.js
const pg_conctn = require('./pg_connection');
pg_conctn.getAll('your table')
.then(res => {
doResponseHandlingstuff();
})
.catch(e => {
doErrorHandlingStuff()
})
imp system/system-password@SID file=directory-you-selected\FILE.dmp log=log-dir\oracle_load.log fromuser=infodba touser=infodba commit=Y
your node.js server is running on a port determined at the end of the script usually. Sometimes 3000. but can be anything. The correct way for others to access is as you say...
http://your.network.ip.address:port/ e.g. http://192.168.0.3:3000
check you have the correct port - and the ip address on the network - not internet ip.
Otherwise, maybe the ports are being blocked by your router. Try using 8080 or 80 to get around this - otherwise re-configure your router.
You can use the String(byte[] bytes)
constructor for that. See this link for details.
EDIT You also have to consider your plateform's default charset as per the java doc:
Constructs a new String by decoding the specified array of bytes using the platform's default charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array. The behavior of this constructor when the given bytes are not valid in the default charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required.
loginView.layer.shadowOpacity = 1.0
you can use setTextColor(int) method or add style to change text color.
<style name="ReviewScreenKbbViewMoreStyle">
<item name="android:textColor">#2F2E86</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">10dip</item>
I know this is a question regarding the CSS.Tooltips library. However, for anyone else came here resulting from google search "tooltip for input box" like I did, here is the simplest way:
<input title="This is the text of the tooltip" value="44"/>
I hope this would provide you with the right solution:
Syntax:
CASE
WHEN search_condition THEN statement_list
[WHEN search_condition THEN statement_list]....
[ELSE statement_list]
END CASE
Implementation:
select id, action_heading,
case when
action_type="Expense" then action_amount
else NULL
end as Expense_amt,
case when
action_type ="Income" then action_amount
else NULL
end as Income_amt
from tbl_transaction;
Here I am using CASE
statement as it is more flexible than if-then-else
. It allows more than one branch. And CASE
statement is standard SQL and works in most databases.
I think it is implemented in the engine as Matthias said: WHERE, GROUP BY, HAVING
Was trying to find a reference online that lists the entire sequence (i.e. "SELECT" comes right down at the bottom), but I can't find it. It was detailed in a "Inside Microsoft SQL Server 2005" book I read not that long ago, by Solid Quality Learning
Edit: Found a link: http://blogs.x2line.com/al/archive/2007/06/30/3187.aspx
If you don't care about the changes that git says are outstanding, then you can do a force checkout.
git checkout -f {{insert your branch name here}}
This will get you the PID of a process by name:
pidof name
Which you can then plug back in to ps for more detail:
ps -p $(pidof name)
I noticed I was using the incorrect HTTP request url while making it, later which i changed that it resolved my problem. my upload url was : http://192.168.0.31:5000/uploader while i was using http://192.168.0.31:5000. that was a get call. and got a java.net.SocketException: Broken pipe? exception.
That was my reason. might lead you to check one more point when this issue
public void postRequest() {
Security.insertProviderAt(Conscrypt.newProvider(), 1);
System.out.println("mediafilename-->>" + mediaFileName);
String[] dirarray = mediaFileName.split("/");
String file_name = dirarray[6];
//Thread.sleep(10000);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file",file_name, RequestBody.create(MediaType.parse("video/mp4"), new File(mediaFileName))).build();
OkHttpClient okHttpClient = new OkHttpClient();
// ExecutorService executor = newFixedThreadPool(20);
// Request request = new Request.Builder().post(requestBody).url("https://192.168.0.31:5000/uploader").build();
Request request = new Request.Builder().url("http://192.168.0.31:5000/uploader").post(requestBody).build();
// Request request = new Request.Builder().url("http://192.168.0.31:5000").build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
//
call.cancel();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),"Something went wrong:" + " ", Toast.LENGTH_SHORT).show();
}
});
e.printStackTrace();
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
System.out.println("Response ; " + response.body().toString());
// Toast.makeText(getApplicationContext(), response.body().toString(),Toast.LENGTH_LONG).show();
System.out.println(response);
}
});
For a unique column, use this:
INSERT OR REPLACE INTO table () values();
For more information, see: sqlite.org/lang_insert
Have you tried using :
git dif | grep -B <number of before lines to show> <regex>
In my case, i try to search where do i put a debug statement in the many files, i need to see which file already got this debug statement like this :
git diff | grep -B 5 dd\(
var str = '';
for( var name in obj ) {
str += (name + '=' + obj[name] + '&');
}
str = str.slice(0,-1);
Give this a shot.
Example: http://jsfiddle.net/T2UWT/
I know the question is asking about your "csv" package implementation, but for your information, there are options that are much simpler — numpy, for instance.
import numpy as np
np.savetxt('data.csv', (col1_array, col2_array, col3_array), delimiter=',')
(This answer posted 6 years later, for posterity's sake.)
In a different case similar to what you're asking about, say you have two columns like this:
names = ['Player Name', 'Foo', 'Bar']
scores = ['Score', 250, 500]
You could save it like this:
np.savetxt('scores.csv', [p for p in zip(names, scores)], delimiter=',', fmt='%s')
scores.csv
would look like this:
Player Name,Score
Foo,250
Bar,500
Every object has a __dict__
variable containing all the variables and its values in it.
Try this
>>> hi_obj = hi()
>>> hi_obj.__dict__.keys()
To expand on Byron's answer, I believe you need to edit the file java.security
in the %JRE_HOME%\lib\security
directory to effect this change.
Here is the relevant section:
#
# The Java-level namelookup cache policy for successful lookups:
#
# any negative value: caching forever
# any positive value: the number of seconds to cache an address for
# zero: do not cache
#
# default value is forever (FOREVER). For security reasons, this
# caching is made forever when a security manager is set. When a security
# manager is not set, the default behavior is to cache for 30 seconds.
#
# NOTE: setting this to anything other than the default value can have
# serious security implications. Do not set it unless
# you are sure you are not exposed to DNS spoofing attack.
#
#networkaddress.cache.ttl=-1
Documentation on the java.security
file here.
TortoiseSVN doesn't use svn.exe it has SVN library compiled in. If you need to run your own tasks you would have to install stand alone subversion client. You either from Cygwin [http://cygwin.com ] or get a native version from http://subversion.apache.org/packages.html#windows
WinForm:
private void button1_Click(object sender, EventArgs e)
{
button2.BackColor = Color.Red;
}
WPF:
private void button1_Click(object sender, RoutedEventArgs e)
{
button2.Background = Brushes.Blue;
}
INSERT INTO KeyedTable(KeyField, Otherfield)
SELECT n.* FROM
(SELECT 'PossibleDupeLiteral' AS KeyField, 'OtherfieldValue' AS Otherfield
UNION ALL
SELECT 'PossibleDupeLiteral', 'OtherfieldValue2'
)
LEFT JOIN KeyedTable k
ON k.KeyField=n.KeyField
WHERE k.KeyField IS NULL
This tells the Server to look for the same data (hopefully the same speedy way it does to check for duplicate keys) and insert nothing if it finds it.
I like the IGNORE_DUP_KEY solution too, but then anyone who relies on errors to catch problems will be mystified when the server silently ignores their dupe-key errors.
The reason I choose this over Philip Kelley's solution is that you can provide several rows of data and only have the missing ones actually get in:
I would like to add some more suggestions based on my most recent implementation. I've looked at some code from Apple and I think my code behaves in much the same way.
The posts above already explain how to create NSError objects and return them, so I won't bother with that part. I'll just try to suggest a good way to integrate errors (codes, messages) in your own app.
I recommend creating 1 header that will be an overview of all the errors of your domain (i.e. app, library, etc..). My current header looks like this:
FSError.h
FOUNDATION_EXPORT NSString *const FSMyAppErrorDomain;
enum {
FSUserNotLoggedInError = 1000,
FSUserLogoutFailedError,
FSProfileParsingFailedError,
FSProfileBadLoginError,
FSFNIDParsingFailedError,
};
FSError.m
#import "FSError.h"
NSString *const FSMyAppErrorDomain = @"com.felis.myapp";
Now when using the above values for errors, Apple will create some basic standard error message for your app. An error could be created like the following:
+ (FSProfileInfo *)profileInfoWithData:(NSData *)data error:(NSError **)error
{
FSProfileInfo *profileInfo = [[FSProfileInfo alloc] init];
if (profileInfo)
{
/* ... lots of parsing code here ... */
if (profileInfo.username == nil)
{
*error = [NSError errorWithDomain:FSMyAppErrorDomain code:FSProfileParsingFailedError userInfo:nil];
return nil;
}
}
return profileInfo;
}
The standard Apple-generated error message (error.localizedDescription
) for the above code will look like the following:
Error Domain=com.felis.myapp Code=1002 "The operation couldn’t be completed. (com.felis.myapp error 1002.)"
The above is already quite helpful for a developer, since the message displays the domain where the error occured and the corresponding error code. End users will have no clue what error code 1002
means though, so now we need to implement some nice messages for each code.
For the error messages we have to keep localisation in mind (even if we don't implement localized messages right away). I've used the following approach in my current project:
1) create a strings
file that will contain the errors. Strings files are easily localizable. The file could look like the following:
FSError.strings
"1000" = "User not logged in.";
"1001" = "Logout failed.";
"1002" = "Parser failed.";
"1003" = "Incorrect username or password.";
"1004" = "Failed to parse FNID."
2) Add macros to convert integer codes to localized error messages. I've used 2 macros in my Constants+Macros.h file. I always include this file in the prefix header (MyApp-Prefix.pch
) for convenience.
Constants+Macros.h
// error handling ...
#define FS_ERROR_KEY(code) [NSString stringWithFormat:@"%d", code]
#define FS_ERROR_LOCALIZED_DESCRIPTION(code) NSLocalizedStringFromTable(FS_ERROR_KEY(code), @"FSError", nil)
3) Now it's easy to show a user friendly error message based on an error code. An example:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:FS_ERROR_LOCALIZED_DESCRIPTION(error.code)
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
Copy and paste the local.properties file from a project you created on your new computer to the folder containing the project from your old computer also works too if you don't want to (or know how to) create a new local.properties file.
you can use accept
attribute for <input type="file">
read this docs http://www.w3schools.com/tags/att_input_accept.asp
To force IE to render in IE9 standards mode you should use
<meta http-equiv="X-UA-Compatible" content="IE=edge">
Some conditions may cause IE9 to jump down into the compatibility modes. By default this can occur on intranet sites.
To simulate a low bandwidth connection for testing web sites use Google Chrome, you can go to the Network Tab in F12 Tools and select a bandwidth level to simulate or create custom bandwidth to simulate.
Here the XAML Version
<Window.Background>
<ImageBrush>
<ImageBrush.ImageSource>
<BitmapImage UriSource="//your source .."/>
</ImageBrush.ImageSource>
</ImageBrush>
</Window.Background>
Since a lot of people still do:
using (System.IO.StreamReader r = new System.IO.StreamReader(""))
using (System.IO.StreamReader r2 = new System.IO.StreamReader("")) {
//code
}
I guess a lot of people still don't know that you can do:
using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2 = new System.IO.StreamReader("")) {
//code
}
http://www.w3schools.com/cssref/css3_pr_animation-keyframes.asp
it is actually a browser issue... use -webkit- for chrome
You can do it by using attr, the mistake that you made is that you put the true inside quotes. instead of that try this:
$("input").attr("required", true);
If you have the ID of the div, try this:
<input type='submit' onclick='$("#div_id").show()'>
I find the "parseInt" suggestions to be pretty curious, because "parseInt" operates on strings by design. That's why its name has the word "parse" in it.
A trick that avoids a function call entirely is
var truncated = ~~number;
The double application of the "~" unary operator will leave you with a truncated version of a double-precision value. However, the value is limited to 32 bit precision, as with all the other JavaScript operations that implicitly involve considering numbers to be integers (like array indexing and the bitwise operators).
edit — In an update quite a while later, another alternative to the ~~
trick is to bitwise-OR the value with zero:
var truncated = number|0;
First of all, your description is misleading. Double
is a floating point data type. You presumably want to pad your digits with leading zeros in a string. The following code does that:
$s = sprintf('%02d', $digit);
For more information, refer to the documentation of sprintf
.
If any1 in 2017 is wondering how to do this programmatically, there is a way that i don't see in the answers
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
I tried lots of different solutions, the only one that worked for me was based on the solution by Chris G on this page (but with a slight modification).
I have turned it into a jQuery plugin for future use for anyone that needs it
(function($){
$.fn.setCursorToTextEnd = function() {
var $initialVal = this.val();
this.val($initialVal);
};
})(jQuery);
example of usage:
$('#myTextbox').setCursorToTextEnd();
As you state in one of your comments that the table in question is in a different database, then ownership chaining applies. I suspect there is a break in the chain somewhere - check that link for full details.
The $push operator appends a specified value to an array.
{ $push: { <field1>: <value1>, ... } }
$push adds the array field with the value as its element.
Above answer fulfils all the requirements, but I got it working by doing the following
var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
Friend.findOneAndUpdate(
{ _id: req.body.id },
{ $push: { friends: objFriends } },
function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
});
)
git log remotename/branchname
Will display the log of a given remote branch in that repository, but only the logs that you have "fetched" from their repository to your personal "copy" of the remote repository.
Remember that your clone of the repository will update its state of any remote branches only by doing git fetch
. You can't connect directly to the server to check the log there, what you do is download the state of the server with git fetch
and then locally see the log of the remote branches.
Perhaps another useful command could be:
git log HEAD..remote/branch
which will show you the commits that are in the remote branch, but not in your current branch (HEAD
).
I tried the code posted by larsmans above but, there are a couple of problems:
1) The code as is will throw the error as mentioned by mauguerra 2) If you change the code to the following:
...
d1 = d1.strftime("%Y-%m-%d")
d2 = d2.strftime("%Y-%m-%d")
return abs((d2 - d1).days)
This will convert your datetime objects to strings but, two things
1) Trying to do d2 - d1 will fail as you cannot use the minus operator on strings and 2) If you read the first line of the above answer it stated, you want to use the - operator on two datetime objects but, you just converted them to strings
What I found is that you literally only need the following:
import datetime
end_date = datetime.datetime.utcnow()
start_date = end_date - datetime.timedelta(days=8)
difference_in_days = abs((end_date - start_date).days)
print difference_in_days
Well, the way to do it with simple parsing would be: get everything starting after the first = sign to the first & sign.
I think they had a similiar answer here:
After reading the other answers (First by @duncan-finney and then by @Marrs) I set out to find the change log that explains the idiomatic react-router 2.x way of solving this. The documentation on using location (which you need for queries) in components is actually contradicted by the actual code. So if you follow their advice, you get big angry warnings like this:
Warning: [react-router] `context.location` is deprecated, please use a route component's `props.location` instead.
It turns out that you cannot have a context property called location that uses the location type. But you can use a context property called loc that uses the location type. So the solution is a small modification on their source as follows:
const RouteComponent = React.createClass({
childContextTypes: {
loc: PropTypes.location
},
getChildContext() {
return { location: this.props.location }
}
});
const ChildComponent = React.createClass({
contextTypes: {
loc: PropTypes.location
},
render() {
console.log(this.context.loc);
return(<div>this.context.loc.query</div>);
}
});
You could also pass down only the parts of the location object you want in your children get the same benefit. It didn't change the warning to change to the object type. Hope that helps.
This worked for me : http://tecadmin.net/fatal-ident-authentication-failed-for-user-postgres/#
local all postgres trust
local all myapp_usr trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
# IPv6 local connections:
#host all all ::1/128 trust
I have nothing against libraries in general. In this case a general purpose library seems overkill, unless other parts of the application process dates heavily.
Writing small utility functions such as this is also a useful exercise for both beginning and accomplished programmers alike and can be a learning experience for the novices amongst us.
function dateFormat (date, fstr, utc) {
utc = utc ? 'getUTC' : 'get';
return fstr.replace (/%[YmdHMS]/g, function (m) {
switch (m) {
case '%Y': return date[utc + 'FullYear'] (); // no leading zeros required
case '%m': m = 1 + date[utc + 'Month'] (); break;
case '%d': m = date[utc + 'Date'] (); break;
case '%H': m = date[utc + 'Hours'] (); break;
case '%M': m = date[utc + 'Minutes'] (); break;
case '%S': m = date[utc + 'Seconds'] (); break;
default: return m.slice (1); // unknown code, remove %
}
// add leading zero if required
return ('0' + m).slice (-2);
});
}
/* dateFormat (new Date (), "%Y-%m-%d %H:%M:%S", true) returns
"2012-05-18 05:37:21" */
You could also do it utilizing getTimezoneOffset and getTime,
x = new Date()_x000D_
var UTCseconds = (x.getTime() + x.getTimezoneOffset()*60*1000)/1000;_x000D_
_x000D_
console.log("UTCseconds", UTCseconds)
_x000D_
you can saperate string using the below code
String thisString="Hello world";
String[] parts = theString.split(" ");
String first = parts[0];//"hello"
String second = parts[1];//"World"
I think you need to explicitly pass the data attribute. One way to do this is to use the data = $('#your-form-id').serialize();
This post may be helpful. Post with jquery and ajax
Have a look at the doc here.. Ajax serialize
Looping helps:
for row in matrix:
print ' '.join(row)
or use nested str.join()
calls:
print '\n'.join([' '.join(row) for row in matrix])
Demo:
>>> matrix = [['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E']]
>>> for row in matrix:
... print ' '.join(row)
...
A B C D E
A B C D E
A B C D E
A B C D E
A B C D E
>>> print '\n'.join([' '.join(row) for row in matrix])
A B C D E
A B C D E
A B C D E
A B C D E
A B C D E
If you wanted to show the rows and columns transposed, transpose the matrix by using the zip()
function; if you pass each row as a separate argument to the function, zip()
recombines these value by value as tuples of columns instead. The *args
syntax lets you apply a whole sequence of rows as separate arguments:
>>> for cols in zip(*matrix): # transposed
... print ' '.join(cols)
...
A A A A A
B B B B B
C C C C C
D D D D D
E E E E E
if ("ontouchstart" in window || navigator.msMaxTouchPoints) {
isTouch = true;
} else {
isTouch = false;
}
Works every where !!
Use YQL and you don't need to worry. It's a query language by Yahoo and you can get all the stock data including the name of the company for the ticker. It's a REST API and it returns the results via XML or JSON. I have a full tutorial and source code on my site take a look: http://www.jarloo.com/yahoo-stock-symbol-lookup/
Tables ::
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'
columns ::
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
or
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='your_table_name'
You can always take the CTE, (Common Tabular Expression), approach.
;WITH updateCTE AS
(
SELECT ID, TITLE
FROM HOLD_TABLE
WHERE ID = 101
)
UPDATE updateCTE
SET TITLE = 'TEST';
You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.
Sample snippet for time-diff:
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
This hasn't solved my problem too, so I changed the parameters slightly.
This code worked for me:
var dataValue = "{ name: 'person', isGoing: 'true', returnAddress: 'returnEmail' }";
$.ajax({
type: "POST",
url: "Default.aspx/OnSubmit",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result.d);
}
});
Updated with recursive array expansion on @max-sirwa 's code
class Objectify:
def __init__(self, **kwargs):
for key, value in kwargs.items():
if isinstance(value, dict):
f = Objectify(**value)
self.__dict__.update({key: f})
elif isinstance(value, list):
t = []
for i in value:
t.append(Objectify(**i)) if isinstance(i, dict) else t.append(i)
self.__dict__.update({key: t})
else:
self.__dict__.update({key: value})
Without seeing your full code, this is impossible to answer with any certainty. The error usually occurs when you are trying to unload a control rather than the form.
Make sure that you don't have the "me" in brackets.
Also if you can post the full code for the userform it would help massively.
I had the problem not being able to send ">" and ended up with echo!
echo "Hello world" | dd of=test.txt
You can use below code also.It quite simple.
$selectedTime = "9:15:00";
echo date('h:i:s',strtotime($selectedTime . ' +15 minutes'));
Here is one more possible way using reshape
:
a_norm = (a/a.sum(axis=1).reshape(-1,1)).round(3)
print(a_norm)
Or using None
works too:
a_norm = (a/a.sum(axis=1)[:,None]).round(3)
print(a_norm)
Output:
array([[0. , 0.333, 0.667],
[0.25 , 0.333, 0.417],
[0.286, 0.333, 0.381]])
You could do an ajax call.
That way, you would be able to populate the POST array yourself through the ajax 'data: ' parameter
var params = {
url: window.location.pathname,
time: new Date().getTime(),
};
$.ajax({
method: "POST",
url: "your/script.php",
data: params
});
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/jsp-api-6.0.16.jar
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/servlet-api-6.0.16.jar
You should not have any server-specific libraries in the /WEB-INF/lib
. Leave them in the appserver's own library. It would only lead to collisions in the classpath. Get rid of all appserver-specific libraries in /WEB-INF/lib
(and also in JRE/lib
and JRE/lib/ext
if you have placed any of them there).
A common cause that the appserver-specific libraries are included in the webapp's library is that starters think that it is the right way to fix compilation errors of among others the javax.servlet
classes not being resolveable. Putting them in webapp's library is the wrong solution. You should reference them in the classpath during compilation, i.e. javac -cp /path/to/server/lib/servlet.jar
and so on, or if you're using an IDE, you should integrate the server in the IDE and associate the web project with the server. The IDE will then automatically take server-specific libraries in the classpath (buildpath) of the webapp project.
it depends what sort of t-test you want to do (one sided or two sided dependent or independent) but it should be as simple as:
from scipy.stats import ttest_ind
cat1 = my_data[my_data['Category']=='cat1']
cat2 = my_data[my_data['Category']=='cat2']
ttest_ind(cat1['values'], cat2['values'])
>>> (1.4927289925706944, 0.16970867501294376)
it returns a tuple with the t-statistic & the p-value
see here for other t-tests http://docs.scipy.org/doc/scipy/reference/stats.html
Well, you must first drop the auto_increment
and primary key
you have and then add yours, as follows:
-- drop auto_increment capability
alter table `users` modify column id INT NOT NULL;
-- in one line, drop primary key and rebuild one
alter table `users` drop primary key, add primary key(id);
-- re add the auto_increment capability, last value is remembered
alter table `users` modify column id INT NOT NULL AUTO_INCREMENT;
First step:
pip uninstall numpy
pip uninstall opencv-python
Second step:
pip install numpy
pip install opencv-python
from IPython.utils.io import Tee
from contextlib import closing
print('This is not in the output file.')
with closing(Tee("outputfile.log", "w", channel="stdout")) as outputstream:
print('This is written to the output file and the console.')
# raise Exception('The file "outputfile.log" is closed anyway.')
print('This is not written to the output file.')
# Output on console:
# This is not in the output file.
# This is written to the output file and the console.
# This is not written to the output file.
# Content of file outputfile.txt:
# This is written to the output file and the console.
The Tee
class in IPython.utils.io
does what you want, but it lacks the __enter__
and __exit__
methods needed to call it in the with
-statement. Those are added by contextlib.closing
.
Can't you style the forms themselves? Then, style the divs accordingly.
form
{
/* styles */
}
You can always overrule inherited styles by making it important:
form
{
/* styles */ !important
}
matches() is an XPATH 2.0 function that allows for case-insensitive regex matching.
One of the flags is i
for case-insensitive matching.
The following XPATH using the matches() function with the case-insensitive flag:
//CD[matches(@title,'empire burlesque','i')]
How are you loading the values into the drop down list or determining which value to select? If you are doing this using Ajax, then the reason you need the delay before the selection occurs could be because the values were not loaded in at the time that the line in question executed. This would also explain why it worked when you put an alert statement on the line before setting the status since the alert action would give enough of a delay for the data to load.
If you are using one of jQuery's Ajax methods, you can specify a callback function and then put $("._statusDDL").val(2);
into your callback function.
This would be a more reliable way of handling the issue since you could be sure that the method executed when the data was ready, even if it took longer than 300 ms.
I am using Jupyter-notebook. And in my case, it was showing the file in the wrong format. The 'encoding' option was not working. So I save the csv in utf-8 format, and it works.
Should work in all cases:
SELECT regexp_replace(0.1234, '^(-?)([.,])', '\10\2') FROM dual
you can use
<p><a href="/link/to/url" target="_blank"><button id="btn_id">Present Name </button></a></p>
I was facing the same issue in spring boot 2.1.3 saying that resource not found 404. I removed below from applicatiion.properties.
#spring.resources.add-mappings=true
#spring.resources.static-locations=classpath:static
#spring.mvc.static-path-pattern=/**,
Removed @enableWebMVC and removed any WebMvcConfigurer overriding
//@EnableWebMvc
Also make sure you have @EnableAutoConfiguration in your config.
And put all static resources into src/main/resources/static and it just worked like magic finally..
by VB function:
Dim m_RowNr(3) as Variant
'
Function RowNr(ByVal strQName As String, ByVal vUniqValue) As Long
' m_RowNr(3)
' 0 - Nr
' 1 - Query Name
' 2 - last date_time
' 3 - UniqValue
If Not m_RowNr(1) = strQName Then
m_RowNr(0) = 1
m_RowNr(1) = strQName
ElseIf DateDiff("s", m_RowNr(2), Now) > 9 Then
m_RowNr(0) = 1
ElseIf Not m_RowNr(3) = vUniqValue Then
m_RowNr(0) = m_RowNr(0) + 1
End If
m_RowNr(2) = Now
m_RowNr(3) = vUniqValue
RowNr = m_RowNr(0)
End Function
Usage(without sorting option):
SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
From table A
Order By A.id
if sorting required or multiple tables join then create intermediate table:
SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
INTO table_with_Nr
From table A
Order By A.id
I use the following vba code where filename is a string containing the filename I want, and Function RemoveSpecialCharactersAndTruncate is defined below:
worksheet1.Name = RemoveSpecialCharactersAndTruncate(filename)
'Function to remove special characters from file before saving
Private Function RemoveSpecialCharactersAndTruncate$(ByVal FormattedString$)
Dim IllegalCharacterSet$
Dim i As Integer
'Set of illegal characters
IllegalCharacterSet$ = "*." & Chr(34) & "//\[]:;|=,"
'Iterate through illegal characters and replace any instances
For i = 1 To Len(IllegalCharacterSet) - 1
FormattedString$ = Replace(FormattedString$, Mid(IllegalCharacterSet, i, 1), "")
Next
'Return the value capped at 31 characters (Excel limit)
RemoveSpecialCharactersAndTruncate$ = Left(FormattedString$, _
Application.WorksheetFunction.Min(Len(FormattedString), 31))
End Function
Like this:
> df[df==""]<-NA
> df
A B
1 <NA> 12
2 xyz <NA>
3 jkl 100
This can be done with java reflection,This method returns false if any one attribute value is present for the object ,hope it helps some one
public boolean isEmpty() {
for (Field field : this.getClass().getDeclaredFields()) {
try {
field.setAccessible(true);
if (field.get(this)!=null) {
return false;
}
} catch (Exception e) {
System.out.println("Exception occured in processing");
}
}
return true;
}
e.relatedTarget.data('load-url');
won't work
use dataset.loadUrl
$('#myModal').on('show.bs.modal', function (e) {
var loadurl = e.relatedTarget.dataset.loadUrl;
$(this).find('.modal-body').load(loadurl);
});
you can use ps
.
e.g. having python process with two busy threads on dual core CPU:
$ ps -p 29492 -L -o pid,tid,psr,pcpu
PID TID PSR %CPU
29492 29492 1 0.0
29492 29493 1 48.7
29492 29494 1 51.9
(PSR is CPU id the thread is currently assigned to)
you see that the threads are running on the same cpu core (because of GIL)
running the same python script in jython, we see, that the script is utilizing both cores (and there are many other service or whatever threads, which are almost idle):
$ ps -p 28671 -L -o pid,tid,psr,pcpu
PID TID PSR %CPU
28671 28671 1 0.0
28671 28672 0 4.4
28671 28673 0 0.6
28671 28674 0 0.5
28671 28675 0 2.3
28671 28676 0 0.0
28671 28677 1 0.0
28671 28678 1 0.0
28671 28679 0 4.6
28671 28680 0 4.4
28671 28681 1 0.0
28671 28682 1 0.0
28671 28721 1 0.0
28671 28729 0 88.6
28671 28730 1 88.5
you can process the output and calculate the total CPU for each CPU core.
Unfortunately, this approach does not seem to be 100% reliable, sometimes i see that in the first case, the two working threads are reported to be separated to each CPU core, or in the latter case, the two threads are reported to be on the same core..
if (!$(row).hasClass("changed")) {
// do your stuff
}
Steveha's answer was helpful to me, but omits an important point (one that I think wisty was getting at). The global keyword is not necessary if you only access but do not assign the variable in the function.
If you assign the variable without the global keyword then Python creates a new local var -- the module variable's value will now be hidden inside the function. Use the global keyword to assign the module var inside a function.
Pylint 1.3.1 under Python 2.7 enforces NOT using global if you don't assign the var.
module_var = '/dev/hello'
def readonly_access():
connect(module_var)
def readwrite_access():
global module_var
module_var = '/dev/hello2'
connect(module_var)
The SQLite documentation is a great reference and the DateAndTimeFunctions page is a good one to bookmark.
It's also helpful to remember that it's pretty easy to play with queries with the sqlite command line utility:
sqlite> select julianday(datetime('now'));
2454788.09219907
sqlite> select datetime(julianday(datetime('now')));
2008-11-17 14:13:55
This is a simple blocking technique:
var waitTill = new Date(new Date().getTime() + seconds * 1000);
while(waitTill > new Date()){}
It's blocking insofar as nothing else will happen in your script (like callbacks). But since this is a console script, maybe it is what you need!
Data
a=[0 3 0 0 7 10 3 0 1 0 7 7 1 7 4]
Do
aa=nonzeros(a)'
Result
aa=[3 7 10 3 1 7 7 1 7 4]
PHP doesn't support traditional method overloading, however one way you might be able to achieve what you want, would be to make use of the __call
magic method:
class MyClass {
public function __call($name, $args) {
switch ($name) {
case 'funcOne':
switch (count($args)) {
case 1:
return call_user_func_array(array($this, 'funcOneWithOneArg'), $args);
case 3:
return call_user_func_array(array($this, 'funcOneWithThreeArgs'), $args);
}
case 'anotherFunc':
switch (count($args)) {
case 0:
return $this->anotherFuncWithNoArgs();
case 5:
return call_user_func_array(array($this, 'anotherFuncWithMoreArgs'), $args);
}
}
}
protected function funcOneWithOneArg($a) {
}
protected function funcOneWithThreeArgs($a, $b, $c) {
}
protected function anotherFuncWithNoArgs() {
}
protected function anotherFuncWithMoreArgs($a, $b, $c, $d, $e) {
}
}
The first line of every source file of your project must be the following:
#include <stdafx.h>
Visit here to understand Precompiled Headers
I know this is a bit of an old question, but if (like me) you're using Javascript with Rhino, you can use...
try
{
java.lang.Thread.sleep(timeInMilliseconds);
}
catch (e)
{
/*
* This will happen if the sleep is woken up - you might want to check
* if enough time has passed and sleep again if not - depending on how
* important the sleep time is to you.
*/
}
Reload the current page:
F5
or
CTRL + R
Reload the current page, ignoring cached content (i.e. JavaScript files, images, etc.):
SHIFT + F5
or
CTRL + F5
or
CTRL + SHIFT + R
Just change <VirtualHost *:80>
to <VirtualHost 127.0.0.1:80>
.
Then the default DocumentRoot
will serve for all domains or IP addresses that point to your server and specified VirtualHost
will work.
You can use closures to pass parameters:
iframe.document.addEventListener('click', function(event) {clic(this.id);}, false);
However, I recommend that you use a better approach to access your frame (I can only assume that you are using the DOM0 way of accessing frame windows by their name - something that is only kept around for backwards compatibility):
document.getElementById("myFrame").contentDocument.addEventListener(...);
This doesn't directly answer your question, but here's a generic function which will create a URL that contains query string parameters. The parameters (names and values) are safely escaped for inclusion in a URL.
function buildUrl(url, parameters){
var qs = "";
for(var key in parameters) {
var value = parameters[key];
qs += encodeURIComponent(key) + "=" + encodeURIComponent(value) + "&";
}
if (qs.length > 0){
qs = qs.substring(0, qs.length-1); //chop off last "&"
url = url + "?" + qs;
}
return url;
}
// example:
var url = "http://example.com/";
var parameters = {
name: "George Washington",
dob: "17320222"
};
console.log(buildUrl(url, parameters));
// => http://www.example.com/?name=George%20Washington&dob=17320222
It reappears because your submit button reloads the page. The simplest way to prevent this behavior is to add a return false
to the onclick
like so:
<input type="submit" value="Remove DUMMY" onclick="removeDummy(); return false;" />
Try this one too:
SELECT CONVERT(CHAR(8),GETDATE(),108)
Why not try MySQL GUI Tools? It's light, and does its job well.
<?php
$val1 = rand(1,4);
$val2=rand(1,4);
if ($pars[$last0] == "reviews" && $pars[$last] > 0) {
echo widget("Bootstrap Theme - Member Profile - Read Review",'',$w[website_id],$w);
} else { ?>
<div class="w100">
<div style="background:transparent!important;" class="w100 well" id="postreview">
<?php
$_GET[user_id] = $user[user_id];
$_GET[member_id] = $_COOKIE[userid];
$_GET[subaction] = "savereview";
$_GET[ip] = $_SERVER[REMOTE_ADDR];
$_GET[httpr] = $_ENV[requesturl];
echo form("member_review","",$w[website_id],$w);?>
</div></div>
ive replaced the 'else' with '&&' so both are placed ... argh
I am currently working on this, and i have already a number of solutions. It is nice to have a high quality site, that i can use also for my convenience. Because if you do not write these things down, you will eventually forget some parts. And i can also recommend writing some basic's down if you are starting any kind of new programming/design.
So if the float functions are causing problems there is a couple of options you can try.
One is modify the div alignment in the div tag it self like so <div class="kosher" align=left>
If this does not suit you then there is another option with margin like so.
.leftdiv {
display: inline-block;
width: 40%;
float: left;
}
.rightdiv {
display: block;
margin-right: 20px;
margin-left: 45%;
}
Don't forget to remove the <div align=left>
.
In 1.0 and 2.0 you can use createElement
prop of Router
to specify how exactly to create your target element. Documentation source
function createWithDefaultProps(Component, props) {
return <Component {...props} myprop="value" />;
}
// and then
<Router createElement={createWithDefaultProps}>
...
</Router>
This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
headers);
JSONObject jsonObject = null;
try {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.exchange(
"https://url", HttpMethod.POST, entity,
String.class);
if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
try {
jsonObject = new JSONObject(responseEntity.getBody());
} catch (JSONException e) {
throw new RuntimeException("JSONException occurred");
}
}
} catch (final HttpClientErrorException httpClientErrorException) {
throw new ExternalCallBadRequestException();
} catch (HttpServerErrorException httpServerErrorException) {
throw new ExternalCallServerErrorException(httpServerErrorException);
} catch (Exception exception) {
throw new ExternalCallServerErrorException(exception);
}
ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.
Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.
Suppose your function enters data in columns A and B and you want to a custom Userform to appear if the user selects a cell in column C. One way to do this is to use the SelectionChange
event:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim clickRng As Range
Dim lastRow As Long
lastRow = Range("A1").End(xlDown).Row
Set clickRng = Range("C1:C" & lastRow) //Dynamically set cells that can be clicked based on data in column A
If Not Intersect(Target, clickRng) Is Nothing Then
MyUserForm.Show //Launch custom userform
End If
End Sub
Note that the userform will appear when a user selects any cell in Column C and you might want to populate each cell in Column C with something like "select cell to launch form" to make it obvious that the user needs to perform an action (having a button naturally suggests that it should be clicked)
If you want the simplest and tiniest way of reading an *.xlsx file in a browser then this library might do:
https://catamphetamine.github.io/read-excel-file/
<input type="file" id="input" />
import readXlsxFile from 'read-excel-file'
const input = document.getElementById('input')
input.addEventListener('change', () => {
readXlsxFile(input.files[0]).then((data) => {
// `data` is an array of rows
// each row being an array of cells.
})
})
In the example above data
is raw string data.
It can be parsed to JSON with a strict schema by passing schema
argument. See API docs for an example of that.
API docs: http://npmjs.com/package/read-excel-file
That's because your hidden fields have duplicate IDs, so jQuery only returns the first in the set. Give them classes instead, like .uid
and grab them via:
var uids = $(".uid").map(function() {
return this.value;
}).get();
Demo: http://jsfiddle.net/karim79/FtcnJ/
EDIT: say your output looks like the following (notice, IDs have changed to classes)
<fieldset><legend>John Smith</legend>
<img src='foo.jpg'/><br>
<a href="#" class="aaf">add as friend</a>
<input name="uid" type="hidden" value='<?php echo $row->uid;?>' class="uid">
</fieldset>
You can target the 'uid' relative to the clicked anchor like this:
$("a.aaf").click(function() {
alert($(this).next('.uid').val());
});
Important: do not have any duplicate IDs. They will cause problems. They are invalid, bad and you should not do it.
This is a modification to jsp's very helpful answer (https://stackoverflow.com/a/45843594/814145). I like the idea of getting not only a list of targets but also their descriptions. jsp's Makefile puts the description as the comment, which I found often will be repeated in the target's description echo command. So instead, I extract the description from the echo command for each target.
Example Makefile:
.PHONY: all
all: build
: "same as 'make build'"
.PHONY: build
build:
@echo "Build the project"
.PHONY: clean
clean:
@echo "Clean the project"
.PHONY: help
help:
@echo -n "Common make targets"
@echo ":"
@cat Makefile | sed -n '/^\.PHONY: / h; /\(^\t@*echo\|^\t:\)/ {H; x; /PHONY/ s/.PHONY: \(.*\)\n.*"\(.*\)"/ make \1\t\2/p; d; x}'| sort -k2,2 |expand -t 20
Output of make help
:
$ make help
Common make targets:
make all same as 'make build'
make build Build the project
make clean Clean the project
make help Common make targets
Notes:
echo
or :
command as the first command of the recipe. :
means "do nothing". I use it here for those targets that no echo is needed, such as all
target above.help
target to add the ":" in the make help
output.Recently I experienced a problem using optimization with g++
. The problem was related to a PCI card, where the registers (for command and data) were repreented by a memory address. My driver mapped the physical address to a pointer within the application and gave it to the called process, which worked with it like this:
unsigned int * pciMemory;
askDriverForMapping( & pciMemory );
...
pciMemory[ 0 ] = someCommandIdx;
pciMemory[ 0 ] = someCommandLength;
for ( int i = 0; i < sizeof( someCommand ); i++ )
pciMemory[ 0 ] = someCommand[ i ];
The card didn't act as expected. When I saw the assembly I understood that the compiler only wrote someCommand[ the last ]
into pciMemory
, omitting all preceding writes.
In conclusion: be accurate and attentive with optimization.
This is just a workaround solution:
In normal cases, use the solutions that are shipped with git. These work great in most cases. Force to LF if you share the development on Windows and Unix based systems by setting .gitattributes.
In my case there were >10 programmers developing a project in Windows. This project was checked in with CRLF and there was no option to force to LF.
Some settings were internally written on my machine without any influence on the LF format; thus some files were globally changed to LF on each small file change.
My solution:
Windows-Machines: Let everything as it is. Care about nothing, since you are a default windows 'lone wolf' developer and you have to handle like this: "There is no other system in the wide world, is it?"
Unix-Machines
Add following lines to a config's [alias]
section. This command lists all changed (i.e. modified/new) files:
lc = "!f() { git status --porcelain \
| egrep -r \"^(\?| ).\*\\(.[a-zA-Z])*\" \
| cut -c 4- ; }; f "
Convert all those changed files into dos format:
unix2dos $(git lc)
Optionally ...
Create a git hook for this action to automate this process
Use params and include it and modify the grep
function to match only particular filenames, e.g.:
... | egrep -r "^(\?| ).*\.(txt|conf)" | ...
Feel free to make it even more convenient by using an additional shortcut:
c2dos = "!f() { unix2dos $(git lc) ; }; f "
... and fire the converted stuff by typing
git c2dos
$page = (isset($_GET['p']) ? (int)$_GET['p'] : 1);
if ($page > 0)
{
...
}
Try casting and checking if it's a number initially.
If you're looking to do this for a userscript, I wrote this: http://userscripts.org/scripts/show/123588
It'll let you include jQuery, plus UI and any plugins you'd like. I'm using it on a site that has 1.5.1 and no UI; this script gives me 1.7.1 instead, plus UI, and no conflicts in Chrome or FF. I've not tested Opera myself, but others have told me it's worked there for them as well, so this ought to be pretty well a complete cross-browser userscript solution, if that's what you need to do this for.
Declare object of EditText on top of class:
EditText myEditText;
Find EditText in onCreate Function and setOnFocusChangeListener of EditText:
myEditText = findViewById(R.id.yourEditTextNameInxml);
myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
Toast.makeText(this, "Focus Lose", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Get Focus", Toast.LENGTH_SHORT).show();
}
}
});
It works fine.
To fix this below error, I did enough research, not got any great solution, I prepared this script and it is working fine, thought to share to the public and make use of it and save there time.
CreateProcess error=206, The filename or extension is too long
If you are using the Gradle build tool, and the executable file is placed in build/libs directory of your application.
run.sh
-> create this file in the root directory of your project, and copy below script in it, then go to git bash and type run.sh then enter. Hope this helps!
#!/bin/bash
dir_name=`pwd`
if [ $# == 1 ] && [ $1 == "debug" ]
then
port=$RANDOM
quit=0
echo "Finding free port for debugging"
while [ "$quit" -ne 1 ]; do
netstat -anp | grep $port >> /dev/null
if [ $? -gt 0 ]; then
quit=1
else
port=`expr $port + 1`
fi
done
echo "Starting in Debug Mode on "$port
gradle clean bootjar
jar_name="build/libs/"`ls -l ./build/libs/|grep jar|grep -v grep|awk '{print $NF}'`
#java -jar -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=$port $jar_name
elif [ $# == 1 ] && [ $1 == 'help' ]
then
echo "please use this commands"
echo "------------------------"
echo "Start in Debug Mode: sh run.sh debug"
echo "Start in Run Mode: sh run.sh"
echo "------------------------"
else
gradle clean bootjar
word_count=`ls -l ./build/libs/|grep jar|grep -v grep|wc -w`
jar_name=`ls -l ./build/libs/|grep jar|grep -v grep|awk '{print $NF}'`
jar_path=build/libs/$jar_name
echo $jar_name
#java -jar $jar_path
fi
Hope this helps!!
Instead of JSONObject , you can use ObjectMapper to convert java object to json string
ObjectMapper mapper = new ObjectMapper();
String requestBean = mapper.writeValueAsString(yourObject);
At first I thought that this would work:
select DBMS_Random.Value(1,9) output
from ...
However, this does not generate an even distribution of output values:
select output,
count(*)
from (
select round(dbms_random.value(1,9)) output
from dual
connect by level <= 1000000)
group by output
order by 1
1 62423
2 125302
3 125038
4 125207
5 124892
6 124235
7 124832
8 125514
9 62557
The reasons are pretty obvious I think.
I'd suggest using something like:
floor(dbms_random.value(1,10))
Hence:
select output,
count(*)
from (
select floor(dbms_random.value(1,10)) output
from dual
connect by level <= 1000000)
group by output
order by 1
1 111038
2 110912
3 111155
4 111125
5 111084
6 111328
7 110873
8 111532
9 110953
Try this one
.responsive-container{
display:table;
}
.img-container{
display:table-cell;
vertical-align: middle;
}
I got same issue while using cygwin to install nvm
In fact, the target directory where empty but the git
binary used was the one from windows (and not git
from cygwin git package
).
After installing cygwin git package
, the git clone
from nvm
install was ok!
You can achieve this using XML notation and the MethodInvokingFactoryBean
. For an example look here.
private static StaticBean staticBean;
public void setStaticBean(StaticBean staticBean) {
StaticBean.staticBean = staticBean;
}
You should aim to use spring injection where possible as this is the recommended approach but this is not always possible as I'm sure you can imagine as not everything can be pulled from the spring container or you maybe dealing with legacy systems.
Note testing can also be more difficult with this approach.
You may want to double check the authorized_keys file permissions:
$ chmod 600 ~/.ssh/authorized_keys
Newer SSH server versions are very picky on this respect.
The solution is very simple if we consider the type of the constant value, which should be "unsigned int" instead of "int".
Instead of:
setval(0)
Use:
setval(0u)
The suffix "u" tell the compiler this is a unsigned integer. Then, no conversion would be needed, and the call will be unambiguous.
Yes, here's an example:
CREATE TABLE myTable ( col1 int, createdDate datetime DEFAULT(getdate()), updatedDate datetime DEFAULT(getdate()) )
You can INSERT into the table without indicating the createdDate and updatedDate columns:
INSERT INTO myTable (col1) VALUES (1)
Or use the keyword DEFAULT:
INSERT INTO myTable (col1, createdDate, updatedDate) VALUES (1, DEFAULT, DEFAULT)
Then create a trigger for updating the updatedDate column:
CREATE TRIGGER dbo.updateMyTable
ON dbo.myTable
FOR UPDATE
AS
BEGIN
IF NOT UPDATE(updatedDate)
UPDATE dbo.myTable SET updatedDate=GETDATE()
WHERE col1 IN (SELECT col1 FROM inserted)
END
GO
I am not sure if this a pythonic way or not but this seems simple if both lists have the same number of elements :
list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]
list_c=[(list_a[i],list_b[i]) for i in range(0,len(list_a))]
I would rather include the factory as dependencies on the controllers than inject them with their own line of code: http://jsfiddle.net/XqDxG/550/
myModule.factory('mySharedService', function($rootScope) {
return sharedService = {thing:"value"};
});
function ControllerZero($scope, mySharedService) {
$scope.thing = mySharedService.thing;
ControllerZero.$inject = ['$scope', 'mySharedService'];
A function void f() compiled by a C compiler and a function with the same name void f() compiled by a C++ compiler are not the same function. If you wrote that function in C, and then you tried to call it from C++, then the linker would look for the C++ function and not find the C function.
extern "C" tells the C++ compiler that you have a function which was compiled by the C compiler. Once you tell it that it was compiled by the C compiler, the C++ compiler will know how to call it correctly.
It also allows the C++ compiler to compile a C++ function in such a way that the C compiler can call it. That function would officially be a C function, but since it is compiled by the C++ compiler, it can use all the C++ features and has all the C++ keywords.
As you can't use android:text
I recommend you to use a normal button and use one of the compound drawables. For instance:
<Button
android:id="@+id/buttonok"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/buttonok"
android:text="OK"/>
You can put the drawable wherever you want by using: drawableTop
, drawableBottom
, drawableLeft
or drawableRight
.
UPDATE
For a button this too works pretty fine. Putting android:background
is fine!
<Button
android:id="@+id/fragment_left_menu_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button_bg"
android:text="@string/login_string" />
I just had this issue and is working perfectly.
DateTime
inherits its equals
method from AbstractInstant
. It is implemented as such
public boolean equals(Object readableInstant) { // must be to fulfil ReadableInstant contract if (this == readableInstant) { return true; } if (readableInstant instanceof ReadableInstant == false) { return false; } ReadableInstant otherInstant = (ReadableInstant) readableInstant; return getMillis() == otherInstant.getMillis() && FieldUtils.equals(getChronology(), otherInstant.getChronology()); }
Notice the last line comparing chronology. It's possible your instances' chronologies are different.
As other answers already suggested, you must have MinGW
installed. The additional part is to add the following two folders to the PATH
environment variable.
Obviously, adjust the path based on where you installed MinGW. Also, dont forget to open a new command line terminal.
What version of jQuery-UI are you using? I've tested the following with 1.6r6, 1.7 and 1.7.1 and it works:
//Set DatePicker to October 3, 2008
$('#dateselector').datepicker("setDate", new Date(2008,9,03) );
use checked
: true, false property of the checkbox.
jQuery:
if($('input[type=checkbox]').is(':checked')) {
$(this).prop('checked',true);
} else {
$(this).prop('checked',false);
}
Another solution:
(function () {
var make_rotated_text = function (text)
{
var can = document.createElement ('canvas');
can.width = 10;
can.height = 10;
var ctx=can.getContext ("2d");
ctx.font="20px Verdana";
var m = ctx.measureText(text);
can.width = 20;
can.height = m.width;
ctx.font="20px Verdana";
ctx.fillStyle = "#000000";
ctx.rotate(90 * (Math.PI / 180));
ctx.fillText (text, 0, -2);
return can;
};
var canvas = make_rotated_text ("Hellooooo :D");
var body = document.getElementsByTagName ('body')[0];
body.appendChild (canvas);
}) ();
I do absolutely admit that this is quite hackish, but it's a simple solution if you want to avoid bloating your css.
A linear search starts at the beginning of a list of values, and checks 1 by 1 in order for the result you are looking for.
A binary search starts in the middle of a sorted array, and determines which side (if any) the value you are looking for is on. That "half" of the array is then searched again in the same fashion, dividing the results in half by two each time.
This works for me. I'm using Identity 2.0, it looks like GetApplicationUser isn't there anymore.
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (!string.IsNullOrEmpty(form["FirstName"]))
{
user.FirstName = form["FirstName"];
}
if (!string.IsNullOrEmpty(form["LastName"]))
{
user.LastName = form["LastName"];
}
IdentityResult result = await UserManager.UpdateAsync(user);
In v2.0 of the Graph API, calling /me/friends
returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends
permission from each user. user_friends
is no longer included by default in every login. Each user must grant the user_friends
permission in order to appear in the response to /me/friends
. See the Facebook upgrade guide for more detailed information, or review the summary below.
The /me/friendlists
endpoint and user_friendlists
permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends
API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends
endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends
permission).
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
If you are thinking of running a server and trying to decide how many connections can be served from one machine, you may want to read about the C10k problem and the potential problems involved in serving lots of clients simultaneously.
Specify the optional selector to target what you want:
jQuery(this).parent('li').addClass('yourClass');
Or:
jQuery(this).parents('li').addClass('yourClass');
Yes. Use WindowBuilder Pro (provided by Google). It supports SWT and Swing as well with multiple layouts (Group layout, MiGLayout etc.) It's integrated out of the box with Eclipse Indigo, but you can install plugin on previous versions (3.4/3.5/3.6):
As it appears you have the values as text, and not the numeric True/False, then you can use either COUNTIF
or SUMPRODUCT
=IF(SUMPRODUCT(--(A2:D2="False")),"False","True")
=IF(COUNTIF(A3:D3,"False*"),"False","True")
If you are using GCP then you have to set workers per instance type.
Link to GCP best practices https://cloud.google.com/appengine/docs/standard/python3/runtime
A few options:
(1) Laboriously make an identity-mapping (i.e. do-nothing) dict out of your fieldnames so that csv.DictWriter can convert it back to a list and pass it to a csv.writer instance.
(2) The documentation mentions "the underlying writer
instance" ... so just use it (example at the end).
dw.writer.writerow(dw.fieldnames)
(3) Avoid the csv.Dictwriter overhead and do it yourself with csv.writer
Writing data:
w.writerow([d[k] for k in fieldnames])
or
w.writerow([d.get(k, restval) for k in fieldnames])
Instead of the extrasaction
"functionality", I'd prefer to code it myself; that way you can report ALL "extras" with the keys and values, not just the first extra key. What is a real nuisance with DictWriter is that if you've verified the keys yourself as each dict was being built, you need to remember to use extrasaction='ignore' otherwise it's going to SLOWLY (fieldnames is a list) repeat the check:
wrong_fields = [k for k in rowdict if k not in self.fieldnames]
============
>>> f = open('csvtest.csv', 'wb')
>>> import csv
>>> fns = 'foo bar zot'.split()
>>> dw = csv.DictWriter(f, fns, restval='Huh?')
# dw.writefieldnames(fns) -- no such animal
>>> dw.writerow(fns) # no such luck, it can't imagine what to do with a list
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\python26\lib\csv.py", line 144, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "C:\python26\lib\csv.py", line 141, in _dict_to_list
return [rowdict.get(key, self.restval) for key in self.fieldnames]
AttributeError: 'list' object has no attribute 'get'
>>> dir(dw)
['__doc__', '__init__', '__module__', '_dict_to_list', 'extrasaction', 'fieldnam
es', 'restval', 'writer', 'writerow', 'writerows']
# eureka
>>> dw.writer.writerow(dw.fieldnames)
>>> dw.writerow({'foo':'oof'})
>>> f.close()
>>> open('csvtest.csv', 'rb').read()
'foo,bar,zot\r\noof,Huh?,Huh?\r\n'
>>>
If you want the password prompt to go away then use key based authentication (described here).
To run commands remotely over ssh you have to give them as an argument to ssh, like the following:
root@host:~ # ssh root@www 'ps -ef | grep apache | grep -v grep | wc -l'
here is an example, where the length of the array is changed during execution of the loop
import java.util.ArrayList;
public class VariableArrayLengthLoop {
public static void main(String[] args) {
//create new ArrayList
ArrayList<String> aListFruits = new ArrayList<String>();
//add objects to ArrayList
aListFruits.add("Apple");
aListFruits.add("Banana");
aListFruits.add("Orange");
aListFruits.add("Strawberry");
//iterate ArrayList using for loop
for(int i = 0; i < aListFruits.size(); i++){
System.out.println( aListFruits.get(i) + " i = "+i );
if ( i == 2 ) {
aListFruits.add("Pineapple");
System.out.println( "added now a Fruit to the List ");
}
}
}
}
I think it's worth putting a few timings up here for some perspective.
All timings done on OS-X 10.5.8 with python2.7
John Clement's answer:
python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop
David Wolever's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop
OP's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop
Note that I'm purposefully putting the smallest item last in the list to make .index
as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.
Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).
One workaround is to just create the columns and catch the exception/error that arise if the column already exist. When adding multiple columns, add them in separate ALTER TABLE statements so that one duplicate does not prevent the others from being created.
With sqlite-net, we did something like this. It's not perfect, since we can't distinguish duplicate sqlite errors from other sqlite errors.
Dictionary<string, string> columnNameToAddColumnSql = new Dictionary<string, string>
{
{
"Column1",
"ALTER TABLE MyTable ADD COLUMN Column1 INTEGER"
},
{
"Column2",
"ALTER TABLE MyTable ADD COLUMN Column2 TEXT"
}
};
foreach (var pair in columnNameToAddColumnSql)
{
string columnName = pair.Key;
string sql = pair.Value;
try
{
this.DB.ExecuteNonQuery(sql);
}
catch (System.Data.SQLite.SQLiteException e)
{
_log.Warn(e, string.Format("Failed to create column [{0}]. Most likely it already exists, which is fine.", columnName));
}
}
The first line of a constructor is always an invocation to another constructor. You can choose between calling a constructor from the same class with "this(...)" or a constructor from the parent clas with "super(...)". If you don't include either, the compiler includes this line for you: super();
The other option in this particular case would be to type the degree symbol: °
R seems to handle it fine. Type Option-k on a Mac to get it. Not sure about other platforms.
After reviewing Microsoft's TechNet article "Azure Active Directory Cmdlets" -> section "Install the Azure AD Module", it seems that this process has been drastically simplified, thankfully.
As of 2016/06/30, in order to successfully execute the PowerShell commands Import-Module MSOnline
and Connect-MsolService
, you will need to install the following applications (64-bit only):
7.250.4556.0
(latest)msoidcli_64.msi
D077CF49077EE133523C1D3AE9A4BF437D220B16D651005BBC12F7BDAD1BF313
AdministrationConfig-en.msi
3.0
(later versions will probably work too)Windows6.1-KB2506143-x64.msu
You can either use a double backslash each time
string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";
or use the @ symbol
string foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
Go to Project-> right Click-> Select Properties -> project Facets -> modify the java version for your JDK version you are using.
Just as another option if you want to print only the key (doesn't write the .env file) you can use:
php artisan key:generate --show
matplotlib.pyplot.vlines
vs. matplotlib.pyplot.axvline
vlines
accepts 1 or more locations for x
, while axvline
permits one location.
x=37
x=[37, 38, 39]
vlines
takes ymin
and ymax
as a position on the y-axis, while axvline
takes ymin
and ymax
as a percentage of the y-axis range.
vlines
, pass a list
to ymin
and ymax
.fig, ax = plt.subplots()
, then replace plt.vlines
or plt.axvline
with ax.vlines
or ax.axvline
, respectively.import numpy as np
import matplotlib.pyplot as plt
xs = np.linspace(1, 21, 200)
plt.figure(figsize=(10, 7))
# only one line may be specified; full height
plt.axvline(x=36, color='b', label='axvline - full height')
# only one line may be specified; ymin & ymax spedified as a percentage of y-range
plt.axvline(x=36.25, ymin=0.05, ymax=0.95, color='b', label='axvline - % of full height')
# multiple lines all full height
plt.vlines(x=[37, 37.25, 37.5], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple - full height')
# multiple lines with varying ymin and ymax
plt.vlines(x=[38, 38.25, 38.5], ymin=[0, 25, 75], ymax=[200, 175, 150], colors='teal', ls='--', lw=2, label='vline_multiple - partial height')
# single vline with full ymin and ymax
plt.vlines(x=39, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single - full height')
# single vline with specific ymin and ymax
plt.vlines(x=39.25, ymin=25, ymax=150, colors='green', ls=':', lw=2, label='vline_single - partial height')
# place legend outside
plt.legend(bbox_to_anchor=(1.0, 1), loc='upper left')
plt.show()
I recently stumbled upon this great Gist that gives a working implementation of a drag sort ListView
, with no external dependencies needed.
Basically it consists on creating your custom Adapter extending ArrayAdapter
as an inner class to the activity containing your ListView
. On this adapter one then sets an onTouchListener
to your List Items that will signal the start of the drag.
In that Gist they set the listener to a specific part of the layout of the List Item (the "handle" of the item), so one does not accidentally move it by pressing any part of it. Personally, I preferred to go with an onLongClickListener
instead, but that is up to you to decide. Here an excerpt of that part:
public class MyArrayAdapter extends ArrayAdapter<String> {
private ArrayList<String> mStrings = new ArrayList<String>();
private LayoutInflater mInflater;
private int mLayout;
//constructor, clear, remove, add, insert...
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View view = convertView;
//inflate, etc...
final String string = mStrings.get(position);
holder.title.setText(string);
// Here the listener is set specifically to the handle of the layout
holder.handle.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
startDrag(string);
return true;
}
return false;
}
});
// change color on dragging item and other things...
return view;
}
}
This also involves adding an onTouchListener
to the ListView
, which checks if an item is being dragged, handles the swapping and invalidation, and stops the drag state. An excerpt of that part:
mListView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
if (!mSortable) { return false; }
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
break;
}
case MotionEvent.ACTION_MOVE: {
// get positions
int position = mListView.pointToPosition((int) event.getX(),
(int) event.getY());
if (position < 0) {
break;
}
// check if it's time to swap
if (position != mPosition) {
mPosition = position;
mAdapter.remove(mDragString);
mAdapter.insert(mDragString, mPosition);
}
return true;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_OUTSIDE: {
//stop drag state
stopDrag();
return true;
}
}
return false;
}
});
Finally, here is how the stopDrag
and startDrag
methods look like, which handle the enabling and disabling of the drag process:
public void startDrag(String string) {
mPosition = -1;
mSortable = true;
mDragString = string;
mAdapter.notifyDataSetChanged();
}
public void stopDrag() {
mPosition = -1;
mSortable = false;
mDragString = null;
mAdapter.notifyDataSetChanged();
}
Your case is an extreme one, but here is a solution for others that fits a more common scenario of wanting to style fewer than 4 borders exactly the same.
border: 1px dashed red; border-width: 1px 1px 0 1px;
that is a little shorter, and maybe easier to read than
border-top: 1px dashed red; border-right: 1px dashed red; border-left: 1px dashed red;
or
border-color: red; border-style: dashed; border-width: 1px 1px 0 1px;
Like this:
$(document).ready(function ()
{
document.title = "Hello World!";
});
Be sure to set a default-title if you want your site to be properly indexed by search-engines.
A little tip:
$(function ()
{
// this is a shorthand for the whole document-ready thing
// In my opinion, it's more readable
});
According to other answers I am adding the parallel stages scenario:
pipeline {
agent any
stages {
stage('some parallel stage') {
parallel {
stage('parallel stage 1') {
when {
expression { ENV == "something" }
}
steps {
echo 'something'
}
}
stage('parallel stage 2') {
steps {
echo 'something'
}
}
}
}
}
}
You need an instance of the class containing the non static method.
Is like when you try to invoke the non-static method startsWith
of class String
without an instance:
String.startsWith("Hello");
What you need is to have an instance and then invoke the non-static method:
String greeting = new String("Hello World");
greeting.startsWith("Hello"); // returns true
So you need to create and instance to invoke it.
Here are the steps
See following code:
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString Replace2(SqlString inputtext, SqlString filter,SqlString replacewith)
{
string str = inputtext.ToString();
try
{
string pattern = (string)filter;
string replacement = (string)replacewith;
Regex rgx = new Regex(pattern);
string result = rgx.Replace(str, replacement);
return (SqlString)result;
}
catch (Exception s)
{
return (SqlString)s.Message;
}
}
}
Deploy your CLR function
Now Test it
See following code:
create table dbo.test(dummydata varchar(255))
Go
INSERT INTO dbo.test values('P@ssw1rd'),('This 12is @test')
Go
Update dbo.test
set dummydata=dbo.Replace2(dummydata,'[0-9@]','')
select * from dbo.test
dummydata, Psswrd, This is test booom!!!!!!!!!!!!!