Have you tried explicitly declaring the version of mail.jar you want? Maven's dependency resolution should use this for dependency resolution over all other versions.
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>jruby</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<artifactId>base</artifactId>
<groupId>es.uniovi.innova</groupId>
<version>1.0.0</version>
</parent>
<dependencies>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>VERSION-#</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.liferay.portal</groupId>
<artifactId>ALL-DEPS</artifactId>
<version>1.0</version>
<scope>provided</scope>
<type>pom</type>
</dependency>
</dependencies>
</project>
Take advantage of SORT and LIMIT as you would with pagination. If you want the ith block of rows, use OFFSET.
SELECT val FROM big_table
where val = someval
ORDER BY id DESC
LIMIT n;
In response to Nir: The sort operation is not necessarily penalized, this depends on what the query planner does. Since this use case is crucial for pagination performance, there are some optimizations (see link above). This is true in postgres as well "ORDER BY ... LIMIT can be done without sorting " E.7.1. Last bullet
explain extended select id from items where val = 48 order by id desc limit 10;
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
| 1 | SIMPLE | items | const | PRIMARY | PRIMARY | 4 | const | 1 | Using index |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
Adding to Dan's answer above: if you supply the int() function with a hex string, you will have to specify the base as 16 or it will not think you gave it a valid value. Specifying base 16 is unnecessary for hex numbers not contained in strings.
print int(0xdeadbeef) # valid
myHex = "0xdeadbeef"
print int(myHex) # invalid, raises ValueError
print int(myHex , 16) # valid
You can use Nullable{T}
GetValueOrDefault()
method. This will return false if null.
bool? nullableBool = null;
bool actualBool = nullableBool.GetValueOrDefault();
This is the default working setup https://www.youtube.com/watch?v=XiD7JTCBdpI
Use Connection Method: standard TCP/IP over ssh
Then ssh hostname: 127.0.0.1:2222
SSH Username: vagrant password vagrant
MySQL Hostname: localhost
Username: homestead password:secret
Here's a simple class that can display SVG images in a UIView
import UIKit
public class SVGImageView: UIView {
private let webView = UIWebView()
public init() {
super.init(frame: .zero)
webView.delegate = self
webView.scrollView.isScrollEnabled = false
webView.contentMode = .scaleAspectFit
webView.backgroundColor = .clear
addSubview(webView)
webView.snp.makeConstraints { make in
make.edges.equalTo(self)
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
webView.stopLoading()
}
public func load(url: String) {
webView.stopLoading()
if let url = URL(string: fullUrl) {
webView.loadRequest(URLRequest(url: url))
}
}
}
extension SVGImageView: UIWebViewDelegate {
public func webViewDidFinishLoad(_ webView: UIWebView) {
let scaleFactor = webView.bounds.size.width / webView.scrollView.contentSize.width
if scaleFactor <= 0 {
return
}
webView.scrollView.minimumZoomScale = scaleFactor
webView.scrollView.maximumZoomScale = scaleFactor
webView.scrollView.zoomScale = scaleFactor
}
}
Normally yes, .gitignore
is useful for everyone who wants to work with the repository. On occasion you'll want to ignore more private things (maybe you often create LOG
or something. In those cases you probably don't want to force that on anyone else.
What worked for me was,
chmod -R 0777 /opt/lampp/htdocs/
You may use this regex with multiple lookahead assertions (conditions):
^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$
This regex will enforce these rules:
(?=.*?[A-Z])
(?=.*?[a-z])
(?=.*?[0-9])
(?=.*?[#?!@$%^&*-])
.{8,}
(with the anchors)The following will work perfectly:
SELECT DISTINCT table.from AS a FROM table
There is no solution that works for all use cases. If you use the $request->get('_route') method, or its variants, it will return '_internal' for cases where forwarding took place.
If you need a solution that works even with forwarding, you have to use the new RequestStack service, that arrived in 2.4, but this will break ESI support:
$requestStack = $container->get('request_stack');
$masterRequest = $requestStack->getMasterRequest(); // this is the call that breaks ESI
if ($masterRequest) {
echo $masterRequest->attributes->get('_route');
}
You can make a twig extension out of this if you need it in templates.
Simple solution: add this header to the response:
Cache-control: no-store
Why this works is clearly explained at this authoritative page: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
It also explains why no-cache
does not work.
Other answers do not work because:
Caching.delete
is about a new cache that you may create for off-line work, see: https://web.dev/cache-api-quick-guide/
Fragments using a # in the URL do not work because the # tells the browser to not send a request to the server.
A cache-buster with a random part added to the url works, but will also fill the browser cache. In my app, I wanted to download a 5 MB picture every few seconds from a web cam. It will take just an hour or less to completely freeze your pc. I still don't know why the browser cache is not limited to a reasonable max, but this is definitely a disadvantage.
CREATE TABLE target_table SELECT * FROM source_table;
It just create a new table with same structure as of source table and also copy all rows from source_table into target_table.
CREATE TABLE target_table SELECT * FROM source_table WHERE condition;
If you need some rows to be copied into target_table, then apply a condition inside where clause
I present you with the cleanest way ever, in the form of the world's smallest jquery plugin:
jQuery.fn.reverse = [].reverse;
Usage:
$('jquery-selectors-go-here').reverse().each(function () {
//business as usual goes here
});
-All credit to Michael Geary in his post here: http://www.mail-archive.com/[email protected]/msg04261.html
In case it's useful, here's a C++ version of the Java snippet posted by Ribo:
struct decompressXML
{
// decompressXML -- Parse the 'compressed' binary form of Android XML docs
// such as for AndroidManifest.xml in .apk files
enum
{
endDocTag = 0x00100101,
startTag = 0x00100102,
endTag = 0x00100103
};
decompressXML(const BYTE* xml, int cb) {
// Compressed XML file/bytes starts with 24x bytes of data,
// 9 32 bit words in little endian order (LSB first):
// 0th word is 03 00 08 00
// 3rd word SEEMS TO BE: Offset at then of StringTable
// 4th word is: Number of strings in string table
// WARNING: Sometime I indiscriminently display or refer to word in
// little endian storage format, or in integer format (ie MSB first).
int numbStrings = LEW(xml, cb, 4*4);
// StringIndexTable starts at offset 24x, an array of 32 bit LE offsets
// of the length/string data in the StringTable.
int sitOff = 0x24; // Offset of start of StringIndexTable
// StringTable, each string is represented with a 16 bit little endian
// character count, followed by that number of 16 bit (LE) (Unicode) chars.
int stOff = sitOff + numbStrings*4; // StringTable follows StrIndexTable
// XMLTags, The XML tag tree starts after some unknown content after the
// StringTable. There is some unknown data after the StringTable, scan
// forward from this point to the flag for the start of an XML start tag.
int xmlTagOff = LEW(xml, cb, 3*4); // Start from the offset in the 3rd word.
// Scan forward until we find the bytes: 0x02011000(x00100102 in normal int)
for (int ii=xmlTagOff; ii<cb-4; ii+=4) {
if (LEW(xml, cb, ii) == startTag) {
xmlTagOff = ii; break;
}
} // end of hack, scanning for start of first start tag
// XML tags and attributes:
// Every XML start and end tag consists of 6 32 bit words:
// 0th word: 02011000 for startTag and 03011000 for endTag
// 1st word: a flag?, like 38000000
// 2nd word: Line of where this tag appeared in the original source file
// 3rd word: FFFFFFFF ??
// 4th word: StringIndex of NameSpace name, or FFFFFFFF for default NS
// 5th word: StringIndex of Element Name
// (Note: 01011000 in 0th word means end of XML document, endDocTag)
// Start tags (not end tags) contain 3 more words:
// 6th word: 14001400 meaning??
// 7th word: Number of Attributes that follow this tag(follow word 8th)
// 8th word: 00000000 meaning??
// Attributes consist of 5 words:
// 0th word: StringIndex of Attribute Name's Namespace, or FFFFFFFF
// 1st word: StringIndex of Attribute Name
// 2nd word: StringIndex of Attribute Value, or FFFFFFF if ResourceId used
// 3rd word: Flags?
// 4th word: str ind of attr value again, or ResourceId of value
// TMP, dump string table to tr for debugging
//tr.addSelect("strings", null);
//for (int ii=0; ii<numbStrings; ii++) {
// // Length of string starts at StringTable plus offset in StrIndTable
// String str = compXmlString(xml, sitOff, stOff, ii);
// tr.add(String.valueOf(ii), str);
//}
//tr.parent();
// Step through the XML tree element tags and attributes
int off = xmlTagOff;
int indent = 0;
int startTagLineNo = -2;
while (off < cb) {
int tag0 = LEW(xml, cb, off);
//int tag1 = LEW(xml, off+1*4);
int lineNo = LEW(xml, cb, off+2*4);
//int tag3 = LEW(xml, off+3*4);
int nameNsSi = LEW(xml, cb, off+4*4);
int nameSi = LEW(xml, cb, off+5*4);
if (tag0 == startTag) { // XML START TAG
int tag6 = LEW(xml, cb, off+6*4); // Expected to be 14001400
int numbAttrs = LEW(xml, cb, off+7*4); // Number of Attributes to follow
//int tag8 = LEW(xml, off+8*4); // Expected to be 00000000
off += 9*4; // Skip over 6+3 words of startTag data
std::string name = compXmlString(xml, cb, sitOff, stOff, nameSi);
//tr.addSelect(name, null);
startTagLineNo = lineNo;
// Look for the Attributes
std::string sb;
for (int ii=0; ii<numbAttrs; ii++) {
int attrNameNsSi = LEW(xml, cb, off); // AttrName Namespace Str Ind, or FFFFFFFF
int attrNameSi = LEW(xml, cb, off+1*4); // AttrName String Index
int attrValueSi = LEW(xml, cb, off+2*4); // AttrValue Str Ind, or FFFFFFFF
int attrFlags = LEW(xml, cb, off+3*4);
int attrResId = LEW(xml, cb, off+4*4); // AttrValue ResourceId or dup AttrValue StrInd
off += 5*4; // Skip over the 5 words of an attribute
std::string attrName = compXmlString(xml, cb, sitOff, stOff, attrNameSi);
std::string attrValue = attrValueSi!=-1
? compXmlString(xml, cb, sitOff, stOff, attrValueSi)
: "resourceID 0x"+toHexString(attrResId);
sb.append(" "+attrName+"=\""+attrValue+"\"");
//tr.add(attrName, attrValue);
}
prtIndent(indent, "<"+name+sb+">");
indent++;
} else if (tag0 == endTag) { // XML END TAG
indent--;
off += 6*4; // Skip over 6 words of endTag data
std::string name = compXmlString(xml, cb, sitOff, stOff, nameSi);
prtIndent(indent, "</"+name+"> (line "+toIntString(startTagLineNo)+"-"+toIntString(lineNo)+")");
//tr.parent(); // Step back up the NobTree
} else if (tag0 == endDocTag) { // END OF XML DOC TAG
break;
} else {
prt(" Unrecognized tag code '"+toHexString(tag0)
+"' at offset "+toIntString(off));
break;
}
} // end of while loop scanning tags and attributes of XML tree
prt(" end at offset "+off);
} // end of decompressXML
std::string compXmlString(const BYTE* xml, int cb, int sitOff, int stOff, int strInd) {
if (strInd < 0) return std::string("");
int strOff = stOff + LEW(xml, cb, sitOff+strInd*4);
return compXmlStringAt(xml, cb, strOff);
}
void prt(std::string str)
{
printf("%s", str.c_str());
}
void prtIndent(int indent, std::string str) {
char spaces[46];
memset(spaces, ' ', sizeof(spaces));
spaces[min(indent*2, sizeof(spaces) - 1)] = 0;
prt(spaces);
prt(str);
prt("\n");
}
// compXmlStringAt -- Return the string stored in StringTable format at
// offset strOff. This offset points to the 16 bit string length, which
// is followed by that number of 16 bit (Unicode) chars.
std::string compXmlStringAt(const BYTE* arr, int cb, int strOff) {
if (cb < strOff + 2) return std::string("");
int strLen = arr[strOff+1]<<8&0xff00 | arr[strOff]&0xff;
char* chars = new char[strLen + 1];
chars[strLen] = 0;
for (int ii=0; ii<strLen; ii++) {
if (cb < strOff + 2 + ii * 2)
{
chars[ii] = 0;
break;
}
chars[ii] = arr[strOff+2+ii*2];
}
std::string str(chars);
free(chars);
return str;
} // end of compXmlStringAt
// LEW -- Return value of a Little Endian 32 bit word from the byte array
// at offset off.
int LEW(const BYTE* arr, int cb, int off) {
return (cb > off + 3) ? ( arr[off+3]<<24&0xff000000 | arr[off+2]<<16&0xff0000
| arr[off+1]<<8&0xff00 | arr[off]&0xFF ) : 0;
} // end of LEW
std::string toHexString(DWORD attrResId)
{
char ch[20];
sprintf_s(ch, 20, "%lx", attrResId);
return std::string(ch);
}
std::string toIntString(int i)
{
char ch[20];
sprintf_s(ch, 20, "%ld", i);
return std::string(ch);
}
};
In my case I was running under a different user than the one I was expecting.
I had 'DRIVER={SQL Server};SERVER=...;DATABASE=...;Trusted_Connection=false;User Id=XXX;Password=YYY'
as the connection string I passed to pypyodbc.connect()
, but the connection was still using the credentials of the Windows user that ran the script (I verified this using the SQL Server Profiler and by trying an invalid uid/password combination - which didn't result in an expected error).
I decided not to dig into this further, since switching to this better way of connecting fixed the issue:
conn = pypyodbc.connect(driver='{SQL Server}', server='servername', database='dbname', uid='userName', pwd='Password')
Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.
Between matplotlib+pylab and NumPy I don't think there's much actual difference between Matlab and python other than cultural inertia as suggested by @Adam Bellaire.
I've used xcode-select --install
given in the accepted answer in previous major releases.
I've just upgraded to OS X 10.15 Catalina and run the Software Update tool from preferences again after the OS upgrade completed. The Xcode utilities update was available there, which also sorted the issue using git which had just output
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)
You fiddle already does the job ... maybe you try to get the string before the double colon? (you really should edit your question) Then the code would go like this:
str.substring(0, str.indexOf(":"));
Where 'str' represents the variable with your string inside.
Click here for JSFiddle Example
Javascript
var input_string = document.getElementById('my-input').innerText;
var output_element = document.getElementById('my-output');
var left_text = input_string.substring(0, input_string.indexOf(":"));
output_element.innerText = left_text;
Html
<p>
<h5>Input:</h5>
<strong id="my-input">Left Text:Right Text</strong>
<h5>Output:</h5>
<strong id="my-output">XXX</strong>
</p>
CSS
body { font-family: Calibri, sans-serif; color:#555; }
h5 { margin-bottom: 0.8em; }
strong {
width:90%;
padding: 0.5em 1em;
background-color: cyan;
}
#my-output { background-color: gold; }
Actually, the jQuery documentation has a more simple approach than the chained examples shown above (although they'll work just fine):
$("#myElement").unbind('mouseenter mouseleave');
As of jQuery 1.7, you are also able use $.on()
and $.off()
for event binding, so to unbind the hover event, you would use the simpler and tidier:
$('#myElement').off('hover');
The pseudo-event-name "hover" is used as a shorthand for "mouseenter mouseleave" but was handled differently in earlier jQuery versions; requiring you to expressly remove each of the literal event names. Using $.off()
now allows you to drop both mouse events using the same shorthand.
Edit 2016:
Still a popular question so it's worth drawing attention to @Dennis98's point in the comments below that in jQuery 1.9+, the "hover" event was deprecated in favour of the standard "mouseenter mouseleave" calls. So your event binding declaration should now look like this:
$('#myElement').off('mouseenter mouseleave');
I solved this problem by enabling WCF Services
Programs and Features > NET Framework 4.5 Services > WCF Services> HTTP Activation node
But you have to admit it guys this ENTIRE IIS setup configure/guess/trial and see/try this/try that spends 4 or 5 of our days trying to find a solution around approach IS A COMPLETE AND UTTER JOKE.
SURELY, 'IIS' IS THE BIGGEST CONFIDENCE TRICK EVER PLAYED ON MANKIND TO DATE
This is an old post but I was looking for an answer and I found this: https://gifs.com. Just upload the video, then it creates a gif we can add easily in a github markdown. I tried it, the quality of the gif is a good one.
git branch
with no arguments displays the current branch marked with an asterisk in front of it:
user@host:~/gittest$ git branch
* master
someotherbranch
In order to not have to type this all the time, I can recommend git prompt:
https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh
In the AIX box how I can see that I am using master or inside a particular branch. What changes inside .git that drives which branch I am on?
Git stores the HEAD
in the file .git/HEAD
. If you're on the master
branch, it could look like this:
$ cat .git/HEAD
ref: refs/heads/master
A submodule is nothing but a clone of a git repo within another repo with some extra meta data (gitlink tree entry, .gitmodules file )
$ cd your_submodule
$ git checkout master
<hack,edit>
$ git commit -a -m "commit in submodule"
$ git push
$ cd ..
$ git add your_submodule
$ git commit -m "Updated submodule"
Pragma
is the HTTP/1.0 implementation and cache-control
is the HTTP/1.1 implementation of the same concept. They both are meant to prevent the client from caching the response. Older clients may not support HTTP/1.1 which is why that header is still in use.
The only property corresponding in WPF to the
Winforms property: TextBox.Multiline = true
is the WPF property: TextBox.AcceptsReturn = true
.
<TextBox AcceptsReturn="True" ...... />
All other settings, such as VerticalAlignement
, WordWrap
etc., only control how the TextBox interacts in the UI but do not affect the Multiline
behaviour.
This might be a better answer copied from this question. Please try it and give opinion here. Please vote up if found useful. Thank you.
<script type="text/javascript">
function generate_excel(tableid) {
var table= document.getElementById(tableid);
var html = table.outerHTML;
window.open('data:application/vnd.ms-excel;base64,' + base64_encode(html));
}
function base64_encode (data) {
// http://kevin.vanzonneveld.net
// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Bayron Guevara
// + improved by: Thunder.m
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Pellentesque Malesuada
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Rafal Kukawski (http://kukawski.pl)
// * example 1: base64_encode('Kevin van Zonneveld');
// * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
// mozilla has this native
// - but breaks in 2.0.0.12!
//if (typeof this.window['btoa'] == 'function') {
// return btoa(data);
//}
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
enc = "",
tmp_arr = [];
if (!data) {
return data;
}
do { // pack three octets into four hexets
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
var r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
}
</script>
In Powershell, you'll need to import the active directory module, then use the get-adgroupmember, and then measure-object. For example, to get the number of users belonging to the group "domain users", do the following:
Import-Module activedirecotry
Get-ADGroupMember "domain users" | Measure-Object
When entering the group name after "Get-ADGroupMember", if the name is a single string with no spaces, then no quotes are necessary. If the group name has spaces in it, use the quotes around it.
The output will look something like:
Count : 12345
Average :
Sum :
Maximum :
Minimum :
Property :
Note - importing the active directory module may be redundant if you're already using PowerShell for other AD admin tasks.
I was using some buttons with some events, converted image file coming from server. Loading normal data wasn't working for me, converting into Base64 working just fine.
String unencodedHtml ="<html><body>'%28' is the code for '('</body></html>";
tring encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(), Base64.NO_PADDING);
webView.loadData(encodedHtml, "text/html", "base64");
Find details on WebView
Consider changing your markup to this:
<span id="someId">onlineff</span>
Then you can use this script:
var x = document.getElementById('someId');
x.style.color = '#00FF00';
see it here: http://jsfiddle.net/2ANmM/
Try this:
git rev-parse --short HEAD
The command git rev-parse
can do a remarkable number of different things, so you'd need to go through the documentation very carefully to spot that though.
If you bind events to the onmouseover and onmouseout events in Jquery, you can then trigger that effect using mouseenter().
What are you trying to accomplish?
Also, I noticed one more difference between .load and .ready. I am opening a child window and I am performing some work when child window opens. .load is called only first time when I open the window and if I don't close the window then .load will not be called again. however, .ready is called every time irrespective of close the child window or not.
The database must have a name (example DB1), try this one:
OracleConnection con = new OracleConnection("data source=DB1;user id=fastecit;password=fastecit");
In case the TNS is not defined you can also try this one:
OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DB1)));
User Id=fastecit;Password=fastecit");
I use a percentage method to achieve
border: 3px solid rgb(1, 1, 1);
border-top-left-radius: 100% 200%;
border-top-right-radius: 100% 200%;
Just wanted to add to an old thread to hopefully aid other people. I needed programmatically add a cert to the firefox database using a GPO, this was how I did it for Windows
1, First download and unzip the precompiled firefox NSS nss-3.13.5-nspr-4.9.1-compiled-x86.zip
2, Add the cert manually to firefox Options-->Advanced--Certificates-->Authorities-->Import
3, from the downloaded NSS package, run
certutil -L -d c:\users\[username]\appdata\roaming\mozilla\firefox\[profile].default
4, The above query will show you the certificate name and Trust Attributes e.g.
my company Ltd CT,C,C
5, Delete the certificate in step 2. Options-->Advanced--Certificates-->Authorities-->Delete
6, Create a powershell script using the information from step 4 as follows. This script will get the users profile path and add the certificate. This only works if the user has one firefox profile (need somehow to retrieve the users firefox folder profile name)
#Script adds Radius Certificate to independent Firefox certificate store since the browser does not use the Windows built in certificate store
#Get Firefox profile cert8.db file from users windows profile path
$ProfilePath = "C:\Users\" + $env:username + "\AppData\Roaming\Mozilla\Firefox\Profiles\"
$ProfilePath = $ProfilePath + (Get-ChildItem $ProfilePath | ForEach-Object { $_.Name }).ToString()
#Update firefox cert8.db file with Radius Certificate
certutil -A -n "UK my company" -t "CT,C,C" -i CertNameToAdd.crt -d $ProfilePath
7, Create GPO as a User Configuration to run the PowerShell script
Hope that helps save someone time
This should be enough:
.nav.navbar-nav li a:hover {
color: red;
}
None of the above worked for me on Ubuntu 12.04 LTS (Precise Pangolin), and here's how I fixed it in the end:
Download ez_setup.py from download setuptools (see "Installation Instructions" section) then:
$ sudo python ez_setup.py
I hope it saves someone some time.
http://site.mockito.org/mockito/docs/1.10.19/org/mockito/Matchers.html
anyObject()
should fit your needs.
Also, you can always consider implementing hashCode()
and equals()
for the Bazoo
class. This would make your code example work the way you want.
This error just means that myapp.views.home
is not something that can be called, like a function. It is a string in fact. While your solution works in django 1.9, nevertheless it throws a warning saying this will deprecate from version 1.10 onwards, which is exactly what has happened. The previous solution by @Alasdair imports the necessary view functions into the script through either
from myapp import views as myapp_views
or
from myapp.views import home, contact
This is an interesting question and since it isn't explained very explicitly in the documentation I'll answer this by going through the sourcecode of mod_rewrite; demonstrating a big benefit of open-source.
In the top section you'll quickly spot the defines used to name these flags:
#define CONDFLAG_NONE 1<<0
#define CONDFLAG_NOCASE 1<<1
#define CONDFLAG_NOTMATCH 1<<2
#define CONDFLAG_ORNEXT 1<<3
#define CONDFLAG_NOVARY 1<<4
and searching for CONDFLAG_ORNEXT confirms that it is used based on the existence of the [OR] flag:
else if ( strcasecmp(key, "ornext") == 0
|| strcasecmp(key, "OR") == 0 ) {
cfg->flags |= CONDFLAG_ORNEXT;
}
The next occurrence of the flag is the actual implementation where you'll find the loop that goes through all the RewriteConditions a RewriteRule has, and what it basically does is (stripped, comments added for clarity):
# loop through all Conditions that precede this Rule
for (i = 0; i < rewriteconds->nelts; ++i) {
rewritecond_entry *c = &conds[i];
# execute the current Condition, see if it matches
rc = apply_rewrite_cond(c, ctx);
# does this Condition have an 'OR' flag?
if (c->flags & CONDFLAG_ORNEXT) {
if (!rc) {
/* One condition is false, but another can be still true. */
continue;
}
else {
/* skip the rest of the chained OR conditions */
while ( i < rewriteconds->nelts
&& c->flags & CONDFLAG_ORNEXT) {
c = &conds[++i];
}
}
}
else if (!rc) {
return 0;
}
}
You should be able to interpret this; it means that OR has a higher precedence, and your example indeed leads to if ( (A OR B) AND (C OR D) )
. If you would, for example, have these Conditions:
RewriteCond A [or]
RewriteCond B [or]
RewriteCond C
RewriteCond D
it would be interpreted as if ( (A OR B OR C) and D )
.
To add new ViewController
once you have have an existing ViewController
, follow below step:
Click on background of Main.storyboard
.
Search and select ViewController
from object library at the
utility window.
Drag and drop it in background to create a new ViewController
.
by making date picker input disabled achieve this but if you want to submit form data then its a problem.
so after lot of juggling this seems to me a perfect solution
1.make your HTML input readonly on some condition.
<input class="form-control date-picker" size="16" data-date-format="dd/mm/yyyy"
th:autocomplete="off"
th:name="birthDate" th:id="birthDate"
type="text" placeholder="dd/mm/jjjj"
th:value="*{#dates.format(birthDate,'dd/MM/yyyy')}"
th:readonly="${client?.isDisableForAoicStatus()}"/>
2. in your js in ready function check for readonly attribute.
$(document).ready(function (e) {
if( $(".date-picker").attr('readonly') == 'readonly') {
$("#birthDate").removeClass('date-picker');
}
});
this will stop the calendar pop up invoking when you click on the readonly field.also this will not make any problem in submit data. But if you make the field disable this will not allow you to submit value.
I presume you're looking to strip spaces from the beginning and/or end of the string (rather than removing all spaces?
If that's the case, you'll need a regex like this:
mystring = mystring.replace(/(^\s+|\s+$)/g,' ');
This will remove all spaces from the beginning or end of the string. If you only want to trim spaces from the end, then the regex would look like this instead:
mystring = mystring.replace(/\s+$/g,' ');
Hope that helps.
Check your server config file /etc/mysql/my.cnf
- verify bind_address
is not set to 127.0.0.1
. Set it to 0.0.0.0
or comment it out then restart server with:
sudo service mysql restart
There are several possibilities (note that the those long values aren't the same as the Unix epoch.
For your example (to reverse ToFileTime()
) just use DateTime.FromFileTime(t)
.
I believe I have a valid use case for using typeid(), the same way it is valid to use sizeof(). For a template function, I need to special case the code based on the template variable, so that I offer maximum functionality and flexibility.
It is much more compact and maintainable than using polymorphism, to create one instance of the function for each type supported. Even in that case I might use this trick to write the body of the function only once:
Note that because the code uses templates, the switch statement below should resolve statically into only one code block, optimizing away all the false cases, AFAIK.
Consider this example, where we may need to handle a conversion if T is one type vs another. I use it for class specialization to access hardware where the hardware will use either myClassA or myClassB type. On a mismatch, I need to spend time converting the data.
switch ((typeid(T)) {
case typeid(myClassA):
// handle that case
break;
case typeid(myClassB):
// handle that case
break;
case typeid(uint32_t):
// handle that case
break;
default:
// handle that case
}
I have just experienced this issue in one of my MySQL db's and I looked at the phpMyAdmin answer here. However the best way I fixed it in phpMyAdmin was in the affected table, drop the id column and make a fresh/new id column (adding A-I -autoincrement-). This restored my table id correctly-simples! Hope that helps (no MySQL code needed-I hope to learn to use that but later!) anyone else with this problem.
For Laravel >=6
composer require laravel/ui
php artisan ui vue --auth
php artisan migrate
Reference : Laravel Documentation for authentication
it looks you are not using Laravel 5.2, these are the available make commands in L5.2 and you are missing more than just the make:auth command
make:auth Scaffold basic login and registration views and routes
make:console Create a new Artisan command
make:controller Create a new controller class
make:entity Create a new entity.
make:event Create a new event class
make:job Create a new job class
make:listener Create a new event listener class
make:middleware Create a new middleware class
make:migration Create a new migration file
make:model Create a new Eloquent model class
make:policy Create a new policy class
make:presenter Create a new presenter.
make:provider Create a new service provider class
make:repository Create a new repository.
make:request Create a new form request class
make:seeder Create a new seeder class
make:test Create a new test class
make:transformer Create a new transformer.
Be sure you have this dependency in your composer.json file
"laravel/framework": "5.2.*",
Then run
composer update
You can override the IIS default document setting using the web.config
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="DefaultPageToBeSet.aspx" />
</files>
</defaultDocument>
</system.webServer>
Or using the IIS, refer the link for reference http://www.iis.net/configreference/system.webserver/defaultdocument
You can't - globally, i.e. for every python program. And this is a good thing - Python is great for scripting (automating stuff), and scripts should be able to run without any user interaction at all.
However, you can always ask for input at the end of your program, effectively keeping the program alive until you press return. Use input("prompt: ")
in Python 3 (or raw_input("promt: ")
in Python 2). Or get used to running your programs from the command line (i.e. python mine.py
), the program will exit but its output remains visible.
I use https://github.com/yabawock/bootstrap-sass-rails
Which is pretty much straight forward install, fast gem updates and followups and quick fixes in case is needed.
Setup IIS on the network server and change the path to http://server/path/to/file.txt
EDIT: Make sure you enable directory browsing in IIS
lines=[]
with open('file') as file:
lines.append(file.readline())
From https://system.data.sqlite.org:
System.Data.SQLite is an ADO.NET adapter for SQLite.
System.Data.SQLite was started by Robert Simpson. Robert still has commit privileges on this repository but is no longer an active contributor. Development and maintenance work is now mostly performed by the SQLite Development Team. The SQLite team is committed to supporting System.Data.SQLite long-term.
"System.Data.SQLite is the original SQLite database engine and a complete ADO.NET 2.0 provider all rolled into a single mixed mode assembly. It is a complete drop-in replacement for the original sqlite3.dll (you can even rename it to sqlite3.dll). Unlike normal mixed assemblies, it has no linker dependency on the .NET runtime so it can be distributed independently of .NET."
It even supports Mono.
Mine is animated:
$(this).animate({
opacity: 0
}, 100, function() {
// Callback
$(this).css("background-image", "url(" + new_img + ")").promise().done(function(){
// Callback of the callback :)
$(this).animate({
opacity: 1
}, 600)
});
});
You can also use gdb instead of addr2line to examine memory address. Load executable file in gdb and print the name of a symbol which is stored at the address. 16 Examining the Symbol Table.
(gdb) info symbol 0x4005BDC
dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))
na.omit(dat)
x1 x2
1 1 100
3 3 300
5 5 500
also try to increase gradle version in your project's build.gradle. It helped me
@papigee should work on Windows 10 just fine. I'm using the integrated VSCode terminal with git bash and this always works for me.
winpty docker exec -it <container-id> //bin//sh
For a single result:
if (reader.Read())
{
Response.Write(reader[0].ToString());
Response.Write(reader[1].ToString());
}
For multiple results:
while (reader.Read())
{
Response.Write(reader[0].ToString());
Response.Write(reader[1].ToString());
}
If you'd like to use dynamic mapping, and don't want to clutter up your model with attributes, this approach worked for me
Usage:
var settings = new JsonSerializerSettings();
settings.DateFormatString = "YYYY-MM-DD";
settings.ContractResolver = new CustomContractResolver();
this.DataContext = JsonConvert.DeserializeObject<CountResponse>(jsonString, settings);
Logic:
public class CustomContractResolver : DefaultContractResolver
{
private Dictionary<string, string> PropertyMappings { get; set; }
public CustomContractResolver()
{
this.PropertyMappings = new Dictionary<string, string>
{
{"Meta", "meta"},
{"LastUpdated", "last_updated"},
{"Disclaimer", "disclaimer"},
{"License", "license"},
{"CountResults", "results"},
{"Term", "term"},
{"Count", "count"},
};
}
protected override string ResolvePropertyName(string propertyName)
{
string resolvedName = null;
var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
}
}
At the time the compiler encounters the call to swapCase in main(), it does not know about the function swapCase, so it reports an error. You can either move the definition of swapCase above main, or declare swap case above main:
void swapCase(char* name);
Also, the 32 in swapCase causes the reader to pause and wonder. The comment helps! In this context, it would add clarity to write
if ('A' <= name[i] && name[i] <= 'Z')
name[i] += 'a' - 'A';
else if ('a' <= name[i] && name[i] <= 'z')
name[i] += 'A' - 'a';
The construction in my if-tests is a matter of personal style. Yours were just fine. The main thing is the way to modify name[i] -- using the difference in 'a' vs. 'A' makes it more obvious what is going on, and nobody has to wonder if the '32' is actually correct.
Good luck learning!
Yes it is simple to do.
Sub CompactRepair()
Dim control As Office.CommandBarControl
Set control = CommandBars.FindControl( Id:=2071 )
control.accDoDefaultAction
End Sub
Basically it just finds the "Compact and repair" menuitem and clicks it, programatically.
Regarding your code: It's slightly hard to read... If you want to try to view it all in a php array format, just print_r it. This might help:
<?php
$a =
array(
'languages' =>
array (
76 =>
array ( 'id' => '76', 'tag' => 'Deutsch', ), ), 'targets' =>
array ( 81 =>
array ( 'id' => '81', 'tag' => 'Deutschland', ), ), 'tags' =>
array ( 7866 =>
array ( 'id' => '7866', 'tag' => 'automobile', ), 17800 =>
array ( 'id' => '17800', 'tag' => 'seat leon', ), 17801 =>
array ( 'id' => '17801', 'tag' => 'seat leon cupra', ), ),
'inactiveTags' =>
array ( 195 =>
array ( 'id' => '195', 'tag' => 'auto', ), 17804 =>
array ( 'id' => '17804', 'tag' => 'coupès', ), 17805 =>
array ( 'id' => '17805', 'tag' => 'fahrdynamik', ), 901 =>
array ( 'id' => '901', 'tag' => 'fahrzeuge', ), 17802 =>
array ( 'id' => '17802', 'tag' => 'günstige neuwagen', ), 1991 =>
array ( 'id' => '1991', 'tag' => 'motorsport', ), 2154 =>
array ( 'id' => '2154', 'tag' => 'neuwagen', ), 10660 =>
array ( 'id' => '10660', 'tag' => 'seat', ), 17803 =>
array ( 'id' => '17803', 'tag' => 'sportliche ausstrahlung', ), 74 =>
array ( 'id' => '74', 'tag' => 'web 2.0', ), ), 'categories' =>
array ( 16082 =>
array ( 'id' => '16082', 'tag' => 'Auto & Motorrad', ), 51 =>
array ( 'id' => '51', 'tag' => 'Blogosphäre', ), 66 =>
array ( 'id' => '66', 'tag' => 'Neues & Trends', ), 68 =>
array ( 'id' => '68', 'tag' => 'Privat', ), ), );
printarr($a);
printarr($a['languages'][76]['tag']);
parintarr($a['targets'][81]['id']);
function printarr($in){
echo "\n";
print_r($in);
echo "\n";
}
//run in php command line php path/to/file.php to test, switching otu the print_r.
I just got the solution to this problem from a friend. he said: Add ob_start(); under your session code. You can add exit(); under the header. I tried it and it worked. Hope this helps
This is for those on a rented Hosting sever who do not have access to php.init file.
wget cant download in multiple connections, instead you can try to user other program like aria2.
You could also use POSIX regular expressions, like
SELECT id FROM groups where name ~* 'administrator'
SELECT 'asd' ~* 'AsD'
returns t
Are we talking WCF here? I had issues where the service calls were not adding the http authorization headers, wrapping any calls into this statement fixed my issue.
using (OperationContextScope scope = new OperationContextScope(RefundClient.InnerChannel))
{
var httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes(RefundClient.ClientCredentials.UserName.UserName + ":" +
RefundClient.ClientCredentials.UserName.Password));
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
PaymentResponse = RefundClient.Payment(PaymentRequest);
}
This was running SOAP calls to IBM ESB via .NET with basic auth over http or https.
I hope this helps someone out because I had massive issues finding a solution online.
svn update /path/to/working/copy
If subversion is not in your PATH, then of course
/path/to/subversion/svn update /path/to/working/copy
or if you are in the current root directory of your svn repo (it contains a .svn subfolder), it's as simple as
svn update
Use blur event to call your function when element loses focus :
$('#filter').blur(function() {
$('#options').hide();
});
The display:table
family of CSS properties is mostly there so that HTML tables can be defined in terms of them. Because they're so intimately linked to a specific tag structure, they don't see much use beyond that.
If you were going to use these properties in your page, you would need a tag structure that closely mimicked that of tables, even though you weren't actually using the <table>
family of tags. A minimal version would be a single container element (display:table
), with direct children that can all be represented as rows (display:table-row
), which themselves have direct children that can all be represented as cells (display:table-cell
). There are other properties that let you mimic other tags in the table
family, but they require analogous structures in the HTML. Without this, it's going to be very hard (if not impossible) to make good use of these properties.
As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:
xlrd has explicitly removed support for anything other than xls files.
In your case, the solution is to:
openpyxl
: https://openpyxl.readthedocs.io/en/stable/df1 = pd.read_excel(
os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
engine='openpyxl',
)
For some reason your padding: 7px setting is nullifying the border-radius. Change it to padding: 0px 7px
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
I just wrote this function, it should do the trick for you, but it does left join
public function mergePerKey($array1,$array2)
{
$mergedArray = [];
foreach ($array1 as $key => $value)
{
if(isset($array2[$key]))
{
$mergedArray[$value] = null;
continue;
}
$mergedArray[$value] = $array2[$key];
}
return $mergedArray;
}
You could consider counts
as a resource. The URL would then be:
/api/counts/member
getResource by example:
package szb.testGetResource;
public class TestGetResource {
private void testIt() {
System.out.println("test1: "+TestGetResource.class.getResource("test.css"));
System.out.println("test2: "+getClass().getResource("test.css"));
}
public static void main(String[] args) {
new TestGetResource().testIt();
}
}
output:
test1: file:/home/szb/projects/test/bin/szb/testGetResource/test.css
test2: file:/home/szb/projects/test/bin/szb/testGetResource/test.css
Yes, this is a kind of inconsistency in the language.
The "=" in myarray = "abc";
is assignment (which won't work as the array is basically a kind of constant pointer), whereas in char myarray[4] = "abc";
it's an initialization of the array. There's no way for "late initialization".
You should just remember this rule.
Spring MVC runs on top of the Servlet API. So, you can use HttpServletRequest#getParameter()
for this:
String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");
The HttpServletRequest
should already be available to you inside Spring MVC as one of the method arguments of the handleRequest()
method.
"Am i doing it right?Is there better/smarter way to achieve the output this code gave me?"
Generally speaking, yes, you're doing it right. Tkinter has no native scrollable container other than the canvas. As you can see, it's really not that difficult to set up. As your example shows, it only takes 5 or 6 lines of code to make it work -- depending on how you count lines.
"Why must i use grid method?(i tried place method, but none of the labels appear on the canvas?)"
You ask about why you must use grid. There is no requirement to use grid. Place, grid and pack can all be used. It's simply that some are more naturally suited to particular types of problems. In this case it looks like you're creating an actual grid -- rows and columns of labels -- so grid is the natural choice.
"What so special about using anchor='nw' when creating window on canvas?"
The anchor tells you what part of the window is positioned at the coordinates you give. By default, the center of the window will be placed at the coordinate. In the case of your code above, you want the upper left ("northwest") corner to be at the coordinate.
We can use four methods for this conversion
10
const numString = "065";_x000D_
_x000D_
//parseInt with radix=10_x000D_
let number = parseInt(numString, 10);_x000D_
console.log(number);_x000D_
_x000D_
// Number constructor_x000D_
number = Number(numString);_x000D_
console.log(number);_x000D_
_x000D_
// unary plus operator_x000D_
number = +numString;_x000D_
console.log(number);_x000D_
_x000D_
// conversion using mathematical function (subtraction)_x000D_
number = numString - 0;_x000D_
console.log(number);
_x000D_
For the primitive type Number
, the safest max value is 253-1(Number.MAX_SAFE_INTEGER
).
console.log(Number.MAX_SAFE_INTEGER);
_x000D_
Now, lets consider the number string '099999999999999999999' and try to convert it using the above methods
const numString = '099999999999999999999';_x000D_
_x000D_
let parsedNumber = parseInt(numString, 10);_x000D_
console.log(`parseInt(radix=10) result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = Number(numString);_x000D_
console.log(`Number conversion result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = +numString;_x000D_
console.log(`Appending Unary plus operator result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = numString - 0;_x000D_
console.log(`Subtracting zero conversion result: ${parsedNumber}`);
_x000D_
All results will be incorrect.
That's because, when converted, the numString value is greater than Number.MAX_SAFE_INTEGER
. i.e.,
99999999999999999999 > 9007199254740991
This means all operation performed with the assumption that the string
can be converted to number
type fails.
For numbers greater than 253, primitive BigInt
has been added recently. Check browser compatibility of BigInt
here.
The conversion code will be like this.
const numString = '099999999999999999999';
const number = BigInt(numString);
parseInt
?If radix is undefined or 0 (or absent), JavaScript assumes the following:
Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet.
For this reason, always specify a radix when using parseInt
I had a similar problem, I wanted to use a different user name for a svn+ssh repository. In the end, I used svn relocate
(as described in in this answer. In my case, I'm using svn 1.6.11 and did the following:
svn switch --relocate \
svn+ssh://olduser@svnserver/path/to/repo \
svn+ssh://newuser@svnserver/path/to/repo
where svn+ssh://olduser@svnserver/path/to/repo
can be found in the URL:
line output of svn info
command. This command asked me for the password of newuser
.
Note that this change is persistent, i.e. if you want only temporarily switch to the new username with this method, you'll have to issue a similar command again after svn update
etc.
I spent some time looking for the best answer, and I think I have it.
This sql will give you the number of days between two dates as integer
:
SELECT
(EXTRACT(epoch from age('2017-6-15', now())) / 86400)::int
..which, when run today (2017-3-28
), provides me with:
?column?
------------
77
The misconception about the accepted answer:
select age('2010-04-01', '2012-03-05'),
date_part('year',age('2010-04-01', '2012-03-05')),
date_part('month',age('2010-04-01', '2012-03-05')),
date_part('day',age('2010-04-01', '2012-03-05'));
..is that you will get the literal difference between the parts of the date strings, not the amount of time between the two dates.
I.E:
Age(interval)=-1 years -11 mons -4 days;
Years(double precision)=-1;
Months(double precision)=-11;
Days(double precision)=-4;
There is no built in function for this.
You could use a CASE statement:
CASE WHEN MonthName= 'January' THEN 1
WHEN MonthName = 'February' THEN 2
...
WHEN MonthName = 'December' TNEN 12
END AS MonthNumber
or create a lookup table to join against
CREATE TABLE Months (
MonthName VARCHAR(20),
MonthNumber INT
);
INSERT INTO Months
(MonthName, MonthNumber)
SELECT 'January', 1
UNION ALL
SELECT 'February', 2
UNION ALL
...
SELECT 'December', 12;
SELECT t.MonthName, m.MonthNumber
FROM YourTable t
INNER JOIN Months m
ON t.MonthName = m.MonthName;
Here's one way. You have to get the individual components from the date object (day, month & year) and then build and format the string however you wish.
n = new Date();_x000D_
y = n.getFullYear();_x000D_
m = n.getMonth() + 1;_x000D_
d = n.getDate();_x000D_
document.getElementById("date").innerHTML = m + "/" + d + "/" + y;
_x000D_
<p id="date"></p>
_x000D_
The exponential function is e^x
where e
is a mathematical constant called Euler's number, approximately 2.718281
. This value has a close mathematical relationship with pi
and the slope of the curve e^x
is equal to its value at every point. np.exp()
calculates e^x
for each value of x
in your input array.
It looks like a common gaps-and-islands problem. The difference between two sequences of row numbers rn1
and rn2
give the "group" number.
Run this query CTE-by-CTE and examine intermediate results to see how it works.
Sample data
I expanded sample data from the question a little.
DECLARE @Source TABLE
(
EmployeeID int,
DateStarted date,
DepartmentID int
)
INSERT INTO @Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001),
(10005,'2013-05-01',001),
(10005,'2013-11-09',001),
(10005,'2013-12-01',002),
(10005,'2014-10-01',001),
(10005,'2016-12-01',001);
Query for SQL Server 2008
There is no LEAD
function in SQL Server 2008, so I had to use self-join via OUTER APPLY
to get the value of the "next" row for the DateEnd
.
WITH
CTE
AS
(
SELECT
EmployeeID
,DateStarted
,DepartmentID
,ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS rn1
,ROW_NUMBER() OVER (PARTITION BY EmployeeID, DepartmentID ORDER BY DateStarted) AS rn2
FROM @Source
)
,CTE_Groups
AS
(
SELECT
EmployeeID
,MIN(DateStarted) AS DateStart
,DepartmentID
FROM CTE
GROUP BY
EmployeeID
,DepartmentID
,rn1 - rn2
)
SELECT
CTE_Groups.EmployeeID
,CTE_Groups.DepartmentID
,CTE_Groups.DateStart
,A.DateEnd
FROM
CTE_Groups
OUTER APPLY
(
SELECT TOP(1) G2.DateStart AS DateEnd
FROM CTE_Groups AS G2
WHERE
G2.EmployeeID = CTE_Groups.EmployeeID
AND G2.DateStart > CTE_Groups.DateStart
ORDER BY G2.DateStart
) AS A
ORDER BY
EmployeeID
,DateStart
;
Query for SQL Server 2012+
Starting with SQL Server 2012 there is a LEAD
function that makes this task more efficient.
WITH
CTE
AS
(
SELECT
EmployeeID
,DateStarted
,DepartmentID
,ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS rn1
,ROW_NUMBER() OVER (PARTITION BY EmployeeID, DepartmentID ORDER BY DateStarted) AS rn2
FROM @Source
)
,CTE_Groups
AS
(
SELECT
EmployeeID
,MIN(DateStarted) AS DateStart
,DepartmentID
FROM CTE
GROUP BY
EmployeeID
,DepartmentID
,rn1 - rn2
)
SELECT
CTE_Groups.EmployeeID
,CTE_Groups.DepartmentID
,CTE_Groups.DateStart
,LEAD(CTE_Groups.DateStart) OVER (PARTITION BY CTE_Groups.EmployeeID ORDER BY CTE_Groups.DateStart) AS DateEnd
FROM
CTE_Groups
ORDER BY
EmployeeID
,DateStart
;
Result
+------------+--------------+------------+------------+
| EmployeeID | DepartmentID | DateStart | DateEnd |
+------------+--------------+------------+------------+
| 10001 | 1 | 2013-01-01 | 2013-12-01 |
| 10001 | 2 | 2013-12-01 | 2014-10-01 |
| 10001 | 1 | 2014-10-01 | NULL |
| 10005 | 1 | 2013-05-01 | 2013-12-01 |
| 10005 | 2 | 2013-12-01 | 2014-10-01 |
| 10005 | 1 | 2014-10-01 | NULL |
+------------+--------------+------------+------------+
You can use 'Indent by fold' plugin. Install it from the plugin manager. It works fine for me.
Django 2.2 version now has a bulk_update.
Refer to the following django documentation section
In short you should be able to use:
ModelClass.objects.filter(name='bar').update(name="foo")
You can also use F
objects to do things like incrementing rows:
from django.db.models import F
Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)
See the documentation.
However, note that:
ModelClass.save
method (so if you have some logic inside it won't be triggered). .update()
on a sliced QuerySet, it must be on an original QuerySet so you'll need to lean on the .filter()
and .exclude()
methods.In reactjs, you can disable the resize widget using style props.
<textarea id={"multiline-id"} ref={'my-ref'} style={{resize: "none"}} className="text-area-additional-styles" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Redirect to a page</title>
</head>
<body onload="window.location.assign('http://example.com')">
</body>
</html>
<script type="text/javascript">
jQuery(document).ready(function($) {
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/,'') + "$");
$("#navbar li a").each(function() {//alert('dsfgsdgfd');
if(urlRegExp.test(this.href.replace(/\/$/,''))){
$(this).addClass("active");}
});
});
</script>
IF you know the width of the container, you could do like this:
#container
width: #{200}px
#element
width: #{(0.25 * 200) - 5}px
I'm aware that in many cases #container could have a relative width. Then this wouldn't work.
I hope it still not too late to share my solution. Before that, you can follow the tutorial as stated in Android Developer documentation. To achieve this, you need to use Cluster Manager with defaultRenderer
.
Create an object that implements ClusterItem
public class SampleJob implements ClusterItem {
private double latitude;
private double longitude;
//Create constructor, getter and setter here
@Override
public LatLng getPosition() {
return new LatLng(latitude, longitude);
}
Create a default renderer class. This is the class that do all the job (inflating custom marker/cluster with your own style). I am using Universal image loader to do the downloading and caching the image.
public class JobRenderer extends DefaultClusterRenderer< SampleJob > {
private final IconGenerator iconGenerator;
private final IconGenerator clusterIconGenerator;
private final ImageView imageView;
private final ImageView clusterImageView;
private final int markerWidth;
private final int markerHeight;
private final String TAG = "ClusterRenderer";
private DisplayImageOptions options;
public JobRenderer(Context context, GoogleMap map, ClusterManager<SampleJob> clusterManager) {
super(context, map, clusterManager);
// initialize cluster icon generator
clusterIconGenerator = new IconGenerator(context.getApplicationContext());
View clusterView = LayoutInflater.from(context).inflate(R.layout.multi_profile, null);
clusterIconGenerator.setContentView(clusterView);
clusterImageView = (ImageView) clusterView.findViewById(R.id.image);
// initialize cluster item icon generator
iconGenerator = new IconGenerator(context.getApplicationContext());
imageView = new ImageView(context.getApplicationContext());
markerWidth = (int) context.getResources().getDimension(R.dimen.custom_profile_image);
markerHeight = (int) context.getResources().getDimension(R.dimen.custom_profile_image);
imageView.setLayoutParams(new ViewGroup.LayoutParams(markerWidth, markerHeight));
int padding = (int) context.getResources().getDimension(R.dimen.custom_profile_padding);
imageView.setPadding(padding, padding, padding, padding);
iconGenerator.setContentView(imageView);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.circle_icon_logo)
.showImageForEmptyUri(R.drawable.circle_icon_logo)
.showImageOnFail(R.drawable.circle_icon_logo)
.cacheInMemory(false)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
}
@Override
protected void onBeforeClusterItemRendered(SampleJob job, MarkerOptions markerOptions) {
ImageLoader.getInstance().displayImage(job.getJobImageURL(), imageView, options);
Bitmap icon = iconGenerator.makeIcon(job.getName());
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon)).title(job.getName());
}
@Override
protected void onBeforeClusterRendered(Cluster<SampleJob> cluster, MarkerOptions markerOptions) {
Iterator<Job> iterator = cluster.getItems().iterator();
ImageLoader.getInstance().displayImage(iterator.next().getJobImageURL(), clusterImageView, options);
Bitmap icon = clusterIconGenerator.makeIcon(iterator.next().getName());
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
}
@Override
protected boolean shouldRenderAsCluster(Cluster cluster) {
return cluster.getSize() > 1;
}
Apply cluster manager in your activity/fragment class.
public class SampleActivity extends AppCompatActivity implements OnMapReadyCallback {
private ClusterManager<SampleJob> mClusterManager;
private GoogleMap mMap;
private ArrayList<SampleJob> jobs = new ArrayList<SampleJob>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setMapToolbarEnabled(true);
mClusterManager = new ClusterManager<SampleJob>(this, mMap);
mClusterManager.setRenderer(new JobRenderer(this, mMap, mClusterManager));
mMap.setOnCameraChangeListener(mClusterManager);
mMap.setOnMarkerClickListener(mClusterManager);
//Assume that we already have arraylist of jobs
for(final SampleJob job: jobs){
mClusterManager.addItem(job);
}
mClusterManager.cluster();
}
Result
VAR1=value1 VAR2=value2 myScript args ...
There is a simple way as well, we can use the reshape function in a different way:
A_reshape = A.reshape(No_of_rows, No_of_columns)
I ran into some issues with backslash in my Domain\User string.
I added this to the other escapes from Anentropic's answer
.replace(/\\/g, '\')
Which I found here: How to escape backslash in JavaScript?
You need to install Package Control first (from the Python console in Sublime. Visit http://wbond.net/sublime_packages/package_control for more info), and then install emmet from their repository.
Reinstalling SDK did not help me but installing SDK+.NET 3.5 did from link below: https://www.microsoft.com/en-us/download/details.aspx?id=3138
I also had the problem after globally changing the project name, applicationid and the folders containing the java files.
Disabling Instant run helped, but was not a good option, so this helped:
rm -Rf .gradle .tags local.properties .idea/workspace.xml .idea/caches/* .idea/libraries app/build
SyntaxHighlighter is a fully functional self-contained code syntax highlighter developed in JavaScript. To get an idea of what SyntaxHighlighter is capable of, have a look at the demo page.
This is not a new question. I addresed it in comments in one SO post, and posted my alternative implementations in another post. The comments in the first post actually elucidate the performance differences between the different implementations.
Basically, which works fastest depends on what database object you use with it.
The previous answers were in the right track, but the complete answer for this is going to Disabling rules only for a group of files, there you'll find the documentation needed to disable/enable rules for certain folders (Because in some cases you don't want to ignore the whole thing, only disable certain rules). Example:
{
"env": {},
"extends": [],
"parser": "",
"plugins": [],
"rules": {},
"overrides": [
{
"files": ["test/*.spec.js"], // Or *.test.js
"rules": {
"require-jsdoc": "off"
}
}
],
"settings": {}
}
I had the same problem. What I did was:
sudo apt-get update
And then reinstall ruby-full
sudo apt-get install ruby-full
Similar issue:
I gave passphrase
when Git-cloned using SSH URL
for git.
So this error now shows up, each time I opened VS Code
on Windows 10
Below fixed the issue:
1 . Run the below command in CMD
setx SSH_ASKPASS "C:\Program Files\Git\mingw64\libexec\git-core\git-gui--askpass"
setx DISPLAY needs-to-be-defined
2 . Exit CMD & VS Code
3 . Reopen VS Code
4 . VS Code now shows a popup dialog where we can enter passpharse
Above commands are for Windows OS, similar instructions will work for Linux/MAC.
DECLARE @CodeNameString varchar(max)
SET @CodeNameString=''
SELECT @CodeNameString=@CodeNameString+CodeName FROM AccountCodes ORDER BY Sort
SELECT @CodeNameString
Kotlin's String class has a format function now, which internally uses Java's String.format
method:
/**
* Uses this string as a format string and returns a string obtained by substituting the specified arguments,
* using the default locale.
*/
@kotlin.internal.InlineOnly
public inline fun String.Companion.format(format: String, vararg args: Any?): String = java.lang.String.format(format, *args)
Usage
val pi = 3.14159265358979323
val formatted = String.format("%.2f", pi) ;
println(formatted)
>>3.14
<input class="form-control search-query input_style" placeholder="Search…" name="" title="Search for:" type="text">
.input_style
{
padding-left:20px;
}
I'm implementing it in Play Framework and for me it worked like this:
1) Notice that I used data-rule-equalTo in input tag for the id inputPassword1. The code section of userform in my Modal:
<div class="form-group">
<label for="pass1">@Messages("authentication.password")</label>
<input class="form-control required" id="inputPassword1" placeholder="@Messages("authentication.password")" type="password" name="password" maxlength=10 minlength=5>
</div>
<div class="form-group">
<label for="pass2">@Messages("authentication.password2")</label>
<input class="form-control required" data-rule-equalTo="#inputPassword1" id="inputPassword2" placeholder="@Messages("authentication.password")" type="password" name="password2">
</div>
2)Since I used validator within a Modal
$(document).on("click", ".createUserModal", function () {
$(this).find('#userform').validate({
rules: {
firstName: "required",
lastName: "required",
nationalId: {
required: true,
digits:true
},
email: {
required: true,
email: true
},
optradio: "required",
password :{
required: true,
minlength: 5
},
password2: {
required: true
}
},
highlight: function (element) {
$(element).parent().addClass('error')
},
unhighlight: function (element) {
$(element).parent().removeClass('error')
},
onsubmit: true
});
});
Hope it helps someone :).
From what I've been able to piece together, you have to add the view using LayoutParams.
LinearLayout linearLayout = new LinearLayout(this);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
relativeParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
parentView.addView(linearLayout, relativeParams);
All credit to sechastain, to relatively position your items programmatically you have to assign ids to them.
TextView tv1 = new TextView(this);
tv1.setId(1);
TextView tv2 = new TextView(this);
tv2.setId(2);
Then addRule(RelativeLayout.RIGHT_OF, tv1.getId());
Your nameContent scope is only inside first function. You'll never get it's value that way.
var nameContent; // now it's global!
function first(){
nameContent = document.getElementById('full_name').value;
}
function second() {
first();
y=nameContent;
alert(y);
}
second();
IEnumerable<string> e = (from char c in source
select new { Data = c.ToString() }).Select(t = > t.Data);
// or
IEnumerable<string> e = from char c in source
select c.ToString();
// or
IEnumerable<string> e = source.Select(c = > c.ToString());
Then you can call ToList()
:
List<string> l = (from char c in source
select new { Data = c.ToString() }).Select(t = > t.Data).ToList();
// or
List<string> l = (from char c in source
select c.ToString()).ToList();
// or
List<string> l = source.Select(c = > c.ToString()).ToList();
To test without copy elision and see you copy/move constructors/operators in action add "-fno-elide-constructors".
Even with no optimizations (-O0 ), GCC and Clang will still do copy elision, which has the effect of skipping copy/move constructors in some cases. See this question for the details about copy elision.
However, in Clang 3.4 it does trigger a bug (an invalid temporary object without calling constructor), which is fixed in 3.5.
This will give you a floating point number between 0 and 47
float low_bound = 0;
float high_bound = 47;
float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);
Or just simply
float rndValue = (((float)arc4random()/0x100000000)*47);
Both lower and upper bound can be negative as well. The example code below gives you a random number between -35.76 and +12.09
float low_bound = -35.76;
float high_bound = 12.09;
float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);
Convert result to a rounder Integer value:
int intRndValue = (int)(rndValue + 0.5);
Based on this answer, I did this in my React component:
export default React.memo(() => {
const containerRef = React.useRef(null);
React.useEffect(() => {
document.addEventListener('mousedown', handleMouseMove);
return () => document.removeEventListener('mousedown', handleMouseMove);
}, []);
const handleMouseMove = React.useCallback(() => {
const drag = (e) => {
console.log('mouse is moving');
};
const lift = (e) => {
console.log('mouse move ended');
window.removeEventListener('mousemove', drag);
window.removeEventListener('mouseup', this);
};
window.addEventListener('mousemove', drag);
window.addEventListener('mouseup', lift);
}, []);
return (
<div style={{ width: '100vw', height: '100vh' }} ref={containerRef} />
);
})
In the second .c
file use extern
keyword with the same variable name.
This will work in .NET 4.7.2 with Visual Studio 2017 (15.9.4):
Another way of simply telling if an element exists is to check the count()
if (myset.count(x)) {
// x is in the set, count is 1
} else {
// count zero, i.e. x not in the set
}
Most of the times, however, I find myself needing access to the element wherever I check for its existence.
So I'd have to find the iterator anyway. Then, of course, it's better to simply compare it to end
too.
set< X >::iterator it = myset.find(x);
if (it != myset.end()) {
// do something with *it
}
C++ 20
In C++20 set gets a contains
function, so the following becomes possible as mentioned at: https://stackoverflow.com/a/54197839/895245
if (myset.contains(x)) {
// x is in the set
} else {
// no x
}
You might get a more descriptive error message if you tried to start the service from command line using this command:
"C:\Program Files\PostgreSQL\9.5\bin\pg_ctl.exe" start -N "postgresql-x64-9.5"
-D "C:\Program Files\PostgreSQL\9.5\data" -w
The log file would be at C:\Program Files\PostgreSQL\9.5\data\pg_log
.
Note that paths and service name might be different depending on your installation.
if [ -n "$var" -a -e "$var" ]; then
do something ...
fi
Please see below an example how to add white noise to the rendered texture. The solution is to use two textures: original and pure white noise, like this one: wiki white noise
private static final String VERTEX_SHADER =
"uniform mat4 uMVPMatrix;\n" +
"uniform mat4 uMVMatrix;\n" +
"uniform mat4 uSTMatrix;\n" +
"attribute vec4 aPosition;\n" +
"attribute vec4 aTextureCoord;\n" +
"varying vec2 vTextureCoord;\n" +
"varying vec4 vInCamPosition;\n" +
"void main() {\n" +
" vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" +
" gl_Position = uMVPMatrix * aPosition;\n" +
"}\n";
private static final String FRAGMENT_SHADER =
"precision mediump float;\n" +
"uniform sampler2D sTextureUnit;\n" +
"uniform sampler2D sNoiseTextureUnit;\n" +
"uniform float uNoseFactor;\n" +
"varying vec2 vTextureCoord;\n" +
"varying vec4 vInCamPosition;\n" +
"void main() {\n" +
" gl_FragColor = texture2D(sTextureUnit, vTextureCoord);\n" +
" vec4 vRandChosenColor = texture2D(sNoiseTextureUnit, fract(vTextureCoord + uNoseFactor));\n" +
" gl_FragColor.r += (0.05 * vRandChosenColor.r);\n" +
" gl_FragColor.g += (0.05 * vRandChosenColor.g);\n" +
" gl_FragColor.b += (0.05 * vRandChosenColor.b);\n" +
"}\n";
The fragment shared contains parameter uNoiseFactor which is updated on every rendering by main application:
float noiseValue = (float)(mRand.nextInt() % 1000)/1000;
int noiseFactorUniformHandle = GLES20.glGetUniformLocation( mProgram, "sNoiseTextureUnit");
GLES20.glUniform1f(noiseFactorUniformHandle, noiseFactor);
I am using the code above but I have changed the delay effect by slideToggle.
It slides the dropdown on hover with animation.
$('.navbar .dropdown').hover(function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideToggle(400);
}, function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideToggle(400)
});
There is a shorter way of doing this now:
exports.someValue = function(req, res, next) {
//query with mongoose
dbSchemas.SomeValue.find({}, 'name', function(err, someValue){
if(err) return next(err);
res.send(someValue);
});
//this eliminates the .select() and .exec() methods
};
In case you want most of the Schema fields
and want to omit only a few, you can prefix the field name
with a -
. For ex "-name"
in the second argument will not include name
field in the doc whereas the example given here will have only the name
field in the returned docs.
Either use window.onload
this way
<script>
window.onload = function() {
// ...
}
</script>
or alternatively
<script>
window.onload = functionName;
</script>
(yes, without the parentheses)
Or just put the script at the very bottom of page, right before </body>
. At that point, all HTML DOM elements are ready to be accessed by document
functions.
<body>
...
<script>
functionName();
</script>
</body>
Another solution is:
>>> "".join(list(hex(255))[2:])
'ff'
Probably an archaic answer, but functional.
you use bad character like ? and & and etc ...
edit it to new code
see this links
also you can use urlencode
$val=urlencode('http://google.com/?var=234&key=234')
There is another alternative: using setAttribute
rather than adding an event listener. Like this:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Demo innerHTML and event listeners</title>_x000D_
<style>_x000D_
div {_x000D_
border: 1px solid black;_x000D_
padding: 10px;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
<span>Click here.</span>_x000D_
</div>_x000D_
<script>_x000D_
document.querySelector('span').setAttribute("onclick","alert('Hi.')");_x000D_
document.querySelector('div').innerHTML += ' Added text.';_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
You have a CryptoListPresenter _presenter
but you are never initializing it. You should either be doing that when you declare it or in your initState()
(or another appropriate but called-before-you-need-it method).
One thing I find that helps is that if I know a member is functionally 'final', to actually set it to final as that way the analyzer complains that it hasn't been initialized.
EDIT:
I see diegoveloper beat me to answering this, and that the OP asked a follow up.
@Jake - it's hard for us to tell without knowing exactly what CryptoListPresenter is, but depending on what exactly CryptoListPresenter actually is, generally you'd do final CryptoListPresenter _presenter = new CryptoListPresenter(...);
, or
CryptoListPresenter _presenter;
@override
void initState() {
_presenter = new CryptoListPresenter(...);
}
To reload a section of the page, you could use jquerys load
with the current url and specify the fragment you need, which would be the same element that load
is called on, in this case #here
:
function updateDiv()
{
$( "#here" ).load(window.location.href + " #here" );
}
+ " #here"
This function can be called within an interval, or attached to a click event
If you are using pdb, you can define aliases for shortcuts. I use these:
# Ned's .pdbrc
# Print a dictionary, sorted. %1 is the dict, %2 is the prefix for the names.
alias p_ for k in sorted(%1.keys()): print "%s%-15s= %-80.80s" % ("%2",k,repr(%1[k]))
# Print the instance variables of a thing.
alias pi p_ %1.__dict__ %1.
# Print the instance variables of self.
alias ps pi self
# Print the locals.
alias pl p_ locals() local:
# Next and list, and step and list.
alias nl n;;l
alias sl s;;l
# Short cuts for walking up and down the stack
alias uu u;;u
alias uuu u;;u;;u
alias uuuu u;;u;;u;;u
alias uuuuu u;;u;;u;;u;;u
alias dd d;;d
alias ddd d;;d;;d
alias dddd d;;d;;d;;d
alias ddddd d;;d;;d;;d;;d
This question has been answered, but maybe this might someone else coming here.
I also had an issue where this
is undefined, when I was foolishly trying to destructure the methods of a class when initialising it:
import MyClass from "./myClass"
// 'this' is not defined here:
const { aMethod } = new MyClass()
aMethod() // error: 'this' is not defined
// So instead, init as you would normally:
const myClass = new MyClass()
myClass.aMethod() // OK
Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.
This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.
The HttpSession#setMaxInactiveInterval()
doesn't change much here by the way. It does exactly the same as <session-timeout>
in web.xml
, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static
method).
To play around and experience this yourself, try to set <session-timeout>
to 1 minute and create a HttpSessionListener
like follows:
@WebListener
public class HttpSessionChecker implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
}
public void sessionDestroyed(HttpSessionEvent event) {
System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
}
}
(if you're not on Servlet 3.0 yet and thus can't use @WebListener
, then register in web.xml
as follows):
<listener>
<listener-class>com.example.HttpSessionChecker</listener-class>
</listener>
Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed
line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.
Just follow any of these:
For jackson it should work:
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(object);
//will return json in string
For gson it should work:
Gson gson = new Gson();
return Response.ok(gson.toJson(yourClass)).build();
I have also used a non-generic version, using the new
keyword:
public interface IMetadata
{
Type DataType { get; }
object Data { get; }
}
public interface IMetadata<TData> : IMetadata
{
new TData Data { get; }
}
Explicit interface implementation is used to allow both Data
members:
public class Metadata<TData> : IMetadata<TData>
{
public Metadata(TData data)
{
Data = data;
}
public Type DataType
{
get { return typeof(TData); }
}
object IMetadata.Data
{
get { return Data; }
}
public TData Data { get; private set; }
}
You could derive a version targeting value types:
public interface IValueTypeMetadata : IMetadata
{
}
public interface IValueTypeMetadata<TData> : IMetadata<TData>, IValueTypeMetadata where TData : struct
{
}
public class ValueTypeMetadata<TData> : Metadata<TData>, IValueTypeMetadata<TData> where TData : struct
{
public ValueTypeMetadata(TData data) : base(data)
{}
}
This can be extended to any kind of generic constraints.
I would just avoid the use of virtualenv
after Python3.3+ and instead use the standard shipped library venv
. To create a new virtual environment you would type:
$ python3 -m venv <MYVENV>
virtualenv
tries to copy the Python binary into the virtual environment's bin directory. However it does not update library file links embedded into that binary, so if you build Python from source into a non-system directory with relative path names, the Python binary breaks. Since this is how you make a copy distributable Python, it is a big flaw. BTW to inspect embedded library file links on OS X, use otool
. For example from within your virtual environment, type:
$ otool -L bin/python
python:
@executable_path/../Python (compatibility version 3.4.0, current version 3.4.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1238.0.0)
Consequently I would avoid virtualenvwrapper
and pipenv
. pyvenv
is deprecated. pyenv
seems to be used often where virtualenv
is used but I would stay away from it also since I think venv
also does what pyenv
is built for.
venv
creates virtual environments in the shell that are fresh and sandboxed, with user-installable libraries, and it's multi-python safe. Fresh because virtual environments only start with the standard libraries that ship with python, you have to install any other libraries all over again with pip install
while the virtual environment is active. Sandboxed because none of these new library installs are visible outside the virtual environment, so you can delete the whole environment and start again without worrying about impacting your base python install. User-installable libraries because the virtual environment's target folder is created without sudo
in some directory you already own, so you won't need sudo
permissions to install libraries into it. Finally it is multi-python safe, since when virtual environments activate, the shell only sees the python version (3.4, 3.5 etc.) that was used to build that virtual environment.
pyenv
is similar to venv
in that it lets you manage multiple python environments. However with pyenv
you can't conveniently rollback library installs to some start state and you will likely need admin
privileges at some point to update libraries. So I think it is also best to use venv
.
In the last couple of years I have found many problems in build systems (emacs packages, python standalone application builders, installers...) that ultimately come down to issues with virtualenv
. I think python will be a better platform when we eliminate this additional option and only use venv
.
EDIT: Tweet of the BDFL,
I use venv (in the stdlib) and a bunch of shell aliases to quickly switch.— Guido van Rossum (@gvanrossum) October 22, 2020select whatever,columns,you,want from mytable
where mykey=(select max(mykey) from mytable);
Simple solution(even though question is old)
Test1.bat
echo off
echo "Batch started"
set arg1=%1
echo "arg1 is %arg1%"
echo on
pause
CallTest1.bat
call "C:\Temp\Test1.bat" pass123
output
YourLocalPath>call "C:\Temp\test.bat" pass123
YourLocalPath>echo off
"Batch started"
"arg1 is pass123"
YourLocalPath>pause
Press any key to continue . . .
Where YourLocalPath is current directory path.
To keep things simple store the command param in variable and use variable for comparison.
Its not just simple to write but its simple to maintain as well so if later some other person or you read your script after long period of time, it will be easy to understand and maintain.
To write code inline : see other answers.
This page on the official mongodb site addresses exactly this question:
When we display our list of stories, we'll need to show the name of the user who posted the story. If we were using a relational database, we could perform a join on users and stores, and get all our objects in a single query. But MongoDB does not support joins and so, at times, requires bit of denormalization. Here, this means caching the 'username' attribute.
Relational purists may be feeling uneasy already, as if we were violating some universal law. But let’s bear in mind that MongoDB collections are not equivalent to relational tables; each serves a unique design objective. A normalized table provides an atomic, isolated chunk of data. A document, however, more closely represents an object as a whole. In the case of a social news site, it can be argued that a username is intrinsic to the story being posted.
<button style="position: absolute; left: 20%; right: 20%; bottom: 5%;"> Button </button>
You can use:
[Min(0)]
This will impose a required minimum value of 0 (zero), and no maximum value.
You need DataAnnotationsExtensions to use this.
Try to get using:
var count = $("ul > li").size();
alert(count);
If you have IIS Express (with Visual Studio):
To enable the SSL within IIS Express, you have to just set “SSL Enabled = true” in the project properties window.
See the steps and pictures at this code project.
IIS Express will generate a certificate for you (you'll be prompted for it, etc.). Note that depending on configuration the site may still automatically start with the URL rather than the SSL URL. You can see the SSL URL - note the port number and replace it in your browser address bar, you should be able to get in and test.
From there you can right click on your project, click property pages, then start options and assign the start URL - put the new https with the new port (usually 44301 - notice the similarity to port 443) and your project will start correctly from then on.
you would have to copy the current data to the new directory and to change your my.cnf
your MySQL.
[mysqld]
datadir=/your/new/dir/
tmpdir=/your/new/temp/
You have to copy the database when the server is not running.
openssl s_client
instead of curl
.-msg
does the trick!-debug
helps to see what actually travels over the socket.-status
OCSP stapling should be standard nowadays.openssl s_client -connect example.com:443 -tls1_2 -status -msg -debug -CAfile <path to trusted root ca pem> -key <path to client private key pem> -cert <path to client cert pem>
Other useful switches
-tlsextdebug
-prexit
-state
That will work just fine. You can export an entire calendar with File
> Export…
, or individual events by dragging them to the Finder.
iCalendar (.ics
) files are human-readable, so you can always pop it open in a text editor to make sure no private events made it in there. They consist of nested sections with start with BEGIN:
and end with END:
. You'll mostly find VEVENT
sections (each of which represents an event) and VTIMEZONE
sections, each of which represents a time zone that's referenced from one or more events.
You should be careful when using the ROW_NUMBER() OVER (ORDER BY)
statement as performance is quite poor. Same goes for using Common Table Expressions with ROW_NUMBER()
that is even worse. I'm using the following snippet that has proven to be slightly faster than using a table variable with an identity to provide the page number.
DECLARE @Offset INT = 120000
DECLARE @Limit INT = 10
DECLARE @ROWCOUNT INT = @Offset+@Limit
SET ROWCOUNT @ROWCOUNT
SELECT * FROM MyTable INTO #ResultSet
WHERE MyTable.Type = 1
SELECT * FROM
(
SELECT *, ROW_NUMBER() OVER(ORDER BY SortConst ASC) As RowNumber FROM
(
SELECT *, 1 As SortConst FROM #ResultSet
) AS ResultSet
) AS Page
WHERE RowNumber BETWEEN @Offset AND @ROWCOUNT
DROP TABLE #ResultSet
I add the ",-std=c++0x" after "-c -fmessage-length=0",under Project Properties -> C/C++ Build -> Settings -> GCC C++ Compiler -> Miscellaneous. Dont't forget to add the comma "," as the seperator.
Spring Boot provide the plugin with maven.
So you can go to your project directory and run
mvn spring-boot:run
This command line run will be easily when you're using spring-boot-devs-tool with auto reload/restart when you have changed you application.
For a valid JSON string at least a "{}" is required. See more at the http://json.org/
<asp:GridView
ID="GridView1" runat="server" AutoGenerateColumns="false" AllowSorting="True" onsorting="GridView1_Sorting" EnableViewState="true">
<Columns>
<asp:BoundField DataField="bookid" HeaderText="BOOK ID"SortExpression="bookid" />
<asp:BoundField DataField="bookname" HeaderText="BOOK NAME" />
<asp:BoundField DataField="writer" HeaderText="WRITER" />
<asp:BoundField DataField="totalbook" HeaderText="TOTALBOOK" SortExpression="totalbook" />
<asp:BoundField DataField="availablebook" HeaderText="AVAILABLE BOOK" />
</Columns>
</asp:GridView>
Code behind:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
string query = "SELECT * FROM book";
DataTable DT = new DataTable();
SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) {
string query = "SELECT * FROM book";
DataTable DT = new DataTable();
SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
if (DT != null) {
DataView dataView = new DataView(DT);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
private string GridViewSortDirection {
get { return ViewState["SortDirection"] as string ?? "DESC"; }
set { ViewState["SortDirection"] = value; }
}
private string ConvertSortDirectionToSql(SortDirection sortDirection) {
switch (GridViewSortDirection) {
case "ASC":
GridViewSortDirection = "DESC";
break;
case "DESC":
GridViewSortDirection = "ASC";
break;
}
return GridViewSortDirection;
}
}
Remember to tackle error messages in order. In my case, the error above this one was "undefined reference", and I visually skipped over it to the more interesting "relocation truncated" error. In fact, my problem was an old library that was causing the "undefined reference" message. Once I fixed that, the "relocation truncated" went away also.
You can directly pass boolean parameter in integer column saying that it should be unsigned or not. In laravel 5.4 following code solved my problem.
$table->integer('user_id', false, true);
Here second parameter false represents that it should not be auto-incrementing and third parameter true represents that it should be unsigned. You can keep foreign key constraint in same migration or separate it. It works on both.
Best real time Example for countDownLatch explained in this link CountDownLatchExample
To vote on this issue, here is one active suggestion of how this could be added to the language. I'm not saying this is the best way to do this (at all), feel free to put out your own suggestion. But allowing properties to be passed by ref like Visual Basic already can do would hugely help simplify some code, and quite often!
The name of the key 'key_name' is key_name, therefore print 'key_name'
or whatever variable you have representing it.
You can even set the prof. pic size to its high resolution that is '1080x1080'
replace "150x150" with 1080x1080 and remove /vp/ from the link.
What worked for me (youtube-dl version 2018.03.03, ffprobe 0.5, no avprobe, 3.4.1-tessus, in Hi-Sierra/iMac) was:
brew install libav
(thanks to marciovsena's post on GitHub).
I saw elsewhere that libav might be deprecated in the future, but I'll worry about it when we get there.
@qbzenker provided the most idiomatic method IMO
Here are a few alternatives:
In [28]: df.query('Col2 != Col2') # Using the fact that: np.nan != np.nan
Out[28]:
Col1 Col2 Col3
1 0 NaN 0.0
In [29]: df[np.isnan(df.Col2)]
Out[29]:
Col1 Col2 Col3
1 0 NaN 0.0
For me, this was the result of having set the document root (in httpd.conf
) to a directory that did not exist (I had just emptied htdocs of a previous project).
Provided that you are extending JFrame:
public void run() {
MyFrame myFrame = new MyFrame();
myFrame.setVisible(true);
myFrame.setExtendedState(myFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
}
Use the FROM_UNIXTIME()
function in MySQL
Remember that if you are using a framework that stores it in milliseconds (for example Java's timestamp) you have to divide by 1000 to obtain the right Unix time in seconds.
Use Conveyor by Keyoti (extensión de Visual Studio). Extension visual studio
<script type="text/javascript">
function showDiv(toggle){
document.getElementById(toggle).style.display = 'block';
}
</script>
<input type="button" name="answer" onclick="showDiv('toggle')">Show</input>
<div id="toggle" style="display:none">Hello</div>
There is a symfony2 tool to display date in the current locale:
{{ user.createdAt|localeDate }} to have a medium date and no time, in the current locale
{{ user.createdAt|localeDate('long','medium') }} to have a long date and medium time, in the current locale
CSS:
.reverse {
transform: rotate(180deg);
}
.rotate {
animation-duration: .5s;
animation-iteration-count: 1;
animation-name: yoyo;
animation-timing-function: linear;
}
@keyframes yoyo {
from { transform: rotate( 0deg); }
to { transform: rotate(360deg); }
}
Javascript:
$(buttonElement).click(function () {
$(".arrow").toggleClass("reverse")
return false
})
$(buttonElement).hover(function () {
$(".arrow").addClass("rotate")
}, function() {
$(".arrow").removeClass("rotate")
})
PS: I've found this somewhere else but don't remember the source
If there is only 1 occurrence, the answer of ivanovic is the best way I guess. But if there are many occurrences, you should use regexp:
\[(.*?)\]
this is your pattern. And in each group(1)
will get you your string.
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(input);
while(m.find())
{
m.group(1); //is your string. do what you want
}
Why don't you simply move the code you have in the ApiController calls - DocumentsController to a class that you can call from both your HomeController and DocumentController. Pull this out into a class you call from both controllers. This stuff in your question:
// All code to find the files are here and is working perfectly...
It doesn't make sense to call a API Controller from another controller on the same website.
This will also simplify the code when you come back to it in the future you will have one common class for finding the files and doing that logic there...
In Some cases, you need to increase the maximum execution time.
max_execution_time=30
I made it
max_execution_time=600000
then I was happy.
A couple of notes first: when you use Data/data1.txt
as an argument, should it really be /Data/data1.txt
(with a leading slash)? Also, should the outer loop scan only for .txt files, or all files in /Data? Here's an answer, assuming /Data/data1.txt
and .txt files only:
#!/bin/bash
for filename in /Data/*.txt; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$filename" "Logs/$(basename "$filename" .txt)_Log$i.txt"
done
done
Notes:
/Data/*.txt
expands to the paths of the text files in /Data (including the /Data/ part)$( ... )
runs a shell command and inserts its output at that point in the command linebasename somepath .txt
outputs the base part of somepath, with .txt removed from the end (e.g. /Data/file.txt
-> file
)If you needed to run MyProgram with Data/file.txt
instead of /Data/file.txt
, use "${filename#/}"
to remove the leading slash. On the other hand, if it's really Data
not /Data
you want to scan, just use for filename in Data/*.txt
.
If you are looking for a rapid, normalized cross correlation in either one or two dimensions
I would recommend the openCV library (see http://opencv.willowgarage.com/wiki/ http://opencv.org/). The cross-correlation code maintained by this group is the fastest you will find, and it will be normalized (results between -1 and 1).
While this is a C++ library the code is maintained with CMake and has python bindings so that access to the cross correlation functions is convenient. OpenCV also plays nicely with numpy. If I wanted to compute a 2-D cross-correlation starting from numpy arrays I could do it as follows.
import numpy
import cv
#Create a random template and place it in a larger image
templateNp = numpy.random.random( (100,100) )
image = numpy.random.random( (400,400) )
image[:100, :100] = templateNp
#create a numpy array for storing result
resultNp = numpy.zeros( (301, 301) )
#convert from numpy format to openCV format
templateCv = cv.fromarray(numpy.float32(template))
imageCv = cv.fromarray(numpy.float32(image))
resultCv = cv.fromarray(numpy.float32(resultNp))
#perform cross correlation
cv.MatchTemplate(templateCv, imageCv, resultCv, cv.CV_TM_CCORR_NORMED)
#convert result back to numpy array
resultNp = np.asarray(resultCv)
For just a 1-D cross-correlation create a 2-D array with shape equal to (N, 1 ). Though there is some extra code involved to convert to an openCV format the speed-up over scipy is quite impressive.
Only first part of Justin's answer is correct. Using "%.3g" will not work for all cases as .3 is not the precision, but total number of digits. Try it for numbers like 1000.123 and it breaks.
So, I would use what Justin is suggesting:
>>> ('%.4f' % 12340.123456).rstrip('0').rstrip('.')
'12340.1235'
>>> ('%.4f' % -400).rstrip('0').rstrip('.')
'-400'
>>> ('%.4f' % 0).rstrip('0').rstrip('.')
'0'
>>> ('%.4f' % .1).rstrip('0').rstrip('.')
'0.1'
An excellent explanation can be found here: Generate script in SQL Server Management Studio
Courtesy Ali Issa Here's what you have to do:
If you want to create a script that just generates the tables (no data) you can skip the advanced part of the instructions!
we can find length of array by using array_name.length attribute
int [] i = i.length;
Found this while Googling. The second post makes a point about the different phases of JSF, which might be causing your error message to become lost. Also, try null in place of "newPassword" because you do not have any object with the id newPassword.
In a fresh spreadsheet (US locale) with 12/19/11
in A1 and DT 30
in B1 then:
=A1+right(B1,2)
in say C1 returns 1/18/12
.
As a string function RIGHT returns Text but that can be coerced into a number when adding. In adding a number to dates unity is treated as one day. Within (very wide) limits, months and even years are adjusted automatically.
Yes, it is extremely useful in browsers that support it, but the "limiting" is as a convenience to users (so they are not overwhelmed with irrelevant files) rather than as a way to prevent them from uploading things you don't want them uploading.
It is supported in
Here is a list of content types you can use with it, followed by the corresponding file extensions (though of course you can use any file extension):
application/envoy evy
application/fractals fif
application/futuresplash spl
application/hta hta
application/internet-property-stream acx
application/mac-binhex40 hqx
application/msword doc
application/msword dot
application/octet-stream *
application/octet-stream bin
application/octet-stream class
application/octet-stream dms
application/octet-stream exe
application/octet-stream lha
application/octet-stream lzh
application/oda oda
application/olescript axs
application/pdf pdf
application/pics-rules prf
application/pkcs10 p10
application/pkix-crl crl
application/postscript ai
application/postscript eps
application/postscript ps
application/rtf rtf
application/set-payment-initiation setpay
application/set-registration-initiation setreg
application/vnd.ms-excel xla
application/vnd.ms-excel xlc
application/vnd.ms-excel xlm
application/vnd.ms-excel xls
application/vnd.ms-excel xlt
application/vnd.ms-excel xlw
application/vnd.ms-outlook msg
application/vnd.ms-pkicertstore sst
application/vnd.ms-pkiseccat cat
application/vnd.ms-pkistl stl
application/vnd.ms-powerpoint pot
application/vnd.ms-powerpoint pps
application/vnd.ms-powerpoint ppt
application/vnd.ms-project mpp
application/vnd.ms-works wcm
application/vnd.ms-works wdb
application/vnd.ms-works wks
application/vnd.ms-works wps
application/winhlp hlp
application/x-bcpio bcpio
application/x-cdf cdf
application/x-compress z
application/x-compressed tgz
application/x-cpio cpio
application/x-csh csh
application/x-director dcr
application/x-director dir
application/x-director dxr
application/x-dvi dvi
application/x-gtar gtar
application/x-gzip gz
application/x-hdf hdf
application/x-internet-signup ins
application/x-internet-signup isp
application/x-iphone iii
application/x-javascript js
application/x-latex latex
application/x-msaccess mdb
application/x-mscardfile crd
application/x-msclip clp
application/x-msdownload dll
application/x-msmediaview m13
application/x-msmediaview m14
application/x-msmediaview mvb
application/x-msmetafile wmf
application/x-msmoney mny
application/x-mspublisher pub
application/x-msschedule scd
application/x-msterminal trm
application/x-mswrite wri
application/x-netcdf cdf
application/x-netcdf nc
application/x-perfmon pma
application/x-perfmon pmc
application/x-perfmon pml
application/x-perfmon pmr
application/x-perfmon pmw
application/x-pkcs12 p12
application/x-pkcs12 pfx
application/x-pkcs7-certificates p7b
application/x-pkcs7-certificates spc
application/x-pkcs7-certreqresp p7r
application/x-pkcs7-mime p7c
application/x-pkcs7-mime p7m
application/x-pkcs7-signature p7s
application/x-sh sh
application/x-shar shar
application/x-shockwave-flash swf
application/x-stuffit sit
application/x-sv4cpio sv4cpio
application/x-sv4crc sv4crc
application/x-tar tar
application/x-tcl tcl
application/x-tex tex
application/x-texinfo texi
application/x-texinfo texinfo
application/x-troff roff
application/x-troff t
application/x-troff tr
application/x-troff-man man
application/x-troff-me me
application/x-troff-ms ms
application/x-ustar ustar
application/x-wais-source src
application/x-x509-ca-cert cer
application/x-x509-ca-cert crt
application/x-x509-ca-cert der
application/ynd.ms-pkipko pko
application/zip zip
audio/basic au
audio/basic snd
audio/mid mid
audio/mid rmi
audio/mpeg mp3
audio/x-aiff aif
audio/x-aiff aifc
audio/x-aiff aiff
audio/x-mpegurl m3u
audio/x-pn-realaudio ra
audio/x-pn-realaudio ram
audio/x-wav wav
image/bmp bmp
image/cis-cod cod
image/gif gif
image/ief ief
image/jpeg jpe
image/jpeg jpeg
image/jpeg jpg
image/pipeg jfif
image/svg+xml svg
image/tiff tif
image/tiff tiff
image/x-cmu-raster ras
image/x-cmx cmx
image/x-icon ico
image/x-portable-anymap pnm
image/x-portable-bitmap pbm
image/x-portable-graymap pgm
image/x-portable-pixmap ppm
image/x-rgb rgb
image/x-xbitmap xbm
image/x-xpixmap xpm
image/x-xwindowdump xwd
message/rfc822 mht
message/rfc822 mhtml
message/rfc822 nws
text/css css
text/h323 323
text/html htm
text/html html
text/html stm
text/iuls uls
text/plain bas
text/plain c
text/plain h
text/plain txt
text/richtext rtx
text/scriptlet sct
text/tab-separated-values tsv
text/webviewhtml htt
text/x-component htc
text/x-setext etx
text/x-vcard vcf
video/mpeg mp2
video/mpeg mpa
video/mpeg mpe
video/mpeg mpeg
video/mpeg mpg
video/mpeg mpv2
video/quicktime mov
video/quicktime qt
video/x-la-asf lsf
video/x-la-asf lsx
video/x-ms-asf asf
video/x-ms-asf asr
video/x-ms-asf asx
video/x-msvideo avi
video/x-sgi-movie movie
x-world/x-vrml flr
x-world/x-vrml vrml
x-world/x-vrml wrl
x-world/x-vrml wrz
x-world/x-vrml xaf
x-world/x-vrml xof
If the mongo instance is build on the cloud.mongodb.com this error appears when the instance can work only from known IP addresses set in the IP whitelist pool when the instance was configured.
So from the mongo dashboard need to be set the current IP address on the IP whitelist from network access menu on the left.
BR,
Add bellow line in build.gradle:
compile 'com.commit451:PhotoView:1.2.4'
or
compile 'com.github.chrisbanes:PhotoView:1.3.0'
In Java file:
PhotoViewAttacher photoAttacher;
photoAttacher= new PhotoViewAttacher(Your_Image_View);
photoAttacher.update();
The answer to "Given a class, see if instance has method (Ruby)" is better. Apparently Ruby has this built-in, and I somehow missed it. My answer is left for reference, regardless.
Ruby classes respond to the methods instance_methods
and public_instance_methods
. In Ruby 1.8, the first lists all instance method names in an array of strings, and the second restricts it to public methods. The second behavior is what you'd most likely want, since respond_to?
restricts itself to public methods by default, as well.
Foo.public_instance_methods.include?('bar')
In Ruby 1.9, though, those methods return arrays of symbols.
Foo.public_instance_methods.include?(:bar)
If you're planning on doing this often, you might want to extend Module
to include a shortcut method. (It may seem odd to assign this to Module
instead of Class
, but since that's where the instance_methods
methods live, it's best to keep in line with that pattern.)
class Module
def instance_respond_to?(method_name)
public_instance_methods.include?(method_name)
end
end
If you want to support both Ruby 1.8 and Ruby 1.9, that would be a convenient place to add the logic to search for both strings and symbols, as well.
At the risk of echoing every other answer, no, you cannot mix them in the same project.
That aside, if you just finished converting VB to C#, why would you write new code in VB?
This worked for me :
e.Row.Cells["cell no "].HorizontalAlign = HorizontalAlign.Center;
But 'css text-align = center '
didn't worked for me
hope it will help you
A2 Hosting permits node.js on their shared hosting accounts. I can vouch that I've had a positive experience with them.
Here are instructions in their KnowledgeBase for installing node.js using Apache/LiteSpeed as a reverse proxy: https://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-managed-hosting-accounts . It takes about 30 minutes to set up the configuration, and it'll work with npm, Express, MySQL, etc.
See a2hosting.com.
I disagree with the document.write
technique (see suggestion of Vahan Margaryan). I like document.getElementsByTagName('head')[0].appendChild(...)
(see suggestion of Matt Ball), but there is one important issue: the script execution order.
Recently, I have spent a lot of time reproducing one similar issue, and even the well-known jQuery plugin uses the same technique (see src here) to load the files, but others have also reported the issue. Imagine you have JavaScript library which consists of many scripts, and one loader.js
loads all the parts. Some parts are dependent on one another. Imagine you include another main.js
script per <script>
which uses the objects from loader.js
immediately after the loader.js
. The issue was that sometimes main.js
is executed before all the scripts are loaded by loader.js
. The usage of $(document).ready(function () {/*code here*/});
inside of main.js
script does not help. The usage of cascading onload
event handler in the loader.js
will make the script loading sequential instead of parallel, and will make it difficult to use main.js
script, which should just be an include somewhere after loader.js
.
By reproducing the issue in my environment, I can see that **the order of execution of the scripts in Internet Explorer 8 can differ in the inclusion of the JavaScript*. It is a very difficult issue if you need include scripts that are dependent on one another. The issue is described in Loading Javascript files in parallel, and the suggested workaround is to use document.writeln
:
document.writeln("<script type='text/javascript' src='Script1.js'></script>");
document.writeln("<script type='text/javascript' src='Script2.js'></script>");
So in the case of "the scripts are downloaded in parallel but executed in the order they're written to the page", after changing from document.getElementsByTagName('head')[0].appendChild(...)
technique to document.writeln
, I had not seen the issue anymore.
So I recommend that you use document.writeln
.
UPDATED: If somebody is interested, they can try to load (and reload) the page in Internet Explorer (the page uses the document.getElementsByTagName('head')[0].appendChild(...)
technique), and then compare with the fixed version used document.writeln
. (The code of the page is relatively dirty and is not from me, but it can be used to reproduce the issue).
see this page Entity Framework and AsNoTracking
Entity Framework exposes a number of performance tuning options to help you optimise the performance of your applications. One of these tuning options is .AsNoTracking()
. This optimisation allows you to tell Entity Framework
not to track the results of a query. This means that Entity Framework
performs no additional processing or storage of the entities which are returned by the query. However, it also means that you can't update these entities without reattaching them to the tracking graph.
there are significant performance gains to be had by using AsNoTracking
Here's an alternate
req.hostname
Read about it in the Express Docs.
In Rails 4 you can add to a specific model:
def self.update_or_create(attributes)
assign_or_new(attributes).save
end
def self.assign_or_new(attributes)
obj = first || new
obj.assign_attributes(attributes)
obj
end
and use it like
User.where(email: "[email protected]").update_or_create(name: "Mr A Bbb")
Or if you'd prefer to add these methods to all models put in an initializer:
module ActiveRecordExtras
module Relation
extend ActiveSupport::Concern
module ClassMethods
def update_or_create(attributes)
assign_or_new(attributes).save
end
def update_or_create!(attributes)
assign_or_new(attributes).save!
end
def assign_or_new(attributes)
obj = first || new
obj.assign_attributes(attributes)
obj
end
end
end
end
ActiveRecord::Base.send :include, ActiveRecordExtras::Relation
if it's not a foreign key field, not using empty strings could save you some trouble. only allow nulls if you'll take null to mean something different than an empty string. for example if you have a password field, a null value could indicate that a new user has not created his password yet while an empty varchar could indicate a blank password. for a field like "address2" allowing nulls can only make life difficult. things to watch out for include null references and unexpected results of = and <> operators mentioned by Vagif Verdi, and watching out for these things is often unnecessary programmer overhead.
edit: if performance is an issue see this related question: Nullable vs. non-null varchar data types - which is faster for queries?
You can use hh
to tell printf
that the argument is an unsigned char. Use 0
to get zero padding and 2
to set the width to 2. x
or X
for lower/uppercase hex characters.
uint8_t a = 0x0a;
printf("%02hhX", a); // Prints "0A"
printf("0x%02hhx", a); // Prints "0x0a"
Edit: If readers are concerned about 2501's assertion that this is somehow not the 'correct' format specifiers I suggest they read the printf
link again. Specifically:
Even though %c expects int argument, it is safe to pass a char because of the integer promotion that takes place when a variadic function is called.
The correct conversion specifications for the fixed-width character types (int8_t, etc) are defined in the header
<cinttypes>
(C++) or<inttypes.h>
(C) (although PRIdMAX, PRIuMAX, etc is synonymous with %jd, %ju, etc).
As for his point about signed vs unsigned, in this case it does not matter since the values must always be positive and easily fit in a signed int. There is no signed hexideximal format specifier anyway.
Edit 2: ("when-to-admit-you're-wrong" edition):
If you read the actual C11 standard on page 311 (329 of the PDF) you find:
hh: Specifies that a following
d
,i
,o
,u
,x
, orX
conversion specifier applies to asigned char
orunsigned char
argument (the argument will have been promoted according to the integer promotions, but its value shall be converted tosigned char
orunsigned char
before printing); or that a followingn
conversion specifier applies to a pointer to asigned char
argument.
FINALLY THE BEST WAY WORKED PERFECTLY FOR ME
None of the solutions in this page worked for me EXCEPT THE FOLLOWING
Below the comment sections of the second answer, try the following :
Adding to my above comment, Task Manager does not display the filename.exe process but Resource Monitor does, so I'm able to kill it from there which solves the issue without having to reboot. – A__ Jun 19 '19 at 21:23
Just my five cents worth. If the object of this is to stop 99% of robots which sounds pretty good, and if 99% of robots can't run Java-script the best solution that beats all is simply to not use a form that has an action of submit with a post URL.
If the form is controlled via java-script and the java-script collects the form data and then sends it via a HTTP request, no robot can submit the form. Since the submit button would use Java-script to run the code that sends the form.
If the author has a GitHub account, just click the author's username from anywhere in the commit history, and the commits you can see will be filtered down to those by that author:
You can also click the 'n commits' link below their name on the repo's "contributors" page:
Alternatively, you can directly append ?author=<theusername>
or ?author=<emailaddress>
to the URL. For example, https://github.com/jquery/jquery/commits/master?author=dmethvin or https://github.com/jquery/jquery/commits/[email protected] both give me:
For authors without a GitHub account, only filtering by email address will work, and you will need to manually add ?author=<emailaddress>
to the URL - the author's name will not be clickable from the commits list.
You can also get the list of commits by a particular author from the command line using
git log --author=[your git name]
Example:
git log --author=Prem
You have to use the JSON.stringify()
function included with the V8 engine that node uses.
var objToJson = { ... };
response.write(JSON.stringify(objToJson));
Edit: As far as I know, IANA has officially registered a MIME type for JSON as application/json
in RFC4627. It is also is listed in the Internet Media Type list here.
Use ClassLoader#getResource()
instead if its URI represents a valid local disk file system path.
URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...
If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.
Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...
That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream
instead of InputStream
. If you can, just fix the API to ask for an InputStream
instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.
Try to combine the query, it will run much faster than executing an additional query per row. Ik don't like the string[] you're using, i would create a class for holding the information.
public List<string[]> get_dados_historico_verificacao_email_WEB(string email)
{
List<string[]> historicos = new List<string[]>();
using (SqlConnection conexao = new SqlConnection("ConnectionString"))
{
string sql =
@"SELECT *,
( SELECT COUNT(e.cd_historico_verificacao_email)
FROM emails_lidos e
WHERE e.cd_historico_verificacao_email = a.nm_email ) QT
FROM historico_verificacao_email a
WHERE nm_email = @email
ORDER BY dt_verificacao_email DESC,
hr_verificacao_email DESC";
using (SqlCommand com = new SqlCommand(sql, conexao))
{
com.Parameters.Add("email", SqlDbType.VarChar).Value = email;
SqlDataReader dr = com.ExecuteReader();
while (dr.Read())
{
string[] dados_historico = new string[6];
dados_historico[0] = dr["nm_email"].ToString();
dados_historico[1] = dr["dt_verificacao_email"].ToString();
dados_historico[1] = dados_historico[1].Substring(0, 10);
//System.Windows.Forms.MessageBox.Show(dados_historico[1]);
dados_historico[2] = dr["hr_verificacao_email"].ToString();
dados_historico[3] = dr["ds_tipo_verificacao"].ToString();
dados_historico[4] = dr["QT"].ToString();
dados_historico[5] = dr["cd_login_usuario"].ToString();
historicos.Add(dados_historico);
}
}
}
return historicos;
}
Untested, but maybee gives some idea.
Here is what worked for me. First dump to a file:
pg_dump -h localhost -U myuser -C -t my_table -d first_db>/tmp/table_dump
then load the dumped file:
psql -U myuser -d second_db</tmp/table_dump
You can force gcc to output directly to assembly code by adding the -S switch
gcc -S hello.c
@dapangmao's answer works, but it doesn't give the regular spark RDD, it returns a Row object. If you want to have the regular RDD format.
Try this:
rdd = df.rdd.map(tuple)
or
rdd = df.rdd.map(list)