VirtualBox is a virtualizer, not an emulator. (The name kinda gives it away.) I.e. it can only virtualize a CPU that is actually there, not emulate one that isn't. In particular, VirtualBox can only virtualize x86 and AMD64 CPUs. iOS only runs on ARM CPUs.
$a !== $b
TRUE if $a
is not equal to $b
, or they are not of the same type
Please Refer to http://php.net/manual/en/language.operators.comparison.php
If you want to open it for a range and for a protocol
ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp
.img-responsive {
margin: 0 auto;
}
you can write like above code in your document so no need to add one another class in image tag.
Tried all the combinations cited above with this Code and got it working, was the only one that worked on that string -> (12) 3456-7890
var str="(12) 3456-7890";
str.replace( /\D+/g, '');
Result: "1234567890"
Obs: i know that a string like that will not be on the attr but whatever, the solution is better, because its more complete.
I use SFTP and its work for me.
step into will dig into method calls
step over will just execute the line and go to the next one
since some minor explanations were missing
Use @Deprecated
annotation on the method like this
/**
* @param basePrice
*
* @deprecated reason this method is deprecated <br/>
* {will be removed in next version} <br/>
* use {@link #setPurchasePrice()} instead like this:
*
*
* <blockquote><pre>
* getProduct().setPurchasePrice(200)
* </pre></blockquote>
*
*/
@Deprecated
public void setBaseprice(int basePrice) {
}
<br/>
{@link #setPurchasePrice()}
In Windows, even after installing graphviz-2.38.msi, you can add your own path in pydot.py (found under site-package folder)
if os.sys.platform == 'win32':
# Try and work out the equivalent of "C:\Program Files" on this
# machine (might be on drive D:, or in a different language)
#
if os.environ.has_key('PROGRAMFILES'):
# Note, we could also use the win32api to get this
# information, but win32api may not be installed.
path = os.path.join(os.environ['PROGRAMFILES'], 'ATT', 'GraphViz', 'bin')
else:
#Just in case, try the default...
path = r"C:\PYTHON27\GraphViz\bin" # add here.
You can find the solution to this problem at: https://help.github.com/en/github/using-git/configuring-git-to-handle-line-endings
Simplified description of how you can solve this problem on windows:
Global settings for line endings The git config core.autocrlf command is used to change how Git handles line endings. It takes a single argument.
On Windows, you simply pass true to the configuration. For example: C:>git config --global core.autocrlf true
Good luck, I hope I helped.
No, there shouldn't be. However, it's possible there is differences in some browsers, so either (or neither) may not work in some case.
For your own specific server or different pages & image button you could use something like this (PHP only)
<a href="http://www.facebook.com/sharer/sharer.php?u=http://'.$_SERVER['SERVER_NAME'].'" target="_blank"><img src="http://i.stack.imgur.com/rffGp.png" /></a>
I cannot share the snippet with this but you will get the idea...
You can cast like this:
return this.createMarkerStyle(<MarkerSymbolInfo> symbolInfo);
Or like this if you want to be compatible with tsx mode:
return this.createMarkerStyle(symbolInfo as MarkerSymbolInfo);
Just remember that this is a compile-time cast, and not a runtime cast.
Offline mode could be set in Android Studio and in your project. To verify that gradle won't build your project in offline mode:
Using pytz
from datetime import datetime
from pytz import timezone
fmt = "%Y-%m-%d %H:%M:%S %Z%z"
timezonelist = ['UTC','US/Pacific','Europe/Berlin']
for zone in timezonelist:
now_time = datetime.now(timezone(zone))
print now_time.strftime(fmt)
Assuming you want to check that all characters in the string are digits, you could use the Enumerable.All Extension Method with the Char.IsDigit Method as follows:
bool allCharactersInStringAreDigits = myStringVariable.All(char.IsDigit);
Yes, it's a valid test although there's an implicit conversion from int to double. For clarity/simplicity you should use (foo.x == 0.0) to test. That will hinder NAN errors/division by zero, but the double value can in some cases be very very very close to 0, but not exactly zero, and then the test will fail (I'm talking about in general now, not your code). Division by that will give huge numbers.
If this has anything to do with money, do not use float or double, instead use BigDecimal.
This solution could seem very long, but it's not. I just included many examples so that everything was clear. It worked for me in Mavericks OS.
Note: I combined and edited some of the answers shown above, added some examples and format and posted the result, so the credit goes mostly to the creators of the original posts.
Download Maven from here.
Open the Terminal.
Extract the file you just downloaded to the location you want, either manually or by typing the following lines in the Terminal (fill the required data):
mv [Your file name] [Destination location]/
tar -xvf [Your file name]
For example, if our file is named "apache-maven-3.2.1-bin.tar
" (Maven version 3.2.1) and we want to locate it in the "/Applications
" directory, then we should type the following lines in Terminal:
mv apache-maven-3.2.1-bin.tar /Applications/
tar -xvf apache-maven-3.2.1-bin.tar
If you don't have any JDK (Java Development Kit) installed on your computer, install one.
Type "java -version
" in Terminal. You should see something like this:
java version "1.8.0"
Java(TM) SE Runtime Environment (build 1.8.0-b132)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)
Remember your java version (in the example, 1.8.0).
Type "cd ~/
" to go to your home folder.
Type "touch .bash_profile
".
Type "open -e .bash_profile
" to open .bash_profile in TextEdit.
Type the following in TextEdit (copy everything and replace the required data):
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk[Your Java version].jdk/Contents/Home
export M2_HOME=[Your file location]/apache-maven-[Your Maven version]/
export PATH=$PATH:$M2_HOME/bin
alias mvn='$M2_HOME/bin/mvn'
For example, in our case we would replace "[Your Java version]
" with "1.8.0
" (value got in step 5), "[Your file location]
" with "/Applications
" (value used as "Destination Location" in step 3) and "[Your Maven version]
" with "3.2.1
" (Maven version observed in step 3), resulting in the following code:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home
export M2_HOME=/Applications/apache-maven-3.2.1/
export PATH=$PATH:$M2_HOME/bin
alias mvn='$M2_HOME/bin/mvn'
Save your changes
Type "source .bash_profile
" to reload .bash_profile and update any functions you add.
Type mvn -version
. If successful you should see the following:
Apache Maven [Your Maven version] ([Some weird stuff. Don't worry about this])
Maven home: [Your file location]/apache-maven-[Your Maven version]
Java version: [You Java version], vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk[Your Java version].jdk/Contents/Home/jre
[Some other stuff which may vary depending on the configuration and the OS of the computer]
In our example, the result would be the following:
Apache Maven 3.2.1 (ea8b2b07643dbb1b84b6d16e1f08391b666bc1e9; 2014-02-14T18:37:52+01:00)
Maven home: /Applications/apache-maven-3.2.1
Java version: 1.8.0, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0</b>.jdk/Contents/Home/jre
Default locale: es_ES, platform encoding: UTF-8
OS name: "mac os x", version: "10.9.2", arch: "x86_64", family: "mac"
A simple trick that works fine for me to prevent conflicts between older and newer javascript files. That means: If there is a conflict and some error occurs, the user will be prompted to press Ctrl-F5.
At the top of the page add something like
<h1 id="welcome"> Welcome to this page <span style="color:red">... press Ctrl-F5</span></h1>
looking like
Let this line of javascript be the last to be executed when loading the page:
document.getElementById("welcome").innerHTML = "Welcome to this page"
In case that no error occurs the welcome greeting above will hardly be visible and almost immediately be replaced by
@Html.ActionLink("linkText", "Action", new {controller="Controller"}, new {target="_blank",@class="edit"})
script below will open the action view url in a new window
<script type="text/javascript">
$(function (){
$('a.edit').click(function () {
var url = $(this).attr('href');
window.open(url, "popupWindow", "width=600,height=800,scrollbars=yes");
});
return false;
});
</script>
Thanks to @Arraxas's anwser, I customized the arrow and make the input
element auto-adaptive to the select
element, and it looks good on Chrome, Firefox of my Android mobile phone (set color:transparent
for select
and some color for option
to hide text display of the select
because the input
and .combobox div:after
cannot completely cover select
).
/* https://stackoverflow.com/questions/13694271/modify-select-so-only-the-first-one-is-gray/41941056#41941056
select option:first-child, */
.combobox select, .combobox select option { color: #000000; }
.combobox select:invalid, .combobox select option[value=""] { color:grey; }
.combobox {position:absolute; left:80px; top:6px;}
.combobox>div { position:relative; font-size:1em; }
.combobox select {
font-size:inherit; color:transparent;
padding:0; -moz-appearance:none; -webkit-appearance:none; appearance:none;
border:1px solid blueviolet;
}
.combobox input {
position:absolute;top:1px;left:0px; text-overflow:ellipsis;
box-sizing:border-box; padding:0px; margin:0px; height:calc(100% - 1px); width:calc(100% - 20px);
border:1px solid blueviolet; border-right:none; border-top:none;
}
.combobox>div:after{
position:absolute; top:0px; right:0px; height:100%; width:20px;
box-sizing:border-box; content:"?"; border:1px solid blueviolet; pointer-events:none;
display:flex; flex-direction:row; align-items:center; justify-content:center;
}
.combobox select:focus, .combobox input:focus {outline:none;}
_x000D_
<!-- mandatory benefits/social security/welfare -->
<div class="combobox"><div>
<select id=MandatoryBenefits onchange="this.nextElementSibling.value=this.value" required>
<option value="" selected>Select ...</option>
<option value="Pension">Pension %</option>
<option value="Medical">Medical %</option>
<option value="Unemployment">Unemployment %</option>
<option value="Injury">Injury %</option>
<option value="Maternity">Maternity %</option>
<option value="Serious Illness">Serious Illness %</option>
<option value="Housing Fund">Housing Fund %</option>
</select>
<input type="text" value="" onchange="this.previousElementSibling.selectedIndex=0"
oninput="this.previousElementSibling.options[0].value=this.value; this.previousElementSibling.options[0].innerHTML=this.value" />
</div></div>
_x000D_
online demo (@jsbin)
I noticed that in netbeans Apache configuration in the servers tab. you can state the platform for your web application. I changed to 1.8 and it worked fine. (I am targeting java 8 platform in my application). Hope that might t help.
If n is 2, it's prime.
If n is 1, it's not prime.
If n is even, it's not prime.
If n is odd, bigger than 2, we must check all odd numbers 3..sqrt(n)+1, if any of this numbers can divide n, n is not prime, else, n is prime.
For better performance i recommend sieve of eratosthenes.
Here is the code sample:
bool is_prime(int n) { if (n == 2) return true; if (n == 1 || n % 2 == 0) return false; for (int i = 3; i*i < n+1; i += 2) { if (n % i == 0) return false; } return true; }
This is how we do it in our application
def store_location
session[:return_to] = request.fullpath if request.get? and controller_name != "user_sessions" and controller_name != "sessions"
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
end
This way you only store last GET request in :return_to
session param, so all forms, even when multiple time POSTed would work with :return_to
.
Now that the Web Audio API is here and gaining browser support, that could be a more robust option.
Zounds is a primitive wrapper around that API for playing simple one-shot sounds with a minimum of boilerplate at the point of use.
In a local directory that contains the file ./docs/specs/openapi.yml
that you want to view, you can run the following to start a container and access the spec at http://127.0.0.1:8246
.
docker run -t -i -p 8246:8080 -e SWAGGER_JSON=/var/specs/openapi.yml -v $PWD/docs/specs:/var/specs swaggerapi/swagger-ui
Selenium Web Driver Handling Frames
It is impossible to click iframe directly through XPath since it is an iframe. First we have to switch to the frame and then we can click using xpath.
driver.switchTo().frame()
has multiple overloads.
driver.switchTo().frame(name_or_id)
Here your iframe
doesn't have id or name, so not for you.
driver.switchTo().frame(index)
This is the last option to choose, because using index is not stable enough as you could imagine. If this is your only iframe in the page, try driver.switchTo().frame(0)
driver.switchTo().frame(iframe_element)
The most common one. You locate your iframe like other elements, then pass it into the method.
driver.switchTo().
defaultContent(); [parentFrame, defaultContent, frame]
// Based on index position:
int frameIndex = 0;
List<WebElement> listFrames = driver.findElements(By.tagName("iframe"));
System.out.println("list frames "+listFrames.size());
driver.switchTo().frame(listFrames.get( frameIndex ));
// XPath|CssPath Element:
WebElement frameCSSPath = driver.findElement(By.cssSelector("iframe[title='Fill Quote']"));
WebElement frameXPath = driver.findElement(By.xpath(".//iframe[1]"));
WebElement frameTag = driver.findElement(By.tagName("iframe"));
driver.switchTo().frame( frameCSSPath ); // frameXPath, frameTag
driver.switchTo().frame("relative=up"); // focus to parent frame.
driver.switchTo().defaultContent(); // move to the most parent or main frame
// For alert's
Alert alert = driver.switchTo().alert(); // Switch to alert pop-up
alert.accept();
alert.dismiss();
XML Test:
<html>
<IFame id='1'>... parentFrame() « context remains unchanged. <IFame1>
|
-> <IFrame id='2'>... parentFrame() « Change focus to the parent context. <IFame1>
</html>
</html>
<frameset cols="50%,50%">
<Fame id='11'>... defaultContent() « driver focus to top window/first frame. <html>
|
-> <Frame id='22'>... defaultContent() « driver focus to top window/first frame. <Fame11>
frame("relative=up") « focus to parent frame. <Fame11>
</frameset>
</html>
Conversion of RC to Web-Driver Java commands. link.
<frame>
is an HTML element which defines a particular area in which another HTML document can be displayed. A frame should be used within a <frameset>
. « Deprecated. Not for use in new websites.
This might be a bug of the recent anaconda. What works for me:
step1: vim /anaconda/bin/activate
, it shows:
#!/bin/sh
_CONDA_ROOT="/anaconda"
# Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
\. "$_CONDA_ROOT/etc/profile.d/conda.sh" || return $?
conda activate "$@"
step2: comment out the last line: # conda activate "$@"
.catch(error => { throw error})
is a no-op. It results in unhandled rejection in route handler.
As explained in this answer, Express doesn't support promises, all rejections should be handled manually:
router.get("/emailfetch", authCheck, async (req, res, next) => {
try {
//listing messages in users mailbox
let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
emailFetch = emailFetch.data
res.send(emailFetch)
} catch (err) {
next(err);
}
})
If you use the clipboard manager Ditto (open source, gratis), you can simply use the shortcut to paste from Ditto, and it will paste the clipboard in CMD for you.
In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime()
gives you the mentioned milliseconds).
In your solution:
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();
long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);
you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.
Another possible solution would be to utilise the static fields of the Calendar
class:
//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);
Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.
You can synchronize your code over the class. That would be simplest.
public class Test
{
private static int count = 0;
private static final Object lock= new Object();
public synchronized void foo()
{
synchronized(Test.class)
{
count++;
}
}
}
Hope you find this answer useful.
I have used this site to find the resolution and developed CSS per actual numbers. My numbers vary quite a bit from the above answers, except that the my CSS actually hits the desired devices.
Also, have this debugging piece of code right after your media query e.g:
@media only screen and (min-width: 769px) and (max-width: 1281px) {
/* for 10 inches tablet screens */
body::before {
content: "tablet to some desktop media query (769 > 1281) fired";
font-weight: bold;
display: block;
text-align: center;
background: rgba(255, 255, 0, 0.9); /* Semi-transparent yellow */
position: absolute;
top: 0;
left: 0;
right: 0;
z-index: 99;
}
}
Add this debugging item in every single media query and you will see what query has being applied.
// app.js or break it up into seperate files
// whatever structure is your flavor
angular.module('myApp', [])
.constant('CONFIG', {
'APP_NAME' : 'My Awesome App',
'APP_VERSION' : '0.0.0',
'GOOGLE_ANALYTICS_ID' : '',
'BASE_URL' : '',
'SYSTEM_LANGUAGE' : ''
})
.controller('GlobalVarController', ['$scope', 'CONFIG', function($scope, CONFIG) {
// If you wish to show the CONFIG vars in the console:
console.log(CONFIG);
// And your CONFIG vars in .constant will be passed to the HTML doc with this:
$scope.config = CONFIG;
}]);
In your HTML:
<span ng-controller="GlobalVarController">{{config.APP_NAME}} | v{{config.APP_VERSION}}</span>
As Coli88 said, you should check the UINavigationBarDelegate protocol.
In a more general way, you can also use the - (void)viewWillDisapear:(BOOL)animated
to perform custom work when the view retained by the currently visible view controller is about to disappear. Unfortunately, this would cover bother the push and the pop cases.
When the first characters in a script are #!
, that is called the shebang. If your file starts with
#!/path/to/something
the standard is to run something
and pass the rest of the file to that program as an input.
With that said, the difference between #!/bin/bash
, #!/bin/sh
, or even #!/bin/zsh
is whether the bash, sh, or zsh programs are used to interpret the rest of the file. bash
and sh
are just different programs, traditionally. On some Linux systems they are two copies of the same program. On other Linux systems, sh
is a link to dash
, and on traditional Unix systems (Solaris, Irix, etc) bash
is usually a completely different program from sh
.
Of course, the rest of the line doesn't have to end in sh. It could just as well be #!/usr/bin/python
, #!/usr/bin/perl
, or even #!/usr/local/bin/my_own_scripting_language
.
PowerCommands is a Microsoft-created plugin that offers a variety of new features that one would think probably should have been in Visual Studio in the first place.
These include
You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.
Escape dot. Sample command will be.
grep '0\.00'
I came up with a simple placeholder JQuery script that allows a custom color and uses a different behavior of clearing inputs when focused. It replaces the default placeholder in Firefox and Chrome and adds support for IE8.
// placeholder script IE8, Chrome, Firefox
// usage: <input type="text" placeholder="some str" />
$(function () {
var textColor = '#777777'; //custom color
$('[placeholder]').each(function() {
(this).attr('tooltip', $(this).attr('placeholder')); //buffer
if ($(this).val() === '' || $(this).val() === $(this).attr('placeholder')) {
$(this).css('color', textColor).css('font-style','italic');
$(this).val($(this).attr('placeholder')); //IE8 compatibility
}
$(this).attr('placeholder',''); //disable default behavior
$(this).on('focus', function() {
if ($(this).val() === $(this).attr('tooltip')) {
$(this).val('');
}
});
$(this).on('keydown', function() {
$(this).css('font-style','normal').css('color','#000');
});
$(this).on('blur', function() {
if ($(this).val() === '') {
$(this).val($(this).attr('tooltip')).css('color', textColor).css('font-style','italic');
}
});
});
});
Use whichever suits your need.
GridView.count(...)
GridView.count(
crossAxisCount: 2,
children: <Widget>[
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
],
)
GridView.builder(...)
GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemBuilder: (_, index) => FlutterLogo(),
itemCount: 4,
)
GridView(...)
GridView(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
children: <Widget>[
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
],
)
GridView.custom(...)
GridView.custom(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
childrenDelegate: SliverChildListDelegate(
[
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
],
),
)
GridView.extent(...)
GridView.extent(
maxCrossAxisExtent: 400,
children: <Widget>[
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
],
)
Output (same for all):
I liked user1333423's solution except that it always re-sized every column; i needed to allow some columns to be fixed width. So in this version columns with a width set to "Auto" will be auto-sized and those set to a fixed amount will not be auto-sized.
public class AutoSizedGridView : GridView
{
HashSet<int> _autoWidthColumns;
protected override void PrepareItem(ListViewItem item)
{
if (_autoWidthColumns == null)
{
_autoWidthColumns = new HashSet<int>();
foreach (var column in Columns)
{
if(double.IsNaN(column.Width))
_autoWidthColumns.Add(column.GetHashCode());
}
}
foreach (GridViewColumn column in Columns)
{
if (_autoWidthColumns.Contains(column.GetHashCode()))
{
if (double.IsNaN(column.Width))
column.Width = column.ActualWidth;
column.Width = double.NaN;
}
}
base.PrepareItem(item);
}
}
onBindViewHolder() is called for each and every item and setting the click listener inside onBindVieHolder() is an unnecessary option to repeat when you can call it once in your ViewHolder constructor.
public class MyViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener{
public final TextView textView;
public MyViewHolder(View view){
textView = (TextView) view.findViewById(R.id.text_view);
view.setOnClickListener(this);
// getAdapterPosition() retrieves the position here.
}
@Override
public void onClick(View v){
// Clicked on item
Toast.makeText(mContext, "Clicked on position: " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
}
$(function () {
$('input[type=checkbox]').click(function () {
var chks = document.getElementById('<%= chkRoleInTransaction.ClientID %>').getElementsByTagName('INPUT');
for (i = 0; i < chks.length; i++) {
chks[i].checked = false;
}
if (chks.length > 1)
$(this)[0].checked = true;
});
});
try this :
SET @StartDate = DATE_SUB(DATE(NOW()),INTERVAL (DAY(NOW())-1) DAY);
SET @EndDate = ADDDATE(CURDATE(),1);
select * from table where (date >= @StartDate and date < @EndDate);
you can set Timeout in connection string (time for Establish connection between client and sql). commandTimeout is set per command but its default time is 30 secend
After spending a lot of time with this issue, Here is what I got working
$state.go('stateName',params,{
// prevent the events onStart and onSuccess from firing
notify:false,
// prevent reload of the current state
reload:false,
// replace the last record when changing the params so you don't hit the back button and get old params
location:'replace',
// inherit the current params on the url
inherit:true
});
I just put --password
flag into my command and after hitting Enter it asked me for password, which I supplied.
In the related question you posted, we already have a way to achieve that in plain javascript, so we only need to get the js reference to the dom node we want to scroll.
The ref
attribute can be used to declare reference to html elements to make them available in vue's component methods.
Or, if the method in the component
is a handler for some UI event, and the target is related to the div you want to scroll in space, you can simply pass in the event object along with your wanted arguments, and do the scroll like scroll(event.target.nextSibling)
.
If #uploadedfile
is an input with type "file" :
var file = $("#uploadedfile")[0].files[0];
var fileName = file.name;
var fileSize = file.size;
alert("Uploading: "+fileName+" @ "+fileSize+"bytes");
Normally this would fire on the change event, like so:
$("#uploadedfile").on("change", function(){
var file = this.files[0],
fileName = file.name,
fileSize = file.size;
alert("Uploading: "+fileName+" @ "+fileSize+"bytes");
CustomFileHandlingFunction(file);
});
If you know in advance the number of numbers to be entered (e.g. a 4-digit PIN) you could auto-dismiss after 4 key presses, as per my answer to this similar question:
No need for an additional done button in this case.
To combine both Nitzan's and Edwin's answers, I found that something like this works for me:
update = (e: React.FormEvent<EventTarget>): void => {
let target = e.target as HTMLInputElement;
this.props.login[target.name] = target.value;
}
In general you can concatenate a whole sequence of arrays along any axis:
numpy.concatenate( LIST, axis=0 )
but you do have to worry about the shape and dimensionality of each array in the list (for a 2-dimensional 3x5 output, you need to ensure that they are all 2-dimensional n-by-5 arrays already). If you want to concatenate 1-dimensional arrays as the rows of a 2-dimensional output, you need to expand their dimensionality.
As Jorge's answer points out, there is also the function stack
, introduced in numpy 1.10:
numpy.stack( LIST, axis=0 )
This takes the complementary approach: it creates a new view of each input array and adds an extra dimension (in this case, on the left, so each n
-element 1D array becomes a 1-by-n
2D array) before concatenating. It will only work if all the input arrays have the same shape—even along the axis of concatenation.
vstack
(or equivalently row_stack
) is often an easier-to-use solution because it will take a sequence of 1- and/or 2-dimensional arrays and expand the dimensionality automatically where necessary and only where necessary, before concatenating the whole list together. Where a new dimension is required, it is added on the left. Again, you can concatenate a whole list at once without needing to iterate:
numpy.vstack( LIST )
This flexible behavior is also exhibited by the syntactic shortcut numpy.r_[ array1, ...., arrayN ]
(note the square brackets). This is good for concatenating a few explicitly-named arrays but is no good for your situation because this syntax will not accept a sequence of arrays, like your LIST
.
There is also an analogous function column_stack
and shortcut c_[...]
, for horizontal (column-wise) stacking, as well as an almost-analogous function hstack
—although for some reason the latter is less flexible (it is stricter about input arrays' dimensionality, and tries to concatenate 1-D arrays end-to-end instead of treating them as columns).
Finally, in the specific case of vertical stacking of 1-D arrays, the following also works:
numpy.array( LIST )
...because arrays can be constructed out of a sequence of other arrays, adding a new dimension to the beginning.
Either of the following SQL will return all schema in Oracle DB.
select owner FROM all_tables group by owner;
select distinct owner FROM all_tables;
Restarting Your Server Can Resolve this problem.
I was getting the same error while Using Dynamic Jasper Reporting , When i deploy my Application for first use to Create Reports, the Report creation works fine, But Once I Do Hot Deployment of some code changes To the Server, I was getting This Error.
If I may add a comment here...
<c:out value="${param.accountID}"></c:out>
doesn't work for me (it prints a 0).
Instead, this works:
<c:out value="${param['accountID']}"></c:out>
I'm getting the same solution as @camino's comment on https://stackoverflow.com/a/19365454/10593190 and XavierStuvw's reply.
I got it to work (for installing ffmpeg) by simply reinstalling the whole thing from the beginning with all instances of $ ./configure
replaced by $ ./configure --enable-shared
(first make sure to delete all the folders and files including the .so files from the previous attempt).
Apparently this works because https://stackoverflow.com/a/13812368/10593190.
RewriteEngine On
RewriteCond %{SERVER_PORT} 443
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Java native code necessities:
hope these points answers your question :)
Indentation when using a block can cause this error and is very hard to find.
if [ ! -d /var/lib/mysql/mysql ]; then
/usr/bin/mysql --protocol=socket --user root << EOSQL
SET @@SESSION.SQL_LOG_BIN=0;
CREATE USER 'root'@'%';
EOSQL
fi
=> Example above will cause an error because EOSQL is indented. Remove indentation as shown below. Posting this because it took me over an hour to figure out the error.
if [ ! -d /var/lib/mysql/mysql ]; then
/usr/bin/mysql --protocol=socket --user root << EOSQL
SET @@SESSION.SQL_LOG_BIN=0;
CREATE USER 'root'@'%';
EOSQL
fi
The new line character is \n
, like so:
echo __("Thanks for your email.\n<br />\n<br />Your order's details are below:", 'jigoshop');
Now that you are editing the file you need to add the line into the server block, like so;
server {
client_max_body_size 8M;
//other lines...
}
If you are hosting multiple sites add it to the http context like so;
http {
client_max_body_size 8M;
//other lines...
}
And also update the upload_max_filesize
in your php.ini file so that you can upload files of the same size.
Once you are done you need to save, this can be done in vi with pressing esc
key and typing :wq
and returning.
Now you need to restart nginx and php to reload the configs. This can be done using the following commands;
sudo service nginx restart
sudo service php5-fpm restart
Or whatever your php service is called.
A Callable is an object that has the __call__
method. This means you can fake callable functions or do neat things like Partial Function Application where you take a function and add something that enhances it or fills in some of the parameters, returning something that can be called in turn (known as Currying in functional programming circles).
Certain typographic errors will have the interpreter attempting to call something you did not intend, such as (for example) a string. This can produce errors where the interpreter attempts to execute a non-callable application. You can see this happening in a python interpreter by doing something like the transcript below.
[nigel@k9 ~]$ python
Python 2.5 (r25:51908, Nov 6 2007, 15:55:44)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 'aaa'() # <== Here we attempt to call a string.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>>
I think all you need to do for your function is just add PtrSafe: i.e. the first line of your first function should look like this:
Private Declare PtrSafe Function swe_azalt Lib "swedll32.dll" ......
final Map<String,String> params = new HashMap<String,String>();
params.put("email", customer.getEmail());
params.put("password", customer.getPassword());
String url = Constants.BASE_URL+"login";
doWebRequestPost(url, params);
public void doWebRequestPost(String url, final Map<String,String> json){
getmDialogListener().showDialog();
StringRequest post = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
getmDialogListener().dismissDialog();
response....
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(App.TAG,error.toString());
getmDialogListener().dismissDialog();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = json;
return map;
}
};
App.getInstance().getRequestQueue().add(post);
}
If you use SQL authentication, use this:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"User Id=UserName;" +
"Password=Secret;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();
If you use Windows authentication, use this:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();
In an ASP.NET application, I think it goes to the Output or Console window which is visible during debugging.
$('</div>').attr('id', 'holdy').appendTo('body');
With me this error ocurred when I copied and pasted a code in text format to my editor (gedit). The code was in a text document (.odt) and I copied it and pasted it into gedit. If you did the same, you have manually rewrite the code.
Increasing column size with ALTER
will not lose any data:
alter table [progennet_dev].PROGEN.LE
alter column UR_VALUE_3 varchar(500)
As @Martin points out, remember to explicitly specify NULL | NOT NULL
+1 to @MartinNuc, you can run the mysql
client in batch mode and then you won't see the long stream of "OK" lines.
The amount of time it takes to import a given SQL file depends on a lot of things. Not only the size of the file, but the type of statements in it, how powerful your server server is, and how many other things are running at the same time.
@MartinNuc says he can load 4GB of SQL in 4-5 minutes, but I have run 0.5 GB SQL files and had it take 45 minutes on a smaller server.
We can't really guess how long it will take to run your SQL script on your server.
Re your comment,
@MartinNuc is correct you can choose to make the mysql client print every statement. Or you could open a second session and run mysql> SHOW PROCESSLIST
to see what's running. But you probably are more interested in a "percentage done" figure or an estimate for how long it will take to complete the remaining statements.
Sorry, there is no such feature. The mysql client doesn't know how long it will take to run later statements, or even how many there are. So it can't give a meaningful estimate for how much time it will take to complete.
Using the Regex methods in .NET you should be able to match any non-numeric digit using \D, like so:
phoneNumber = Regex.Replace(phoneNumber, "\\D", String.Empty);
You want to define min-width
on row so when it browser is re-sized it does not go below that and wrap.
Updating on the answer of @Ahmed ALaa
# import msvcrt
import getch
def getPass():
passwor = ''
while True:
x = getch.getch()
# x = msvcrt.getch().decode("utf-8")
if x == '\r' or x == '\n':
break
print('*', end='', flush=True)
passwor +=x
return passwor
print("\nout=", getPass())
msvcrt us only for windows, but getch from PyPI should work for both (I only tested with linux). You can also comment/uncomment the two lines to make it work for windows.
I tried several solutions from this page, but none worked. I had a series of numbered files which I simply wanted be ordered by alphabetical foldername so when piped to concat()
they'd be in the same order. That is, preserve the order of the globbing input. Easy, right?
Here's my specific proof-of-concept code (print
is just to see the order printed to the cli):
var order = require('gulp-order');
var gulp = require('gulp');
var print = require('gulp-print').default;
var options = {};
options.rootPath = {
inputDir: process.env.INIT_CWD + '/Draft',
inputGlob: '/**/*.md',
};
gulp.task('default', function(){
gulp.src(options.rootPath.inputDir + options.rootPath.inputGlob, {base: '.'})
.pipe(order([options.rootPath.inputDir + options.rootPath.inputGlob]))
.pipe(print());
});
The reason for the madness of gulp.src
? I determined that gulp.src
was running async when I was able to use a sleep()
function (using a .map
with sleeptime incremented by index) to order the stream output properly.
The upshot of the async of src
mean dirs with more files in it came after dirs with fewer files, because they took longer to process.
The non-static block:
{
// Do Something...
}
Gets called every time an instance of the class is constructed. The static block only gets called once, when the class itself is initialized, no matter how many objects of that type you create.
Example:
public class Test {
static{
System.out.println("Static");
}
{
System.out.println("Non-static block");
}
public static void main(String[] args) {
Test t = new Test();
Test t2 = new Test();
}
}
This prints:
Static
Non-static block
Non-static block
The source code for the Android mobile application open-gpstracker which you appreciated is available here.
You can checkout the code using SVN client application or via Git:
Debugging the source code will surely help you.
SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS
(SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)
or
SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN
(SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)
or
SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B
ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL
Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.
is an inline element ..but in css you can change it simply by:- img{display:inline-block;} or img{display:inline-block;} or img{display:inliblock;}
I am happy that browsers care to save us from intrusive scripts and the like. I am not happy with IE putting something into the browser that makes a simple style-fix look like a hack-attack!
I've used a < span > to represent the file-input so that I could apply appropriate styling to the < div > instead of the < input > (once again, because of IE). Now due to this IE want's to show the User a path with a value that's just guaranteed to put them on guard and in the very least apprehensive (if not totally scare them off?!)... MORE IE-CRAP!
Anyhow, thanks to to those who posted the explanation here: IE Browser Security: Appending "fakepath" to file path in input[type="file"], I've put together a minor fixer-upper...
The code below does two things - it fixes a lte IE8 bug where the onChange event doesn't fire until the upload field's onBlur and it updates an element with a cleaned filepath that won't scare the User.
// self-calling lambda to for jQuery shorthand "$" namespace
(function($){
// document onReady wrapper
$().ready(function(){
// check for the nefarious IE
if($.browser.msie) {
// capture the file input fields
var fileInput = $('input[type="file"]');
// add presentational <span> tags "underneath" all file input fields for styling
fileInput.after(
$(document.createElement('span')).addClass('file-underlay')
);
// bind onClick to get the file-path and update the style <div>
fileInput.click(function(){
// need to capture $(this) because setTimeout() is on the
// Window keyword 'this' changes context in it
var fileContext = $(this);
// capture the timer as well as set setTimeout()
// we use setTimeout() because IE pauses timers when a file dialog opens
// in this manner we give ourselves a "pseudo-onChange" handler
var ieBugTimeout = setTimeout(function(){
// set vars
var filePath = fileContext.val(),
fileUnderlay = fileContext.siblings('.file-underlay');
// check for IE's lovely security speil
if(filePath.match(/fakepath/)) {
// update the file-path text using case-insensitive regex
filePath = filePath.replace(/C:\\fakepath\\/i, '');
}
// update the text in the file-underlay <span>
fileUnderlay.text(filePath);
// clear the timer var
clearTimeout(ieBugTimeout);
}, 10);
});
}
});
})(jQuery);
You could just add one needed external jar file to the project. Go to your project-->java build path-->libraries, add external JARS.Then add your downloaded file from the formal website. My default name is commons-codec-1.10.jar
I think what you want to do is actually pass by reference (pointer) to the function-- create a new environment (which are passed by reference to functions) with the list added to it:
listptr=new.env(parent=globalenv())
listptr$list=mylist
#Then the function is modified as:
lPtrAppend <- function(lstptr, obj) {
lstptr$list[[length(lstptr$list)+1]] <- obj
}
Now you are only modifying the existing list (not creating a new one)
Try this:
x = a > b and 10 or 11
This is a sample of execution:
>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11
math.log2(x)
import math
log2 = math.log(x, 2.0)
log2 = math.log2(x) # python 3.3 or later
math.frexp(x)
If all you need is the integer part of log base 2 of a floating point number, extracting the exponent is pretty efficient:
log2int_slow = int(math.floor(math.log(x, 2.0)))
log2int_fast = math.frexp(x)[1] - 1
Python frexp() calls the C function frexp() which just grabs and tweaks the exponent.
Python frexp() returns a tuple (mantissa, exponent). So [1]
gets the exponent part.
For integral powers of 2 the exponent is one more than you might expect. For example 32 is stored as 0.5x26. This explains the - 1
above. Also works for 1/32 which is stored as 0.5x2?4.
Floors toward negative infinity, so log231 computed this way is 4 not 5. log2(1/17) is -5 not -4.
x.bit_length()
If both input and output are integers, this native integer method could be very efficient:
log2int_faster = x.bit_length() - 1
- 1
because 2n requires n+1 bits. Works for very large integers, e.g. 2**10000
.
Floors toward negative infinity, so log231 computed this way is 4 not 5.
in the university it was necessary to count prime numbers up to 10,000 did so, the teacher was a little surprised, but I passed the test. Lang c#
void Main()
{
int number=1;
for(long i=2;i<10000;i++)
{
if(PrimeTest(i))
{
Console.WriteLine(number+++" " +i);
}
}
}
List<long> KnownPrime = new List<long>();
private bool PrimeTest(long i)
{
if (i == 1) return false;
if (i == 2)
{
KnownPrime.Add(i);
return true;
}
foreach(int k in KnownPrime)
{
if(i%k==0)
return false;
}
KnownPrime.Add(i);
return true;
}
I had the same problem today. I tested for four things, some of them already mentioned here:
Are there any values in your child column that don't exist in the parent column (besides NULL, if the child column is nullable)
Do child and parent columns have the same datatype?
Is there an index on the parent column you are referencing? MySQL seems to require this for performance reasons (http://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html)
And this one solved it for me: Do both tables have identical collation?
I had one table in UTF-8 and the other in iso-something. That didn't work. After changing the iso-table to UTF-8 collation the constraints could be added without problems. In my case, phpMyAdmin didn't even show the child table in iso-encoding in the dropdown for creating the foreign key constraint.
This should be simple using jquery:
HTML:
<input type="text" name="txtJob" value="software engineer">
JS:
var jobValue = $('#txtJob').val(); //Get the text field value
$('#txtJob').val(jobValue); //Set the text field value
it is because you already defined the 'abuse_id' as auto increment, then there is no need to insert its value. it will be inserted automatically. the error comes because you are inserting 1 many times that is duplication of data. the primary key should be unique. should not be repeated.
the thing you have to do is to change your insertion query as below
INSERT INTO `abuses` ( `user_id` , `abuser_username` , `comment` , `reg_date` , `auction_id` )
VALUES ( 100020, 'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;
function getParent(event)
{
return event.target.parentNode;
}
Examples: 1.
document.body.addEventListener("click", getParent, false);
returns the parent element of the current element that you have clicked.
- If you want to use inside any function then pass your event and call the function like this :
function yourFunction(event){ var parentElement = getParent(event); }
document.getElementById('TextBoxID').readOnly = true; //to enable readonly
document.getElementById('TextBoxID').readOnly = false; //to disable readonly
Go to Jenkins -> Manage Jenkins -> Configure System -> Global properties Check the box 'Environment variables' and add the JAVA_HOME path = "C:\Program Files\Java\jdk-10.0.1"
*Don't write bin at the end
Make sure you are loading those modules (myApp.services and myApp.directives) as dependencies of your main app module, like this:
angular.module('myApp', ['myApp.directives', 'myApp.services']);
plunker: http://plnkr.co/edit/wxuFx6qOMfbuwPq1HqeM?p=preview
I have a span. I want to take the value of attribute data-txt-lang, which is used defined.
$(document).ready(function ()
{
<span class="txt-lang-btn" data-txt-lang="en">EN</span>
alert($('.txt-lang-btn').attr('data-txt-lang'));
});
I have modified the above answer, so you don't need to cast from Object
public static <T> List<T> safeClient( List<T> other ) {
return other == null ? Collections.EMPTY_LIST : other;
}
and then simply call the List by
for (MyOwnObject ownObject : safeClient(someList)) {
// do whatever
}
Explaination:
MyOwnObject: If List<Integer>
then MyOwnObject will be Integer in this case.
If you read the docs (http://momentjs.com/docs/#/displaying/) you can find this format:
moment("2015-01-16T12:00:00").format("hh:mm:ss a")
See JS Fiddle http://jsfiddle.net/Bjolja/6mn32xhu/
Don't do things like [A-Z] or [0-9]. Do \p{Lu} and \d instead. Of course, this is valid for perl based regex flavours. This includes java.
I would suggest that you don't make some huge regex. First split the text in sentences. then tokenize it (split into words). Use a regex to check each token/word. Skip the first token from sentence. Check if all tokens are uppercase beforehand and skip the whole sentence if so, or alter the regex in this case.
Well, switch
probably wasn't really meant to work like this, but you can:
AA = 'foo'
switch(AA,
foo={
# case 'foo' here...
print('foo')
},
bar={
# case 'bar' here...
print('bar')
},
{
print('default')
}
)
...each case is an expression - usually just a simple thing, but here I use a curly-block so that you can stuff whatever code you want in there...
I know the question explicitly says JS or jQuery, but anyway using lodash is always on the table for other searchers I suppose.
From the source docs:
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false }
];
_.filter(users, function(o) { return !o.active; });
// => objects for ['fred']
// The `_.matches` iteratee shorthand.
_.filter(users, { 'age': 36, 'active': true });
// => objects for ['barney']
// The `_.matchesProperty` iteratee shorthand.
_.filter(users, ['active', false]);
// => objects for ['fred']
// The `_.property` iteratee shorthand.
_.filter(users, 'active');
// => objects for ['barney']
So the solution for the original question would be just one liner:
var result = _.filter(data, ['website', 'yahoo']);
You could add flex-basis: 100%
to achieve this.
.header {
display: flex;
}
.item {
flex-basis: 100%;
text-align: center;
border: 1px solid black;
}
For what it's worth, you could also use flex: 1
for the same results as well.
The shorthand of flex: 1
is the same as flex: 1 1 0
, which is equivalent to:
.item {
flex-grow: 1;
flex-shrink: 1;
flex-basis: 0;
text-align: center;
border: 1px solid black;
}
you need external library
json-lib-2.2.2-jdk15.jar
List mybeanList = new ArrayList();
mybeanList.add("S");
mybeanList.add("b");
JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);
Google Gson is the best library http://code.google.com/p/google-gson/
Don't let white space fool you. Just test this in a console browser.
Use native javascript. Here is and example with two 'ul' sets with the same class. You don't need to have your 'ul' list all in one line to avoid white space just use your array count to jump over white space.
How to get around white space with querySelector()
then childNodes[]
js fiddle link: https://jsfiddle.net/aparadise/56njekdo/
var y = document.querySelector('.list');
var myNode = y.childNodes[11].style.backgroundColor='red';
<ul class="list">
<li>8</li>
<li>9</li>
<li>100</li>
</ul>
<ul class="list">
<li>ABC</li>
<li>DEF</li>
<li>XYZ</li>
</ul>
The proper way to set the root logging level is using the property logging.level.root
. See documentation, which has been updated since this question was originally asked.
Example:
logging.level.root=WARN
You can pass the value to the function using this.value
, where this
points to the button
<input type="button" value="mybutton1" onclick="dosomething(this.value)">
And then access that value in the function
function dosomething(val){
console.log(val);
}
There's also the pygame.freetype
module which is more modern, works with more fonts and offers additional functionality.
Create a font object with pygame.freetype.SysFont()
or pygame.freetype.Font
if the font is inside of your game directory.
You can render the text either with the render
method similarly to the old pygame.font.Font.render
or directly onto the target surface with render_to
.
import pygame
import pygame.freetype # Import the freetype module.
pygame.init()
screen = pygame.display.set_mode((800, 600))
GAME_FONT = pygame.freetype.Font("your_font.ttf", 24)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((255,255,255))
# You can use `render` and then blit the text surface ...
text_surface, rect = GAME_FONT.render("Hello World!", (0, 0, 0))
screen.blit(text_surface, (40, 250))
# or just `render_to` the target surface.
GAME_FONT.render_to(screen, (40, 350), "Hello World!", (0, 0, 0))
pygame.display.flip()
pygame.quit()
Maybe you just copied tree of folder and trying to add lowest one.
SVN
|_
|
subfolder1
|
subfolder2 (here you get an error)
in that case you have to commit directory on the upper level.
All the answers are good. The java8+ have these patterns for parsing and formatting timezone: V
, z
, O
, X
, x
, Z
.
Here's they are, for parsing, according to rules from the documentation :
Symbol Meaning Presentation Examples
------ ------- ------------ -------
V time-zone ID zone-id America/Los_Angeles; Z; -08:30
z time-zone name zone-name Pacific Standard Time; PST
O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;
X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15;
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Z zone-offset offset-Z +0000; -0800; -08:00;
But how about formatting?
Here's a sample for a date (assuming ZonedDateTime
) that show these patters behavior for different formatting patters:
// The helper function:
static void printInPattern(ZonedDateTime dt, String pattern) {
System.out.println(pattern + ": " + dt.format(DateTimeFormatter.ofPattern(pattern)));
}
// The date:
String strDate = "2020-11-03 16:40:44 America/Los_Angeles";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss zzzz");
ZonedDateTime dt = ZonedDateTime.parse(strDate, format);
// 2020-11-03T16:40:44-08:00[America/Los_Angeles]
// Rules:
// printInPattern(dt, "V"); // exception!
printInPattern(dt, "VV"); // America/Los_Angeles
// printInPattern(dt, "VVV"); // exception!
// printInPattern(dt, "VVVV"); // exception!
printInPattern(dt, "z"); // PST
printInPattern(dt, "zz"); // PST
printInPattern(dt, "zzz"); // PST
printInPattern(dt, "zzzz"); // Pacific Standard Time
printInPattern(dt, "O"); // GMT-8
// printInPattern(dt, "OO"); // exception!
// printInPattern(dt, "OO0"); // exception!
printInPattern(dt, "OOOO"); // GMT-08:00
printInPattern(dt, "X"); // -08
printInPattern(dt, "XX"); // -0800
printInPattern(dt, "XXX"); // -08:00
printInPattern(dt, "XXXX"); // -0800
printInPattern(dt, "XXXXX"); // -08:00
printInPattern(dt, "x"); // -08
printInPattern(dt, "xx"); // -0800
printInPattern(dt, "xxx"); // -08:00
printInPattern(dt, "xxxx"); // -0800
printInPattern(dt, "xxxxx"); // -08:00
printInPattern(dt, "Z"); // -0800
printInPattern(dt, "ZZ"); // -0800
printInPattern(dt, "ZZZ"); // -0800
printInPattern(dt, "ZZZZ"); // GMT-08:00
printInPattern(dt, "ZZZZZ"); // -08:00
In the case of positive offset the +
sign character is used everywhere(where there is -
now) and never omitted.
This well works for new java.time
types. If you're about to use these for java.util.Date
or java.util.Calendar
- not all going to work as those types are broken(and so marked as deprecated, please don't use them)
If you are developing a .Net Core WebApi or WebSite you dont not need to install newtownsoft.json to perform json serialization/deserealization
Just make sure that your controller method returns a JsonResult
and call return Json(<objectoToSerialize>);
like this example
namespace WebApi.Controllers
{
[Produces("application/json")]
[Route("api/Accounts")]
public class AccountsController : Controller
{
// GET: api/Transaction
[HttpGet]
public JsonResult Get()
{
List<Account> lstAccounts;
lstAccounts = AccountsFacade.GetAll();
return Json(lstAccounts);
}
}
}
If you are developing a .Net Framework WebApi or WebSite you need to use NuGet to download and install the newtonsoft json
package
"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".
namespace WebApi.Controllers
{
[Produces("application/json")]
[Route("api/Accounts")]
public class AccountsController : Controller
{
// GET: api/Transaction
[HttpGet]
public JsonResult Get()
{
List<Account> lstAccounts;
lstAccounts = AccountsFacade.GetAll();
//This line is different !!
return new JsonConvert.SerializeObject(lstAccounts);
}
}
}
More details can be found here - https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-2.1
You can use is_null() function.
http://php.net/manual/en/function.is-null.php : in the comments :
mdufour at gmail dot com 20-Aug-2008 04:31 Testing for a NULL field/column returned by a mySQL query.
Say you want to check if field/column “foo” from a given row of the table “bar” when > returned by a mySQL query is null. You just use the “is_null()” function:
[connect…]
$qResult=mysql_query("Select foo from bar;");
while ($qValues=mysql_fetch_assoc($qResult))
if (is_null($qValues["foo"]))
echo "No foo data!";
else
echo "Foo data=".$qValues["foo"];
[…]
When there's no better choice (as suggested by others), then man socat can help:
(sleep 5; echo PASSWORD; sleep 5; echo ls; sleep 1) |
socat - EXEC:'ssh -l user server',pty,setsid,ctty
EXEC’utes an ssh session to server. Uses a pty for communication
between socat and ssh, makes it ssh’s controlling tty (ctty),
and makes this pty the owner of a new process group (setsid), so
ssh accepts the password from socat.
All of the pty,setsid,ctty complexity is necessary and, while you might not need to sleep as long, you will need to sleep. The echo=0 option is worth a look too, as is passing the remote command on ssh's command line.
The color of the buttons and other text can also be changed via theme:
values-21/styles.xml
<style name="AppTheme" parent="...">
...
<item name="android:timePickerDialogTheme">@style/AlertDialogCustom</item>
<item name="android:datePickerDialogTheme">@style/AlertDialogCustom</item>
<item name="android:alertDialogTheme">@style/AlertDialogCustom</item>
</style>
<style name="AlertDialogCustom" parent="android:Theme.Material.Light.Dialog.Alert">
<item name="android:colorPrimary">#00397F</item>
<item name="android:colorAccent">#0AAEEF</item>
</style>
The result:
I spoke too soon! Rebuild brought the errors back into play...
I found this works - right click in Solution Explorer and exclude it from the project. Click Show all files, right click and now include it in the project again. Now undo pending changes...
For some reason this sorted it out for me and was relatively painless!
defaultMember
already is an alias - it doesn't need to be the name of the exported function/thing. Just do
import alias from 'my-module';
Alternatively you can do
import {default as alias} from 'my-module';
but that's rather esoteric.
my solution is to check what ratio (height or width) need to apply depending of the pdf orientation and image size. note: set margin to 0 if no margin is required.
const imgData = canvas.toDataURL("image/jpeg");
const pdf = new jsPDF({
orientation: "portrait", // landscape or portrait
unit: "mm",
format: "a4",
});
const imgProps = pdf.getImageProperties(imgData);
const margin = 0.1;
const pdfWidth = pdf.internal.pageSize.width * (1 - margin);
const pdfHeight = pdf.internal.pageSize.height * (1 - margin);
const x = pdf.internal.pageSize.width * (margin / 2);
const y = pdf.internal.pageSize.height * (margin / 2);
const widthRatio = pdfWidth / imgProps.width;
const heightRatio = pdfHeight / imgProps.height;
const ratio = Math.min(widthRatio, heightRatio);
const w = imgProps.width * ratio;
const h = imgProps.height * ratio;
pdf.addImage(imgData, "JPEG", x, y, w, h);
If you are using large table and want to access of 10 percent of the data then run this following command: SELECT TOP 10 PERCENT * FROM Table1 ORDER BY NEWID();
You are mixing the 2 different CASE
syntaxes inappropriately.
Use this style (Searched)
CASE
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Or this style (Simple)
CASE u.nnmu
WHEN '0' THEN mu.naziv_mesta
WHEN '1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Not This (Simple but with boolean search predicates)
CASE u.nnmu
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
In MySQL this will end up testing whether u.nnmu
is equal to the value of the boolean expression u.nnmu ='0'
itself. Regardless of whether u.nnmu
is 1
or 0
the result of the case expression itself will be 1
For example if nmu = '0'
then (nnmu ='0'
) evaluates as true
(1) and (nnmu ='1'
) evaluates as false
(0). Substituting these into the case expression gives
SELECT CASE '0'
WHEN 1 THEN '0'
WHEN 0 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
if nmu = '1'
then (nnmu ='0'
) evaluates as false
(0) and (nnmu ='1'
) evaluates as true
(1). Substituting these into the case expression gives
SELECT CASE '1'
WHEN 0 THEN '0'
WHEN 1 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
CSS Flexbox was designed to simplify creating these types of layouts.
html {
height: 100%;
}
body {
height: 100%;
display: flex;
}
.Content {
flex-grow: 1;
}
.Sidebar {
width: 290px;
flex-shrink: 0;
}
_x000D_
<div class="Content" style="background:#bed">Content</div>
<div class="Sidebar" style="background:#8cc">Sidebar</div>
_x000D_
<script type="text/javascript">
$(document).ready(function(e) {
$(".mqimg").mouseover(function()
{
$("#imgprev").animate({height: "250px",width: "70%",left: "15%"},100).html("<img src='"+$(this).attr('src')+"' width='100%' height='100%' />");
})
$(".mqimg").mouseout(function()
{
$("#imgprev").animate({height: "0px",width: "0%",left: "50%"},100);
})
});
</script>
<style>
.mqimg{ cursor:pointer;}
</style>
<div style="position:relative; width:100%; height:1px; text-align:center;">`enter code here`
<div id="imgprev" style="position:absolute; display:block; box-shadow:2px 5px 10px #333; width:70%; height:0px; background:#999; left:15%; bottom:15px; "></div>
<img class='mqimg' src='spppimages/1.jpg' height='100px' />
<img class='mqimg' src='spppimages/2.jpg' height='100px' />
<img class='mqimg' src='spppimages/3.jpg' height='100px' />
<img class='mqimg' src='spppimages/4.jpg' height='100px' />
<img class='mqimg' src='spppimages/5.jpg' height='100px' />
you can also used findOrFail()
method here it's good to used
if the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these method not give a 500 error..
ModelName::findOrFail($id, ['firstName', 'lastName']);
First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate
$('.swipeRight').click(function()
{
$('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});
$('.swipeLeft').click(function()
{
$('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});
The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.
The xmlhttp request method is not valid for the files on local disk because the browser security does not allow us to do so.But we can override the browser security by creating a shortcut->right click->properties In target "... browser location path.exe" append --allow-file-access-from-files.This is tested on chrome,however care should be taken that all browser windows should be closed and the code should be run from the browser opened via this shortcut.
In Visual Studio 2008, CTRL+E+W.
Everybody is using at least Java 7 now, right? Here is the answer to the original problem:
String myString = getFruitString();
switch (myString) {
case "apple":
method1();
break;
case "carrot":
method2();
break;
case "mango":
method3();
break;
case "orange":
method4();
break;
}
Notes
String.equals
.if
-else
statements (as in cHao's answer).If you have a dinamically added link to some container or the body:
var newLink= $("<a></a>", {
"id": "approve-ctrl",
"href": "#approve",
"class": "status-ctrl",
"data-attributes": "DATA"
}).html("Its ok").appendTo(document.body);
you can take its raw javascript element and add an event listener to it, like the click:
newLink.get(0).addEventListener("click", doActionFunction);
No matter how many times you add this new link instance you can use it as if you where using a jquery click
function.
function doActionFunction(e) {
e.preventDefault();
e.stopPropagation();
alert($(this).html());
}
So you will receive a message saying
Its ok
It has better performance than other alternatives.
Extra: You could gain better performance avoiding jquery and using plain javascript. If you are using IE up to version 8 you should use this polyfill to use the method addEventListener
if (typeof Element.prototype.addEventListener === 'undefined') {
Element.prototype.addEventListener = function (e, callback) {
e = 'on' + e;
return this.attachEvent(e, callback);
};
}
String
is present in package java.lang
which is imported by default in all java programs.
Use fnmatch
:
import fnmatch
lst = ['this','is','just','a','test']
filtered = fnmatch.filter(lst, 'th?s')
If you want to allow _
as a wildcard, just replace all underscores with '?'
(for one character) or *
(for multiple characters).
If you want your users to use even more powerful filtering options, consider allowing them to use regular expressions.
Among my colleagues, the meaning (or perhaps more accurately - the use) of the term "foo" has been to serve as a placeholder to represent an example for a name. Examples include, but not limited to, yourVariableName, yourObjectName, or yourColumnName.
Today, I avoid using "foo" and prefer using this type of named substitution for a couple of reasons.
You can do this with .htaccess:
php_value upload_max_filesize 20M
php_value post_max_size 20M
You can use .gitignore in the top level to ignore all directories in the project with the same name. For example:
Debug/
Release/
This should update immediately so it's visible when you do git status. Ensure that these directories are not already added to git, as that will override the ignores.
Using analytic function row_number:
WITH CTE (col1, col2, dupcnt)
AS
(
SELECT col1, col2,
ROW_NUMBER() OVER (PARTITION BY col1, col2 ORDER BY col1) AS dupcnt
FROM Youtable
)
DELETE
FROM CTE
WHERE dupcnt > 1
GO
public void showHideFragment(final Fragment fragment){
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in,
android.R.animator.fade_out);
if (fragment.isHidden()) {
ft.show(fragment);
Log.d("hidden","Show");
} else {
ft.hide(fragment);
Log.d("Shown","Hide");
}
ft.commit();
}
Actually, all the other answers have flaws. The most reliable way is:
IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
Detailed Explanation:
Using "%1"=="-b"
will flat out crash if passing argument with spaces and quotes. This is the least reliable method.
IF "%1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
C:\> run.bat "a b"
b""=="-b" was unexpected at this time.
Using [%1]==[-b]
is better because it will not crash with spaces and quotes, but it will not match if the argument is surrounded by quotes.
IF [%1]==[-b] (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
C:\> run.bat "-b"
(does not match, and jumps to UNKNOWN instead of SPECIFIC)
Using "%~1"=="-b"
is the most reliable. %~1
will strip off surrounding quotes if they exist. So it works with and without quotes, and also with no args.
IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
C:\> run.bat
C:\> run.bat -b
C:\> run.bat "-b"
C:\> run.bat "a b"
(all of the above tests work correctly)
To avoid the form submition, just use required
attr in the input fields.
<input type="text" required>
Or, after submit
When the form is submited, you can use str.trim() to remove white spaces form start and end of an string. I did a submit function to show you:
submitFunction(formData){
if(!formData.foo){
// launch an alert to say the user the field cannot be empty
return false;
}
else
{
formData.foo = formData.foo.trim(); // removes white
// do your logic here
return true;
}
}
Rails 4.0.0 will look image defined with image-url
in same directory structure with your css file.
For example, if your css in assets/stylesheets/main.css.scss
, image-url('logo.png')
becomes url(/assets/logo.png)
.
If you move your css file to assets/stylesheets/cpanel/main.css.scss
, image-url('logo.png')
becomes /assets/cpanel/logo.png
.
If you want to use image directly under assets/images directory, you can use asset-url('logo.png')
Previous versions of Angular (pre 1.0 RC) allowed you to use this interchangeably with the $scope method, but this is no longer the case. Inside of methods defined on the scope this and $scope are interchangeable (angular sets this to $scope), but not otherwise inside your controller constructor.
To bring back this behaviour (does anyone know why was it changed?) you can add:
return angular.extend($scope, this);
at the end of your controller function (provided that $scope was injected to this controller function).
This has a nice effect of having access to parent scope via controller object that you can get in child with require: '^myParentDirective'
While you are switching, switch to PDO instead of mysqli, It helps you write database agnositc code and have better features for prepared statements.
Bindparam for PDO: http://se.php.net/manual/en/pdostatement.bindparam.php
$sth = $dbh->prepare("SELECT * FROM tablename WHERE field1 = :value1 && field2 = :value2");
$sth->bindParam(':value1', 'foo');
$sth->bindParam(':value2', 'bar');
$sth->execute();
or:
$sth = $dbh->prepare("SELECT * FROM tablename WHERE field1 = ? && field2 = ?");
$sth->bindParam(1, 'foo');
$sth->bindParam(2, 'bar');
$sth->execute();
or execute with the parameters as an array:
$sth = $dbh->prepare("SELECT * FROM tablename WHERE field1 = :value1 && field2 = :value2");
$sth->execute(array(':value1' => 'foo' , ':value2' => 'bar'));
It will be easier for you if you would like your application to be able to run on different databases in the future.
I also think you should invest some time in using some of the classes from Zend Framwework whilst working with PDO. Check out their Zend_Db and more specifically [Zend_Db_Factory][2]. You do not have to use all of the framework or convert your application to the MVC pattern, but using the framework and reading up on it is time well spent.
char a[2]
defines an array of char
's. a
is a pointer to the memory at the beginning of the array and using ==
won't actually compare the contents of a
with 'ab'
because they aren't actually the same types, 'ab'
is integer type. Also 'ab'
should be "ab"
otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.
Something that might be illustrative is looking at the typeid
of 'ab'
:
#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
int some_int =5;
std::cout << typeid('ab').name() << std::endl;
std::cout << typeid(some_int).name() << std::endl;
return 0;
}
on my system this returns:
i
i
showing that 'ab'
is actually evaluated as an int.
If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator ==
overloaded and will do a comparison check when called this way.
If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:
#include <iostream>
#include <string>
using namespace std;
int main(){
string a;
cout<<"enter ab ";
cin>>a;
if(a=="ab"){
cout<<"correct";
}
return 0;
}
This one is due to:
if(a=='ab')
, here, a
is const char*
type (ie : array of char)
'ab'
is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.
Since char
is a primitive type inherited from C, no operator ==
is defined.
the good code should be:
if(strcmp(a,"ab")==0)
, then you'll compare a const char*
to another const char*
using strcmp
.
You should give the container an id and use that in your custom css file (which should be linked after the bootstrap css):
#container {
box-shadow: values
}
If you are not sharing develop branch with anybody, then I would just rebase it every time master updated, that way you will not have merge commits all over your history once you will merge develop back into master. Workflow in this case would be as follows:
> git clone git://<remote_repo_path>/ <local_repo>
> cd <local_repo>
> git checkout -b develop
....do a lot of work on develop
....do all the commits
> git pull origin master
> git rebase master develop
Above steps will ensure that your develop branch will be always on top of the latest changes from the master branch. Once you are done with develop branch and it's rebased to the latest changes on master you can just merge it back:
> git checkout -b master
> git merge develop
> git branch -d develop
May be this will help, I'd prefer pure JS wherever possible, it improves the performance drastically as you won't have lots of JQuery function calls.
var obj = [];
var elems = $("input[class=email]");
for (i = 0; i < elems.length; i += 1) {
var id = this.getAttribute('title');
var email = this.value;
tmp = {
'title': id,
'email': email
};
obj.push(tmp);
}
Code:
if [[ -e $1 && ! -e $2 ]]; then
mkdir --parents --verbose -- "$(dirname -- "$2")"
fi
mv --verbose -- "$1" "$2"
Example:
arguments: "d1" "d2/sub"
mkdir: created directory 'd2'
renamed 'd1' -> 'd2/sub'
Since the existing answers were written, Xcode's interface has been updated and they're no longer correct (notably the Click on Window, Organiser // Expand the Teams section step). Now the instructions for importing an existing certificate are as follows:
To export selected certificates
- Choose Xcode > Preferences.
- Click Accounts at the top of the window.
- Select the team you want to view, and click View Details.
- Control-click the certificate you want to export in the Signing Identities table and choose Export from the pop-up menu.
- Enter a filename in the Save As field and a password in both the Password and Verify fields. The file is encrypted and password protected.
- Click Save. The file is saved to the location you specified with a .p12 extension.
Source (Apple's documentation)
To import it, I found that Xcode's let-me-help-you menu didn't recognise the .p12 file. Instead, I simply imported it manually into Keychain, then Xcode built and archived without complaining.
@OP, you can use for loops to capture the return status of your program, if it outputs something other than numbers
At CMD
prompt:
>ver
Microsoft Windows [Version 10.0.18362.476]
>dir \\.\pipe\\
As pointed out by Ryan above, the command you need is
GRANT ALL ON *.* to user@'%' IDENTIFIED BY 'password';
However, note that the documentation indicates that in order for this to work, another user account from localhost
must be created for the same user; otherwise, the anonymous account created automatically by mysql_install_db
takes precedence because it has a more specific host column.
In other words; in order for user user
to be able to connect from any server; 2 accounts need to be created as follows:
GRANT ALL ON *.* to user@localhost IDENTIFIED BY 'password';
GRANT ALL ON *.* to user@'%' IDENTIFIED BY 'password';
Read the full documentation here.
And here's the relevant piece for reference:
After connecting to the server as root, you can add new accounts. The following statements use GRANT to set up four new accounts:
mysql> CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost'
-> WITH GRANT OPTION;
mysql> CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%'
-> WITH GRANT OPTION;
mysql> CREATE USER 'admin'@'localhost';
mysql> GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
mysql> CREATE USER 'dummy'@'localhost';
The accounts created by these statements have the following properties:
Two of the accounts have a user name of monty and a password of some_pass. Both accounts are superuser accounts with full privileges to do anything. The 'monty'@'localhost' account can be used only when connecting from the local host. The 'monty'@'%' account uses the '%' wildcard for the host part, so it can be used to connect from any host.
It is necessary to have both accounts for monty to be able to connect from anywhere as monty. Without the localhost account, the anonymous-user account for localhost that is created by mysql_install_db would take precedence when monty connects from the local host. As a result, monty would be treated as an anonymous user. The reason for this is that the anonymous-user account has a more specific Host column value than the 'monty'@'%' account and thus comes earlier in the user table sort order. (user table sorting is discussed in Section 6.2.4, “Access Control, Stage 1: Connection Verification”.)
It depends on what sender address you are talking about. The sender address visble in the recipients mailprogramm is extracted from the "From:" Header. which can probably easily be set from your program.
If you are talking about the SMTP envelope sender address, you can pass the -f argument to the sendmail binary. Depending on the server configuration you may not be allowed to do that with the apache user.
from the sendmail manpage :
-f <address>
This option sets the address of the envelope sender of a
locally-generated message (also known as the return path).
The option can normally be used only by a trusted user, but
untrusted_set_sender can be set to allow untrusted users to
use it. [...]
I did something like this. I passed "fragmentType" and created two ViewHolders
and on basis of this, i classified my Layouts accordingly in a single adapter that can have different Layouts
and LayoutManagers
private Context mContext;
protected IOnLoyaltyCardCategoriesItemClicked mListener;
private String fragmentType;
private View view;
public LoyaltyCardsCategoriesRecyclerViewAdapter(Context context, IOnLoyaltyCardCategoriesItemClicked itemListener, String fragmentType) {
this.mContext = context;
this.mListener = itemListener;
this.fragmentType = fragmentType;
}
public class LoyaltyCardCategoriesFragmentViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView lc_categories_iv;
private TextView lc_categories_name_tv;
private int pos;
public LoyaltyCardCategoriesFragmentViewHolder(View v) {
super(v);
view.setOnClickListener(this);
lc_categories_iv = (ImageView) v.findViewById(R.id.lc_categories_iv);
lc_categories_name_tv = (TextView) v.findViewById(R.id.lc_categories_name_tv);
}
public void setData(int pos) {
this.pos = pos;
lc_categories_iv.setImageResource(R.mipmap.ic_launcher);
lc_categories_name_tv.setText("Loyalty Card Categories");
}
@Override
public void onClick(View view) {
if (mListener != null) {
mListener.onLoyaltyCardCategoriesItemClicked(pos);
}
}
}
public class MyLoyaltyCardsFragmentTagViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageButton lc_categories_btn;
private int pos;
public MyLoyaltyCardsFragmentTagViewHolder(View v) {
super(v);
lc_categories_btn = (ImageButton) v.findViewById(R.id.lc_categories_btn);
lc_categories_btn.setOnClickListener(this);
}
public void setData(int pos) {
this.pos = pos;
lc_categories_btn.setImageResource(R.mipmap.ic_launcher);
}
@Override
public void onClick(View view) {
if (mListener != null) {
mListener.onLoyaltyCardCategoriesItemClicked(pos);
}
}
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (fragmentType.equalsIgnoreCase(Constants.LoyaltyCardCategoriesFragmentTag)) {
view = LayoutInflater.from(mContext).inflate(R.layout.loyalty_cards_categories_frag_item, parent, false);
return new LoyaltyCardCategoriesFragmentViewHolder(view);
} else if (fragmentType.equalsIgnoreCase(Constants.MyLoyaltyCardsFragmentTag)) {
view = LayoutInflater.from(mContext).inflate(R.layout.my_loyalty_cards_categories_frag_item, parent, false);
return new MyLoyaltyCardsFragmentTagViewHolder(view);
} else {
return null;
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if (fragmentType.equalsIgnoreCase(Constants.LoyaltyCardCategoriesFragmentTag)) {
((LoyaltyCardCategoriesFragmentViewHolder) holder).setData(position);
} else if (fragmentType.equalsIgnoreCase(Constants.MyLoyaltyCardsFragmentTag)) {
((MyLoyaltyCardsFragmentTagViewHolder) holder).setData(position);
}
}
@Override
public int getItemCount() {
return 7;
}
}
LOL, I'm just wondering why no one had idea about the PHP header function:
header("Refresh: 0"); // here 0 is in seconds
I use this, so user is not prompt to resubmit data if he refresh the page.
See Refresh a page using PHP for more details
You can just look for the value that corresponds with the key and then check if the input is equal to the key.
for key in PIX0:
NUM = input("Which standard has a resolution of %s " % PIX0[key])
if NUM == key:
Also, you will have to change the last line to fit in, so it will print the key instead of the value if you get the wrong answer.
print("I'm sorry but thats wrong. The correct answer was: %s." % key )
Also, I would recommend using str.format
for string formatting instead of the %
syntax.
Your full code should look like this (after adding in string formatting)
PIX0 = {"QVGA":"320x240", "VGA":"640x480", "SVGA":"800x600"}
for key in PIX0:
NUM = input("Which standard has a resolution of {}".format(PIX0[key]))
if NUM == key:
print ("Nice Job!")
count = count + 1
else:
print("I'm sorry but that's wrong. The correct answer was: {}.".format(key))
Percent encoding. Replace the hash with %23
.
Create a folder named images located in the path you are planning to place the php script you are about to create. Make sure it has write rights for everybody or the scripts won't work ( it won't be able to upload the files into the directory).
dt.AsEnumerable()
.GroupBy(r => new { Col1 = r["Col1"], Col2 = r["Col2"] })
.Select(g =>
{
var row = dt.NewRow();
row["PK"] = g.Min(r => r.Field<int>("PK"));
row["Col1"] = g.Key.Col1;
row["Col2"] = g.Key.Col2;
return row;
})
.CopyToDataTable();
If I understand your problem well you want the following things:
Unfortunately there is no ultimate solution for what you want, but there are some things by which you can make your life easier.
First you should decide one important thing: do you want to store for every version in your project repository a reference to the version of the media files? So for example if you have a project called example.com, do you need know which style.css it used 2 weeks ago, or the latest is always (or mostly) the best?
If you don't need to know that, the solution is easy:
In most of the cases, however, you want to know this versioning information. In this case you have two choices:
Store every project in one big repository. The advantage of this solution is that you will have only 1 copy of the media repository. The big disadvantage is that it is much harder to switch between project versions (if you checkout to a different version you will always modify ALL projects)
Use submodules (as explained in answer 1). This way you will store the media files in one repository, and the projects will contain only a reference to a specific media repo version. But this way you will normally have many local copies of the media repository, and you cannot easily modify a media file in all projects.
If I were you I would probably choose the first or third solution (symbolic links or submodules). If you choose to use submodules you can still do a lot of things to make your life easier:
Before committing you can rename the submodule directory and put a symlink to a common media directory. When you're ready to commit, you can remove the symlink and remove the submodule back, and then commit.
You can add one of your copy of the media repository as a remote repository to all of your projects.
You can add local directories as a remote this way:
cd /my/project2/media
git remote add project1 /my/project1/media
If you modify a file in /my/project1/media, you can commit it and pull it from /my/project2/media without pushing it to a remote server:
cd /my/project1/media
git commit -a -m "message"
cd /my/project2/media
git pull project1 master
You are free to remove these commits later (with git reset) because you haven't shared them with other users.
var list = [
{prop1:"abc",prop2:"qwe"},
{prop1:"bnmb",prop2:"yutu"},
{prop1:"zxvz",prop2:"qwrq"}
];
var findProp = p => {
var index = -1;
$.each(list, (i, o) => {
if(o.prop2 == p) {
index = i;
return false; // break
}
});
return index; // -1 == not found, else == index
}
The IFRAME
element may be a security risk if your site is embedded inside an IFRAME
on hostile site. Google "clickjacking" for more details. Note that it does not matter if you use <iframe>
or not. The only real protection from this attack is to add HTTP header X-Frame-Options: DENY
and hope that the browser knows its job.
In addition, IFRAME element may be a security risk if any page on your site contains an XSS vulnerability which can be exploited. In that case the attacker can expand the XSS attack to any page within the same domain that can be persuaded to load within an <iframe>
on the page with XSS vulnerability. This is because content from the same origin (same domain) is allowed to access the parent content DOM (practically execute JavaScript in the "host" document). The only real protection methods from this attack is to add HTTP header X-Frame-Options: DENY
and/or always correctly encode all user submitted data (that is, never have an XSS vulnerability on your site - easier said than done).
That's the technical side of the issue. In addition, there's the issue of user interface. If you teach your users to trust that URL bar is supposed to not change when they click links (e.g. your site uses a big iframe with all the actual content), then the users will not notice anything in the future either in case of actual security vulnerability. For example, you could have an XSS vulnerability within your site that allows the attacker to load content from hostile source within your iframe. Nobody could tell the difference because the URL bar still looks identical to previous behavior (never changes) and the content "looks" valid even though it's from hostile domain requesting user credentials.
If somebody claims that using an <iframe>
element on your site is dangerous and causes a security risk, he does not understand what <iframe>
element does, or he is speaking about possibility of <iframe>
related vulnerabilities in browsers. Security of <iframe src="...">
tag is equal to <img src="..."
or <a href="...">
as long there are no vulnerabilities in the browser. And if there's a suitable vulnerability, it might be possible to trigger it even without using <iframe>
, <img>
or <a>
element, so it's not worth considering for this issue.
However, be warned that content from <iframe>
can initiate top level navigation by default. That is, content within the <iframe>
is allowed to automatically open a link over current page location (the new location will be visible in the address bar). The only way to avoid that is to add sandbox
attribute without value allow-top-navigation
. For example, <iframe sandbox="allow-forms allow-scripts" ...>
. Unfortunately, sandbox also disables all plugins, always. For example, Youtube content cannot be sandboxed because Flash player is still required to view all Youtube content. No browser supports using plugins and disallowing top level navigation at the same time.
Note that X-Frame-Options: DENY
also protects from rendering performance side-channel attack that can read content cross-origin (also known as "Pixel perfect Timing Attacks").
On Mac: /Library/PostgreSQL/9.0/data/base
The directory can't be entered, but you can look at the content via: sudo du -hc data
The permgen space is the area of heap that holds all the reflective data of the virtual machine itself, such as class and method objects.
DevArt's OraDirect provider now supports entity framework. See http://devart.com/news/2008/directs475.html
Windows uses carriage return
+ line feed
for newline:
\r\n
Unix only uses Line feed
for newline:
\n
In conclusion, simply replace every occurence of \n
by \r\n
.
Both unix2dos
and dos2unix
are not by default available on Mac OSX.
Fortunately, you can simply use Perl
or sed
to do the job:
sed -e 's/$/\r/' inputfile > outputfile # UNIX to DOS (adding CRs)
sed -e 's/\r$//' inputfile > outputfile # DOS to UNIX (removing CRs)
perl -pe 's/\r\n|\n|\r/\r\n/g' inputfile > outputfile # Convert to DOS
perl -pe 's/\r\n|\n|\r/\n/g' inputfile > outputfile # Convert to UNIX
perl -pe 's/\r\n|\n|\r/\r/g' inputfile > outputfile # Convert to old Mac
Code snippet from:
http://en.wikipedia.org/wiki/Newline#Conversion_utilities
If it's in a class, you can use getattr:
class MyClass(object):
def install(self):
print "In install"
method_name = 'install' # set by the command line options
my_cls = MyClass()
method = None
try:
method = getattr(my_cls, method_name)
except AttributeError:
raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))
method()
or if it's a function:
def install():
print "In install"
method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
raise NotImplementedError("Method %s not implemented" % method_name)
method()
See http://jsfiddle.net/qP8DY/24/
You can add a class (such as "success-dialog" in my example) to div#success, either directly in your HTML, or in your JavaScript by adding to the dialogClass option, as I've done.
$('#success').dialog({
height: 50,
width: 350,
modal: true,
resizable: true,
dialogClass: 'no-close success-dialog'
});
Then just add the success-dialog class to your CSS rules as appropriate. To indicate an element with two (or more) classes applied to it, just write them all together, with no spaces in between. For example:
.ui-dialog.success-dialog {
font-family: Verdana,Arial,sans-serif;
font-size: .8em;
}
Blorgbeard had a great answer for SQL server. If you have a MySQL server like mine then the following will allow you to select the information from columns where the name is like some key phrase. You just have to substitute the table name, database name, and keyword.
SET @columnnames = (SELECT concat("`",GROUP_CONCAT(`COLUMN_NAME` SEPARATOR "`, `"),"`")
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='your_database'
AND `TABLE_NAME`='your_table'
AND COLUMN_NAME LIKE "%keyword%");
SET @burrito = CONCAT("SELECT ",@columnnames," FROM your_table");
PREPARE result FROM @burrito;
EXECUTE result;
^[+-]?(([1-9][0-9]*)?[0-9](\.[0-9]*)?|\.[0-9]+)$
should reflect what people usually think of as a well formed decimal number.
The digits before the decimal point can be either a single digit, in which case it can be from 0 to 9, or more than one digits, in which case it cannot start with a 0.
If there are any digits present before the decimal sign, then the decimal and the digits following it are optional. Otherwise, a decimal has to be present followed by at least one digit. Note that multiple trailing 0's are allowed after the decimal point.
grep -E '^[+-]?(([1-9][0-9]*)?[0-9](\.[0-9]*)?|\.[0-9]+)$'
correctly matches the following:
9
0
10
10.
0.
0.0
0.100
0.10
0.01
10.0
10.10
.0
.1
.00
.100
.001
as well as their signed equivalents, whereas it rejects the following:
.
00
01
00.0
01.3
and their signed equivalents, as well as the empty string.
Date in 24 hrs format
Output:14/02/2020 19:56:49 PM
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss aa");
dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
System.out.println("date is: "+dateFormat.format(date));
Date in 12 hrs format
Output:14/02/2020 07:57:11 PM
Date date = new Date();`enter code here`
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
System.out.println("date is: "+dateFormat.format(date));
Single quotes are used to indicate the beginning and end of a string in SQL. Double quotes generally aren't used in SQL, but that can vary from database to database.
Stick to using single quotes.
That's the primary use anyway. You can use single quotes for a column alias — where you want the column name you reference in your application code to be something other than what the column is actually called in the database. For example: PRODUCT.id
would be more readable as product_id
, so you use either of the following:
SELECT PRODUCT.id AS product_id
SELECT PRODUCT.id 'product_id'
Either works in Oracle, SQL Server, MySQL… but I know some have said that the TOAD IDE seems to give some grief when using the single quotes approach.
You do have to use single quotes when the column alias includes a space character, e.g., product id
, but it's not recommended practice for a column alias to be more than one word.
We can use the get_locale
function:
if (get_locale() == 'en_GB') {
// drink tea
}
You could do:
Color c = Color.FromArgb(red, green, blue); //red, green and blue are integer variables containing red, green and blue components
EDIT: The correct way to do this is in @LiviuT's answer!
You can always extend Angular's scope to allow you to remove such listeners like so:
//A little hack to add an $off() method to $scopes.
(function () {
var injector = angular.injector(['ng']),
rootScope = injector.get('$rootScope');
rootScope.constructor.prototype.$off = function(eventName, fn) {
if(this.$$listeners) {
var eventArr = this.$$listeners[eventName];
if(eventArr) {
for(var i = 0; i < eventArr.length; i++) {
if(eventArr[i] === fn) {
eventArr.splice(i, 1);
}
}
}
}
}
}());
And here's how it would work:
function myEvent() {
alert('test');
}
$scope.$on('test', myEvent);
$scope.$broadcast('test');
$scope.$off('test', myEvent);
$scope.$broadcast('test');
This solution remembers the scroll position
var currentscroll = 0;
$('input').bind('focus',function() {
currentscroll = $(window).scrollTop();
});
$('input').bind('blur',function() {
if(currentscroll != $(window).scrollTop()){
$(window).scrollTop(currentscroll);
}
});
use "Content-type: application/x-www-form-urlencoded" instead of "application/json"
First of all, you need to make sure you're producing the correct number of *
symbols. We need to produce 1, 3, 5 et cetera instead of 1, 2, 3. This can be fixed by modifying the counter variables:
for (int i=1; i<10; i += 2)
{
for (int j=0; j<i; j++)
{
System.out.print("*");
}
System.out.println("");
}
As you can see, this causes i
to start at 1
and increase by 2
at each step as long is it is smaller than 10
(i.e., 1
, 3
, 5
, 7
, 9
). This gives us the correct number of *
symbols. We then need to fix the indentation level per line. This can be done as follows:
for (int i=1; i<10; i += 2)
{
for (int k=0; k < (4 - i / 2); k++)
{
System.out.print(" ");
}
for (int j=0; j<i; j++)
{
System.out.print("*");
}
System.out.println("");
}
Before printing the *
symbols we print some spaces and the number of spaces varies depending on the line that we are on. That is what the for loop with the k
variable is for. We can see that k
iterates over the values 4
, 3
, 2
, 1
and 0
when ì
is 1
,3
, 5
, 7
and 9
. This is what we want because the higher in the triangle we are, the more spaces we need to place. The further we get down the triangle, we less spaces we need and the last line of the triangle does not even need spaces at all.
This is the only answer you got first when you search for default workspace, but any solution is not solved my problem, So I follow this step for a default workspace:
In Target:
D:\eclipse_path\eclipse.exe -clean -data D:\workspace_path\workspace
For using the same shortcuts and preference into this workspace, Export general --> preference from your working eclipse, it will generate one .epf file.
So, just import .epf file into your new workspace, and you are done.
CLOCK_REALTIME
represents the machine's best-guess as to the current wall-clock, time-of-day time. As Ignacio and MarkR say, this means that CLOCK_REALTIME
can jump forwards and backwards as the system time-of-day clock is changed, including by NTP.
CLOCK_MONOTONIC
represents the absolute elapsed wall-clock time since some arbitrary, fixed point in the past. It isn't affected by changes in the system time-of-day clock.
If you want to compute the elapsed time between two events observed on the one machine without an intervening reboot, CLOCK_MONOTONIC
is the best option.
Note that on Linux, CLOCK_MONOTONIC
does not measure time spent in suspend, although by the POSIX definition it should. You can use the Linux-specific CLOCK_BOOTTIME
for a monotonic clock that keeps running during suspend.
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);
Suppose STUDENTID contains some characters or numbers that you already know i.e. 'searchstring' then below query will work for you.
You could try this:
select * from STUDENTS where CHARINDEX('searchstring',STUDENTID)>0
I think this one is the fastest and easiest one.
After all the Jquery script tag's add
<script>jQuery.noConflict();</script>
to avoid the conflict between Prototype and Jquery.
Why not use the MAC address of your network card?
Instead of using XmlSerializer
you can use a System.Runtime.Serialization.DataContractSerializer
. This can serialize dictionaries and interfaces no sweat.
Here is a link to a full example, http://theburningmonk.com/2010/05/net-tips-xml-serialize-or-deserialize-dictionary-in-csharp/
Here's a simple function I just wrote which reads a .hdf5 file generated by the save_weights function in keras and returns a dict with layer names and weights:
def read_hdf5(path):
weights = {}
keys = []
with h5py.File(path, 'r') as f: # open file
f.visit(keys.append) # append all keys to list
for key in keys:
if ':' in key: # contains data if ':' in key
print(f[key].name)
weights[f[key].name] = f[key].value
return weights
https://gist.github.com/Attila94/fb917e03b04035f3737cc8860d9e9f9b.
Haven't tested it thoroughly but does the job for me.
In linux make sure getting all authority with:
sudo su
This worked for me:
git reset HEAD <filename>
We can convert Today's date in the format of 'JUN 12, 2020'.
String.valueOf(DateFormat.getDateInstance().format(new Date())));
Give this a try, works for me:
var today = new Date();
var yesterday = new Date(today.setDate(today.getDate() - 1)); `
This got me a date object back for yesterday
Following JavaScript function handles ', ", \b, \t, \n, \f or \r equivalent of php function addslashes().
function addslashes(string) {
return string.replace(/\\/g, '\\\\').
replace(/\u0008/g, '\\b').
replace(/\t/g, '\\t').
replace(/\n/g, '\\n').
replace(/\f/g, '\\f').
replace(/\r/g, '\\r').
replace(/'/g, '\\\'').
replace(/"/g, '\\"');
}
keyCodes are different from the ASCII values. For a complete keyCode reference, see http://unixpapa.com/js/key.html
For example, Numpad numbers have keyCodes 96 - 105, which corresponds to the beginning of lowercase alphabet in ASCII. This could lead to problems in validating numeric input.
Using List.tabulate
, like this,
List.tabulate(3)( x => 2*x )
res: List(0, 2, 4)
List.tabulate(3)( _ => Math.random )
res: List(0.935455779102479, 0.6004888906328091, 0.3425278797788426)
List.tabulate(3)( _ => (Math.random*10).toInt )
res: List(8, 0, 7)
Morgan should not be used to log in the way you're describing. Morgan was built to do logging in the way that servers like Apache and Nginx log to the error_log or access_log. For reference, this is how you use morgan:
var express = require('express'),
app = express(),
morgan = require('morgan'); // Require morgan before use
// You can set morgan to log differently depending on your environment
if (app.get('env') == 'production') {
app.use(morgan('common', { skip: function(req, res) { return res.statusCode < 400 }, stream: __dirname + '/../morgan.log' }));
} else {
app.use(morgan('dev'));
}
Note the production line where you see morgan called with an options hash {skip: ..., stream: __dirname + '/../morgan.log'}
The stream
property of that object determines where the logger outputs. By default it's STDOUT (your console, just like you want) but it'll only log request data. It isn't going to do what console.log()
does.
If you want to inspect things on the fly use the built in util
library:
var util = require('util');
console.log(util.inspect(anyObject)); // Will give you more details than console.log
So the answer to your question is that you're asking the wrong question. But if you still want to use Morgan for logging requests, there you go.
Try this library, it supports shadow, there is minSdkVersion=7
and also supports android:elevation
attribute for API-21
implicitly.
Original post is here.
For completeness, write_csv()
from the readr
package is faster and never writes row names
# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")
If you need to write big data out, use fwrite()
from the data.table
package. It's much faster than both write.csv
and write_csv
# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")
Below is a benchmark that Edouard published on his site
microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
write_csv(data, "readr_file.csv"),
fwrite(data, "datatable_file.csv"),
times = 10, unit = "s")
## Unit: seconds
## expr min lq mean median uq max neval
## write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311 10
## write_csv(data, "readr_file.csv") 3.6742610 3.7999409 3.8572456 3.8690681 3.8991995 4.0637453 10
## fwrite(data, "datatable_file.csv") 0.3976728 0.4014872 0.4097876 0.4061506 0.4159007 0.4355469 10
Easiest solution is to create the column using the correct data type: DATE
For example:
Create table:
create table test_date (mydate date);
Insert row:
insert into test_date values (to_date('01-01-2011','dd-mm-yyyy'));
To get the month and year, do as follows:
select to_char(mydate, 'MM-YYYY') from test_date;
Your result will be as follows: 01-2011
Another cool function to use is "EXTRACT"
select extract(year from mydate) from test_date;
This will return: 2011
Try the following -
var FullUrl = Request.Url.AbsolutePath.ToString();
var ID = FullUrl.Split('/').Last();
This worked for me in angular >= 6.x versions:
this.router.events
.subscribe((event) => {
if (event instanceof NavigationStart) {
window.localStorage.setItem('previousUrl', this.router.url);
}
});
Unfortunately there is no hung state for a process. Now hung can be deadlock. This is block state. The threads in the process are blocked. The other things could be live lock where the process is running but doing the same thing again and again. This process is in running state. So as you can see there is no definite hung state. As suggested you can use the top command to see if the process is using 100% CPU or lot of memory.
You can make a directory "fonts" in a root of your project and put your fonts (sans_serif.ttf) file there. Then you can make something like this:
fonts_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'fonts')
font = ImageFont.truetype(os.path.join(fonts_path, 'sans_serif.ttf'), 24)
Hopefully this will help you visualize a Stack, and how it works.
Empty Stack:
| |
| |
| |
-------
After Pushing A
, you get:
| |
| |
| A |
-------
After Pushing B
, you get:
| |
| B |
| A |
-------
After Popping, you get:
| |
| |
| A |
-------
After Pushing C
, you get:
| |
| C |
| A |
-------
After Popping, you get:
| |
| |
| A |
-------
After Popping, you get:
| |
| |
| |
-------
@Steve Farthing's answer is absolutely right.
But if you rotate more than 4 times then the image will get cropped from both the side. For that you need to do like this.
$("#clockwise").click(function(){
angleInDegrees+=90 % 360;
drawRotated(angleInDegrees);
if(angleInDegrees == 360){ // add this lines
angleInDegrees = 0
}
});
Then you will get the desired result. Thanks. Hope this will help someone :)
Install & Add Material to Angular Projects
There is an automatic/easy way of adding Material to Angular Projects. Use the Angular CLI's install schematic to set up your Angular Material project by running the following command:
ng add @angular/material
The ng add command will additionally perform the following configurations:
You're done! Angular Material is now configured to be used in your application.
Read more about this here
You can use following example for building SQL statement.
DECLARE @sqlCommand varchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City'
SET @city = '''London'''
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = ' + @city
EXEC (@sqlCommand)
With using this approach you can ensure that the data values being passed into the query are the correct datatypes and avoind use of more quotes.
DECLARE @sqlCommand nvarchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City'
SET @city = 'London'
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city
You may also want to check your $PYTHONPATH
. I had changed mine in ~/.bashrc
in order to get another package to work.
To check your path:
echo $PYTHONPATH
To change your path (I use nano but you could edit another way)
nano ~/.bashrc
Look for the line with export PYTHONPATH
...
After making changes, don't forget to
source ~/.bashrc
Use the built-in function round()
:
In [23]: round(66.66666666666,4)
Out[23]: 66.6667
In [24]: round(1.29578293,6)
Out[24]: 1.295783
help on round()
:
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number. Precision may be negative.