There are other libraries that are JSON compatible, which support comments.
One notable example is the "Hashcorp Language" (HCL)". It is written by the same people who made Vagrant, packer, consul, and vault.
This is how I get the number of hours that elapsed between two datetime.datetime objects:
before = datetime.datetime.now()
after = datetime.datetime.now()
hours = math.floor(((after - before).seconds) / 3600)
As found on this website So Let’s begin by installing jEnv
Run this in the terminal
brew install https://raw.github.com/gcuisinier/jenv/homebrew/jenv.rb
Add jEnv to the bash profile
if which jenv > /dev/null; then eval "$(jenv init -)"; fi
When you first install jEnv will not have any JDK associated with it.
For example, I just installed JDK 8 but jEnv does not know about it. To check Java versions on jEnv
At the moment it only found Java version(jre) on the system. The *
shows the version currently selected. Unlike rvm and rbenv, jEnv cannot install JDK for you. You need to install JDK manually from Oracle website.
Install JDK 6 from Apple website. This will install Java in /System/Library/Java/JavaVirtualMachines/
. The reason we are installing Java 6 from Apple website is that SUN did not come up with JDK 6 for MAC, so Apple created/modified its own deployment version.
Similarly install JDK7 and JDK8.
Add JDKs to jEnv.
JDK 6:
Check the java versions installed using jenv
So now we have 3 versions of Java on our system. To set a default version use the command
jenv local <jenv version>
Ex – I wanted Jdk 1.6 to start IntelliJ
jenv local oracle64-1.6.0.65
check the java version
That’s it. We now have multiple versions of java and we can switch between them easily. jEnv also has some other features, such as wrappers for Gradle, Ant, Maven, etc, and the ability to set JVM options globally or locally. Check out the documentation for more information.
I'm able to make it in a native way @ jsfiddle. Hope it will help.
Post improved answer when it work, and help others.
$(function () {
$(".example").multiselect({
checkAllText : 'Select All',
uncheckAllText : 'Deselect All',
selectedText: function(numChecked, numTotal, checkedItems){
return numChecked + ' of ' + numTotal + ' checked';
},
minWidth: 325
});
$(".example").multiselect("checkAll");
});
You need to add the URL to your app:
That's all and you are done. Make sure that the app's URL is the same from where you're logging in.
Creating a .bashrc file in your home directory also works. That way you don't have to copy your .bash_profile every time you install a new version of git bash.
It may be useful to you to simply increase the number of results that get displayed
In the mongo shell >
DBQuery.shellBatchSize = 3000
and then you can select all the results out of the terminal in one go and paste into a text file.
It is what I am going to do :)
I'm quite sure this can be very simple
2.0.0p247 :032 > list = Array.new(5)
=> [nil, nil, nil, nil, nil]
2.0.0p247 :033 > list.map!{ |x| x = [0] }
=> [[0], [0], [0], [0], [0]]
2.0.0p247 :034 > list[0][0]
=> 0
Yo can simply google for "exit sub in c#".
Also why would you check every text box if it is empty. You can place requiredfieldvalidator for these text boxes if this is an asp.net app and check if(Page.IsValid)
Or another solution is to get not of these conditions:
private void button1_Click(object sender, EventArgs e)
{
if (!(textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == ""))
{
//do events
}
}
And better use String.IsNullOrEmpty:
private void button1_Click(object sender, EventArgs e)
{
if (!(String.IsNullOrEmpty(textBox1.Text)
|| String.IsNullOrEmpty(textBox2.Text)
|| String.IsNullOrEmpty(textBox3.Text)))
{
//do events
}
}
If you want to get a constraint by the column or table names, or you want to get all the constraints in the database, look to other answers. However, if you're just looking for exactly what the question asks, namely, to "test if a given default constraint exists ... by the name of the constraint", then there's a much easier way.
Here's a future-proof answer that doesn't use the sysobjects
or other sys
tables at all:
IF object_id('DF_CONSTRAINT_NAME', 'D') IS NOT NULL BEGIN
-- constraint exists, work with it.
END
There is a problem with upgrading npm under Windows. The inital install done as part of the nodejs install using an msi package will create an npmrc file:
C:\Program Files\nodejs\node_modules\npm\npmrc
when you update npm using:
npm install -g npm@latest
it will install the new version in:
C:\Users\Jack\AppData\Roaming\npm
assuming that your name is Jack, which is %APPDATA%\npm.
The new install does not include an npmrc file and without it the global root directory will be based on where node was run from, hence it is C:\Program Files\nodejs\node_modules
You can check this by running:
npm root -g
This will not work as npm does not have permission to write into the "Program Files"
directory. You need to copy the npmrc file from the original install into the new install. By default the file only has the line below:
prefix=${APPDATA}\npm
The accepted solution does not work unless the browser takes up the full screen,
This seems to always work
const popupCenterScreen = (url, title, w, h, focus) => {
const top = (screen.height - h) / 4, left = (screen.width - w) / 2;
const popup = window.open(url, title, `scrollbars=yes,width=${w},height=${h},top=${top},left=${left}`);
if (focus === true && window.focus) popup.focus();
return popup;
}
Impl:
some.function.call({data: ''})
.then(result =>
popupCenterScreen(
result.data.url,
result.data.title,
result.data.width,
result.data.height,
true));
If you are using a C99 compiler it has built-in support for bool types:
#include <stdbool.h>
int main()
{
bool b = false;
b = true;
}
After going mad trying to remove the border in IE7, I found that the frameBorder attribute is case sensitive.
You have to set the frameBorder attribute with a capital B.
<iframe frameBorder="0"></iframe>
InputStream in = new ByteArrayInputStream(yourstring.getBytes());
If you want to go the other way round (associate FILE* with existing file descriptor), use fdopen() :
FDOPEN(P)
NAME
fdopen - associate a stream with a file descriptor
SYNOPSIS
#include <stdio.h>
FILE *fdopen(int fildes, const char *mode);
This is how you can insert into an identity column:
CREATE TABLE my_table (id INTEGER PRIMARY KEY AUTOINCREMENT, name COLLATE NOCASE);
CREATE TABLE temp_table (name COLLATE NOCASE);
.import predefined/myfile.txt temp_table
insert into my_table (name) select name from temp_table;
myfile.txt is a file in C:\code\db\predefined\
data.db is in C:\code\db\
myfile.txt contains strings separated by newline character.
If you want to add more columns, it's easier to separate them using the pipe character, which is the default.
# This code works fine in QtSpim simulator
.data
buffer: .space 20
str1: .asciiz "Enter string"
str2: .asciiz "You wrote:\n"
.text
main:
la $a0, str1 # Load and print string asking for string
li $v0, 4
syscall
li $v0, 8 # take in input
la $a0, buffer # load byte space into address
li $a1, 20 # allot the byte space for string
move $t0, $a0 # save string to t0
syscall
la $a0, str2 # load and print "you wrote" string
li $v0, 4
syscall
la $a0, buffer # reload byte space to primary address
move $a0, $t0 # primary address = t0 address (load pointer)
li $v0, 4 # print string
syscall
li $v0, 10 # end program
syscall
For those using Codeigniter, add this below your sidebar menu,
<script>
$(document).ready(function () {
$(".nav li").removeClass("active");
var currentUrl = "<?php echo current_url(); ?>";
$('a[href="' + currentUrl + '"]').parents('li,ul').addClass('active');
});
</script>
I think that is easier than this.
You can change 'tabs' at left side of the wizard (General, Files, Options)
You don't have to give up simple css :)
.short { max-width: 300px; }
<input type="text" class="form-control short" id="...">
No need of any manual break in code. Just add \n where you want to break.
alert ("Please Select file \n to delete");
This will show the alert like
Please select file
to delete.
With an editable div you can use the method document.execCommand
(more details) to easily provide the support for the tags you specified and for some other functionality..
#text {_x000D_
width : 500px;_x000D_
min-height : 100px;_x000D_
border : 2px solid;_x000D_
}
_x000D_
<div id="text" contenteditable="true"></div>_x000D_
<button onclick="document.execCommand('bold');">toggle bold</button>_x000D_
<button onclick="document.execCommand('italic');">toggle italic</button>_x000D_
<button onclick="document.execCommand('underline');">toggle underline</button>
_x000D_
I use the ~/.Rprofile solution suggested by Dirk, but I just wanted to point out that
chooseCRANmirror(graphics=FALSE)
seems to be the sensible thing to do instead of
chooseCRANmirror(81)
, which may work, but which involves the magic number 81 (or maybe this is subtle way to promote tourism to 81 = UK (Bristol) :-) )
Here is the alternative command:
gnuplot -p -e 'plot for [file in system("find . -name \\*.txt -depth 1")] file using 1:2 title file with lines'
The include path is set against the server configuration (PHP.ini) but the include path you specify is relative to that path so in your case the include path is (actual path in windows):
C:\xampp\php\PEAR\initcontrols\header_myworks.php
providing the path you pasted in the subject is correct. Make sure your file is located there.
For more info you can get and set the include path programmatically.
public class User : List<UserData>
{
public int id { get; set; }
public string screen_name { get; set; }
}
string json = client.DownloadString(url);
JavaScriptSerializer serializer = new JavaScriptSerializer();
var Data = serializer.Deserialize<List<UserData>>(json);
Had a similar issue, and tried lots of things. Ultimately what worked for me, was to have Gnu on Windows installed (https://github.com/bmatzelle/gow/releases) , and ensure that it was using the ssh tool inside that directory and not the one with Git. Once installed test with (ensure if its in your environment PATH that it preceds Git\bin)
C:\Git\htest2>which ssh
C:\Program Files (x86)\Gow\bin\ssh.BAT
I used putty and pageant as described here:http://rubyonrailswin.wordpress.com/2010/03/08/getting-git-to-work-on-heroku-on-windows-using-putty-plink-pageant/
Once the keys had been sent to heroku (heroku keys:add c:\Users\Person.ssh\id_rsa.pub), use
ssh -v <username>@heroku.com
and ensure that your stack is showing use of Putty - ie a working stack:
Looking up host "heroku.com"
Connecting to 50.19.85.132 port 22
Server version: SSH-2.0-Twisted
Using SSH protocol version 2
**We claim version: SSH-2.0-PuTTY_Release_0.62**
Using Diffie-Hellman with standard group "group1"
Doing Diffie-Hellman key exchange with hash SHA-1
Host key fingerprint is:
ssh-rsa 2048 8b:48:5e:67:0e:c9:16:47:32:f2:87:0c:1f:c8:60:ad
Initialised AES-256 SDCTR client->server encryption
Initialised HMAC-SHA1 client->server MAC algorithm
Initialised AES-256 SDCTR server->client encryption
Initialised HMAC-SHA1 server->client MAC algorithm
Pageant is running. Requesting keys.
Pageant has 1 SSH-2 keys
Using username "*--ommitted for security--*".
**Trying Pageant key #0**
Authenticating with public key "rsa-key-20140401" from agent
Sending Pageant's response
Access granted
Opened channel for session
Server refused to allocate pty
Server refused to start a shell/command
FATAL ERROR: Server refused to start a shell/command
One that was running previously and failed:
C:\Git\htest2>ssh -v <username>@[email protected]
OpenSSH_4.6p1, OpenSSL 0.9.8e 23 Feb 2007
debug1: Connecting to heroku.com [50.19.85.156] port 22.
debug1: Connection established.
debug1: identity file /c/Users/Person/.ssh/identity type -1
debug1: identity file /c/Users/Person/.ssh/id_rsa type 1
debug1: identity file /c/Users/Person/.ssh/id_dsa type -1
debug1: Remote protocol version 2.0, remote software version Twisted
debug1: no match: Twisted
debug1: Enabling compatibility mode for protocol 2.0
**debug1: Local version string SSH-2.0-OpenSSH_4.6**
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-cbc hmac-md5 none
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: sending SSH2_MSG_KEXDH_INIT
debug1: expecting SSH2_MSG_KEXDH_REPLY
debug1: Host 'heroku.com' is known and matches the RSA host key.
debug1: Found key in /c/Users/Person/.ssh/known_hosts:1
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /c/Users/Person/.ssh/identity
debug1: Offering public key: /c/Users/Person/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 277
debug1: Trying private key: /c/Users/Person/.ssh/id_dsa
debug1: No more authentication methods to try.
Permission denied (publickey).
You can create a startTime and endTime of DateTime, then do endTime.Subtract(startTime). Then output your span.Seconds.
I think that should work.
Yes, we can pass arrays to a function.
$arr = array(“a” => “first”, “b” => “second”, “c” => “third”);
function user_defined($item, $key)
{
echo $key.”-”.$item.”<br/>”;
}
array_walk($arr, ‘user_defined’);
We can find more array functions here
You can send intent MASTER_CLEAR in adb:
adb shell am broadcast -a android.intent.action.MASTER_CLEAR
or as root
adb shell "su -c 'am broadcast -a android.intent.action.MASTER_CLEAR'"
Most of the other answers point to eager loading, but I found another solution.
In my case I had an EF object InventoryItem
with a collection of InvActivity
child objects.
class InventoryItem {
...
// EF code first declaration of a cross table relationship
public virtual List<InvActivity> ItemsActivity { get; set; }
public GetLatestActivity()
{
return ItemActivity?.OrderByDescending(x => x.DateEntered).SingleOrDefault();
}
...
}
And since I was pulling from the child object collection instead of a context query (with IQueryable
), the Include()
function was not available to implement eager loading. So instead my solution was to create a context from where I utilized GetLatestActivity()
and attach()
the returned object:
using (DBContext ctx = new DBContext())
{
var latestAct = _item.GetLatestActivity();
// attach the Entity object back to a usable database context
ctx.InventoryActivity.Attach(latestAct);
// your code that would make use of the latestAct's lazy loading
// ie latestAct.lazyLoadedChild.name = "foo";
}
Thus you aren't stuck with eager loading.
Add alias bashs="source ~/.bash_profile"
in to your bash file.
So you can call bashs
from next time
python: read lines from compressed text files
Using gzip.GzipFile
:
import gzip
with gzip.open('input.gz','r') as fin:
for line in fin:
print('got line', line)
Answer:
public void Print(string FileName)
{
StringBuilder logMessage = new StringBuilder();
logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "-------------------[ START - {0} - {1} -------------------]", MethodBase.GetCurrentMethod(), DateTime.Now.ToShortDateString()));
logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "Parameter: 1: [Name - {0}, Value - {1}", "None]", Convert.ToString("")));
try
{
if (string.IsNullOrWhiteSpace(FileName)) return; // Prevents execution of below statements if filename is not selected.
PrintDocument pd = new PrintDocument();
//Disable the printing document pop-up dialog shown during printing.
PrintController printController = new StandardPrintController();
pd.PrintController = printController;
//For testing only: Hardcoded set paper size to particular paper.
//pd.PrinterSettings.DefaultPageSettings.PaperSize = new PaperSize("Custom 6x4", 720, 478);
//pd.DefaultPageSettings.PaperSize = new PaperSize("Custom 6x4", 720, 478);
pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
pd.PrinterSettings.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
pd.PrintPage += (sndr, args) =>
{
System.Drawing.Image i = System.Drawing.Image.FromFile(FileName);
//Adjust the size of the image to the page to print the full image without loosing any part of the image.
System.Drawing.Rectangle m = args.MarginBounds;
//Logic below maintains Aspect Ratio.
if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
}
//Calculating optimal orientation.
pd.DefaultPageSettings.Landscape = m.Width > m.Height;
//Putting image in center of page.
m.Y = (int)((((System.Drawing.Printing.PrintDocument)(sndr)).DefaultPageSettings.PaperSize.Height - m.Height) / 2);
m.X = (int)((((System.Drawing.Printing.PrintDocument)(sndr)).DefaultPageSettings.PaperSize.Width - m.Width) / 2);
args.Graphics.DrawImage(i, m);
};
pd.Print();
}
catch (Exception ex)
{
log.ErrorFormat("Error : {0}\n By : {1}-{2}", ex.ToString(), this.GetType(), MethodBase.GetCurrentMethod().Name);
}
finally
{
logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "-------------------[ END - {0} - {1} -------------------]", MethodBase.GetCurrentMethod().Name, DateTime.Now.ToShortDateString()));
log.Info(logMessage.ToString());
}
}
Your example wasn't working because you are trying to add 1 to a string that looks like this: "1.html". That will just get you this "1.html1" which is not what you want. You have to isolate the numeric part of the string and then convert it to an actual number before you can do math on it. After getting it to an actual number, you can then increase its value and then combine it back with the rest of the string.
You can use a custom replace function like this to isolate the various pieces of the original URL and replace the number with an incremented number:
function nextImage() {
return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
return((Number(p1) + 1) + p2);
}));
}
You can then call it like this:
window.location.href = nextImage();
Demo here: http://jsfiddle.net/jfriend00/3VPEq/
This will work for any URL that ends in some series of digits followed by .html and if you needed a slightly different URL form, you could just tweak the regular expression.
Easiest way to clear/reset the text field on click is to clear/reset the scope
<input type="text" class="form-control" ng-model="searchAll" ng-click="clearfunction(this)"/>
In Controller
$scope.clearfunction=function(event){
event.searchAll=null;
}
I've coded a small Node.js module to scrape app and list data from Google Play: google-play-scraper
var gplay = require('google-play-scrapper');
gplay.List({
category: gplay.category.GAME_ACTION,
collection: gplay.collection.TOP_FREE,
num: 2
}).then(console.log);
Results:
[ { url: 'https://play.google.com/store/apps/details?id=com.playappking.busrush',
appId: 'com.playappking.busrush',
title: 'Bus Rush',
developer: 'Play App King',
icon: 'https://lh3.googleusercontent.com/R6hmyJ6ls6wskk5hHFoW02yEyJpSG36il4JBkVf-Aojb1q4ZJ9nrGsx6lwsRtnTqfA=w340',
score: 3.9,
price: '0',
free: false },
{ url: 'https://play.google.com/store/apps/details?id=com.yodo1.crossyroad',
appId: 'com.yodo1.crossyroad',
title: 'Crossy Road',
developer: 'Yodo1 Games',
icon: 'https://lh3.googleusercontent.com/doHqbSPNekdR694M-4rAu9P2B3V6ivff76fqItheZGJiN4NBw6TrxhIxCEpqgO3jKVg=w340',
score: 4.5,
price: '0',
free: false } ]
You are casting ClientID
to char* causing the function to assume its a null terinated char array, which it is not.
from cplusplus.com :
string& append ( const char * s ); Appends a copy of the string formed by the null-terminated character sequence (C string) pointed by s. The length of this character sequence is determined by the first ocurrence of a null character (as determined by traits.length(s)).
If you need binary mode, you'll need to do it the hard way:
s = File.open(filename, 'rb') { |f| f.read }
If not, shorter and sweeter is:
s = IO.read(filename)
Another common gotcha is thinking you can ignore the Form DragOver (or DragEnter) events. I typically use the Form's DragOver event to set the AllowedEffect, and then a specific control's DragDrop event to handle the dropped data.
Set style= "display:none;"
. By setting visible=false
, it will not render button in the browser. Thus,client side script wont execute.
<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />
html markup should be
<button id="btnsave" onclick="fncsave()">Save</button>
Change javascript to
<script type="text/javascript">
function fncsave()
{
document.getElementById('<%= savebtn.ClientID %>').click();
}
</script>
If you want to concatenate the input, then replace printf("%s\n", buffer);
with strcat(big_buffer, buffer);
. Also create and initialize the big buffer at the beginning: char *big_buffer = new char[BIG_BUFFERSIZE];
big_buffer[0] = '\0';
. You should also prevent a buffer overrun by verifying the current buffer length plus the new buffer length does not exceed the limit: if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE)
. The modified program would look like this:
#include <stdio.h>
#include <string.h>
#define BUFFERSIZE 10
#define BIG_BUFFERSIZE 1024
int main (int argc, char *argv[])
{
char buffer[BUFFERSIZE];
char *big_buffer = new char[BIG_BUFFERSIZE];
big_buffer[0] = '\0';
printf("Enter a message: \n");
while(fgets(buffer, BUFFERSIZE , stdin) != NULL)
{
if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE)
{
strcat(big_buffer, buffer);
}
}
return 0;
}
You're right that you should use the Dispatcher
to update controls on the UI thread, and also right that long-running processes should not run on the UI thread. Even if you run the long-running process asynchronously on the UI thread, it can still cause performance issues.
It should be noted that Dispatcher.CurrentDispatcher
will return the dispatcher for the current thread, not necessarily the UI thread. I think you can use Application.Current.Dispatcher
to get a reference to the UI thread's dispatcher if that's available to you, but if not you'll have to pass the UI dispatcher in to your background thread.
Typically I use the Task Parallel Library for threading operations instead of a BackgroundWorker
. I just find it easier to use.
For example,
Task.Factory.StartNew(() =>
SomeObject.RunLongProcess(someDataObject));
where
void RunLongProcess(SomeViewModel someDataObject)
{
for (int i = 0; i <= 1000; i++)
{
Thread.Sleep(10);
// Update every 10 executions
if (i % 10 == 0)
{
// Send message to UI thread
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Normal,
(Action)(() => someDataObject.ProgressValue = (i / 1000)));
}
}
}
If you are using MySQL you can do it like this:
SELECT '2008-12-31 23:59:59' + INTERVAL 30 MINUTE;
For a pure PHP solution use strtotime
strtotime('+ 30 minute',$yourdate);
Oracle DateDiff is from a different product, probably mysql (which is now owned by Oracle).
The difference between two dates (in oracle's usual database product) is in days (which can have fractional parts). Factor by 24 to get hours, 24*60 to get minutes, 24*60*60 to get seconds (that's as small as dates go). The math is 100% accurate for dates within a couple of hundred years or so. E.g. to get the date one second before midnight of today, you could say
select trunc(sysdate) - 1/24/60/60 from dual;
That means "the time right now", truncated to be just the date (i.e. the midnight that occurred this morning). Then it subtracts a number which is the fraction of 1 day that measures one second. That gives you the date from the previous day with the time component of 23:59:59.
You should ensure the HTTP server headers are correct.
In particular, the header:
Content-Type: text/html; charset=utf-8
should be present.
The meta tag is ignored by browsers if the HTTP header is present.
Also ensure that your file is actually encoded as UTF-8 before serving it, check/try the following:
&#uuu;
.Note: If you use an unicode character for which your system can't find a glyph (no font with that character), your browser should display a question mark or some block like symbol. But if you see multiple roman characters like you do, this denotes an encoding problem.
ip = InetAddress.getByAddress(new byte[] {
(byte)192, (byte)168, (byte)0, (byte)102}
);
To remove the separator between items in the same ListView, here is the solution:
getListView().setDivider(null);
getListView().setDividerHeight(0);
developer.android.com # ListView
Or, if you want to do it in XML:
android:divider="@null"
android:dividerHeight="0dp"
This answer is similar to the accepted one, but a bit less convoluted.
L<-list()
for (i in 1:3) {
L<-c(L, list(list(sample(1:3))))
}
One of the below solve your problem
URL::previous()
URL::back()
other
URL::current()
This is a convention defined in RFC 2045 - Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies.
Private [subtype] values (starting with "X-") may be defined bilaterally between two cooperating agents without outside registration or standardization. Such values cannot be registered or standardized.
New standard values should be registered with IANA as described in RFC 2048.
A similar restriction applies to the top-level type. From the same source,
If another top-level type is to be used for any reason, it must be given a name starting with "X-" to indicate its non-standard status and to avoid a potential conflict with a future official name.
(Note that per RFC 2045, "[m]atching of media type and subtype is ALWAYS case-insensitive", so there's no difference between the interpretation of 'X-' and 'x-'.)
So it's fair to guess that "application/x-foo" was used before the IANA defined "application/foo". And it still might be used by folks who aren't aware of the IANA token assignment.
As Chris Hanson said MIME types are controlled by the IANA. This is detailed in RFC 2048 - Multipurpose Internet Mail Extensions (MIME) Part Four: Registration Procedures. According to RFC 3778, which is cited by the IANA as the definition for "application/pdf",
The application/pdf media type was first registered in 1993 by Paul Lindner for use by the gopher protocol; the registration was subsequently updated in 1994 by Steve Zilles.
The type "application/pdf" has been around for well over a decade. So it seems to me that wherever "application/x-pdf" has been used in new apps, the decision may not have been deliberate.
For PHP's own session cookies on Apache:
add this to your Apache configuration or .htaccess
<IfModule php5_module>
php_flag session.cookie_httponly on
</IfModule>
This can also be set within a script, as long as it is called before session_start()
.
ini_set( 'session.cookie_httponly', 1 );
A String is a type of Object. So any method that accepts Object as parameter will surely accept String also. Please provide more of your code if you still do not find a solution.
A quick, clean approach using very little JS and CSS padding: http://jsfiddle.net/benjamincharity/ZcTsT/14/
var headerHeight = $('#header').height(),
footerHeight = $('#footer').height();
$('#content').css({
'padding-top': headerHeight,
'padding-bottom': footerHeight
});
You can use jQuery serialize function along with get/post as follows:
$.get('server.php?' + $('#theForm').serialize())
$.post('server.php', $('#theform').serialize())
jQuery Serialize Documentation: http://api.jquery.com/serialize/
Simple AJAX submit using jQuery:
// this is the id of the submit button
$("#submitButtonId").click(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
Maybe a more simple solution.
if ($(document).height() > $(window).height()) {
// scrollbar
}
TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, NT, 2000 and XP TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows. The TCPView download includes Tcpvcon, a command-line version with the same functionality.
http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx
In my case I had a ucfirst
on the asian letters string. This was not possible and produced a non utf8 string.
It might not be the best practice, but you can simply target a specific column using collect()
, export it as a list of Rows, and loop through the list.
Assume this is your df:
+----------+----------+-------------------+-----------+-----------+------------------+
| Date| New_Date| New_Timestamp|date_sub_10|date_add_10|time_diff_from_now|
+----------+----------+-------------------+-----------+-----------+------------------+
|2020-09-23|2020-09-23|2020-09-23 00:00:00| 2020-09-13| 2020-10-03| 51148 |
|2020-09-24|2020-09-24|2020-09-24 00:00:00| 2020-09-14| 2020-10-04| -35252 |
|2020-01-25|2020-01-25|2020-01-25 00:00:00| 2020-01-15| 2020-02-04| 20963548 |
|2020-01-11|2020-01-11|2020-01-11 00:00:00| 2020-01-01| 2020-01-21| 22173148 |
+----------+----------+-------------------+-----------+-----------+------------------+
to loop through rows in Date column:
rows = df3.select('Date').collect()
final_list = []
for i in rows:
final_list.append(i[0])
print(final_list)
Twitter has a public API which returns JSON, for example -
A GET
request to:
https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=mralexgray&count=1
,
EDIT: Removed due to twitter restricting their API with OAUTH
requirements...
{"errors": [{"message": "The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.", "code": 68}]}
Replacing it with a simple example of the Github API - that returns a tree, of in this case, my repositories...
I won't include the output, as it's long.. (returns 30 repos at a time) ... But here is proof of it's tree-ed-ness.
This works for me,
DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;
DateTimeFormatInfo ukDtfi = new CultureInfo("en-GB", false).DateTimeFormat;
string result = Convert.ToDateTime("26/09/2015",ukDtfi).ToString(usDtfi.ShortDatePattern);
The disappointing thing here is that the "X" isn't transparent (which is how I would likely create a PNG, at least).
I put together this quick test. http://jsfiddle.net/UM3a2/22/embedded/result/ which allows you to color the positive space while leaving the negative space transparent. Since it is made entirely of borders it is easy to color since border-color defaults to the text color.
It doesn't fully support I.E. 8 and earlier (border-radius issues), but it degrades to a square fairly nicely (if you're okay with a square close button).
It also requires two HTML elements since you are only allowed two pseudo elements per selector. I don't know exactly where I learned this, but I think it was in an article by Chris Coyier.
<div id="close" class="arrow-t-b">
Close
<div class="arrow-l-r"> </div>
</div>
#close {
border-width: 4px;
border-style: solid;
border-radius: 100%;
color: #333;
height: 12px;
margin:auto;
position: relative;
text-indent: -9999px;
width: 12px;
}
#close:hover {
color: #39F;
}
.arrow-t-b:after,
.arrow-t-b:before,
.arrow-l-r:after,
.arrow-l-r:before {
border-color: transparent;
border-style: solid;
border-width: 4px;
content: "";
left: 2px;
top: 0px;
position: absolute;
}
.arrow-t-b:after {
border-top-color: inherit;
}
.arrow-l-r:after {
border-right-color: inherit;
left: 4px;
top: 2px;
}
.arrow-t-b:before {
border-bottom-color: inherit;
bottom: 0;
}
.arrow-l-r:before {
border-left-color: inherit;
left: 0;
top: 2px;
}
Your first CSS selector—social.h2
—is looking for the "social" element in the "h2", class, e.g.:
<social class="h2">
Class selectors are proceeded with a dot (.
). Also, use a space () to indicate that one element is inside of another. To find an
<h2>
descendant of an element in the social
class, try something like:
.social h2 {
color: pink;
font-size: 14px;
}
To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.
Try EPPlus if you use Excel 2007. Supports ranges, cellstyling, charts, shapes, pictures and a lot of other stuff
For instance you can use
update tablename set datetimefield='19980223 14:23:05'
update tablename set datetimefield='02/23/1998 14:23:05'
update tablename set datetimefield='1998-12-23 14:23:05'
update tablename set datetimefield='23 February 1998 14:23:05'
update tablename set datetimefield='1998-02-23T14:23:05'
You need to be careful of day/month order since this will be language dependent when the year is not specified first. If you specify the year first then there is no problem; date order will always be year-month-day.
You want to multiply out to milliseconds as the fractional part is discarded.
SELECT DATEADD(ms, 121.25 * 1000, 0)
If you want it without the date portion you can use CONVERT, with style 114
SELECT CONVERT(varchar, DATEADD(ms, 121.25 * 1000, 0), 114)
It's an encoding error - so if it's a unicode string, this ought to fix it:
text.encode("windows-1252").decode("utf-8")
If it's a plain string, you'll need an extra step:
text.decode("utf-8").encode("windows-1252").decode("utf-8")
Both of these will give you a unicode string.
By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:
>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}
I see a few answers here, most of them complicated or with some cons (additional divs, text-align doesn't work because of display: inline-block). I think this is the simplest and problem-free solution:
HTML:
<table>
<!-- Rows -->
<tr>
<td>E-MAIL</td>
<td><input name="email" type="email" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Register!" /></td>
</tr>
</table>
CSS:
table input[type="submit"] {
display: block;
margin: 0 auto;
}
Not sure why do you need w,h. If these values are actually required and mean that only specified number of rows and cols should be read than you can try the following:
output = []
with open(r'c:\file.txt', 'r') as f:
w, h = map(int, f.readline().split())
tmp = []
for i, line in enumerate(f):
if i == h:
break
tmp.append(map(int, line.split()[:w]))
output.append(tmp)
This is what I came up with:
$(document).ready(function(){_x000D_
_x000D_
$(".fc-event").each(function(){_x000D_
_x000D_
console.log(this.attributes['data'].nodeValue) _x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>_x000D_
<div id='external-events'>_x000D_
<h4>Booking</h4>_x000D_
<div class='fc-event' data='00:30:00' >30 Mins</div>_x000D_
<div class='fc-event' data='00:45:00' >45 Mins</div>_x000D_
</div>
_x000D_
Basically set up your css like:
element {
border: 1px solid #fff;
transition: border .5s linear;
}
element.saved {
border: 1px solid transparent;
}
Check this Official Link
You can use the AssemblyName
class to get the assembly name, provided you have the full name for the assembly:
AssemblyName.GetAssemblyName(Assembly.GetExecutingAssembly().FullName).Name
or
AssemblyName.GetAssemblyName(e.Source).Name
Its just like creating a WAR
file of your project, you can do it in several ways (from Eclipse, command line, maven).
If you want to do from command line, the command is
jar -cvf my_web_app.war *
Which means, "compress everything in this directory into a file named my_web_app.war" (c=create, v=verbose, f=file)
In your example you are comparing the string objects, not their content.
Your comparison should be :
if (s.equals("/quit"))
Or if s
string nullity doesn't mind / or you really don't like NPEs:
if ("/quit".equals(s))
The onclick
attribute on your anchor tag is going to call a client-side function. (This is what you would use if you wanted to call a javascript function when the link is clicked.)
What you want is a server-side control, like the LinkButton
:
<asp:LinkButton ID="lnkTutorial" runat="server" Text="Tutorial" OnClick="displayTutorial_Click"/>
This has an OnClick
attribute that will call the method in your code behind.
Looking further into your code, it looks like you're just trying to open a different tutorial based on access level of the user. You don't need an event handler for this at all. A far better approach would be to just set the end point of your LinkButton
control in the code behind.
protected void Page_Load(object sender, EventArgs e)
{
userinfo = (UserInfo)Session["UserInfo"];
if (userinfo.user == "Admin")
{
lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
}
else
{
lnkTutorial.PostBackUrl = "help/UserTutorial.html";
}
}
Really, it would be best to check that you actually have a user first.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserInfo"] != null && ((UserInfo)Session["UserInfo"]).user == "Admin")
{
lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
}
else
{
lnkTutorial.PostBackUrl = "help/UserTutorial.html";
}
}
Create a PowerShell script with the following code in the file.
param([string]$path)
Get-ChildItem $path | Where-Object {$_.LinkType -eq 'SymbolicLink'} | select name, target
This creates a script with a path parameter. It will list all symbolic links within the path provided as well as the specified target of the symbolic link.
if (row.Columns.Contains("US_OTHERFRIEND"))
Two things I noticed (they may be mistakes from when you wrote it down though).
$('.navlink').click
)return $(this).data("selected")==true
)To add Tomer and Charles answers,
Syntax to run nginx in forground in Docker container using Entrypoint:
ENTRYPOINT nginx -g 'daemon off;'
Not directly related but to run multiple commands with Entrypoint:
ENTRYPOINT /bin/bash -x /myscripts/myscript.sh && nginx -g 'daemon off;'
Log into AWS Management Console. Navigate to RDS then select the db instance and go to "security Groups". Adding CIDR/IP under the security group fixed the problem.
As a generic solution, I recommend that you remove all the secondary dependencies and run the application, if it worked, revert back some, and continue doing the same as long as the application starts, in the end, you will be able to identify which dependency caused the issue.
Using the same way, for example, I found that dependencies whose the groupId is: org.apache.axis2 have caused the issue.
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-transport-local</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-transport-http</artifactId>
<version>1.6.1</version>
</dependency>
The best way I've always had to mentally visualize an algorithm that runs in O(log n) is as follows:
If you increase the problem size by a multiplicative amount (i.e. multiply its size by 10), the work is only increased by an additive amount.
Applying this to your binary tree question so you have a good application: if you double the number of nodes in a binary tree, the height only increases by 1 (an additive amount). If you double it again, it still only increased by 1. (Obviously I'm assuming it stays balanced and such). That way, instead of doubling your work when the problem size is multiplied, you're only doing very slightly more work. That's why O(log n) algorithms are awesome.
I would recommend having a look at this answer of mine, and see if it is relevant to what you are doing. If I understand your real problem, it's that your just not using your async action correctly and updating the redux "store", which will automatically update your component with it's new props.
This section of your code:
componentDidMount() {
if (this.props.isManager) {
this.props.dispatch(actions.fetchAllSites())
} else {
const currentUserId = this.props.user.get('id')
this.props.dispatch(actions.fetchUsersSites(currentUserId))
}
}
Should not be triggering in a component, it should be handled after executing your first request.
Have a look at this example from redux-thunk:
function makeASandwichWithSecretSauce(forPerson) {
// Invert control!
// Return a function that accepts `dispatch` so we can dispatch later.
// Thunk middleware knows how to turn thunk async actions into actions.
return function (dispatch) {
return fetchSecretSauce().then(
sauce => dispatch(makeASandwich(forPerson, sauce)),
error => dispatch(apologize('The Sandwich Shop', forPerson, error))
);
};
}
You don't necessarily have to use redux-thunk, but it will help you reason about scenarios like this and write code to match.
try this with jQuery:
$('body').load( url,[data],[callback] );
Read more at docs.jquery.com / Ajax / load
A recursive solution in python. The good thing about this code is that it exports a dictionary, with keys as strings and all possible permutations as values. All possible string lengths are included, so in effect, you are creating a superset.
If you only require the final permutations, you can delete other keys from the dictionary.
In this code, the dictionary of permutations is global.
At the base case, I store the value as both possibilities in a list. perms['ab'] = ['ab','ba']
.
For higher string lengths, the function refers to lower string lengths and incorporates the previously calculated permutations.
The function does two things:
Expensive for memory.
perms = {}
def perm(input_string):
global perms
if input_string in perms:
return perms[input_string] # This will send a list of all permutations
elif len(input_string) == 2:
perms[input_string] = [input_string, input_string[-1] + input_string [-2]]
return perms[input_string]
else:
perms[input_string] = []
for index in range(0, len(input_string)):
new_string = input_string[0:index] + input_string[index +1:]
perm(new_string)
for entries in perms[new_string]:
perms[input_string].append(input_string[index] + entries)
return perms[input_string]
There is no such tool till now to print the heap memory in the format as you requested The Only and only way to print is to write a java program with the help of Runtime Class,
public class TestMemory {
public static void main(String [] args) {
int MB = 1024*1024;
//Getting the runtime reference from system
Runtime runtime = Runtime.getRuntime();
//Print used memory
System.out.println("Used Memory:"
+ (runtime.totalMemory() - runtime.freeMemory()) / MB);
//Print free memory
System.out.println("Free Memory:"
+ runtime.freeMemory() / mb);
//Print total available memory
System.out.println("Total Memory:" + runtime.totalMemory() / MB);
//Print Maximum available memory
System.out.println("Max Memory:" + runtime.maxMemory() / MB);
}
}
reference:https://viralpatel.net/blogs/getting-jvm-heap-size-used-memory-total-memory-using-java-runtime/
I would like to add a new column, 'e', to the existing data frame and do not change anything in the data frame. (The series always got the same length as a dataframe.)
I assume that the index values in e
match those in df1
.
The easiest way to initiate a new column named e
, and assign it the values from your series e
:
df['e'] = e.values
assign (Pandas 0.16.0+)
As of Pandas 0.16.0, you can also use assign
, which assigns new columns to a DataFrame and returns a new object (a copy) with all the original columns in addition to the new ones.
df1 = df1.assign(e=e.values)
As per this example (which also includes the source code of the assign
function), you can also include more than one column:
df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
>>> df.assign(mean_a=df.a.mean(), mean_b=df.b.mean())
a b mean_a mean_b
0 1 3 1.5 3.5
1 2 4 1.5 3.5
In context with your example:
np.random.seed(0)
df1 = pd.DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])
mask = df1.applymap(lambda x: x <-0.7)
df1 = df1[-mask.any(axis=1)]
sLength = len(df1['a'])
e = pd.Series(np.random.randn(sLength))
>>> df1
a b c d
0 1.764052 0.400157 0.978738 2.240893
2 -0.103219 0.410599 0.144044 1.454274
3 0.761038 0.121675 0.443863 0.333674
7 1.532779 1.469359 0.154947 0.378163
9 1.230291 1.202380 -0.387327 -0.302303
>>> e
0 -1.048553
1 -1.420018
2 -1.706270
3 1.950775
4 -0.509652
dtype: float64
df1 = df1.assign(e=e.values)
>>> df1
a b c d e
0 1.764052 0.400157 0.978738 2.240893 -1.048553
2 -0.103219 0.410599 0.144044 1.454274 -1.420018
3 0.761038 0.121675 0.443863 0.333674 -1.706270
7 1.532779 1.469359 0.154947 0.378163 1.950775
9 1.230291 1.202380 -0.387327 -0.302303 -0.509652
The description of this new feature when it was first introduced can be found here.
Based on icecrime's answer I wrote this function
std::vector<int> intToDigits(int num_)
{
std::vector<int> ret;
string iStr = to_string(num_);
for (int i = iStr.size() - 1; i >= 0; --i)
{
int units = pow(10, i);
int digit = num_ / units % 10;
ret.push_back(digit);
}
return ret;
}
If you want to use steffens21's approach with unittest.TestLoader
, you can modify the original test loader (see unittest.py
):
import unittest
from unittest import suite
class TestLoaderWithKwargs(unittest.TestLoader):
"""A test loader which allows to parse keyword arguments to the
test case class."""
def loadTestsFromTestCase(self, testCaseClass, **kwargs):
"""Return a suite of all tests cases contained in
testCaseClass."""
if issubclass(testCaseClass, suite.TestSuite):
raise TypeError("Test cases should not be derived from "\
"TestSuite. Maybe you meant to derive from"\
" TestCase?")
testCaseNames = self.getTestCaseNames(testCaseClass)
if not testCaseNames and hasattr(testCaseClass, 'runTest'):
testCaseNames = ['runTest']
# Modification here: parse keyword arguments to testCaseClass.
test_cases = []
for test_case_name in testCaseNames:
test_cases.append(testCaseClass(test_case_name, **kwargs))
loaded_suite = self.suiteClass(test_cases)
return loaded_suite
# call your test
loader = TestLoaderWithKwargs()
suite = loader.loadTestsFromTestCase(MyTest, extraArg=extraArg)
unittest.TextTestRunner(verbosity=2).run(suite)
This is a repackaging of the accepted answer - but in a way that lets you compare them all to each other for yourself - the top 3 algorithms are compared (and comments explain why other methods are excluded) and you can run against your own setup to see how they each perform with the size of sequence that you desire.
SET NOCOUNT ON;
--
-- Set the count of numbers that you want in your sequence ...
--
DECLARE @NumberOfNumbers int = 10000000;
--
-- Some notes on choosing a useful length for your sequence ...
-- For a sequence of 100 numbers -- winner depends on preference of min/max/avg runtime ... (I prefer PhilKelley algo here - edit the algo so RowSet2 is max RowSet CTE)
-- For a sequence of 1k numbers -- winner depends on preference of min/max/avg runtime ... (Sadly PhilKelley algo is generally lowest ranked in this bucket, but could be tweaked to perform better)
-- For a sequence of 10k numbers -- a clear winner emerges for this bucket
-- For a sequence of 100k numbers -- do not test any looping methods at this size or above ...
-- the previous winner fails, a different method is need to guarantee the full sequence desired
-- For a sequence of 1MM numbers -- the statistics aren't changing much between the algorithms - choose one based on your own goals or tweaks
-- For a sequence of 10MM numbers -- only one of the methods yields the desired sequence, and the numbers are much closer than for smaller sequences
DECLARE @TestIteration int = 0;
DECLARE @MaxIterations int = 10;
DECLARE @MethodName varchar(128);
-- SQL SERVER 2017 Syntax/Support needed
DROP TABLE IF EXISTS #TimingTest
CREATE TABLE #TimingTest (MethodName varchar(128), TestIteration int, StartDate DateTime2, EndDate DateTime2, ElapsedTime decimal(38,0), ItemCount decimal(38,0), MaxNumber decimal(38,0), MinNumber decimal(38,0))
--
-- Conduct the test ...
--
WHILE @TestIteration < @MaxIterations
BEGIN
-- Be sure that the test moves forward
SET @TestIteration += 1;
/* -- This method has been removed, as it is BY FAR, the slowest method
-- This test shows that, looping should be avoided, likely at all costs, if one places a value / premium on speed of execution ...
--
-- METHOD - Fast looping
--
-- Prep for the test
DROP TABLE IF EXISTS [Numbers].[Test];
CREATE TABLE [Numbers].[Test] (Number INT NOT NULL);
-- Method information
SET @MethodName = 'FastLoop';
-- Record the start of the test
INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
SELECT @MethodName, @TestIteration, GETDATE()
-- Run the algorithm
DECLARE @i INT = 1;
WHILE @i <= @NumberOfNumbers
BEGIN
INSERT INTO [Numbers].[Test](Number) VALUES (@i);
SELECT @i = @i + 1;
END;
ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)
-- Record the end of the test
UPDATE tt
SET
EndDate = GETDATE()
FROM #TimingTest tt
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
-- And the stats about the numbers in the sequence
UPDATE tt
SET
ItemCount = results.ItemCount,
MaxNumber = results.MaxNumber,
MinNumber = results.MinNumber
FROM #TimingTest tt
CROSS JOIN (
SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
) results
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
*/
/* -- This method requires GO statements, which would break the script, also - this answer does not appear to be the fastest *AND* seems to perform "magic"
--
-- METHOD - "Semi-Looping"
--
-- Prep for the test
DROP TABLE IF EXISTS [Numbers].[Test];
CREATE TABLE [Numbers].[Test] (Number INT NOT NULL);
-- Method information
SET @MethodName = 'SemiLoop';
-- Record the start of the test
INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
SELECT @MethodName, @TestIteration, GETDATE()
-- Run the algorithm
INSERT [Numbers].[Test] values (1);
-- GO --required
INSERT [Numbers].[Test] SELECT Number + (SELECT COUNT(*) FROM [Numbers].[Test]) FROM [Numbers].[Test]
-- GO 14 --will create 16384 total rows
ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)
-- Record the end of the test
UPDATE tt
SET
EndDate = GETDATE()
FROM #TimingTest tt
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
-- And the stats about the numbers in the sequence
UPDATE tt
SET
ItemCount = results.ItemCount,
MaxNumber = results.MaxNumber,
MinNumber = results.MinNumber
FROM #TimingTest tt
CROSS JOIN (
SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
) results
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
*/
--
-- METHOD - Philip Kelley's algo
-- (needs tweaking to match the desired length of sequence in order to optimize its performance, relies more on the coder to properly tweak the algorithm)
--
-- Prep for the test
DROP TABLE IF EXISTS [Numbers].[Test];
CREATE TABLE [Numbers].[Test] (Number INT NOT NULL);
-- Method information
SET @MethodName = 'PhilKelley';
-- Record the start of the test
INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
SELECT @MethodName, @TestIteration, GETDATE()
-- Run the algorithm
; WITH
RowSet0 as (select 1 as Item union all select 1), -- 2 rows -- We only have to name the column in the first select, the second/union select inherits the column name
RowSet1 as (select 1 as Item from RowSet0 as A, RowSet0 as B), -- 4 rows
RowSet2 as (select 1 as Item from RowSet1 as A, RowSet1 as B), -- 16 rows
RowSet3 as (select 1 as Item from RowSet2 as A, RowSet2 as B), -- 256 rows
RowSet4 as (select 1 as Item from RowSet3 as A, RowSet3 as B), -- 65536 rows (65k)
RowSet5 as (select 1 as Item from RowSet4 as A, RowSet4 as B), -- 4294967296 rows (4BB)
-- Add more RowSetX to get higher and higher numbers of rows
-- Each successive RowSetX results in squaring the previously available number of rows
Tally as (select row_number() over (order by Item) as Number from RowSet5) -- This is what gives us the sequence of integers, always select from the terminal CTE expression
-- Note: testing of this specific use case has shown that making Tally as a sub-query instead of a terminal CTE expression is slower (always) - be sure to follow this pattern closely for max performance
INSERT INTO [Numbers].[Test] (Number)
SELECT o.Number
FROM Tally o
WHERE o.Number <= @NumberOfNumbers
ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)
-- Record the end of the test
UPDATE tt
SET
EndDate = GETDATE()
FROM #TimingTest tt
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
-- And the stats about the numbers in the sequence
UPDATE tt
SET
ItemCount = results.ItemCount,
MaxNumber = results.MaxNumber,
MinNumber = results.MinNumber
FROM #TimingTest tt
CROSS JOIN (
SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
) results
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
--
-- METHOD - Mladen Prajdic answer
--
-- Prep for the test
DROP TABLE IF EXISTS [Numbers].[Test];
CREATE TABLE [Numbers].[Test] (Number INT NOT NULL);
-- Method information
SET @MethodName = 'MladenPrajdic';
-- Record the start of the test
INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
SELECT @MethodName, @TestIteration, GETDATE()
-- Run the algorithm
INSERT INTO [Numbers].[Test](Number)
SELECT TOP (@NumberOfNumbers) row_number() over(order by t1.number) as N
FROM master..spt_values t1
CROSS JOIN master..spt_values t2
ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)
-- Record the end of the test
UPDATE tt
SET
EndDate = GETDATE()
FROM #TimingTest tt
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
-- And the stats about the numbers in the sequence
UPDATE tt
SET
ItemCount = results.ItemCount,
MaxNumber = results.MaxNumber,
MinNumber = results.MinNumber
FROM #TimingTest tt
CROSS JOIN (
SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
) results
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
--
-- METHOD - Single INSERT
--
-- Prep for the test
DROP TABLE IF EXISTS [Numbers].[Test];
-- The Table creation is part of this algorithm ...
-- Method information
SET @MethodName = 'SingleInsert';
-- Record the start of the test
INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
SELECT @MethodName, @TestIteration, GETDATE()
-- Run the algorithm
SELECT TOP (@NumberOfNumbers) IDENTITY(int,1,1) AS Number
INTO [Numbers].[Test]
FROM sys.objects s1 -- use sys.columns if you don't get enough rows returned to generate all the numbers you need
CROSS JOIN sys.objects s2 -- use sys.columns if you don't get enough rows returned to generate all the numbers you need
ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)
-- Record the end of the test
UPDATE tt
SET
EndDate = GETDATE()
FROM #TimingTest tt
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
-- And the stats about the numbers in the sequence
UPDATE tt
SET
ItemCount = results.ItemCount,
MaxNumber = results.MaxNumber,
MinNumber = results.MinNumber
FROM #TimingTest tt
CROSS JOIN (
SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
) results
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
END
-- Calculate the timespan for each of the runs
UPDATE tt
SET
ElapsedTime = DATEDIFF(MICROSECOND, StartDate, EndDate)
FROM #TimingTest tt
--
-- Report the results ...
--
SELECT
MethodName, AVG(ElapsedTime) / AVG(ItemCount) as TimePerRecord, CAST(AVG(ItemCount) as bigint) as SequenceLength,
MAX(ElapsedTime) as MaxTime, MIN(ElapsedTime) as MinTime,
MAX(MaxNumber) as MaxNumber, MIN(MinNumber) as MinNumber
FROM #TimingTest tt
GROUP by tt.MethodName
ORDER BY TimePerRecord ASC, MaxTime ASC, MinTime ASC
I had the same question as the original poster, did this as a solution. Not sure how efficient this is ....
interval = 5000; // initial condition
var run = setInterval(request , interval); // start setInterval as "run"
function request() {
console.log(interval); // firebug or chrome log
clearInterval(run); // stop the setInterval()
// dynamically change the run interval
if(interval>200 ){
interval = interval*.8;
}else{
interval = interval*1.2;
}
run = setInterval(request, interval); // start the setInterval()
}
In my case, the warning occurred because of just the regular type of boolean indexing -- because the series had only np.nan. Demonstration (pandas 1.0.3):
>>> import pandas as pd
>>> import numpy as np
>>> pd.Series([np.nan, 'Hi']) == 'Hi'
0 False
1 True
>>> pd.Series([np.nan, np.nan]) == 'Hi'
~/anaconda3/envs/ms3/lib/python3.7/site-packages/pandas/core/ops/array_ops.py:255: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
res_values = method(rvalues)
0 False
1 False
I think with pandas 1.0 they really want you to use the new 'string'
datatype which allows for pd.NA
values:
>>> pd.Series([pd.NA, pd.NA]) == 'Hi'
0 False
1 False
>>> pd.Series([np.nan, np.nan], dtype='string') == 'Hi'
0 <NA>
1 <NA>
>>> (pd.Series([np.nan, np.nan], dtype='string') == 'Hi').fillna(False)
0 False
1 False
Don't love at which point they tinkered with every-day functionality such as boolean indexing.
Maybe you are looking for jar
command to get the list of classes in terminal,
$ jar tf ~/.m2/repository/org/apache/spark/spark-assembly/1.2.0-SNAPSHOT/spark-assembly-1.2.0-SNAPSHOT-hadoop1.0.4.jar
META-INF/
META-INF/MANIFEST.MF
org/
org/apache/
org/apache/spark/
org/apache/spark/unused/
org/apache/spark/unused/UnusedStubClass.class
META-INF/maven/
META-INF/maven/org.spark-project.spark/
META-INF/maven/org.spark-project.spark/unused/
META-INF/maven/org.spark-project.spark/unused/pom.xml
META-INF/maven/org.spark-project.spark/unused/pom.properties
META-INF/NOTICE
where,
-t list table of contents for archive
-f specify archive file name
Or, just grep above result to see .class
es only
$ jar tf ~/.m2/repository/org/apache/spark/spark-assembly/1.2.0-SNAPSHOT/spark-assembly-1.2.0-SNAPSHOT-hadoop1.0.4.jar | grep .class
org/apache/spark/unused/UnusedStubClass.class
To see number of class
es,
jar tvf launcher/target/usergrid-launcher-1.0-SNAPSHOT.jar | grep .class | wc -l
61079
Although in your case, just plain initialization will do, there's a trick to wrap the array into a struct (which can be initialized after declaration).
For example:
struct foo {
GLfloat arr[10];
};
...
struct foo foo;
foo = (struct foo) { .arr = {1.0, ... } };
Digest Authentication communicates credentials in an encrypted form by applying a hash function to: the username, the password, a server supplied nonce value, the HTTP method and the requested URI.
Whereas Basic Authentication uses non-encrypted base64 encoding.
Therefore, Basic Authentication should generally only be used where transport layer security is provided such as https.
See RFC-2617 for all the gory details.
select cast (height as decimal)/10 as HeightDecimal
Try this:
String[] columnDetail = column.split("\t", -1);
Read the Javadoc on String.split(java.lang.String, int) for an explanation about the limit parameter of split function:
split
public String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
The string "boo:and:foo", for example, yields the following results with these parameters:
Regex Limit Result
: 2 { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }
When the last few fields (I guest that's your situation) are missing, you will get the column like this:
field1\tfield2\tfield3\t\t
If no limit is set to split(), the limit is 0, which will lead to that "trailing empty strings will be discarded". So you can just get just 3 fields, {"field1", "field2", "field3"}.
When limit is set to -1, a non-positive value, trailing empty strings will not be discarded. So you can get 5 fields with the last two being empty string, {"field1", "field2", "field3", "", ""}.
The guidelines we use, which seem to be fairly widely used and are backed up by the figures that we get from Google Analytics, are to design the site so that it will work on a screen that is 1024 pixels wide and 768 pixels high (1024x768 and 1280x800 are the most common resolutions we see, accounting for at least 70% of all traffic).
This is why you see many sites (this one included) which use a central column approx 1000 pixels wide and with the most important content in the top 500-600 pixels so it's above the fold when being viewed in screens this size.
Using a 1000 pixel wide layout works fairly well on screen sizes of up to about 1680 pixels in width (typically as high as you'll see on laptops, except the large 17" ones) but do start to look a bit silly on 1920 pixel wide ones (high end computers, typically workstations), however these very high resolutions don't account for a large percentage of traffic on the general internet - 2% or less (on the other hand, if you have a specialist audience like this site, the figure with high resolutions may be somewhat higher).
Very interesting question. I think it's mainly a semantic meaning, and may also be due to historical reasons.
Although in current Android Activity and Service implementations, getApplication()
and getApplicationContext()
return the same object, there is no guarantee that this will always be the case (for example, in a specific vendor implementation).
So if you want the Application class you registered in the Manifest, you should never call getApplicationContext()
and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework).
Why does getApplicationContext()
exist in the first place ?
getApplication()
is only available in the Activity class and the Service class, whereas getApplicationContext()
is declared in the Context class.
That actually means one thing : when writing code in a broadcast receiver, which is not a context but is given a context in its onReceive method, you can only call getApplicationContext()
. Which also means that you are not guaranteed to have access to your application in a BroadcastReceiver.
When looking at the Android code, you see that when attached, an activity receives a base context and an application, and those are different parameters. getApplicationContext()
delegates it's call to baseContext.getApplicationContext()
.
One more thing : the documentation says that it most cases, you shouldn't need to subclass Application:
There is normally no need to subclass
Application
. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given aContext
which internally usesContext.getApplicationContext()
when first constructing the singleton.
I know this is not an exact and precise answer, but still, does that answer your question?
explode
is an alternative. However, if you meant to split through a regular expression, the alternative is preg_split
instead.
I'm not sure about changing the tint vs the background color but this is how you change the tint color of the Navigation Bar:
Try this code..
[navigationController.navigationBar setTintColor:[UIColor redColor];
//Red as an example.
You should stop the submit procedure by returning false on the onsubmit callback.
<script>
function checkRegistration(){
if(!form_valid){
alert('Given data is not correct');
return false;
}
return true;
}
</script>
<form onsubmit="return checkRegistration()"...
Here you have a fully working example. The form will submit only when you write google into input, otherwise it will return an error:
<script>
function checkRegistration(){
var form_valid = (document.getElementById('some_input').value == 'google');
if(!form_valid){
alert('Given data is incorrect');
return false;
}
return true;
}
</script>
<form onsubmit="return checkRegistration()" method="get" action="http://google.com">
Write google to go to google...<br/>
<input type="text" id="some_input" value=""/>
<input type="submit" value="google it"/>
</form>
The prompt:
Password for 'https://[email protected]':
suggests, that you are using https not ssh. SSH urls start with git@, for example:
[email protected]:beginninggit/alias.git
Even if you work alone, with a single repo that you own, the operation:
git push
will cause:
Password for 'https://[email protected]':
if the remote origin starts with https
.
Check your remote with:
git remote -v
The remote depends on git clone
. If you want to use ssh clone the repo using its ssh url, for example:
git clone [email protected]:user/repo.git
I suggest you to start with git push
and git pull
for your private repo.
If that works, you have two joices suggested by Lazy Badger:
use Date.prototype.toLocaleTimeString()
as documented here
please note the locale example en-US in the url.
int(limit)
returns the value converted into an integer, and doesn't change it in place as you call the function (which is what you are expecting it to).
Do this instead:
limit = int(limit)
Or when definiting limit
:
if 'limit' in user_data :
limit = int(user_data['limit'])
The solution I have applied to this situation is to simply place an absolute loading image in the DOM, which will be covered by the iframe layer after the iframe is loaded.
The z-index of the iframe should be (loading's z-index + 1), or just higher.
For example:
.loading-image { position: absolute; z-index: 0; }
.iframe-element { position: relative; z-index: 1; }
Hope this helps if no javaScript solution did. I do think that CSS is best practice for these situations.
Best regards.
If you only want to read the first 999,999 (non-header) rows:
read_csv(..., nrows=999999)
If you only want to read rows 1,000,000 ... 1,999,999
read_csv(..., skiprows=1000000, nrows=999999)
nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*
skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file
and for large files, you'll probably also want to use chunksize:
chunksize : int, default None Return TextFileReader object for iteration
you would have to copy the current data to the new directory and to change your my.cnf
your MySQL.
[mysqld]
datadir=/your/new/dir/
tmpdir=/your/new/temp/
You have to copy the database when the server is not running.
As others have said,
new String[0]
will indeed create an empty array. However, there's one nice thing about arrays - their size can't change, so you can always use the same empty array reference. So in your code, you can use:
private static final String[] EMPTY_ARRAY = new String[0];
and then just return EMPTY_ARRAY
each time you need it - there's no need to create a new object each time.
I think you just need to create your volume outside docker first with a docker create -v /location --name
and then reuse it.
And by the time I used to use docker a lot, it wasn't possible to use a static docker volume with dockerfile definition so my suggestion is to try the command line (eventually with a script ) .
Object class is the base class for all the classes in java, if you are missing this it means you don't have the jdk libs in your buildpath. I don't know much about Kepler but you need to make sure it points to a correct jdk for compilation and a correct jre for running your java apps.
However I have set the path as C:\Program Files\Java\jdk1.6.0_41 from eclipse Kepler toolbar->windows->preferences->java->installed jre
You are trying to point jdk instead of jre in your preferences. toolbar->windows->preferences->java->installed jre should point to a jre and not jdk.
There is a very simple way in which you can do this. It involves injecting a javascript code to a label control from code behind. here is sample code:
<head runat="server">
<title>Calling javascript function from code behind example</title>
<script type="text/javascript">
function showDialogue() {
alert("this dialogue has been invoked through codebehind.");
}
</script>
</head>
..........
lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";
Check out the full code here: http://softmate-technologies.com/javascript-from-CodeBehind.htm (dead)
Link from Internet Archive: https://web.archive.org/web/20120608053720/http://softmate-technologies.com/javascript-from-CodeBehind.htm
Visual Studio 2013 has a pretty cool visualizer built in.
File -> Open -> File pick your .xsd and then drag elements from XML Schema Explorer onto the designer surface.
you can also use this :
import requests
from bs4 import BeautifulSoup
import csv
url = "http://58.68.130.147/"
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data, "html.parser")
get_details = soup.find_all("input", attrs={"name":"stainfo"})
for val in get_details:
get_val = val["value"]
print(get_val)
Short for Dimension. It's a type of variable. You declare (or "tell" Visual Basic) that you are setting up a variable with this word.
str_replace will do the trick thusly
$new_str = str_replace(' ', '', $old_str);
Galen Gidman has posted a really good solution to the problem of a responsive sticky footer that does not have a fixed height. You can find his full solution on his blog: http://galengidman.com/2014/03/25/responsive-flexible-height-sticky-footers-in-css/
HTML
<header class="page-row">
<h1>Site Title</h1>
</header>
<main class="page-row page-row-expanded">
<p>Page content goes here.</p>
</main>
<footer class="page-row">
<p>Copyright, blah blah blah.</p>
</footer>
CSS
html,
body { height: 100%; }
body {
display: table;
width: 100%;
}
.page-row {
display: table-row;
height: 1px;
}
.page-row-expanded { height: 100%; }
Replace the below line code:
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener{
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
button.setOnClickListener(this);
}
public void onClick(View v) {
if(v.getId==R.id.button1){
Intent i = new Intent(FromActivity.this, ToActivity.class);
startActivity(i);
}
}
}
Add the below lines in your manifest file:
<activity android:name="com.packagename.FromActivity"></activity>
<activity android:name="com.packagename.ToActivity"></activity>
I disagree on the comment posted by Hogan. Those instructions will work for IBM DB2 Mini, but it's not the case of DB2 Z/OS.
Here is an example:
Exception data: org.apache.ibatis.exceptions.PersistenceException:
The error occurred while setting parameters
SQL: INSERT INTO TABLENAME(ID_, F1_, F2_, F3_, F4_, F5_) VALUES
(?, 1, ?, ?, ?, ?),
(?, 1, ?, ?, ?, ?)
Cause: com.ibm.db2.jcc.am.SqlSyntaxErrorException:
ILLEGAL SYMBOL ",". SOME SYMBOLS THAT MIGHT BE LEGAL ARE: FOR <END-OF-STATEMENT> NOT ATOMIC. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.25.17
So I can confirm that inline comma separated bulk inserts are not working on DB2 Z/OS (maybe you could feed it some props to get it working...)
Yes, it works when with the command npm install --no-optional
Using environment:
All the answers here have good working explanation of hashable objects in python, but I believe one needs to understand the term Hashing first.
Hashing is a concept in computer science which is used to create high performance, pseudo random access data structures where large amount of data is to be stored and accessed quickly.
For example, if you have 10,000 phone numbers, and you want to store them in an array (which is a sequential data structure that stores data in contiguous memory locations, and provides random access), but you might not have the required amount of contiguous memory locations.
So, you can instead use an array of size 100, and use a hash function to map a set of values to same indices, and these values can be stored in a linked list. This provides a performance similar to an array.
Now, a hash function can be as simple as dividing the number with the size of the array and taking the remainder as the index.
For more detail refer to https://en.wikipedia.org/wiki/Hash_function
Here is another good reference: http://interactivepython.org/runestone/static/pythonds/SortSearch/Hashing.html
Or you can just use this method in case you don't have StringUtils on hand:
public static String abbreviateString(String input, int maxLength) {
if (input.length() <= maxLength)
return input;
else
return input.substring(0, maxLength-2) + "..";
}
Use the Refresh method:
context.Refresh(RefreshMode.StoreWins, yourEntity);
or in alternative dispose your current context and create a new one.
An other solution rm(list=ls(pattern="temp"))
, remove all objects matching the pattern.
CONTAINS
is for a Full Text Indexed field - if not, then use LIKE
Think this is, what you are searching for: Allow access to specific projects for Users
Short description without screenshots:
Use Jenkins "Project-based Matrix Authorization Strategy" under "Manage Jenkins" => "Configure System". On the configuration page of each project, you now have "Enable project-based security". Now add each user you want to authorize.
$(function () {
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
showButtonPanel: true,
changeMonth: true,
changeYear: true,
yearRange: '1999:2012',
showOn: "button",
buttonImage: "images/calendar.gif",
buttonImageOnly: true,
minDate: new Date(1999, 10 - 1, 25),
maxDate: '+30Y',
inline: true
});
});
Just added year range option. It should solve the problem
I personally prefer using scrapy and selenium and dockerizing both in separate containers. This way you can install both with minimal hassle and crawl modern websites that almost all contain javascript in one form or another. Here's an example:
Use the scrapy startproject
to create your scraper and write your spider, the skeleton can be as simple as this:
import scrapy
class MySpider(scrapy.Spider):
name = 'my_spider'
start_urls = ['https://somewhere.com']
def start_requests(self):
yield scrapy.Request(url=self.start_urls[0])
def parse(self, response):
# do stuff with results, scrape items etc.
# now were just checking everything worked
print(response.body)
The real magic happens in the middlewares.py. Overwrite two methods in the downloader middleware, __init__
and process_request
, in the following way:
# import some additional modules that we need
import os
from copy import deepcopy
from time import sleep
from scrapy import signals
from scrapy.http import HtmlResponse
from selenium import webdriver
class SampleProjectDownloaderMiddleware(object):
def __init__(self):
SELENIUM_LOCATION = os.environ.get('SELENIUM_LOCATION', 'NOT_HERE')
SELENIUM_URL = f'http://{SELENIUM_LOCATION}:4444/wd/hub'
chrome_options = webdriver.ChromeOptions()
# chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
self.driver = webdriver.Remote(command_executor=SELENIUM_URL,
desired_capabilities=chrome_options.to_capabilities())
def process_request(self, request, spider):
self.driver.get(request.url)
# sleep a bit so the page has time to load
# or monitor items on page to continue as soon as page ready
sleep(4)
# if you need to manipulate the page content like clicking and scrolling, you do it here
# self.driver.find_element_by_css_selector('.my-class').click()
# you only need the now properly and completely rendered html from your page to get results
body = deepcopy(self.driver.page_source)
# copy the current url in case of redirects
url = deepcopy(self.driver.current_url)
return HtmlResponse(url, body=body, encoding='utf-8', request=request)
Dont forget to enable this middlware by uncommenting the next lines in the settings.py file:
DOWNLOADER_MIDDLEWARES = {
'sample_project.middlewares.SampleProjectDownloaderMiddleware': 543,}
Next for dockerization. Create your Dockerfile
from a lightweight image (I'm using python Alpine here), copy your project directory to it, install requirements:
# Use an official Python runtime as a parent image
FROM python:3.6-alpine
# install some packages necessary to scrapy and then curl because it's handy for debugging
RUN apk --update add linux-headers libffi-dev openssl-dev build-base libxslt-dev libxml2-dev curl python-dev
WORKDIR /my_scraper
ADD requirements.txt /my_scraper/
RUN pip install -r requirements.txt
ADD . /scrapers
And finally bring it all together in docker-compose.yaml
:
version: '2'
services:
selenium:
image: selenium/standalone-chrome
ports:
- "4444:4444"
shm_size: 1G
my_scraper:
build: .
depends_on:
- "selenium"
environment:
- SELENIUM_LOCATION=samplecrawler_selenium_1
volumes:
- .:/my_scraper
# use this command to keep the container running
command: tail -f /dev/null
Run docker-compose up -d
. If you're doing this the first time it will take a while for it to fetch the latest selenium/standalone-chrome and the build your scraper image as well.
Once it's done, you can check that your containers are running with docker ps
and also check that the name of the selenium container matches that of the environment variable that we passed to our scraper container (here, it was SELENIUM_LOCATION=samplecrawler_selenium_1
).
Enter your scraper container with docker exec -ti YOUR_CONTAINER_NAME sh
, the command for me was docker exec -ti samplecrawler_my_scraper_1 sh
, cd into the right directory and run your scraper with scrapy crawl my_spider
.
The entire thing is on my github page and you can get it from here
Don't use: import UserController from "api/xxxx" Should be: import UserController from "./api/xxxx"
I don't know if I understand your question, but maybe:
foreach ($_POST as $id=>$value)
if (strncmp($id,'id[',3) $info[rtrim(ltrim($id,'id['),']')]=$_POST[$id];
would help
That is if you really want to have a different name (id[key]) on each checkbox of the html form (not very efficient). If not you can just name them all the same, i.e. 'id' and iterate on the (selected) values of the array, like: foreach ($_POST['id'] as $key=>$value)...
I hope that I am understing your question correctly, but you can do this very quickly with Linq. I'm assuming that universally you will always have an Id property. Just create an interface to ensure this.
If how you identify an object to be the same changes from class to class, I would recommend passing in a delegate that returns true if the two objects have the same persistent id.
Here is how to do it in Linq:
List<Employee> listA = new List<Employee>();
List<Employee> listB = new List<Employee>();
listA.Add(new Employee() { Id = 1, Name = "Bill" });
listA.Add(new Employee() { Id = 2, Name = "Ted" });
listB.Add(new Employee() { Id = 1, Name = "Bill Sr." });
listB.Add(new Employee() { Id = 3, Name = "Jim" });
var identicalQuery = from employeeA in listA
join employeeB in listB on employeeA.Id equals employeeB.Id
select new { EmployeeA = employeeA, EmployeeB = employeeB };
foreach (var queryResult in identicalQuery)
{
Console.WriteLine(queryResult.EmployeeA.Name);
Console.WriteLine(queryResult.EmployeeB.Name);
}
As stated,
innodb_buffer_pool_size=50M
Following the convention on the other predefined variables, make sure there is no space either side of the equals sign.
Then run
sudo service mysqld stop
sudo service mysqld start
Note
Sometimes, e.g. on Ubuntu, the MySQL daemon is named mysql
as opposed to mysqld
I find that running /etc/init.d/mysqld restart
doesn't always work and you may get an error like
Stopping mysqld: [FAILED]
Starting mysqld: [ OK ]
To see if the variable has been set, run show variables
and see if the value has been updated.
Using table
:
library(magrittr)
myvec %>% unique %>% '['(1) %>% table %>% as.data.frame %>%
setNames(c("name","number_of_distinct_orders"))
# name number_of_distinct_orders
# 1 Amy 2
# 2 Dave 1
# 3 Jack 3
# 4 Larry 1
# 5 Tom 2
try this script:
with open("data.json") as f:
data = json.load(f)
data["id"] = 134
json.dump(data, open("data.json", "w"), indent = 4)
the result is:
{
"name":"mynamme",
"id":134
}
Just the arrangement is different, You can solve the problem by converting the "data" type to a list, then arranging it as you wish, then returning it and saving the file, like that:
index_add = 0
with open("data.json") as f:
data = json.load(f)
data_li = [[k, v] for k, v in data.items()]
data_li.insert(index_add, ["id", 134])
data = {data_li[i][0]:data_li[i][1] for i in range(0, len(data_li))}
json.dump(data, open("data.json", "w"), indent = 4)
the result is:
{
"id":134,
"name":"myname"
}
you can add if condition in order not to repeat the key, just change it, like that:
index_add = 0
n_k = "id"
n_v = 134
with open("data.json") as f:
data = json.load(f)
if n_k in data:
data[n_k] = n_v
else:
data_li = [[k, v] for k, v in data.items()]
data_li.insert(index_add, [n_k, n_v])
data = {data_li[i][0]:data_li[i][1] for i in range(0, len(data_li))}
json.dump(data, open("data.json", "w"), indent = 4)
This answer assumes that you have python3.6
installed. For python3.7
, replace 3.6
with 3.7
. For python3.8
, replace 3.6
with 3.8
, but it may also first require the python3.8-distutils
package.
With regard to installing pip
, using curl
(instead of wget
) avoids writing the file to disk.
curl https://bootstrap.pypa.io/get-pip.py | sudo -H python3.6
The -H
flag is evidently necessary with sudo
in order to prevent errors such as the following when installing pip for an updated python interpreter:
The directory '/home/someuser/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/someuser/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
curl https://bootstrap.pypa.io/get-pip.py | python3.6 - --user
This may sometimes give a warning such as:
WARNING: The script wheel is installed in '/home/ubuntu/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
After this, pip
, pip3
, and pip3.6
can all be expected to point to the same target:
$ (pip -V && pip3 -V && pip3.6 -V) | uniq
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)
Of course you can alternatively use python3.6 -m pip
as well.
$ python3.6 -m pip -V
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)
You can quote the entire path as in windows or you can escape the spaces like in:
/foo\ folder\ with\ space/foo.sh -help
Both ways will work!
Changing the Process Model Identity to LocalSystem fixed this issue for me. You can find this setting if you right click on the application pool and chose "Advanced Settings". I'm running IIS 7.5.
In case you need to use it with Javascript
We can use arguments[0].click() to simulate click operation.
var element = element(by.linkText('webdriverjs'));
browser.executeScript("arguments[0].click()",element);
The pipe character |
has a special meaning in regular expressions. a|b
means "match either a
or b
". If you want to match a literal |
character, you need to escape it:
... | Select-String -Pattern 'H\|159' -NotMatch | ...
If this example can help, adds a "custom confirm popin" on some links (I keep the code of "$.ui.Modal.confirm", it's just an exemple for the callback that executes the original action) :
//Register "custom confirm popin" on click on specific links
$(document).on(
"click",
"A.confirm",
function(event){
//prevent default click action
event.preventDefault();
//show "custom confirm popin"
$.ui.Modal.confirm(
//popin text
"Do you confirm ?",
//action on click 'ok'
function() {
//Unregister handler (prevent loop)
$(document).off("click", "A.confirm");
//Do default click action
$(event.target)[0].click();
}
);
}
);
a rapid response not tested on several brosers, works on gg chrome / win
-> On focus event -> show/hide password
<input type="password" name="password">
script jQuery
// show on focus
$('input[type="password"]').on('focusin', function(){
$(this).attr('type', 'text');
});
// hide on focus Out
$('input[type="password"]').on('focusout', function(){
$(this).attr('type', 'password');
});
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model {
use SoftDeletes;
protected $table = 'posts';
// ...
}
When soft deleting a model, it is not actually removed from your database. Instead, a
deleted_at
timestamp is set on the record. To enable soft deletes for a model, specify thesoftDelete
property on the model (Documentation).
use Illuminate\Database\Eloquent\SoftDeletingTrait; // <-- This is required
class Post extends Eloquent {
use SoftDeletingTrait;
protected $table = 'posts';
// ...
}
For example (Using a posts
table and Post
model):
class Post extends Eloquent {
protected $table = 'posts';
protected $softDelete = true;
// ...
}
To add a deleted_at column to your table, you may use the
softDeletes
method from a migration:
For example (Migration class' up
method for posts
table) :
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function(Blueprint $table)
{
$table->increments('id');
// more fields
$table->softDeletes(); // <-- This will add a deleted_at field
$table->timeStamps();
});
}
Now, when you call the delete
method on the model, the deleted_at
column will be set to the current timestamp
. When querying a model that uses soft deletes, the "deleted" models will not be included in query results. To soft delete
a model you may use:
$model = Contents::find( $id );
$model->delete();
Deleted (soft) models are identified by the timestamp
and if deleted_at
field is NULL
then it's not deleted and using the restore
method actually makes the deleted_at
field NULL
. To permanently delete a model you may use forceDelete
method.
lst = [('candy','30','100'), ('apple','10','200'), ('baby','20','300')]
lst.sort(key=lambda x:x[1])
print(lst)
It will print as following:
[('apple', '10', '200'), ('baby', '20', '300'), ('candy', '30', '100')]
I use a method that first filters the fields and then combines them.
reference Exclude property from type
interface A {
x: string
}
export type B = Omit<A, 'x'> & { x: number };
for interface:
interface A {
x: string
}
interface B extends Omit<A, 'x'> {
x: number
}
I'd love to know if this is an insecure/bad idea, but after thinking about it a bit I don't see an issue here:
Modifying Linus's insecure solution to add it to the end, using npm bin
to find the directory, and making the script only call npm bin
when a package.json
is present in a parent (for speed), this is what I came up with for zsh
:
find-up () {
path=$(pwd)
while [[ "$path" != "" && ! -e "$path/$1" ]]; do
path=${path%/*}
done
echo "$path"
}
precmd() {
if [ "$(find-up package.json)" != "" ]; then
new_bin=$(npm bin)
if [ "$NODE_MODULES_PATH" != "$new_bin" ]; then
export PATH=${PATH%:$NODE_MODULES_PATH}:$new_bin
export NODE_MODULES_PATH=$new_bin
fi
else
if [ "$NODE_MODULES_PATH" != "" ]; then
export PATH=${PATH%:$NODE_MODULES_PATH}
export NODE_MODULES_PATH=""
fi
fi
}
For bash
, instead of using the precmd
hook, you can use the $PROMPT_COMMAND
variable (I haven't tested this but you get the idea):
__add-node-to-path() {
if [ "$(find-up package.json)" != "" ]; then
new_bin=$(npm bin)
if [ "$NODE_MODULES_PATH" != "$new_bin" ]; then
export PATH=${PATH%:$NODE_MODULES_PATH}:$new_bin
export NODE_MODULES_PATH=$new_bin
fi
else
if [ "$NODE_MODULES_PATH" != "" ]; then
export PATH=${PATH%:$NODE_MODULES_PATH}
export NODE_MODULES_PATH=""
fi
fi
}
export PROMPT_COMMAND="__add-node-to-path"
Find out the format of the floating point numbers used on the CPU that directly supports floating point and break it down into those parts. The most common format is IEEE-754.
Alternatively, you could obtain those parts using a few special functions (double frexp(double value, int *exp);
and double ldexp(double x, int exp);
) as shown in this answer.
Another option is to use %a
with printf()
.
Put this in C2 and copy down
=IF(ISNA(VLOOKUP(A2,$B$2:$B$65535,1,FALSE)),"not in B","")
Then if the value in A isn't in B the cell in column C will say "not in B".
Right click on your website go to property pages and check both the check-boxes under Accessibility validation click on ok. run the website.
I found the above answer giving an error with Oracle SQL, you also must use square brackets, below;
SQL> SELECT Q'[Paddy O'Reilly]' FROM DUAL;
Result: Paddy O'Reilly
I had a similar problem recently, and here's what I did:
SELECT
columnname as 'Original_Value',
LEN(LTRIM(columnname)) as 'Orig_Val_Char_Count',
N'['+columnname+']' as 'UnicodeStr_Value',
LEN(N'['+columnname+']')-2 as 'True_Char_Count'
FROM mytable
The first two columns look at the original value and count the characters (minus leading/trailing spaces).
I needed to compare that with the true count of characters, which is why I used the second LEN function. It sets the column value to a string, forces that string to Unicode, and then counts the characters.
By using the brackets, you ensure that any leading or trailing spaces are also counted as characters; of course, you don't want to count the brackets themselves, so you subtract 2 at the end.
I have the home directory in a non-standard location and in sshd
logs I have the following line, even if all permissions were just fine (see the other answers):
Could not open authorized keys '/data/home/user1/.ssh/authorized_keys': Permission denied
I have found a solution here: Trouble with ssh public key authentication to RHEL 6.5
In my particular case:
Added a new line in /etc/selinux/targeted/contexts/files/file_contexts.homedirs
:
This is the original line for regular home directories:
/home/[^/]*/\.ssh(/.*)? unconfined_u:object_r:ssh_home_t:s0
This is my new line:
/data/home/[^/]*/\.ssh(/.*)? unconfined_u:object_r:ssh_home_t:s0
Followed by a restorecon -r /data/
and a sshd
restart.
npm
for managing client-side libraries is a good choice (as opposed to Bower or NuGet), you're thinking in the right direction :)FileServer
, having StaticFiles
should suffice for serving static files (.js, images, etc.)wwwroot
to public
, otherwise the folder structure in Azure Web Apps will be confusing (D:\Home\site\wwwroot\wwwroot
vs D:\Home\site\wwwroot\public
)node_modules
to a web hosting server). See tools/deploy.js
as an example.Visit ASP.NET Core Starter Kit on GitHub (disclaimer: I'm the author)
If you're using MySQL and want the database itself to perform the conversion, use this:
If you prefer to format using Java, use this:
SimpleDateFormat dateFormat = new SimpleDateFormat("M/dd/yyyy");
dateFormat.format( new Date() );
#import "YourViewController.h"
To push a view including the navigation bar and/or tab bar:
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"YourStoryboard" bundle:nil];
YourViewController *viewController = (YourViewcontroller *)[storyboard instantiateViewControllerWithIdentifier:@"YourViewControllerIdentifier"];
[self.navigationController pushViewController:viewController animated:YES];
To set identifier to a view controller, Open YourStoryboard.storyboard. Select YourViewController View-> Utilities -> ShowIdentityInspector. There you can specify the identifier.
This function generates random string consisting of upper,lowercase letters, digits, pass the length seperator, no_of_blocks to specify your string format
eg: len_sep = 4, no_of_blocks = 4 will generate the following pattern,
F4nQ-Vh5z-JKEC-WhuS
Where, length seperator will add "-" after 4 characters
XXXX-
no of blocks will generate the following patten of characters as string
XXXX - XXXX - XXXX - XXXX
if a single random string is needed, just keep the no_of_blocks variable to be equal to 1 and len_sep to specify the length of the random string.
eg: len_sep = 10, no_of_blocks = 1, will generate the following pattern ie. random string of length 10,
F01xgCdoDU
import random as r
def generate_random_string(len_sep, no_of_blocks):
random_string = ''
random_str_seq = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(0,len_sep*no_of_blocks):
if i % len_sep == 0 and i != 0:
random_string += '-'
random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
return random_string
I got the same issue, but i solved it with changing my Grunt.js to Gruntfile.js Check your file name before typing grunt.cmd on windows cmd (if you're using windows).
Breadth first is a queue, depth first is a stack.
For breadth first, add all children to the queue, then pull the head and do a breadth first search on it, using the same queue.
For depth first, add all children to the stack, then pop and do a depth first on that node, using the same stack.
I hope this complete example will help you.
This is the TaxiInfo class which holds information about a taxi ride:
namespace Taxi.Models
{
public class TaxiInfo
{
public String Driver { get; set; }
public Double Fare { get; set; }
public Double Distance { get; set; }
public String StartLocation { get; set; }
public String EndLocation { get; set; }
}
}
We also have a convenience model which holds a List of TaxiInfo(s):
namespace Taxi.Models
{
public class TaxiInfoSet
{
public List<TaxiInfo> TaxiInfoList { get; set; }
public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
{
TaxiInfoList = new List<TaxiInfo>();
foreach(var TaxiInfo in TaxiInfos)
{
TaxiInfoList.Add(TaxiInfo);
}
}
}
}
Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:
public ActionResult Index()
{
var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };
return View(new TaxiInfoSet(taxi1,taxi2));
}
The code for the view is as follows:
@model Taxi.Models.TaxiInfoSet
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach(var TaxiInfo in Model.TaxiInfoList){
<form>
<h1>Cost: [email protected]</h1>
<h2>Distance: @(TaxiInfo.Distance) km</h2>
<p>
Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
</p>
@Html.ActionLink("Home","Booking",TaxiInfo)
</form>
}
The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:
public ActionResult Booking(TaxiInfo Taxi)
{
return View(Taxi);
}
This returns a the following view:
@model Taxi.Models.TaxiInfo
@{
ViewBag.Title = "Booking";
}
<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>
A visual tour:
This problem is ridiculous! No one's solution worked for me in 2010, but I based mine off of tpascale's:
Dim C As ChartObject
Set C = ActiveSheet.ChartObjects("CTR_Chart")
C.Chart.SetSourceData Source:=Range( _
"KeywordBreakdown!$A$8:$A$12,KeywordBreakdown!$E$8:$E$12")
Simply redefined the Source Data range. If it's a named range, that could conceivably be reasonably clean. I guess the best solution to this is keep trying to modify different chart properties until it refreshes.
You can simply do
node --version
or short form would also do
node -v
If above commands does not work, you have done something wrong in installation, reinstall the node.js and try.
I found a duplicate over here: Convert json data to a html table
Well, there are many plugins exists, including commercial one (Make this as commercial project?! Kinda overdone... but you can checkout over here: https://github.com/alfajango/jquery-dynatable)
This one has more fork: https://github.com/afshinm/Json-to-HTML-Table
//Example data, Object
var objectArray = [{
"Total": "34",
"Version": "1.0.4",
"Office": "New York"
}, {
"Total": "67",
"Version": "1.1.0",
"Office": "Paris"
}];
//Example data, Array
var stringArray = ["New York", "Berlin", "Paris", "Marrakech", "Moscow"];
//Example data, nested Object. This data will create nested table also.
var nestedTable = [{
key1: "val1",
key2: "val2",
key3: {
tableId: "tblIdNested1",
tableClassName: "clsNested",
linkText: "Download",
data: [{
subkey1: "subval1",
subkey2: "subval2",
subkey3: "subval3"
}]
}
}];
Apply the code
//Only first parameter is required
var jsonHtmlTable = ConvertJsonToTable(objectArray, 'jsonTable', null, 'Download');
Or you might want to checkout this jQuery plugins as well: https://github.com/jongha/jquery-jsontotable
I think jongha's plugins is easier to use
<div id="jsontotable" class="jsontotable"></div>
var data = [[1, 2, 3], [1, 2, 3]];
$.jsontotable(data, { id: '#jsontotable', header: false });
localStorage
is something that is kept on the client side. There is no data transmitted to the server side.
You can only get the data with JavaScript and you can send it to the server side with Ajax.
Microsoft's Visual Studio Code text editor has built in support for .md files written in markdown syntax.
The syntax is automatically color-coded inside of the .md file, and a preview window of the rendered markdown can be viewed by pressing Shift+Ctrl+V
(Windows) or Shift+Cmd+V
(Mac).
To see them side-by-side, drag the preview tab to the right side of the editor, or use Ctrl+K V
(Windows) or Cmd+K V
(Mac) instead.
VS Code uses the marked library for parsing, and has Github Flavored Markdown support enabled by default, but it will not display the Github Emoji inline like Github's Atom text editor does.
Also, VS Code supports has several markdown plugins available for extended functionality.
for UNIQUEIDENTIFIER datatype in sql server try this
Alter table table_name
add ID UNIQUEIDENTIFIER not null unique default(newid())
If you want to create primary key out of that column use this
ALTER TABLE table_name
ADD CONSTRAINT PK_name PRIMARY KEY (ID);
My privilege prevents me making my comment on the first post so it will have to go here.
Consideration should be taken into account of 2038 unix bug when setting 20 years in advance from the current date which is suggest as the correct answer above.
Your cookie on January 19, 2018 + (20 years) could well hit 2038 problem depending on the browser and or versions you end up running on.
Many mobile devices have resolutions so high that it's hard to distinguish between them and much larger screens. There are two ways to deal with this problem:
Use the following HTML code to scale the pixels (grouping smaller pixels into groups the size of the unit pixel - 96dpi, so px
units will have the same physical size on all screens). Note that this will affect the scale of pretty much everything in your website, but this is generally the way to go when making sites mobile-friendly.
<meta name="viewport" content="width=device-width, initial-scale=1">
Alternatively, measuring the screen width in @media
queries using cm
instead of px
units can tell you if you're dealing with a physically small screen regardless of resolution.
/*link*/
$q.when(scope.regions).then(function(result) {
console.log(result);
});
var Regions = $resource('mocks/regions.json');
$scope.regions = Regions.query().$promise.then(function(response) {
return response;
});
Try escaping the slash: someString.replace(/\//g, "-");
By the way - /
is a (forward-)slash; \
is a backslash.
filter_by
is used for simple queries on the column names using regular kwargs, like
db.users.filter_by(name='Joe')
The same can be accomplished with filter
, not using kwargs, but instead using the '==' equality operator, which has been overloaded on the db.users.name object:
db.users.filter(db.users.name=='Joe')
You can also write more powerful queries using filter
, such as expressions like:
db.users.filter(or_(db.users.name=='Ryan', db.users.country=='England'))
all the properties and methods of the parent class is inherited in the child class so theoretically you can access them in the child class but beware using the protected
keyword in your class because it throws a fatal error when used in the child class.
as mentioned in php.net
The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.
You can combine the following two commands
cat("\014");
cat(rep("\n", 50))
I added both declarations on the a href which worked in outlook and gmail apps. outlook ignores the !important and gmail needs it. Web versions of email work with both/either.
text-decoration: none !important; text-decoration: none;
Try this:
var thumbnailHold;
$(".image_thumb").mousedown(function() {
thumbnailHold = setTimeout(function(){
checkboxOn(); // Your action Here
} , 1000);
return false;
});
$(".image_thumb").mouseup(function() {
clearTimeout(thumbnailHold);
});
Try this:
Update users
Set username = 'Jack', password='123'
Where ID = '1'
Or if you're actually trying to insert:
Insert Into users (id, username, password) VALUES ('1', 'Jack','123');
The issue has been fixed in Infinispan 5.1.5.CR1: ISPN-2023
I believe
rgba( 0, 0, 0, 0.8 )
is equivalent in shade with #333
.
Live demo: http://jsfiddle.net/8MVC5/1/
Cron is good for something that will run periodically, like every Saturday at 4am. There's also anacron, which works around power shutdowns, sleeps, and whatnot. As well as at.
But for a one-off solution, that doesn't require root or anything, you can just use date to compute the seconds-since-epoch of the target time as well as the present time, then use expr to find the difference, and sleep that many seconds.
First install openpyxl:
pip install openpyxl
Then:
from openpyxl import Workbook
import csv
wb = Workbook()
ws = wb.active
with open('test.csv', 'r') as f:
for row in csv.reader(f):
ws.append(row)
wb.save('name.xlsx')
Instead of instantiating the FileUpload
in your code behind file, just declare it in your markup file (.aspx file):
<asp:FileUpload ID="fileUpload" runat="server" />
Then you will be able to access all of the properties of the control, such as HasFile
.
To get back the unstaged and staged changes which were reverted after a commit:
git reset HEAD@{1}
To recover all unstaged deletions:
git ls-files -d | xargs git checkout --
This is likely due to your system's overcommit handling mode.
In the default mode, 0
,
Heuristic overcommit handling. Obvious overcommits of address space are refused. Used for a typical system. It ensures a seriously wild allocation fails while allowing overcommit to reduce swap usage. root is allowed to allocate slightly more memory in this mode. This is the default.
The exact heuristic used is not well explained here, but this is discussed more on Linux over commit heuristic and on this page.
You can check your current overcommit mode by running
$ cat /proc/sys/vm/overcommit_memory
0
In this case you're allocating
>>> 156816 * 36 * 53806 / 1024.0**3
282.8939827680588
~282 GB, and the kernel is saying well obviously there's no way I'm going to be able to commit that many physical pages to this, and it refuses the allocation.
If (as root) you run:
$ echo 1 > /proc/sys/vm/overcommit_memory
This will enable "always overcommit" mode, and you'll find that indeed the system will allow you to make the allocation no matter how large it is (within 64-bit memory addressing at least).
I tested this myself on a machine with 32 GB of RAM. With overcommit mode 0
I also got a MemoryError
, but after changing it back to 1
it works:
>>> import numpy as np
>>> a = np.zeros((156816, 36, 53806), dtype='uint8')
>>> a.nbytes
303755101056
You can then go ahead and write to any location within the array, and the system will only allocate physical pages when you explicitly write to that page. So you can use this, with care, for sparse arrays.
From your SQL Server Management Studio, you open Object Explorer, go to your database where you want to load the data into, right click, then pick Tasks > Import Data.
This opens the Import Data Wizard, which typically works pretty well for importing from Excel. You can pick an Excel file, pick what worksheet to import data from, you can choose what table to store it into, and what the columns are going to be. Pretty flexible indeed.
You can run this as a one-off, or you can store it as a SQL Server Integration Services (SSIS) package into your file system, or into SQL Server itself, and execute it over and over again (even scheduled to run at a given time, using SQL Agent).
Update: yes, yes, yes, you can do all those things you keep asking - have you even tried at least once to run that wizard??
OK, here it comes - step by step:
Step 1: pick your Excel source
Step 2: pick your SQL Server target database
Step 3: pick your source worksheet (from Excel) and your target table in your SQL Server database; see the "Edit Mappings" button!
Step 4: check (and change, if needed) your mappings of Excel columns to SQL Server columns in the table:
Step 5: if you want to use it later on, save your SSIS package to SQL Server:
Step 6: - success! This is on a 64-bit machine, works like a charm - just do it!!
This can be done with a single statement and some XML magic:
select table_name,
to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from '||owner||'.'||table_name)),'/ROWSET/ROW/C')) as count
from all_tables
where owner = 'FOOBAR'
You should be referencing it as localhost
. Like this:
<img src="http:\\localhost\site\img\mypicture.jpg"/>
Use findElements
instead of findElement
.
findElements
will return an empty list if no matching elements are found instead of an exception.
To check that an element is present, you could try this
Boolean isPresent = driver.findElements(By.yourLocator).size() > 0
This will return true if at least one element is found and false if it does not exist.
The official documentation recommends this method:
findElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead.
To do it in non interactive mode (from a script):
systemctl start mysqld
MYSQL_ROOT_TMP_PSW=$(grep 'temporary password' $logpath/mysqld.log |sed "s|.*: ||")
## POPULATE SCHEMAS WITH ROOT USER
/usr/bin/mysql --connect-expired-password -u root -p${MYSQL_ROOT_TMP_PSW} < "$mysql_init_script"
Here's the head of the init script
SET GLOBAL validate_password_policy=LOW;
FLUSH privileges;
SET PASSWORD = PASSWORD('MYSQL_ROOT_PSW');
FLUSH privileges;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';
FLUSH privileges;
...
Then restart the service systemctl restart mysqld
show all apps heroku have access with
heroku apps
And check you app exist then
execute heroku git:remote -a yourapp_exist
React is a declarative, efficient, and flexible JavaScript library for building user interfaces.Your components tell React what you want to render – then React will efficiently update and render just the right components when your data changes. Here, ShoppingList is a React component class, or React component type.
A React Native app is a real mobile app. With React Native, you don't build a “mobile web app”, an “HTML5 app”, or a “hybrid app”. You build a real mobile app that's indistinguishable from an app built using Objective-C or Java. React Native uses the same fundamental UI building blocks as regular iOS and Android apps.
rownumber() over(...) is working but I didn't like this solution for 2 reasons. - This function is not available when you using older version of SQL like SQL2000 - Dependency on function and is not really readable.
Another solution is:
SELECT tmpall.[OrderNO] ,
tmpall.[PartCode] ,
tmpall.[Quantity] ,
FROM (SELECT [OrderNO],
[PartCode],
[Quantity],
[DateEntered]
FROM you_table) AS tmpall
INNER JOIN (SELECT [OrderNO],
Max([DateEntered]) AS _max_date
FROM your_table
GROUP BY OrderNO ) AS tmplast
ON tmpall.[OrderNO] = tmplast.[OrderNO]
AND tmpall.[DateEntered] = tmplast._max_date
On windows launching default browser with a predefined url:
Tools > Build System > New Build System:
{
"cmd": ["cmd","/K","start http://localhost/projects/Reminder/"]
}
ctrl + B and voila!
I realize this is an old question but I found it in a Google search so I'm going to go ahead and answer just in case someone else runs across this. I'm on a Mac and had the same issue, but solved it by using HomeBrew. Once you've got it installed, you can just run this command:
brew install php56-pdo-pgsql
And replace the 56 with whatever version of PHP you're using without the decimal point.
2021 ANSWER
You can use the native .toLocaleDateString()
function which supports several useful params like locale (to select a format like MM/DD/YYYY or YYYY/MM/DD), timezone (to convert the date) and formats details options (eg: 1 vs 01 vs January).
Examples
new Date().toLocaleDateString() // 8/19/2020
new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}); // 08/19/2020 (month and day with two digits)
new Date().toLocaleDateString('en-ZA'); // 2020/08/19 (year/month/day) notice the different locale
new Date().toLocaleDateString('en-CA'); // 2020-08-19 (year-month-day) notice the different locale
new Date().toLocaleString("en-US", {timeZone: "America/New_York"}); // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)
new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"}); // 09 (just the hour)
Notice that sometimes to output a date in your specific desire format, you have to find a compatible locale with that format. You can find the locale examples here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all
Please notice that locale just change the format, if you want to transform a specific date to a specific country or city time equivalent then you need to use the timezone param.
My Problem: "please select Android SDK", But everything is okey :( -> I think one of IntelliJ file was crashed (after blue screen of death)
My resolution:
File -> Settings -> Android SDK -> Android SDK Location Edit -> Next, Next (Android SDK is up to date.), Finished
... and crashed file was repaired!
I was able to solve a similar problem with simple URL parameters and auto refresh.
You can get the values from the URL parameters, do whatever you want with them and simply refresh the page.
HTML:
<a href=\"webpage.aspx?parameterName=parameterValue"> LinkText </a>
C#:
string variable = Request.QueryString["parameterName"];
if (parameterName!= null)
{
Session["sessionVariable"] += parameterName;
Response.AddHeader("REFRESH", "1;URL=webpage.aspx");
}