Hi For jQuery You can only use like this
Use async and type="text/javascript" only
Depending on your use of Google Analytics data, if you want basic information (such as visits, UI interactions) you might be able to not include analytics.js at all, yet still collect data in GA.
One option may be to instead use the measurement protocol in a cached script. Google Analytics: Measurement Protocol Overview
When you set the transport method explicitly to image, you can see how GA constructs its own image beacons.
ga('set', 'transport', 'image');
https://www.google-analytics.com/r/collect
?v={protocol-version}
&tid={tracking-id}
&cid={client-id}
&t={hit-type}
&dl={location}
You could create your own GET or POST requests with the required payload.
However, if you require a greater level of detail it probably won't be worth your effort.
To gzip up your font files as well!
add "x-font/otf x-font/ttf x-font/eot"
as in:
AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml x-font/otf x-font/ttf x-font/eot
OK, after making a lot of test, here my concluson:
When you perform:
window.open('www.yourdomain.tld','_blank');
window.open('www.yourdomain.tld','myWindow');
or whatever you put in the destination field, this will change nothing: the new page will be opened in a new tab (so depend on user preference)
If you want the page to be opened in a new "real" window, you must put extra parameter. Like:
window.open('www.yourdomain.tld', 'mywindow','location=1,status=1,scrollbars=1, resizable=1, directories=1, toolbar=1, titlebar=1');
After testing, it seems the extra parameter you use, dont' really matter: this is not the fact you put "this parameter" or "this other one" which create the new "real window" but the fact there is new parameter(s).
But something is confused and may explain a lot of wrong answers:
This:
win1 = window.open('myurl1', 'ID_WIN');
win2 = window.open('myurl2', 'ID_WIN', 'location=1,status=1,scrollbars=1');
And this:
win2 = window.open('myurl2', 'ID_WIN', 'location=1,status=1,scrollbars=1');
win1 = window.open('myurl1', 'ID_WIN');
will NOT give the same result.
In the first case, as you first open a page without extra parameter, it will open in a new tab. And in this case, the second call will be also opened in this tab because of the name you give.
In second case, as your first call is made with extra parameter, the page will be opened in a new "real window". And in that case, even if the second call is made without the extra parameter, it will also be opened in this new "real window"... but same tab!
This mean the first call is important as it decided where to put the page.
For temporary internal files their are 2 options
1.
File file;
file = File.createTempFile(filename, null, this.getCacheDir());
2.
File file
file = new File(this.getCacheDir(), filename);
Both options adds files in the applications cache directory and thus can be cleared to make space as required but option 1 will add a random number on the end of the filename to keep files unique. It will also add a file extension which is .tmp
by default, but it can be set to anything via the use of the 2nd parameter. The use of the random number means despite specifying a filename it doesn't stay the same as the number is added along with the suffix/file extension (.tmp
by default) e.g you specify your filename as internal_file
and comes out as internal_file1456345.tmp
. Whereas you can specify the extension you can't specify the number that is added. You can however find the filename it generates via file.getName();
, but you would need to store it somewhere so you can use it whenever you wanted for example to delete or read the file. Therefore for this reason I prefer the 2nd option as the filename you specify is the filename that is created.
Never construct BigDecimals from floats or doubles. Construct them from ints or strings. floats and doubles loose precision.
This code works as expected (I just changed the type from double to String):
public static void main(String[] args) {
String doubleVal = "1.745";
String doubleVal1 = "0.745";
BigDecimal bdTest = new BigDecimal( doubleVal);
BigDecimal bdTest1 = new BigDecimal( doubleVal1 );
bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("bdTest:"+bdTest); //1.75
System.out.println("bdTest1:"+bdTest1);//0.75, no problem
}
sudo apt install php-xml
will work but the thing is it will download the plugin for the latest PHP version.
If your PHP version is not the latest, then you can add version in it:
# PHP 7.1
sudo apt install php7.1-xml
# PHP 7.2:
sudo apt install php7.2-xml
# PHP 7.3
sudo apt install php7.3-xml
# PHP 7.4
sudo apt install php7.4-xml
# PHP 8
sudo apt install php-xml
I have just tried to install that extension on my dev server.
First, make sure that the extension is correctly enabled. Your phpinfo()
output doesn't seem complete.
If it is indeed installed properly, your phpinfo()
should have a section that looks like this:
If you do not get that section in your phpinfo()
. Make sure that you are using the right version. There are both non-thread-safe and thread-safe versions of the extension.
Finally, check your extension_dir
setting. By default it's this: extension_dir = "ext"
, for most of the time it works fine, but if it doesn't try: extension_dir = "C:\PHP\ext"
.
===========================================================================
EDIT given new info:
You are using the wrong function. mssql_connect()
is part of the Mssql extension. You are using microsoft's extension, so use sqlsrv_connect()
, for the API for the microsoft driver, look at SQLSRV_Help.chm
which should be extracted to your ext
directory when you extracted the extension.
When learning a new concept I don't like using libraries or code dumps. I found a good description here and in the documentation of how to resize an image by pinching. This answer is a slightly modified summary. You will probably want to add more functionality later, but it will help you get started.
The ImageView
just uses the app logo since it is already available. You can replace it with any image you like, though.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@mipmap/ic_launcher"
android:layout_centerInParent="true"/>
</RelativeLayout>
We use a ScaleGestureDetector
on the activity to listen to touch events. When a scale (ie, pinch) gesture is detected, then the scale factor is used to resize the ImageView
.
public class MainActivity extends AppCompatActivity {
private ScaleGestureDetector mScaleGestureDetector;
private float mScaleFactor = 1.0f;
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize the view and the gesture detector
mImageView = findViewById(R.id.imageView);
mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());
}
// this redirects all touch events in the activity to the gesture detector
@Override
public boolean onTouchEvent(MotionEvent event) {
return mScaleGestureDetector.onTouchEvent(event);
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
// when a scale gesture is detected, use it to resize the image
@Override
public boolean onScale(ScaleGestureDetector scaleGestureDetector){
mScaleFactor *= scaleGestureDetector.getScaleFactor();
mImageView.setScaleX(mScaleFactor);
mImageView.setScaleY(mScaleFactor);
return true;
}
}
}
You can limit the size of the scaling with something like
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
Thanks again to Pinch-to-zoom with multi-touch gestures In Android
You will probably want to do other things like panning and scaling to some focus point. You can develop these things yourself, but if you would like to use a pre-made custom view, copy TouchImageView.java
into your project and use it like a normal ImageView
. It worked well for me and I only ran into one bug. I plan to further edit the code to remove the warning and the parts that I don't need. You can do the same.
You would want to use equals()
since they are objects, and utilize the built in ZERO
instance:
if (selectPrice.equals(BigDecimal.ZERO))
Note that .equals()
takes scale into account, so unless selectPrice is the same scale (0) as .ZERO
then this will return false.
To take scale out of the equation as it were:
if (selectPrice.compareTo(BigDecimal.ZERO) == 0)
I should note that for certain mathematical situations, 0.00 != 0
, which is why I imagine .equals()
takes the scale into account. 0.00
gives precision to the hundredths place, whereas 0
is not that precise. Depending on the situation you may want to stick with .equals()
.
The reason your attempt wasn't working, is because the two animations (fade-in and fade-out) were working against each other.
Right before an object became visible, it was still invisible and so the animation for fading-out would run. Then, the fraction of a second later when that same object had become visible, the fade-in animation would try to run, but the fade-out was still running. So they would work against each other and you would see nothing.
Eventually the object would become visible (most of the time), but it would take a while. And if you would scroll down by using the arrow-button at the button of the scrollbar, the animation would sort of work, because you would scroll using bigger increments, creating less scroll-events.
Enough explanation, the solution (JS, CSS, HTML):
$(window).on("load",function() {_x000D_
$(window).scroll(function() {_x000D_
var windowBottom = $(this).scrollTop() + $(this).innerHeight();_x000D_
$(".fade").each(function() {_x000D_
/* Check the location of each desired element */_x000D_
var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
_x000D_
/* If the element is completely within bounds of the window, fade it in */_x000D_
if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}_x000D_
} else { //object goes out of view (scrolling up)_x000D_
if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}_x000D_
}_x000D_
});_x000D_
}).scroll(); //invoke scroll-handler on page-load_x000D_
});
_x000D_
.fade {_x000D_
margin: 50px;_x000D_
padding: 50px;_x000D_
background-color: lightgreen;_x000D_
opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
<div class="fade">Fade In 01</div>_x000D_
<div class="fade">Fade In 02</div>_x000D_
<div class="fade">Fade In 03</div>_x000D_
<div class="fade">Fade In 04</div>_x000D_
<div class="fade">Fade In 05</div>_x000D_
<div class="fade">Fade In 06</div>_x000D_
<div class="fade">Fade In 07</div>_x000D_
<div class="fade">Fade In 08</div>_x000D_
<div class="fade">Fade In 09</div>_x000D_
<div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
if ($(this).css("opacity")==0) {...}
. This makes sure the object is only faded in when the opacity
is 0
. Same goes for fading out. And this prevents the fade-in and fade-out from working against each other, because now there's ever only one of the two running at one time on an object..animate()
to .fadeTo()
. It's jQuery's specialized function for opacity, a lot shorter to write and probably lighter than animate..position()
to .offset()
. This always calculates relative to the body, whereas position is relative to the parent. For your case I believe offset is the way to go.$(window).height()
to $(window).innerHeight()
. The latter is more reliable in my experience.$(window).scroll();
. Now you can give all desired objects on the page the .fade
class, and objects that should be invisible at page-load, will be faded out immediately.#container
from both HTML and CSS, because (at least for this answer) it isn't necessary. (I thought maybe you needed the height:2000px
because you used .position()
instead of .offset()
, otherwise I don't know. Feel free of course to leave it in your code.)If you want opacity values other than 0
and 1
, use the following code:
$(window).on("load",function() {_x000D_
function fade(pageLoad) {_x000D_
var windowBottom = $(window).scrollTop() + $(window).innerHeight();_x000D_
var min = 0.3;_x000D_
var max = 0.7;_x000D_
var threshold = 0.01;_x000D_
_x000D_
$(".fade").each(function() {_x000D_
/* Check the location of each desired element */_x000D_
var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
_x000D_
/* If the element is completely within bounds of the window, fade it in */_x000D_
if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
if ($(this).css("opacity")<=min+threshold || pageLoad) {$(this).fadeTo(500,max);}_x000D_
} else { //object goes out of view (scrolling up)_x000D_
if ($(this).css("opacity")>=max-threshold || pageLoad) {$(this).fadeTo(500,min);}_x000D_
}_x000D_
});_x000D_
} fade(true); //fade elements on page-load_x000D_
$(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
margin: 50px;_x000D_
padding: 50px;_x000D_
background-color: lightgreen;_x000D_
opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
<div class="fade">Fade In 01</div>_x000D_
<div class="fade">Fade In 02</div>_x000D_
<div class="fade">Fade In 03</div>_x000D_
<div class="fade">Fade In 04</div>_x000D_
<div class="fade">Fade In 05</div>_x000D_
<div class="fade">Fade In 06</div>_x000D_
<div class="fade">Fade In 07</div>_x000D_
<div class="fade">Fade In 08</div>_x000D_
<div class="fade">Fade In 09</div>_x000D_
<div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
threshold
and for min/max
at the start of the function. In the rest of the function these variables are referenced. This way, if you ever want to change the values again, you only have to do it in one place.|| pageLoad
to the if-clause. This was necessary to make sure all objects are faded to the correct opacity on page-load. pageLoad
is a boolean that is send along as an argument when fade()
is invoked.function fade() {...}
, in order to be able to send along the pageLoad
boolean when the scroll-handler is invoked.Explanation:
The reason the code in your fiddle didn't work, is because the actual opacity values are always a little off from the value you set it to. So if you set the opacity to 0.3
, the actual value (in this case) is 0.300000011920929
. That's just one of those little bugs you have to learn along the way by trail and error. That's why this if-clause won't work: if ($(this).css("opacity") == 0.3) {...}
.
I added a threshold, to take that difference into account: == 0.3
becomes <= 0.31
.
(I've set the threshold to 0.01
, this can be changed of course, just as long as the actual opacity will fall between the set value and this threshold.)
The operators are now changed from ==
to <=
and >=
.
If you want to fade the elements based on their visible percentage, use the following code:
$(window).on("load",function() {_x000D_
function fade(pageLoad) {_x000D_
var windowTop=$(window).scrollTop(), windowBottom=windowTop+$(window).innerHeight();_x000D_
var min=0.3, max=0.7, threshold=0.01;_x000D_
_x000D_
$(".fade").each(function() {_x000D_
/* Check the location of each desired element */_x000D_
var objectHeight=$(this).outerHeight(), objectTop=$(this).offset().top, objectBottom=$(this).offset().top+objectHeight;_x000D_
_x000D_
/* Fade element in/out based on its visible percentage */_x000D_
if (objectTop < windowTop) {_x000D_
if (objectBottom > windowTop) {$(this).fadeTo(0,min+((max-min)*((objectBottom-windowTop)/objectHeight)));}_x000D_
else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
} else if (objectBottom > windowBottom) {_x000D_
if (objectTop < windowBottom) {$(this).fadeTo(0,min+((max-min)*((windowBottom-objectTop)/objectHeight)));}_x000D_
else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
} else if ($(this).css("opacity")<=max-threshold || pageLoad) {$(this).fadeTo(0,max);}_x000D_
});_x000D_
} fade(true); //fade elements on page-load_x000D_
$(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
margin: 50px;_x000D_
padding: 50px;_x000D_
background-color: lightgreen;_x000D_
opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
<div class="fade">Fade In 01</div>_x000D_
<div class="fade">Fade In 02</div>_x000D_
<div class="fade">Fade In 03</div>_x000D_
<div class="fade">Fade In 04</div>_x000D_
<div class="fade">Fade In 05</div>_x000D_
<div class="fade">Fade In 06</div>_x000D_
<div class="fade">Fade In 07</div>_x000D_
<div class="fade">Fade In 08</div>_x000D_
<div class="fade">Fade In 09</div>_x000D_
<div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
I used Ctrl+Shift+F. Next, put a \n
in the search box and enable regular expressions box. Then in the find results, in the end of the screen are the number of files searched and lines of code found.
You can use [^\n\s]\r\n
to skip blank and space-only lines (credits to Zach in the comments).
Use of pseudo-element as suggested by Terry has one PRO and one CON:
Anyway is a great solution.
OTHER SOLUTIONS:
If you can accept compatibility since IE9 (IE8 does not have support for this), you can achieve desired result in other two possible ways:
outline
property combined with border
and a single inset box-shadow
box-shadow
combined with border
.Here a jsFiddle with Terry's modified code that shows, side by side, these other possible solutions. Main specific properties for each one are the following (others are shared in .double-border
class):
.left
{
outline: 4px solid #fff;
box-shadow:inset 0 0 0 4px #fff;
}
.right
{
box-shadow:0 0 0 4px #fff, inset 0 0 0 4px #fff;
}
LESS code:
You asked for possible advantages about using a pre-processor like LESS. I this specific case, utility is not so great, but anyway you could optimize something, declaring colors and border/ouline/shadow with @variable.
Here an example of my CSS code, declared in LESS (changing colors and border-width becomes very quick):
@double-border-size:4px;
@inset-border-color:#fff;
@content-color:#ccc;
.double-border
{
background-color: @content-color;
border: @double-border-size solid @content-color;
padding: 2em;
width: 16em;
height: 16em;
float:left;
margin-right:20px;
text-align:center;
}
.left
{
outline: @double-border-size solid @inset-border-color;
box-shadow:inset 0 0 0 @double-border-size @inset-border-color;
}
.right
{
box-shadow:0 0 0 @double-border-size @inset-border-color, inset 0 0 0 @double-border-size @inset-border-color;
}
One point not yet mentioned is that there are a few different types of assembly code. In the most basic form, all numbers used in instructions must be specified as constants. For example:
$1902: BD 37 14 : LDA $1437,X $1905: 85 03 : STA $03 $1907: 85 09 : STA $09 $1909: CA : DEX $190A: 10 : BPL $1902
The above bit of code, if stored at address $1900 in an Atari 2600 cartridge, will display a number of lines in different colors fetched from a table which starts at address $1437. On some tools, typing in an address, along with the rightmost part of the line above, would store to memory the values shown in the middle column, and start the next line with the following address. Typing code in that form was much more convenient than typing in hex, but one had to know the precise addresses of everything.
Most assemblers allow one to use symbolic addresses. The above code would be written more like:
rainbow_lp: lda ColorTbl,x sta WSYNC sta COLUBK dex bpl rainbow_lp
The assembler would automatically adjust the LDA instruction so it would refer to whatever address was mapped to the label ColorTbl. Using this style of assembler makes it much easier to write and edit code than would be possible if one had to hand-key and hand-maintain all addresses.
In your my.ini
, write this:
[mysqld]
sql_mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
depend on your version. Or:
[mysqld]
sql_mode = ""
or simply remove this: ONLY_FULL_GROUP_BY
I highly recommend reading the docs on the Intent.FLAG_ACTIVITY_CLEAR_TOP
flag. Using it will not necessarily go back all the way to the first (main
) activity. The flag will only remove all existing activities up to the activity class given in the Intent
. This is explained well in the docs:
For example, consider a task consisting of the activities: A, B, C, D.
If D calls startActivity() with an Intent that resolves to the component of
activity B, then C and D will be finished and B receive the given Intent,
resulting in the stack now being: A, B.
Note that the activity can set to be moved to the foreground (i.e., clearing all other activities on top of it), and then also being relaunched, or only get onNewIntent()
method called.
I suggest you to first try to understand Java 8 in the whole picture, most importantly in your case it will be streams, lambdas and method references.
You should never convert existing code to Java 8 code on a line-by-line basis, you should extract features and convert those.
What I identified in your first case is the following:
Let's see how we do that, we can do it with the following:
List<Player> playersOfTeam = players.stream()
.filter(player -> player.getTeam().equals(teamName))
.collect(Collectors.toList());
What you do here is:
Collection<Player>
, now you have a Stream<Player>
.Predicate<Player>
, mapping every player to the boolean true if it is wished to be kept.Collector
, here we can use one of the standard library collectors, which is Collectors.toList()
.This also incorporates two other points:
List<E>
over ArrayList<E>
.new ArrayList<>()
, you are using Java 8 after all.Now onto your second point:
You again want to convert something of legacy Java to Java 8 without looking at the bigger picture. This part has already been answered by @IanRoberts, though I think that you need to do players.stream().filter(...)...
over what he suggested.
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z"));
You can not directly send an email with a HTML form. You can however send the form to your web server and then generate the email with a server side program written in e.g. PHP.
The other solution is to create a link as you did with the "mailto:". This will open the local email program from the user. And he/she can then send the pre-populated email.
When you decided how you wanted to do it you can ask another (more specific) question on this site. (Or you can search for a solution somewhere on the internet.)
Here are the complete list of scripts required to get rid of this problem. (Make sure the file exists at the given file path)
<script src="@Url.Content("~/Scripts/jquery-1.8.2.js")" type="text/javascript">
</script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.24.js")" type="text/javascript">
</script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript">
</script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript">
</script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript">
</script>
and also include the below css link in _Layout.cshtml for a stylish popup.
<link rel="stylesheet" type="text/css" href="../../Content/themes/base/jquery-ui.css" />
On some level Chris Pietschmann is correct. SQL isn't Turing complete (at least without stored procedures) yet people will list that as a language, TeX is Turing complete but most people regard it as a markup language.
Having said that: if you are just applying for jobs, not arguing formal logic, I would just list them all as technologies. Things like .NET aren't languages but would probably be listed as well.
A working example: http://jsfiddle.net/0sgLbynd/
<table>
<tr>
<td>0</td>
<td class="ms-vb2">1</td>
<td class="ms-vb2">2</td>
<td class="ms-vb2">3</td>
<td class="ms-vb2">4</td>
<td class="ms-vb2">5</td>
<td class="ms-vb2">6</td>
</tr>
</table>
$(document).ready(function () {
//alert("sss");
$("td").each(function () {
//alert($(this).html());
$(this).html("aaaaaaa");
});
});
You can use get methods:
var fullDate = new Date();_x000D_
console.log(fullDate);_x000D_
var twoDigitMonth = fullDate.getMonth() + "";_x000D_
if (twoDigitMonth.length == 1)_x000D_
twoDigitMonth = "0" + twoDigitMonth;_x000D_
var twoDigitDate = fullDate.getDate() + "";_x000D_
if (twoDigitDate.length == 1)_x000D_
twoDigitDate = "0" + twoDigitDate;_x000D_
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);
_x000D_
If you have Windows 10 and VS2015, below you can see the Location of WSDL.exe
Path in your pc C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7 Tools
It's a bit confusing - I believe you will need to grant yourself readWrite to query a database. A user with dbadmin or useradmin can admin the database (including granting yourself additional rights) but cannot perform queries or write data.
so grant yourself readWrite and you should be fine -
http://docs.mongodb.org/manual/reference/built-in-roles/#readWrite
For a python -c
oriented solution, and provided you use Bash shell, yes you can have a simple one-line syntax like in this example:
Suppose you would like to do something like this (very similar to your sample, including except: pass
instruction):
python -c "from __future__ import print_function\ntry: import numpy; print( numpy.get_include(), end='\n' )\nexcept:pass\n" OUTPUT_VARIABLE __numpy_path
This will NOT work and produce this Error:
File "<string>", line 1
from __future__ import print_function\ntry: import numpy; print( numpy.get_include(), end='\n' )\nexcept:pass\n
^
SyntaxError: unexpected character after line continuation character `
This is because the competition between Bash and Python Interpretation of \n
escape sequences. To solve the problem one can use the $'string'
Bash syntax to force \n
Bash interpretation BEFORE the Python one. To make the example more challenging I added a typical Python end=..\n..
specification in the Python print call: at the end you will be able to get BOTH \n
interpretations from bash and Python working together, each on its piece of text of concern. So that finally the proper solution is like this :
python -c $'from __future__ import print_function\ntry:\n import numpy;\n print( numpy.get_include(), end="\\n" )\n print( "Hello" )\nexcept:pass\n' OUTPUT_VARIABLE __numpy_path
That leads to the proper clean output with no error:
/Softs/anaconda/lib/python3.7/site-packages/numpy/core/include
Hello
Note: this should work as well with exec
oriented solutions, because the problem is still the same (Bash and Python interpreters competition).
Note2: one could workaround the problem by replacing some \n
by some ;
but it will not work anytime (depending on Python constructs), while my solution allows to always "one-line" any piece of classic multi-line Python program.
Note3: of course, when one-lining, one has always to take care of Python spaces and indentation, because in fact we are not strictly "one-lining" here, BUT doing a proper mixed-management of \n
escape sequence between bash and Python. This is how we can deal with any piece of classic multi-line Python program. The solution sample illustrates this as well.
Sending an HTTP POST request on iOS (Objective c):
-(NSString *)postexample{
// SEND POST
NSString *url = [NSString stringWithFormat:@"URL"];
NSString *post = [NSString stringWithFormat:@"param=value"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:url]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;
//RESPONDE DATA
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
if([responseCode statusCode] != 200){
NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]);
return nil;
}
//SEE RESPONSE DATA
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Response" message:[[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
}
In your Topic
model you're allowing for more than one element to have the same topic
field. You have created two with the same one already.
topic=models.TextField(verbose_name='Thema')
Now when trying to add a new learningObjective
you seem to want to add it to only one Topic
that matches what you're sending on the form. Since there's more than one with the same topic
field get
is finding 2, hence the exception.
You can either add the learningObjective
to all Topics with that topic
field:
for t in topic.objects.filter(topic=request.POST['Thema']):
t.learningObjectivesTopic.add(neuesLernziel)
or restrict the Topic
model to have a unique topic
field and keep using get
, but that might not be what you want.
Probably you use Microsoft SQL Server which support Common Table Expressions (CTE) (see http://msdn.microsoft.com/en-us/library/ms190766.aspx) which are very friendly for query optimization. So I suggest you my favor construction:
WITH GetNumberOfPlans(Id,NumberOfPlans) AS (
SELECT tableA.Id, COUNT(tableC.Id)
FROM tableC
RIGHT OUTER JOIN tableA ON tableC.tableAId = tableA.Id
GROUP BY tableA.Id
),GetUserInformation(Id,Name,Owner,ImageUrl,
CompanyImageUrl,NumberOfUsers) AS (
SELECT tableA.Id, tableA.Name, tableB.Username AS Owner, tableB.ImageUrl,
tableB.CompanyImageUrl,COUNT(tableD.UserId),p.NumberOfPlans
FROM tableA
INNER JOIN tableB ON tableB.Id = tableA.Owner
RIGHT OUTER JOIN tableD ON tableD.tableAId = tableA.Id
GROUP BY tableA.Name, tableB.Username, tableB.ImageUrl, tableB.CompanyImageUrl
)
SELECT u.Id,u.Name,u.Owner,u.ImageUrl,u.CompanyImageUrl
,u.NumberOfUsers,p.NumberOfPlans
FROM GetUserInformation AS u
INNER JOIN GetNumberOfPlans AS p ON p.Id=u.Id
After some experiences with CTE you will be find very easy to write code using CTE and you will be happy with the performance.
Well I tried a lot of things but none seemed to be working. But the following process did it right, I can now use composer
command in terminal. I'm in mac OS 10.12.1
$ curl -sS https://getcomposer.org/installer | php
$ chmod +x composer.phar
$ mv composer.phar /usr/local/bin/composer
$ composer
Or
help(list.append)
if you're generally poking around.
rt.jar
contains all of the compiled class files for the base Java Runtime environment. You should not be messing with this jar file.
For MacOS it is called classes.jar
and located under /System/Library/Frameworks/<java_version>/Classes
. Same not messing with it rule applies there as well :).
http://javahowto.blogspot.com/2006/05/what-does-rtjar-stand-for-in.html
Here is how I fixed this issue:
Open the nuget package manager console and install the below nuget packages:
Install-Package WebMatrix.Data
Install-Package Microsoft.AspNet.WebHelpers
Update-Package
Clean the solution, rebuild and my asp.net web app starts working!
This answer will not work correctly with root paths containing equal signs (=
). (Thanks @dbenham for pointing that out.)
EDITED: Fixed the issue with paths containing !
, again spotted by @dbenham (thanks!).
Alternatively to calculating the length and extracting substrings you could use a different approach:
store the root path;
clear the root path from the file paths.
Here's my attempt (which worked for me):
@ECHO OFF
SETLOCAL DisableDelayedExpansion
SET "r=%__CD__%"
FOR /R . %%F IN (*) DO (
SET "p=%%F"
SETLOCAL EnableDelayedExpansion
ECHO(!p:%r%=!
ENDLOCAL
)
The r
variable is assigned with the current directory. Unless the current directory is the root directory of a disk drive, it will not end with (No longer the case, as the script now reads the \
, which we amend by appending the character.__CD__
variable, whose value always ends with \
(thanks @jeb!), instead of CD
.)
In the loop, we store the current file path into a variable. Then we output the variable, stripping the root path along the way.
Check this answer: https://stackoverflow.com/a/7346598/1764509
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
What I believe you're looking for is a way to work with arrays as object values:
var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into
var data = {
sampleTime: '1450632410296',
data: '76.36731:3.4651554:0.5665419'
};
var data2 = {
sampleTime: '1450632410296',
data: '78.15431:0.5247617:-0.20050584'
};
o[key].push(data);
o[key].push(data2);
This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify
:
JSON.stringify(o);
//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'
This was in response to your other question, that looks like it's been deleted....the point still stands.
Looks like a classic Unicode to ASCII issue. The trick would be to find where it's happening.
.NET works fine with Unicode, assuming it's told it's Unicode to begin with (or left at the default).
My guess is that your receiving app can't handle it. So, I'd probably use the ASCIIEncoder with an EncoderReplacementFallback with String.Empty:
using System.Text;
string inputString = GetInput();
var encoder = ASCIIEncoding.GetEncoder();
encoder.Fallback = new EncoderReplacementFallback(string.Empty);
byte[] bAsciiString = encoder.GetBytes(inputString);
// Do something with bytes...
// can write to a file as is
File.WriteAllBytes(FILE_NAME, bAsciiString);
// or turn back into a "clean" string
string cleanString = ASCIIEncoding.GetString(bAsciiString);
// since the offending bytes have been removed, can use default encoding as well
Assert.AreEqual(cleanString, Default.GetString(bAsciiString));
Of course, in the old days, we'd just loop though and remove any chars greater than 127...well, those of us in the US at least. ;)
Possible solution:
var tasks = dataList
.Select(data => Task.Factory.StartNew(arg => DoThreadStuff(data), TaskContinuationOptions.LongRunning | TaskContinuationOptions.PreferFairness))
.ToArray();
var timeout = TimeSpan.FromMinutes(1);
Task.WaitAll(tasks, timeout);
Assuming dataList is the list of items and each item needs to be processed in a separate thread.
For anyone want to replace your script.
update dbo.[TABLE_NAME] set COLUMN_NAME= replace(COLUMN_NAME, 'old_value', 'new_value') where COLUMN_NAME like %CONDITION%
This way you can Create NSArray, NSMutableArray.
NSArray keys =[NSArray arrayWithObjects:@"key1",@"key2",@"key3",nil];
NSArray objects =[NSArray arrayWithObjects:@"value1",@"value2",@"value3",nil];
use css3 flexbox with justify-content:center;
<div class="row">
<div class="col" style="background:red;">content1</div>
<div class="col" style="">content2</div>
</div>
.row {
display: flex; /* equal height of the children */
height:100px;
border:1px solid red;
width: 400px;
justify-content:center;
}
I'm a little late, and I'm not sure if this is what you're looking for, but I thought I'd add it just in case someone else finds it useful.
Suppose this is your file structure:
/BulutDepoProject
/bin
Main.exe
/FolderIcon
Folder.ico
Main.cs
You need to write your path relative to the Main.exe
file. So, you want to access Folder.ico
, in your Main.cs
you can use:
String path = "..\\FolderIcon\\Folder.ico"
That seemed to work for me!
For Swift 3 and 4, if you're willing to use IBInspectable
s, there's this:
@IBDesignable extension UIView {
@IBInspectable var borderColor:UIColor? {
set {
layer.borderColor = newValue!.cgColor
}
get {
if let color = layer.borderColor {
return UIColor(cgColor: color)
}
else {
return nil
}
}
}
@IBInspectable var borderWidth:CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
@IBInspectable var cornerRadius:CGFloat {
set {
layer.cornerRadius = newValue
clipsToBounds = newValue > 0
}
get {
return layer.cornerRadius
}
}
}
Use Application.GetSaveAsFilename()
in the same way that you used Application.GetOpenFilename()
In C++, now int and other data is stored using 2's compliment method. That means the range is:
-2147483648 to 2147483647
or -2^31 to 2^31-1
1 bit is reserved for 0 so positive value is one less than 2^(31)
you can try using this
System.Web.HttpContext.Current.Server.MapPath(path);
or use HostingEnvironment.MapPath
System.Web.Hosting.HostingEnvironment.MapPath(path);
Using HttpClient (Http's replacement) in Angular 4.3+, the entire mapping/casting process is made simpler/eliminated.
Using your CountryData class, you would define a service method like this:
getCountries() {
return this.httpClient.get<CountryData[]>('http://theUrl.com/all');
}
Then when you need it, define an array like this:
countries:CountryData[] = [];
and subscribe to it like this:
this.countryService.getCountries().subscribe(countries => this.countries = countries);
A complete setup answer is posted here also.
Terminal > su
> password
> vim /etc/vimrc
Click here and edit as in line number (13):
set nu
The correct, fully Pythonic way to read a file is the following:
with open(...) as f:
for line in f:
# Do something with 'line'
The with
statement handles opening and closing the file, including if an exception is raised in the inner block. The for line in f
treats the file object f
as an iterable, which automatically uses buffered I/O and memory management so you don't have to worry about large files.
There should be one -- and preferably only one -- obvious way to do it.
After searching the Web and trying many different ways, here's what I'd suggest for Java EE 6 authentication:
In my case, I had the users in the database. So I followed this blog post to create a JDBC Realm that could authenticate users based on username and MD5-hashed passwords in my database table:
http://blog.gamatam.com/2009/11/jdbc-realm-setup-with-glassfish-v3.html
Note: the post talks about a user and a group table in the database. I had a User class with a UserType enum attribute mapped via javax.persistence annotations to the database. I configured the realm with the same table for users and groups, using the userType column as the group column and it worked fine.
Still following the above blog post, configure your web.xml and sun-web.xml, but instead of using BASIC authentication, use FORM (actually, it doesn't matter which one you use, but I ended up using FORM). Use the standard HTML , not the JSF .
Then use BalusC's tip above on lazy initializing the user information from the database. He suggested doing it in a managed bean getting the principal from the faces context. I used, instead, a stateful session bean to store session information for each user, so I injected the session context:
@Resource
private SessionContext sessionContext;
With the principal, I can check the username and, using the EJB Entity Manager, get the User information from the database and store in my SessionInformation
EJB.
I also looked around for the best way to logout. The best one that I've found is using a Servlet:
@WebServlet(name = "LogoutServlet", urlPatterns = {"/logout"})
public class LogoutServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
// Destroys the session for this user.
if (session != null)
session.invalidate();
// Redirects back to the initial page.
response.sendRedirect(request.getContextPath());
}
}
Although my answer is really late considering the date of the question, I hope this helps other people that end up here from Google, just like I did.
Ciao,
Vítor Souza
The only thing that worked for me was changing
android:screenOrientation="portrait"
to
android:screenOrientation="unspecified"
in the manifest for all translucent activities.
That way it is compatible with all API versions since the translucent activity seems to inherit its orientation from the parent activity as of targetApi: 28
.
The style can be left as it is including <item name="android:windowIsTranslucent">true</item>
.
Use
s.length()
The following was once suggested in one of the answers, but its very inefficient
textMessage.getText().toString().length()
You can quote the entire path as in windows or you can escape the spaces like in:
/foo\ folder\ with\ space/foo.sh -help
Both ways will work!
I know this has been answered, but TypeScript introduced type guards: https://www.typescriptlang.org/docs/handbook/advanced-types.html#typeof-type-guards
If you have a type like: Object[] | string[]
and what to do something conditionally based on what type it is - you can use this type guarding:
function isStringArray(value: any): value is string[] {
if (value instanceof Array) {
value.forEach(function(item) { // maybe only check first value?
if (typeof item !== 'string') {
return false
}
})
return true
}
return false
}
function join<T>(value: string[] | T[]) {
if (isStringArray(value)) {
return value.join(',') // value is string[] here
} else {
return value.map((x) => x.toString()).join(',') // value is T[] here
}
}
There is an issue with an empty array being typed as string[]
, but that might be okay
You're missing a close paren in this line:
fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494
There are three ( and only two ).
I hope This will help you.
I looked around the internet for correct dimensions for these densities for square images, but couldn't find anything reliable.
If it's any consolation, referring to Veerababu Medisetti's answer I used these dimensions for SQUARES :)
xxxhdpi: 1280x1280 px
xxhdpi: 960x960 px
xhdpi: 640x640 px
hdpi: 480x480 px
mdpi: 320x320 px
ldpi: 240x240 px
I checked some of the methods for speed performance and find that there is no difference! The only difference is that using some methods you must carefully check dimension.
Timing:
|------------|----------------|-------------------|
| | shape (10000) | shape (1,10000) |
|------------|----------------|-------------------|
| np.concat | 0.18280 | 0.17960 |
|------------|----------------|-------------------|
| np.stack | 0.21501 | 0.16465 |
|------------|----------------|-------------------|
| np.vstack | 0.21501 | 0.17181 |
|------------|----------------|-------------------|
| np.array | 0.21656 | 0.16833 |
|------------|----------------|-------------------|
As you can see I tried 2 experiments - using np.random.rand(10000)
and np.random.rand(1, 10000)
And if we use 2d arrays than np.stack
and np.array
create additional dimension - result.shape is (1,10000,10000) and (10000,1,10000) so they need additional actions to avoid this.
Code:
from time import perf_counter
from tqdm import tqdm_notebook
import numpy as np
l = []
for i in tqdm_notebook(range(10000)):
new_np = np.random.rand(10000)
l.append(new_np)
start = perf_counter()
stack = np.stack(l, axis=0 )
print(f'np.stack: {perf_counter() - start:.5f}')
start = perf_counter()
vstack = np.vstack(l)
print(f'np.vstack: {perf_counter() - start:.5f}')
start = perf_counter()
wrap = np.array(l)
print(f'np.array: {perf_counter() - start:.5f}')
start = perf_counter()
l = [el.reshape(1,-1) for el in l]
conc = np.concatenate(l, axis=0 )
print(f'np.concatenate: {perf_counter() - start:.5f}')
I found a solution that works for hiding the grid lines in a Line chart.
Set the gridLines
color to be the same as the div's background color.
var options = {
scales: {
xAxes: [{
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}],
yAxes: [{
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}]
}
}
or use
var options = {
scales: {
xAxes: [{
gridLines: {
display:false
}
}],
yAxes: [{
gridLines: {
display:false
}
}]
}
}
try this:
files = ['file.jpeg','file.tar.gz','file.png','file.foo.bar','file.etc']
pen_ext = ['foo', 'tar', 'bar', 'etc']
for file in files: #1
if (file.split(".")[-2] in pen_ext): #2
ext = file.split(".")[-2]+"."+file.split(".")[-1]#3
else:
ext = file.split(".")[-1] #4
print (ext) #5
Try using Bulk Insert....
http://code.msdn.microsoft.com/LinqEntityDataReader
If you have a collection of entities e.g storeEntities you can store them using SqlBulkCopy as follows
var bulkCopy = new SqlBulkCopy(connection);
bulkCopy.DestinationTableName = TableName;
var dataReader = storeEntities.AsDataReader();
bulkCopy.WriteToServer(dataReader);
There is one gotcha with this code. Make sure that the Entity Framework definition for the entity correlates exactly with the table definition, ensure that the Entity's properties are in the same order in the Entity Model as the columns in the SQL Server table. Failure to do this will result in an exception.
It would help you... assume you have a form with "formname" form and a text box with "txt" name. then you can use following code to allow only aphanumeric values
var checkString = document.formname.txt.value;
if (checkString != "") {
if ( /[^A-Za-z\d]/.test(checkString)) {
alert("Please enter only letter and numeric characters");
document.formname.txt.focus();
return (false);
}
}
I suggest you to use provider
.
Provide is good when you want to configure it first before to use (against Service/Factory)
Something like:
.provider('Magazines', function() {
this.url = '/';
this.urlArray = '/';
this.organId = 'Default';
this.$get = function() {
var url = this.url;
var urlArray = this.urlArray;
var organId = this.organId;
return {
invoke: function() {
return ......
}
}
};
this.setUrl = function(url) {
this.url = url;
};
this.setUrlArray = function(urlArray) {
this.urlArray = urlArray;
};
this.setOrganId = function(organId) {
this.organId = organId;
};
});
.config(function(MagazinesProvider){
MagazinesProvider.setUrl('...');
MagazinesProvider.setUrlArray('...');
MagazinesProvider.setOrganId('...');
});
And now controller:
function MyCtrl($scope, Magazines) {
Magazines.invoke();
....
}
In my case, it was very a silly and funny mistake. I, accidentally without actually knowing, checked "Android Debug Bridge, Use libUsb backend". Actually it should stay unchecked..
In Mac Pro, Go Preferences - > Build, Execution,Deployment -> Debugger.
In your AndroidManifest.xml file
<application
android:name="ApplicationClass"
android:icon="@drawable/ic_launcher" <--------
android:label="@string/app_name"
android:theme="@style/AppTheme" >
Not really, in the standard. Some implementations have a nonstandard itoa() function, and you could look up Boost's lexical_cast, but if you stick to the standard it's pretty much a choice between stringstream and sprintf() (snprintf() if you've got it).
The following code implements a default context menu known from Windows
with copy, cut, paste, select all, undo and redo functions. It also works on Linux
and Mac OS X
:
import javax.swing.*;
import javax.swing.text.JTextComponent;
import javax.swing.undo.UndoManager;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class DefaultContextMenu extends JPopupMenu
{
private Clipboard clipboard;
private UndoManager undoManager;
private JMenuItem undo;
private JMenuItem redo;
private JMenuItem cut;
private JMenuItem copy;
private JMenuItem paste;
private JMenuItem delete;
private JMenuItem selectAll;
private JTextComponent textComponent;
public DefaultContextMenu()
{
undoManager = new UndoManager();
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
addPopupMenuItems();
}
private void addPopupMenuItems()
{
undo = new JMenuItem("Undo");
undo.setEnabled(false);
undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
undo.addActionListener(event -> undoManager.undo());
add(undo);
redo = new JMenuItem("Redo");
redo.setEnabled(false);
redo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
redo.addActionListener(event -> undoManager.redo());
add(redo);
add(new JSeparator());
cut = new JMenuItem("Cut");
cut.setEnabled(false);
cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
cut.addActionListener(event -> textComponent.cut());
add(cut);
copy = new JMenuItem("Copy");
copy.setEnabled(false);
copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
copy.addActionListener(event -> textComponent.copy());
add(copy);
paste = new JMenuItem("Paste");
paste.setEnabled(false);
paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
paste.addActionListener(event -> textComponent.paste());
add(paste);
delete = new JMenuItem("Delete");
delete.setEnabled(false);
delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
delete.addActionListener(event -> textComponent.replaceSelection(""));
add(delete);
add(new JSeparator());
selectAll = new JMenuItem("Select All");
selectAll.setEnabled(false);
selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
selectAll.addActionListener(event -> textComponent.selectAll());
add(selectAll);
}
private void addTo(JTextComponent textComponent)
{
textComponent.addKeyListener(new KeyAdapter()
{
@Override
public void keyPressed(KeyEvent pressedEvent)
{
if ((pressedEvent.getKeyCode() == KeyEvent.VK_Z)
&& ((pressedEvent.getModifiersEx() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0))
{
if (undoManager.canUndo())
{
undoManager.undo();
}
}
if ((pressedEvent.getKeyCode() == KeyEvent.VK_Y)
&& ((pressedEvent.getModifiersEx() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0))
{
if (undoManager.canRedo())
{
undoManager.redo();
}
}
}
});
textComponent.addMouseListener(new MouseAdapter()
{
@Override
public void mousePressed(MouseEvent releasedEvent)
{
handleContextMenu(releasedEvent);
}
@Override
public void mouseReleased(MouseEvent releasedEvent)
{
handleContextMenu(releasedEvent);
}
});
textComponent.getDocument().addUndoableEditListener(event -> undoManager.addEdit(event.getEdit()));
}
private void handleContextMenu(MouseEvent releasedEvent)
{
if (releasedEvent.getButton() == MouseEvent.BUTTON3)
{
processClick(releasedEvent);
}
}
private void processClick(MouseEvent event)
{
textComponent = (JTextComponent) event.getSource();
textComponent.requestFocus();
boolean enableUndo = undoManager.canUndo();
boolean enableRedo = undoManager.canRedo();
boolean enableCut = false;
boolean enableCopy = false;
boolean enablePaste = false;
boolean enableDelete = false;
boolean enableSelectAll = false;
String selectedText = textComponent.getSelectedText();
String text = textComponent.getText();
if (text != null)
{
if (text.length() > 0)
{
enableSelectAll = true;
}
}
if (selectedText != null)
{
if (selectedText.length() > 0)
{
enableCut = true;
enableCopy = true;
enableDelete = true;
}
}
if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor) && textComponent.isEnabled())
{
enablePaste = true;
}
undo.setEnabled(enableUndo);
redo.setEnabled(enableRedo);
cut.setEnabled(enableCut);
copy.setEnabled(enableCopy);
paste.setEnabled(enablePaste);
delete.setEnabled(enableDelete);
selectAll.setEnabled(enableSelectAll);
// Shows the popup menu
show(textComponent, event.getX(), event.getY());
}
public static void addDefaultContextMenu(JTextComponent component)
{
DefaultContextMenu defaultContextMenu = new DefaultContextMenu();
defaultContextMenu.addTo(component);
}
}
Usage:
JTextArea textArea = new JTextArea();
DefaultContextMenu.addDefaultContextMenu(textArea);
Now the textArea
will have a context menu when it is right-clicked on.
JSON makes a lot of sense for config files and other local usage because it's ubiquitous and because it's much simpler than XML.
If people have strong reasons against having comments in JSON when communicating data (whether valid or not), then possibly JSON could be split into two:
JSON-DOC will allow comments, and other minor differences might exist such as handling whitespace. Parsers can easily convert from one spec to the other.
With regards to the remark made by Douglas Crockford on this issues (referenced by @Artur Czajka)
Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser.
We're talking about a generic config file issue (cross language/platform), and he's answering with a JS specific utility!
Sure a JSON specific minify can be implemented in any language, but standardize this so it becomes ubiquitous across parsers in all languages and platforms so people stop wasting their time lacking the feature because they have good use-cases for it, looking the issue up in online forums, and getting people telling them it's a bad idea or suggesting it's easy to implement stripping comments out of text files.
The other issue is interoperability. Suppose you have a library or API or any kind of subsystem which has some config or data files associated with it. And this subsystem is to be accessed from different languages. Then do you go about telling people: by the way don't forget to strip out the comments from the JSON files before passing them to the parser!
The answer by Kleist certainly works, but there is an important caveat:
When you write a Makefile
manually, you might generate a SRCS
variable using a function to select all .cpp
and .h
files. If a source file is later added, re-running make
will include it.
However, CMake (with a command like file(GLOB ...)
) will explicitly generate a file list and place it in the auto-generated Makefile
. If you have a new source file, you will need to re-generate the Makefile
by re-running cmake
.
edit: No need to remove the Makefile.
To read a whole line from a file into a string, use std::getline
like so:
std::ifstream file("my_file");
std::string temp;
std::getline(file, temp);
You can do this in a loop to until the end of the file like so:
std::ifstream file("my_file");
std::string temp;
while(std::getline(file, temp)) {
//Do with temp
}
http://en.cppreference.com/w/cpp/string/basic_string/getline
Here's another version, and it's arguably a bit simpler.
multipetal <- function(df, n) {
varname <- paste("petal", n, sep=".")
df<-mutate_(df, .dots=setNames(paste0("Petal.Width*",n), varname))
df
}
for(i in 2:5) {
iris <- multipetal(df=iris, n=i)
}
> head(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species petal.2 petal.3 petal.4 petal.5
1 5.1 3.5 1.4 0.2 setosa 0.4 0.6 0.8 1
2 4.9 3.0 1.4 0.2 setosa 0.4 0.6 0.8 1
3 4.7 3.2 1.3 0.2 setosa 0.4 0.6 0.8 1
4 4.6 3.1 1.5 0.2 setosa 0.4 0.6 0.8 1
5 5.0 3.6 1.4 0.2 setosa 0.4 0.6 0.8 1
6 5.4 3.9 1.7 0.4 setosa 0.8 1.2 1.6 2
I installed EntityFramework 6.2
instead of 6.3
and it worked.
Perhaps it is the .NetCoreApp v2.1
or .NETFramework v4.6.1
.
In my case I had to set the file encoding without BOM.
I would like to run an automation test in different environments.
So I add this to command maven command:
spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=productionEnv1"
Here is the link where I found the solution: [1]https://github.com/spring-projects/spring-boot/issues/1095
I think my answer to my own question here is the simplest solution to what you are trying to do:
Select the cell where the first line of text from the file should be.
Use the Data
/Get External Data
/From File
dialog to select the text file to import.
Format the imported text as required.
In the Import Data
dialog that opens, click on Properties...
Uncheck the Prompt for file name on refresh
box.
Whenever the external file changes, click the Data
/Get External Data
/Refresh All
button.
Note: in your case, you should probably want to skip step #5.
var script = (<HTMLScriptElement[]><any>document.getElementsByName(id))[0];
In the Powershell, cd to the .exe file location. For example:
cd C:\Users\Administrators\Downloads
PS C:\Users\Administrators\Downloads> & '.\aaa.exe'
The installer pops up and follow the instruction on the screen.
The official statement "Due to this restriction, functions and parameters such as autoplay, playVideo(), loadVideoById() won't work in all mobile environments.
Reference: https://developers.google.com/youtube/iframe_api_reference
You can see all the privileges for all directories wit the following
SELECT *
from all_tab_privs
where table_name in
(select directory_name
from dba_directories);
The following gives you the sql statements to grant the privileges should you need to backup what you've done or something
select 'Grant '||privilege||' on directory '||table_schema||'.'||table_name||' to '||grantee
from all_tab_privs
where table_name in (select directory_name from dba_directories);
import os
def parent_filedir(n):
return parent_filedir_iter(n, os.path.dirname(__file__))
def parent_filedir_iter(n, path):
n = int(n)
if n <= 1:
return path
return parent_filedir_iter(n - 1, os.path.dirname(path))
test_dir = os.path.abspath(parent_filedir(2))
Tested xcode 8 stable version ; Need to use var request
variable with URLRequest()
With thats you can easily fix that (bug)
var request = URLRequest(url:myUrl!)
And
let task = URLSession.shared().dataTask(with: request as URLRequest) { }
Worked fine ! Thank you guys, i think help many people. !
n = int(input())
for i in range(1,n+1):
print(i,end='')
I do it like this, to launch the SendFreeTextActivity from a (custom) menu fragment that appears in multiple activities:
In the MenuFragment class:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu, container, false);
final Button sendFreeTextButton = (Button) view.findViewById(R.id.sendFreeTextButton);
sendFreeTextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "sendFreeTextButton clicked");
Intent intent = new Intent(getActivity(), SendFreeTextActivity.class);
MenuFragment.this.startActivity(intent);
}
});
...
At some point, I suppose you will add your programatically created LinearLayout to some root layout that you defined in .xml. This is just a suggestion of mine and probably one of many solutions, but it works: Simply set an ID for the programatically created layout, and add it to the root layout that you defined in .xml, and then use the set ID to add the Fragment.
It could look like this:
LinearLayout rowLayout = new LinearLayout();
rowLayout.setId(whateveryouwantasid);
// add rowLayout to the root layout somewhere here
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTransaction = fragMan.beginTransaction();
Fragment myFrag = new ImageFragment();
fragTransaction.add(rowLayout.getId(), myFrag , "fragment" + fragCount);
fragTransaction.commit();
Simply choose whatever Integer value you want for the ID:
rowLayout.setId(12345);
If you are using the above line of code not just once, it would probably be smart to figure out a way to create unique-IDs, in order to avoid duplicates.
UPDATE:
Here is the full code of how it should be done: (this code is tested and works) I am adding two Fragments to a LinearLayout with horizontal orientation, resulting in the Fragments being aligned next to each other. Please also be aware, that I used a fixed height and width of 200dp, so that one Fragment does not use the full screen as it would with "match_parent".
MainActivity.java:
public class MainActivity extends Activity {
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout fragContainer = (LinearLayout) findViewById(R.id.llFragmentContainer);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setId(12345);
getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 1"), "someTag1").commit();
getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 2"), "someTag2").commit();
fragContainer.addView(ll);
}
}
TestFragment.java:
public class TestFragment extends Fragment {
public static TestFragment newInstance(String text) {
TestFragment f = new TestFragment();
Bundle b = new Bundle();
b.putString("text", text);
f.setArguments(b);
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment, container, false);
((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));
return v;
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rlMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<LinearLayout
android:id="@+id/llFragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="19dp"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="200dp" >
<TextView
android:id="@+id/tvFragText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="" />
</RelativeLayout>
And this is the result of the above code: (the two Fragments are aligned next to each other)
As Mentioned by Everyone above, This is a Git Credential Manager
Issue.
Due to permissions, I could not modify my credentials or manipulate the credential manager.
I also could not afford to sit password in plain text on pc.
A workaround was deleting the remote branch in intellij
and re-adding the remote branch. This removes the stored credential and forces refreshing of the credential.
I found an article that explains why we need to do both Registry edit and use a tool such as UrlScan to set this up in IIS properly. I followed it on our servers and it works: http://blogs.msdn.com/b/varunm/archive/2013/04/23/remove-unwanted-http-response-headers.aspx. If you only use UrlScan but don't do the registry change, during the time you are stopping World Wide Publishing Service, your server will return server http response from the HTTP.sys file. Also, here are common pitfals of using UrlScan tool: http://msdn.microsoft.com/en-us/library/ff648552.aspx#ht_urlscan_008
This is in contrast to the previous answers, I had exactly the same error: "A collection with cascade=”all-delete-orphan” was no longer referenced...." when my setter function looked like this:
public void setTaxCalculationRules(Set<TaxCalculationRule> taxCalculationRules_) {
if( this.taxCalculationRules == null ) {
this.taxCalculationRules = taxCalculationRules_;
} else {
this.taxCalculationRules.retainAll(taxCalculationRules_);
this.taxCalculationRules.addAll(taxCalculationRules_);
}
}
And then it disappeared when I changed it to the simple version:
public void setTaxCalculationRules(Set<TaxCalculationRule> taxCalculationRules_) {
this.taxCalculationRules = taxCalculationRules_;
}
(hibernate versions - tried both 5.4.10 and 4.3.11. Spent several days trying all sorts of solutions before coming back to the simple assignment in the setter. Confused now as to why this so.)
I was missing modal-dialog
that's why my close modal wasn't working properly.
Just use a specific variable for that.
$ cat Makefile
all:
echo foo | gcc $(USER_DEFINES) -E -xc -
$ make USER_DEFINES="-Dfoo=one"
echo foo | gcc -Dfoo=one -E -xc -
...
one
$ make USER_DEFINES="-Dfoo=bar"
echo foo | gcc -Dfoo=bar -E -xc -
...
bar
$ make
echo foo | gcc -E -xc -
...
foo
Solved it. Turns out the column had a limited set of characters it would accept, changed it, and now the query works fine.
tl;dr
"Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.
Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).
Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.
Also, it seems likely the military FUBAR contributed to their popularity.
The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)
OK, so let's find some references.
STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:
On Foo-ism
The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")
As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.
It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!
The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:
By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.
...
It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.
Hopefully yours,
Indignant Mother of Five.
And The Tech in December 1938:
General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."
The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:
FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.
These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:
Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.
And from 1996's Jargon File 4.0.0:
Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."
A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):
Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!
Also 1964's MIT Voo Doo (PDF) references the TMRC usage:
Yes! I want to be an instant success and snow customers. Send me a degree in: ...
Foo Counters
Foo Jung
Let's find "foo", "bar" and "foobar" published in code examples.
So, Jargon File 4.4.7 says of "foobar":
Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.
The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:
Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.
Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z
I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:
car[((FOO . CROCK) . GLITCH)]
It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER
For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:
EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).
Some more recallations.
@Walter Mitty recalled on this site in 2008:
I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.
John V. Everett recalls in 1996:
When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.
Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.
It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.
Daniel P. B. Smith in 1998:
Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.
Robert Schuldenfrei in 1996:
The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?
Paul M. Wexelblat in 1992:
The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.
Bruce B. Reynolds in 1996:
On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...
Here's a straight IBM "BAR" from 1955.
Other early references:
1973 foo bar International Joint Council on Artificial Intelligence
1975 foo bar International Joint Council on Artificial Intelligence
I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.
Here are a some of even earlier F00s but I think they're coincidences/false positives:
You need to use
<?php bloginfo('template_directory'); ?>
It returns the directory of the current WordPress theme.
Now for example, if your theme has some image named example.jpg
inside some folder name subfolder
folder in the images
folder.
themes
|-> your theme
|-> images
|->subfolder
|-> examples.jpg
You access it like this
<img class="article-image" src="<?php bloginfo('template_directory'); ?> /images/subfolder/example.jpg" border="0" alt="">
Guys thank you for your help. I think all of this answers works. However i think my byte array contains raw bytes. That's why all of those solutions didnt work for my code.
However i found a solution. Maybe this solution helps other coders who have problem like mine.
static byte[] PadLines(byte[] bytes, int rows, int columns) {
int currentStride = columns; // 3
int newStride = columns; // 4
byte[] newBytes = new byte[newStride * rows];
for (int i = 0; i < rows; i++)
Buffer.BlockCopy(bytes, currentStride * i, newBytes, newStride * i, currentStride);
return newBytes;
}
int columns = imageWidth;
int rows = imageHeight;
int stride = columns;
byte[] newbytes = PadLines(imageData, rows, columns);
Bitmap im = new Bitmap(columns, rows, stride,
PixelFormat.Format8bppIndexed,
Marshal.UnsafeAddrOfPinnedArrayElement(newbytes, 0));
im.Save("C:\\Users\\musa\\Documents\\Hobby\\image21.bmp");
This solutions works for 8bit 256 bpp (Format8bppIndexed). If your image has another format you should change PixelFormat
.
And there is a problem with colors right now. As soon as i solved this one i will edit my answer for other users.
*PS = I am not sure about stride value but for 8bit it should be equal to columns.
And also this function Works for me.. This function copies 8 bit greyscale image into a 32bit layout.
public void SaveBitmap(string fileName, int width, int height, byte[] imageData)
{
byte[] data = new byte[width * height * 4];
int o = 0;
for (int i = 0; i < width * height; i++)
{
byte value = imageData[i];
data[o++] = value;
data[o++] = value;
data[o++] = value;
data[o++] = 0;
}
unsafe
{
fixed (byte* ptr = data)
{
using (Bitmap image = new Bitmap(width, height, width * 4,
PixelFormat.Format32bppRgb, new IntPtr(ptr)))
{
image.Save(Path.ChangeExtension(fileName, ".jpg"));
}
}
}
}
Just subscribe to the control's ToolTipTextNeeded event, and return e.TooltipText, much simpler.
Seems like you can't iterate through JSONArray
with a for each
. You can loop through your JSONArray
like this:
for (int i=0; i < arr.length(); i++) {
arr.getJSONObject(i);
}
You may want to know why this is happening. Together with the great explanation by that other guy, find a reference of Why does my shell script choke on whitespace or other special characters? written by Gilles in Unix & Linux:
Why do I need to write
"$foo"
? What happens without the quotes?
$foo
does not mean “take the value of the variablefoo
”. It means something much more complex:
- First, take the value of the variable.
- Field splitting: treat that value as a whitespace-separated list of fields, and build the resulting list. For example, if the variable contains
foo * bar ?
then the result of this step is the 3-element listfoo
,*
,bar
.- Filename generation: treat each field as a glob, i.e. as a wildcard pattern, and replace it by the list of file names that match this pattern. If the pattern doesn't match any files, it is left unmodified. In our example, this results in the list containing
foo
, following by the list of files in the current directory, and finallybar
. If the current directory is empty, the result isfoo
,*
,bar
.Note that the result is a list of strings. There are two contexts in shell syntax: list context and string context. Field splitting and filename generation only happen in list context, but that's most of the time. Double quotes delimit a string context: the whole double-quoted string is a single string, not to be split. (Exception:
"$@"
to expand to the list of positional parameters, e.g."$@"
is equivalent to"$1" "$2" "$3"
if there are three positional parameters. See What is the difference between $* and $@?)The same happens to command substitution with
$(foo)
or with`foo`
. On a side note, don't use`foo`
: its quoting rules are weird and non-portable, and all modern shells support$(foo)
which is absolutely equivalent except for having intuitive quoting rules.The output of arithmetic substitution also undergoes the same expansions, but that isn't normally a concern as it only contains non-expandable characters (assuming
IFS
doesn't contain digits or-
).See When is double-quoting necessary? for more details about the cases when you can leave out the quotes.
Unless you mean for all this rigmarole to happen, just remember to always use double quotes around variable and command substitutions. Do take care: leaving out the quotes can lead not just to errors but to security holes.
Run vim
from the terminal. For the basics, you're advised to run the command vimtutor
.
# On your terminal command line:
$ vim
If you have a specific file to edit, pass it as an argument.
$ vim yourfile.cpp
Likewise, launch the tutorial
$ vimtutor
In Python, Storing a bare python list as a numpy.array and then saving it out to file, then loading it back, and converting it back to a list takes some conversion tricks. The confusion is because python lists are not at all the same thing as numpy.arrays:
import numpy as np
foods = ['grape', 'cherry', 'mango']
filename = "./outfile.dat.npy"
np.save(filename, np.array(foods))
z = np.load(filename).tolist()
print("z is: " + str(z))
This prints:
z is: ['grape', 'cherry', 'mango']
Which is stored on disk as the filename: outfile.dat.npy
The important methods here are the tolist()
and np.array(...)
conversion functions.
For NighwatchJS use:
"ie" : {
"desiredCapabilities": {
"browserName": "internet explorer",
"javascriptEnabled": true,
"acceptSslCerts": true,
"allowBlockedContent": true,
"ignoreProtectedModeSettings": true
}
},
An inner class, by definition, cannot be static, so I am going to recast your question as "What is the difference between static and non-static nested classes?"
A non-static nested class has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.
You can use jquery numeric for numbers.
The current version does allow what you're looking for but someone has changed the code a little bit and it works:
HTML
<input class="numeric" type="text" />
Javascript
$(".numeric").numeric({ decimal : ".", negative : false, scale: 3 });
This is the whole source.
And I've prepared this fiddle so you can see how it works.
At last this post helps me on iOS: http://www.excellentwebworld.com/phonegap-open-a-link-in-safari-or-external-browser/.
Open "CDVwebviewDelegate.m" file and search "shouldStartLoadWithRequest", then add this code to the beginning of the function:
if([[NSString stringWithFormat:@"%@",request.URL] rangeOfString:@"file"].location== NSNotFound) { [[UIApplication sharedApplication] openURL:[request URL]]; return NO; }
While using navigator.app.loadUrl("http://google.com", {openExternal : true});
for Android is OK.
Via Cordova 3.3.0.
I am new to all this, but for me a simple alias worked:
alias node='env NODE_NO_READLINE=1 rlwrap nodejs'
at least for running things directly in bash and executing .js files.
If the width of the table won't change, you can set the width of the element (such as tbody) that contains the scrollbar > 100% (allowing extra space for the scrollbar) and set overflow-y to "overlay" (so that the scrollbar stays fixed, and won't shift the table left when it appears). Also set a fixed height for the element with the scrollbar, so the scrollbar will appear once the height is exceeded. Like so:
tbody {
height: 100px;
overflow-y: overlay;
width: 105%
}
Note: you will have to manually adjust the width % as the % of space the scrollbar takes up will be relative to your table width (ie: smaller width of table, more % required to fit the scrollbar, as it's size in pixels is constant)
A dynamic table example:
function addRow(tableID)_x000D_
{_x000D_
var table = document.getElementById(tableID);_x000D_
var rowCount = table.rows.length;_x000D_
var row = table.insertRow(rowCount);_x000D_
var colCount = table.rows[0].cells.length;_x000D_
_x000D_
for(var i=0; i<colCount; i++)_x000D_
{_x000D_
var newRow = row.insertCell(i);_x000D_
_x000D_
newRow.innerHTML = table.rows[0].cells[i].innerHTML;_x000D_
newRow.childNodes[0].value = "";_x000D_
}_x000D_
}_x000D_
_x000D_
function deleteRow(row)_x000D_
{_x000D_
var table = document.getElementById("data");_x000D_
var rowCount = table.rows.length;_x000D_
var rowIndex = row.parentNode.parentNode.rowIndex;_x000D_
_x000D_
document.getElementById("data").deleteRow(rowIndex);_x000D_
}
_x000D_
.scroll-table {_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.scroll-table tbody {_x000D_
display:block;_x000D_
overflow-y:overlay;_x000D_
height:60px;_x000D_
width: 105%_x000D_
}_x000D_
_x000D_
.scroll-table tbody td {_x000D_
color: #333;_x000D_
padding: 10px;_x000D_
text-shadow: 1px 1px 1px #fff;_x000D_
}_x000D_
_x000D_
.scroll-table thead tr {_x000D_
display:block;_x000D_
}_x000D_
_x000D_
.scroll-table td {_x000D_
border-top: thin solid; _x000D_
border-bottom: thin solid;_x000D_
}_x000D_
_x000D_
.scroll-table td:first-child {_x000D_
border-left: thin solid;_x000D_
}_x000D_
_x000D_
.scroll-table td:last-child {_x000D_
border-right: thin solid;_x000D_
}_x000D_
_x000D_
.scroll-table tr:first-child {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.delete_button {_x000D_
background-color: red;_x000D_
color: white;_x000D_
}_x000D_
_x000D_
.container {_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
body {_x000D_
text-align: center;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<link rel="stylesheet" href="test_table.css">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<h1>Dynamic Table</h1>_x000D_
<div class="container">_x000D_
_x000D_
<table id="data" class="scroll-table">_x000D_
<tbody>_x000D_
<tr>_x000D_
<td><input type="text" /></td>_x000D_
<td><input type="text" /></td>_x000D_
<td><input type="button" class="delete_button" value="X" onclick="deleteRow(this)"></td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
<input type="button" value="Add" onclick="addRow('data')" />_x000D_
_x000D_
</div>_x000D_
_x000D_
<script src="test_table.js"></script>_x000D_
</body>_x000D_
</html>
_x000D_
just give the surrounding <tr>
a custom class like:
<tr class="custom_centered">
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
and have the css only select <td>
s that are inside an <tr>
with your custom class.
tr.custom_centered td {
text-align: center;
}
like this you don't risk to override other tables or even override a bootstrap base class (like some of my predecessors suggested).
Another problem you are likely to face after setting up all your URLconf patterns is that the variable {{ MEDIA_URL }}
won't work in your templates. To fix this,in your settings.py, make sure you add
django.core.context_processors.media
in your TEMPLATE_CONTEXT_PROCESSORS
.
You should be able to remove it using
outline: none;
but keep in mind this is potentially bad for usability: It will be hard to tell whether an element is focused, which can suck when you walk through all a form's elements using the Tab key - you should reflect somehow when an element is focused.
If You try to connect by pysftp to "normal" FTP You have to set hostkey to None.
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection(host='****',username='****',password='***',port=22,cnopts=cnopts) as sftp:
print('DO SOMETHING')
I recently had the same problem and used the solution provided by Harry Joy. That solution only works with with zero-based enumaration though. I also wouldn't consider it save as it doesn't deal with indexes that are out of range.
The solution I ended up using might not be as simple but it's completely save and won't hurt the performance of your code even with big enums:
public enum Example {
UNKNOWN(0, "unknown"), ENUM1(1, "enum1"), ENUM2(2, "enum2"), ENUM3(3, "enum3");
private static HashMap<Integer, Example> enumById = new HashMap<>();
static {
Arrays.stream(values()).forEach(e -> enumById.put(e.getId(), e));
}
public static Example getById(int id) {
return enumById.getOrDefault(id, UNKNOWN);
}
private int id;
private String description;
private Example(int id, String description) {
this.id = id;
this.description= description;
}
public String getDescription() {
return description;
}
public int getId() {
return id;
}
}
If you are sure that you will never be out of range with your index and you don't want to use UNKNOWN
like I did above you can of course also do:
public static Example getById(int id) {
return enumById.get(id);
}
You're looking for the onclose event.
see: https://developer.mozilla.org/en/DOM/window.onclose
note that not all browsers support this (for example firefox 2)
DataTable formerSlidesData = new DataTable();
DformerSlidesData = searchAndFilterService.SearchSlideById(ids[i]);
if (formerSlidesData.Rows.Count > 0)
{
DataRow rowa = formerSlidesData.Rows[0];
cabinet = Convert.ToInt32(rowa["cabinet"]);
box = Convert.ToInt32(rowa["box"]);
drawer = Convert.ToInt32(rowa["drawer"]);
}
In case others may find this useful: I found that by adding an initial empty cell to my list of search terms, a zero value will be returned instead of error.
={INDEX(SearchTerms!$A$1:$A$38,MAX(IF(ISERROR(SEARCH(SearchTerms!$A$1:$A$38,SearchCell)),0,1)*((SearchTerms!$B$1:$B$38)+1)))}
NB: Column A has the search terms, B is the row number index.
Because python checks in the directories in sequential order starting at the first directory in sys.path
list, till it find the .py
file it was looking for.
Ideally, the current directory or the directory of the script is the first always the first element in the list, unless you modify it, like you did. From documentation -
As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.
So, most probably, you had a .py
file with the same name as the module you were trying to import from, in the current directory (where the script was being run from).
Also, a thing to note about ImportError
s , lets say the import error says -
ImportError: No module named main
- it doesn't mean the main.py
is overwritten, no if that was overwritten we would not be having issues trying to read it. Its some module above this that got overwritten with a .py
or some other file.
Example -
My directory structure looks like -
- test
- shared
- __init__.py
- phtest.py
- testmain.py
Now From testmain.py
, I call from shared import phtest
, it works fine.
Now lets say I introduce a shared.py in test
directory` , example -
- test
- shared
- __init__.py
- phtest.py
- testmain.py
- shared.py
Now when I try to do from shared import phtest
from testmain.py
, I will get the error -
ImportError: cannot import name 'phtest'
As you can see above, the file that is causing the issue is shared.py
, not phtest.py
.
i think you are doing every thing fine just remove ";" from the last of java_home variable. every thing will work fine.
You could do something like this
String[] myStrings = { "One", "Two", "Three" };
or in expression
functionCall(new String[] { "One", "Two", "Three" });
or
String myStrings[];
myStrings = new String[] { "One", "Two", "Three" };
function var_view($var)
{
ini_set("highlight.keyword", "#a50000; font-weight: bolder");
ini_set("highlight.string", "#5825b6; font-weight: lighter; ");
ob_start();
highlight_string("<?php\n" . var_export($var, true) . "?>");
$highlighted_output = ob_get_clean();
$highlighted_output = str_replace( ["<?php","?>"] , '', $highlighted_output );
echo $highlighted_output;
die();
}
None of the above solved this issue.
Someone had one project in my solution set to use x64 CPU in the build configuration. Changing it to Any CPU caused the build to use a new folder. I still don't know what process had (has) a lock on that file.
test.html
is will be helpful for how to use VLC WebAPI.
test.html
is located in the directory where VLC was installed.
e.g. C:\Program Files (x86)\VideoLAN\VLC\sdk\activex\test.html
The following code is a quote from the test.html
.
HTML:
<object classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" width="640" height="360" id="vlc" events="True">
<param name="MRL" value="" />
<param name="ShowDisplay" value="True" />
<param name="AutoLoop" value="False" />
<param name="AutoPlay" value="False" />
<param name="Volume" value="50" />
<param name="toolbar" value="true" />
<param name="StartTime" value="0" />
<EMBED pluginspage="http://www.videolan.org"
type="application/x-vlc-plugin"
version="VideoLAN.VLCPlugin.2"
width="640"
height="360"
toolbar="true"
loop="false"
text="Waiting for video"
name="vlc">
</EMBED>
</object>
JavaScript:
You can get vlc object from getVLC()
.
It works on IE 10 and Chrome.
function getVLC(name)
{
if (window.document[name])
{
return window.document[name];
}
if (navigator.appName.indexOf("Microsoft Internet")==-1)
{
if (document.embeds && document.embeds[name])
return document.embeds[name];
}
else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
{
return document.getElementById(name);
}
}
var vlc = getVLC("vlc");
// do something.
// e.g. vlc.playlist.play();
mkdir -p "$d" && cp file "$d"
(there's no such option for cp
).
Jokab's answer helped me a lot but in my case I could not push to github until I logged in my github account to my git bash so i ran the following commands
git config credential.helper store
then
git push http://github.com/[user name]/[repo name].git
After the second command a GUI window appeared, I provided my login credentials and it worked for me.
Receiver converted to snake case: http://rubydoc.info/gems/extlib/0.9.15/String#snake_case-instance_method
This is the Support library for DataMapper and Merb. (http://rubygems.org/gems/extlib)
def snake_case
return downcase if match(/\A[A-Z]+\z/)
gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').
gsub(/([a-z])([A-Z])/, '\1_\2').
downcase
end
"FooBar".snake_case #=> "foo_bar"
"HeadlineCNNNews".snake_case #=> "headline_cnn_news"
"CNN".snake_case #=> "cnn"
BigInteger is immutable, you need to do this,
BigInteger sum = test.add(new BigInteger(30));
System.out.println(sum);
Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:
open(filename, 'w').close()
Here the simple step that you can easily set phpMyAdmin Password.
C:\xampp\phpMyAdmin
and find config.inc.php
fileconfig.inc.php
file in Text editor like Notepad++.$cfg['Servers'][$a]['auth_type'] = 'config';
in config.inc.php
file.$cfg['Servers'][$a]['auth_type'] = 'config';
to $cfg['Servers'][$a]['auth_type'] = 'cookie';
in config.inc.php
file and Save the changes.localhost/phpmyadmin
. Enter username is root. password is null means empty. you don't type anything leave blank and press GO button.one more solution for this Automatically close or fade away the bootstrap alert message after 5 seconds:
This is the HTML code used to display the message:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
_x000D_
<div class="alert alert-danger">_x000D_
This is an example message..._x000D_
</div>_x000D_
_x000D_
_x000D_
<script type="text/javascript">_x000D_
_x000D_
$(document).ready(function () {_x000D_
_x000D_
window.setTimeout(function() {_x000D_
$(".alert").fadeTo(1000, 0).slideUp(1000, function(){_x000D_
$(this).remove(); _x000D_
});_x000D_
}, 5000);_x000D_
_x000D_
});_x000D_
</script>
_x000D_
JavaScript is a client-side language and your MySQL database is going to be running on a server.
So you have to rename your file to index.php
for example (.php is important) so you can use php code for that. It is not very difficult, but not directly possible with html.
(Somehow you can tell your server to let the html files behave like php files, but this is not the best solution.)
So after you renamed your file, go to the very top, before <html>
or <!DOCTYPE html>
and type:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
/*Creating variables*/
$name = $_POST["name"];
$address = $_POST["address"];
$age = $_POST["age"];
$dbhost = "localhost"; /*most of the time it's localhost*/
$username = "yourusername";
$password = "yourpassword";
$dbname = "mydatabase";
$mysql = mysqli_connect($dbhost, $username, $password, $dbname); //It connects
$query = "INSERT INTO yourtable (name,address,age) VALUES $name, $address, $age";
mysqli_query($mysql, $query);
}
?>
<!DOCTYPE html>
<html>
<head>.......
....
<form method="post">
<input name="name" type="text"/>
<input name="address" type="text"/>
<input name="age" type="text"/>
</form>
....
Try this code my friend...
#include<stdio.h>
int main(){
char *s1, *s2;
char str[10];
printf("type a string: ");
scanf("%s", str);
s1 = &str[0];
s2 = &str[2];
printf("%c\n", *s1); //use %c instead of %s and *s1 which is the content of position 1
printf("%c\n", *s2); //use %c instead of %s and *s3 which is the content of position 1
return 0;
}
You can try doing a replace of #region with \n, turning extended search mode on.
instead of using the URL::path() to check your current path location, you may want to consider the Route::currentRouteName() so just in case you update your path, you don't need to explore all your pages to update the path name again.
The best option is to use the free community version of Intellij Idea 11+. The ADT eclipse plugin is always having problems.
I stumbled upon the same need. And I read a lot on this so, here is my copper on the subject.
If you want your change detection on push, then you would have it when you change a value of an object inside right ? And you also would have it if somehow, you remove objects.
As already said, use of changeDetectionStrategy.onPush
Say you have this component you made, with changeDetectionStrategy.onPush:
<component [collection]="myCollection"></component>
Then you'd push an item and trigger the change detection :
myCollection.push(anItem);
refresh();
or you'd remove an item and trigger the change detection :
myCollection.splice(0,1);
refresh();
or you'd change an attrbibute value for an item and trigger the change detection :
myCollection[5].attribute = 'new value';
refresh();
Content of refresh :
refresh() : void {
this.myCollection = this.myCollection.slice();
}
The slice method returns the exact same Array, and the [ = ] sign make a new reference to it, triggering the change detection every time you need it. Easy and readable :)
Regards,
This might be a generic solution in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CoinProblem
{
class Program
{
static void Main(string[] args)
{
var coins = new int[] { 1, 5, 10, 25 }; // sorted lowest to highest
int upperBound = 99;
int numCoinsRequired = upperBound / coins.Last();
for (int i = coins.Length - 1; i > 0; --i)
{
numCoinsRequired += coins[i] / coins[i - 1] - (coins[i] % coins[i - 1] == 0 ? 1 : 0);
}
Console.WriteLine(numCoinsRequired);
Console.ReadLine();
}
}
}
I haven't fully thought it through...it's too late at night. I thought the answer should be 9 in this case, but Gabe said it should be 10... which is what this yields. I guess it depends how you interpret the question... are we looking for the least number of coins that can produce any value <= X, or the least number of coins that can produce any value <= X using the least number of coins? For example... I'm pretty sure we can make any value with only 9 coins, without nickels, but then to produce 9... you need...oh... I see. You'd need 9 pennies, which you don't have, because that's not what we chose... in that case, I think this answer is right. Just a recursive implementation of Thomas' idea, but I don't know why he stopped there.. you don't need to brute force anything.
Edit: This be wrong.
This is the reason why you should whenever possible use strict equality ===
or strict inequality !==
"100" == 100
true
because this only checks value, not the data type
"100" === 100
false
this checks value and data type
If you want to check syntax error for any nginx files, you can use the -c option.
[root@server ~]# sudo nginx -t -c /etc/nginx/my-server.conf
nginx: the configuration file /etc/nginx/my-server.conf syntax is ok
nginx: configuration file /etc/nginx/my-server.conf test is successful
[root@server ~]#
I won't refer too your example as it is quite simple for a general answer (for example it doesn't contain templated functions ,which force you to implement them on the header) , what I follow as a rule of thumb is the pimpl idiom
It has quite some benefits as you get faster compilation times and the syntactic sugar :
class->member
instead of class.member
The only drawback is the extra pointer you pay.
To get the exact output you requested, you can use the below:
CAST(DATEPART(YEAR, @Date) AS NVARCHAR(10)) + ' - Q' + CAST(DATEPART(QUARTER, @Date) AS NVARCHAR(10))
This will give you an outputs like: "2015 - Q1", "2013 - Q3", etc.
@Borealid's answer is correct, but suppose that you don't care about preserving the exact merging history of a branch and just want to cherry-pick a linearized version of it. Here's an easy and safe way to do that:
Starting state: you are on branch X
, and you want to cherry-pick the commits Y..Z
.
git checkout -b tempZ Z
git rebase Y
git checkout -b newX X
git cherry-pick Y..tempZ
git branch -D tempZ
What this does is to create a branch tempZ
based on Z
, but with the history from Y
onward linearized, and then cherry-pick that onto a copy of X
called newX
. (It's safer to do this on a new branch rather than to mutate X
.) Of course there might be conflicts in step 4, which you'll have to resolve in the usual way (cherry-pick
works very much like rebase
in that respect). Finally it deletes the temporary tempZ
branch.
If step 2 gives the message "Current branch tempZ is up to date", then Y..Z
was already linear, so just ignore that message and proceed with steps 3 onward.
Then review newX
and see whether that did what you wanted.
(Note: this is not the same as a simple git rebase X
when on branch Z
, because it doesn't depend in any way on the relationship between X
and Y
; there may be commits between the common ancestor and Y
that you didn't want.)
Simple command to check keras version:
(py36) C:\WINDOWS\system32>python
Python 3.6.8 |Anaconda custom (64-bit)
>>> import keras
Using TensorFlow backend.
>>> keras.__version__
'2.2.4'
You can do it with following code(track by),
<select ng-model="modelName" ng-options="data.name for data in list track by data.id" ></select>
Doing it in one bulk read:
import re
textfile = open(filename, 'r')
filetext = textfile.read()
textfile.close()
matches = re.findall("(<(\d{4,5})>)?", filetext)
Line by line:
import re
textfile = open(filename, 'r')
matches = []
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
matches += reg.findall(line)
textfile.close()
But again, the matches that returns will not be useful for anything except counting unless you added an offset counter:
import re
textfile = open(filename, 'r')
matches = []
offset = 0
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
matches += [(reg.findall(line),offset)]
offset += len(line)
textfile.close()
But it still just makes more sense to read the whole file in at once.
a.button:hover{
background: #383; }
works for me but in my case
#buttonClick:hover {
background-color:green; }
on windows open a cmd.exe window with administrator permissions and use netstat -a -b -o
you will get the id of the proccess that holds your port and be able to kill it using task manager.
You get the question-mark-diamond characters when your textfile uses high-ANSI encoding -- meaning it uses characters between 127 and 255. Those characters have the eighth (i.e. the most significant) bit set. When ASP.NET reads the textfile it assumes UTF-8 encoding, and that most significant bit has a special meaning.
You must force ASP.NET to interpret the textfile as high-ANSI encoding, by telling it the codepage is 1252:
String textFilePhysicalPath = System.Web.HttpContext.Current.Server.MapPath("~/textfiles/MyInputFile.txt");
String contents = File.ReadAllText(textFilePhysicalPath, System.Text.Encoding.GetEncoding(1252));
lblContents.Text = contents.Replace("\n", "<br />"); // change linebreaks to HTML
$output = file("http://www.example.com");
didn't work until I enabled: allow_url_fopen, allow_url_include,
and file_uploads
in php.ini
for PHP7
The error is pretty clear. The file hello.py
is not an executable file. You need to specify the executable:
subprocess.call(['python.exe', 'hello.py', 'htmlfilename.htm'])
You'll need python.exe
to be visible on the search path, or you could pass the full path to the executable file that is running the calling script:
import sys
subprocess.call([sys.executable, 'hello.py', 'htmlfilename.htm'])
With PHP version >= 5.4 DateTime can do this:-
echo (new \DateTime())->format('Y-m-d H:i:s');
in below code midpointsList is an ArrayList of waypoints
private String getMapsApiDirectionsUrl(GoogleMap googleMap, LatLng startLatLng, LatLng endLatLng, ArrayList<LatLng> midpointsList) {
String origin = "origin=" + startLatLng.latitude + "," + startLatLng.longitude;
String midpoints = "";
for (int mid = 0; mid < midpointsList.size(); mid++) {
midpoints += "|" + midpointsList.get(mid).latitude + "," + midpointsList.get(mid).longitude;
}
String waypoints = "waypoints=optimize:true" + midpoints + "|";
String destination = "destination=" + endLatLng.latitude + "," + endLatLng.longitude;
String key = "key=AIzaSyCV1sOa_7vASRBs6S3S6t1KofFvDhjohvI";
String sensor = "sensor=false";
String params = origin + "&" + waypoints + "&" + destination + "&" + sensor + "&" + key;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + params;
Log.e("url", url);
parseDirectionApidata(url, googleMap);
return url;
}
Then copy and paste this url in your browser to check And the below code is to parse the url
private void parseDirectionApidata(String url, final GoogleMap googleMap) {
final JSONObject jsonObject = new JSONObject();
try {
AppUtill.getJsonWithHTTPPost(ViewMapActivity.this, 1, new ServiceCallBack() {
@Override
public void serviceCallBack(int id, JSONObject jsonResult) throws JSONException {
if (jsonResult != null) {
Log.e("jsonRes", jsonResult.toString());
String status = jsonResult.optString("status");
if (status.equalsIgnoreCase("ok")) {
drawPath(jsonResult, googleMap);
}
} else {
Toast.makeText(ViewMapActivity.this, "Unable to parse Directions Data", Toast.LENGTH_LONG).show();
}
}
}, url, jsonObject);
} catch (Exception e) {
e.printStackTrace();
}
}
And then pass the result to the drawPath method
public void drawPath(JSONObject jObject, GoogleMap googleMap) {
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
List<LatLng> list = null;
try {
Toast.makeText(ViewMapActivity.this, "Drawing Path...", Toast.LENGTH_SHORT).show();
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for (int j = 0; j < jLegs.length(); j++) {
jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for (int k = 0; k < jSteps.length(); k++) {
String polyline = "";
polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
list = decodePoly(polyline);
}
Log.e("list", list.toString());
routes.add(path);
Log.e("routes", routes.toString());
if (list != null) {
Polyline line = googleMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.parseColor("#FF0000"))//Google maps blue color #05b1fb
.geodesic(true)
);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
decode poly function is to decode the points(lat and long) provided by Directions API in encoded form
You cannot use ++
on something which is not a variable, this would be the closest you can get:
$('#counter').html(function(i, val) { return +val+1 });
jQuery's html()
method can get and set the HTML value of an element. If passed a function it can update the HTML based upon the existing value. So in the context of your code:
$("#update").click(function() {
$('#counter').html(function(i, val) { return +val+1 });
}
DEMO: http://jsfiddle.net/marcuswhybrow/zRX2D/2/
When it comes to synchronising your counter on the page, with the counter value in your database, never trust the client! You send either an increment or decrement signal to you server side script, rather than a continuous value such as 10, or 23.
However you could send an AJAX request to the server when you change the HTML of your counter:
$("#update").click(function() {
$('#counter').html(function(i, val) {
$.ajax({
url: '/path/to/script/',
type: 'POST',
data: {increment: true},
success: function() { alert('Request has returned') }
});
return +val+1;
});
}
mod = a % b
This stores the result of a mod b
in the variable mod
.
And you are right, 15 mod 4
is 3, which is exactly what python returns:
>>> 15 % 4
3
a %= b
is also valid.
Knowing the scope of each can make things easier to remember.
process
is node
's global object, and .cwd()
returns where node is running.
__dirname
is module
's property, and represents the file path of the module. In node, one module resides in one file.
Similarly, __filename
is another module
's property, which holds the file name of the module.
Another way to think about Return-Path
vs Reply-To
is to compare it to snail mail.
When you send an envelope in the mail, you specify a return address. If the recipient does not exist or refuses your mail, the postmaster returns the envelope back to the return address. For email, the return address is the Return-Path
.
Inside of the envelope might be a letter and inside of the letter it may direct the recipient to "Send correspondence to example address". For email, the example address is the Reply-To
.
In essence, a Postage Return Address is comparable to SMTP's Return-Path
header and SMTP's Reply-To
header is similar to the replying instructions contained in a letter.
Above (Pre-SQL12) we see examples like this:-
SELECT
T1.id, SUM(T2.id) AS CumSum
FROM
#TMP T1
JOIN #TMP T2 ON T2.id < = T1.id
GROUP BY
T1.id
More efficient...
SELECT
T1.id, SUM(T2.id) + T1.id AS CumSum
FROM
#TMP T1
JOIN #TMP T2 ON T2.id < T1.id
GROUP BY
T1.id
Another elegant solution to the first question may be the insert
command:
p = np.array([[1,2],[3,4]])
p = np.insert(p, 2, values=0, axis=1) # insert values before column 2
Leads to:
array([[1, 2, 0],
[3, 4, 0]])
insert
may be slower than append
but allows you to fill the whole row/column with one value easily.
As for the second question, delete
has been suggested before:
p = np.delete(p, 2, axis=1)
Which restores the original array again:
array([[1, 2],
[3, 4]])
Just paste this code into functions.php file:
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class ($classes, $item) {
if (in_array('current-menu-item', $classes) ){
$classes[] = 'active ';
}
return $classes;
}
More on wordpress.org:
The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method setObject:forKey:
.
You can convert between the two like this:
NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease];
Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):
BOOL success = [dict writeToFile:@"/file/path" atomically:YES];
To read a dictionary from a file, there's a corresponding method:
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];
If you want to read the file as an NSMutableDictionary, simply use:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];
By default the android sdk installer path is ~/Library/Android/sdk/
you can check the type. s3 has a special application/x-directory
bucket.objects({:delimiter=>"/", :prefix=>"f1/"}).each { |obj| p obj.object.content_type }
Converting a range to a table as described in this answer:
Sub CreateTable() ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$1:$D$16"), , xlYes).Name = _ "Table1" 'No go in 2003 ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleLight2" End Sub
You can chain methods off the returned object, so you can immediately close the file you just opened in a single statement.
File.Open("filename", FileMode.Create).Close();
Based on what you all shared I was able to put this together:
#!/usr/bin/env bash
VAR1="192.168.1.20 192.168.1.126 192.168.1.36"
for a in $VAR1; do { ssh -t -t $a -l Administrator "sudo softwareupdate -l"; } & done;
WAITPIDS="$WAITPIDS "$!;...; wait $WAITPIDS
echo "Script has finished"
Exit 1
This lists all the updates on the mac on three machines at once. Later on I used it to perform a software update for all machines when i CAT my ipaddress.txt
To me it seems like the best solution is to use a directive; there's no need for the controller to know that the view is being updated.
Javascript:
var app = angular.module('app', ['directives']);
angular.module('directives', []).directive('toggleClass', function () {
var directiveDefinitionObject = {
restrict: 'A',
template: '<span ng-click="localFunction()" ng-class="selected" ng-transclude></span>',
replace: true,
scope: {
model: '='
},
transclude: true,
link: function (scope, element, attrs) {
scope.localFunction = function () {
scope.model.value = scope.$id;
};
scope.$watch('model.value', function () {
// Is this set to my scope?
if (scope.model.value === scope.$id) {
scope.selected = "active";
} else {
// nope
scope.selected = '';
}
});
}
};
return directiveDefinitionObject;
});
HTML:
<div ng-app="app" ng-init="model = { value: 'dsf'}"> <span>Click a span... then click another</span>
<br/>
<br/>
<span toggle-class model="model">span1</span>
<br/><span toggle-class model="model">span2</span>
<br/><span toggle-class model="model">span3</span>
CSS:
.active {
color:red;
}
I have a fiddle that demonstrates. The idea is when a directive is clicked, a function is called on the directive that sets a variable to the current scope id. Then each directive also watches the same value. If the scope ID's match, then the current element is set to be active using ng-class.
The reason to use directives, is that you no longer are dependent on a controller. In fact I don't have a controller at all (I do define a variable in the view named "model"). You can then reuse this directive anywhere in your project, not just on one controller.
Actually you get promise
on $http.get
.
Try to use followed flow:
<li ng-repeat="document in documents" ng-class="IsFiltered(document.Filtered)">
<span><input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" /></span>
<span>{{document.Name}}</span>
</li>
Where documents
is your array.
$scope.documents = [];
$http.get('/Documents/DocumentsList/' + caseId).then(function(result) {
result.data.forEach(function(val, i) {
$scope.documents.push(/* put data here*/);
});
}, function(error) {
alert(error.message);
});
I think this other Stack Overflow question could help:
How to get JDK 1.5 on Mac OS X
It basically says that if you need to compile or execute a Java application with an older version of the JDK (for example 1.4 or 1.5), you can do it using the 1.6 because it is backwards compatible. To do it so you will need to add the parameter -source 1.5
and/or -target 1.5
in the javac options or in your IDE.
Swift 3
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Hide the navigation bar on the this view controller
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Show the navigation bar on other view controllers
self.navigationController?.setNavigationBarHidden(false, animated: animated)
}
robocopy yourfolder yourdestination /MON:0
should do it, although you may need some more options. The switch at the end will re-run robocopy if more than 0 changes are seen.
CSS properties should be set by cssText
property or setAttribute
method.
// Set multiple styles in a single statement
elt.style.cssText = "color: blue; border: 1px solid black";
// Or
elt.setAttribute("style", "color:red; border: 1px solid blue;");
Styles should not be set by assigning a string directly to the style
property (as in elt.style = "color: blue;"
), since it is considered read-only, as the style
attribute returns a CSSStyleDeclaration
object which is also read-only.
I finally got this working.
I think the fact that our project had two different versions of the commons-httpclient jar wasn't helping. Once I sorted that out I found you can do two things...
In code you can put the following:
HttpComponentsClientHttpRequestFactory rf =
(HttpComponentsClientHttpRequestFactory) restTemplate.getRequestFactory();
rf.setReadTimeout(1 * 1000);
rf.setConnectTimeout(1 * 1000);
The first time this code is called it will set the timeout for the HttpComponentsClientHttpRequestFactory
class used by the RestTemplate
. Therefore, all subsequent calls made by RestTemplate
will use the timeout settings defined above.
Or the better option is to do this:
<bean id="RestOperations" class="org.springframework.web.client.RestTemplate">
<constructor-arg>
<bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<property name="readTimeout" value="${application.urlReadTimeout}" />
<property name="connectTimeout" value="${application.urlConnectionTimeout}" />
</bean>
</constructor-arg>
</bean>
Where I use the RestOperations
interface in my code and get the timeout values from a properties file.
From the spring docs
Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation to set which context files to load.
The <context-param>
:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
You can then use the WebApplicationContext to get a handle on your beans.
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
SomeBean someBean = (SomeBean) ctx.getBean("someBean");
See http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html for more info
Several possibilities : (SwiftUI / Xcode 11)
1 .background(Color.black) //for system colors
2 .background(Color("green")) //for colors you created in Assets.xcassets
Hope it help :)
Seems there is some demand to be able to access this statically.
How can I get such thing in static methods in non-spring-managed classes? – Aetherus
It's a hack, but you can write your own class to expose it. You must be careful to ensure that nothing will call SpringContext.getEnvironment()
before all beans have been created, since there is no guarantee when this component will be instantiated.
@Component
public class SpringContext
{
private static Environment environment;
public SpringContext(Environment environment) {
SpringContext.environment = environment;
}
public static Environment getEnvironment() {
if (environment == null) {
throw new RuntimeException("Environment has not been set yet");
}
return environment;
}
}
Maybe something like this:
import matplotlib.pyplot
import pylab
x = [1,2,3,4]
y = [3,4,8,6]
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
EDIT:
Let me see if I understand you correctly now:
You have:
test1 | test2 | test3
test3 | 1 | 0 | 1
test4 | 0 | 1 | 0
test5 | 1 | 1 | 0
Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.
Let's say you results are stored in a 2-D list:
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
We want to transform them into two variables so we are able to plot them.
And I believe this code will give you what you are looking for:
import matplotlib
import pylab
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
x = []
y = []
for ind_1, sublist in enumerate(results):
for ind_2, ele in enumerate(sublist):
if ele == 1:
x.append(ind_1)
y.append(ind_2)
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
Notice that I do need to import pylab
, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.
import time
from datetime import datetime
now = datetime.now()
# same as above except keeps microseconds
time.mktime(now.timetuple()) + now.microsecond * 1e-6
(Sorry, it wouldn't let me comment on existing answer)
following should be your right solution
ren somefile.txt somefile_%time:~0,2%%time:~3,2%-%DATE:/=%.txt
[HttpPost]
public ActionResult SaveComments(int id, string comments){
var actions = new Actions(User.Identity.Name);
var status = actions.SaveComments(id, comments);
return Content(status);
}
While the answer above is correct I would not recommend you to change the name in order to rely on it in the code.
Names are tricky. They can change. You should use the ShapeId and SlideId.
Especially beware to change the name of a shape programmatically since PowerPoint relies on the name and it might hinder its regular operation.
You can use "translateX(-100%)" and "text-align: right" if your absolute element is "display: inline-block"
<div class="box">
<div class="absolute-right"></div>
</div>
<style type="text/css">
.box{
text-align: right;
}
.absolute-right{
display: inline-block;
position: absolute;
}
/*The magic:*/
.absolute-right{
-moz-transform: translateX(-100%);
-ms-transform: translateX(-100%);
-webkit-transform: translateX(-100%);
-o-transform: translateX(-100%);
transform: translateX(-100%);
}
</style>
You will get absolute-element aligned to the right relative its parent
There are many ways to scroll up and down in Selenium Webdriver I always use Java Script to do the same.
Below is the code which always works for me if I want to scroll up or down
// This will scroll page 400 pixel vertical
((JavascriptExecutor)driver).executeScript("scroll(0,400)");
You can get full code from here Scroll Page in Selenium
If you want to scroll for a element then below piece of code will work for you.
je.executeScript("arguments[0].scrollIntoView(true);",element);
You will get the full doc here Scroll for specific Element
var list = [];
for (var i = lowEnd; i <= highEnd; i++) {
list.push(i);
}
Thymeleaf has an equivalent to <c:choose>
and <c:when>
: the th:switch
and th:case
attributes introduced in Thymeleaf 2.0.
They work as you'd expect, using *
for the default case:
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p>
</div>
See this for a quick explanation of syntax (or the Thymeleaf tutorials).
Disclaimer: As required by StackOverflow rules, I'm the author of Thymeleaf.
This is how it can be fixed easily through Storyboard (iOS 11 and Xcode 9.1):
Select Table View > Size Inspector > Content Insets: Never
If you updated Internet Explorer and began having technical problems, you can use the Compatibility View feature to emulate a previous version of Internet Explorer.
For instructions, see the section below that corresponds with your version. To find your version number, click Help > About Internet Explorer. Internet Explorer 11
To edit the Compatibility View list:
Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.
Tap or click the Tools button (Image), and then tap or click Compatibility View settings.
To remove a website:
Click the website(s) where you would like to turn off Compatibility View, clicking Remove after each one.
To add a website:
Under Add this website, enter the website(s) where you would like to turn on Compatibility View, clicking Add after each one.
I guess a generic client-side JavaScript compression implementation would be a very expensive operation in terms of processing time as opposed to transfer time of a few more HTTP packets with uncompressed payload.
Have you done any testing that would give you an idea how much time there is to save? I mean, bandwidth savings can't be what you're after, or can it?
They are not the same. The first one replaces the HTML without creating another jQuery object first. The second creates an additional jQuery wrapper for the second div, then appends it to the first.
One jQuery Wrapper (per example):
$("#myDiv").html('<div id="mySecondDiv"></div>');
$("#myDiv").append('<div id="mySecondDiv"></div>');
Two jQuery Wrappers (per example):
var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').html(mySecondDiv);
var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').append(mySecondDiv);
You have a few different use cases going on. If you want to replace the content, .html
is a great call since its the equivalent of innerHTML = "..."
. However, if you just want to append content, the extra $()
wrapper set is unneeded.
Only use two wrappers if you need to manipulate the added div
later on. Even in that case, you still might only need to use one:
var mySecondDiv = $("<div id='mySecondDiv'></div>").appendTo("#myDiv");
// other code here
mySecondDiv.hide();
I struggled with this exception while running my application.
Finally the problem was on the sql query. i mean that the query is wrong.
please verify your query. This is my suggestion
You can use plain javascript, this will call your_func once, after 5 seconds:
setTimeout(function() { your_func(); }, 5000);
If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)
There is also a plugin I've used once. It has oneTime
and everyTime
methods.
User "portrait"
in your AndroidManifest.xml file might seem like a good solution. But it forces certain devices (that work best in landscape) to go into portrait, not getting the proper orientation. On the latest Android version, you will get wearing an error. So my suggestion it's better to use "nosensor"
.
<activity
...
...
android:screenOrientation="nosensor">
I would take a look at the BinaryReader and BinaryWriter classes. I recently had to serialize data to a byte array (and back) and only found these classes after I'd basically rewritten them myself.
http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx
There is a good example on that page too.
HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
HashMap<String, int[]> map = new HashMap<String, int[]>();
pick one, for example
HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
map.put("Something", new ArrayList<Integer>());
for (int i=0;i<numarulDeCopii; i++) {
map.get("Something").add(coeficientUzura[i]);
}
or just
HashMap<String, int[]> map = new HashMap<String, int[]>();
map.put("Something", coeficientUzura);
Never got exist to work.
I use if not exist g:xyz/what goto h: Else xcopy c:current/files g:bu/current There are modifiers /a etc. Not sure which ones. Laptop in shop. And computer in office. I am not there.
Never got batch files to work above Windows XP
This is a fairly straightforward way to do this, but it may not be the fastest. It is quite powerful because it is composable.
public static IEnumerable<int> ToBase(this int x, int b)
{
IEnumerable<int> ToBaseReverse()
{
if (x == 0)
{
yield return 0;
yield break;
}
int z = x;
while (z > 0)
{
yield return z % b;
z = z / b;
}
}
return ToBaseReverse().Reverse();
}
Combine this with this simple extension method and any getting any base is now possible:
public static string ToBase(this int number, string digits) =>
String.Concat(number.ToBase(digits.Length).Select(x => digits[x]));
It can be used like this:
var result = 23.ToBase("01");
var result2 = 23.ToBase("012X");
Console.WriteLine(result);
Console.WriteLine(result2);
The output is:
10111 11X
when you add a new data set to a geom you need to use the data=
argument. Or put the arguments in the proper order mapping=..., data=...
. Take a look at the arguments for ?geom_line
.
Thus:
p + geom_line(data=df.last, aes(HrEnd, MWh, group=factor(Date)), color="red")
Or:
p + geom_line(aes(HrEnd, MWh, group=factor(Date)), df.last, color="red")
You can't. It's immediate mode graphics. But you can sort of simulate it by drawing a rectangle over it in the background color with an opacity.
If the image is over something other than a constant color, then it gets quite a bit trickier. You should be able to use the pixel manipulation methods in this case. Just save the area before drawing the image, and then blend that back on top with an opacity afterwards.
How about this?
formdata.append('tags', JSON.stringify(tags));
... and, correspondingly, using json_decode
on server to deparse it. See, the second value of FormData.append can be...
a Blob, File, or a string, if neither, the value is converted to a string
The way I see it, your tags
array contains objects (@Musa is right, btw; making this_tag
an Array, then assigning string properties to it makes no sense; use plain object instead), so native conversion (with toString()
) won't be enough. JSON'ing should get the info through, though.
As a sidenote, I'd rewrite the property assigning block just into this:
tags.push({article: article, gender: gender, brand: brand});
If you're using the ordered set to maintain a sorted order, consider using a sorted set implementation from PyPI. The sortedcontainers module provides a SortedSet for just this purpose. Some benefits: pure-Python, fast-as-C implementations, 100% unit test coverage, hours of stress testing.
Installing from PyPI is easy with pip:
pip install sortedcontainers
Note that if you can't pip install
, simply pull down the sortedlist.py and sortedset.py files from the open-source repository.
Once installed you can simply:
from sortedcontainers import SortedSet
help(SortedSet)
The sortedcontainers module also maintains a performance comparison with several alternative implementations.
For the comment that asked about Python's bag data type, there's alternatively a SortedList data type which can be used to efficiently implement a bag.
Just use ary.slice(0,1).pop();
In
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];_x000D_
_x000D_
console.log("1º "+ary.slice(0,1).pop());_x000D_
console.log("2º "+ary.slice(0,2).pop());_x000D_
console.log("3º "+ary.slice(0,3).pop());_x000D_
console.log("4º "+ary.slice(0,4).pop());_x000D_
console.log("5º "+ary.slice(0,5).pop());_x000D_
console.log("Last "+ary.slice(-1).pop());
_x000D_
array.slice(START,END).pop();
This windows batch works regardless of whether or not it's on GitHub. I'm using it because it shows some stark caveats. You'll notice that the operation is slow and traversing hundreds of megabytes of data, so don't use this method if your requirements are based on available bandwidth/R-W memory.
sparse_checkout.bat
pushd "%~dp0"
if not exist .\ms-server-essentials-docs mkdir .\ms-server-essentials-docs
pushd .\ms-server-essentials-docs
git init
git remote add origin -f https://github.com/MicrosoftDocs/windowsserverdocs.git
git config core.sparseCheckout true
(echo EssentialsDocs)>>.git\info\sparse-checkout
git pull origin master
=>
C:\Users\user name\Desktop>sparse_checkout.bat
C:\Users\user name\Desktop>pushd "C:\Users\user name\Desktop\"
C:\Users\user name\Desktop>if not exist .\ms-server-essentials-docs mkdir .\ms-server-essentials-docs
C:\Users\user name\Desktop>pushd .\ms-server-essentials-docs
C:\Users\user name\Desktop\ms-server-essentials-docs>git init Initialized empty Git repository in C:/Users/user name/Desktop/ms-server-essentials-docs/.git/
C:\Users\user name\Desktop\ms-server-essentials-docs>git remote add origin -f https://github.com/MicrosoftDocs/windowsserverdocs.git Updating origin remote: Enumerating objects: 97, done. remote: Counting objects: 100% (97/97), done. remote: Compressing objects: 100% (44/44), done. remote: Total 145517 (delta 63), reused 76 (delta 53), pack-reused 145420 Receiving objects: 100% (145517/145517), 751.33 MiB | 32.06 MiB/s, done. Resolving deltas: 100% (102110/102110), done. From https://github.com/MicrosoftDocs/windowsserverdocs * [new branch]
1106-conflict -> origin/1106-conflict * [new branch]
FromPrivateRepo -> origin/FromPrivateRepo * [new branch]
PR183 -> origin/PR183 * [new branch]
conflictfix -> origin/conflictfix * [new branch]
eross-msft-patch-1 -> origin/eross-msft-patch-1 * [new branch]
master -> origin/master * [new branch] patch-1
-> origin/patch-1 * [new branch] repo_sync_working_branch -> origin/repo_sync_working_branch * [new branch]
shortpatti-patch-1 -> origin/shortpatti-patch-1 * [new branch]
shortpatti-patch-2 -> origin/shortpatti-patch-2 * [new branch]
shortpatti-patch-3 -> origin/shortpatti-patch-3 * [new branch]
shortpatti-patch-4 -> origin/shortpatti-patch-4 * [new branch]
shortpatti-patch-5 -> origin/shortpatti-patch-5 * [new branch]
shortpatti-patch-6 -> origin/shortpatti-patch-6 * [new branch]
shortpatti-patch-7 -> origin/shortpatti-patch-7 * [new branch]
shortpatti-patch-8 -> origin/shortpatti-patch-8C:\Users\user name\Desktop\ms-server-essentials-docs>git config core.sparseCheckout true
C:\Users\user name\Desktop\ms-server-essentials-docs>(echo EssentialsDocs ) 1>>.git\info\sparse-checkout
C:\Users\user name\Desktop\ms-server-essentials-docs>git pull origin master
From https://github.com/MicrosoftDocs/windowsserverdocs
* branch master -> FETCH_HEAD
If you use the following CSS
<link href="~/Content/common/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" type="text/css" />
just change it into the following style by adding media="screen"
<link href="~/Content/common/bootstrap.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" **media="screen"** type="text/css" />
I think it will work.
the former answers like
@media print {
a[href]:after {
content: none !important;
}
}
were not worked well in the chrome browse.
Install the MSI file:
Go to the installed directory C:\Program Files\nodejs
from command prompt n
C:\>cd C:\Program Files\nodejs enter..
node helloworld.js
output:
Hello World
Some sargable methods...
SELECT *
FROM #T
WHERE SomeCol = '' OR SomeCol IS NULL;
SELECT *
FROM #T
WHERE SomeCol = ''
UNION ALL
SELECT *
FROM #T
WHERE SomeCol IS NULL;
SELECT *
FROM #T
WHERE EXISTS ((SELECT NULL UNION SELECT '') INTERSECT SELECT SomeCol);
And some non-sargable ones...
SELECT *
FROM #T
WHERE IIF(SomeCol <> '',0,1) = 1;
SELECT *
FROM #T
WHERE NULLIF(SomeCol,'') IS NULL;
SELECT *
FROM #T
WHERE ISNULL(SomeCol,'') = '';
This is pretty must just a copy of that projects demo page and shows uploading a single file on form submit with upload progress.
(function (angular) {
'use strict';
angular.module('uploadModule', [])
.controller('uploadCtrl', [
'$scope',
'$upload',
function ($scope, $upload) {
$scope.model = {};
$scope.selectedFile = [];
$scope.uploadProgress = 0;
$scope.uploadFile = function () {
var file = $scope.selectedFile[0];
$scope.upload = $upload.upload({
url: 'api/upload',
method: 'POST',
data: angular.toJson($scope.model),
file: file
}).progress(function (evt) {
$scope.uploadProgress = parseInt(100.0 * evt.loaded / evt.total, 10);
}).success(function (data) {
//do something
});
};
$scope.onFileSelect = function ($files) {
$scope.uploadProgress = 0;
$scope.selectedFile = $files;
};
}
])
.directive('progressBar', [
function () {
return {
link: function ($scope, el, attrs) {
$scope.$watch(attrs.progressBar, function (newValue) {
el.css('width', newValue.toString() + '%');
});
}
};
}
]);
}(angular));
HTML
<form ng-submit="uploadFile()">
<div class="row">
<div class="col-md-12">
<input type="text" ng-model="model.fileDescription" />
<input type="number" ng-model="model.rating" />
<input type="checkbox" ng-model="model.isAGoodFile" />
<input type="file" ng-file-select="onFileSelect($files)">
<div class="progress" style="margin-top: 20px;">
<div class="progress-bar" progress-bar="uploadProgress" role="progressbar">
<span ng-bind="uploadProgress"></span>
<span>%</span>
</div>
</div>
<button button type="submit" class="btn btn-default btn-lg">
<i class="fa fa-cloud-upload"></i>
<span>Upload File</span>
</button>
</div>
</div>
</form>
EDIT: Added passing a model up to the server in the file post.
The form data in the input elements would be sent in the data property of the post and be available as normal form values.
You can try:
model.ImageField.path = os.path.join('/Upload', generated_image_path)
Use the HEREDOC syntax. You can mix single and double quotes, variables and even function calls with unaltered / unescaped html markup.
echo <<<MYTAG
<tr><td> <input type="hidden" name="type" value="$var1" ></td></tr>
<tr><td> <input type="hidden" name="type" value="$var2" ></td></tr>
<tr><td> <input type="hidden" name="type" value="$var3" ></td></tr>
<tr><td> <input type="hidden" name="type" value="$var4" ></td></tr>
MYTAG;
Just for completeness, you can get a list of kernels with jupyter kernelspec list
, but I ran into a case where one of the kernels did not show up in this list. You can find all kernel names by opening a Jupyter notebook and selecting Kernel -> Change kernel
. If you do not see everything in this list when you run jupyter kernelspec list
, try looking in common Jupyter folders:
ls ~/.local/share/jupyter/kernels # usually where local kernels go
ls /usr/local/share/jupyter/kernels # usually where system-wide kernels go
ls /usr/share/jupyter/kernels # also where system-wide kernels can go
Also, you can delete a kernel with jupyter kernelspec remove
or jupyter kernelspec uninstall
. The latter is an alias for remove
. From the in-line help text for the command:
uninstall
Alias for remove
remove
Remove one or more Jupyter kernelspecs by name.