There's a oneliner for this one.
You can simply run,
docker run -v /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat
This will copy the war file to webapps directory and get your app running in no time.
Something Like this, Two Conditions Two Columns
SELECT ITEMSREQ.ITEM AS ITEM,
ITEMSREQ.CANTIDAD AS CANTIDAD,
(CASE WHEN ITEMSREQ.ITEMAPROBADO=1 THEN 'APROBADO'
WHEN ITEMSREQ.ITEMAPROBADO=0 THEN 'NO APROBADO'
END) AS ITEMS,
(CASE
WHEN ITEMSREQ.ITEMAPROBADO = 0
THEN CASE WHEN REQUISICIONES.RECIBIDA IS NULL THEN 'ITEM NO APROBADO PARA ENTREGA' END
WHEN ITEMSREQ.ITEMAPROBADO = 1
THEN CASE WHEN REQUISICIONES.RECIBIDA IS NULL THEN 'ITEM AUN NO RECIBIDO'
WHEN REQUISICIONES.RECIBIDA=1 THEN 'RECIBIDO'
WHEN REQUISICIONES.RECIBIDA=0 THEN 'NO RECIBIDO'
END
END)
AS RECIBIDA
FROM ITEMSREQ
INNER JOIN REQUISICIONES ON
ITEMSREQ.CNSREQ = REQUISICIONES.CNSREQ
A great substitute for np.isnan() and pd.isnull() is
for i in range(0,a.shape[0]):
if(a[i]!=a[i]):
//do something here
//a[i] is nan
since only nan is not equal to itself.
You need to access a geocoding service (i.e. from Google), there is no simple formula to transfer addresses to geo coordinates.
I usually start with grep, to get the regexp right.
# [multiple failed attempts here]
grep '[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*' file # good?
grep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' file # good enough
Then I'd try and convert it to sed
to filter out the rest of the line. (After reading this thread, you and I aren't going to do that anymore: we're going to use grep -o
instead)
sed -ne 's/.*\([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\).*/\1/p # FAIL
That's when I usually get annoyed with sed
for not using the same regexes as anyone else. So I move to perl
.
$ perl -nle '/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/ and print $&'
Perl's good to know in any case. If you've got a teeny bit of CPAN installed, you can even make it more reliable at little cost:
$ perl -MRegexp::Common=net -nE '/$RE{net}{IPV4}/ and say $&' file(s)
For windows. if Ctrl+p doesn't always work use Ctrl+shift+n instead.
To start:
Pros:
Cons:
Code that calls COM object dlls (for example, to read proprietary data files), may work fine in a user interface but hang mysteriously from a service. The reason is that as of .Net 2.0 user interfaces assume STA (thread-safe) while services assume MTA ((before that, services assumed STA). Having to create an STA thread for every COM call in a service can add significant overhead.
Run ipconfig /flushdns from a command prompt. Apparently some people seem to think I posted this answer for sheer fun. That's why they down voted my answer. Perhaps an explanation would help them. When I used "SVN Update" it said it can't connect to the SVN repository although I could ping the server. After running ipconfig /flushdns the issue was fixed.
Use find. Seriously, it is the best way because then you can really see what files it's operating on:
find . -name "*.sql" -exec grep -H "slow" {} \;
Note, the -H is mac-specific, it shows the filename in the results.
Chrome and Safari has a restriction on using ajax with local resources. That's why it's throwing an error like
Origin null is not allowed by Access-Control-Allow-Origin.
Solution: Use firefox or upload your data to a temporary server. If you still want to use Chrome, start it with the below option;
--allow-file-access-from-files
More info how to add the above parameter to your Chrome: Right click the Chrome icon on your task bar, right click the Google Chrome on the pop-up window and click properties and add the above parameter inside the Target textbox under Shortcut tab. It will like as below;
C:\Users\XXX_USER\AppData\Local\Google\Chrome\Application\chrome.exe --allow-file-access-from-files
Hope this will help!
Actualy we can use the two providers(GPS & NETWORK). And they just share a public listener:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10 * 1000, (float) 10.0, listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 90 * 1000, (float) 10.0, listener);
This is necessary because the OnLocationChanged()
method always need to be called in time.
I used the below code to disable BT when my app launches and works fine. Not sure if this the correct way to implement this as google recommends not using "bluetooth.disable();" without explicit user action to turn off Bluetooth.
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
bluetooth.disable();
I only used the below permission.
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:
Dim MyVar as string = "some text ""hello"" "
This will give the MyVar
variable a value of some text "hello"
.
Some time you can solve problem through MySQL Administrator wizard. In
Startup variables > Advanced >
and set Def. char Set:utf8
Maybe this config need restart MySQL.
realpath
is probably best
But ...
The initial question was very confused to start with, with an example poorly related to the question as stated.
The selected answer actually answers the example given, and not at all the question in the title. The first command is that answer (is it really ? I doubt), and could do as well without the '/'. And I fail to see what the second command is doing.
Several issues are mixed :
changing a relative pathname into an absolute one, whatever it
denotes, possibly nothing.
(Typically, if you issue a command such as touch foo/bar
, the
pathname foo/bar
must exist for you, and possibly be used in
computation, before the file is actually created.)
there may be several absolute pathname that denote the same file (or potential file), notably because of symbolic links (symlinks) on the path, but possibly for other reasons (a device may be mounted twice as read-only). One may or may not want to resolve explicity such symlinks.
getting to the end of a chain of symbolic links to a non-symlink file or name. This may or may not yield an absolute path name, depending on how it is done. And one may, or may not want to resolve it into an absolute pathname.
The command readlink foo
without option gives an answer only if its
argument foo
is a symbolic link, and that answer is the value of that
symlink. No other link is followed. The answer may be a relative path:
whatever was the value of the symlink argument.
However, readlink
has options (-f -e or -m) that will work for all
files, and give one absolute pathname (the one with no symlinks) to
the file actually denoted by the argument.
This works fine for anything that is not a symlink, though one might
desire to use an absolute pathname without resolving the intermediate
symlinks on the path. This is done by the command realpath -s foo
In the case of a symlink argument, readlink
with its options will
again resolve all symlinks on the absolute path to the argument, but
that will also include all symlinks that may be encountered by
following the argument value. You may not want that if you desired an
absolute path to the argument symlink itself, rather than to whatever
it may link to. Again, if foo
is a symlink, realpath -s foo
will
get an absolute path without resolving symlinks, including the one
given as argument.
Without the -s
option, realpath
does pretty much the same as
readlink
, except for simply reading the value of a link, as well as several
other things. It is just not clear to me why readlink
has its
options, creating apparently an undesirable redundancy with
realpath
.
Exploring the web does not say much more, except that there may be some variations across systems.
Conclusion : realpath
is the best command to use, with the most
flexibility, at least for the use requested here.
Try to change the loop like this:
for line in $(cat filename); do
read input
echo $input;
done
Unit test:
for line in $(cat /etc/passwd); do
read input
echo $input;
echo "[$line]"
done
I'm the creator of Restangular.
You can take a look at this CRUD example to see how you can PUT/POST/GET elements without all that URL configuration and $resource configuration that you need to do. Besides it, you can then use nested resources without any configuration :).
Check out this plunkr example:
http://plnkr.co/edit/d6yDka?p=preview
You could also see the README and check the documentation here https://github.com/mgonto/restangular
If you need some feature that's not there, just create an issue. I usually add features asked within a week, as I also use this library for all my AngularJS projects :)
Hope it helps!
Method names which are same as the class name are called constructors. Constructors do not have a return type. So correct as:
private Flow()
{
X = x;
Y = y;
}
Or rename the function as:
private void DoFlow()
{
X = x;
Y = y;
}
Though the whole code does not make any sense to me.
A nice practical use of this is if you want to make your own HtmlHelper
extensions. For example, I hate trying to remember the <link>
tag syntax, so I've created my own extension method to make a <link>
tag:
<Extension()> _
Public Function CssBlock(ByVal html As HtmlHelper, ByVal src As String, ByVal Optional ByVal htmlAttributes As Object = Nothing) As MvcHtmlString
Dim tag = New TagBuilder("link")
tag.MergeAttribute("type", "text/css")
tag.MergeAttribute("rel", "stylesheet")
tag.MergeAttribute("href", src)
tag.MergeAttributes(New RouteValueDictionary(htmlAttributes))
Dim result = tag.ToString(TagRenderMode.Normal)
Return MvcHtmlString.Create(result)
End Function
I could have returned String
from this method, but if I had the following would break:
<%: Html.CssBlock(Url.Content("~/sytles/mysite.css")) %>
With MvcHtmlString
, using either <%: ... %>
or <%= ... %>
will both work correctly.
Your syntax is incorrect, you should pass the value as the second parameter:
jQuery(this).prev("li").attr("id","newId");
I configured the app.config
with the tool for EntLib configuration and set up my LoggingConfiguration
block. Then I copied this into the DotNetConfig.xsd
. Of course, it does not cover all attributes, only the ones I added but it does not display those annoying info messages anymore.
<xs:element name="loggingConfiguration">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="add">
<xs:complexType>
<xs:attribute name="fileName" type="xs:string" use="required" />
<xs:attribute name="footer" type="xs:string" use="required" />
<xs:attribute name="formatter" type="xs:string" use="required" />
<xs:attribute name="header" type="xs:string" use="required" />
<xs:attribute name="rollFileExistsBehavior" type="xs:string" use="required" />
<xs:attribute name="rollInterval" type="xs:string" use="required" />
<xs:attribute name="rollSizeKB" type="xs:unsignedByte" use="required" />
<xs:attribute name="timeStampPattern" type="xs:string" use="required" />
<xs:attribute name="listenerDataType" type="xs:string" use="required" />
<xs:attribute name="traceOutputOptions" type="xs:string" use="required" />
<xs:attribute name="filter" type="xs:string" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="formatters">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="template" type="xs:string" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="logFilters">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="enabled" type="xs:boolean" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="categorySources">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="add">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="specialSources">
<xs:complexType>
<xs:sequence>
<xs:element name="allEvents">
<xs:complexType>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="notProcessed">
<xs:complexType>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="errors">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="tracingEnabled" type="xs:boolean" use="required" />
<xs:attribute name="defaultCategory" type="xs:string" use="required" />
<xs:attribute name="logWarningsWhenNoCategoriesMatch" type="xs:boolean" use="required" />
</xs:complexType>
</xs:element>
In Python 3.5.1 things like these work:
c = input('Enter number:')
print (int(float(c)))
print (round(float(c)))
and
Enter number: 4.7
4
5
George.
If you pass jQuery a function, it will not run until the page has loaded:
<script type="text/javascript">
$(function() {
//your header rotation code goes here
});
</script>
When using the data on the server, your characters can reach with the addition of slashes eg if string = {"hello"} comes as string = {\ "hello \"} to solve the following function can be used later to use json decode.
<?php
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$array = $_POST['jObject'];
$array = stripslashes_deep($array);
$data = json_decode($array, true);
print_r($data);
?>
The connection to adb is down, and a severe error has occured.
[2011-12-19 11:45:09 - RayhReport] You must restart adb and Eclipse.
[2011-12-19 11:45:09 - RayhReport] Please ensure that adb is correctly located at 'D:\android-sdk-windows\tools\adb.exe' and can be executed.
When you go to D:\android-sdk-windows\tools\adb.exe
path then you see the text file,the name of file is "adb_has_moved" thats means your adb.exe
is moved to platform-tools copied down the adb.exe and paste in tools folder and run it. I'm sure it works.
Simple pass Intent
first:
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
And you will get picture path on your onActivityResult
:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
for full source code here
setting the content-type to undefined would make javascript pass the header data As it is , and over writing the default angular $httpProvider header configurations. Angular $http Documentation
$http({url:url,method:"POST", headers:{'Content-Type':undefined}).then(success,failure);
Making the custom rating bar with layer list and selectors is complex, it is better to override the RatingBar class and create a custom RatingBar. createBackgroundDrawableShape() is the function where you should put your empty state png and createProgressDrawableShape() is the function where you should put your filled state png.
Note: This code will not work with svg for now.
public class CustomRatingBar extends RatingBar {
@Nullable
private Bitmap mSampleTile;
public ShapeDrawableRatingBar(final Context context, final AttributeSet attrs) {
super(context, attrs);
setProgressDrawable(createProgressDrawable());
}
@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mSampleTile != null) {
final int width = mSampleTile.getWidth() * getNumStars();
setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, 0), getMeasuredHeight());
}
}
protected LayerDrawable createProgressDrawable() {
final Drawable backgroundDrawable = createBackgroundDrawableShape();
LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{
backgroundDrawable,
backgroundDrawable,
createProgressDrawableShape()
});
layerDrawable.setId(0, android.R.id.background);
layerDrawable.setId(1, android.R.id.secondaryProgress);
layerDrawable.setId(2, android.R.id.progress);
return layerDrawable;
}
protected Drawable createBackgroundDrawableShape() {
final Bitmap tileBitmap = drawableToBitmap(getResources().getDrawable(R.drawable.ic_star_empty));
if (mSampleTile == null) {
mSampleTile = tileBitmap;
}
final ShapeDrawable shapeDrawable = new ShapeDrawable(getDrawableShape());
final BitmapShader bitmapShader = new BitmapShader(tileBitmap, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);
shapeDrawable.getPaint().setShader(bitmapShader);
return shapeDrawable;
}
protected Drawable createProgressDrawableShape() {
final Bitmap tileBitmap = drawableToBitmap(getResources().getDrawable(R.drawable.ic_star_full));
final ShapeDrawable shapeDrawable = new ShapeDrawable(getDrawableShape());
final BitmapShader bitmapShader = new BitmapShader(tileBitmap, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);
shapeDrawable.getPaint().setShader(bitmapShader);
return new ClipDrawable(shapeDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);
}
Shape getDrawableShape() {
final float[] roundedCorners = new float[]{5, 5, 5, 5, 5, 5, 5, 5};
return new RoundRectShape(roundedCorners, null, null);
}
public static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
int width = drawable.getIntrinsicWidth();
width = width > 0 ? width : 1;
int height = drawable.getIntrinsicHeight();
height = height > 0 ? height : 1;
final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
}
Why not write it yourself? It's a one-liner or such:
from operator import mul # or mul=lambda x,y:x*y
from fractions import Fraction
def nCk(n,k):
return int( reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1) )
Test - printing Pascal's triangle:
>>> for n in range(17):
... print ' '.join('%5d'%nCk(n,k) for k in range(n+1)).center(100)
...
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1
>>>
PS. edited to replace int(round(reduce(mul, (float(n-i)/(i+1) for i in range(k)), 1)))
with int(reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1))
so it won't err for big N/K
Silly answer but if you can't figure out why its not redirecting check that the following is enabled for the web folder ..
AllowOverride All
This will enable you to run htaccess which must be running! (there are alternatives but not on will cause problems https://httpd.apache.org/docs/2.4/mod/core.html#allowoverride)
As Sai said, the shell is the child, so signals are intercepted by it -- best way I've found is to use shell=False and use shlex to split the command line:
if isinstance(command, unicode):
cmd = command.encode('utf8')
args = shlex.split(cmd)
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
Then p.kill() and p.terminate() should work how you expect.
You don't need JDK
to run Java based programs. JDK
is for development which stands for Java Development Kit
.
You need JRE
which should be there in Mac.
Try: java -jar Myjar_file.jar
EDIT: According to this article, for Mac OS 10
The Java runtime is no longer installed automatically as part of the OS installation.
Then, you need to install JRE to your machine.
I usually use the following:
if (selectPrice.compareTo(BigDecimal.ZERO) == 0) { ... }
you can pickle your dict and save as string.
import pickle
import redis
r = redis.StrictRedis('localhost')
mydict = {1:2,2:3,3:4}
p_mydict = pickle.dumps(mydict)
r.set('mydict',p_mydict)
read_dict = r.get('mydict')
yourdict = pickle.loads(read_dict)
If you have libpq-dev installed and are still having this problem it is likely due to conflicting versions of OpenSSL's libssl and friends - the Ubuntu system version in /usr/lib (which libpq is built against) and a second version RVM installed in $HOME/.rvm/usr/lib (or /usr/local/rvm/usr/lib if it's a system install). You can verify this by temporarily renaming $HOME/.rvm/usr/lib and seeing if "gem install pg" works.
To solve the problem have rvm rebuild using the system OpenSSL libraries (you may need to manually remove libssl.* and libcrypto.* from the rvm/usr/lib dir):
rvm reinstall 1.9.3 --with-openssl-dir=/usr
This finally solved the problem for me on Ubunto 12.04.
SOLUTION: @Before building your component (using mvn clean install). Build the entire project once and build your component again
WHY SO :
I get this error many times.
Most of the times I will try to build my component alone (As I have not made changes elsewhere).
Right, But that extra jar which has been downloaded recently might have affected by changes done by a third party(inside their component). Making a full mvn clean install on entire project saved me many times
It's true that true
and false
don't represent any numerical values in Javascript.
In some languages (e.g. C, VB), the boolean values are defined as actual numerical values, so they are just different names for 1 and 0 (or -1 and 0).
In some other languages (e.g. Pascal, C#), there is a distinct boolean type that is not numerical. It's possible to convert between boolean values and numerical values, but it doesn't happen automatically.
Javascript falls in the category that has a distinct boolean type, but on the other hand Javascript is quite keen to convert values between different data types.
For example, eventhough a number is not a boolean, you can use a numeric value where a boolean value is expected. Using if (1) {...}
works just as well as if (true) {...}
.
When comparing values, like in your example, there is a difference between the ==
operator and the ===
operator. The ==
equality operator happily converts between types to find a match, so 1 == true
evaluates to true because true
is converted to 1
. The ===
type equality operator doesn't do type conversions, so 1 === true
evaluates to false because the values are of different types.
Update
Based on Manipulating the browser history, passing the empty string as second parameter of pushState
method (aka title) should be safe against future changes to the method, so it's better to use pushState
like this:
history.pushState(null, '', '/en/step2');
You can read more about that in mentioned article
Original Answer
Use history.pushState
like this:
history.pushState(null, null, '/en/step2');
Update 2 to answer Idan Dagan's comment:
Why not using
history.replaceState()
?
From MDN
history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one
That means if you use replaceState
, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState
doesn't add new entry to history) and it's not recommended and provide bad UX.
Update 3 to add window.onpopstate
So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState
, you can detect the back/forward button navigation by using window.onpopstate
like this:
window.onpopstate = function(e) {
// ...
};
As the first argument of pushState
is an object, if you passed an object
instead of null
, you can access that object in onpopstate
which is very handy, here is how:
window.onpopstate = function(e) {
if(e.state) {
console.log(e.state);
}
};
Update 4 to add Reading the current state:
When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate
event using the history.state
property like this:
console.log(history.state);
Bonus: Use following to check history.pushState
support:
if (history.pushState) {
// \o/
}
You need to attach the Form1_Load
handler to the Load
event:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Diagnostics;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e)
{
Random rnd = new Random();
Chart mych = new Chart();
mych.Height = 100;
mych.Width = 100;
mych.BackColor = SystemColors.Highlight;
mych.Series.Add("duck");
mych.Series["duck"].SetDefault(true);
mych.Series["duck"].Enabled = true;
mych.Visible = true;
for (int q = 0; q < 10; q++)
{
int first = rnd.Next(0, 10);
int second = rnd.Next(0, 10);
mych.Series["duck"].Points.AddXY(first, second);
Debug.WriteLine(first + " " + second);
}
Controls.Add(mych);
}
}
}
This code worked for me
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<UserDetail>()
.HasRequired(d => d.User)
.WithOptional(u => u.UserDetail)
.WillCascadeOnDelete(true);
}
The migration code was:
public override void Up()
{
AddForeignKey("UserDetail", "UserId", "User", "UserId", cascadeDelete: true);
}
And it worked fine. When I first used
modelBuilder.Entity<User>()
.HasOptional(a => a.UserDetail)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
The migration code was:
AddForeignKey("User", "UserDetail_UserId", "UserDetail", "UserId", cascadeDelete: true);
but it does not match any of the two overloads available (in EntityFramework 6)
try this
<input type="button" style="background-image:url('your_url')"/>
I know this is an old thread, but none of the answers really did it for me - either inefficient, or not encapsulated for easy reuse. I also wanted to ensure it returned false if the string was empty or null. TryParse returns true in this case (an empty string does not cause an error when parsing as a number). So, here's my string extension method:
public static class Extensions
{
/// <summary>
/// Returns true if string is numeric and not empty or null or whitespace.
/// Determines if string is numeric by parsing as Double
/// </summary>
/// <param name="str"></param>
/// <param name="style">Optional style - defaults to NumberStyles.Number (leading and trailing whitespace, leading and trailing sign, decimal point and thousands separator) </param>
/// <param name="culture">Optional CultureInfo - defaults to InvariantCulture</param>
/// <returns></returns>
public static bool IsNumeric(this string str, NumberStyles style = NumberStyles.Number,
CultureInfo culture = null)
{
double num;
if (culture == null) culture = CultureInfo.InvariantCulture;
return Double.TryParse(str, style, culture, out num) && !String.IsNullOrWhiteSpace(str);
}
}
Simple to use:
var mystring = "1234.56789";
var test = mystring.IsNumeric();
Or, if you want to test other types of number, you can specify the 'style'. So, to convert a number with an Exponent, you could use:
var mystring = "5.2453232E6";
var test = mystring.IsNumeric(style: NumberStyles.AllowExponent);
Or to test a potential Hex string, you could use:
var mystring = "0xF67AB2";
var test = mystring.IsNumeric(style: NumberStyles.HexNumber)
The optional 'culture' parameter can be used in much the same way.
It is limited by not being able to convert strings that are too big to be contained in a double, but that is a limited requirement and I think if you are working with numbers larger than this, then you'll probably need additional specialised number handling functions anyway.
Below is a positive lookbehind JavaScript alternative showing how to capture the last name of people with 'Michael' as their first name.
1) Given this text:
const exampleText = "Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green Miller and Michael Wood?";
get an array of last names of people named Michael.
The result should be: ["Jordan","Johnson","Green","Wood"]
2) Solution:
function getMichaelLastName2(text) {
return text
.match(/(?:Michael )([A-Z][a-z]+)/g)
.map(person => person.slice(person.indexOf(' ')+1));
}
// or even
.map(person => person.slice(8)); // since we know the length of "Michael "
3) Check solution
console.log(JSON.stringify( getMichaelLastName(exampleText) ));
// ["Jordan","Johnson","Green","Wood"]
Demo here: http://codepen.io/PiotrBerebecki/pen/GjwRoo
You can also try it out by running the snippet below.
const inputText = "Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green Miller and Michael Wood?";_x000D_
_x000D_
_x000D_
_x000D_
function getMichaelLastName(text) {_x000D_
return text_x000D_
.match(/(?:Michael )([A-Z][a-z]+)/g)_x000D_
.map(person => person.slice(8));_x000D_
}_x000D_
_x000D_
console.log(JSON.stringify( getMichaelLastName(inputText) ));
_x000D_
Follow these steps to change an app's name in Django:
views.py
, urls.py
, 'manage.py' , and settings.py
files.django_content_type
with the following command: UPDATE django_content_type SET app_label='<NewAppName>' WHERE app_label='<OldAppName>'
ALTER TABLE <oldAppName>_modelName RENAME TO <newAppName>_modelName
. For mysql too I think it is the same (as mentioned by @null_radix)django_migrations
table to avoid having your previous migrations re-run: UPDATE django_migrations SET app='<NewAppName>' WHERE app='<OldAppName>'
. Note: there is some debate (in comments) if this step is required for Django 1.8+; If someone knows for sure please update here.models.py
's Meta Class has app_name
listed, make sure to rename that too (mentioned by @will).static
or templates
folders inside your app, you'll also need to rename those. For example, rename old_app/static/old_app
to new_app/static/new_app
.models
, you'll need to change django_content_type.name
entry in DB. For postgreSQL use UPDATE django_content_type SET name='<newModelName>' where name='<oldModelName>' AND app_label='<OldAppName>'
Meta point (If using virtualenv): Worth noting, if you are renaming the directory that contains your virtualenv, there will likely be several files in your env that contain an absolute path and will also need to be updated. If you are getting errors such as ImportError: No module named ...
this might be the culprit. (thanks to @danyamachine for providing this).
Other references: you might also want to refer the below links for a more complete picture
Restricting to few lines will work in almost all browsers, but an ellipsis(3 dots) will not be displayed in Firefox & IE. Demo - http://jsfiddle.net/ahzo4b91/1/
div {
width: 300px;
height: 2.8em;
line-height: 1.4em;
display: flex;
-webkit-line-clamp: 2;
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
}
Combine Kim's answer with os:
p=Path(os.getcwd())
os.chdir(p.parent)
If the texts has different sizes and they must be underlined this is the solution:
<table>
<tr>
<td class='left'>January</td>
<td class='right'>2014</td>
</tr>
</table>
css:
table{
width: 100%;
border-bottom: 2px solid black;
/*this is the size of the small text's baseline over part (˜25px*3/4)*/
line-height: 19.5px;
}
table td{
vertical-align: baseline;
}
.left{
font-family: Arial;
font-size: 40px;
text-align: left;
}
.right{
font-size: 25px;
text-align: right;
}
Hey I had the same problem. I tried to convert '2017-02-20 12:15:32' varchar to a date with TO_DATE('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS')
and all I received was 2017-02-20 the time disappeared
My solution was to use TO_TIMESTAMP('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS')
now the time doesn't disappear.
The easiest solution is to use Uri.getLastPathSegment():
String filename = uri.getLastPathSegment();
Much like setState in Class components created by extending React.Component
or React.PureComponent
, the state update using the updater provided by useState
hook is also asynchronous, and will not be reflected immediately.
Also, the main issue here is not just the asynchronous nature but the fact that state values are used by functions based on their current closures, and state updates will reflect in the next re-render by which the existing closures are not affected, but new ones are created. Now in the current state, the values within hooks are obtained by existing closures, and when a re-render happens, the closures are updated based on whether the function is recreated again or not.
Even if you add a setTimeout
the function, though the timeout will run after some time by which the re-render would have happened, the setTimeout
will still use the value from its previous closure and not the updated one.
setMovies(result);
console.log(movies) // movies here will not be updated
If you want to perform an action on state update, you need to use the useEffect hook, much like using componentDidUpdate
in class components since the setter returned by useState doesn't have a callback pattern
useEffect(() => {
// action on update of movies
}, [movies]);
As far as the syntax to update state is concerned, setMovies(result)
will replace the previous movies
value in the state with those available from the async request.
However, if you want to merge the response with the previously existing values, you must use the callback syntax of state updation along with the correct use of spread syntax like
setMovies(prevMovies => ([...prevMovies, ...result]));
I'm surprised no one has mentioned using regular expressions via re.sub()
:
import re
print re.sub(r'([\"])', r'\\\1', 'it\'s "this"') # it's \"this\"
print re.sub(r"([\'])", r'\\\1', 'it\'s "this"') # it\'s "this"
print re.sub(r'([\" \'])', r'\\\1', 'it\'s "this"') # it\'s\ \"this\"
Important things to note:
\
as well as the character(s) you're looking for.
You're going to be using \
to escape your characters, so you need to escape
that as well.([\"])
, so that the substitution
pattern can use the found character when it adds \
in front of it. (That's what
\1
does: uses the value of the first parenthesized group.)r
in front of r'([\"])'
means it's a raw string. Raw strings use different
rules for escaping backslashes. To write ([\"])
as a plain string, you'd need to
double all the backslashes and write '([\\"])'
. Raw strings are friendlier when
you're writing regular expressions.\
to distinguish it from a
backslash that precedes a substitution group, e.g. \1
, hence r'\\\1'
. To write
that as a plain string, you'd need '\\\\\\1'
— and nobody wants that.Let's break it down:
So the GAC must be a place to store code libraries so they're accessible to all applications running on the machine.
This should help.
Integer startIn = null;
// (optional below but a good practice, to prevent errors.)
boolean dontContinue = false;
try {
Integer.parseInt (startField.getText());
} catch (NumberFormatException e){
e.printStackTrace();
}
// in java = assigns a boolean in if statements oddly.
// Thus double equal must be used. So if startIn is null, display the message
if (startIn == null) {
JOptionPane.showMessageDialog(null,
"You must enter a number between 0-16.","Input Error",
JOptionPane.ERROR_MESSAGE);
}
// (again optional)
if (dontContinue == true) {
//Do-some-error-fix
}
parentElement
is new to Firefox 9 and to DOM4, but it has been present in all other major browsers for ages.
In most cases, it is the same as parentNode
. The only difference comes when a node's parentNode
is not an element. If so, parentElement
is null
.
As an example:
document.body.parentNode; // the <html> element
document.body.parentElement; // the <html> element
document.documentElement.parentNode; // the document node
document.documentElement.parentElement; // null
(document.documentElement.parentNode === document); // true
(document.documentElement.parentElement === document); // false
Since the <html>
element (document.documentElement
) doesn't have a parent that is an element, parentElement
is null
. (There are other, more unlikely, cases where parentElement
could be null
, but you'll probably never come across them.)
Alternatively one could say having an infinite loop is normally bad practice anyway, since it needs an exit condition unless the app really runs forever. However, if this is for a cruise missile I will accept an explicit exit condition might not be required.
Though I do like this one:
for (float f = 16777216f; f < 16777217f; f++) { }
@Carlo I really like your implementation of this, but I wanted to share my version and how to use it in my ViewModel
First implement ICommand
public class Command : ICommand
{
public delegate void ICommandOnExecute();
public delegate bool ICommandOnCanExecute();
private ICommandOnExecute _execute;
private ICommandOnCanExecute _canExecute;
public Command(ICommandOnExecute onExecuteMethod, ICommandOnCanExecute onCanExecuteMethod = null)
{
_execute = onExecuteMethod;
_canExecute = onCanExecuteMethod;
}
#region ICommand Members
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object parameter)
{
return _canExecute?.Invoke() ?? true;
}
public void Execute(object parameter)
{
_execute?.Invoke();
}
#endregion
}
Notice I have removed the parameter from ICommandOnExecute and ICommandOnCanExecute and added a null to the constructor
Then to use in the ViewModel
public Command CommandToRun_WithCheck
{
get
{
return new Command(() =>
{
// Code to run
}, () =>
{
// Code to check to see if we can run
// Return true or false
});
}
}
public Command CommandToRun_NoCheck
{
get
{
return new Command(() =>
{
// Code to run
});
}
}
I just find this way cleaner as I don't need to assign variables and then instantiate, it all done in one go.
Use return
operator:
function FUNCT {
if [ blah is false ]; then
return 1 # or return 0, or even you can omit the argument.
else
keep running the function
fi
}
I would like to add that Lin's answer is correct.
If you improperly delete the MDF you will have to fix it. To fix the screwed up connections in the project to the MDF. Short answer; recreate and delete it properly.
update-database -force
[Use force if necessary]Done, enjoy your new db
UPDATE 11/12/14 - I use this all the time when I make a breaking db change. I found this is a great way to roll back your migrations to the original db:
Run the normal migration to put it back to current
Update-Database -TargetMigration:0 -force
[This will destroy all tables and all data.] Update-Database -force
[use force if necessary]This worked for my GIT version 1.8.4:
My problem was that I could no longer run an emulator that had worked because I had quit the emulator application but the process wasn't fully ended, so I was trying to launch another emulator while the previous one was still running. On a mac, I had to use the Activity Monitor to see the other process and kill it. Steps:
on the server side in node.js I just added this and it worked. reactjs front end on my local machine can access api backend hosted on azure:
// Enables CORS
const cors = require('cors');
app.use(cors({ origin: true }));
For future reference, the above code does not work with Python 3. For Python 3, the D.keys()
needs to be converted to a list.
import matplotlib.pyplot as plt
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
plt.bar(range(len(D)), D.values(), align='center')
plt.xticks(range(len(D)), list(D.keys()))
plt.show()
I had this error in code that looked like this:
int A = 1;
int B = A;
The fix is to change it to this
int A = 1;
#define B A
The compiler assigns a location in memory to a variable. The second is trying a assign a second variable to the same location as the first - which makes no sense. Using the macro preprocessor solves the problem.
Using the chronic gem:
class MyModel < ActiveRecord::Base
validate :valid_date?
def valid_date?
unless Chronic.parse(from_date)
errors.add(:from_date, "is missing or invalid")
end
end
end
You can use Decode
as well:
SELECT DISTINCT a.item, decode(b.salesman,'VIKKIE','ICKY',Else),NVL(a.manufacturer,'Not Set')Manufacturer
FROM inv_items a, arv_sales b
WHERE a.co = b.co
AND A.ITEM_KEY = b.item_key
AND a.co = '100'
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
and to_date('011713','mmddrr')
GROUP BY a.item, b.salesman, a.manufacturer
ORDER BY a.item
I believe +%s
is seconds since epoch. It's timezone invariant.
If you are using RemoteDriver things are different. From http://element34.ca/blog/iedriverserver-webdriver-and-python :
You will need to start the server using a line like
java -jar selenium-server-standalone-2.26.0.jar -Dwebdriver.ie.driver=C:\Temp\IEDriverServer.exe
I found that if the IEDriverServer.exe was in C:\Windows\System32\
or its subfolders, it couldn't be found automatically (even though System32 was in the %PATH%
) or explicitly using the -D flag.
Using parameters in batch files: %0 and %9
Batch files can refer to the words passed in as parameters with the tokens: %0
to %9
.
%0 is the program name as it was called.
%1 is the first command line parameter
%2 is the second command line parameter
and so on till %9.
parameters passed in on the commandline must be alphanumeric characters and delimited by spaces. Since %0
is the program name as it was called, in DOS %0
will be empty for AUTOEXEC.BAT if started at boot time.
Example:
Put the following command in a batch file called mybatch.bat
:
@echo off
@echo hello %1 %2
pause
Invoking the batch file like this: mybatch john billy
would output:
hello john billy
Get more than 9 parameters for a batch file, use: %*
The Percent Star token %*
means "the rest of the parameters". You can use a for loop to grab them, as defined here:
http://www.robvanderwoude.com/parameters.php
Notes about delimiters for batch parameters
Some characters in the command line parameters are ignored by batch files, depending on the DOS version, whether they are "escaped" or not, and often depending on their location in the command line:
commas (",") are replaced by spaces, unless they are part of a string in
double quotes
semicolons (";") are replaced by spaces, unless they are part of a string in
double quotes
"=" characters are sometimes replaced by spaces, not if they are part of a
string in double quotes
the first forward slash ("/") is replaced by a space only if it immediately
follows the command, without a leading space
multiple spaces are replaced by a single space, unless they are part of a
string in double quotes
tabs are replaced by a single space
leading spaces before the first command line argument are ignored
git diff <revision> <path>
For example:
git diff b0d14a4 foobar.txt
I have a widget which does relatively frequent updates when the device is awake and I was seeing thousands of crashes in just a few days.
I even noticed the issue even on my Pixel 3 XL when I wouldn't have thought the device to have much load at all. And any and all code paths were covered with startForeground()
. But then I realized that in many cases my service gets the job done really quickly. I believe the trigger for my app was that the service was finishing before the system actually got around to showing a notification.
I was able to get rid of all crashes. What I did was to remove the call to stopSelf()
. (I was thinking about delaying the stop until I was pretty sure the notification was shown, but I don't want the user to see the notification if it isn't necessary.) When the service has been idle for a minute or the system destroys it normally without throwing any exceptions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
stopForeground(true);
} else {
stopSelf();
}
function isset(element) {
return element.length > 0;
}
Or, as a jQuery extension:
$.fn.exists = function() { return this.length > 0; };
// later ...
if ( $("#id").exists() ) {
// do something
}
You can do that using three ways first use if condition like below
{!! $text !!}
The is Second way
<td class="nowrap">
@if( $order->status == '0' )
<button class="btn btn-danger">Inactive</button>
@else
<button class="btn btn-success">Active</button>
@endif
</td>
The third and proper way for use ternary operator on blade
<td class="nowrap">
{!! $order->status=='0' ?
'<button class="btn btn-danger">Inactive</button> :
'<button class="btn btn-success">Active</button> !!}
</td>
I hope the third way is perfect for used ternary operator on blade.
I'm not sure how you might do this with Node, but the general idea would be to send an HTTP HEAD request to the URL you're interested in.
HEAD
Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.
Something like this, based it on this question:
var cli = require('cli');
var http = require('http');
var url = require('url');
cli.parse();
cli.main(function(args, opts) {
this.debug(args[0]);
var siteUrl = url.parse(args[0]);
var site = http.createClient(80, siteUrl.host);
console.log(siteUrl);
var request = site.request('HEAD', siteUrl.pathname, {'host' : siteUrl.host})
request.end();
request.on('response', function(response) {
response.setEncoding('utf8');
console.log('STATUS: ' + response.statusCode);
response.on('data', function(chunk) {
console.log("DATA: " + chunk);
});
});
});
CSS has become a very powerful tool over the years and it has hacks for a lot of things javaScript can do
There is a hack in CSS for using conditional statements/logic.
It involves using the symbol '~'
Let me further illustrate with an example.
Let's say you want a background to slide into the page when a button is clicked. All you need to do is use a radio checkbox. Style the label for the radio underneath the button so that when the button is pressed the checkbox is also pressed.
Then you use the code below
.checkbox:checked ~ .background{
opacity:1
width: 100%
}
This code simply states IF the checkbox is CHECKED then open up the background ELSE leave it as it is.
My problem
get_courses(); //// To load the course list
$("#course").val(course); //// Setting default value of the list
I had the same issue . The Only difference from your code is that I was loading the select box through an ajax call and soon as the ajax call was executed I had set the default value of the select box
The Solution
get_courses();
setTimeout(function() {
$("#course").val(course);
}, 10);
Actually a name can be used however it cannot have spaces so
window.open("../myPage","MyWindows",...)
should work with no problem (window.open).
The solution that worked for me. Delete this folder:
workspace/.metadata/.plugins/org.eclipse.e4.workbench
From the Javadoc:
Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by
java.util.Hashtable
.The general contract of
hashCode
is:
Whenever it is invoked on the same object more than once during an execution of a Java application, the
hashCode
method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.If two objects are equal according to the
equals(Object)
method, then calling thehashCode
method on each of the two objects must produce the same integer result.It is not required that if two objects are unequal according to the
equals(java.lang.Object)
method, then calling thehashCode
method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java programming language.)
Suppose you have data in A1:A10 and B1:B10 and you want to highlight which values in A1:A10 do not appear in B1:B10.
Try as follows:
Enter the following formula:
=ISERROR(MATCH(A1,$B$1:$B$10,0))
Now select the format you want to highlight the values in col A that do not appear in col B
This will highlight any value in Col A that does not appear in Col B.
You either need to use first()
or get()
to fetch the results :
$userRecord = $this->where('email', $email)->where('password', $password)->first();
You most likely need to use first()
as you want only one result returned.
If the record isn't found null
will be returned. If you are building this query from inside an Eloquent class you could use self
.
for example :
$userRecord = self::where('email', $email)->where('password', $password)->first();
More info here
As nobody published a solution with CountDownLatch. What about:
public class Lockeable {
private final CountDownLatch countDownLatch = new CountDownLatch(1);
public void doAfterEvent(){
countDownLatch.await();
doSomething();
}
public void reportDetonatingEvent(){
countDownLatch.countDown();
}
}
The short answer to your question, I think, is no (you can just create a new object).
In this example, I believe setting the length to 0 still leaves all of the elements for garbage collection.
You could add this to Object.prototype if it's something you'd frequently use. Yes it's linear in complexity, but anything that doesn't do garbage collection later will be.
This is the best solution. I know it's not related to your question - but for how long do we need to continue supporting IE6? There are many campaigns to discontinue the usage of it.
Feel free to correct me if there's anything incorrect above.
Since you are the only user:
git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}
( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )
Without doing any changes to your local repo, you can also do something like:
git push -f origin <sha_of_previous_commit>:master
Generally, in published repos, it is safer to do git revert
and then git push
I can't see an obvious way to do that in the docs, but you try triggering the focus (or click) event on the autocomplete enabled textbox:
$('#myButton').click(function() {
$('#autocomplete').trigger("focus"); //or "click", at least one should work
});
Sometimes opening old project in new version Xcode will get this message.
Go to Issue navigator and follow the warning hint 'Upate to reconmmented settings'.
Boom, magic!
Delete the line "/*# sourceMappingURL=bootstrap.min.css.map */ "
in following files.
To fetch the file path in Linux use the command find / -name "\*bootstrap\*"
Remove column constraint: not null
to null
ALTER TABLE test ALTER COLUMN column_01 DROP NOT NULL;
require 'pp'
pp my_hash
Use pp
if you need a built-in solution and just want reasonable line breaks.
Use awesome_print if you can install a gem. (Depending on your users, you may wish to use the index:false
option to turn off displaying array indices.)
var geturl;
geturl = $.ajax({
type: "GET",
url: 'http://....',
success: function () {
alert("done!"+ geturl.getAllResponseHeaders());
}
});
X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
Variable1 Variable2
1 11 2
2 14 3
3 12 1
4 15 4
> X[X$Variable1!=11 & X$Variable1!=12, ]
Variable1 Variable2
2 14 3
4 15 4
> X[ ! X$Variable1 %in% c(11,12), ]
Variable1 Variable2
2 14 3
4 15 4
You can functionalize this however you like.
private List<SimpleLogType> GetLogType()
{
List<SimpleLogType> logList = new List<SimpleLogType>();
SimpleLogType internalLogType;
foreach (var logtype in Enum.GetValues(typeof(Log)))
{
internalLogType = new SimpleLogType();
internalLogType.Id = (int) (Log) Enum.Parse(typeof (Log), logtype.ToString(), true);
internalLogType.Name = (Log)Enum.Parse(typeof(Log), logtype.ToString(), true);
logList.Add(internalLogType);
}
return logList;
}
in top Code , Log is a Enum and SimpleLogType is a structure for logs .
public enum Log
{
None = 0,
Info = 1,
Warning = 8,
Error = 3
}
Try this :)
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
function initialize() {
var loc = {};
var geocoder = new google.maps.Geocoder();
if(google.loader.ClientLocation) {
loc.lat = google.loader.ClientLocation.latitude;
loc.lng = google.loader.ClientLocation.longitude;
var latlng = new google.maps.LatLng(loc.lat, loc.lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
alert(results[0]['formatted_address']);
};
});
}
}
google.load("maps", "3.x", {other_params: "sensor=false", callback:initialize});
</script>
Use vertical-align:top; for the element you want at the top, as I have demonstrated on your jsfiddle.
Always try to use interface reference in Collection, this adds more flexibility.
What is the problem with the below code?
List<Map<String,List<String>>> list = new ArrayList<Map<String,List<String>>>();//This is the final list you need
Map<String, List<String>> map1 = new HashMap<String, List<String>>();//This is one instance of the map you want to store in the above list.
List<String> arraylist1 = new ArrayList<String>();
arraylist1.add("Text1");//And so on..
map1.put("key1",arraylist1);
//And so on...
list.add(map1);//In this way you can add.
You can easily do it like the above.
I had the same error, the problem was because I no longer had disk space. to check the space run this:
$ df -h
Then delete some files that you didn't need.
After this commands:
service mysql start
systemctl status mysql.service
mysql -u root -p
After entering with the root password verify that the mysql service was active
<android.support.design.widget.BottomNavigationView
android:id="@+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
app:menu="@menu/navigation" />
navigation.xml(inside menu)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/navigation_home"
android:icon="@drawable/ic_home_black_24dp"
android:title="@string/title_home"
app:showAsAction="always|withText"
android:enabled="true"/>
Inside onCreate()
method,
BottomNavigationView navigation = (BottomNavigationView)findViewById(R.id.navigation);
//Dont forgot this line
BottomNavigationViewHelper.disableShiftMode(navigation);
And Create class as below.
public class BottomNavigationViewHelper {
public static void disableShiftMode(BottomNavigationView view) {
BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
try {
Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
shiftingMode.setAccessible(true);
shiftingMode.setBoolean(menuView, false);
shiftingMode.setAccessible(false);
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
//noinspection RestrictedApi
item.setShiftingMode(false);
// set once again checked value, so view will be updated
//noinspection RestrictedApi
item.setChecked(item.getItemData().isChecked());
}
} catch (NoSuchFieldException e) {
Log.e("BNVHelper", "Unable to get shift mode field", e);
} catch (IllegalAccessException e) {
Log.e("BNVHelper", "Unable to change value of shift mode", e);
}
}
}
If you want to achieve a shadow like the one that Android does in the Launcher, we're managing these values. They're useful if you want to create TextViews that will appear as a Widget, without a background.
android:shadowColor="#94000000"
android:shadowDy="2"
android:shadowRadius="4"
You can use a position: absolute
inside a position: relative
Python allows you to use a string as an iterator:
for character in 'string':
print(character)
I'm guessing it's your job to figure out how to turn that into a while loop.
On Windows add following lines to _vimrc
" store backup, undo, and swap files in temp directory
set directory=$HOME/temp//
set backupdir=$HOME/temp//
set undodir=$HOME/temp//
This works because Integer::min
resolves to an implementation of the Comparator<Integer>
interface.
The method reference of Integer::min
resolves to Integer.min(int a, int b)
, resolved to IntBinaryOperator
, and presumably autoboxing occurs somewhere making it a BinaryOperator<Integer>
.
And the min()
resp max()
methods of the Stream<Integer>
ask the Comparator<Integer>
interface to be implemented.
Now this resolves to the single method Integer compareTo(Integer o1, Integer o2)
. Which is of type BinaryOperator<Integer>
.
And thus the magic has happened as both methods are a BinaryOperator<Integer>
.
This is what you are looking for:
1.- Navigate to the Source tab and open the javascript file
2.- Edit the file, right-click it and a menu will appear: click Save and save it locally.
In order to view the diff or revert your changes, right-click and select the option Local Modifications... from the menu. You will see your changes diff with respect to the original file if you expand the timestamp shown.
More detailed info here: http://www.sitepoint.com/edit-source-files-in-chrome/
if($('#someElement').hasClass('test')) {
... do something ...
}
else {
... do something else ...
}
Let's start with a qualitative description of what we want to do (much of this is said in Ben Straub's answer). We've made some number of commits, five of which changed a given file, and we want to revert the file to one of the previous versions. First of all, git doesn't keep version numbers for individual files. It just tracks content - a commit is essentially a snapshot of the work tree, along with some metadata (e.g. commit message). So, we have to know which commit has the version of the file we want. Once we know that, we'll need to make a new commit reverting the file to that state. (We can't just muck around with history, because we've already pushed this content, and editing history messes with everyone else.)
So let's start with finding the right commit. You can see the commits which have made modifications to given file(s) very easily:
git log path/to/file
If your commit messages aren't good enough, and you need to see what was done to the file in each commit, use the -p/--patch
option:
git log -p path/to/file
Or, if you prefer the graphical view of gitk
gitk path/to/file
You can also do this once you've started gitk through the view menu; one of the options for a view is a list of paths to include.
Either way, you'll be able to find the SHA1 (hash) of the commit with the version of the file you want. Now, all you have to do is this:
# get the version of the file from the given commit
git checkout <commit> path/to/file
# and commit this modification
git commit
(The checkout command first reads the file into the index, then copies it into the work tree, so there's no need to use git add
to add it to the index in preparation for committing.)
If your file may not have a simple history (e.g. renames and copies), see VonC's excellent comment. git
can be directed to search more carefully for such things, at the expense of speed. If you're confident the history's simple, you needn't bother.
I had this problem. Reinstalling the latest version of Adobe Reader did nothing. Adobe Reader worked in Chrome but not in IE. This worked for me ...
1) Go to IE's Tools-->Compatibility View menu.
2) Enter a website that has the PDF you wish to see. Click OK.
3) Restart IE
4) Go to the website you entered and select the PDF. It should come up.
5) Go back to Compatibility View and delete the entry you made.
6) Adobe Reader works OK now in IE on all websites.
It's a strange fix, but it worked for me. I needed to go through an Adobe acceptance screen after reinstall that only appeared after I did the Compatibility View trick. Once accepted, it seemed to work everywhere. Pretty flaky stuff. Hope this helps someone.
I agree with @GregoryKlopper that the right way to solve the general problem of finding Waldo (or any object of interest) in an arbitrary image would be to train a supervised machine learning classifier. Using many positive and negative labeled examples, an algorithm such as Support Vector Machine, Boosted Decision Stump or Boltzmann Machine could likely be trained to achieve high accuracy on this problem. Mathematica even includes these algorithms in its Machine Learning Framework.
The two challenges with training a Waldo classifier would be:
A quick Google image search turns up some good data -- I'm going to have a go at collecting some training examples and coding this up right now!
However, even a machine learning approach (or the rule-based approach suggested by @iND) will struggle for an image like the Land of Waldos!
Thank you WiredPrairie!
Just to expand on your answer a bit, here is a complete example of defining a constants class.
// CYConstants.ts
class CYConstants {
public static get NOT_FOUND(): number { return -1; }
public static get EMPTY_STRING(): string { return ""; }
}
export = CYConstants;
To use
// main.ts
import CYConstants = require("./CYConstants");
console.log(CYConstants.NOT_FOUND); // Prints -1
console.log(CYConstants.EMPTY_STRING); // Prints "" (Nothing!)
Not tested, but I think you can do the following:
dataGrid.Rows[index].Selected = true;
or you could do the following (but again: not tested):
dataGrid.SelectedRows.Clear();
foreach(DataGridViewRow row in dataGrid.Rows)
{
if(YOUR CONDITION)
row.Selected = true;
}
The current HTML5 draft also allows ommitting the href attribute completely.
If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant.
To answer your question: Yes it's valid.
In Arduino:
//temporarily holds data from vals
char charVal[10];
//4 is mininum width, 3 is precision; float value is copied onto buff
dtostrf(123.234, 4, 3, charVal);
monitor.print("charVal: ");
monitor.println(charVal);
For some reason the android.text.LoginFilter class's constructor is package-scoped, so you can't directly extend it (even though it would be identical to this code). But you can extend LoginFilter.UsernameFilterGeneric! Then you just have this:
class ABCFilter extends LoginFilter.UsernameFilterGeneric {
public UsernameFilter() {
super(false); // false prevents not-allowed characters from being appended
}
@Override
public boolean isAllowed(char c) {
if ('A' <= c && c <= 'C')
return true;
if ('a' <= c && c <= 'c')
return true;
return false;
}
}
This isn't really documented, but it's part of the core lib, and the source is straightforward. I've been using it for a while now, so far no problems, though I admit I haven't tried doing anything complex involving spannables.
var valueOfTextBox=$("#result").val();
var valueOfSelectedCheckbox=$("#radio:checked").val();
$.ajax({
url: 'result.php',
type: 'POST',
data: { forValue: valueOfTextBox, check : valueOfSelectedCheckbox } ,
beforeSend: function() {
$("#loader").show();
},
success: function (response) {
$("#loader").hide();
$("#answer").text(response);
},
error: function () {
//$("#loader").show();
alert("error occured");
}
});
I guess for Wicket it's better to call add
method in the onInitialize()
(see components lifecycle) :
public abstract class BasicPage extends WebPage {
public BasicPage() {
}
@Override
public void onInitialize() {
add(new Label("title", getTitle()));
}
protected abstract String getTitle();
}
apply this code for get the ipaddress:
if (getenv('HTTP_X_FORWARDED_FOR')) { $pipaddress = getenv('HTTP_X_FORWARDED_FOR');
$ipaddress = getenv('REMOTE_ADDR');
echo "Your Proxy IP address is : ".$pipaddress. "(via $ipaddress)" ; }
else { $ipaddress = getenv('REMOTE_ADDR'); echo "Your IP address is : $ipaddress"; }
------------------------------------------------------------------------
Serial.println(val)
Serial.println(val, format)
for more you can visit to the site of arduino https://www.arduino.cc/en/Serial/Println
wish this will help you. thanks!
There may be other ways to get your desired result.
Declare @a int
Declare @b int
SET @a = 3
SET @b=2
SELECT cast((cast(@a as float)/ cast(@b as float)) as float)
An easier way to get the machine epsilon for a given float type is to use np.finfo()
:
print(np.finfo(float).eps)
# 2.22044604925e-16
print(np.finfo(np.float32).eps)
# 1.19209e-07
ctrl != super on windows and linux machines.
If the F12 version of "Goto Definition" produces results of several files, the "ctrl + shift + click" version might not work well. I found that bug when viewing golang project with GoSublime package.
You are missimg @ModelAttribute
annotation for UserProfessionalForm professionalForm
parameter in forgotPassword
method.
@RequestMapping(value = "proffessional", method = RequestMethod.POST)
public @ResponseBody
String forgotPassword(@ModelAttribute UserProfessionalForm professionalForm,
BindingResult result, Model model) {
UserProfileVO userProfileVO = new UserProfileVO();
userProfileVO.setUser(sessionData.getUser());
userService.saveUserProfile(userProfileVO);
model.addAttribute("professional", professionalForm);
return "Your Professional Details Updated";
}
This is BY FAR the easiest way to convert DBNull
to a string.
The trick is that you CANNOT use the TRIM
function (which was my initial problem) when referring to the fields from the database:
BEFORE (produced error msg):
Me.txtProvNum.Text = IIf(Convert.IsDBNull(TRIM(myReader("Prov_Num"))), "", TRIM(myReader("Prov_Num")))
AFTER (no more error msg :-) ):
Me.txtProvNum.Text = IIf(Convert.IsDBNull(myReader("Prov_Num")), "", myReader("Prov_Num"))
if you are using razor engine template then do the following
in your view write :
<script> var myJsVariable = '@ViewBag.MyVariable' </script>
UPDATE: A more appropriate approach is to define a set of configuration on the master layout for example, base url, facebook API Key, Amazon S3 base URL, etc ...```
<head>
<script>
var AppConfig = @Html.Raw(Json.Encode(new {
baseUrl: Url.Content("~"),
fbApi: "get it from db",
awsUrl: "get it from db"
}));
</script>
</head>
And you can use it in your JavaScript code as follow:
<script>
myProduct.fullUrl = AppConfig.awsUrl + myProduct.path;
alert(myProduct.fullUrl);
</script>
\w\-
is probably the best but here just another alternative
Use [:alnum:]
if(!preg_match("/[^[:alnum:]\-_]/",$str)) echo "valid";
I would recommend doing the following:
foreach ($fields as $key => $field) {
if ($field['required'] && strlen($_POST[$field['name']]) <= 0) {
$fields[$key]['value'] = "Some error";
}
}
So basically use $field
when you need the values, and $fields[$key]
when you need to change the data.
for /f "tokens=* delims= " %%f in (myfile) do
This reads a file line-by-line, removing leading spaces (thanks, jeb).
set line=%%f
sets then the line
variable to the line just read and
call :procesToken
calls a subroutine that does something with the line
:processToken
is the start of the subroutine mentioned above.
for /f "tokens=1* delims=/" %%a in ("%line%") do
will then split the line at /
, but stopping tokenization after the first token.
echo Got one token: %%a
will output that first token and
set line=%%b
will set the line
variable to the rest of the line.
if not "%line%" == "" goto :processToken
And if line
isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.
// Step 1, update your constraint
self.myOutletToConstraint.constant = 50; // New height (for example)
// Step 2, trigger animation
[UIView animateWithDuration:2.0 animations:^{
// Step 3, call layoutIfNeeded on your animated view's parent
[self.view layoutIfNeeded];
}];
Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf
file (in the /etc/postgresql/9.1/main
directory), it should contain this line as the first rule:
# Database administrative login by Unix domain socket
local all postgres peer
(About the file location: 9.1
is the major postgres version and main
the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters
command to obtain this information for your version/system).
Anyway, if the pg_hba.conf
file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload
.
Then you should be able to log in with psql
as the postgres superuser with this shell command:
sudo -u postgres psql
Once inside psql, issue the SQL command:
ALTER USER postgres PASSWORD 'newpassword';
In this command, postgres
is the name of a superuser. If the user whose password is forgotten was ritesh
, the command would be:
ALTER USER ritesh PASSWORD 'newpassword';
References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication
Keep in mind that you need to type postgres with a single S at the end
If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD
:
\password username
It asks for the password with a double blind input, then hashes it according to the password_encryption
setting and issue the ALTER USER
command to the server with the hashed version of the password, instead of the clear text version.
Adding a branch
option in .gitmodule
is NOT related to the detached behavior of submodules at all. The old answer from @mkungla is incorrect, or obsolete.
From git submodule --help
, HEAD detached is the default behavior of git submodule update --remote
.
First, there's no need to specify a branch to be tracked. origin/master
is the default branch to be tracked.
--remote
Instead of using the superproject's recorded SHA-1 to update the submodule, use the status of the submodule's remote-tracking branch. The remote used is branch's remote (
branch.<name>.remote
), defaulting toorigin
. The remote branch used defaults tomaster
.
So why is HEAD detached after update
? This is caused by the default module update behavior: checkout
.
--checkout
Checkout the commit recorded in the superproject on a detached HEAD in the submodule. This is the default behavior, the main use of this option is to override
submodule.$name.update
when set to a value other thancheckout
.
To explain this weird update behavior, we need to understand how do submodules work?
Quote from Starting with Submodules in book Pro Git
Although sbmodule
DbConnector
is a subdirectory in your working directory, Git sees it as a submodule and doesn’t track its contents when you’re not in that directory. Instead, Git sees it as a particular commit from that repository.
The main repo tracks the submodule with its state at a specific point, the commit id. So when you update modules, you're updating the commit id to a new one.
If you want the submodule merged with remote branch automatically, use --merge
or --rebase
.
--merge
This option is only valid for the update command. Merge the commit recorded in the superproject into the current branch of the submodule. If this option is given, the submodule's HEAD will not be detached.
--rebase
Rebase the current branch onto the commit recorded in the superproject. If this option is given, the submodule's HEAD will not be detached.
All you need to do is,
git submodule update --remote --merge
# or
git submodule update --remote --rebase
Recommended alias:
git config alias.supdate 'submodule update --remote --merge'
# do submodule update with
git supdate
There's also an option to make --merge
or --rebase
as the default behavior of git submodule update
, by setting submodule.$name.update
to merge
or rebase
.
Here's an example about how to config the default update behavior of submodule update in .gitmodule
.
[submodule "bash/plugins/dircolors-solarized"]
path = bash/plugins/dircolors-solarized
url = https://github.com/seebi/dircolors-solarized.git
update = merge # <-- this is what you need to add
Or configure it in command line,
# replace $name with a real submodule name
git config -f .gitmodules submodule.$name.update merge
git submodule --help
Be careful counting number of documents for large collections. It is a little bit complex with firestore database if you want to have a precalculated counter for every collection.
Code like this doesn't work in this case:
export const customerCounterListener =
functions.firestore.document('customers/{customerId}')
.onWrite((change, context) => {
// on create
if (!change.before.exists && change.after.exists) {
return firestore
.collection('metadatas')
.doc('customers')
.get()
.then(docSnap =>
docSnap.ref.set({
count: docSnap.data().count + 1
}))
// on delete
} else if (change.before.exists && !change.after.exists) {
return firestore
.collection('metadatas')
.doc('customers')
.get()
.then(docSnap =>
docSnap.ref.set({
count: docSnap.data().count - 1
}))
}
return null;
});
The reason is because every cloud firestore trigger has to be idempotent, as firestore documentation say: https://firebase.google.com/docs/functions/firestore-events#limitations_and_guarantees
So, in order to prevent multiple executions of your code, you need to manage with events and transactions. This is my particular way to handle large collection counters:
const executeOnce = (change, context, task) => {
const eventRef = firestore.collection('events').doc(context.eventId);
return firestore.runTransaction(t =>
t
.get(eventRef)
.then(docSnap => (docSnap.exists ? null : task(t)))
.then(() => t.set(eventRef, { processed: true }))
);
};
const documentCounter = collectionName => (change, context) =>
executeOnce(change, context, t => {
// on create
if (!change.before.exists && change.after.exists) {
return t
.get(firestore.collection('metadatas')
.doc(collectionName))
.then(docSnap =>
t.set(docSnap.ref, {
count: ((docSnap.data() && docSnap.data().count) || 0) + 1
}));
// on delete
} else if (change.before.exists && !change.after.exists) {
return t
.get(firestore.collection('metadatas')
.doc(collectionName))
.then(docSnap =>
t.set(docSnap.ref, {
count: docSnap.data().count - 1
}));
}
return null;
});
Use cases here:
/**
* Count documents in articles collection.
*/
exports.articlesCounter = functions.firestore
.document('articles/{id}')
.onWrite(documentCounter('articles'));
/**
* Count documents in customers collection.
*/
exports.customersCounter = functions.firestore
.document('customers/{id}')
.onWrite(documentCounter('customers'));
As you can see, the key to prevent multiple execution is the property called eventId in the context object. If the function has been handled many times for the same event, the event id will be the same in all cases. Unfortunately, you must have "events" collection in your database.
I already had "HTTPS//" in the git URL yet faced this error.
All I did was to add option -u with push and it worked.
git push -u origin master
F5 and the refresh button will look at your browser cache before asking the server for content.
Ctrl + F5 forces a load from the server.
You can set content expiration headers and/or meta tags to ensure the browser doesn't cache anything (perhaps something you can do only for the development environment).
I would like to add another use of Virtual function though it uses the same concept as above stated answers but I guess its worth mentioning.
VIRTUAL DESTRUCTOR
Consider this program below, without declaring Base class destructor as virtual; memory for Cat may not be cleaned up.
class Animal {
public:
~Animal() {
cout << "Deleting an Animal" << endl;
}
};
class Cat:public Animal {
public:
~Cat() {
cout << "Deleting an Animal name Cat" << endl;
}
};
int main() {
Animal *a = new Cat();
delete a;
return 0;
}
Output:
Deleting an Animal
class Animal {
public:
virtual ~Animal() {
cout << "Deleting an Animal" << endl;
}
};
class Cat:public Animal {
public:
~Cat(){
cout << "Deleting an Animal name Cat" << endl;
}
};
int main() {
Animal *a = new Cat();
delete a;
return 0;
}
Output:
Deleting an Animal name Cat Deleting an Animal
For Spring version 4.1.3+
I tried Jama's solution, but then all responses were returned with Content-type 'application/json', including the main, generated HTML page.
Overriding configureMessageConverters(...)
prevents spring from setting up the default converters. Spring 4.1.3 allows modification of already configured converters by overriding extendMessageConverters(...)
:
@Configuration
public class ConverterConfig extends WebMvcConfigurerAdapter {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof AbstractJackson2HttpMessageConverter) {
AbstractJackson2HttpMessageConverter c = (AbstractJackson2HttpMessageConverter) converter;
ObjectMapper objectMapper = c.getObjectMapper();
objectMapper.setSerializationInclusion(Include.NON_NULL);
}
}
super.extendMessageConverters(converters);
}
}
see
org.springframework..WebMvcConfigurationSupport#getMessageConverters()
see
org.springframework..WebMvcConfigurationSupport#addDefaultHttpMessageConverters(...)
Starting from API level 5 you can call overridePendingTransition immediately to specify an explicit transition animation:
startActivity();
overridePendingTransition(R.anim.hold, R.anim.fade_in);
or
finish();
overridePendingTransition(R.anim.hold, R.anim.fade_out);
A very easy solution from cssportal.com
If pressed [show], the text [show] will be hidden and other way around.
This example does not work in Chrome, I don't why...
.show {_x000D_
display: none;_x000D_
}_x000D_
.hide:focus + .show {_x000D_
display: inline;_x000D_
}_x000D_
.hide:focus {_x000D_
display: none;_x000D_
}_x000D_
.hide:focus ~ #list { display:none; }_x000D_
@media print {_x000D_
.hide, .show {_x000D_
display: none;_x000D_
}_x000D_
}
_x000D_
<div><a class="hide" href="#">[hide]</a> <a class="show" href="#">[show]</a>_x000D_
<ol id="list">_x000D_
<li>item 1</li>_x000D_
<li>item 2</li>_x000D_
<li>item 3</li>_x000D_
</ol>_x000D_
</div>
_x000D_
If all you are trying to do is solve the content length error from amazon then you could just read the bytes from the input stream to a Long and add that to the metadata.
/*
* Obtain the Content length of the Input stream for S3 header
*/
try {
InputStream is = event.getFile().getInputstream();
contentBytes = IOUtils.toByteArray(is);
} catch (IOException e) {
System.err.printf("Failed while reading bytes from %s", e.getMessage());
}
Long contentLength = Long.valueOf(contentBytes.length);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(contentLength);
/*
* Reobtain the tmp uploaded file as input stream
*/
InputStream inputStream = event.getFile().getInputstream();
/*
* Put the object in S3
*/
try {
s3client.putObject(new PutObjectRequest(bucketName, keyName, inputStream, metadata));
} catch (AmazonServiceException ase) {
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Error Message: " + ace.getMessage());
} finally {
if (inputStream != null) {
inputStream.close();
}
}
You'll need to read the input stream twice using this exact method so if you are uploading a very large file you might need to look at reading it once into an array and then reading it from there.
In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.
So to convert string limit="100"
to a number, you need to do
limit = int(limit) # will return new object (integer) and assign to "limit"
If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:
def int_in_place(mutable):
mutable[0] = int(mutable[0])
mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer
But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).
There is another thread with more examples here: A recursive remove directory function for PHP?
If you are using Yii then you can leave it to the framework:
CFileHelper::removeDirectory($my_directory);
To get the exact output you requested, you can use the below:
CAST(DATEPART(YEAR, @Date) AS NVARCHAR(10)) + ' - Q' + CAST(DATEPART(QUARTER, @Date) AS NVARCHAR(10))
This will give you an outputs like: "2015 - Q1", "2013 - Q3", etc.
a = 10.1234
print(f"{a:0.2f}")
in 0.2f:
A detailed video on f-string for numbers https://youtu.be/RtKUsUTY6to?t=606
A const
to a pointer indicates a "read-only" memory location. Whereas the ones without const
are a read-write memory areas. So, you "cannot" convert a const
(read-only location) to a normal(read-write) location.
The alternate is to copy the data to a different read-write location and pass this pointer to the required function. You may use strdup()
to perform this action.
This worked out for me. I made a custom php code to force redirect it to https. Just include this code on the header.php
<?php
if (isset($_SERVER['HTTPS']) &&
($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
$protocol = 'https://';
}
else {
$protocol = 'http://';
}
$notssl = 'http://';
if($protocol==$notssl){
$url = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";?>
<script>
window.location.href ='<?php echo $url?>';
</script>
<?php } ?>
I had a similar problem when I did major changes to my Podfile. My solution was to remove the workspace file and run pod install
again:
rm -rf MyProject.xcworkspace
pod install
There might be a problem with your DNS servers of the ISP. A computer by default uses the ISP's DNS servers. You can manually configure your DNS servers. It is free and usually better than your ISP.
Preferred DNS server : 8.8.8.8
Alternate DNS server : 8.8.4.4
Preferred DNS server : 208.67.222.222
Alternate DNS server : 208.67.220.220
import java.util.Scanner; import javax.swing.JOptionPane;
public class javaCalculator {
public static void main(String[] args)
{
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("please enter the first number");
num1 = input.nextInt();
System.out.println("please enter the second number");
num2 = input.nextInt();
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation");
operation = op.next();
if (operation.equals("+"))
{
System.out.println("your answer is" + (num1 + num2));
}
else if (operation.equals("-"))
{
System.out.println("your answer is" + (num1 - num2));
}
else if (operation.equals("/"))
{
System.out.println("your answer is" + (num1 / num2));
}
else if (operation.equals("*"))
{
System.out.println("your answer is" + (num1 * num2));
}
else
{
System.out.println("Wrong selection");
}
}
}
self.navigationBar.barTintColor = [UIColor blueColor];
self.navigationBar.tintColor = [UIColor whiteColor];
self.navigationBar.translucent = NO;
// *barTintColor* sets the background color
// *tintColor* sets the buttons color
It stands indeed for whatever, as in whatever works for you
MVC vs MVVM vs MVP. What a controversial topic that many developers can spend hours and hours debating and arguing about.
For several years +AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings and api improvements, it's now closer to MVVM – the $scope object could be considered the ViewModel that is being decorated by a function that we call a Controller.
Being able to categorize a framework and put it into one of the MV* buckets has some advantages. It can help developers get more comfortable with its apis by making it easier to create a mental model that represents the application that is being built with the framework. It can also help to establish terminology that is used by developers.
Having said, I'd rather see developers build kick-ass apps that are well-designed and follow separation of concerns, than see them waste time arguing about MV* nonsense. And for this reason, I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for "whatever works for you".
Angular gives you a lot of flexibility to nicely separate presentation logic from business logic and presentation state. Please use it fuel your productivity and application maintainability rather than heated discussions about things that at the end of the day don't matter that much.
You can loop all of the array and add into ArrayList:
ArrayList<String> files = new ArrayList<String>(filesOrig.length);
for(String file: filesOrig) {
files.add(file);
}
Or use Arrays.asList(T... a)
to do as the comment posted.
Reading answers here, it seems that the error "RenderBox was not laid out" is caused when somehow the ListView size is limitless and this can happen in different scenarios.
Just aiming to help who may have the same case as mine. In my case, I was getting this error because my ListView was inside a a column whose parent was a SingleChildScrollView. I remove this parent and it worked.
Here is my working code:
List _todoList = ["AAA", "BBB"];
...
body: Column(
children: [
Container(...),
Expanded(
child: ListView.builder(
itemCount: _todoList.length,
itemBuilder: (context, index) {
return ListTile(title: Text(_todoList[index]));
}))
],
));
Here how it was when I was getting the "not laid out" error:
List _todoList = ["AAA", "BBB"];
...
body: SingleChildScrollView(child: Column(
children: [
Container(...),
Expanded(
child: ListView.builder(
itemCount: _todoList.length,
itemBuilder: (context, index) {
return ListTile(title: Text(_todoList[index]));
}))
],
)));
I hope this may be useful for someone.
If you're on C# 7, you should consider using value tuples as your composite key. Value tuples typically offer better performance than the traditional reference tuples (Tuple<T1, …>
) since value tuples are value types (structs), not reference types, so they avoid the memory allocation and garbage collection costs. Also, they offer conciser and more intuitive syntax, allowing for their fields to be named if you so wish. They also implement the IEquatable<T>
interface needed for the dictionary.
var dict = new Dictionary<(int PersonId, int LocationId, int SubjectId), string>();
dict.Add((3, 6, 9), "ABC");
dict.Add((PersonId: 4, LocationId: 9, SubjectId: 10), "XYZ");
var personIds = dict.Keys.Select(k => k.PersonId).Distinct().ToList();
For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str
to int
) so you must do this yourself. You'll like that in the long-run, trust me!
In my case the accepted answer did not work. I was calling the API from an MVC application which had no async actions.
This is how I managed to make it work:
private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);
public static T RunSync<T>(Func<Task<T>> func)
{
CultureInfo cultureUi = CultureInfo.CurrentUICulture;
CultureInfo culture = CultureInfo.CurrentCulture;
return _myTaskFactory.StartNew<Task<T>>(delegate
{
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = cultureUi;
return func();
}).Unwrap<T>().GetAwaiter().GetResult();
}
Then I called it like this:
Helper.RunSync(new Func<Task<ReturnTypeGoesHere>>(async () => await AsyncCallGoesHere(myparameter)));
I've tried with
let UUID = UIDevice.currentDevice().identifierForVendor?.UUIDString
instead
let UUID = NSUUID().UUIDString
and it works.
Either you set LDAP_DOMAIN variable or you misconfigured it. Jump inside of ldap machine/container and run:
slapcat > backup.ldif
If it fails, check punctuation, quotes etc while you assigned variable "LDAP_DOMAIN" Otherwise you will find answer inside on backup.ldif file.
You need to make sure that a mac compatible version of java exists on your computer. Do java -version from terminal to check that. If not, download the apple jdk from the apple website. (Sun doesn't make one for apple themselves, IIRC.)
From there, follow the same command line instructions from compiling your program that you would use for java on any other platform.
ssh user@machine 'bash -s' < local_script.sh
or you can just
ssh user@machine "remote command to run"
You can use :visible for visible elements and :hidden to find out hidden elements. This hidden elements have display
attribute set to none
.
hiddenElements = $(':hidden');
visibleElements = $(':visible');
To check particular element.
if($('#yourID:visible').length == 0)
{
}
Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero, Reference
You can also use is() with :visible
if(!$('#yourID').is(':visible'))
{
}
If you want to check value of display then you can use css()
if($('#yourID').css('display') == 'none')
{
}
If you are using display the following values display
can have.
display: none
display: inline
display: block
display: list-item
display: inline-block
Check complete list of possible display
values here.
To check the display property with JavaScript
var isVisible = document.getElementById("yourID").style.display == "block";
var isHidden = document.getElementById("yourID").style.display == "none";
There are situations where it matters.
If you pass AF_INET to socket()
in Cygwin, your socket may or may not be randomly reset. Passing PF_INET ensures that the connection works right.
Cygwin is self-admittedly a huge mess for socket programming, but it is a real world case where AF_INET and PF_INET are not identical.
While the answers above are valid, if you are iterating over a dict {key:value} it this is the approach I like to use:
for key, value in Dictionary.items():
print(key, value)
Therefore, if I wanted to do something like stringify all keys and values in my dictionary, I would do this:
stringified_dictionary = {}
for key, value in Dictionary.items():
stringified_dictionary.update({str(key): str(value)})
return stringified_dictionary
This avoids any mutation issues when applying this type of iteration, which can cause erratic behavior (sometimes) in my experience.
For the ZipArchive
class to be present, PHP needs to have the zip extension installed.
See this page for installation instructions (both Linux and Windows).
Youre looking for the builtin function zip.
In EF 6.2 using FluentAPI, you can use HasIndex()
modelBuilder.Entity<User>().HasIndex(u => u.UserName).IsUnique();
you could use awk. like this...
cat <yourFile> | awk '/word1/ && /word2/'
Order is not important. So if you have a file and...
a file named , file1 contains:
word1 is in this file as well as word2
word2 is in this file as well as word1
word4 is in this file as well as word1
word5 is in this file as well as word2
then,
/tmp$ cat file1| awk '/word1/ && /word2/'
will result in,
word1 is in this file as well as word2
word2 is in this file as well as word1
yes, awk is slower.
you could utilize bootstrap events:: as
//when modal opens
$('#yourModal').on('shown.bs.modal', function (e) {
$("#pageContent").css({ opacity: 0.5 });
})
//when modal closes
$('#yourModal').on('hidden.bs.modal', function (e) {
$("#pageContent").css({ opacity: 1 });
})
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="empTable")
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String empName;
List<Address> addList=new ArrayList<Address>();
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="emp_id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
@OneToMany(mappedBy="employee",cascade=CascadeType.ALL)
public List<Address> getAddList() {
return addList;
}
public void setAddList(List<Address> addList) {
this.addList = addList;
}
}
We have two entities Employee and Address with One to Many relationship.
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="address")
public class Address implements Serializable{
private static final long serialVersionUID = 1L;
private int address_id;
private String address;
Employee employee;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getAddress_id() {
return address_id;
}
public void setAddress_id(int address_id) {
this.address_id = address_id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@ManyToOne
@JoinColumn(name="emp_id")
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
By this way we can implement inner join between two tables
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
public class Main {
public static void main(String[] args) {
saveEmployee();
retrieveEmployee();
}
private static void saveEmployee() {
Employee employee=new Employee();
Employee employee1=new Employee();
Employee employee2=new Employee();
Employee employee3=new Employee();
Address address=new Address();
Address address1=new Address();
Address address2=new Address();
Address address3=new Address();
address.setAddress("1485,Sector 42 b");
address1.setAddress("1485,Sector 42 c");
address2.setAddress("1485,Sector 42 d");
address3.setAddress("1485,Sector 42 a");
employee.setEmpName("Varun");
employee1.setEmpName("Krishan");
employee2.setEmpName("Aasif");
employee3.setEmpName("Dut");
address.setEmployee(employee);
address1.setEmployee(employee1);
address2.setEmployee(employee2);
address3.setEmployee(employee3);
employee.getAddList().add(address);
employee1.getAddList().add(address1);
employee2.getAddList().add(address2);
employee3.getAddList().add(address3);
Session session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(employee);
session.save(employee1);
session.save(employee2);
session.save(employee3);
session.getTransaction().commit();
session.close();
}
private static void retrieveEmployee() {
try{
String sqlQuery="select e from Employee e inner join e.addList";
Session session=HibernateUtil.getSessionFactory().openSession();
Query query=session.createQuery(sqlQuery);
List<Employee> list=query.list();
list.stream().forEach((p)->{System.out.println(p.getEmpName());});
session.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
I have used Java 8 for loop for priting the names. Make sure you have jdk 1.8 with tomcat 8. Also add some more records for better understanding.
public class HibernateUtil {
private static SessionFactory sessionFactory ;
static {
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(Employee.class);
configuration.addAnnotatedClass(Address.class);
configuration.setProperty("connection.driver_class","com.mysql.jdbc.Driver");
configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");
configuration.setProperty("hibernate.connection.username", "root");
configuration.setProperty("hibernate.connection.password", "root");
configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
configuration.setProperty("hibernate.hbm2ddl.auto", "update");
configuration.setProperty("hibernate.show_sql", "true");
configuration.setProperty(" hibernate.connection.pool_size", "10");
// configuration
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
From the javadoc:
The serialization runtime associates with each serializable class a version number, called a
serialVersionUID
, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a differentserialVersionUID
than that of the corresponding sender's class, then deserialization will result in anInvalidClassException
. A serializable class can declare its ownserialVersionUID
explicitly by declaring a field named"serialVersionUID"
that must be static, final, and of type long:
You can configure your IDE to:
As per your additional question "Can it be that the discussed warning message is a reason why my GUI application freeze?":
No, it can't be. It can cause a problem only if you are serializing objects and deserializing them in a different place (or time) where (when) the class has changed, and it will not result in freezing, but in InvalidClassException
.
You can use https://github.com/Mischback/django-project-skeleton repository.
Run below command:
$ django-admin startproject --template=https://github.com/Mischback/django-project-skeleton/archive/development.zip [projectname]
The structure is something like this:
[projectname]/ <- project root
+-- [projectname]/ <- Django root
¦ +-- __init__.py
¦ +-- settings/
¦ ¦ +-- common.py
¦ ¦ +-- development.py
¦ ¦ +-- i18n.py
¦ ¦ +-- __init__.py
¦ ¦ +-- production.py
¦ +-- urls.py
¦ +-- wsgi.py
+-- apps/
¦ +-- __init__.py
+-- configs/
¦ +-- apache2_vhost.sample
¦ +-- README
+-- doc/
¦ +-- Makefile
¦ +-- source/
¦ +-- *snap*
+-- manage.py
+-- README.rst
+-- run/
¦ +-- media/
¦ ¦ +-- README
¦ +-- README
¦ +-- static/
¦ +-- README
+-- static/
¦ +-- README
+-- templates/
+-- base.html
+-- core
¦ +-- login.html
+-- README
EDIT: the following is wrong, because Cell("width") returns the width of the last modified cell.
Cell("width")
returns the width of the current cell, so you don't need a reference to the current cell. If you need one, though, cell("address")
returns the address of the current cell, so if you need a reference to the current cell, use indirect(cell("address"))
. See the documentation: http://www.techonthenet.com/excel/formulas/cell.php
JsVIS was pretty nice, but slow with larger graphs, and has been abandoned since 2007.
prefuse is a set of software tools for creating rich interactive data visualizations in Java. flare is an ActionScript library for creating visualizations that run in the Adobe Flash Player, abandoned since 2012.
Java Reflection is quite powerful and can be very useful. Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.
A quick Java Reflection example to show you what using reflection looks like:
Method[] methods = MyObject.class.getMethods();
for(Method method : methods){
System.out.println("method = " + method.getName());
}
This example obtains the Class object from the class called MyObject. Using the class object the example gets a list of the methods in that class, iterates the methods and print out their names.
Exactly how all this works is explained here
Edit: After almost 1 year I am editing this answer as while reading about reflection I got few more uses of Reflection.
<bean id="someID" class="com.example.Foo">
<property name="someField" value="someValue" />
</bean>
When the Spring context processes this < bean > element, it will use Class.forName(String) with the argument "com.example.Foo" to instantiate that Class.
It will then again use reflection to get the appropriate setter for the < property > element and set its value to the specified value.
For Private methods,
Method method = targetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);
For private fields,
Field field = targetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);
If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
Also see this SO thread: Open directory dialog
Use the below statement to delete any files:
FileUtils.forceDelete(FilePath);
Note: Use exception handling
codes if you want to use.
It's simple:
from django.http import HttpResponseRedirect
def myview(request):
...
return HttpResponseRedirect("/path/")
More info in the official Django docs
Update: Django 1.0
There is apparently a better way of doing this in Django now using generic views
.
Example -
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
(r'^one/$', redirect_to, {'url': '/another/'}),
#etc...
)
There is more in the generic views documentation. Credit - Carles Barrobés.
Update #2: Django 1.3+
In Django 1.5 redirect_to no longer exists and has been replaced by RedirectView. Credit to Yonatan
from django.views.generic import RedirectView
urlpatterns = patterns('',
(r'^one/$', RedirectView.as_view(url='/another/')),
)
SELECT Subject, CONVERT(varchar(10),DeliveryDate) as DeliveryDate
from Email_Administration
where MerchantId =@ MerchantID
if (isset($_POST['Register']))
{
$ErrorArrays = array (); //Empty array for input errors
$Input_Username = $_POST['Username'];
$Input_Password = $_POST['Password'];
$Input_Confirm = $_POST['ConfirmPass'];
$Input_Email = $_POST['Email'];
if (empty($Input_Username))
{
$ErrorArrays[] = "Username Is Empty";
}
if (empty($Input_Password))
{
$ErrorArrays[] = "Password Is Empty";
}
if ($Input_Password !== $Input_Confirm)
{
$ErrorArrays[] = "Passwords Do Not Match!";
}
if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
{
$ErrorArrays[] = "Incorrect Email Formatting";
}
if (count($ErrorArrays) == 0)
{
// No Errors
}
else
{
foreach ($ErrorArrays AS $Errors)
{
echo "<font color='red'><b>".$Errors."</font></b><br>";
}
}
}
?>
<form method="POST">
Username: <input type='text' name='Username'> <br>
Password: <input type='password' name='Password'><br>
Confirm Password: <input type='password' name='ConfirmPass'><br>
Email: <input type='text' name='Email'> <br><br>
<input type='submit' name='Register' value='Register'>
</form>
This is a very basic PHP Form validation. This could be put in a try
block, but for basic reference, I see this fit following our conversation in the comment box.
What this script will do, is process each of the post elements, and act accordingly, for example:
if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
{
$ErrorArrays[] = "Incorrect Email Formatting";
}
This will check:
if $Input_Email is not a valid email. If this is not a valid E-mail, then a message will get added to a empty array.
Further down the script, you will see:
if (count($ErrorArrays) == 0)
{
// No Errors
}
else
{
foreach ($ErrorArrays AS $Errors)
{
echo "<font color='red'><b>".$Errors."</font></b><br>";
}
}
Basically. if the array count is not 0, errors have been found. Then the script will print out the errors.
Remember, this is a reference based on our conversation in the comment box, and should be used as such.
In [34]: import pandas as pd
In [35]: import numpy as np
In [36]: df = pd.DataFrame([1,2,3,4], columns=["data"])
In [37]: df
Out[37]:
data
0 1
1 2
2 3
3 4
In [38]: df["desired_output"] = np.where(df["data"] <2.5, "False", "True")
In [39]: df
Out[39]:
data desired_output
0 1 False
1 2 False
2 3 True
3 4 True
I came here to provide a more up-to-date solution, because I wasn't satisfied with the existing answers.
I needed something that would work for translated texts and does not have the performance hit of using Html.fromHtml()
.
If you're using Kotlin, here is an extension function which will easily set multiple parts of your text to bold. This works just like Markdown, and could be extended to support other Markdown tags, if need be.
val yourString = "**This** is your **string**.".makePartialTextsBold()
val anotherString = getString(R.string.something).makePartialTextsBold()
/**
* This function requires that the parts of the string that need
* to be bolded are wrapped in ** and ** tags
*/
fun String.makePartialTextsBold(): SpannableStringBuilder {
var copy = this
return SpannableStringBuilder().apply {
var setSpan = true
var next: String
do {
setSpan = !setSpan
next = if (length == 0) copy.substringBefore("**", "") else copy.substringBefore("**")
val start = length
append(next)
if (setSpan) {
setSpan(StyleSpan(Typeface.BOLD), start, length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
copy = copy.removePrefix(next).removePrefix("**")
} while (copy.isNotEmpty())
}
}
For people using Kotlin, inazaruk's answer will not work, the IDE will require the variable to be initialized, so instead of using the postDelayed
inside the Runnable
, we'll use it in an separate method.
Initialize your Runnable
like this :
private var myRunnable = Runnable {
//Do some work
//Magic happens here ?
runDelayedHandler(1000) }
Initialize your runDelayedHandler
method like this :
private fun runDelayedHandler(timeToWait : Long) {
if (!keepRunning) {
//Stop your handler
handler.removeCallbacksAndMessages(null)
//Do something here, this acts like onHandlerStop
}
else {
//Keep it running
handler.postDelayed(myRunnable, timeToWait)
}
}
As you can see, this approach will make you able to control the lifetime of the task, keeping track of keepRunning
and changing it during the lifetime of the application will do the job for you.
copy the below content to file tomcat-users.xml
<?xml version='1.0' encoding='utf-8'?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<tomcat-users xmlns="http://tomcat.apache.org/xml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
version="1.0">
<!--
NOTE: By default, no user is included in the "manager-gui" role required
to operate the "/manager/html" web application. If you wish to use this app,
you must define such a user - the username and password are arbitrary. It is
strongly recommended that you do NOT use one of the users in the commented out
section below since they are intended for use with the examples web
application.
-->
<!--
NOTE: The sample user and role entries below are intended for use with the
examples web application. They are wrapped in a comment and thus are ignored
when reading this file. If you wish to configure these users for use with the
examples web application, do not forget to remove the <!.. ..> that surrounds
them. You will also need to set the passwords to something appropriate.
-->
<!--
<role rolename="tomcat"/>
<role rolename="role1"/>
<user username="tomcat" password="<must-be-changed>" roles="tomcat"/>
<user username="both" password="<must-be-changed>" roles="tomcat,role1"/>
<user username="role1" password="<must-be-changed>" roles="role1"/>
-->
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<user username="notadmin" password="not_real_pass" roles="manager-gui"/>
<user username="cargo" password="not_real_pass" roles="manager-script"/>
</tomcat-users>
I have tested, it just works!
Let's first look at the definitions of these words before evaluating what the difference is in HTML:
English definition:
In HTML context:
When the browser parses the HTML, it creates a tree data structure wich basically is an in memory representation of the HTML. It the tree data structure contains nodes which are HTML elements and text. Attributes and properties relate to this is the following manner:
It is also important to realize that the mapping of these properties is not 1 to 1. In other words, not every attribute which we give on an HTML element will have a similar named DOM property.
Furthermore have different DOM elements different properties. For example, an <input>
element has a value property which is not present on a <div>
property.
Let's take the following HTML document:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> <!-- charset is a attribute -->
<meta name="viewport" content="width=device-width"> <!-- name and content are attributes -->
<title>JS Bin</title>
</head>
<body>
<div id="foo" class="bar foobar">hi</div> <!-- id and class are attributes -->
</body>
</html>
Then we inspect the <div>
, in the JS console:
console.dir(document.getElementById('foo'));
We see the following DOM properties (chrome devtools, not all properties shown):
class
is reserved keyword in JS). But actually 2 properties, classList
and className
.For those looking for an SCSS mixin instead, including woff2:
@mixin fface($path, $family, $type: '', $weight: 400, $svg: '', $style: normal) {
@font-face {
font-family: $family;
@if $svg == '' {
// with OTF without SVG and EOT
src: url('#{$path}#{$type}.otf') format('opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype');
} @else {
// traditional src inclusions
src: url('#{$path}#{$type}.eot');
src: url('#{$path}#{$type}.eot?#iefix') format('embedded-opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype'), url('#{$path}#{$type}.svg##{$svg}') format('svg');
}
font-weight: $weight;
font-style: $style;
}
}
// ========================================================importing
$dir: '/assets/fonts/';
$famatic: 'AmaticSC';
@include fface('#{$dir}amatic-sc-v11-latin-regular', $famatic, '', 400, $famatic);
$finter: 'Inter';
// adding specific types of font-weights
@include fface('#{$dir}#{$finter}', $finter, '-Thin-BETA', 100);
@include fface('#{$dir}#{$finter}', $finter, '-Regular', 400);
@include fface('#{$dir}#{$finter}', $finter, '-Medium', 500);
@include fface('#{$dir}#{$finter}', $finter, '-Bold', 700);
// ========================================================usage
.title {
font-family: Inter;
font-weight: 700; // Inter-Bold font is loaded
}
.special-title {
font-family: AmaticSC;
font-weight: 700; // default font is loaded
}
The $type
parameter is useful for stacking related families with different weights.
The @if
is due to the need of supporting the Inter font (similar to Roboto), which has OTF but doesn't have SVG and EOT types at this time.
If you get a can't resolve error, remember to double check your fonts directory ($dir
).
The type char is a primitive -- not an object -- so it cannot be dereferenced
Dereferencing is the process of accessing the value referred to by a reference. Since a char is already a value (not a reference), it can not be dereferenced.
use Character
class:
if(Character.isLetter(c)) {
This will get selected value from multi-value select boxes: $("#id option:selected").val()
Okay, per http://www.oracle.com/technology/tech/globalization/htdocs/nls_lang%20faq.htm:
NLS_LANG cannot be changed by ALTER SESSION, NLS_LANGUAGE and NLS_TERRITORY can. However NLS_LANGUAGE and /or NLS_TERRITORY cannot be set as "standalone" parameters in the environment or registry on the client.
Evidently the "right" solution is, before logging into Oracle at all, setting the following environment variable:
export NLS_LANG=AMERICAN_AMERICA.UTF8
Oracle gets a big fat F for usability.
you can use cURL library for posting data: http://www.php.net/curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);
where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects
you might want to look at the online version of xsv
Right now with using Spring-Boot 2.0.4 - { } won't work.
@RequestMapping
still has String[] as a value parameter, so declaration looks like this:
@RequestMapping(value=["/","/index","/login","/home"], method = RequestMethod.GET)
** Update - Works With Spring-Boot 2.2**
@RequestMapping(value={"/","/index","/login","/home"}, method = RequestMethod.GET)
There is an another way to see XML SOAP - custom MessageEncoder. The main difference from IClientMessageInspector is that it works on lower level, so it captures original byte content including any malformed xml.
In order to implement tracing using this approach you need to wrap a standard textMessageEncoding with custom message encoder as new binding element and apply that custom binding to endpoint in your config.
Also you can see as example how I did it in my project - wrapping textMessageEncoding, logging encoder, custom binding element and config.
I had the same issue with SQL Server 2014 locally installed named instance. Connecting using the FQDN\InstanceName
would fail, while connecting using only my hostname\InstanceName
worked. For example: connecting using mycomputername\sql2014
worked, but using mycomputername.mydomain.org\sql2014
did not. DNS resolved correctly, TCP/IP was enabled within SQL Configuration Manager, Windows Firewall rules added (and then turned the firewall off for testing to ensure it wasn't blocking anything), but none of those fixed the problem.
Finally, I had to start the "SQL Server Browser" service on the SQL Server and that fixed the connectivity issue.
I had never realized that the SQL Server Browser service actually assisted the SQL Server in making connections; I was under the impression that it simply helped populate the dropdowns when you clicked "browse for more" servers to connect to, but it actually helps align client requests with the correct port # to use, if the port # is not explicitly assigned (similar to how website bindings help alleviate the same issue on an IIS web server that hosts multiple websites).
This connect item is what gave me the clue about the SQL Server Browser service: https://connect.microsoft.com/SQLServer/feedback/details/589901/unable-to-connect-on-localhost-using-fqdn-machine-name
- when you use wstst05\sqlexpress as a server name, the client code separates the machine name from the instance name and the wstst05 is compared against the netbios name. I see no problem for them to match and the connection is considered local. From there, we retrieve the needed information WITHOUT contacting SQL Browser and connect to the SQL instance via Shared Memory without any problem.
- when you use wstst05.capatest.local\sqlexpress, the client code fails the comparison of the name (wstst05.capatest.local) to the netbios name (wstst05) and considers the connection "remote". This is by design and we will definitely consider improving this in the future. Anyway, due to considering the connection remote and the fact that it is a named instance, client decides that it needs to use SQLBrowser for name resolution. It attempts to contact SQL Browser on wstst05.capatest.local (UDP port 1434) and apparently that part fails. Hence the error you get.
The reason for the "SQL Server Browser" service from TechNet (emphasis added by me): https://technet.microsoft.com/en-us/library/ms181087(v=sql.120).aspx
From the "Using SQL Server Browser" section:
If the SQL Server Browser service is not running, you are still able to connect to SQL Server if you provide the correct port number or named pipe. For instance, you can connect to the default instance of SQL Server with TCP/IP if it is running on port 1433. However, if the SQL Server Browser service is not running, the following connections do not work:
- Any component that tries to connect to a named instance without fully specifying all the parameters (such as the TCP/IP port or named pipe).
- Any component that generates or passes server\instance information that could later be used by other components to reconnect.
- Connecting to a named instance without providing the port number or pipe.
- DAC to a named instance or the default instance if not using TCP/IP port 1433.
- The OLAP redirector service.
- Enumerating servers in SQL Server Management Studio, Enterprise Manager, or Query Analyzer.
If you are using SQL Server in a client-server scenario (for example, when your application is accessing SQL Server across a network), if you stop or disable the SQL Server Browser service, you must assign a specific port number to each instance and write your client application code to always use that port number. This approach has the following problems:
- You must update and maintain client application code to ensure it is connecting to the proper port.
- The port you choose for each instance may be used by another service or application on the server, causing the instance of SQL Server to be unavailable.
And more info from the same article from the "How SQL Server Browser Works" section:
Because only one instance of SQL Server can use a port or pipe, different port numbers and pipe names are assigned for named instances, including SQL Server Express. By default, when enabled, both named instances and SQL Server Express are configured to use dynamic ports, that is, an available port is assigned when SQL Server starts. If you want, a specific port can be assigned to an instance of SQL Server. When connecting, clients can specify a specific port; but if the port is dynamically assigned, the port number can change anytime SQL Server is restarted, so the correct port number is unknown to the client. ... When SQL Server clients request SQL Server resources, the client network library sends a UDP message to the server using port 1434. SQL Server Browser responds with the TCP/IP port or named pipe of the requested instance. The network library on the client application then completes the connection by sending a request to the server using the port or named pipe of the desired instance
You can use something like this:
$('#your-button').text('New Value');
You can also add extra properties like this:
$(this).text('New Value').attr('disabled', true).addClass('bt-hud').unbind('click');
The file in question is not using the CP1252
encoding. It's using another encoding. Which one you have to figure out yourself. Common ones are Latin-1
and UTF-8
. Since 0x90 doesn't actually mean anything in Latin-1
, UTF-8
(where 0x90 is a continuation byte) is more likely.
You specify the encoding when you open the file:
file = open(filename, encoding="utf8")
You could use a library such as node-uuid for this to make sure you get unique ids.
Install using:
npm install node-uuid --save
Then in your react component add the following:
import {default as UUID} from "node-uuid";
import {default as React} from "react";
export default class MyComponent extends React.Component {
componentWillMount() {
this.id = UUID.v4();
},
render() {
return (
<div>
<label htmlFor={this.id}>My label</label>
<input id={this.id} type="text"/>
</div>
);
}
}
DateTime.Today
as it implies is todays date and you need to get the Date a day before so you subtract one day using AddDays(-1)
;
There are sufficient options available in DateTime to get the formatting like ToShortDateString
depending on your culture and you have no need to concatenate them individually.
Also you can have a desirable format in the .ToString()
version of the DateTime
instance
You can use python-docx2txt which is adapted from python-docx but can also extract text from links, headers and footers. It can also extract images.
Put empty value if the value does not exist or null.
value={ this.state.value || "" }
On apache page: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html
You have something like this:
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("www.google.com").setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.setParameter("aq", "f")
.setParameter("oq", "");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
I think it will help you
string filename = String.Format("Results_{0}_{1}.xls", DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString());
if (!string.IsNullOrEmpty(GRIDVIEWNAME.Page.Title))
filename = GRIDVIEWNAME.Page.Title + ".xls";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.Charset = "";
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
GRIDVIEWNAME.Parent.Controls.Add(form);
form.Controls.Add(GRIDVIEWNAME);
form.RenderControl(htmlWriter);
HttpContext.Current.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
HttpContext.Current.Response.Write(stringWriter.ToString());
HttpContext.Current.Response.End();
Instead of using a Label class, I would recommend using a TextBlock. This allows you to set the TextWrapping appropriately.
You can always do:
label1.Content = new TextBlock() { Text = textBox1.Text, TextWrapping = TextWrapping.Wrap };
However, if all this "label" is for is to display text, use a TextBlock
instead.