You can still delete the file programmatically, using the NSFileManager:removeItemAtPath:: method.
NSPersistentStore *store = ...;
NSError *error;
NSURL *storeURL = store.URL;
NSPersistentStoreCoordinator *storeCoordinator = ...;
[storeCoordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];
Then, just add the persistent store back to ensure it is recreated properly.
The programmatic way for iterating through each entity is both slower and prone to error. The use for doing it that way is if you want to delete some entities and not others. However you still need to make sure you retain referential integrity or you won't be able to persist your changes.
Just removing the store and recreating it is both fast and safe, and can certainly be done programatically at runtime.
Update for iOS5+
With the introduction of external binary storage (allowsExternalBinaryDataStorage or Store in External Record File) in iOS 5 and OS X 10.7, simply deleting files pointed by storeURLs is not enough. You'll leave the external record files behind. Since the naming scheme of these external record files is not public, I don't have a universal solution yet. – an0 May 8 '12 at 23:00
How to explain callbacks in plain English?
In plain English, a callback function is like a Worker who "calls back" to his Manager when he has completed a Task.
How are they different from calling one function from another function taking some context from the calling function?
It is true that you are calling a function from another function, but the key is that the callback is treated like an Object, so you can change which Function to call based on the state of the system (like the Strategy Design Pattern).
How can their power be explained to a novice programmer?
The power of callbacks can easily be seen in AJAX-style websites which need to pull data from a server. Downloading the new data may take some time. Without callbacks, your entire User Interface would "freeze up" while downloading the new data, or you would need to refresh the entire page rather than just part of it. With a callback, you can insert a "now loading" image and replace it with the new data once it is loaded.
function grabAndFreeze() {
showNowLoading(true);
var jsondata = getData('http://yourserver.com/data/messages.json');
/* User Interface 'freezes' while getting data */
processData(jsondata);
showNowLoading(false);
do_other_stuff(); // not called until data fully downloaded
}
function processData(jsondata) { // do something with the data
var count = jsondata.results ? jsondata.results.length : 0;
$('#counter_messages').text(['Fetched', count, 'new items'].join(' '));
$('#results_messages').html(jsondata.results || '(no new messages)');
}
Here is an example with a callback, using jQuery's getJSON:
function processDataCB(jsondata) { // callback: update UI with results
showNowLoading(false);
var count = jsondata.results ? jsondata.results.length : 0;
$('#counter_messages').text(['Fetched', count, 'new items'].join(' '));
$('#results_messages').html(jsondata.results || '(no new messages)');
}
function grabAndGo() { // and don't freeze
showNowLoading(true);
$('#results_messages').html(now_loading_image);
$.getJSON("http://yourserver.com/data/messages.json", processDataCB);
/* Call processDataCB when data is downloaded, no frozen User Interface! */
do_other_stuff(); // called immediately
}
Often the callback needs to access state
from the calling function using a closure
, which is like the Worker needing to get information from the Manager before he can complete his Task. To create the closure
, you can inline the function so it sees the data in the calling context:
/* Grab messages, chat users, etc by changing dtable. Run callback cb when done.*/
function grab(dtable, cb) {
if (null == dtable) { dtable = "messages"; }
var uiElem = "_" + dtable;
showNowLoading(true, dtable);
$('#results' + uiElem).html(now_loading_image);
$.getJSON("http://yourserver.com/user/"+dtable+".json", cb || function (jsondata) {
// Using a closure: can "see" dtable argument and uiElem variables above.
var count = jsondata.results ? jsondata.results.length : 0,
counterMsg = ['Fetched', count, 'new', dtable].join(' '),
// no new chatters/messages/etc
defaultResultsMsg = ['(no new ', dtable, ')'].join('');
showNowLoading(false, dtable);
$('#counter' + uiElem).text(counterMsg);
$('#results'+ uiElem).html(jsondata.results || defaultResultsMsg);
});
/* User Interface calls cb when data is downloaded */
do_other_stuff(); // called immediately
}
// update results_chatters when chatters.json data is downloaded:
grab("chatters");
// update results_messages when messages.json data is downloaded
grab("messages");
// call myCallback(jsondata) when "history.json" data is loaded:
grab("history", myCallback);
Finally, here is a definition of closure
from Douglas Crockford:
Functions can be defined inside of other functions. The inner function has access to the vars and parameters of the outer function. If a reference to an inner function survives (for example, as a callback function), the outer function's vars also survive.
See also:
I was able to Do it using the U (Underline Tag)
u {
text-decoration: none;
position: relative;
}
u:after {
content: '';
width: 100%;
position: absolute;
left: 0;
bottom: 1px;
border-width: 0 0 1px;
border-style: solid;
}
<a href="" style="text-decoration:none">
<div style="text-align: right; color: Red;">
<u> Shop Now</u>
</div>
</a>
The solution of creating a new HTML file with HTML (Web Forms) Designer worked for that file but not for other, individual HTML files that I wanted to edit.
I did find the Open With option in the Open File dialogue and was able to select the HTML (Web Forms) Editor there. Having clicked the "Set as Default" option in that window, VS then remembered to use that editor when I opened other HTML files.
result_array()
is faster,
result()
is easier
Rather than finding which version you are using you can rephrase your question to "which version of ECMA script does my browser's JavaScript/JSscript engine conform to".
For IE :
alert(@_jscript_version); //IE
Refer Squeegy's answer for non-IE versions :)
In my case it was because of my 4K screen too thin to read. Then u need to change from monospace In my case it was because of my 4K screen too thin to read. Then u need to change from Monospaced to Consolas.
Settings --> Color Scheme Font --> Font --> Consolas
class BankAccount:
def __init__(self, balance=0):
self.balance = int(balance)
def checkBalance(self): ## Checking opening balance....
return self.balance
def deposit(self, deposit_amount=1000): ## takes in cash deposit amount and updates the balance accordingly.
self.deposit_amount = deposit_amount
self.balance += deposit_amount
return self.balance
def withdraw(self, withdraw_amount=500): ## takes in cash withdrawal amount and updates the balance accordingly
if self.balance < withdraw_amount: ## if amount is greater than balance return `"invalid transaction"`
return 'invalid transaction'
else:
self.balance -= withdraw_amount
return self.balance
class MinimumBalanceAccount(BankAccount): #subclass MinimumBalanceAccount of the BankAccount class
def __init__(self,balance=0, minimum_balance=500):
BankAccount.__init__(self, balance=0)
self.minimum_balance = minimum_balance
self.balance = balance - minimum_balance
#print "Subclass MinimumBalanceAccount of the BankAccount class created!"
def MinimumBalance(self):
return self.minimum_balance
c = BankAccount()
print(c.deposit(50))
print(c.withdraw(10))
b = MinimumBalanceAccount(100, 50)
print(b.deposit(50))
print(b.withdraw(10))
print(b.MinimumBalance())
Update 2019/05 Now this can be done in the JetBrains Toolbox app. You can set it once with the Toolbox, for all of your JetBrain IDEs.
As of 2019.1 EAP, the Create Commmand Line Launcher
option is not available in the Tools menu anymore. My solution is to use the following alias in my bash/zsh profile:
Make sure that you run chmod -x ...../pycharm
to make the binary executable.
# in your ~/.profile or other rc file to the effect.
alias pycharm="open -a '$(ls -r /Users/geyang/Library/Application\ Support/JetBrains/Toolbox/apps/PyCharm-P/**/PyCharm*.app/Contents/MacOS/pycharm)'"
The syntax you used is problematic. In html, an attribute (ex: style) has a value delimited by double quotes. In that case, the value of the style attribute is a css list of selectors. Try this:
<h2 style="text-align:center; font-family:tahoma">TITLE</h2>
Yes, there is a way to emulate max-width
using a table, thus giving you both responsive and Outlook-friendly layout. What's more, this solution doesn't require conditional comments.
Suppose you want the equivalent of a centered div
with max-width
of 350px
. You create a table, set the width to 100%
. The table has three cells in a row. Set the width of the center TD
to 350
(using the HTML width
attribute, not CSS), and there you go.
If you want your content aligned left instead of centered, just leave out the first empty cell.
Example:
<table border="0" cellspacing="0" width="100%">
<tr>
<td></td>
<td width="350">The width of this cell should be a maximum of
350 pixels, but shrink to widths less than 350 pixels.
</td>
<td></td>
</tr>
</table>
In the jsfiddle I give the table a border so you can see what's going on, but obviously you wouldn't want one in real life:
This simple method solved the problem for me: Copy the content of your dataset, open an empty Excel sheet, choose "Paste Special" -> "Values", and save. Import the new file instead.
(I tried all the existing solutions, and none worked for me. My old dataset appeared to have no missing values, space, special characters, or embedded formulas.)
Without less, ans simply for a given div :
In a css :
.footer {
background-color: #ab0000;
padding-top: 40px;
padding-bottom: 10px;
border-radius:5px;
}
In html :
<div class="footer">
<p>blablabla</p>
</div>
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
http://sfml-dev.org/documentation/2.0/classsf_1_1Music.php
SFML does not have mp3 support as another has suggested. What I always do is use Audacity and make all my music into ogg, and leave all my sound effects as wav.
Loading and playing a wav is simple (crude example):
http://www.sfml-dev.org/tutorials/2.0/audio-sounds.php
#include <SFML/Audio.hpp>
...
sf::SoundBuffer buffer;
if (!buffer.loadFromFile("sound.wav")){
return -1;
}
sf::Sound sound;
sound.setBuffer(buffer);
sound.play();
Streaming an ogg music file is also simple:
#include <SFML/Audio.hpp>
...
sf::Music music;
if (!music.openFromFile("music.ogg"))
return -1; // error
music.play();
Insert Into FEMALE(ID, Image)
Select '1', BulkColumn
from Openrowset (Bulk 'D:\thepathofimage.jpg', Single_Blob) as Image
You will also need admin rights to run the query.
On this page, the Arduino sketch defines a couple of Structs (plus a couple of methods) which are then called in the setup loop and main loop. Simple enough to interpret, even for a barely-literate programmer like me.
Simple function to alert contents of an object or an array .
Call this function with an array or string or an object it alerts the contents.
Function
function print_r(printthis, returnoutput) {
var output = '';
if($.isArray(printthis) || typeof(printthis) == 'object') {
for(var i in printthis) {
output += i + ' : ' + print_r(printthis[i], true) + '\n';
}
}else {
output += printthis;
}
if(returnoutput && returnoutput == true) {
return output;
}else {
alert(output);
}
}
Usage
var data = [1, 2, 3, 4];
print_r(data);
You must hide AppBarLayout
before scrollToPosition
if you are using him
Can't instantiate an interface but there are few implementations:
JDK2
List<String> list = Arrays.asList("one", "two", "three");
JDK7
//diamond operator
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
JDK8
List<String> list = Stream.of("one", "two", "three").collect(Collectors.toList());
JDK9
// creates immutable lists, so you can't modify such list
List<String> immutableList = List.of("one", "two", "three");
// if we want mutable list we can copy content of immutable list
// to mutable one for instance via copy-constructor (which creates shallow copy)
List<String> mutableList = new ArrayList<>(List.of("one", "two", "three"));
Plus there are lots of other ways supplied by other libraries like Guava.
List<String> list = Lists.newArrayList("one", "two", "three");
You can use an index in a range and then access the array via its index:
<ul>
<li v-for="index in 10" :key="index">
{{ shoppingItems[index].name }} - {{ shoppingItems[index].price }}
</li>
</ul>
You can also check the Official Documentation for more information.
How it works: It is a variable that can store another pointer.
When would you use them : Many uses one of them is if your function wants to construct an array and return it to the caller.
//returns the array of roll nos {11, 12} through paramater
// return value is total number of students
int fun( int **i )
{
int *j;
*i = (int*)malloc ( 2*sizeof(int) );
**i = 11; // e.g., newly allocated memory 0x2000 store 11
j = *i;
j++;
*j = 12; ; // e.g., newly allocated memory 0x2004 store 12
return 2;
}
int main()
{
int *i;
int n = fun( &i ); // hey I don't know how many students are in your class please send all of their roll numbers.
for ( int j=0; j<n; j++ )
printf( "roll no = %d \n", i[j] );
return 0;
}
It's not a direct answer to the question, however I would suggest in most cases to simply set multiple classes to each element:
<div class="myclass one"></div>
<div class="myclass two></div>
<div class="myclass three"></div>
In this way you can set rules for all myclass
elements and then more specific rules for one
, two
and three
.
.myclass { color: #f00; }
.two { font-weight: bold; }
etc.
I often ended up doing things like this. Therefore I tried to write a simple function that 'snips' out the unwanted elements in an easy way. This turns matlab logic a bit upside down, but looks good:
b = snip(a,'0')
you can find the function file at: http://www.mathworks.co.uk/matlabcentral/fileexchange/41941-snip-m-snip-elements-out-of-vectorsmatrices
It also works with all other 'x', nan or whatever elements.
It's better to create a new factor variable using cut(). I've added a few options using ggplot2 also.
df <- data.frame(
X1=seq(0, 5, by=0.001),
X2=rnorm(df$X1, mean = 3.5, sd = 1.5)
)
# Create new variable for plotting
df$Colour <- cut(df$X2, breaks = c(-Inf, 1, 3, +Inf),
labels = c("low", "medium", "high"),
right = FALSE)
### Base Graphics
plot(df$X1, df$X2,
col = df$Colour, ylim = c(0, 10), xlab = "POS",
ylab = "CS", main = "Plot Title", pch = 21)
plot(df$X1,df$X2,
col = df$Colour, ylim = c(0, 10), xlab = "POS",
ylab = "CS", main = "Plot Title", pch = 19, cex = 0.5)
# Using `with()`
with(df,
plot(X1, X2, xlab="POS", ylab="CS", col = Colour, pch=21, cex=1.4)
)
# Using ggplot2
library(ggplot2)
# qplot()
qplot(df$X1, df$X2, colour = df$Colour)
# ggplot()
p <- ggplot(df, aes(X1, X2, colour = Colour))
p <- p + geom_point() + xlab("POS") + ylab("CS")
p
p + facet_grid(Colour~., scales = "free")
ok, after 5 years have passed....
if discount.try :nonzero?
...
end
It's important to note that try
is defined in the ActiveSupport gem, so it is not available in plain ruby.
My solution is a bit funny.I never thought that would it be as easy as save as with UTF-8 codec.I'm using notepad++(v5.6.8).I didn't notice that I saved it with ANSI codec initially. I'm using separate file to place all localized dictionary. I found my solution under 'Encoding' tab from my Notepad++.I select 'Encoding in UTF-8 without BOM' and save it. It works brilliantly.
Try like this..
NameVirtualHost *:80
<VirtualHost *:80>
ServerAdmin [email protected]
ServerName www.cmsplus.dev
ServerAlias cmsplus.dev
DocumentRoot /var/www/cmsplus.dev/public
LogLevel warn
ErrorLog /var/www/cmsplus.dev/log/error.log
CustomLog /var/www/cmsplus.dev/log/access.log combined
</VirtualHost>
and add entry in /etc/hosts
127.0.0.1 www.cmsplus.dev
restart apache..
Here's the simple function with correct typing I use
/**
* Helper to produce an array of enum values.
* @param enumeration Enumeration object.
*/
export function enumToArray<T, G extends keyof T = keyof T>(enumeration: T): T[G][] {
// tslint:disable: comment-format
// enum Colors {
// WHITE = 0,
// BLACK = 1,
// }
// Object.values(Colors) will produce ['WHITE', 'BLACK', 0, 1]
// So, simply slice the second half
const enumValues = Object.values(enumeration);
return enumValues.slice(enumValues.length / 2, enumValues.length) as T[G][];
}
Usage example:
enum Colors {
Red = 1,
Blue = 2,
}
enumToArray(Colors)
Console applications will exit when the main function has finished running. A "return" will achieve this.
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("I'm running!");
return; //This will exit the console application's running thread
}
}
If you're returning an error code you can do it this way, which is accessible from functions outside of the initial thread:
System.Environment.Exit(-1);
sudo apt-get install msttcorefonts
works (on our Ubuntu development environment), but is not a very good solution.
Instead, we bundled the fonts with our application based on this tip. Their JAR file bundles the following fonts,
Direct Link to download jar: Maven ver 1.0. DynamicFonts
declare function in global scope with window
first.js
window.fn1 = function fn1() {
alert("external fn clicked");
}
second.js
document.getElementById("btn").onclick = function() {
fn1();
}
include like this
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
In your script you can add the following to the lines that you know are going to give an output:
some_code 2>>/dev/null
Or else you can also try
some_code >>/dev/null
Note that you must use asynchronous calls for spinners to work (at least that is what caused mine to not show until after the ajax call and then swiftly went away as the call had finished and removed the spinner).
$.ajax({
url: requestUrl,
data: data,
dataType: 'JSON',
processData: false,
type: requestMethod,
async: true, <<<<<<------ set async to true
accepts: 'application/json',
contentType: 'application/json',
success: function (restResponse) {
// something here
},
error: function (restResponse) {
// something here
}
});
In case you have a local variable with the same name, you might want to use the globals()
function.
globals()['your_global_var'] = 42
mosquitto.org is very active (at the time of this posting). This is a nice smoke test for a MQTT subscriber linux device:
mosquitto_sub -h test.mosquitto.org -t "#" -v
The "#" is a wildcard for topics and returns all messages (topics): the server had a lot of traffic, so it returned a 'firehose' of messages.
If your MQTT device publishes a topic of irisys/V4D-19230005/
to the test MQTT broker , then you could filter the messages:
mosquitto_sub -h test.mosquitto.org -t "irisys/V4D-19230005/#" -v
Options:
>>> import subprocess
>>> cmd = [ 'echo', 'arg1', 'arg2' ]
>>> output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
>>> print output
arg1 arg2
>>>
There is a bug in using of the subprocess.PIPE. For the huge output use this:
import subprocess
import tempfile
with tempfile.TemporaryFile() as tempf:
proc = subprocess.Popen(['echo', 'a', 'b'], stdout=tempf)
proc.wait()
tempf.seek(0)
print tempf.read()
On Android Studio 0.5.8 I managed to change my icon set by right clicking on the 'res' folder and selecting New > Image Asset. This brings you to the icon screen you are presented when creating the application, here after you change the icon it confirms that it will replace all the icons. Confirm and done.
Though using find
command can be useful here, the shell itself provides options to achieve this requirement without any third party tools. The bash
shell provides an extended glob support option using which you can get the file names under recursive paths that match with the extensions you want.
The extended option is extglob
which needs to be set using the shopt
option as below. The options are enabled with the -s
support and disabled with he -u
flag. Additionally you could use couple of options more i.e. nullglob
in which an unmatched glob is swept away entirely, replaced with a set of zero words. And globstar
that allows to recurse through all the directories
shopt -s extglob nullglob globstar
Now all you need to do is form the glob expression to include the files of a certain extension which you can do as below. We use an array to populate the glob results because when quoted properly and expanded, the filenames with special characters would remain intact and not get broken due to word-splitting by the shell.
For example to list all the *.csv
files in the recursive paths
fileList=(**/*.csv)
The option **
is to recurse through the sub-folders and *.csv
is glob expansion to include any file of the extensions mentioned. Now for printing the actual files, just do
printf '%s\n' "${fileList[@]}"
Using an array and doing a proper quoted expansion is the right way when used in shell scripts, but for interactive use, you could simply use ls
with the glob expression as
ls -1 -- **/*.csv
This could very well be expanded to match multiple files i.e. file ending with multiple extension (i.e. similar to adding multiple flags in find
command). For example consider a case of needing to get all recursive image files i.e. of extensions *.gif
, *.png
and *.jpg
, all you need to is
ls -1 -- **/+(*.jpg|*.gif|*.png)
This could very well be expanded to have negate results also. With the same syntax, one could use the results of the glob to exclude files of certain type. Assume you want to exclude file names with the extensions above, you could do
excludeResults=()
excludeResults=(**/!(*.jpg|*.gif|*.png))
printf '%s\n' "${excludeResults[@]}"
The construct !()
is a negate operation to not include any of the file extensions listed inside and |
is an alternation operator just as used in the Extended Regular Expressions library to do an OR match of the globs.
Note that these extended glob support is not available in the POSIX bourne shell and its purely specific to recent versions of bash
. So if your are considering portability of the scripts running across POSIX and bash
shells, this option wouldn't be right.
Use Regular expression to validate it.
isDate('2018-08-01T18:30:00.000Z');
isDate(_date){
const _regExp = new RegExp('^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$');
return _regExp.test(_date);
}
I think ./gradlew tasks
is same with Android studio sync
. Why? I will explain it.
I meet a problem when I test jacoco coverage report. When I run ./gradlew clean :Test:testDebugUnitTest
in command line directly , error appear.
Error opening zip file or JAR manifest missing : build/tmp/expandedArchives/org.jacoco.agent-0.8.2.jar_5bdiis3s7lm1rcnv0gawjjfxc/jacocoagent.jar
However, if I click android studio sync firstly , it runs OK. Because the build/../jacocoagent.jar
appear naturally.
I dont know why, maybe there is bug in jacoco plugin. Unit I find running .gradlew tasks
makes the jar appear as well. So I can get the same result in gralde script.
Besides, gradle --recompile-scripts
does not work for the problem.
There's an idea to subclass the Popen class and extend it with some simple method decorators. Let's call it ExpirablePopen.
from logging import error
from subprocess import Popen
from threading import Event
from threading import Thread
class ExpirablePopen(Popen):
def __init__(self, *args, **kwargs):
self.timeout = kwargs.pop('timeout', 0)
self.timer = None
self.done = Event()
Popen.__init__(self, *args, **kwargs)
def __tkill(self):
timeout = self.timeout
if not self.done.wait(timeout):
error('Terminating process {} by timeout of {} secs.'.format(self.pid, timeout))
self.kill()
def expirable(func):
def wrapper(self, *args, **kwargs):
# zero timeout means call of parent method
if self.timeout == 0:
return func(self, *args, **kwargs)
# if timer is None, need to start it
if self.timer is None:
self.timer = thr = Thread(target=self.__tkill)
thr.daemon = True
thr.start()
result = func(self, *args, **kwargs)
self.done.set()
return result
return wrapper
wait = expirable(Popen.wait)
communicate = expirable(Popen.communicate)
if __name__ == '__main__':
from subprocess import PIPE
print ExpirablePopen('ssh -T [email protected]', stdout=PIPE, timeout=1).communicate()
Using reshape2
and dplyr
. Your data:
df <- read.table(text=
"tea coke beer water gender
14.55 26.50793651 22.53968254 40 1
24.92997199 24.50980392 26.05042017 24.50980393 2
23.03732304 30.63063063 25.41827542 20.91377091 1
225.51781276 24.6064623 24.85501243 50.80645161 1
24.53662842 26.03706973 25.24271845 24.18358341 2", header=TRUE)
Getting data into correct form:
library(reshape2)
library(dplyr)
df.melt <- melt(df, id="gender")
bar <- group_by(df.melt, variable, gender)%.%summarise(mean=mean(value))
Plotting:
library(ggplot2)
ggplot(bar, aes(x=variable, y=mean, fill=factor(gender)))+
geom_bar(position="dodge", stat="identity")
Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.
Create two string data type variables namely DirPath
and FilePath
. Set the value C:\backup\ to the variable DirPath
. Do not set any value to the variable FilePath
.
Select the variable FilePath
and select F4 to view the properties. Set the EvaluateAsExpression
property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)
You could set the width of the abbrev column to a fixed pixel width, then set the width of the description column to the width of the DataGridView, minus the sum of the widths of the other columns and some extra margin (if you want to prevent a horizontal scrollbar from appearing on the DataGridView):
dataGridView1.Columns[1].Width = 108; // or whatever width works well for abbrev
dataGridView1.Columns[2].Width =
dataGridView1.Width
- dataGridView1.Columns[0].Width
- dataGridView1.Columns[1].Width
- 72; // this is an extra "margin" number of pixels
If you wanted the description column to always take up the "remainder" of the width of the DataGridView, you could put something like the above code in a Resize
event handler of the DataGridView.
Looks like your style has been sanitized, to bypass it try using bypassSecurityTrustStyle method from DomSanitizer.
import { Component, OnInit, Input } from '@angular/core';_x000D_
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';_x000D_
_x000D_
@Component({_x000D_
selector: 'my-component',_x000D_
templateUrl: './my-component.component.html',_x000D_
styleUrls: ['./my-component.component.scss']_x000D_
})_x000D_
_x000D_
export class MyComponent implements OnInit {_x000D_
_x000D_
public backgroundImg: SafeStyle;_x000D_
@Input() myObject: any;_x000D_
_x000D_
constructor(private sanitizer: DomSanitizer) {}_x000D_
_x000D_
ngOnInit() {_x000D_
this.backgroundImg = this.sanitizer.bypassSecurityTrustStyle('url(' + this.myObject.ImageUrl + ')');_x000D_
}_x000D_
_x000D_
}
_x000D_
<div *ngIf="backgroundImg.length > 0" [style.background-image]="backgroundImg"></div>
_x000D_
What exactly do you want to know?
The shared library soname? That's part of the filename, libstdc++.so.6
, or shown by readelf -d /usr/lib64/libstdc++.so.6 | grep soname
.
The minor revision number? You should be able to get that by simply checking what the symlink points to:
$ ls -l /usr/lib/libstdc++.so.6
lrwxrwxrwx. 1 root root 19 Mar 23 09:43 /usr/lib/libstdc++.so.6 -> libstdc++.so.6.0.16
That tells you it's 6.0.16, which is the 16th revision of the libstdc++.so.6
version, which corresponds to the GLIBCXX_3.4.16
symbol versions.
Or do you mean the release it comes from? It's part of GCC so it's the same version as GCC, so unless you've screwed up your system by installing unmatched versions of g++
and libstdc++.so
you can get that from:
$ g++ -dumpversion
4.6.3
Or, on most distros, you can just ask the package manager. On my Fedora host that's
$ rpm -q libstdc++
libstdc++-4.6.3-2.fc16.x86_64
libstdc++-4.6.3-2.fc16.i686
As other answers have said, you can map releases to library versions by checking the ABI docs
Go to the page from where you want to access the App_code class, and then add the namespace of the app_code class. You need to provide a using
statement, as follows:
using WebApplication3.App_Code;
After that, you will need to go to the app_code class property and set the 'Build Action' to 'Compile'.
User Roles can be checked using following ways:
Using call static methods in SecurityContextHolder:
Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null && auth.getAuthorities().stream().anyMatch(role -> role.getAuthority().equals("ROLE_NAME"))) { //do something}
Using HttpServletRequest
@GetMapping("/users")
public String getUsers(HttpServletRequest request) {
if (request.isUserInRole("ROLE_NAME")) {
}
_x000D_
While admittedly a bit obscure, I would say that the most typographically pleasing way of doing this is
for (int i = myArray.Length; i --> 0; )
{
//do something
}
You DO NOT NEED to replace the comma and dot..
I have had the very same problem. The reason is simple, the conversion culture plays a big role in which the comma or a dot is interpreted. I use a German culture where the comma distinguish the fractions, where as elsewhere the dot does the job.
Here I made a complete example to make the difference clear.
string[] doubleStrings = {"hello", "0.123", "0,123"};
double localCultreResult;
foreach (var doubleString in doubleStrings)
{
double.TryParse(doubleString, NumberStyles.Any, CultureInfo.CurrentCulture, out localCultreResult);
Console.WriteLine(string.Format("Local culture results for the parsing of {0} is {1}", doubleString, localCultreResult));
}
double invariantCultureResult;
foreach (var doubleString in doubleStrings)
{
double.TryParse(doubleString, NumberStyles.Any, CultureInfo.InvariantCulture, out invariantCultureResult);
Console.WriteLine(string.Format("Invariant culture results for the parsing of {0} is {1}", doubleString, invariantCultureResult));
}
The results is the following:
Play around with the culture and you will get the result you need.
There are two ways. In case of doubt, you can always just try it. If it does not work, you can add extra braces to make sure, like that:
if not ((u0 <= u) and (u < u0+step)):
An expansion on Eran's answer that was the top answer, if you have a bunch of layers of lists, you can keep flatmapping them.
This also comes with a handy way of filtering as you go down the layers if needed as well.
So for example:
List<List<List<List<List<List<Object>>>>>> multiLayeredList = ...
List<Object> objectList = multiLayeredList
.stream()
.flatmap(someList1 -> someList1
.stream()
.filter(...Optional...))
.flatmap(someList2 -> someList2
.stream()
.filter(...Optional...))
.flatmap(someList3 -> someList3
.stream()
.filter(...Optional...))
...
.collect(Collectors.toList())
This is would be similar in SQL to having SELECT statements within SELECT statements.
1.Generate a war file from your application
2. open tomcat manager, go down the page
3. Click on browse to deploy the war.
4. choose your war file.
There you go!
For the record, none of the aforementioned Git Python libraries seem to contain a "git status" equivalent, which is really the only thing I would want since dealing with the rest of the git commands via subprocess is so easy.
Java and Kotlin runs on Java Virtual Machine (JVM).
Converting a Kotlin file to Java file involves two steps i.e. compiling the Kotlin code to the JVM bytecode and then decompile the bytecode to the Java code.
Steps to convert your Kotlin source file to Java source file:
After @SedatKapanoglu comment, I am adding all my approach that works, because he was right, just using the fluent API does not work.
1- Create custom code generator and override Generate for a ColumnModel.
public class ExtendedMigrationCodeGenerator : CSharpMigrationCodeGenerator
{
protected override void Generate(ColumnModel column, IndentedTextWriter writer, bool emitName = false)
{
if (column.Annotations.Keys.Contains("Default"))
{
var value = Convert.ChangeType(column.Annotations["Default"].NewValue, column.ClrDefaultValue.GetType());
column.DefaultValue = value;
}
base.Generate(column, writer, emitName);
}
}
2- Assign the new code generator:
public sealed class Configuration : DbMigrationsConfiguration<Data.Context.EfSqlDbContext>
{
public Configuration()
{
CodeGenerator = new ExtendedMigrationCodeGenerator();
AutomaticMigrationsEnabled = false;
}
}
3- Use fluent api to created the Annotation:
public static void Configure(DbModelBuilder builder){
builder.Entity<Company>().Property(c => c.Status).HasColumnAnnotation("Default", 0);
}
As mentioned in other answers, JavaScript regexes have no support for Unicode character classes. However, there is a library that does provide this: Steven Levithan's excellent XRegExp and its Unicode plug-in.
Here are the basics. I'm not sure that any of these count as "clear and simple" though.
ps(1)
For process-level view:
$ ps -opid,vsz,rss,osz,args
PID VSZ RSS SZ COMMAND
1831 1776 1008 222 ps -opid,vsz,rss,osz,args
1782 3464 2504 433 -bash
$
vsz/VSZ: total virtual process size (kb)
rss/RSS: resident set size (kb, may be inaccurate(!), see man)
osz/SZ: total size in memory (pages)
To compute byte size from pages:
$ sz_pages=$(ps -o osz -p $pid | grep -v SZ )
$ sz_bytes=$(( $sz_pages * $(pagesize) ))
$ sz_mbytes=$(( $sz_bytes / ( 1024 * 1024 ) ))
$ echo "$pid OSZ=$sz_mbytes MB"
vmstat(1M)
$ vmstat 5 5
kthr memory page disk faults cpu
r b w swap free re mf pi po fr de sr rm s3 -- -- in sy cs us sy id
0 0 0 535832 219880 1 2 0 0 0 0 0 -0 0 0 0 402 19 97 0 1 99
0 0 0 514376 203648 1 4 0 0 0 0 0 0 0 0 0 402 19 96 0 1 99
^C
prstat(1M)
PID USERNAME SIZE RSS STATE PRI NICE TIME CPU PROCESS/NLWP
1852 martin 4840K 3600K cpu0 59 0 0:00:00 0.3% prstat/1
1780 martin 9384K 2920K sleep 59 0 0:00:00 0.0% sshd/1
...
swap(1)
"Long listing" and "summary" modes:
$ swap -l
swapfile dev swaplo blocks free
/dev/zvol/dsk/rpool/swap 256,1 16 1048560 1048560
$ swap -s
total: 42352k bytes allocated + 20192k reserved = 62544k used, 607672k available
$
top(1)
An older version (3.51) is available on the Solaris companion CD from Sun, with the disclaimer that this is "Community (not Sun) supported". More recent binary packages available from sunfreeware.com or blastwave.org.
load averages: 0.02, 0.00, 0.00; up 2+12:31:38 08:53:58
31 processes: 30 sleeping, 1 on cpu
CPU states: 98.0% idle, 0.0% user, 2.0% kernel, 0.0% iowait, 0.0% swap
Memory: 1024M phys mem, 197M free mem, 512M total swap, 512M free swap
PID USERNAME LWP PRI NICE SIZE RES STATE TIME CPU COMMAND
1898 martin 1 54 0 3336K 1808K cpu 0:00 0.96% top
7 root 11 59 0 10M 7912K sleep 0:09 0.02% svc.startd
sar(1M)
And just what's wrong with sar
? :)
The svnbook has a section on how Subversion allows you to revert the changes from a particular revision without affecting the changes that occured in subsequent revisions:
http://svnbook.red-bean.com/en/1.4/svn.branchmerge.commonuses.html#svn.branchmerge.commonuses.undo
I don't use Eclipse much, but in TortoiseSVN you can do this from the from the log dialogue; simply right-click on the revision you want to revert and select "Revert changes from this revision".
In the case that the files for which you want to revert "bad changes" had "good changes" in subsequent revisions, then the process is the same. The changes from the "bad" revision will be reverted leaving the changes from "good" revisions untouched, however you might get conflicts.
Initial Check.
1) When you are exporting the DISPLAY to other machine, ensure you entered the command xhost +
on that machine. This command allows to other machine to export their DISPLAY on this machine. There may be security constraints, just know about it. Need to check ssh -X MachineIP
will not require xhost +
?
2) Some times JCONSOLE
won't show all its process, since those JVM process may run with different user and you are exporting the DISPLAY with another user. so better follow CD_DIR>sudo ./jconsole
3) In WAS (WEBSPHERE); jconsole won't be able to connect its java server process, that time just go till the link, then try connecting it. This worked for me. May be this page is initializing some variables to enable jconsole to connect with that server.
WAS console > Application servers > server1 > Process definition > Java Virtual Machine
I have faced the same issue with AIX (where command line interface only available, There is no DISPLAY UI) machine. I resolved by installing
NX Client for Windows
Step 1: Through that Windows machine, I connected with unix box where GUI console is available.
Step 2: SSH to the AIX box from that UNIX box.
Step 3: set DISPLAY like "export DISPLAY=UNIXMACHINE:NXClientPORTConnectedMentionedOnTitle"
Step 4: Now if we launch any programs which requires DISPLAY; it will be launched on this UNIX box.
VNC
If you installed VNC on UNIX box where display is available; then Windows and NX Client is not required.
Step 1: Use VNC to connect with Unix box where GUI console is available.
Step 2: SSH to the AIX box from that UNIX box.
Step 3: set DISPLAY like "export DISPLAY=UNIXMACHINE:VNCPORT"
Step 4: Now if we launch any programs which requires DISPLAY; it will be launched on this UNIX box.
ELSE
Step 1: SSH to the AIX box from that UNIX box.
Step 2: set DISPLAY like "export DISPLAY=UNIXMACHINE:VNCPORT"
Step 3: Now if we launch any programs which requires DISPLAY; it will be launched on this UNIX box.
If you are using python3.x then Run below command
pip install mysqlclient
Then change setting.py like
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DB',
'USER': 'username',
'PASSWORD': 'passwd',
}
}
As m.edmondson mentioned, "The remote host closed the connection." occurs when a user or browser cancels something, or the network connection drops etc. It doesn't necessarily have to be a file download however, just any request for any resource that results in a response to the client. Basically the error means that the response could not be sent because the server can no longer talk to the client(browser).
There are a number of steps that you can take in order to stop it happening. If you are manually sending something in the response with a Response.Write, Response.Flush, returning data from a web servivce/page method or something similar, then you should consider checking Response.IsClientConnected before sending the response. Also, if the response is likely to take a long time or a lot of server-side processing is required, you should check this periodically until the response.end if called. See the following for details on this property:
http://msdn.microsoft.com/en-us/library/system.web.httpresponse.isclientconnected.aspx
Alternatively, which I believe is most likely in your case, the error is being caused by something inside the framework. The following link may by of use:
The following stack-overflow post might also be of interest:
"The remote host closed the connection" in Response.OutputStream.Write
It is very simple, first, you need to be inside the virtualenv you created, then to install a specific version of python say 3.5, use Anaconda, conda install python=3.5
In general you can do this for any python package you want
conda install package_name=package_version
This script will add a div that covers the entire window as the page loads. It will show a CSS-only loading spinner automatically. It will wait until the window (not the document) finishes loading, then it will wait an optional extra few seconds.
CSS loader code from https://projects.lukehaas.me/css-loaders
_x000D_
$('body').append('<div style="" id="loadingDiv"><div class="loader">Loading...</div></div>');_x000D_
$(window).on('load', function(){_x000D_
setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds._x000D_
});_x000D_
function removeLoader(){_x000D_
$( "#loadingDiv" ).fadeOut(500, function() {_x000D_
// fadeOut complete. Remove the loading div_x000D_
$( "#loadingDiv" ).remove(); //makes page more lightweight _x000D_
}); _x000D_
}
_x000D_
.loader,_x000D_
.loader:after {_x000D_
border-radius: 50%;_x000D_
width: 10em;_x000D_
height: 10em;_x000D_
}_x000D_
.loader { _x000D_
margin: 60px auto;_x000D_
font-size: 10px;_x000D_
position: relative;_x000D_
text-indent: -9999em;_x000D_
border-top: 1.1em solid rgba(255, 255, 255, 0.2);_x000D_
border-right: 1.1em solid rgba(255, 255, 255, 0.2);_x000D_
border-bottom: 1.1em solid rgba(255, 255, 255, 0.2);_x000D_
border-left: 1.1em solid #ffffff;_x000D_
-webkit-transform: translateZ(0);_x000D_
-ms-transform: translateZ(0);_x000D_
transform: translateZ(0);_x000D_
-webkit-animation: load8 1.1s infinite linear;_x000D_
animation: load8 1.1s infinite linear;_x000D_
}_x000D_
@-webkit-keyframes load8 {_x000D_
0% {_x000D_
-webkit-transform: rotate(0deg);_x000D_
transform: rotate(0deg);_x000D_
}_x000D_
100% {_x000D_
-webkit-transform: rotate(360deg);_x000D_
transform: rotate(360deg);_x000D_
}_x000D_
}_x000D_
@keyframes load8 {_x000D_
0% {_x000D_
-webkit-transform: rotate(0deg);_x000D_
transform: rotate(0deg);_x000D_
}_x000D_
100% {_x000D_
-webkit-transform: rotate(360deg);_x000D_
transform: rotate(360deg);_x000D_
}_x000D_
}_x000D_
#loadingDiv {_x000D_
position:absolute;;_x000D_
top:0;_x000D_
left:0;_x000D_
width:100%;_x000D_
height:100%;_x000D_
background-color:#000;_x000D_
}
_x000D_
This script will add a div that covers the entire window as the page loads. It will show a CSS-only loading spinner automatically. It will wait until the window (not the document) finishes loading._x000D_
_x000D_
<ul>_x000D_
<li>Works with jQuery 3, which has a new window load event</li>_x000D_
<li>No image needed but it's easy to add one</li>_x000D_
<li>Change the delay for branding or instructions</li>_x000D_
<li>Only dependency is jQuery.</li>_x000D_
</ul>_x000D_
_x000D_
Place the script below at the bottom of the body._x000D_
_x000D_
CSS loader code from https://projects.lukehaas.me/css-loaders_x000D_
_x000D_
<!-- Place the script below at the bottom of the body -->_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Here are 2 from infochimps.com:
http://www.infochimps.com/datasets/wikipedia-articles-abstract-search
http://www.infochimps.com/datasets/wikipedia-articles-title-autocomplete
this works well without any special function needed. Much easier to write with php as well. <input onclick="this.form.submit()"/>
If you come from Java/C# background I guess your best bet would be to use Eclipse with Pydev. This gives you a fully functional IDE with debugger built in. I use it with django as well.
Ahah! Checkout the previous commit, then checkout the master.
git checkout HEAD^
git checkout -f master
Android Studio was not able to connect to internet in my work PC due to Intranet Proxy/Firewall settings, changing the proxy settings didnt help me either.
Android studio was failing to run as it requires to install the above mentioned packages. As a work around I installed the packages from Android SDK Manager and it solved it.
You can find the SDK Manager under C:\Users\< UserName> \AppData\Local\Android\sdk\SDK Manager.exe In the GUI choose the following options whichever is relavant.
After installation is complete try launching the Android Studio
It depends on how you validate your XML. If you use XML Schema validation, the correct way of representing null
values is with the xsi:nil
attribute.
[Source]
If you don't need an algorithm that's strong against intentional modification, I've found an algorithm called adler32 that produces pretty short (~8 character) results. Choose it from the dropdown here to try it out:
I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:
$("#addComment").click(function() {
if(typeof TinyMCE === "undefined") {
$.ajax({
url: "tinymce.js",
dataType: "script",
cache: true,
success: function() {
TinyMCE.init();
}
});
}
});
The getScript()
function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:
http://www.yoursite.com/js/tinymce.js?_=1399055841840
If a user clicks the #addComment
link multiple times, tinymce.js
will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.
===
Alternatively, in the getScript()
documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript()
function as follows:
jQuery.cachedScript = function( url, options ) {
// Allow user to set any option except for dataType, cache, and url
options = $.extend( options || {}, {
dataType: "script",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax( options );
};
// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
console.log( textStatus );
});
===
Or, if you want to disable caching globally, you can do so using ajaxSetup()
as follows:
$.ajaxSetup({
cache: true
});
Using WebClient.UploadString
or WebClient.UploadData
you can POST data to the server easily. I’ll show an example using UploadData, since UploadString is used in the same manner as DownloadString.
byte[] bret = client.UploadData("http://www.website.com/post.php", "POST",
System.Text.Encoding.ASCII.GetBytes("field1=value1&field2=value2") );
string sret = System.Text.Encoding.ASCII.GetString(bret);
int[] Data= { 1, 212, 333,2,12,3311,122,23 };
int large = Data.Max();
Console.WriteLine(large);
i am using replay future , to do some update and run quickly .
This should do it, let me know if you have trouble with it:
Sub foo()
Dim x As Workbook
Dim y As Workbook
'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")
'Now, copy what you want from x:
x.Sheets("name of copying sheet").Range("A1").Copy
'Now, paste to y worksheet:
y.Sheets("sheetname").Range("A1").PasteSpecial
'Close x:
x.Close
End Sub
Alternatively, you could just:
Sub foo2()
Dim x As Workbook
Dim y As Workbook
'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")
'Now, transfer values from x to y:
y.Sheets("sheetname").Range("A1").Value = x.Sheets("name of copying sheet").Range("A1")
'Close x:
x.Close
End Sub
To extend this to the entire sheet:
With x.Sheets("name of copying sheet").UsedRange
'Now, paste to y worksheet:
y.Sheets("sheet name").Range("A1").Resize( _
.Rows.Count, .Columns.Count) = .Value
End With
And yet another way, store the value as a variable and write the variable to the destination:
Sub foo3()
Dim x As Workbook
Dim y As Workbook
Dim vals as Variant
'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")
'Store the value in a variable:
vals = x.Sheets("name of sheet").Range("A1").Value
'Use the variable to assign a value to the other file/sheet:
y.Sheets("sheetname").Range("A1").Value = vals
'Close x:
x.Close
End Sub
The last method above is usually the fastest for most applications, but do note that for very large datasets (100k rows) it's observed that the Clipboard actually outperforms the array dump:
Copy/PasteSpecial vs Range.Value = Range.Value
That said, there are other considerations than just speed, and it may be the case that the performance hit on a large dataset is worth the tradeoff, to avoid interacting with the Clipboard.
I would go with unset because it might give the garbage collector a better hint so that the memory can be available again sooner. Be careful that any things the object points to either have other references or get unset first or you really will have to wait on the garbage collector since there would then be no handles to them.
Use PHP's strip_tags() function.
For example:
$businessDesc = strip_tags($row_get_Business['business_description']);
$businessDesc = substr($businessDesc, 0, 110);
print($businessDesc);
You need to use a directed graph instead of a graph, i.e.
G = nx.DiGraph()
Then, create a list of the edge colors you want to use and pass those to nx.draw
(as shown by @Marius).
Putting this all together, I get the image below. Still not quite the other picture you show (I don't know where your edge weights are coming from), but much closer! If you want more control of how your output graph looks (e.g. get arrowheads that look like arrows), I'd check out NetworkX with Graphviz.
Problem: root@localhost is unable to connect to a fresh installation of mysql-community-server on openSUSE 42.2-1.150.x86_64. Mysql refuses connections - period.
Solution:
$ ls -l /var/lib/mysql/mysql/user.*
-rw-rw---- 1 mysql mysql 0 Apr 29 19:44 /var/lib/mysql/mysql/user.MYD
-rw-rw---- 1 mysql mysql 1024 Apr 29 19:44 /var/lib/mysql/mysql/user.MYI
-rw-rw---- 1 mysql mysql 10684 Apr 29 19:44 /var/lib/mysql/mysql/user.frm
File user.MYD has 0 size (really ?!). I copied all 3 files from another working system.
$ /usr/sbin/rcmysql stop
$ cd /var/lib/mysql/mysql/
$ scp root@othersytem:/var/lib/mysql/mysql/user.* ./
$ /usr/sbin/rcmysql start
$ cd -
$ mysql -u root -p
I was able to log in. Then, it was just a matter of re-applying all schema privileges. Also, if you disabled IPv6, re-enable it temporary so that root@::1 account can also work.
Right click on your website go to property pages and check both the check-boxes under Accessibility validation click on ok. run the website.
select t1.*, sq.*
from table1 t1,
(select a,b,c from table2 ...) sq
where ...
This way of specifying the encoding of a Python file comes from PEP 0263 - Defining Python Source Code Encodings.
It is also recognized by GNU Emacs (see Python Language Reference, 2.1.4 Encoding declarations), though I don't know if it was the first program to use that syntax.
Does this really make sense?
There is no "first" record in a relational database, you can only delete one random record.
You need to use JavaScript in your HTML and make sure you are using forms so that. You may finally serialize the data using Ajax method to push the data from HTML into database
You can use the TypeDescriptor class to do this:
foreach(PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
{
string name=descriptor.Name;
object value=descriptor.GetValue(obj);
Console.WriteLine("{0}={1}",name,value);
}
TypeDescriptor lives in the System.ComponentModel namespace and is the API that Visual Studio uses to display your object in its property browser. It's ultimately based on reflection (as any solution would be), but it provides a pretty good level of abstraction from the reflection API.
Here is Haagenti's answer updated to Swift 4.2:
class PaddedTextField: UITextField {
func getPadding(plusExtraFor clearButtonMode: ViewMode) -> UIEdgeInsets {
var padding = UIEdgeInsets(top: 11, left: 16, bottom: 11, right: 16)
// Add additional padding on the right side when showing the clear button
if self.clearButtonMode == .always || self.clearButtonMode == clearButtonMode {
padding.right = 28
}
return padding
}
override open func textRect(forBounds bounds: CGRect) -> CGRect {
let padding = getPadding(plusExtraFor: .unlessEditing)
return bounds.inset(by: padding)
}
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
let padding = getPadding(plusExtraFor: .unlessEditing)
return bounds.inset(by: padding)
}
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
let padding = getPadding(plusExtraFor: .whileEditing)
return bounds.inset(by: padding)
}
}
Reference: Upgrading To Swift 4.2.
Edit: Account for clear button.
For Swift 2.0 users with Alamofire > 2.0
Alamofire.request(.GET, url)
.responseString { _, response, result in
if response?.statusCode == 200{
//Do something with result
}
}
I discoverd the same Error message trying to pull from a Bitbuck Repo into my lokal copy. There is also only one Branche Master and the command git pull origin master
lead to this Error Message
From https://bitbucket.org/xxx
* branch master -> FETCH_HEAD
error: Couldn't set ORIG_HEAD
fatal: Cannot update the ref 'ORIG_HEAD'.
Solution as follows
git reflog
find the number of the last commitgit reset --hard <numnber>
reset to the last commit git pull origin master
pull again without errorI used this method:
$(document).mousemove(function(e) {
window.x = e.pageX;
window.y = e.pageY;
});
function show_popup(str) {
$("#popup_content").html(str);
$("#popup").fadeIn("fast");
$("#popup").css("top", y);
$("#popup").css("left", x);
}
In this way I'll always have the distance from the top saved in y and the distance from the left saved in x.
@folex answer is right.
But it will fail if the tableView has more than one section displayed at a time.
-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if([indexPath isEqual:((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject])]){
//end of loading
}
}
How about ['hello', 'hi', 'howdy'].includes(str)
?
Another clean way to save the file is this:
import csv
import urllib
urllib.retrieve("your url goes here" , "output.csv")
If you want control over how many NAs are valid for each row, try this function. For many survey data sets, too many blank question responses can ruin the results. So they are deleted after a certain threshold. This function will allow you to choose how many NAs the row can have before it's deleted:
delete.na <- function(DF, n=0) {
DF[rowSums(is.na(DF)) <= n,]
}
By default, it will eliminate all NAs:
delete.na(final)
gene hsap mmul mmus rnor cfam
2 ENSG00000199674 0 2 2 2 2
6 ENSG00000221312 0 1 2 3 2
Or specify the maximum number of NAs allowed:
delete.na(final, 2)
gene hsap mmul mmus rnor cfam
2 ENSG00000199674 0 2 2 2 2
4 ENSG00000207604 0 NA NA 1 2
6 ENSG00000221312 0 1 2 3 2
Thanks to Hallgrim, here is the code I ended up with:
ScreenCapture = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
bmp.GetHbitmap(),
IntPtr.Zero,
System.Windows.Int32Rect.Empty,
BitmapSizeOptions.FromWidthAndHeight(width, height));
I also ended up binding to a BitmapSource instead of a BitmapImage as in my original question
At the moment I write this, TCPDF only supports padding for tables.
I have written a Java class RawConsoleInput that uses JNA to call operating system functions of Windows and Unix/Linux.
_kbhit()
and _getwch()
from msvcrt.dll.tcsetattr()
to switch the console to non-canonical mode, System.in.available()
to check whether data is available and System.in.read()
to read bytes from the console. A CharsetDecoder
is used to convert bytes to characters.It supports non-blocking input and mixing raw mode and normal line mode input.
To sum up if your remote is called origin
and you're working on master
branch:
git tag -d <tagname>
git push origin :refs/tags/<tagname>
git tag <tagname> <commitId>
git push origin <tagname>
You can also exchange line 4 to git push origin --tags
to push all the changes with tags from your local changes.
Basing on @stuart-golodetz, @greg-hewgill, @eedeep, @ben-hocking answers, comments below their answers and NateS comments below my answer.
From Laravel 6, Now It's working with the following command:
composer create-project --prefer-dist laravel/laravel:^7.0 blog
This can be changed to 0/1 through using CASE WHEN
like this example:
SELECT
CASE WHEN SchemaName.TableName.BitFieldName = 'true' THEN 1 ELSE 0 END AS 'bit Value'
FROM SchemaName.TableName
There are four ways I've found to put a newline into the minibuffer.
C-o
C-q C-j
C-q 12
(12 is the octal value of newline)
C-x o to the main window, kill a newline with C-k, then C-x o back to the minibuffer, yank it with C-y
//To get Filename + date and time
SimpleDateFormat f = new SimpleDateFormat("MMM");
SimpleDateFormat f1 = new SimpleDateFormat("dd");
SimpleDateFormat f2 = new SimpleDateFormat("a");
int h;
if(Calendar.getInstance().get(Calendar.HOUR)==0)
h=12;
else
h=Calendar.getInstance().get(Calendar.HOUR)
String filename="TestReport"+f1.format(new Date())+f.format(new Date())+h+f2.format(new Date())+".txt";
The Output Like:TestReport27Apr3PM.txt
If you want to read multiple CSV files starting from line 2, this works like a charm
for files in csv_file_list:
with open(files, 'r') as r:
next(r) #skip headers
rr = csv.reader(r)
for row in rr:
#do something
(this is part of Parfait's answer to a different question)
Here simple example to create pandas dataframe by using numpy array.
import numpy as np
import pandas as pd
# create an array
var1 = np.arange(start=1, stop=21, step=1).reshape(-1)
var2 = np.random.rand(20,1).reshape(-1)
print(var1.shape)
print(var2.shape)
dataset = pd.DataFrame()
dataset['col1'] = var1
dataset['col2'] = var2
dataset.head()
You need to set up your server to use ISO-8859-15 as the character encoding (adding the appropriate HTTP header). Doing it in the body of the html won't help.
I can see this line
<?php header('Content-Type: text/html; charset=ISO-8859-15'); ?>
at the source of your html. This shouldn't happen. Using Live HTTP Headers I can't see the appropriate charset HTTP header. Use that for both your first page and the ajax service.
Adding to Eric Jablow's answer, here is a possible solution (it worked for me - linux mint 14 /nadia)
find /path/to/search/ -type f -name "glob-to-find-files" | xargs cp -t /target/path/
You can refer to "How can I use xargs to copy files that have spaces and quotes in their names?" as well.
// will return the host name and port
var host = window.location.host;
or possibly
var host = window.location.protocol + "//" + window.location.host;
or if you like concatenation
var protocol = location.protocol;
var slashes = protocol.concat("//");
var host = slashes.concat(window.location.host);
// or as you probably should do
var host = location.protocol.concat("//").concat(window.location.host);
// the above is the same as origin, e.g. "https://stackoverflow.com"
var host = window.location.origin;
If you have or expect custom ports use window.location.host
instead of window.location.hostname
You should debug first, to help identify your level of XML hell. In my opinion, the first step is to add
-Djavax.xml.parsers.SAXParserFactory=com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl
-Djavax.xml.transform.TransformerFactory=com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl
-Djavax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl
to the command line. If that works, then start excluding libraries. If not, then add
-Djaxp.debug=1
to the command-line.
Check your pom.xml
first (if you have one)
Check your module's JDK
dependancy. Make sure that it is 1.8
To do this,go to Project Structure -> SDK's
Add the path to where you have stored 1.8 (jdk1.8.0_45.jdk
in my case)
Apply the changes
Now, go to Project Structure ->Modules
Change the Module SDK to 1.8
Apply the changes
Voila! You're done
for me, i did this and it worked. just go to C:\Users\$your username$\AppData(which is hidden most likely)\Local\ then at this location try to find this Folder : "Android" if you don't have it already make one with the exact name and try to open the android studio again.
I reinstalled the usb
drivers and ensured that I was not using USB 3.0
port.
I then closed out eclipse and killed and restarted adb
.
Was immediately prompted on phone to allow computer access. After accepting I restarted eclipse and now my Galaxy S3 shows up in device Device Manager.
I stumbled across this attempting to solve the same issue. The installation I am working with uses JBOSS and Hibernate, so I had to do this a different way. For the basic case, you should be able to add zeroDateTimeBehavior=convertToNull
to your connection URI as per this configuration properties page.
I found other suggestions across the land referring to putting that parameter in your hibernate config:
In hibernate.cfg.xml:
<property name="hibernate.connection.zeroDateTimeBehavior">convertToNull</property>
In hibernate.properties:
hibernate.connection.zeroDateTimeBehavior=convertToNull
But I had to put it in my mysql-ds.xml file for JBOSS as:
<connection-property name="zeroDateTimeBehavior">convertToNull</connection-property>
Hope this helps someone. :)
import java.util.Timer;
import java.util.TimerTask;
class Clock {
private Timer mTimer = new Timer();
private int mSecondsPassed = 0;
private TimerTask mTask = new TimerTask() {
@Override
public void run() {
mSecondsPassed++;
System.out.println("Seconds passed: " + mSecondsPassed);
}
};
private void start() {
mTimer.scheduleAtFixedRate(mTask, 1000, 1000);
}
public static void main(String[] args) {
Clock c = new Clock();
c.start();
}
}
If sometimes a link! will not work. so create a temporary object and take all values from the writable object then change the value and assign it to the writable object. it should perfectly.
var globalObject = {
name:"a",
age:20
}
function() {
let localObject = {
name:'a',
age:21
}
this.globalObject = localObject;
}
You can also use callto:########### replacing the email code mail with call, at least according to W3Cschool site but I haven't had an opportunity to test it out.
For anyone else out there wondering how to do this, I have the following solution for SQL Server 2008 R2 and later:
USE master
go
DENY VIEW ANY DATABASE TO [user]
go
This will address exactly the requirement outlined above..
After some years have passed, you can do that now with ES6 Array.from
(or spread syntax):
const navbar = Array.from(document.querySelectorAll('#navbar>ul>li'));_x000D_
console.log('Get first: ', navbar[0].textContent);_x000D_
_x000D_
// If you need to iterate once over all these nodes, you can use the callback function:_x000D_
console.log('Iterate with Array.from callback argument:');_x000D_
Array.from(document.querySelectorAll('#navbar>ul>li'),li => console.log(li.textContent))_x000D_
_x000D_
// ... or a for...of loop:_x000D_
console.log('Iterate with for...of:');_x000D_
for (const li of document.querySelectorAll('#navbar>ul>li')) {_x000D_
console.log(li.textContent);_x000D_
}
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
<div id="navbar">_x000D_
<ul>_x000D_
<li id="navbar-One">One</li>_x000D_
<li id="navbar-Two">Two</li>_x000D_
<li id="navbar-Three">Three</li>_x000D_
</ul>_x000D_
</div>
_x000D_
The solution
angular.element(document.getElementById('ID')).scope().get()
stopped working for me in angular 1.5.2. Sombody mention in a comment that this doesn't work in 1.4.9 also.
I fixed it by storing the scope in a global variable:
var scopeHolder;
angular.module('fooApp').controller('appCtrl', function ($scope) {
$scope = function bar(){
console.log("foo");
};
scopeHolder = $scope;
})
call from custom code:
scopeHolder.bar()
if you wants to restrict the scope to only this method. To minimize the exposure of whole scope. use following technique.
var scopeHolder;
angular.module('fooApp').controller('appCtrl', function ($scope) {
$scope.bar = function(){
console.log("foo");
};
scopeHolder = $scope.bar;
})
call from custom code:
scopeHolder()
From the Maven Embedder documentation:
-fae
,--fail-at-end
Only fail the build afterwards; allow all non-impacted builds to continue
-fn
,--fail-never
NEVER fail the build, regardless of project result
So if you are testing one module than you are safe using -fae
.
Otherwise, if you have multiple modules, and if you want all of them tested (even the ones that depend on the failing tests module), you should run mvn clean install -fn
.
-fae
will continue with the module that has a failing test (will run all other tests), but all modules that depend on it will be skipped.
If you are trying to run Google android sample code, try to import the entire repository instead of an individual sample.
Here is instructions.html, included with the Google Calendar API sample code.
- Import calendar-android-sample project
- Select "Import Project..." or File > Import Project...
- Select [someDirectory]/google-api-java-client-samples/build.gradle and click OK.
- Note: it will not work if you try to import [someDirectory]/google-api-java-client-samples/calendar-android-sample/build.gradle
- Select "Use local gradle distribution" with "Gradle home" of [someDirectory]/gradle-2.2.1 and click OK.
You need to store it in a String
variable first before displaying it like so:
String Txt = TxtBoxContent.getText();
System.out.println(Txt);
I use these two .gitconfig settings:
[log]
date = relative
[format]
pretty = format:%h %Cblue%ad%Creset %ae %Cgreen%s%Creset
%ad is the author date, which can be overidden by --date
or the option specified in the [log] stanza in .gitconfig.
I like the relative date because it gives an immediate feeling of when stuff was comitted.
Output looks like this:
6c3e1a2 2 hours ago [email protected] lsof is a dependency now.
0754f18 11 hours ago [email protected] Properly unmount, so detaching works.
336a3ac 13 hours ago [email protected] Show ami registration command if auto register fails
be2ad45 17 hours ago [email protected] Fixes #6. Sao Paolo region is included as well.
5aed68e 17 hours ago [email protected] Shorten while loops
This is all of course in color, so it is easy to distinguish the various parts of a log line.
Also it is the default when typing git log
because of the [format] section.
2014 UPDATE: Since git now supports padding I have a nice amendment to the version above:
pretty = format:%C(yellow)%h %Cblue%>(12)%ad %Cgreen%<(7)%aN%Cred%d %Creset%s
This right aligns the relative dates and left aligns committer names, meaning you get a column-like look that is easy on the eyes.
Screenshot2016 UPDATE: Since GPG commit signing is becoming a thing, I thought I'd update this post with a version that includes signature verification (in the screenshot it's the magenta letter right after the commit). A short explanation of the flag:
%G?: show "G" for a good (valid) signature, "B" for a bad signature, "U" for a good signature with unknown validity and "N" for no signature
Other changes include:
git log -g
now contains the reflog selector.3 years, 4..
)%<(7,trunc)
or check out the git .mailmap feature to shorten commiter names)Here's the config:
pretty = format:%C(auto,yellow)%h%C(auto,magenta)% G? %C(auto,blue)%>(12,trunc)%ad %C(auto,green)%<(7,trunc)%aN%C(auto,reset)%s%C(auto,red)% gD% D
All in all column alignment is now preserved a lot better at the expense of some (hopefully) useless characters. Feel free to edit if you have any improvements, I'd love to make the message color depend on whether a commit is signed, but it doesn't seem like that is possible atm.
ScreenshotThis was a problem for me for a long time. I had to come up with a solution that can be easily migrated once we get Elvis operator or something.
This is what I use; works for both arrays and objects
put this in tools.js file or something
// this will create the object/array if null
Object.prototype.__ = function (prop) {
if (this[prop] === undefined)
this[prop] = typeof prop == 'number' ? [] : {}
return this[prop]
};
// this will just check if object/array is null
Object.prototype._ = function (prop) {
return this[prop] === undefined ? {} : this[prop]
};
usage example:
let student = {
classes: [
'math',
'whatev'
],
scores: {
math: 9,
whatev: 20
},
loans: [
200,
{ 'hey': 'sup' },
500,
300,
8000,
3000000
]
}
// use one underscore to test
console.log(student._('classes')._(0)) // math
console.log(student._('classes')._(3)) // {}
console.log(student._('sports')._(3)._('injuries')) // {}
console.log(student._('scores')._('whatev')) // 20
console.log(student._('blabla')._('whatev')) // {}
console.log(student._('loans')._(2)) // 500
console.log(student._('loans')._(1)._('hey')) // sup
console.log(student._('loans')._(6)._('hey')) // {}
// use two underscores to create if null
student.__('loans').__(6)['test'] = 'whatev'
console.log(student.__('loans').__(6).__('test')) // whatev
well I know it makes the code a bit unreadable but it's a simple one liner solution and works great. I hope it helps someone :)
As @Josh said, the correct answer is:
int column = 0,
row = 0,
index = 0;
You'll need to watch out for the same thing with pointers. This:
int* a, b, c;
Is equivalent to:
int *a;
int b;
int c;
Define the query method with signatures as follows.
@Query(select p from Person p where p.forename = :forename and p.surname = :surname)
User findByForenameAndSurname(@Param("surname") String lastname,
@Param("forename") String firstname);
}
For further details, check the Spring Data JPA reference
Instead of using .get, using like this should be ok for lists. Just a usage difference.
>>> l = [1]
>>> l[10] if 10 < len(l) else 'fail'
'fail'
You can pass params directly to $http.get()
The following works fine
$http.get(user.details_path, {
params: { user_id: user.id }
});
Try this code:
imgView.setImageResource(android.R.color.transparent);
also this one works:
imgView.setImageResource(0);
but be careful this one doesn't work:
imgView.setImageResource(null);
I think you are searching for something like this one.
class test {
private $str = NULL;
public function newTest(){
$this->str .= 'function "newTest" called, ';
return $this;
}
public function bigTest(){
return $this->str . ' function "bigTest" called,';
}
public function smallTest(){
return $this->str . ' function "smallTest" called,';
}
public function scoreTest(){
return $this->str . ' function "scoreTest" called,';
}
}
$test = new test;
echo $test->newTest()->bigTest();
I think this will do what you want:
DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(-1);
TimeSpan t = d1 - d2;
double NrOfDays = t.TotalDays;
I found 3 ways to implement this:
C# class:
public class AddressInfo {
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public string Country { get; set; }
}
Action:
[HttpPost]
public ActionResult Check(AddressInfo addressInfo)
{
return Json(new { success = true });
}
JavaScript you can do it three ways:
1) Query String:
$.ajax({
url: '/en/Home/Check',
data: $('#form').serialize(),
type: 'POST',
});
Data here is a string.
"Address1=blah&Address2=blah&City=blah&State=blah&ZipCode=blah&Country=blah"
2) Object Array:
$.ajax({
url: '/en/Home/Check',
data: $('#form').serializeArray(),
type: 'POST',
});
Data here is an array of key/value pairs :
=[{name: 'Address1', value: 'blah'}, {name: 'Address2', value: 'blah'}, {name: 'City', value: 'blah'}, {name: 'State', value: 'blah'}, {name: 'ZipCode', value: 'blah'}, {name: 'Country', value: 'blah'}]
3) JSON:
$.ajax({
url: '/en/Home/Check',
data: JSON.stringify({ addressInfo:{//missing brackets
Address1: $('#address1').val(),
Address2: $('#address2').val(),
City: $('#City').val(),
State: $('#State').val(),
ZipCode: $('#ZipCode').val()}}),
type: 'POST',
contentType: 'application/json; charset=utf-8'
});
Data here is a serialized JSON string. Note that the name has to match the parameter name in the server!!
='{"addressInfo":{"Address1":"blah","Address2":"blah","City":"blah","State":"blah", "ZipCode", "blah", "Country", "blah"}}'
The simplest way is to simply use the following line of jquery
, using this you don't get the /fakepath
nonsense, you straight up get the file that was uploaded:
$('input[type=file]')[0].files[0]; // This gets the file
$('#idOfFileUpload')[0].files[0]; // This gets the file with the specified id
Some other useful commands are:
To get the name of the file:
$('input[type=file]')[0].files[0].name; // This gets the file name
To get the type of the file:
If I were to upload a PNG, it would return image/png
$("#imgUpload")[0].files[0].type
To get the size (in bytes) of the file:
$("#imgUpload")[0].files[0].size
Also you don't have to use these commands on('change'
, you can get the values at any time, for instance you may have a file upload and when the user clicks upload
, you simply use the commands I listed.
Even though the above answer appears to be correct, I wanted to add a (hopefully) more readable example that also stays in 3 columns form at different widths:
.flex-row-container {_x000D_
background: #aaa;_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
}_x000D_
.flex-row-container > .flex-row-item {_x000D_
flex: 1 1 30%; /*grow | shrink | basis */_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
.flex-row-item {_x000D_
background-color: #fff4e6;_x000D_
border: 1px solid #f76707;_x000D_
}
_x000D_
<div class="flex-row-container">_x000D_
<div class="flex-row-item">1</div>_x000D_
<div class="flex-row-item">2</div>_x000D_
<div class="flex-row-item">3</div>_x000D_
<div class="flex-row-item">4</div>_x000D_
<div class="flex-row-item">5</div>_x000D_
<div class="flex-row-item">6</div>_x000D_
</div>
_x000D_
Hope this helps someone else.
Use the S_ISDIR
macro:
int isDirectory(const char *path) {
struct stat statbuf;
if (stat(path, &statbuf) != 0)
return 0;
return S_ISDIR(statbuf.st_mode);
}
But its still giving an error message in Query Builder. I am using SqlServerCe 2008.
SELECT Products_Master.ProductName, Order_Products.Quantity, Order_Details.TotalTax, Order_Products.Cost, Order_Details.Discount,
Order_Details.TotalPrice
FROM Order_Products INNER JOIN
Order_Details ON Order_Details.OrderID = Order_Products.OrderID INNER JOIN
Products_Master ON Products_Master.ProductCode = Order_Products.ProductCode
HAVING (Order_Details.OrderID = (SELECT MAX(OrderID) AS Expr1 FROM Order_Details AS mx1))
I replaced WHERE with HAVING as said by @powerlord. But still showing an error.
Error parsing the query. [Token line number = 1, Token line offset = 371, Token in error = SELECT]
Yes:
git rev-parse --show-toplevel
If you want to replicate the Git command more directly, you can create an alias:
git config --global alias.root 'rev-parse --show-toplevel'
and now git root
will function just as hg root
.
Note: In a submodule this will display the root directory of the submodule and not the parent repository. If you are using Git >=2.13 or above, there is a way that submodules can show the superproject's root directory. If your git is older than that, see this other answer.
Instead of using http GET, use http POST. And JSON. Or XML
This is how your request stream to the server would look like.
POST /appointments HTTP/1.0
Content-Type: application/json
Content-Length: (calculated by your utility)
{users: [user:{id:id1}, user:{id:id2}]}
Or in XML,
POST /appointments HTTP/1.0
Content-Type: application/json
Content-Length: (calculated by your utility)
<users><user id='id1'/><user id='id2'/></users>
You could certainly continue using GET as you have proposed, as it is certainly simpler.
/appointments?users=1d1,1d2
Which means you would have to keep your data structures very simple.
However, if/when your data structure gets more complex, http GET and without JSON, your programming and ability to recognise the data gets very difficult.
Therefore,unless you could keep your data structure simple, I urge you adopt a data transfer framework. If your requests are browser based, the industry usual practice is JSON. If your requests are server-server, than XML is the most convenient framework.
JQuery
If your client is a browser and you are not using GWT, you should consider using jquery REST. Google on RESTful services with jQuery.
Here is a sample code: my app uses ZXing Barcode Scanner.
You need these 2 classes: IntentIntegrator and IntentResult
Call scanner (e.g. OnClickListener, OnMenuItemSelected...), "PRODUCT_MODE" - it scans standard 1D barcodes (you can add more).:
IntentIntegrator.initiateScan(this,
"Warning",
"ZXing Barcode Scanner is not installed, download?",
"Yes", "No",
"PRODUCT_MODE");
Get barcode as a result:
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case IntentIntegrator.REQUEST_CODE:
if (resultCode == Activity.RESULT_OK) {
IntentResult intentResult =
IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (intentResult != null) {
String contents = intentResult.getContents();
String format = intentResult.getFormatName();
this.elemQuery.setText(contents);
this.resume = false;
Log.d("SEARCH_EAN", "OK, EAN: " + contents + ", FORMAT: " + format);
} else {
Log.e("SEARCH_EAN", "IntentResult je NULL!");
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("SEARCH_EAN", "CANCEL");
}
}
}
contents holds barcode number
another solution is catching onClick event and for aggregate data to js function you can
.hmtl.erb
<%= link_to "Action", 'javascript:;', class: 'my-class', data: { 'array' => %w(foo bar) } %>
.js
// handle my-class click
$('a.my-class').on('click', function () {
var link = $(this);
var array = link.data('array');
});
DateTime.ToString("dd/MM/yyyy") may give the date in dd-MM-yyyy format. This depends on your short date format. If short date format is not as per format, we have to replace character '-' with '/' as below:
date = DateTime.Now.ToString("dd/MM/yyyy").Replace('-','/');
If you have assigned a certain controller to your view, then your controller will be invoked every time your view loads. In that case, you can execute some code in your controller as soon as it is invoked, for example this way:
<ion-nav-view ng-controller="indexController" name="other" ng-init="doSomething()"></ion-nav-view>
And in your controller:
app.controller('indexController', function($scope) {
/*
Write some code directly over here without any function,
and it will be executed every time your view loads.
Something like this:
*/
$scope.xyz = 1;
});
Edit: You might try to track state changes and then execute some code when the route is changed and a certain route is visited, for example:
$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams){ ... })
You can find more details here: State Change Events.
For security reasons you must avoid providing password on a command line otherwise anyone running ps command can see your password. Better to use sshpass utility like this:
#!/bin/bash
export SSHPASS="your-password"
sshpass -e ssh -oBatchMode=no sshUser@remoteHost
You might be interested in How to run the sftp command with a password from Bash script?
No matter what we tried we couldn't manage to get the timeout below 21 seconds when the server we were checking was down.
To work around this we combined a TcpClient check to see if the domain was alive followed by a separate check to see if the URL was active
public static bool IsUrlAlive(string aUrl, int aTimeoutSeconds)
{
try
{
//check the domain first
if (IsDomainAlive(new Uri(aUrl).Host, aTimeoutSeconds))
{
//only now check the url itself
var request = System.Net.WebRequest.Create(aUrl);
request.Method = "HEAD";
request.Timeout = aTimeoutSeconds * 1000;
var response = (HttpWebResponse)request.GetResponse();
return response.StatusCode == HttpStatusCode.OK;
}
}
catch
{
}
return false;
}
private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds)
{
try
{
using (TcpClient client = new TcpClient())
{
var result = client.BeginConnect(aDomain, 80, null, null);
var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds));
if (!success)
{
return false;
}
// we have connected
client.EndConnect(result);
return true;
}
}
catch
{
}
return false;
}
The .load("file.txt")
is much easier. Which works but even if testing, you won't get results from a localdrive, you'll need an actual http server. The invisible error is an XMLHttpRequest
error.
Haven't tried it myself, but maybe dotTrace? Their ReSharper application is certainly a good one. Maybe dotTrace is too :)
if you are having the
Allow from All
in httpd.conf then make sure us have
index.php
like in the below line in httpd.conf
DirectoryIndex index.html index.php
The built-in object
can be instantiated but can't have any attributes set on it. (I wish it could, for this exact purpose.) It doesn't have a __dict__
to hold the attributes.
I generally just do this:
class Object(object):
pass
a = Object()
a.somefield = somevalue
When I can, I give the Object
class a more meaningful name, depending on what kind of data I'm putting in it.
Some people do a different thing, where they use a sub-class of dict
that allows attribute access to get at the keys. (d.key
instead of d['key']
)
Edit: For the addition to your question, using setattr
is fine. You just can't use setattr
on object()
instances.
params = ['attr1', 'attr2', 'attr3']
for p in params:
setattr(obj.a, p, value)
with itertools.product:
import itertools
result = list(itertools.product(*somelists))
a) Adding inline style
document.head.insertAdjacentHTML('beforeend', '<style>#mydiv:hover{color:red;}</style>');
b) or a bit harder method - adding "mouseover"
document.getElementById("mydiv").onmouseover= function(e){this.className += ' my-special-class'; };
document.getElementById("mydiv").onmouseleave= function(e){this.className = this.className.replace('my-special-class',''); };
Note: multi-word styles (i.e.font-size
) in Javascript are written together:
element.style.fontSize="12px"
One of the simple way is to create your database on SD-Card. Because you cannot get access to your phone's data folder in internal memory, unless you root your phone. So why not simply create your database on SD-Card.
Moreover, if you want, you may write some file copying-code to copy your existing database file (from internal memory) to external memory without requiring any root.
The difference is, re.match()
misleads anyone accustomed to Perl, grep, or sed regular expression matching, and re.search()
does not. :-)
More soberly, As John D. Cook remarks, re.match()
"behaves as if every pattern has ^ prepended." In other words, re.match('pattern')
equals re.search('^pattern')
. So it anchors a pattern's left side. But it also doesn't anchor a pattern's right side: that still requires a terminating $
.
Frankly given the above, I think re.match()
should be deprecated. I would be interested to know reasons it should be retained.
I got this error and found that I don't have my SSH port (non standard number) whitelisted in config server firewall.
As Filburt says; but also note that it's usually better to write
test="not(Count = 'N/A')"
If there's exactly one Count element they mean the same thing, but if there's no Count, or if there are several, then the meanings are different.
6 YEARS LATER
Since this answer seems to have become popular, but may be a little cryptic to some readers, let me expand it.
The "=" and "!=" operator in XPath can compare two sets of values. In general, if A and B are sets of values, then "=" returns true if there is any pair of values from A and B that are equal, while "!=" returns true if there is any pair that are unequal.
In the common case where A selects zero-or-one nodes, and B is a constant (say "NA"), this means that not(A = "NA")
returns true if A is either absent, or has a value not equal to "NA". By contrast, A != "NA"
returns true if A is present and not equal to "NA". Usually you want the "absent" case to be treated as "not equal", which means that not(A = "NA")
is the appropriate formulation.
Sometimes cleaning the repository with the "break locks"-option still doesn't work if the lock was created by another process. Possible Solution: 1) Acquire a new lock on the folder/file and choose the option "Steal the locks" 2) Release your new lock.
Hello World!
You see, the main question while using hidden input is what kind of data you want to pass?
I will assume that you are trying to pass the user ID.
Which is not a really good idea to pass it here because field() method will generate input
and the value will be shown to user as we can't hide html from the users browser. This if you really care about security of your website.
please check this link, and you will see that it's impossible to hide value attribute from users to see.
so what to do then?
See, this is the core of OOP in PHP.
and I quote from Matt Zandstr in his great book PHP Objects, Patterns, and Practice fifth edition
I am still stuck with a great deal of unwanted flexibility, though. I rely on the client coder to change a ShopProduct object’s properties from their default values. This is problematic in two ways. First, it takes five lines to properly initialize a ShopProduct object, and no coder will thank you for that. Second, I have no way of ensuring that any of the properties are set when a ShopProduct object is initialized. What I need is a method that is called automatically when an object is instantiated from a class.
Please check this example of using __construct() method which is mentioned in his book too.
class ShopProduct {
public $title;
public $producerMainName;
public $producerFirstName;
public $price = 0;
public function __construct($title,$firstName,$mainName,$price) {
$this->title = $title;
$this->producerFirstName = $firstName;
$this->producerMainName = $mainName;
$this->price = $price;
}
}
$product1 = new ShopProduct("My Antonia","Willa","Cather",5.99 );
print "author: {$product1->getProducer()}\n";
This produces the following:
author: Willa Cather
Class Car {
private $user_id;
//.. your properties
public function __construct($title,$firstName,$mainName,$price){
$this->user_id = \Yii::$app->user->id;
//..Your magic
}
}
Neither main()
or void main()
are standard C. The former is allowed as it has an implicit int
return value, making it the same as int main()
. The purpose of main
's return value is to return an exit status to the operating system.
In standard C, the only valid signatures for main
are:
int main(void)
and
int main(int argc, char **argv)
The form you're using: int main()
is an old style declaration that indicates main
takes an unspecified number of arguments. Don't use it - choose one of those above.
A quick google search lead me to: http://gitstats.sourceforge.net/
Have you tried this project? I'm sure there are similar projects.
You need to compare, not assign:
if (strcmp("hello", "hello") == 0)
^
Because you want to check if the result of strcmp("hello", "hello")
equals to 0
.
About the error:
lvalue required as left operand of assignment
lvalue
means an assignable value (variable), and in assignment the left value to the =
has to be lvalue
(pretty clear).
Both function results and constants are not assignable (rvalue
s), so they are rvalue
s. so the order doesn't matter and if you forget to use ==
you will get this error. (edit:)I consider it a good practice in comparison to put the constant in the left side, so if you write =
instead of ==
, you will get a compilation error. for example:
int a = 5;
if (a = 0) // Always evaluated as false, no error.
{
//...
}
vs.
int a = 5;
if (0 = a) // Generates compilation error, you cannot assign a to 0 (rvalue)
{
//...
}
(see first answer to this question: https://stackoverflow.com/questions/2349378/new-programming-jargon-you-coined)
It simply calls the default constructor of the superclass.
As others have mentioned, it's possible that the name for your constraint is already in use by another table in your DB. They must be unique across the database.
A good convention for naming foreign key constraints is:
fk_TableName_ColumnName
To investigate whether there's a possible clash, you can list all constraints used by your database with this query:
SELECT * FROM information_schema.table_constraints WHERE constraint_schema = 'YOUR_DB';
When I ran this query, I discovered I had previously made a temporary copy of a table and this copy was already using the constraint name I was attempting to use.
public int this[int key]
{
get => GetValue(key);
set => SetValue(key, value);
}
Copy should be used for NSString. If it's Mutable, then it gets copied. If it's not, then it just gets retained. Exactly the semantics that you want in an app (let the type do what's best).
A one-liner with commons-io:
List<String> lines = FileUtils.readLines(new File("/path/to/file.txt"), "utf-8");
The same with guava:
List<String> lines =
Files.readLines(new File("/path/to/file.txt"), Charset.forName("utf-8"));
Why do you want to use sprintf
for string concatenation when there are methods intended specifically for what you need such as strcat
and strncat
?
based on Wesley Coetzee's answer i wrote this. Hope it can help anyone googling this issue. I had bugs with swapping the paginator size in the middle of the list that's why i submit my answer:
Paginator html and list
<mat-paginator [length]="localNewspapers.length" pageSize=20
(page)="getPaginatorData($event)" [pageSizeOptions]="[10, 20, 30]"
showFirstLastButtons="false">
</mat-paginator>
<mat-list>
<app-newspaper-pagi-item *ngFor="let paper of (localNewspapers |
slice: lowValue : highValue)"
[newspaper]="paper">
</app-newspaper-pagi-item>
Component logic
import {Component, Input, OnInit} from "@angular/core";
import {PageEvent} from "@angular/material";
@Component({
selector: 'app-uniques-newspaper-list',
templateUrl: './newspaper-uniques-list.component.html',
})
export class NewspaperUniquesListComponent implements OnInit {
lowValue: number = 0;
highValue: number = 20;
// used to build an array of papers relevant at any given time
public getPaginatorData(event: PageEvent): PageEvent {
this.lowValue = event.pageIndex * event.pageSize;
this.highValue = this.lowValue + event.pageSize;
return event;
}
}
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
If you have low enough standards ;) you could place a table that contains only a header directly above a table that has only a body. It won't scroll horizontally, but if you don't need that...
Jupytext is nice to have in your toolchain for such conversions. It allows not only conversion from a notebook to a script, but you can go back again from the script to notebook as well. And even have that notebook produced in executed form.
jupytext --to py notebook.ipynb # convert notebook.ipynb to a .py file
jupytext --to notebook notebook.py # convert notebook.py to an .ipynb file with no outputs
jupytext --to notebook --execute notebook.py # convert notebook.py to an .ipynb file and run it
Another flavor for same "proxy for nuget": alternatively you can set your nuget proxing settings to connect through fiddler. Below cmd will save proxy settings in in default nuget config file for user at %APPDATA%\NuGet\NuGet.Config
nuget config -Set HTTP_PROXY=http://127.0.0.1:8888
Whenever you need nuget to reach out the internet, just open Fiddler, asumming you have fiddler listening on default port 8888.
This configuration is not sensitive to passwork changes because fiddler will resolve any authentication with up stream proxy for you.
Building on other posted answers.
Both of these will produce the right values:
select distributor_id,
count(*) total,
sum(case when level = 'exec' then 1 else 0 end) ExecCount,
sum(case when level = 'personal' then 1 else 0 end) PersonalCount
from yourtable
group by distributor_id
SELECT a.distributor_id,
(SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
(SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
(SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
FROM myTable a ;
However, the performance is quite different, which will obviously be more relevant as the quantity of data grows.
I found that, assuming no indexes were defined on the table, the query using the SUMs would do a single table scan, while the query with the COUNTs would do multiple table scans.
As an example, run the following script:
IF OBJECT_ID (N't1', N'U') IS NOT NULL
drop table t1
create table t1 (f1 int)
insert into t1 values (1)
insert into t1 values (1)
insert into t1 values (2)
insert into t1 values (2)
insert into t1 values (2)
insert into t1 values (3)
insert into t1 values (3)
insert into t1 values (3)
insert into t1 values (3)
insert into t1 values (4)
insert into t1 values (4)
insert into t1 values (4)
insert into t1 values (4)
insert into t1 values (4)
SELECT SUM(CASE WHEN f1 = 1 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 2 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 3 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 4 THEN 1 else 0 end)
from t1
SELECT
(select COUNT(*) from t1 where f1 = 1),
(select COUNT(*) from t1 where f1 = 2),
(select COUNT(*) from t1 where f1 = 3),
(select COUNT(*) from t1 where f1 = 4)
Highlight the 2 SELECT statements and click on the Display Estimated Execution Plan icon. You will see that the first statement will do one table scan and the second will do 4. Obviously one table scan is better than 4.
Adding a clustered index is also interesting. E.g.
Create clustered index t1f1 on t1(f1);
Update Statistics t1;
The first SELECT above will do a single Clustered Index Scan. The second SELECT will do 4 Clustered Index Seeks, but they are still more expensive than a single Clustered Index Scan. I tried the same thing on a table with 8 million rows and the second SELECT was still a lot more expensive.
Here's how to do it using default ACLs, at least under Linux.
First, you might need to enable ACL support on your filesystem. If you are using ext4 then it is already enabled. Other filesystems (e.g., ext3) need to be mounted with the acl
option. In that case, add the option to your /etc/fstab
. For example, if the directory is located on your root filesystem:
/dev/mapper/qz-root / ext3 errors=remount-ro,acl 0 1
Then remount it:
mount -oremount /
Now, use the following command to set the default ACL:
setfacl -dm u::rwx,g::rwx,o::r /shared/directory
All new files in /shared/directory
should now get the desired permissions. Of course, it also depends on the application creating the file. For example, most files won't be executable by anyone from the start (depending on the mode argument to the open(2) or creat(2) call), just like when using umask. Some utilities like cp
, tar
, and rsync
will try to preserve the permissions of the source file(s) which will mask out your default ACL if the source file was not group-writable.
Hope this helps!
Unfortunately this is not supported in Entity Framework. It was on the roadmap for EF 6, but it got pushed back: Workitem 299: Unique Constraints (Unique Indexes)
When creating a file, use slashes to specify the directory. For example:
Name the file:
repositoryname/newfoldername/filename
GitHub will automatically create a folder with the name newfoldername.
Your setters are strange, which is why you may be seeing a problem.
First, consider whether you even need these setters - if so, they should take a List<string>
, not just a string
:
set
{
_subHead = value;
}
These lines:
newSec.subHead.Add("test string");
Are calling the getter and then call Add
on the returned List<string>
- the setter is not invoked.
$('.IsBestAnswer').removeClass('IsBestAnswer').addClass('bestanswer');
Your code has two problems:
.IsBestAnswe
does not match what you thoughtaddClass()
, not addclass()
.Also, I'm not sure whether you want to replace the class or add it. The above will replace, but remove the .removeClass('IsBestAnswer')
part to add only:
$('.IsBestAnswer').addClass('bestanswer');
You should decide whether to use camelCase or all-lowercase in your CSS classes too (e.g. bestAnswer
vs. bestanswer
).
Updated again:
The following method might not work in newer versions of virtualenv. Before you try to make modifications to the old virtualenv, you should save the dependencies in a requirement file (pip freeze > requirements.txt
) and make a backup of it somewhere else. If anything goes wrong, you can still create a new virtualenv and install the old dependencies in it (pip install -r requirements.txt
).
Updated: I changed the answer 5 months after I originally answered. The following method is more convenient and robust.
Side effect: it also fixes the Symbol not found: _SSLv2_method
exception when you do import ssl
in a virtual environment after upgrading Python to v2.7.8.
Notice: Currently, this is for Python 2.7.x only.
If you're using Homebrew Python on OS X, first deactivate
all virtualenv, then upgrade Python:
brew update && brew upgrade python
Run the following commands (<EXISTING_ENV_PATH>
is path of your virtual environment):
cd <EXISTING_ENV_PATH>
rm .Python
rm bin/pip{,2,2.7}
rm bin/python{,2,2.7}
rm -r include/python2.7
rm lib/python2.7/*
rm -r lib/python2.7/distutils
rm lib/python2.7/site-packages/easy_install.*
rm -r lib/python2.7/site-packages/pip
rm -r lib/python2.7/site-packages/pip-*.dist-info
rm -r lib/python2.7/site-packages/setuptools
rm -r lib/python2.7/site-packages/setuptools-*.dist-info
Finally, re-create your virtual environment:
virtualenv <EXISTING_ENV_PATH>
By doing so, old Python core files and standard libraries (plus setuptools
and pip
) are removed, while the custom libraries installed in site-packages
are preserved and working, as soon as they are in pure Python. Binary libraries may or may not need to be reinstalled to function properly.
This worked for me on 5 virtual environments with Django installed.
BTW, if ./manage.py compilemessages
is not working afterwards, try this:
brew install gettext && brew link gettext --force
As Jage's answer removes the element completely, including event handlers and data, I'm adding a simple solution that doesn't do that, thanks to the detach
function.
var element = $('#childNode').detach();
$('#parentNode').append(element);
Edit:
Igor Mukhin suggested an even shorter version in the comments below:
$("#childNode").detach().appendTo("#parentNode");
In order to get all the details I had to add the -v option to romaintaz answer:
keytool -v -list -keystore <FileName>.keystore
As of .NET Core 2.0, there is an override that takes a string.
So now you can do "THExxQUICKxxBROWNxxFOX".Split("xx")
.
Before every insert action I added below line and solved my issue,
SET SQL_MODE = '';
I'm not sure if this is the best solution,
SET SQL_MODE = ''; INSERT INTO `mytable` ( `field1` , `field2`) VALUES ('value1', 'value2');
These solutions didn't work with my datagrid. I was hoping they would. I don't really need Tab or Enter to move to the next input, column, row or whatever. I just need Enter to trigger .focusout or .change and my datagrid updates the database. So I added the "enter" class to the relevant text inputs and this did the trick for me:
$(function() {
if ($.browser.mozilla) {
$(".enter").keypress(checkForEnter);
} else {
$(".enter").keydown(checkForEnter);
}
});
function checkForEnter(event) {
if (event.keyCode == 13) {
$(".enter").blur();
}
}
It looks to me like the background images aren't actually background images...the site has the background images and the quotes in sibling divs with the children of the div containing the images having been assigned position: fixed; The quotes div is also given a transparent background.
wrapper div{
image wrapper div{
div for individual image{ <--- Fixed position
image <--- relative position
}
}
quote wrapper div{
div for individual quote{
quote
}
}
}
You can use this prompt.
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Prompt } from "react-router-dom";
function PreventingTransitionsExample() {
return (
<Router>
<div>
<ul>
<li>
<Link to="/">Form</Link>
</li>
<li>
<Link to="/one">One</Link>
</li>
<li>
<Link to="/two">Two</Link>
</li>
</ul>
<Route path="/" exact component={Form} />
<Route path="/one" render={() => <h3>One</h3>} />
<Route path="/two" render={() => <h3>Two</h3>} />
</div>
</Router>
);
}
class Form extends Component {
state = { isBlocking: false };
render() {
let { isBlocking } = this.state;
return (
<form
onSubmit={event => {
event.preventDefault();
event.target.reset();
this.setState({
isBlocking: false
});
}}
>
<Prompt
when={isBlocking}
message={location =>
`Are you sure you want to go to ${location.pathname}`
}
/>
<p>
Blocking?{" "}
{isBlocking ? "Yes, click a link or the back button" : "Nope"}
</p>
<p>
<input
size="50"
placeholder="type something to block transitions"
onChange={event => {
this.setState({
isBlocking: event.target.value.length > 0
});
}}
/>
</p>
<p>
<button>Submit to stop blocking</button>
</p>
</form>
);
}
}
export default PreventingTransitionsExample;
If triangle.lborderA
is indeed a long then the test in the original code is trivially true, and there is no way to test it. It is also useless.
However, if triangle.lborderA
is a double, the comparison is useful and can be tested. isBiggerThanMaxLong(1e300)
does return true.
public static boolean isBiggerThanMaxLong(double in){
return in > Long.MAX_VALUE;
}
Angular Reactive Forms:
onCancel(): void {
this.registrationForm.reset();
this.registrationForm.controls['name'].setErrors(null);
this.registrationForm.controls['email'].setErrors(null);
}
use isinstance(v, type_name)
or type(v) is type_name
or type(v) == type_name
,
where type_name can be one of the following:
and, of course,
I just came up with a solution for sending stdout
to one command and stderr
to another, using named pipes.
Here goes.
mkfifo stdout-target
mkfifo stderr-target
cat < stdout-target | command-for-stdout &
cat < stderr-target | command-for-stderr &
main-command 1>stdout-target 2>stderr-target
It's probably a good idea to remove the named pipes afterward.
# This program reads columns in a csv file
import csv
ifile = open('years.csv', "r")
reader = csv.reader(ifile)
# initialization and declaration of variables
rownum = 0
year = 0
dec = 0
jan = 0
total_years = 0`
for row in reader:
if rownum == 0:
header = row #work with header row if you like
else:
colnum = 0
for col in row:
if colnum == 0:
year = float(col)
if colnum == 1:
dec = float(col)
if colnum == 2:
jan = float(col)
colnum += 1
# end of if structure
# now we can process results
if rownum != 0:
print(year, dec, jan)
total_years = total_years + year
print(total_years)
# time to go after the next row/bar
rownum += 1
ifile.close()
A bit late but nonetheless... You need to create and identify the csv file named "years.csv":
Year Dec Jan 1 50 60 2 25 50 3 30 30 4 40 20 5 10 10
Add to server.xml :
<Context docBase="c:/dirtoshare" path="/dir" />
Enable dir file listing parameter in web.xml :
<init-param>
<param-name>listings</param-name>
<param-value>true</param-value>
</init-param>
First modify the column to remove the auto_increment field like this: alter table user_customer_permission modify column id int;
Next, drop the primary key. alter table user_customer_permission drop primary key;
Better yet, configure the editor to something you are comfortable with (gedit as an example):
git config --global core.editor "gedit"
You can read the current configuration like this:
git config core.editor
You can also add the commit message from the command line.
git commit -m "blablabla"
and the editor will not be opened in the first place.
There is nothing wrong with your code. It's the NBC.com doing tricks on you. When NBC.com decides that your browser is not capable of displaying PDF, it simply sends back a webpage regardless what you are requesting, even if it doesn't exist.
You need to trick it back by telling it your browser is capable, something like,
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13");
sqlCommand.CommandType = CommandType.Text
@
and not ?
try this:
Public Function InsertCar() As Boolean
Dim iReturn as boolean
Using SQLConnection As New MySqlConnection(connectionString)
Using sqlCommand As New MySqlCommand()
With sqlCommand
.CommandText = "INSERT INTO members_car (`car_id`, `member_id`, `model`, `color`, `chassis_id`, `plate_number`, `code`) values (@xid,@m_id,@imodel,@icolor,@ch_id,@pt_num,@icode)"
.Connection = SQLConnection
.CommandType = CommandType.Text // You missed this line
.Parameters.AddWithValue("@xid", TextBox20.Text)
.Parameters.AddWithValue("@m_id", TextBox20.Text)
.Parameters.AddWithValue("@imodel", TextBox23.Text)
.Parameters.AddWithValue("@icolor", TextBox24.Text)
.Parameters.AddWithValue("@ch_id", TextBox22.Text)
.Parameters.AddWithValue("@pt_num", TextBox21.Text)
.Parameters.AddWithValue("@icode", ComboBox1.SelectedItem)
End With
Try
SQLConnection.Open()
sqlCommand.ExecuteNonQuery()
iReturn = TRUE
Catch ex As MySqlException
MsgBox ex.Message.ToString
iReturn = False
Finally
SQLConnection.Close()
End Try
End Using
End Using
Return iReturn
End Function
You can use the shift keyword (operator?) to iterate through them. Example:
#!/bin/bash
function print()
{
while [ $# -gt 0 ]
do
echo $1;
shift 1;
done
}
print $*;
You can either use (on the h4 elements, as they are block by default)
display: inline-block;
Or you can float the elements to the left/rght
float: left;
Just don't forget to clear the floats after
clear: left;
More visual example for the float left/right option as shared below by @VSB:
<h4> _x000D_
<div style="float:left;">Left Text</div>_x000D_
<div style="float:right;">Right Text</div>_x000D_
<div style="clear: left;"/>_x000D_
</h4>
_x000D_
you can set an image URL for the content prop instead of the background-image.
content: url(/img/border-left3.png);
This is because PHP uses the period character .
for string concatenation, not the plus character +
. Therefore to append to a string you want to use the .=
operator:
for ($i=1;$i<=100;$i++)
{
$selectBox .= '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox .= '</select>';