Goto Properties -> maven Remove the pom.xml from the activate profiles and follow the below steps.
Steps :
I have found a solution of git bash command when you try to build war using git mvn clean install for “java.lang.OutOfMemoryError: PermGen space” in Maven build error come
use below command first
$ export MAVEN_OPTS="-Xmx512m -Xss32m"
then use your mvn command to clean install /build war file
$ mvn clean install
NOTE: you don't need -XX:MaxPermSize argument in MAVEN_OPTS when your are using jdk1.8
Java HotSpot(TM) Client VM warning: ignoring option MaxPermSize=XXXm; support was removed in 8.0
I spent sometime looking for best practice that make sense and found the following which worked perfected for me. I hope this will save you sometime.
Using Config file (for example an asp.net website) https://blogs.msdn.microsoft.com/kaushal/2013/05/22/http-to-https-redirects-on-iis-7-x-and-higher/
or on your own server https://www.sslshopper.com/iis7-redirect-http-to-https.html
[SHORT ANSWER] Simply The code below goes inside
<system.webServer>
<rewrite>
<rules>
<rule name="HTTP/S to HTTPS Redirect" enabled="true"
stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAny">
<add input="{SERVER_PORT_SECURE}" pattern="^0$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}"
redirectType="Permanent" />
</rule>
</rules>
</rewrite>
The #
means that it matches the id
of an element. The .
signifies the class name:
<div id="myRedText">This will be red.</div>
<div class="blueText">this will be blue.</div>
#myRedText {
color: red;
}
.blueText {
color: blue;
}
Note that in a HTML document, the id attribute must be unique, so if you have more than one element needing a specific style, you should use a class name.
Based on A.K's code, here is a Helper Function. JS Fiddle Here (http://jsfiddle.net/M5vsL/1/) ...
// Helper Method Defined Here.
(function (helper, $) {
// This is now a utility function to "Get the Document Hash"
helper.getDocumentHash = function (urlString) {
var hashValue = "";
if (urlString.indexOf('#') != -1) {
hashValue = urlString.substring(parseInt(urlString.indexOf('#')) + 1);
}
return hashValue;
};
})(this.helper = this.helper || {}, jQuery);
As a string, no. As an integer, %d.
Unless you count:
static char* enumStrings[] = { /* filler 0's to get to the first value, */
"enum0", "enum1",
/* filler for hole in the middle: ,0 */
"enum2", "enum3", .... };
...
printf("The value is %s\n", enumStrings[thevalue]);
This won't work for something like an enum of bit masks. At that point, you need a hash table or some other more elaborate data structure.
The hold on
feature is switched on by default in matplotlib.pyplot
. So each time you evoke plt.plot()
before plt.show()
a drawing is added to the plot. Launching plt.plot()
after the function plt.show()
leads to redrawing the whole picture.
If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using broadcasting.
Starting with your example array:
import numpy as np
x = np.array([[1000, 10, 0.5],
[ 765, 5, 0.35],
[ 800, 7, 0.09]])
x_normed = x / x.max(axis=0)
print(x_normed)
# [[ 1. 1. 1. ]
# [ 0.765 0.5 0.7 ]
# [ 0.8 0.7 0.18 ]]
x.max(0)
takes the maximum over the 0th dimension (i.e. rows). This gives you a vector of size (ncols,)
containing the maximum value in each column. You can then divide x
by this vector in order to normalize your values such that the maximum value in each column will be scaled to 1.
If x
contains negative values you would need to subtract the minimum first:
x_normed = (x - x.min(0)) / x.ptp(0)
Here, x.ptp(0)
returns the "peak-to-peak" (i.e. the range, max - min) along axis 0. This normalization also guarantees that the minimum value in each column will be 0.
There is another solution from the pandas documentation (that I don't see here),
using the .append
>>> df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
A B
0 1 2
1 3 4
>>> df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
A B
0 5 6
1 7 8
>>> df.append(df2, ignore_index=True)
A B
0 1 2
1 3 4
2 5 6
3 7 8
The ignore_index=True
is used to ignore the index of the appended dataframe, replacing it with the next index available in the source one.
If there are different column names, Nan
will be introduced.
PHP has catchable fatal errors. They are defined as E_RECOVERABLE_ERROR. The PHP manual describes an E_RECOVERABLE_ERROR as:
Catchable fatal error. It indicates that a probably dangerous error occured, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR.
You can "catch" these "fatal" errors by using set_error_handler() and checking for E_RECOVERABLE_ERROR. I find it useful to throw an Exception when this error is caught, then you can use try/catch.
This question and answer provides a useful example: How can I catch a "catchable fatal error" on PHP type hinting?
E_ERROR errors, however, can be handled, but not recovered from as the engine is in an unstable state.
private String relative(String left, String right){
String[] lefts = left.split("/");
String[] rights = right.split("/");
int min = Math.min(lefts.length, rights.length);
int commonIdx = -1;
for(int i = 0; i < min; i++){
if(commonIdx < 0 && !lefts[i].equals(rights[i])){
commonIdx = i - 1;
break;
}
}
if(commonIdx < 0){
return null;
}
StringBuilder sb = new StringBuilder(Math.max(left.length(), right.length()));
sb.append(left).append("/");
for(int i = commonIdx + 1; i < lefts.length;i++){
sb.append("../");
}
for(int i = commonIdx + 1; i < rights.length;i++){
sb.append(rights[i]).append("/");
}
return sb.deleteCharAt(sb.length() -1).toString();
}
For each works with JQuery as in
$(<selector>).each(function() {
//this points to item
alert('<msg>');
});
JQuery also, for a popup, has in the UI library a dialog widget: http://jqueryui.com/demos/dialog/
Check it out, works really well.
HTH.
select *
from sysobjects
where xtype='pk' and
parent_obj in (select id from sysobjects where name='tablename')
this will work in sql 2005
Do a reset of the configuration and set the root level to OFF
LogManager.getLogManager().reset();
Logger globalLogger = Logger.getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME);
globalLogger.setLevel(java.util.logging.Level.OFF);
Ok, so I see this is an old post, but why are we rewriting code that is already provided in the framework?
I would suggest that you add a reference to the framework DLL "Microsoft.VisualBasic"
using Microsoft.VisualBasic;
//...
string value = Strings.Right("34234234d124", 4);
I have been trying to attach an audio which should autoplay and will be hidden. It's very simple. Just a few lines of HTML and CSS. Check this out!! Here is the piece of code I used within the body.
<div id="player">
<audio controls autoplay hidden>
<source src="file.mp3" type="audio/mpeg">
unsupported !!
</audio>
</div>
Without actually doing some debugging, I guess you can't be certain that a debugger is working.
But you can be pretty sure -- I guess one should assume that if some aspects of xDebug are working then it would all be working.
Given that, you can confirm that xDebug is installed and in place by trying the following:
1) phpinfo()
-- this will show you all the extensions that are loaded, including xDebug. If it is there, then it's a safe bet that it's working.
2) If that isn't good enough for you, you can try using the var_dump()
function. xDebug modifies the output of var_dump()
to include additional information. If this is in place, then xDebug is working.
3) xDebug modifies PHP's error output. If your program crashes with xDebug in place, you'll get more information about the failure than with the standard PHP crash output.
4) xDebug also adds a number of helper functions to PHP. You could try any of these to see if it's working. For example, the function xdebug_get_code_coverage()
should exist and return an array. If it does, then xDebug is installed. If not, it isn't.
I had precisely this problem, but I needed sequential plots to have highly contrasting color. I was also doing plots with a common sub-plot containing reference data, so I wanted the color sequence to be consistently repeatable.
I initially tried simply generating colors randomly, reseeding the RNG before each plot. This worked OK (commented-out in code below), but could generate nearly indistinguishable colors. I wanted highly contrasting colors, ideally sampled from a colormap containing all colors.
I could have as many as 31 data series in a single plot, so I chopped the colormap into that many steps. Then I walked the steps in an order that ensured I wouldn't return to the neighborhood of a given color very soon.
My data is in a highly irregular time series, so I wanted to see the points and the lines, with the point having the 'opposite' color of the line.
Given all the above, it was easiest to generate a dictionary with the relevant parameters for plotting the individual series, then expand it as part of the call.
Here's my code. Perhaps not pretty, but functional.
from matplotlib import cm
cmap = cm.get_cmap('gist_rainbow') #('hsv') #('nipy_spectral')
max_colors = 31 # Constant, max mumber of series in any plot. Ideally prime.
color_number = 0 # Variable, incremented for each series.
def restart_colors():
global color_number
color_number = 0
#np.random.seed(1)
def next_color():
global color_number
color_number += 1
#color = tuple(np.random.uniform(0.0, 0.5, 3))
color = cmap( ((5 * color_number) % max_colors) / max_colors )
return color
def plot_args(): # Invoked for each plot in a series as: '**(plot_args())'
mkr = next_color()
clr = (1 - mkr[0], 1 - mkr[1], 1 - mkr[2], mkr[3]) # Give line inverse of marker color
return {
"marker": "o",
"color": clr,
"mfc": mkr,
"mec": mkr,
"markersize": 0.5,
"linewidth": 1,
}
My context is JupyterLab and Pandas, so here's sample plot code:
restart_colors() # Repeatable color sequence for every plot
fig, axs = plt.subplots(figsize=(15, 8))
plt.title("%s + T-meter"%name)
# Plot reference temperatures:
axs.set_ylabel("°C", rotation=0)
for s in ["T1", "T2", "T3", "T4"]:
df_tmeter.plot(ax=axs, x="Timestamp", y=s, label="T-meter:%s" % s, **(plot_args()))
# Other series gets their own axis labels
ax2 = axs.twinx()
ax2.set_ylabel(units)
for c in df_uptime_sensors:
df_uptime[df_uptime["UUID"] == c].plot(
ax=ax2, x="Timestamp", y=units, label="%s - %s" % (units, c), **(plot_args())
)
fig.tight_layout()
plt.show()
The resulting plot may not be the best example, but it becomes more relevant when interactively zoomed in.
Just a side note, in Python 2.0 you could compare anything to anything (int to string). As this wasn't explicit, it was changed in 3.0, which is a good thing as you are not running into the trouble of comparing senseless values with each other or when you forget to convert a type.
This is by far the easiest example I have found on the net. http://jonraasch.com/blog/a-simple-jquery-slideshow
Summaring the example, this is what you need to do a slideshow:
HTML:
<div id="slideshow">
<img src="img1.jpg" style="position:absolute;" class="active" />
<img src="img2.jpg" style="position:absolute;" />
<img src="img3.jpg" style="position:absolute;" />
</div>
Position absolute is used to put an each image over the other.
CSS
<style type="text/css">
.active{
z-index:99;
}
</style>
The image that has the class="active" will appear over the others, the class=active property will change with the following Jquery code.
<script>
function slideSwitch() {
var $active = $('div#slideshow IMG.active');
var $next = $active.next();
$next.addClass('active');
$active.removeClass('active');
}
$(function() {
setInterval( "slideSwitch()", 5000 );
});
</script>
If you want to go further with slideshows I suggest you to have a look at the link above (to see animated oppacity changes - 2n example) or at other more complex slideshows tutorials.
if you want to use it inside a 'for' to copy the last generated files for a every-day bacakup...
j=0
var="`find /backup/path/ -name 'something*' -type f -mtime -1`"
#we have in $var some files with last day change date
for i in $var
do
j=$(( $j + 1 ))
dirname="`dirname $i`"
filename="`basename $i`"
/usr/bin/ftp -in >> /tmp/ftp.good 2>> /tmp/ftp.bad << EOF
open 123.456.789.012
user user_name passwd
bin
lcd $dirname
put $filename
quit
EOF #end of ftp
done #end of for iteration
why don't you store your values in HTML5 storage objects such as sessionStorage
or localStorage
, visit HTML5 Storage Doc to get more details. Using this you can store intermediate values temporarily/permanently locally and then access your values later.
To store values for a session:
sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')
or more permanently:
localStorage.getItem('label')
localStorage.setItem('label', 'value')
So you can store (temporarily) form data between multiple pages using HTML5 storage objects which you can even retain after reload..
This works for me.
cp -r /home/server/folder/test/. /home/server
Your problem is rather clear. Perhaps you're looking for extend, to add all elements of another list to an existing list:
>>> x = [1,2]
>>> x.extend([3,4,5])
>>> x
[1, 2, 3, 4, 5]
If you want to convert integers to strings, use str() or string interpolation, possibly combined with a list comprehension, i.e.
>>> x = ['1', '2']
>>> x.extend([str(i) for i in range(3, 6)])
>>> x
['1', '2', '3', '4', '5']
All of this is considered pythonic (ok, a generator expression is even more pythonic but let's stay simple and on topic)
I used to think that creating the objects at runtime would be the better approach. I'm less certain now, since you do lose some useful features, though it may be worth it regardless simply to prevent newbie confusion. The disadvantages of doing so are:
1. Performance
def foo(arg=something_expensive_to_compute())):
...
If call-time evaluation is used, then the expensive function is called every time your function is used without an argument. You'd either pay an expensive price on each call, or need to manually cache the value externally, polluting your namespace and adding verbosity.
2. Forcing bound parameters
A useful trick is to bind parameters of a lambda to the current binding of a variable when the lambda is created. For example:
funcs = [ lambda i=i: i for i in range(10)]
This returns a list of functions that return 0,1,2,3... respectively. If the behaviour is changed, they will instead bind i
to the call-time value of i, so you would get a list of functions that all returned 9
.
The only way to implement this otherwise would be to create a further closure with the i bound, ie:
def make_func(i): return lambda: i
funcs = [make_func(i) for i in range(10)]
3. Introspection
Consider the code:
def foo(a='test', b=100, c=[]):
print a,b,c
We can get information about the arguments and defaults using the inspect
module, which
>>> inspect.getargspec(foo)
(['a', 'b', 'c'], None, None, ('test', 100, []))
This information is very useful for things like document generation, metaprogramming, decorators etc.
Now, suppose the behaviour of defaults could be changed so that this is the equivalent of:
_undefined = object() # sentinel value
def foo(a=_undefined, b=_undefined, c=_undefined)
if a is _undefined: a='test'
if b is _undefined: b=100
if c is _undefined: c=[]
However, we've lost the ability to introspect, and see what the default arguments are. Because the objects haven't been constructed, we can't ever get hold of them without actually calling the function. The best we could do is to store off the source code and return that as a string.
Try something like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
}
The exception is in the $_
variable. You might explore $_
like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
$_ | fl * -Force
}
I think it will give you all the info you need.
My rule: if there is some data that is not displayed, try to use -force
.
You can use some inline CSS like this
<input type="submit" name="submit" style="background: url(images/stack.png); width:100px; height:25px;" />
Should do the magic, also you may wanna do a border:none; to get rid of the standard borders.
Since eval("3+2")=5
,you can use it as following :
byId=(id)=>document.getElementById(id);
byId('txt3').value=eval(`${byId('txt1').value}+${byId('txt2').value}`)
By that, you don't need parseInt
All you need to do is run
pip install /opt/mypackage
and pip will search /opt/mypackage
for a setup.py
, build a wheel, then install it.
The problem with using the -e
flag for pip install
as suggested in the comments and this answer is that this requires that the original source directory stay in place for as long as you want to use the module. It's great if you're a developer working on the source, but if you're just trying to install a package, it's the wrong choice.
Alternatively, you don't even need to download the repo from Github at all. pip supports installing directly from git repos using a variety of protocols including HTTP, HTTPS, and SSH, among others. See the docs I linked to for examples.
var user = [
{ id: 1, name: 'Siddhu' },
{ id: 2, name: 'Siddhartha' },
{ id: 3, name: 'Tiwary' }
];
var recToRemove={ id: 1, name: 'Siddhu' };
user.splice(user.indexOf(recToRemove),1)
For me work when i change my php.ini in my host:
; Default timeout for socket based streams (seconds)
default_socket_timeout = 300
This is pretty basic, just put in the php file you want to use for processing in the element.
For example
<form action="process.php" method="post">
Then in process.php you would get the form values using $_POST['name of the variable]
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
if(segue!.identifier){
var name = segue!.identifier;
if (name.compare("Load View") == 0){
}
}
}
You can't compare the the identifier with == you have to use the compare() method
You can also use the title attribute in your image tag
<img src="content/assets/thumbnails/transparent_150x150.png" alt="" title="hover text" />
I used this function to download pdf stream from server.
function printPdf(url) {
var iframe = document.createElement('iframe');
// iframe.id = 'pdfIframe'
iframe.className='pdfIframe'
document.body.appendChild(iframe);
iframe.style.display = 'none';
iframe.onload = function () {
setTimeout(function () {
iframe.focus();
iframe.contentWindow.print();
URL.revokeObjectURL(url)
// document.body.removeChild(iframe)
}, 1);
};
iframe.src = url;
// URL.revokeObjectURL(url)
}
Splitting a string by whitespace is very simple:
print $_, "\n" for split ' ', 'file1.gz file1.gz file3.gz';
This is a special form of split
actually (as this function usually takes patterns instead of strings):
As another special case,
split
emulates the default behavior of the command line toolawk
when thePATTERN
is either omitted or a literal string composed of a single space character (such as' '
or"\x20"
). In this case, any leading whitespace inEXPR
is removed before splitting occurs, and thePATTERN
is instead treated as if it were/\s+/
; in particular, this means that any contiguous whitespace (not just a single space character) is used as a separator.
Here's an answer for the original question (with a simple string without any whitespace):
Perhaps you want to split on .gz
extension:
my $line = "file1.gzfile1.gzfile3.gz";
my @abc = split /(?<=\.gz)/, $line;
print $_, "\n" for @abc;
Here I used (?<=...)
construct, which is look-behind assertion, basically making split at each point in the line preceded by .gz
substring.
If you work with the fixed set of extensions, you can extend the pattern to include them all:
my $line = "file1.gzfile2.txtfile2.gzfile3.xls";
my @exts = ('txt', 'xls', 'gz');
my $patt = join '|', map { '(?<=\.' . $_ . ')' } @exts;
my @abc = split /$patt/, $line;
print $_, "\n" for @abc;
While searching for a way to round tabs, I found Carlo's answer and it did help but I needed a bit more. Here is what I put together, based on his work. This was done with MS Visual Studio 2015.
The Code:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MealNinja"
mc:Ignorable="d"
Title="Rounded Tabs Example" Height="550" Width="700" WindowStartupLocation="CenterScreen" FontFamily="DokChampa" FontSize="13.333" ResizeMode="CanMinimize" BorderThickness="0">
<Window.Effect>
<DropShadowEffect Opacity="0.5"/>
</Window.Effect>
<Grid Background="#FF423C3C">
<TabControl x:Name="tabControl" TabStripPlacement="Left" Margin="6,10,10,10" BorderThickness="3">
<TabControl.Resources>
<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<Border Name="Border" Background="#FF6E6C67" Margin="2,2,-8,0" BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="10">
<ContentPresenter x:Name="ContentSite" ContentSource="Header" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="2,2,12,2" RecognizesAccessKey="True"/>
</Border>
<Rectangle Height="100" Width="10" Margin="0,0,-10,0" Stroke="Black" VerticalAlignment="Bottom" HorizontalAlignment="Right" StrokeThickness="0" Fill="#FFD4D0C8"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="FontWeight" Value="Bold" />
<Setter TargetName="ContentSite" Property="Width" Value="30" />
<Setter TargetName="Border" Property="Background" Value="#FFD4D0C8" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="#FF6E6C67" />
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="FontWeight" Value="Bold" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<ContentPresenter Content="{TemplateBinding Content}">
<ContentPresenter.LayoutTransform>
<RotateTransform Angle="270" />
</ContentPresenter.LayoutTransform>
</ContentPresenter>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="Background" Value="#FF6E6C67" />
<Setter Property="Height" Value="90" />
<Setter Property="Margin" Value="0" />
<Setter Property="Padding" Value="0" />
<Setter Property="FontFamily" Value="DokChampa" />
<Setter Property="FontSize" Value="16" />
<Setter Property="VerticalAlignment" Value="Top" />
<Setter Property="HorizontalAlignment" Value="Right" />
<Setter Property="UseLayoutRounding" Value="False" />
</Style>
<Style x:Key="tabGrids">
<Setter Property="Grid.Background" Value="#FFE5E5E5" />
<Setter Property="Grid.Margin" Value="6,10,10,10" />
</Style>
</TabControl.Resources>
<TabItem Header="Planner">
<Grid Style="{StaticResource tabGrids}"/>
</TabItem>
<TabItem Header="Section 2">
<Grid Style="{StaticResource tabGrids}"/>
</TabItem>
<TabItem Header="Section III">
<Grid Style="{StaticResource tabGrids}"/>
</TabItem>
<TabItem Header="Section 04">
<Grid Style="{StaticResource tabGrids}"/>
</TabItem>
<TabItem Header="Tools">
<Grid Style="{StaticResource tabGrids}"/>
</TabItem>
</TabControl>
</Grid>
</Window>
Screenshot:
This will both show the input in uppercase and send the input data through post in uppercase.
HTML
<input type="text" id="someInput">
JavaScript
var someInput = document.querySelector('#someInput');
someInput.addEventListener('input', function () {
someInput.value = someInput.value.toUpperCase();
});
All the answers here suggest to use ipairs but beware, it does not work all the time.
t = {[2] = 44, [4]=77, [6]=88}
--This for loop prints the table
for key,value in next,t,nil do
print(key,value)
end
--This one does not print the table
for key,value in ipairs(t) do
print(key,value)
end
I don't understand why people are seeding with a time value. This has in my experience never been a good idea. For example, while the system clock is maybe represented in nanoseconds, the system's clock precision isn't nanoseconds.
This program should not be run on the Go playground but if you run it on your machine you get a rough estimate on what type of precision you can expect. I see increments of about 1000000 ns, so 1 ms increments. That's 20 bits of entropy that are not used. All the while the high bits are mostly constant!? Roughly ~24 bits of entropy over a day which is very brute forceable (which can create vulnerabilities).
The degree that this matters to you will vary but you can avoid pitfalls of clock based seed values by simply using the crypto/rand.Read
as source for your seed. It will give you that non-deterministic quality that you are probably looking for in your random numbers (even if the actual implementation itself is limited to a set of distinct and deterministic random sequences).
import (
crypto_rand "crypto/rand"
"encoding/binary"
math_rand "math/rand"
)
func init() {
var b [8]byte
_, err := crypto_rand.Read(b[:])
if err != nil {
panic("cannot seed math/rand package with cryptographically secure random number generator")
}
math_rand.Seed(int64(binary.LittleEndian.Uint64(b[:])))
}
As a side note but in relation to your question. You can create your own rand.Source
using this method to avoid the cost of having locks protecting the source. The rand
package utility functions are convenient but they also use locks under the hood to prevent the source from being used concurrently. If you don't need that you can avoid it by creating your own Source
and use that in a non-concurrent way. Regardless, you should NOT be reseeding your random number generator between iterations, it was never designed to be used that way.
I had surprising luck with with simple:
body {
height: 100vh;
}
It works great to disable overscroll for pop-ups or menus and it doesn't force browser bars to appear like when using position:fixed. BUT - you need to save scroll position before setting fixed height and restore it when hiding the pop-up, otherwise, browser will scroll to top.
try
System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
appLog.Source = "This Application's Name";
appLog.WriteEntry("An entry to the Application event log.");
For me, i wanted my devl to be back to the master after it was ahead.
While on develop:
git checkout master
git pull
git checkout develop
git pull
git reset --hard origin/master
git push -f
This is fairly easy, using marshalling.
Top of file
using System.Runtime.InteropServices
Function
byte[] getBytes(CIFSPacket str) {
int size = Marshal.SizeOf(str);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(str, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}
And to convert it back:
CIFSPacket fromBytes(byte[] arr) {
CIFSPacket str = new CIFSPacket();
int size = Marshal.SizeOf(str);
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.Copy(arr, 0, ptr, size);
str = (CIFSPacket)Marshal.PtrToStructure(ptr, str.GetType());
Marshal.FreeHGlobal(ptr);
return str;
}
In your structure, you will need to put this before a string
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
public string Buffer;
And make sure SizeConst is as big as your biggest possible string.
And you should probably read this: http://msdn.microsoft.com/en-us/library/4ca6d5z7.aspx
Correct syntax looks like this. See MSDN.
SELECT *
FROM [FAEB].[dbo].[ExportaComisiones] AS f
JOIN [zCredifiel].[dbo].[optPerson] AS p
ON p.vTreasuryId COLLATE Latin1_General_CI_AS = f.RFC COLLATE Latin1_General_CI_AS
Hej man, why are you using this ?
dir /s/b/o:gn > f.txt (wrong one)
Don't you know what is that 'g' in '/o' ??
Check this out: http://www.computerhope.com/dirhlp.htm or dir /? for dir help
You should be using this instead:
dir /s/b/o:n > f.txt (right one)
This will work for null able dateTime parameter
. .
SearchUsingDate(DateTime? StartDate, DateTime? EndDate){
DateTime LastDate;
if (EndDate != null)
{
LastDate = (DateTime)EndDate;
LastDate = LastDate.AddDays(1);
EndDate = LastDate;
}
}
If you want to disable all the div's controls, you can try adding a transparent div on the div to disable, you gonna make it unclickable, also use fadeTo to create a disable appearance.
try this.
$('#DisableDiv').fadeTo('slow',.6);
$('#DisableDiv').append('<div style="position: absolute;top:0;left:0;width: 100%;height:100%;z-index:2;opacity:0.4;filter: alpha(opacity = 50)"></div>');
Doing
SET FOREIGN_KEY_CHECKS=0;
before the Operation can also do the trick.
A bit late but ... I found a link that I saved a couple of years ago and I thought it might be useful for you guys:
CDE: Automatically create portable Linux applications
http://www.pgbovine.net/cde.html
Execute the binary passing as a argument the name of the binary you want make portable, for example: nmap
./cde_2011-08-15_64bit nmap
The program will read all of libs linked to nmap and its dependencias and it will save all of them in a folder called cde-package/ (in the same directory that you are).
Remember, to launch the portable program you have to exec the binary located in cde-package/nmap.cde
Best regards
I use intellj idea and in windows in terminal type:
gradlew.bat run
it is working for me.
You can do something like this:
(SELECT
name, games, goals
FROM tblMadrid WHERE name = 'ronaldo')
UNION
(SELECT
name, games, goals
FROM tblBarcelona WHERE name = 'messi')
ORDER BY goals;
See, for example: https://dev.mysql.com/doc/refman/5.0/en/union.html
you could also grep the line out and then cut it like for instance:
grep 'text' filename | cut -c 1-5
You can do it by specifying alternating class names on the rows. I prefer using row0
and row1
, which means you can easily add them in, if the list is being built programmatically:
for ($i = 0; $i < 10; ++$i) {
echo '<tr class="row' . ($i % 2) . '">...</tr>';
}
Another way would be to use javascript. jQuery is being used in this example:
$('table tr:odd').addClass('row1');
Edit: I don't know why I gave examples using table rows... replace tr
with li
and table
with ul
and it applies to your example
Here's the basic approach,
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate = dateFormat.parse("2013-11-29");
Date endDate = dateFormat.parse("2013-12-4");
Calendar beginCalendar = Calendar.getInstance();
beginCalendar.setTime(beginDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
There is simple way to implement it. We can use Calendar.add method with loop. The minus days between beginDate and endDate, and the implemented code as below,
int minusDays = 0;
while (true) {
minusDays++;
// Day increasing by 1
beginCalendar.add(Calendar.DAY_OF_MONTH, 1);
if (dateFormat.format(beginCalendar.getTime()).
equals(dateFormat.format(endCalendar).getTime())) {
break;
}
}
System.out.println("The subtraction between two days is " + (minusDays + 1));**
if (typeof jQuery == 'undefined')) { ...
Or
if(!window.jQuery){
Will not works if cdn version not loaded, because browser will run through this condition and during it still downloading the rest of javascripts which needs jQuery and it returns error. Solution was to load scripts through that condition.
<script src="http://WRONGPATH.code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script><!-- WRONGPATH for test-->
<script type="text/javascript">
function loadCDN_or_local(){
if(!window.jQuery){//jQuery not loaded, take a local copy of jQuery and then my scripts
var scripts=['local_copy_jquery.js','my_javascripts.js'];
for(var i=0;i<scripts.length;i++){
scri=document.getElementsByTagName('head')[0].appendChild(document.createElement('script'));
scri.type='text/javascript';
scri.src=scripts[i];
}
}
else{// jQuery loaded can load my scripts
var s=document.getElementsByTagName('head')[0].appendChild(document.createElement('script'));
s.type='text/javascript';
s.src='my_javascripts.js';
}
}
window.onload=function(){loadCDN_or_local();};
</script>
I was getting the same error "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mylocaldb.hibernate_sequence' doesn't exist".
Using spring mvc 4.3.7 and hibernate version 5.2.9, application is made using spring java based configuration. Now I have to add the hibernate.id.new_generator_mappings
property mentioned by @Eva Mariam in my code like this:
@Autowired
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
sessionBuilder.addProperties(getHibernateProperties());
sessionBuilder.addAnnotatedClasses(User.class);
return sessionBuilder.buildSessionFactory();
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.id.new_generator_mappings","false");
return properties;
}
And it worked like charm.
Also worth noting window.scrollBy(dx,dy)
(ref)
With oracle 10.2g:
select level, sequence.NEXTVAL
from dual
connect by level <= (select max(pk) from tbl);
will set the current sequence value to the max(pk) of your table (i.e. the next call to NEXTVAL will give you the right result); if you use Toad, press F5 to run the statement, not F9, which pages the output (thus stopping the increment after, usually, 500 rows). Good side: this solution is only DML, not DDL. Only SQL and no PL-SQL. Bad side : this solution prints max(pk) rows of output, i.e. is usually slower than the ALTER SEQUENCE solution.
The format option %ai
was what I wanted:
%ai
: author date, ISO 8601-like format
--format="%ai"
Previous answers were good and correct, but in my opinion, an extra names
parameter will make it perfect, and it should be the recommended way, especially when the csv has no headers
.
usecols
and names
parametersdf = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])
or use header=None
to explicitly tells people that the csv
has no headers (anyway both lines are identical)
df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)
So that you can retrieve your data by
# with `names` parameter
df['colA']
df['colB']
instead of
# without `names` parameter
df[0]
df[1]
Based on read_csv, when names
are passed explicitly, then header
will be behaving like None
instead of 0
, so one can skip header=None
when names
exist.
If the need is only to prohibit the user from closing the window, this is a simple solution.
XAML code:
IsCloseButtonEnabled="False"
It's block the button.
For System.Timers.Timer, on separate thread, if SynchronizingObject is not set.
static System.Timers.Timer DummyTimer = null;
static void Main(string[] args)
{
try
{
Console.WriteLine("Main Thread Id: " + System.Threading.Thread.CurrentThread.ManagedThreadId);
DummyTimer = new System.Timers.Timer(1000 * 5); // 5 sec interval
DummyTimer.Enabled = true;
DummyTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnDummyTimerFired);
DummyTimer.AutoReset = true;
DummyTimer.Start();
Console.WriteLine("Hit any key to exit");
Console.ReadLine();
}
catch (Exception Ex)
{
Console.WriteLine(Ex.Message);
}
return;
}
static void OnDummyTimerFired(object Sender, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
return;
}
Output you'd see if DummyTimer fired on 5 seconds interval:
Main Thread Id: 9
12
12
12
12
12
...
So, as seen, OnDummyTimerFired is executed on Workers thread.
No, further complication - If you reduce interval to say 10 ms,
Main Thread Id: 9
11
13
12
22
17
...
This is because if prev execution of OnDummyTimerFired isn't done when next tick is fired, then .NET would create a new thread to do this job.
Complicating things further, "The System.Timers.Timer class provides an easy way to deal with this dilemma—it exposes a public SynchronizingObject property. Setting this property to an instance of a Windows Form (or a control on a Windows Form) will ensure that the code in your Elapsed event handler runs on the same thread on which the SynchronizingObject was instantiated."
Hans and DarkDust answer covered i386/i686 and amd64/x86_64, so there's no sense in revisiting them. This answer will focus on X32, and provide some info learned after a X32 port.
x32 is an ABI for amd64/x86_64 CPUs using 32-bit integers, longs and pointers. The idea is to combine the smaller memory and cache footprint from 32-bit data types with the larger register set of x86_64. (Reference: Debian X32 Port page).
x32 can provide up to about 30% reduction in memory usage and up to about 40% increase in speed. The use cases for the architecture are:
x32 is a somewhat recent addition. It requires kernel support (3.4 and above), distro support (see below), libc support (2.11 or above), and GCC 4.8 and above (improved address size prefix support).
For distros, it was made available in Ubuntu 13.04 or Fedora 17. Kernel support only required pointer to be in the range from 0x00000000 to 0xffffffff. From the System V Application Binary Interface, AMD64 (With LP64 and ILP32 Programming Models), Section 10.4, p. 132 (its the only sentence):
10.4 Kernel Support
Kernel should limit stack and addresses returned from system calls between 0x00000000 to 0xffffffff.
When booting a kernel with the support, you must use syscall.x32=y
option. When building a kernel, you must include the CONFIG_X86_X32=y
option. (Reference: Debian X32 Port page and X32 System V Application Binary Interface).
Here is some of what I have learned through a recent port after the Debian folks reported a few bugs on us after testing:
__x86_64__
(and friends) and __ILP32__
, but not __i386__
/__i686__
(and friends)__ILP32__
alone because it shows up unexpectedly under Clang and Sun Studiopushq
and popq
adcq
If you are looking for a test platform, then you can use Debian 8 or above. Their wiki page at Debian X32 Port has all the information. The 3-second tour: (1) enable X32 in the kernel at boot; (2) use debootstrap
to install the X32 chroot environment, and (3) chroot debian-x32
to enter into the environment and test your software.
A string can be escaped comprehensively and compactly using JSON.stringify. It is part of JavaScript as of ECMAScript 5 and supported by major newer browser versions.
str = JSON.stringify(String(str));
str = str.substring(1, str.length-1);
Using this approach, also special chars as the null byte, unicode characters and line breaks \r
and \n
are escaped properly in a relatively compact statement.
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET /a pid=1600
FOR /f "skip=3delims=" %%a IN ('tasklist') DO (
SET "found=%%a"
SET /a foundpid=!found:~26,8!
IF %pid%==!foundpid! echo found %pid%=!found:~0,24%!
)
GOTO :EOF
...set PID to suit your circumstance.
This worked for me
expo update 39.0.0 --npm
As my expo version was 38(Check in package.json).
Surprisingly nobody have mentioned all powerful SUDO. Had the same problem and sudo fixed it
var date1 = new Date("7/11/2010");
var date2 = new Date("8/11/2010");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24), 10);
alert(diffDays )
What about something like this?
<?php
$URL = "http://example.com";
$base = '<base href="'.$URL.'">';
$host = preg_replace('/^[^\/]+\/\//', '', $URL);
$tarray = explode('/', $host);
$host = array_shift($tarray);
$URI = '/' . implode('/', $tarray);
$content = '';
$fp = @fsockopen($host, 80, $errno, $errstr, 30);
if(!$fp) { echo "Unable to open socked: $errstr ($errno)\n"; exit; }
fwrite($fp,"GET $URI HTTP/1.0\r\n");
fwrite($fp,"Host: $host\r\n");
if( isset($_SERVER["HTTP_USER_AGENT"]) ) { fwrite($fp,'User-Agent: '.$_SERVER
["HTTP_USER_AGENT"]."\r\n"); }
fwrite($fp,"Connection: Close\r\n");
fwrite($fp,"\r\n");
while (!feof($fp)) { $content .= fgets($fp, 128); }
fclose($fp);
if( strpos($content,"\r\n") > 0 ) { $eolchar = "\r\n"; }
else { $eolchar = "\n"; }
$eolpos = strpos($content,"$eolchar$eolchar");
$content = substr($content,($eolpos + strlen("$eolchar$eolchar")));
if( preg_match('/<head\s*>/i',$content) ) { echo( preg_replace('/<head\s*>/i','<head>'.
$base,$content,1) ); }
else { echo( preg_replace('/<([a-z])([^>]+)>/i',"<\\1\\2>".$base,$content,1) ); }
?>
I had the same problem; In my application there are multiple exit() points and there was no way to know where exactly it exits, then I found out about this:
atexit(system("pause"));
or
atexit(cin.get());
This way it'll stop no matter where we exit in the program.
Be aware of the single quotes for the string format. This doesn't work:
Content="{Binding PlannedDateTime, StringFormat={}{0:yy.MM.dd HH:mm}}"
while this does:
Content="{Binding PlannedDateTime, StringFormat='{}{0:yy.MM.dd HH:mm}'}"
You shouldn't write your own browser-detection code - it's been done many times before. Use Modernizr to detect independent browser features instead. It's better to detect the various features than to detect entire browsers because various browsers may support different set of features and those features may even change through various versions of the same browser. If you detect the presence of a given feature, your code will likely work better in more browsers. This is especially true for the various mobile browsers.
When you run Modernizr, it'll update your HEAD
element's class
attribute so that it lists the various features of the browser that you're using - you can then use Javascript to query the attribute and decide what to do if a feature is present (or missing).
2015-03-30: Edited - Missing information has been added
To retrieve the current directory you can use the dynamic %cd%
variable that holds the current active directory
set "curpath=%cd%"
This generates a value with a ending backslash for the root directory, and without a backslash for the rest of directories. You can force and ending backslash for any directory with
for %%a in ("%cd%\") do set "curpath=%%~fa"
Or you can use another dynamic variable: %__CD__%
that will return the current active directory with an ending backslash.
Also, remember the %cd%
variable can have a value directly assigned. In this case, the value returned will not be the current directory, but the assigned value. You can prevent this with a reference to the current directory
for %%a in (".\") do set "curpath=%%~fa"
Up to windows XP, the %__CD__%
variable has the same behaviour. It can be overwritten by the user, but at least from windows 7 (i can't test it on Vista), any change to the %__CD__%
is allowed but when the variable is read, the changed value is ignored and the correct current active directory is retrieved (note: the changed value is still visible using the set
command).
BUT all the previous codes will return the current active directory, not the directory where the batch file is stored.
set "curpath=%~dp0"
It will return the directory where the batch file is stored, with an ending backslash.
BUT this will fail if in the batch file the shift
command has been used
shift
echo %~dp0
As the arguments to the batch file has been shifted, the %0
reference to the current batch file is lost.
To prevent this, you can retrieve the reference to the batch file before any shifting, or change the syntax to shift /1
to ensure the shift operation will start at the first argument, not affecting the reference to the batch file. If you can not use any of this options, you can retrieve the reference to the current batch file in a call to a subroutine
@echo off
setlocal enableextensions
rem Destroy batch file reference
shift
echo batch folder is "%~dp0"
rem Call the subroutine to get the batch folder
call :getBatchFolder batchFolder
echo batch folder is "%batchFolder%"
exit /b
:getBatchFolder returnVar
set "%~1=%~dp0" & exit /b
This approach can also be necessary if when invoked the batch file name is quoted and a full reference is not used (read here).
why not just pass an data an object with your key/value pairs then you don't have to worry about encoding
$.ajax({
type: "Post",
url: "getdata.php",
data:{
timestamp: timestamp,
uid: id,
uname: name
},
async: true,
cache: false,
success: function(data) {
};
}?);?
You simply have to do:
INSERT INTO def (catid, title, page, publish)
SELECT catid, title, 'page','yes' from `abc`
It looks like details
is an array of hashes. So item
inside of your block will be the whole hash. Therefore, to check the :qty
key, you'd do something like the following:
details.select{ |item| item[:qty] != "" }
That will give you all items where the :qty
key isn't an empty string.
Salvaging (and extending) the list from an old version of the Wikipedia page:
Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.
The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:
Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.
There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),
docutils
)JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.
Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.
The Nim compiler features the commands rst2html
and rst2tex
which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:
Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.
pip
-installable python package requires docutils
, which does the actual rendering. restview
's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
docutils
to render your document(s) to HTMLSome projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.
The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.
rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.
Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.
While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.
The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el
The vim-common
package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:
There is a rst mode for the Jed programmers editor.
gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.
Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).
Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).
It also provides a way to preview the resulting HTML, in a "viewrendered" pane.
The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.
PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.
The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.
NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.
Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.
Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.
Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.
BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.
TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.
Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.
E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.
PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).)
here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:
MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst>
and </rst>
.
MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.
There is a reStructuredText Parser for MoinMoin.
Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.
This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.
rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.
Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.
An Online reStructuredText editor can be used to play with the markup and see the results immediately.
WordPreSt reStructuredText plugin for WordPress. (PHP)
reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)
Pelican is a static blog generator that supports writing articles in ReST. (Python)
Hyde is a static website generator that supports ReST. (Python)
Acrylamid is a static blog generator that supports writing articles in ReST. (Python)
Nikola is a Static Site and Blog Generator that supports ReST. (Python)
Ipsum genera is a static blog generator written in Nim.
Yozuch is a static blog generator written in Python.
A programmer solution:
const int RADIUS = 64;
const int MATRIX_SIZE = RADIUS * 2;
bool matrix[MATRIX_SIZE][MATRIX_SIZE] = {0};
struct Point { int x; int y; };
Point lookupTable[MATRIX_SIZE * MATRIX_SIZE];
void init()
{
int numberOfOnBits = 0;
for (int x = 0 ; x < MATRIX_SIZE ; ++x)
{
for (int y = 0 ; y < MATRIX_SIZE ; ++y)
{
if (x * x + y * y < RADIUS * RADIUS)
{
matrix[x][y] = true;
loopUpTable[numberOfOnBits].x = x;
loopUpTable[numberOfOnBits].y = y;
++numberOfOnBits;
} // if
} // for
} // for
} // ()
Point choose()
{
int randomIndex = randomInt(numberOfBits);
return loopUpTable[randomIndex];
} // ()
The bitmap is only necessary for the explanation of the logic. This is the code without the bitmap:
const int RADIUS = 64;
const int MATRIX_SIZE = RADIUS * 2;
struct Point { int x; int y; };
Point lookupTable[MATRIX_SIZE * MATRIX_SIZE];
void init()
{
int numberOfOnBits = 0;
for (int x = 0 ; x < MATRIX_SIZE ; ++x)
{
for (int y = 0 ; y < MATRIX_SIZE ; ++y)
{
if (x * x + y * y < RADIUS * RADIUS)
{
loopUpTable[numberOfOnBits].x = x;
loopUpTable[numberOfOnBits].y = y;
++numberOfOnBits;
} // if
} // for
} // for
} // ()
Point choose()
{
int randomIndex = randomInt(numberOfBits);
return loopUpTable[randomIndex];
} // ()
If you type this command:
echo cd d:/some/path >> ~/.bashrc
Appends the line cd d:/some/path
to .bashrc
. The >>
creates a file if it doesn’t exist and then appends.
$Hour1 = "09:00 am";
$Hour = date("H:i", strtotime($Hour1));
You might also consider trying one of these approaches, since larger tables aren't exactly friendly on mobile even if it works:
http://elvery.net/demo/responsive-tables/
I'm partial to 'No More Tables' but that obviously depends on your application.
I think you want \b\w{1,10}\b
. The \b
matches a word boundary.
Of course, you could also replace the \b
and do ^\w{1,10}$
. This will match a word of at most 10 characters as long as its the only contents of the string. I think this is what you were doing before.
Since it's Java, you'll actually have to escape the backslashes: "\\b\\w{1,10}\\b"
. You probably knew this already, but it's gotten me before.
Might be, more safe alternative to "_ORACLE_SCRIPT"=true
is to change "_common_user_prefix"
from C##
to an empty string. When it's null - any name can be used for common user. Found there.
During changing that value you may face another issue - ORA-02095 - parameter cannot be modified, that can be fixed in a several ways, based on your configuration (source).
So for me worked that:
alter system set _common_user_prefix = ''; scope=spfile;
The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.
CONTIGUOUS NON-PRINTING Ruby Code
This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml
, etc.
This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>
DETAILS:
Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:
<%# if flash[:myErrors] %>
<%# if flash[:myErrors].any? %>
<%# if @post.id.nil? %>
<%# if @myPost!=-1 %>
<%# @post = @myPost %>
<%# else %>
<%# @post = Post.new %>
<%# end %>
<%# end %>
<%# end %>
<%# end %>
YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:
<%#
if flash[:myErrors] then
if flash[:myErrors].any? then
if @post.id.nil? then
if @myPost!=-1 then
@post = @myPost
else
@post = Post.new
end
end
end
end
%>
You can use regular expressions for this, so I think this is what you want:
select t.*
from test t
where not regexp_like(sampletext, '.*[^a-zA-Z0-9 .{}\[\]].*')
Try to avoid formatting in your query. You should return your data in a raw format and let the receiving application (e.g. a reporting service or end user app) do the formatting, i.e. rounding and so on.
Formatting the data in the server makes it harder (or even impossible) for you to further process your data. You usually want export the table or do some aggregation as well, like sum, average etc. As the numbers arrive as strings (varchar), there is usually no easy way to further process them. Some report designers will even refuse to offer the option to aggregate these 'numbers'.
Also, the end user will see the country specific formatting of the server instead of his own PC.
Also, consider rounding problems. If you round the values in the server and then still do some calculations (supposing the client is able to revert the number-strings back to a number), you will end up getting wrong results.
The following is an easy method to convert dates to different formats.
// Create a new DateTime object
$date = DateTime::createFromFormat('Y-m-d', '2016-03-25');
// Output the date in different formats
echo $date->format('Y-m-d')."\n";
echo $date->format('d-m-Y')."\n";
echo $date->format('m-d-Y')."\n";
You can use Cursor like that:
USE master
GO
DECLARE @SQL AS VARCHAR(255)
DECLARE @SPID AS SMALLINT
DECLARE @Database AS VARCHAR(500)
SET @Database = 'AdventureWorks2016CTP3'
DECLARE Murderer CURSOR FOR
SELECT spid FROM sys.sysprocesses WHERE DB_NAME(dbid) = @Database
OPEN Murderer
FETCH NEXT FROM Murderer INTO @SPID
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = 'Kill ' + CAST(@SPID AS VARCHAR(10)) + ';'
EXEC (@SQL)
PRINT ' Process ' + CAST(@SPID AS VARCHAR(10)) +' has been killed'
FETCH NEXT FROM Murderer INTO @SPID
END
CLOSE Murderer
DEALLOCATE Murderer
I wrote about that in my blog here: http://www.pigeonsql.com/single-post/2016/12/13/Kill-all-connections-on-DB-by-Cursor
I mostly use lstlistings in papers, but for coloured output (for slides) I use pygments instead.
You can make use of the following code incase you want to check the types of primitive data types.
// Returns 0 if the object type is equal to double
strcmp([myNumber objCType], @encode(double))
I fixed my error. just removed "Value" from this line:
If drv.Item("Quantity").Value < 5 Then
So it will look like
If drv.Item("Quantity") < 5 Then
Also you can use Android Debug Bridge (adb) to copy your file from Android device to folder on your PC:
adb pull /storage/emulated/0/AudioRecorder/1436854479696.mp4 <folder_on_your_PC_e.g. c:/temp>
And you can copy from device whole AudioRecorder
folder:
adb pull /storage/emulated/0/AudioRecorder <folder_on_your_PC_e.g. c:/temp>
There is a better solution now: Vertical align anything with just 3 lines of CSS
In computer programming, a callback is executable code that is passed as an argument to other code.
C# has delegates for that purpose. They are heavily used with events, as an event can automatically invoke a number of attached delegates (event handlers).
while it might not matter now here is a function which generate a float between 2 values.
#include <math.h>
float func_Uniform(float left, float right) {
float randomNumber = sin(rand() * rand());
return left + (right - left) * fabs(randomNumber);
}
Well, you have to iterate through your abstract type Foo and that depends on the methods available on that object. You don't have to loop through the ArrayList because this object grows automatically in Java. (Don't confuse it with an array in other programming languages)
Recommended reading. Lists in the Java Tutorial
Consider also .attr()
$("#roommate_but").attr("disabled", true);
worked for me.
Here is a solution I use in one of my project.
network_utils.telnet
import socket
from timeit import default_timer as timer
def telnet(hostname, port=23, timeout=1):
start = timer()
connection = socket.socket()
connection.settimeout(timeout)
try:
connection.connect((hostname, port))
end = timer()
delta = end - start
except (socket.timeout, socket.gaierror) as error:
logger.debug('telnet error: ', error)
delta = None
finally:
connection.close()
return {
hostname: delta
}
def test_telnet_is_null_when_host_unreachable(self):
hostname = 'unreachable'
response = network_utils.telnet(hostname)
self.assertDictEqual(response, {'unreachable': None})
def test_telnet_give_time_when_reachable(self):
hostname = '127.0.0.1'
response = network_utils.telnet(hostname, port=22)
self.assertGreater(response[hostname], 0)
Starting from Xcode 8, you can use the class property attribute as answered by Berbie.
However, in the implementation, you need to define both class getter and setter for the class property using a static variable in lieu of an iVar.
Sample.h
@interface Sample: NSObject
@property (class, retain) Sample *sharedSample;
@end
Sample.m
@implementation Sample
static Sample *_sharedSample;
+ ( Sample *)sharedSample {
if (_sharedSample==nil) {
[Sample setSharedSample:_sharedSample];
}
return _sharedSample;
}
+ (void)setSharedSample:(Sample *)sample {
_sharedSample = [[Sample alloc]init];
}
@end
to run mysqld as root user from command line you need to add the switch/options --user=root
This mistake i was doing is i was passing the whole url in domain attribute, it should be only domain name.
let cookie = HTTPCookie(properties: [
.domain: "example.com",
.path: "/",
.name: "MyCookieName",
.value: "MyCookieValue",
.secure: "TRUE",
])!
webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
I am not completely sure what you're trying to achieve by seeking to a specific offset and attempting to load individual values manually, the typical usage of the pickle
module is:
# save data to a file
with open('myfile.pickle','wb') as fout:
pickle.dump([1,2,3],fout)
# read data from a file
with open('myfile.pickle') as fin:
print pickle.load(fin)
# output
>> [1, 2, 3]
If you dumped a list, you'll load a list, there's no need to load each item individually.
you're saying that you got an error before you were seeking to the -5000 offset, maybe the file you're trying to read is corrupted.
If you have access to the original data, I suggest you try saving it to a new file and reading it as in the example.
You simply need to use semilogy instead of plot:
from pylab import *
import matplotlib.pyplot as pyplot
a = [ pow(10,i) for i in range(10) ]
fig = pyplot.figure()
ax = fig.add_subplot(2,1,1)
line, = ax.semilogy(a, color='blue', lw=2)
show()
You could use dplyr::mutate_if()
to convert all character columns or dplyr::mutate_at()
for select named character columns to factors:
library(dplyr)
# all character columns to factor:
df <- mutate_if(df, is.character, as.factor)
# select character columns 'char1', 'char2', etc. to factor:
df <- mutate_at(df, vars(char1, char2), as.factor)
Let us say we have to sort a list of objects in ascending order based on a particular property, in this example lets say we have to sort based on the "name" property, then below is the required code :
var list_Objects = [{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}];
Console.log(list_Objects); //[{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}]
list_Objects.sort(function(a,b){
return a["name"].localeCompare(b["name"]);
});
Console.log(list_Objects); //[{"name"="Abhi"},{"name"="Bob"},{"name"="Jay"}]
NOTE: This is mentioned in the question but restarting Visual Studio fixes the issue in most cases.
Updating Visual Studio to 'Update 2' got it working again.
Tools -> Extensions and Updates ->Visual Studio Update 2
As mentioned in the question and the link i posted therein, I'd already updated NuGet Package Manager to 3.4.4 prior to this and restarted to no avail, so I don't know if the combination of both these actions worked.
Fragments are of particular use in some cases like where we want to keep a navigation drawer in all our pages. You can inflate a frame layout with whatever fragment you want and still have access to the navigation drawer.
If you had used an activity, you would have had to keep the drawer in all activities which makes for redundant code. This is one interesting use of a fragment.
I'm new to Android and still think a fragment is helpful this way.
This is my list of extensions.
The list on this is pretty comprehensive, so I spent sometime to find the extensions that I need. Here is the snapshot. Hope it will help someone.
I tried installing Codemaid, and it appeared to be a nifty addon, but my Visual Studio response became very slow. Felt like some threads were doing some work all the time when Codemaid was on. So uninstalling for now.
Here is how it worked beautifully for me. In the window resources add the image.
<Image x:Key="delImg" >
<Image.Source>
<BitmapImage UriSource="Images/delitem.gif"></BitmapImage>
</Image.Source>
</Image>
Then the code goes like this.
Image img = new Image()
img.Source = ((Image)this.Resources["delImg"]).Source;
"this" is referring to the Window object
Constructor injection is used when the class cannot function without the dependent class.
Property injection is used when the class can function without the dependent class.
As a concrete example, consider a ServiceRepository which depends on IService to do its work. Since ServiceRepository cannot function usefully without IService, it makes sense to have it injected via the constructor.
The same ServiceRepository class may use a Logger to do tracing. The ILogger can be injected via Property injection.
Other common examples of Property injection are ICache (another aspect in AOP terminology) or IBaseProperty (a property in the base class).
I recommend using passthru
and handling the output buffer directly:
ob_start();
passthru('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
$output = ob_get_clean();
It might be most sensible to use multiprocessing.Pool
which produces a pool of worker processes based on the max number of cores available on your system, and then basically feeds tasks in as the cores become available.
The example from the standard docs (http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers) shows that you can also manually set the number of cores:
from multiprocessing import Pool
def f(x):
return x*x
if __name__ == '__main__':
pool = Pool(processes=4) # start 4 worker processes
result = pool.apply_async(f, [10]) # evaluate "f(10)" asynchronously
print result.get(timeout=1) # prints "100" unless your computer is *very* slow
print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"
And it's also handy to know that there is the multiprocessing.cpu_count()
method to count the number of cores on a given system, if needed in your code.
Edit: Here's some draft code that seems to work for your specific case:
import multiprocessing
def f(name):
print 'hello', name
if __name__ == '__main__':
pool = multiprocessing.Pool() #use all available cores, otherwise specify the number you want as an argument
for i in xrange(0, 512):
pool.apply_async(f, args=(i,))
pool.close()
pool.join()
A simple Javascript function that makes the content inside a page-element unselectable:
function makeUnselectable(elem) {
if (typeof(elem) == 'string')
elem = document.getElementById(elem);
if (elem) {
elem.onselectstart = function() { return false; };
elem.style.MozUserSelect = "none";
elem.style.KhtmlUserSelect = "none";
elem.unselectable = "on";
}
}
Your vector<string> userString
has size 0
, so the loop is never entered. You could start with a vector of a given size:
vector<string> userString(10);
string word;
string sentence;
for (decltype(userString.size()) i = 0; i < userString.size(); ++i)
{
cin >> word;
userString[i] = word;
sentence += userString[i] + " ";
}
although it is not clear why you need the vector at all:
string word;
string sentence;
for (int i = 0; i < 10; ++i)
{
cin >> word;
sentence += word + " ";
}
If you don't want to have a fixed limit on the number of input words, you can use std::getline
in a while
loop, checking against a certain input, e.g. "q"
:
while (std::getline(std::cin, word) && word != "q")
{
sentence += word + " ";
}
This will add words to sentence
until you type "q".
In build.gradle(Module:app) add this code
dependencies {
……..
compile 'com.google.android.gms:play-services:10.0.1’
……
}
If you still have a problem after that, then add this code in build.gradle(Module:app)
defaultConfig {
….
…...
multiDexEnabled true
}
dependencies {
…..
compile 'com.google.android.gms:play-services:10.0.1'
compile 'com.android.support:multidex:1.0.1'
}
Elliot inspired me to this solution - thanks:
aspectratio.png
is a completely transparent PNG-file with the size of your preferred aspect-ratio, in my case 30x10 pixels.
<div class="eyecatcher">
<img src="/img/aspectratio.png"/>
</div>
.eyecatcher img {
width: 100%;
background-repeat: no-repeat;
background-size: 100% 100%;
background-image: url(../img/autoresized-picture.jpg);
}
Please note: background-size
is a css3-feature which might not work with your target-browsers. You may check interoperability (f.e. on caniuse.com).
Here is how you can do it and it works fine
func refreshCollectionView(_ count: Int) {
let collectionViewHeight = collectionView.bounds.height
let collectionViewWidth = collectionView.bounds.width
let numberOfItemsThatCanInCollectionView = Int(collectionViewWidth / collectionViewHeight)
if numberOfItemsThatCanInCollectionView > count {
let totalCellWidth = collectionViewHeight * CGFloat(count)
let totalSpacingWidth: CGFloat = CGFloat(count) * (CGFloat(count) - 1)
// leftInset, rightInset are the global variables which I am passing to the below function
leftInset = (collectionViewWidth - CGFloat(totalCellWidth + totalSpacingWidth)) / 2;
rightInset = -leftInset
} else {
leftInset = 0.0
rightInset = -collectionViewHeight
}
collectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(0, leftInset, 0, rightInset)
}
Asterisk symbol (*) is used to check values in the array, not the array itself.
$validator = Validator::make($request->all(), [
"names" => "required|array|min:3",
"names.*" => "required|string|distinct|min:3",
]);
In the example above:
EDIT: Since Laravel 5.5 you can call validate() method directly on Request object like so:
$data = $request->validate([
"name" => "required|array|min:3",
"name.*" => "required|string|distinct|min:3",
]);
This is the way I've been doing this sort of stuff. Angular tends to favor declarative manipulation of the dom rather than a imperative one(at least that's the way I've been playing with it).
The markup
<table class="table">
<thead>
<tr>
<th>
<input type="checkbox"
ng-click="selectAll($event)"
ng-checked="isSelectedAll()">
</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="e in entities" ng-class="getSelectedClass(e)">
<td>
<input type="checkbox" name="selected"
ng-checked="isSelected(e.id)"
ng-click="updateSelection($event, e.id)">
</td>
<td>{{e.title}}</td>
</tr>
</tbody>
</table>
And in the controller
var updateSelected = function(action, id) {
if (action === 'add' && $scope.selected.indexOf(id) === -1) {
$scope.selected.push(id);
}
if (action === 'remove' && $scope.selected.indexOf(id) !== -1) {
$scope.selected.splice($scope.selected.indexOf(id), 1);
}
};
$scope.updateSelection = function($event, id) {
var checkbox = $event.target;
var action = (checkbox.checked ? 'add' : 'remove');
updateSelected(action, id);
};
$scope.selectAll = function($event) {
var checkbox = $event.target;
var action = (checkbox.checked ? 'add' : 'remove');
for ( var i = 0; i < $scope.entities.length; i++) {
var entity = $scope.entities[i];
updateSelected(action, entity.id);
}
};
$scope.getSelectedClass = function(entity) {
return $scope.isSelected(entity.id) ? 'selected' : '';
};
$scope.isSelected = function(id) {
return $scope.selected.indexOf(id) >= 0;
};
//something extra I couldn't resist adding :)
$scope.isSelectedAll = function() {
return $scope.selected.length === $scope.entities.length;
};
EDIT: getSelectedClass()
expects the entire entity but it was being called with the id of the entity only, which is now corrected
I solved this by overriding the default Content-Type:
const config = { headers: {'Content-Type': 'application/json'} };
axios.put(url, content, config).then(response => {
...
});
Based on m experience, the default Conent-Type is application/x-www-form-urlencoded for strings, and application/json for objects (including arrays). Your server probably expects JSON.
Make sure you have the access to the directory you are trying to spool. I tried to spool to root and it did not created the file (e.g c:\test.txt
). You can check where you are spooling by issuing spool
command.
You can pass the parameter(s) as a property of the function object, not as a parameter:
var f = this.someFunction; //use 'this' if called from class
f.parameter1 = obj;
f.parameter2 = this;
f.parameter3 = whatever;
setInterval(f, 1000);
Then in your function someFunction
, you will have access to the parameters. This is particularly useful inside classes where the scope goes to the global space automatically and you lose references to the class that called setInterval to begin with. With this approach, "parameter2" in "someFunction", in the example above, will have the right scope.
I used all the above answers and it was giving me errors so I tried
adb shell monkey -p com.yourpackage.name -c android.intent.category.LAUNCHER 1
and it worked. One advantage is you dont have to specify your launcher activity if you use this command.
There are a lot of solutions, here one: if you want only number erase the letters and the method receives a random and the result length.
public String GenerateRandom(Random oRandom, int iLongitudPin)
{
String sCharacters = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
int iLength = sCharacters.Length;
char cCharacter;
int iLongitudNuevaCadena = iLongitudPin;
String sRandomResult = "";
for (int i = 0; i < iLongitudNuevaCadena; i++)
{
cCharacter = sCharacters[oRandom.Next(iLength)];
sRandomResult += cCharacter.ToString();
}
return (sRandomResult);
}
go test -v -timeout 30s <path_to_package> -run ^(TestFuncRegEx)
go
test file in that package-run TestCaseFunc
I'd suggest using grep -i version
to make sure you get the right line containing the version string. If you have the environment variable JAVA_OPTIONS set, openjdk will print the java options before printing the version information. This version returns 1.6, 1.7 etc.
java -version 2>&1 | grep -i version | cut -d'"' -f2 | cut -d'.' -f1-2
spool "D:\test\test.txt"
select
a.ename
from
employee a
inner join department b
on
(
a.dept_id = b.dept_id
)
;
spool off
This query will spool the sql result in D:\test\test.txt
Use empty()
. It checks for both empty strings and null.
if (!empty($_POST['user'])) {
// do stuff
}
From the manual:
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Thanks Notable1, works for me with the tidytextr Create a dataframe with the name of files in one column and content in other.
diretorio <- "D:/base"
arquivos <- list.files(diretorio, pattern = "*.PDF")
quantidade <- length(arquivos)
#
df = NULL
for (k in 1:quantidade) {
nome = arquivos[k]
print(nome)
Sys.sleep(1)
dados = read_pdf(arquivos[k],ocr = T)
print(dados)
Sys.sleep(1)
df = rbind(df, data.frame(nome,dados))
Sys.sleep(1)
}
Encoding(df$text) <- "UTF-8"
It depends on what you are after in the Dictionary
Models.TestModels obj = new Models.TestModels();
foreach (var keyValuPair in obj.sp)
{
// KeyValuePair<int, dynamic>
}
foreach (var key in obj.sp.Keys)
{
// Int
}
foreach (var value in obj.sp.Values)
{
// dynamic
}
do a phpinfo(), and look for session.save_path. the directory there needs to have the correct permissions for the user and/or group that your webserver runs as
This just removes the highlight
class from everything that has the edgetoedge
class:
$(".edgetoedge").removeClass("highlight");
I think you want this:
$(".edgetoedge .highlight").removeClass("highlight");
The .edgetoedge .highlight
selector will choose everything that is a child of something with the edgetoedge
class and has the highlight
class.
You need to wrap all the html into one single element.
<template>
<div>
<div class="form-group">
<label for="avatar" class="control-label">Avatar</label>
<input type="file" v-on:change="fileChange" id="avatar">
<div class="help-block">
Help block here updated 4 ...
</div>
</div>
<div class="col-md-6">
<input type="hidden" name="avatar_id">
<img class="avatar" title="Current avatar">
</div>
</div>
</template>
<script>
export default{
methods: {
fileChange(){
console.log('Test of file input change')
}
}
}
</script>
For environments where here documents are unavailable (Makefile
, Dockerfile
, etc) you can often use printf
for a reasonably legible and efficient solution.
printf '%s\n' '#!/bin/sh' '# Second line' \
'# Third line' \
'# Conveniently mix single and double quotes, too' \
"# Generated $(date)" \
'# ^ the date command executes when the file is generated' \
'for file in *; do' \
' echo "Found $file"' \
'done' >outputfile
You just need one line:
ImageViewer1.Source = new BitmapImage(new Uri(@"\myserver\folder1\Customer Data\sample.png"));
I know this is an old thread, but I was running into the same problem and found HashSet to be very unreliable because given the same seed, GetHashCode() returned different codes. So, I thought, why not just use a List and hide the add method like this
public class UniqueList<T> : List<T>
{
public new void Add(T obj)
{
if(!Contains(obj))
{
base.Add(obj);
}
}
}
Because List uses the Equals method solely to determine equality, you can define the Equals method on your T type to make sure you get the desired results.
Not being a developer I found a solution in running multiple ps commands in one line. E.g:
powershell "& 'c:\path with spaces\to\executable.exe' -arguments ; second command ; etc
By placing a " (double quote) before the & (ampersand) it executes the executable. In none of the examples I have found this was mentioned. Without the double quotes the ps prompt opens and waits for input.
a for
loop is a construct that says "perform this operation n. times".
a foreach
loop is a construct that says "perform this operation against each value/object in this IEnumerable"
$myArr = array();
function someFuntion(array $myArr) {
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
return $myArr;
}
$myArr = someFunction($myArr);
Add this in your .htaccess file:
Options -Indexes
If it is not work for any reason, try this within your .htaccess file:
IndexIgnore *
You could initialize them to None
.
You need to name the entity that holds the association to User. For example,
... INNER JOIN ug.user u ...
That's the "path" the error message is complaining about -- path from UserGroup to User entity.
Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.
This worked for me and also worked with bootstrap tables
<style>
.table td, .table th {
font-size: 10px;
}
</style>
@Synxmax's answer is correct when using a Service
and the MediaPlayer
class, however you also need to declare the Service
in the Manifest for this to work, like so:
<service
android:enabled="true"
android:name="com.package.name.BackgroundSoundService" />
The Eclipse team with The Open University have prepared the following document, which includes creating proxy classes with tests. It might be what you are looking for.
http://www.eclipse.org/webtools/community/education/web/t320/Generating_a_client_from_WSDL.pdf
Everything is included in the Dynamic Web Project template.
In the project create a Web Service Client. This starts a wizard that has you point out a wsdl url and creates the client with tests for you.
The user guide (targeted at indigo though) for this task is found at http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.jst.ws.cxf.doc.user%2Ftasks%2Fcreate_client.html.
std::vector
is a template class that encapsulate a dynamic array1, stored in the heap, that grows and shrinks automatically if elements are added or removed. It provides all the hooks (begin()
, end()
, iterators, etc) that make it work fine with the rest of the STL. It also has several useful methods that let you perform operations that on a normal array would be cumbersome, like e.g. inserting elements in the middle of a vector (it handles all the work of moving the following elements behind the scenes).
Since it stores the elements in memory allocated on the heap, it has some overhead in respect to static arrays.
std::array
is a template class that encapsulate a statically-sized array, stored inside the object itself, which means that, if you instantiate the class on the stack, the array itself will be on the stack. Its size has to be known at compile time (it's passed as a template parameter), and it cannot grow or shrink.
It's more limited than std::vector
, but it's often more efficient, especially for small sizes, because in practice it's mostly a lightweight wrapper around a C-style array. However, it's more secure, since the implicit conversion to pointer is disabled, and it provides much of the STL-related functionality of std::vector
and of the other containers, so you can use it easily with STL algorithms & co. Anyhow, for the very limitation of fixed size it's much less flexible than std::vector
.
For an introduction to std::array
, have a look at this article; for a quick introduction to std::vector
and to the the operations that are possible on it, you may want to look at its documentation.
Make sure that the directory exists, you have permission to access it and add the file to the path to write the log:
File file = new File("D:/Data/" + item.getFileName());
hyperlink1.NavigateUrl = "#"; or
hyperlink1.attributes["href"] = "#"; or
<asp:HyperLink NavigateUrl="#" runat="server" />
LastLogon is the last time that the user logged into whichever domain controller you happen to have been load balanced to at the moment that you ran the GET-ADUser cmdlet, and is not replicated across the domain. You really should use LastLogonTimestamp if you want the time the last user logged in to any domain controller in your domain.
I use this trick for equal data bucketing. Instead of text result you get the number. Here is example for four buckets. Suppose you have data in A1:A100
range. Put this formula in B1:
=MAX(ROUNDUP(PERCENTRANK($A$1:$A$100,A1) *4,0),1)
Fill down the formula all across B column and you are done. The formula divides the range into 4 equal buckets and it returns the bucket number which the cell A1 falls into. The first bucket contains the lowest 25% of values.
Adjust the number of buckets according to thy wish:
=MAX(ROUNDUP(PERCENTRANK([Range],[OneCellOfTheRangeToTest]) *[NumberOfBuckets],0),1)
The number of observation in each bucket will be equal or almost equal. For example if you have a 100 observations and you want to split it into 3 buckets (like in your example) then the buckets will contain 33, 33, 34 observations. So almost equal. You do not have to worry about that - the formula works that out for you.
You can encapsulate this quite nicely in a func similar to what is below.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
fmt.Println(prompt())
}
func prompt(params ...string) string {
prompt := ": "
if len(params) > 0 {
prompt = params[0]
}
reader := bufio.NewReader(os.Stdin)
fmt.Print(prompt)
text, _ := reader.ReadString('\n')
return text
}
In this example, the prompt by default has a colon and a space in front of it . . .
:
. . . however you can override that by supplying a parameter to the prompt function.
prompt("Input here -> ")
This will result in a prompt like below.
Input here ->
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
You have to cast one (or both) of the arguments to the division operator to double
:
double firstSolution = (b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21);
Since you are performing the same calculation twice I'd recommend refactoring your code:
double determinant = a11 * a22 - a12 * a21;
double firstSolution = (b1 * a22 - b2 * a12) / determinant;
double secondSolution = (b2 * a11 - b1 * a21) / determinant;
This works in the same way, but now there is an implicit cast to double. This conversion from int
to double
is an example of a widening primitive conversion.
Window
->Show View
->device
(if not found ->Other
->Device
) in right most side, there is arrow, click that, you will see reset adb, just click and enjoy!! It worked for me.
For me I was trying to auto generate code, and needed to reuse a simple variable like "x" for multiple different classes so that I didn't have to keep generating new variable names. I found that I could limit the scope of a variable and reuse it multiple times if I just put the code in a curly brace section {}.
See the example:
public class Main
{
public void Execute()
{
// Execute new Foos and new Bars many times with same variable.
double a = 0;
double b = 0;
double c = 0;
double d = 0;
double e = 0;
double f = 0;
double length = 0;
double area = 0;
double size = 0;
{
Foo x = new Foo(5, 6).Execute();
a = x.A;
b = x.B;
c = x.C;
d = x.D;
e = x.E;
f = x.F;
}
{
Bar x = new Bar("red", "circle").Execute();
length = x.Length;
area = x.Area;
size = x.Size;
}
{
Foo x = new Foo(3, 10).Execute();
a = x.A;
b = x.B;
c = x.C;
d = x.D;
e = x.E;
f = x.F;
}
{
Bar x = new Bar("blue", "square").Execute();
length = x.Length;
area = x.Area;
size = x.Size;
}
}
}
public class Foo
{
public int X { get; set; }
public int Y { get; set; }
public double A { get; private set; }
public double B { get; private set; }
public double C { get; private set; }
public double D { get; private set; }
public double E { get; private set; }
public double F { get; private set; }
public Foo(int x, int y)
{
X = x;
Y = y;
}
public Foo Execute()
{
A = X * Y;
B = X + Y;
C = X / (X + Y + 1);
D = Y / (X + Y + 1);
E = (X + Y) / (X + Y + 1);
F = (Y - X) / (X + Y + 1);
return this;
}
}
public class Bar
{
public string Color { get; set; }
public string Shape { get; set; }
public double Size { get; private set; }
public double Area { get; private set; }
public double Length { get; private set; }
public Bar(string color, string shape)
{
Color = color;
Shape = shape;
}
public Bar Execute()
{
Length = Color.Length + Shape.Length;
Area = Color.Length * Shape.Length;
Size = Area * Length;
return this;
}
}
In VB I would have used the With and not needed variable "x" at all. Excluding the vb class definitions of Foo and Bar, the vb code is:
Public Class Main
Public Sub Execute()
Dim a As Double = 0
Dim b As Double = 0
Dim c As Double = 0
Dim d As Double = 0
Dim e As Double = 0
Dim f As Double = 0
Dim length As Double = 0
Dim area As Double = 0
Dim size As Double = 0
With New Foo(5, 6).Execute()
a = .A
b = .B
c = .C
d = .D
e = .E
f = .F
End With
With New Bar("red", "circle").Execute()
length = .Length
area = .Area
size = .Size
End With
With New Foo(3, 10).Execute()
a = .A
b = .B
c = .C
d = .D
e = .E
f = .F
End With
With New Bar("blue", "square").Execute()
length = .Length
area = .Area
size = .Size
End With
End Sub
End Class
A solution that helped me: Go to Tools > NuGet Package Manager > Manage NuGet Packaged for Solution... > Browse > Search for System.IO.Compression.ZipFile and install it
I tend to make my scripts all be relative to one another. That way I can use dirname:
#!/bin/sh
my_dir="$(dirname "$0")"
"$my_dir/other_script.sh"
The plugin vagrant-vbguest solved my problem:
$ vagrant plugin install vagrant-vbguest
Output:
$ vagrant reload
==> default: Attempting graceful shutdown of VM...
...
==> default: Machine booted and ready!
GuestAdditions 4.3.12 running --- OK.
==> default: Checking for guest additions in VM...
==> default: Configuring and enabling network interfaces...
==> default: Exporting NFS shared folders...
==> default: Preparing to edit /etc/exports. Administrator privileges will be required...
==> default: Mounting NFS shared folders...
==> default: VM already provisioned. Run `vagrant provision` or use `--provision` to force it
Just make sure you are running the latest version of VirtualBox
I have a simpler method that works for me. Basically, remember what the hash actually is in HTML. It's an anchor link to a Name tag. That's why it scrolls...the browser is attempting to scroll to an anchor link. So, give it one!
<a name="home"></a><a name="firstsection"></a><a name="secondsection"></a><a name="thirdsection"></a>
Name your section divs with classes instead of IDs.
In your processing code, strip off the hash mark and replace with a dot:
var trimPanel = loadhash.substring(1); //lose the hash var dotSelect = '.' + trimPanel; //replace hash with dot $(dotSelect).addClass("activepanel").show(); //show the div associated with the hash.
Finally, remove element.preventDefault or return: false and allow the nav to happen. The window will stay at the top, the hash will be appended to the address bar url, and the correct panel will open.
categories_posts
and categories_news
start with substring 'categories_' then it is enough to check that developer_configurations_cms.cfg_name_unique
starts with 'categories' instead of check if it contains the given substring. Translating all that into a query:
SELECT *
FROM developer_configurations_cms
WHERE developer_configurations_cms.cat_id = '1'
AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%'
AND developer_configurations_cms.cfg_name_unique NOT LIKE 'categories%'
Delete all the apk files from platfroms >> android >> build >> generated >> outputs >> apk and run command cordova run android
Don't forget DataFrame.tail
! e.g. df1.tail(10)
"^.*$"
literally just means select everything
"^" // anchors to the beginning of the line
".*" // zero or more of any character
"$" // anchors to end of line
Check std::mismatch
method of C++.
comparing vectors has been discussed on DaniWeb forum and also answered.
Check the below SO post. will helpful for you. they have achieved the same with different-2 method.
For me pros of emacs are,
The answers here are straightforward but only apply to a 1 dimensional array. For multi-dimensional arrays, checking for null is a straightforward way to tell if the element exists. Example code here checks for null. Note the try/catch block is [probably] overkill but it makes the block bomb-proof.
public ItemContext GetThisElement(int row,
int col)
{
ItemContext ctx = null;
if (rgItemCtx[row, col] != null)
{
try
{
ctx = rgItemCtx[row, col];
}
catch (SystemException sex)
{
ctx = null;
// perhaps do something with sex properties
}
}
return (ctx);
}
You can try a simple ffmpeg wrapper .NET from here : http://ivolo.mit.edu/post/Convert-Audio-Video-to-Any-Format-using-C.aspx
You have to queue the rest of your request for it to work.
var elems = $(parentSelect).nextAll();
var lastID = elems.length - 1;
elems.each( function(i) {
$(this).fadeOut(200, function() {
$(this).remove();
if (i == lastID) {
$j(this).queue("fx",function(){ doMyThing;});
}
});
});
I want to return odd numbers of an array
If i read that correctly, you want something like this?
List<Integer> getOddNumbers(int[] integers) {
List<Integer> oddNumbers = new ArrayList<Integer>();
for (int i : integers)
if (i % 2 != 0)
oddNumbers.add(i);
return oddNumbers;
}
Late reply, but adding that Mongoose also has the concept of Subdocuments
With this syntax, you should be able to reference your userSchema
as a type in your postSchema
like so:
var userSchema = new Schema({
twittername: String,
twitterID: Number,
displayName: String,
profilePic: String,
});
var postSchema = new Schema({
name: String,
postedBy: userSchema,
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
Note the updated postedBy
field with type userSchema
.
This will embed the user object within the post, saving an extra lookup required by using a reference. Sometimes this could be preferable, other times the ref/populate route might be the way to go. Depends on what your application is doing.
Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:
Sub FilterAndCopy()
Dim LastRow As Long
Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
.Range("$A:$E").AutoFilter
.Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
.Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
.Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
.Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub
As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.
PHP Instead of using alphabetical sorting, use the ASCII value of the character to make the comparison. Lowercase letters have a higher ASCII value than capitals. It's better to use the identity operator === to make this sort of comparison. strcmp() is a function to perform binary safe string comparisons. It takes two strings as arguments and returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. There is also a case-insensitive version named strcasecmp() that first converts strings to lowercase and then compares them.
This is default by iOS7 design. try to do the below:
[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
You can set the 'Separator Inset' from the storyboard:
jQuery.Deferred() can simplify management of asynchronous sequencing and error handling.
polling_active = true // set false to interrupt polling
function initiate_polling()
{
$.Deferred().resolve() // optional boilerplate providing the initial 'then()'
.then( () => $.Deferred( d=>setTimeout(()=>d.resolve(),5000) ) ) // sleep
.then( () => $.get('/my-api') ) // initiate AJAX
.then( response =>
{
if ( JSON.parse(response).my_result == my_target ) polling_active = false
if ( ...unhappy... ) return $.Deferred().reject("unhappy") // abort
if ( polling_active ) initiate_polling() // iterative recursion
})
.fail( r => { polling_active=false, alert('failed: '+r) } ) // report errors
}
This is an elegant approach, but there are some gotchas...
then()
to fall through immediately, the callback should return another thenable object (probably another Deferred
), which the sleep and ajax lines both do.//Disable future dates after current date
$("#datepicker").datepicker('setEndDate', new Date());
//Disable past dates after current date
$("#datepicker").datepicker('setEndDate', new Date());
it turns out that I got this error because my requested module is not bundled in the minification prosses
due to path misspelling
so make sure that your module exists in minified js file (do search for a word within it to be sure)
The SimpleDateFormat class allows you to parse a String
into a java.util.Date
object. Once you have the Date object, you can get the milliseconds since the epoch by calling Date.getTime()
.
The full example:
String myDate = "2014/10/29 18:10:45";
//creates a formatter that parses the date in the given format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long timeInMillis = date.getTime();
Note that this gives you a long
and not a double, but I think that's probably what you intended. The documentation for the SimpleDateFormat
class has tons on information on how to set it up to parse different formats.
A simple solution would be to configure static http headers needed for all calls in the bean configuration of the RestTemplate:
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate getRestTemplate(@Value("${did-service.bearer-token}") String bearerToken) {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add((request, body, clientHttpRequestExecution) -> {
HttpHeaders headers = request.getHeaders();
if (!headers.containsKey("Authorization")) {
String token = bearerToken.toLowerCase().startsWith("bearer") ? bearerToken : "Bearer " + bearerToken;
request.getHeaders().add("Authorization", token);
}
return clientHttpRequestExecution.execute(request, body);
});
return restTemplate;
}
}
Suppose you have this function:
var Foo = function(){
this.A = 1;
this.B = 2;
};
If you call this as a standalone function like so:
Foo();
Executing this function will add two properties to the window
object (A
and B
). It adds it to the window
because window
is the object that called the function when you execute it like that, and this
in a function is the object that called the function. In Javascript at least.
Now, call it like this with new
:
var bar = new Foo();
What happens when you add new
to a function call is that a new object is created (just var bar = new Object()
) and that the this
within the function points to the new Object
you just created, instead of to the object that called the function. So bar
is now an object with the properties A
and B
. Any function can be a constructor, it just doesn't always make sense.
To get around this issue, wrap your select statement in a CTE, and then you can query against the CTE and use the windowed function's results in the where clause.
WITH MyCte AS
(
select employee_id,
RowNum = row_number() OVER ( order by employee_id )
from V_EMPLOYEE
ORDER BY Employee_ID
)
SELECT employee_id
FROM MyCte
WHERE RowNum > 0
In System.Web.Mvc.Html ( in System.Web.Mvc.dll ) the begin form is defined like:- Details
BeginForm ( this HtmlHelper htmlHelper, string actionName, string
controllerName, object routeValues, FormMethod method, object htmlAttributes)
Means you should use like this :
Html.BeginForm( string actionName, string controllerName,object routeValues, FormMethod method, object htmlAttributes)
So, it worked in MVC 4
@using (Html.BeginForm(null, null, new { @id = string.Empty }, FormMethod.Post,
new { @id = "signupform" }))
{
<input id="TRAINER_LIST" name="TRAINER_LIST" type="hidden" value="">
<input type="submit" value="Create" id="btnSubmit" />
}
I cannot add comment so I will use this
in a vbs run that and have fun figuring out why the 2 give a result of 2
you can't trust round
msgbox round(1.5) 'result to 2
msgbox round(2.5) 'yes, result to 2 too
Please see below image and apply changes in SqlServer :
first right click on Database --> Task --> Restore --> Select Backup File --> Finally Apply Change in Options Tab.
git pull
wants you to either remove or save your current work so that the merge it triggers doesn't cause conflicts with your uncommitted work. Note that you should only need to remove/save untracked files if the changes you're pulling create files in the same locations as your local uncommitted files.
git checkout -f
git clean -fd
git stash
git stash -u
git pull
:git stash pop
As if often happens, your question suffers from a serious terminological error/ambiguity. In common speech it usually doesn't matter, but in the context of this specific problem it is critically important.
You see, there's no such thing as "hex value" and "decimal value" (or "hex number" and "decimal number"). "Hex" and "decimal" are properties of representations of values. Meanwhile, values (or numbers) by themselves have no representation, so they can't be "hex" or "decimal". For example, 0xF
and 15
in C syntax are two different representations of the same number.
I would guess that your question, the way it is stated, suggests that you need to convert ASCII hex representation of a value (i.e. a string) into a ASCII decimal representation of a value (another string). One way to do that is to use an integer representation as an intermediate one: first, convert ASCII hex representation to an integer of sufficient size (using functions from strto...
group, like strtol
), then convert the integer into the ASCII decimal representation (using sprintf
).
If that's not what you need to do, then you have to clarify your question, since it is impossible to figure it out from the way your question is formulated.
Why not just wrap an anchor tag around a button element.
<a href="somepage.html"><button type="button">Text of Some Page</button></a>
This will work for IE9+, Chrome, Safari, Firefox, and probably Opera.
The Django documentation for database queries includes a section on copying model instances. Assuming your primary keys are autogenerated, you get the object you want to copy, set the primary key to None
, and save the object again:
blog = Blog(name='My blog', tagline='Blogging is easy')
blog.save() # blog.pk == 1
blog.pk = None
blog.save() # blog.pk == 2
In this snippet, the first save()
creates the original object, and the second save()
creates the copy.
If you keep reading the documentation, there are also examples on how to handle two more complex cases: (1) copying an object which is an instance of a model subclass, and (2) also copying related objects, including objects in many-to-many relations.
Note on miah's answer: Setting the pk to None
is mentioned in miah's answer, although it's not presented front and center. So my answer mainly serves to emphasize that method as the Django-recommended way to do it.
Historical note: This wasn't explained in the Django docs until version 1.4. It has been possible since before 1.4, though.
Possible future functionality: The aforementioned docs change was made in this ticket. On the ticket's comment thread, there was also some discussion on adding a built-in copy
function for model classes, but as far as I know they decided not to tackle that problem yet. So this "manual" way of copying will probably have to do for now.
Classic technique (escape metacharacters):
if [ \( "$g" -eq 1 -a "$c" = "123" \) -o \( "$g" -eq 2 -a "$c" = "456" \) ]
then echo abc
else echo efg
fi
I've enclosed the references to $g
in double quotes; that's good practice, in general. Strictly, the parentheses aren't needed because the precedence of -a
and -o
makes it correct even without them.
Note that the -a
and -o
operators are part of the POSIX specification for test
, aka [
, mainly for backwards compatibility (since they were a part of test
in 7th Edition UNIX, for example), but they are explicitly marked as 'obsolescent' by POSIX. Bash (see conditional expressions) seems to preempt the classic and POSIX meanings for -a
and -o
with its own alternative operators that take arguments.
With some care, you can use the more modern [[
operator, but be aware that the versions in Bash and Korn Shell (for example) need not be identical.
for g in 1 2 3
do
for c in 123 456 789
do
if [[ ( "$g" -eq 1 && "$c" = "123" ) || ( "$g" -eq 2 && "$c" = "456" ) ]]
then echo "g = $g; c = $c; true"
else echo "g = $g; c = $c; false"
fi
done
done
Example run, using Bash 3.2.57 on Mac OS X:
g = 1; c = 123; true
g = 1; c = 456; false
g = 1; c = 789; false
g = 2; c = 123; false
g = 2; c = 456; true
g = 2; c = 789; false
g = 3; c = 123; false
g = 3; c = 456; false
g = 3; c = 789; false
You don't need to quote the variables in [[
as you do with [
because it is not a separate command in the same way that [
is.
Isn't it a classic question?
I would have thought so. However, there is another alternative, namely:
if [ "$g" -eq 1 -a "$c" = "123" ] || [ "$g" -eq 2 -a "$c" = "456" ]
then echo abc
else echo efg
fi
Indeed, if you read the 'portable shell' guidelines for the autoconf
tool or related packages, this notation — using '||
' and '&&
' — is what they recommend. I suppose you could even go so far as:
if [ "$g" -eq 1 ] && [ "$c" = "123" ]
then echo abc
elif [ "$g" -eq 2 ] && [ "$c" = "456" ]
then echo abc
else echo efg
fi
Where the actions are as trivial as echoing, this isn't bad. When the action block to be repeated is multiple lines, the repetition is too painful and one of the earlier versions is preferable — or you need to wrap the actions into a function that is invoked in the different then
blocks.
In my case the error was still there, because my system used upgraded Java. If you are using Java 10, modify the compileOptions:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_10
targetCompatibility JavaVersion.VERSION_1_10
}
Add this class in .css class
.scrol {
font: bold 14px Arial;
border:1px solid black;
width:100% ;
color:#616D7E;
height:20px;
overflow:scroll;
overflow-y:scroll;
overflow-x:hidden;
}
and use the class in div. like here.
<div> <p class = "scrol" id = "title">-</p></div>
I have attached image , you see the out put of the above code
Those of us using Python 3.x should do this:
python -c "import sys; print(sys.path)"
I created a small working example that copies a source folder to another destination folder in just a few steps (based on shift66's answer using ncp):
Step 1 - Install ncp module:
npm install ncp --save
Step 2 - create copy.js (modify the srcPath and destPath variables to whatever you need):
var path = require('path');
var ncp = require('ncp').ncp;
ncp.limit = 16;
var srcPath = path.dirname(require.main.filename); // Current folder
var destPath = '/path/to/destination/folder'; // Any destination folder
console.log('Copying files...');
ncp(srcPath, destPath, function (err) {
if (err) {
return console.error(err);
}
console.log('Copying files complete.');
});
Step 3 - run
node copy.js
You can use
value.ToString(CultureInfo.InvariantCulture)
to get exact double value without putting precision.
I had the same problem. Now its working fine after doing below changes.
https://www.google.com/settings/security/lesssecureapps
You should change the "Access for less secure apps" to Enabled (it was enabled, I changed to disabled and than back to enabled). After a while I could send email.
Friend comes handy when you are building a container and you want to implement an iterator for that class.
Use router.back()
directly to go back/route-back programmatic on vue-router.
well for what its worth now... JsonProperty is ALSO used to specify getter and setter methods for the variable apart from usual serialization and deserialization. For example suppose you have a payload like this:
{
"check": true
}
and a Deserializer class:
public class Check {
@JsonProperty("check") // It is needed else Jackson will look got getCheck method and will fail
private Boolean check;
public Boolean isCheck() {
return check;
}
}
Then in this case JsonProperty annotation is neeeded. However if you also have a method in the class
public class Check {
//@JsonProperty("check") Not needed anymore
private Boolean check;
public Boolean getCheck() {
return check;
}
}
Have a look at this documentation too: http://fasterxml.github.io/jackson-annotations/javadoc/2.3.0/com/fasterxml/jackson/annotation/JsonProperty.html
You need to use one of the following commands. Which one depends on different-2 OS and software you have and use.
sudo easy_install mysql-python (mix os)
sudo pip install mysql-python (mix os)
sudo apt-get install python-mysqldb (Linux Ubuntu, ...)
cd /usr/ports/databases/py-MySQLdb && make install clean (FreeBSD)
yum install MySQL-python (Linux Fedora, CentOS ...)