MODERN REVISION: you also now need to fix it by changing the little known ''security.limit_extensions' in php-fpm doing this. You will probably already know the well documented mechanism of changing apache to AddHandler/AddType I will not go into that here.
YOU MUST find out where php-fpm/conf is in your set up. I did it by doing this
# grep -rnw '/etc/' -e 'security.limit_extensions'
I got this back
'/etc/php-fpm.d/www.conf:387:;security.limit_extensions = .php .php3 .php4 .php5 .php7'
go to this file, edit it and MAKE SURE YOU REALISE IT IS COMMENTED OUT
EG: change it from ';security.limit_extensions = .php .php3 .php4 .php5 .php7'
<- NB: note the ";"
- this line is actually DISABLED by default - and you do not need all the nonsense extensions, in fact they are probably dangerous.. change it to 'security.limit_extensions = .php .htm'
<- note the semi colon is now removed. then restart apache/(or nginx) and restart php-fpm # service php-fpm restart
# service httpd restart
refer intel.com's requirements : Important: Intel HAXM cannot be used on systems without an Intel processor, or with an Intel processor that lacks the hardware features described in the "Hardware Requirements" section above.To determine the capabilities of your Intel processor
[Installation Instructions for Intel® Hardware Accelerated Execution Manager ] https://software.intel.com/en-us/android/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-mac-os-x
My PC does not support vt-x, I can not use android studio 1.0.2.
I open a text editor, in my case I used Atom. Paste this code
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
and save as
helloworld.js
in
c:\xampp\htdocs\myproject
directory. Next I open node.js commamd prompt enter
cd c:\xampp\htdocs\myproject
next
node helloworld.js
next I open my chrome browser and I type
http://localhost:1337
and there it is.
Install the MSI file:
Go to the installed directory C:\Program Files\nodejs
from command prompt n
C:\>cd C:\Program Files\nodejs enter..
node helloworld.js
output:
Hello World
In latest XAMPP version; You need to find only intl(Line no 912)in php.ini file. Change ;extension=intl To extension=intl
If you are using a MVVM, based on @rudigrobler answer you can do the following:
Add the following property to the ViewModel class
public Array ExampleEnumValues => Enum.GetValues(typeof(ExampleEnum));
Then in the XAML do the following:
<ComboBox ItemsSource="{Binding ExampleEnumValues}" ... />
Qt provides the simplest API
const char *qPrintable(const QString &str)
const char *qUtf8Printable(const QString &str)
If you want non-const data pointer use
str.toLocal8Bit().data()
str.toUtf8().data()
Email validation is easy to get wrong. I would therefore recommend that you use Verimail.js.
Why?
Another great thing with Verimail.js is that it has spelling suggestion for the most common email domains and registered TLDs. This can lower your bounce rate drastically for users that misspell common domain names such as gmail.com, hotmail.com, aol.com, aso..
Example:
How to use it?
The easiest way is to download and include verimail.jquery.js on your page. After that, hookup Verimail by running the following function on the input-box that needs the validation:
$("input#email-address").verimail({
messageElement: "p#status-message"
});
The message element is an optional element that displays a message such as "Invalid email.." or "Did you mean [email protected]?". If you have a form and only want to proceed if the email is verified, you can use the function getVerimailStatus as shown below:
if($("input#email-address").getVerimailStatus() < 0){
// Invalid email
}else{
// Valid email
}
The getVerimailStatus-function returns an integer code according to the object Comfirm.AlphaMail.Verimail.Status. As shown above, if the status is a negative integer value, then the validation should be treated as a failure. But if the value is greater or equal to 0, then the validation should be treated as a success.
Just json.dumps will fix the problem
json.dumps function actually converts all the unicode literals to string literals and it will be easy for us to load the data either in json file or csv file.
sample code:
import json
EmployeeList = [u'1001', u'Karick', u'14-12-2020', u'1$']
result_list = json.dumps(EmployeeList)
print result_list
output: ["1001", "Karick", "14-12-2020", "1$"]
You might find useful mosaic
plot from statsmodels. Which can also give statistical highlighting for the variances.
from statsmodels.graphics.mosaicplot import mosaic
plt.rcParams['font.size'] = 16.0
mosaic(df, ['direction', 'colour']);
But beware of the 0 sized cell - they will cause problems with labels.
See this answer for details
You need to set property for the control:
listView1.View = View.Details;
Just wait. In a few minutes all will be ok.
Just to add to the correct answer above, in Vue.JS v1.0 you can write
<a v-on:click="doSomething">
So in this example it would be
v-on:change="foo"
I also had to save Base64 encoded images that are part of data URLs, so I ended up making a small npm module to do it in case I (or someone else) needed to do it again in the future. It's called ba64.
Simply put, it takes a data URL with a Base64 encoded image and saves the image to your file system. It can save synchronously or asynchronously. It also has two helper functions, one to get the file extension of the image, and the other to separate the Base64 encoding from the data:
scheme prefix.
Here's an example:
var ba64 = require("ba64"),
data_url = "data:image/jpeg;base64,[Base64 encoded image goes here]";
// Save the image synchronously.
ba64.writeImageSync("myimage", data_url); // Saves myimage.jpeg.
// Or save the image asynchronously.
ba64.writeImage("myimage", data_url, function(err){
if (err) throw err;
console.log("Image saved successfully");
// do stuff
});
Install it: npm i ba64 -S
. Repo is on GitHub: https://github.com/HarryStevens/ba64.
P.S. It occurred to me later that ba64 is probably a bad name for the module since people may assume it does Base64 encoding and decoding, which it doesn't (there are lots of modules that already do that). Oh well.
if($var == "abc" || $var == "def" || ...)
{
echo "true";
}
Using "Or" instead of "And" would help here, i think
Mark, this is already answered in your previous topic. But OK, here it is again:
Suppose ${list}
points to a List<Object>
, then the following
<c:forEach items="${list}" var="item">
${item}<br>
</c:forEach>
does basically the same as as following in "normal Java":
for (Object item : list) {
System.out.println(item);
}
If you have a List<Map<K, V>>
instead, then the following
<c:forEach items="${list}" var="map">
<c:forEach items="${map}" var="entry">
${entry.key}<br>
${entry.value}<br>
</c:forEach>
</c:forEach>
does basically the same as as following in "normal Java":
for (Map<K, V> map : list) {
for (Entry<K, V> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
The key
and value
are here not special methods or so. They are actually getter methods of Map.Entry
object (click at the blue Map.Entry
link to see the API doc). In EL (Expression Language) you can use the .
dot operator to access getter methods using "property name" (the getter method name without the get
prefix), all just according the Javabean specification.
That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".
Use the DateTime.SpecifyKind
static method.
Creates a new DateTime object that has the same number of ticks as the specified DateTime, but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value.
Example:
DateTime dateTime = DateTime.Now;
DateTime other = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
Console.WriteLine(dateTime + " " + dateTime.Kind); // 6/1/2011 4:14:54 PM Local
Console.WriteLine(other + " " + other.Kind); // 6/1/2011 4:14:54 PM Utc
The following replaces variables of the form <<VAR>>
, with values looked up from a Map. You can test it online here
For example, with the following input string
BMI=(<<Weight>>/(<<Height>>*<<Height>>)) * 70
Hi there <<Weight>> was here
and the following variable values
Weight, 42
Height, HEIGHT 51
outputs the following
BMI=(42/(HEIGHT 51*HEIGHT 51)) * 70
Hi there 42 was here
Here's the code
static Pattern pattern = Pattern.compile("<<([a-z][a-z0-9]*)>>", Pattern.CASE_INSENSITIVE);
public static String replaceVarsWithValues(String message, Map<String,String> varValues) {
try {
StringBuffer newStr = new StringBuffer(message);
int lenDiff = 0;
Matcher m = pattern.matcher(message);
while (m.find()) {
String fullText = m.group(0);
String keyName = m.group(1);
String newValue = varValues.get(keyName)+"";
String replacementText = newValue;
newStr = newStr.replace(m.start() - lenDiff, m.end() - lenDiff, replacementText);
lenDiff += fullText.length() - replacementText.length();
}
return newStr.toString();
} catch (Exception e) {
return message;
}
}
public static void main(String args[]) throws Exception {
String testString = "BMI=(<<Weight>>/(<<Height>>*<<Height>>)) * 70\n\nHi there <<Weight>> was here";
HashMap<String,String> values = new HashMap<>();
values.put("Weight", "42");
values.put("Height", "HEIGHT 51");
System.out.println(replaceVarsWithValues(testString, values));
}
and although not requested, you can use a similar approach to replace variables in a string with properties from your application.properties file, though this may already be being done:
private static Pattern patternMatchForProperties =
Pattern.compile("[$][{]([.a-z0-9_]*)[}]", Pattern.CASE_INSENSITIVE);
protected String replaceVarsWithProperties(String message) {
try {
StringBuffer newStr = new StringBuffer(message);
int lenDiff = 0;
Matcher m = patternMatchForProperties.matcher(message);
while (m.find()) {
String fullText = m.group(0);
String keyName = m.group(1);
String newValue = System.getProperty(keyName);
String replacementText = newValue;
newStr = newStr.replace(m.start() - lenDiff, m.end() - lenDiff, replacementText);
lenDiff += fullText.length() - replacementText.length();
}
return newStr.toString();
} catch (Exception e) {
return message;
}
}
JPA 2.1 (finally) adds support for indexes and foreign keys! See this blog for details. JPA 2.1 is a part of Java EE 7, which is out .
If you like living on the edge, you can get the latest snapshot for eclipselink from their maven repository (groupId:org.eclipse.persistence, artifactId:eclipselink, version:2.5.0-SNAPSHOT). For just the JPA annotations (which should work with any provider once they support 2.1) use artifactID:javax.persistence, version:2.1.0-SNAPSHOT.
I'm using it for a project which won't be finished until after its release, and I haven't noticed any horrible problems (although I'm not doing anything too complex with it).
UPDATE (26 Sep 2013): Nowadays release and release candidate versions of eclipselink are available in the central (main) repository, so you no longer have to add the eclipselink repository in Maven projects. The latest release version is 2.5.0 but 2.5.1-RC3 is also present. I'd switch over to 2.5.1 ASAP because of issues with the 2.5.0 release (the modelgen stuff doesn't work).
SAP ABAP programming? "Teach Yourself ABAP in 21 Days" is the best book!
It contains no clever tricks or wizardry, but after 3 years, I never came upon a more comprehensive book
Are the users able to convert the apk file of my application back to the actual code?
yes.
People can use various tools to:
FDex2
to dump out dex
file
dex2jar
to convert to jar
jadx
to conver to java
source codeIf they do - is there any way to prevent this?
yes. Several (can combined) ways to prevent (certain degree) this:
ProGuard
More details can refer my Chinese tutorial: ??????????
• real: The actual time spent in running the process from start to finish, as if it was measured by a human with a stopwatch
• user: The cumulative time spent by all the CPUs during the computation
• sys: The cumulative time spent by all the CPUs during system-related tasks such as memory allocation.
Notice that sometimes user + sys might be greater than real, as multiple processors may work in parallel.
I know this is a different twist on the answer, but isn't this more of a concern for a web server? For example, nginx, could help.
The ngx_http_headers_module module allows adding the “Expires” and “Cache-Control” header fields, and arbitrary fields, to a response header
...
location ~ ^<REGXP MATCHING CORS ROUTES> {
add_header Access-Control-Allow-Methods POST
...
}
...
Adding nginx in front of your go service in production seems wise. It provides a lot more feature for authorizing, logging,and modifying requests. Also, it gives the ability to control who has access to your service and not only that but one can specify different behavior for specific locations in your app, as demonstrated above.
I could go on about why to use a web server with your go api, but I think that's a topic for another discussion.
I thought i will add some light to this post on what i know. We used this technique extensively in our recent android project
. Instead of creating objects using new operator
you can also use static method
to instantiate a class. Code listing:
//instantiating a class using constructor
Vinoth vin = new Vinoth();
//instantiating the class using static method
Class Vinoth{
private Vinoth(){
}
// factory method to instantiate the class
public static Vinoth getInstance(){
if(someCondition)
return new Vinoth();
}
}
Static methods support conditional object creation: Each time you invoke a constructor an object will get created but you might not want that. suppose you want to check some condition only then you want to create a new object.You would not be creating a new instance of Vinoth each time, unless your condition is satisfied.
Another example taken from Effective Java.
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
This method translates a boolean primitive value into a Boolean object reference. The Boolean.valueOf(boolean)
method illustrates us, it never creates an object. The ability of static factory methods
to return the same object from repeated invocations
allows classes to maintain strict control over what instances exist at any time.
Static factory methods
is that, unlike constructors
, they can return an object
of any subtype
of their return type. One application of this flexibility is that an API can return objects without making their classes public. Hiding implementation classes in this fashion leads to a very compact API.
Calendar.getInstance() is a great example for the above, It creates depending on the locale a BuddhistCalendar
, JapaneseImperialCalendar
or by default one Georgian
.
Another example which i could think is Singleton pattern
, where you make your constructors private create an own getInstance
method where you make sure, that there is always just one instance available.
public class Singleton{
//initailzed during class loading
private static final Singleton INSTANCE = new Singleton();
//to prevent creating another instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}
I was able to connect from SSMS using "(LocalDb)\Projects". That's the way it appears in VS2012 as well.
A handy way to achieve this would be:
df.groupby('a').agg({'b':lambda x: list(x)})
Look into writing Custom Aggregations: https://www.kaggle.com/akshaysehgal/how-to-group-by-aggregate-using-py
Other answers are correct to suggest Sort
, but they seem to have missed the fact that the storage location is typed as IList<string
. Sort
is not part of the interface.
If you know that ListaServizi
will always contain a List<string>
, you can either change its declared type, or use a cast. If you're not sure, you can test the type:
if (typeof(List<string>).IsAssignableFrom(ListaServizi.GetType()))
((List<string>)ListaServizi).Sort();
else
{
//... some other solution; there are a few to choose from.
}
Perhaps more idiomatic:
List<string> typeCheck = ListaServizi as List<string>;
if (typeCheck != null)
typeCheck.Sort();
else
{
//... some other solution; there are a few to choose from.
}
If you know that ListaServizi
will sometimes hold a different implementation of IList<string>
, leave a comment, and I'll add a suggestion or two for sorting it.
I usually use selectors in my main stylesheet, then make an ie6 specific .js (jquery) file that adds a class to all of the input types. Example:
$(document).ready(function(){
$("input[type='text']").addClass('text');
)};
And then just duplicate my styles in the ie6 specific stylesheet using the classes. That way the actual markup is a little bit cleaner.
try this it may help you
$.ajax({
type:"post",
url:"clientnetworkpricelist/yourfile.php",
data:"title="+clientid,
beforeSend: function( ) {
// load your loading fiel here
}
})
.done(function( data ) {
//hide your loading file here
});
You could try implemeting something like this: http://www.codeproject.com/KB/cs/reporting__windowsforms.aspx
I've run into the very same issue, when mistakenly named variable with the very same name, as function.
So this:
isLive = isLive(data);
failed, generating OP's mentioned error message.
Fix to this was as simple as changing above line to:
isItALive = isLive(data);
I don't know, how much does it helps in this situation, but I decided to put this answer for others looking for a solution for similar problems.
I guess this may work, in Eclipse select your project ? then click on project menu bar on top ? goto to properties ? click on Targeted Runtimes ? now you must select a check box next to the server you are using to run current project ? click Apply ? then click OK button. That's it, give a try.
What happens is when these elements are called before the DOM is loaded these kind of errors come up. Always use:
window.onload = function(){
this.keywordsInput.nativeElement.focus();
}
I decided not to touch headers and make a redirect on the server side instead and it woks like a charm.
The example below is for the current version of Angular (currently 9) and probably any other framework using webpacks DevServer. But I think the same principle will work on other backends.
So I use the following configuration in the file proxy.conf.json:
{
"/api": {
"target": "http://localhost:3000",
"pathRewrite": {"^/api" : ""},
"secure": false
}
}
In case of Angular I serve with that configuration:
$ ng serve -o --proxy-config=proxy.conf.json
I prefer to use the proxy in the serve command, but you may also put this configuration to angular.json like this:
"architect": {
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your-application-name:build",
"proxyConfig": "src/proxy.conf.json"
},
See also:
https://www.techiediaries.com/fix-cors-with-angular-cli-proxy-configuration/
https://webpack.js.org/configuration/dev-server/#devserverproxy
Are you creating a very large table (hundreds of rows and columns)? If so, table-layout: fixed;
is a good idea, as the browser only needs to read the first row in order to compute and render the entire table
, so it loads faster.
But if not, I would suggest dumping table-layout: fixed;
and changing your css as follows:
table th, table td{
border: 1px solid #000;
width:20px; //or something similar
}
table td.wideRow, table th.wideRow{
width: 300px;
}
According to the documentation, the static method UUID.randomUUID()
generates a type 4 UUID.
This means that six bits are used for some type information and the remaining 122 bits are assigned randomly.
The six non-random bits are distributed with four in the most significant half of the UUID and two in the least significant half. So the most significant half of your UUID contains 60 bits of randomness, which means you on average need to generate 2^30 UUIDs to get a collision (compared to 2^61 for the full UUID).
So I would say that you are rather safe. Note, however that this is absolutely not true for other types of UUIDs, as Carl Seleborg mentions.
Incidentally, you would be slightly better off by using the least significant half of the UUID (or just generating a random long using SecureRandom).
There is an ES7 proposal for RegExp.escape at https://github.com/benjamingr/RexExp.escape/, with a polyfill available at https://github.com/ljharb/regexp.escape.
Great Start. Here's what I came up with:
$('img.resize').each(function(){
$(this).load(function(){
var maxWidth = $(this).width(); // Max width for the image
var maxHeight = $(this).height(); // Max height for the image
$(this).css("width", "auto").css("height", "auto"); // Remove existing CSS
$(this).removeAttr("width").removeAttr("height"); // Remove HTML attributes
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
if(width > height) {
// Check if the current width is larger than the max
if(width > maxWidth){
var ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
}
} else {
// Check if current height is larger than max
if(height > maxHeight){
var ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
}
}
});
});
This has the benefit of allowing you to specify both width and height while allowing the image to still scale proportionally.
file
-> Project Structure
-> Modules
, find the module with problems, click it and choose the Dependencies
tab in the right side. Click the green plus sign, try to add the jar or libraries that cause the problem. That works for me.
Why not type this is the urlbar?
javascript:alert(document.body.innerHTML)
If you want a pure CSS solution, this trick works very well - use the transform object. This also works with images when they're cached or not:
CSS:
.main_container{
position: relative;
width: 500px;
height: 300px;
background-color: #cccccc;
}
.center_horizontally{
position: absolute;
width: 100px;
height: 100px;
background-color: green;
left: 50%;
top: 0;
transform: translate(-50%,0);
}
.center_vertically{
position: absolute;
top: 50%;
left: 0;
width: 100px;
height: 100px;
background-color: blue;
transform: translate(0,-50%);
}
.center{
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
background-color: red;
transform: translate(-50%,-50%);
}
HTML:
<div class="main_container">
<div class="center_horizontally"></div>
<div class="center_vertically"></div>
<div class="center"></div>
</div>
</div
I built a Bash debugger. Just give it a try. I hope it will help https://sourceforge.net/projects/bashdebugingbash
includes() is not supported by most browsers. Your options are either to use
-polyfill from MDN https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes
or to use
-indexof()
var str = "abcde";
var n = str.indexOf("cd");
Which gives you n=2
This is widely supported.
If you use matplotlib
, you need to show the image using plt.show()
unless you are not in interactive mode.
E.g.:
plt.figure()
plt.imshow(sample_image)
plt.show() # display it
I am currently on OS X 10.9 and my efforts to compile vim with +xterm_clipboard brought me nothing. So my current solution is to use MacVim in terminal mode with option set clipboard=unnamed
in my ~/.vimrc file. Works perfect for me.
The following permissions and features are necessary in the AndroidManifest.xml file without which you will get the following dialog box
"It seems that your device does not support camera (or it is locked). Application will be closed"
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
<uses-feature android:name="android.hardware.camera.front" android:required="false"/>
<uses-feature android:name="android.hardware.camera.front.autofocus" android:required="false"/>
If you add:
<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>
in the head of the document it will start working as expected:
<script type="text/javascript">
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
A lot of good answers already for Ubuntu. I'm on Linux and had the same problem but none of the commands above worked for me.
With Linux and php70 I used the following command which worked great:
sudo yum install php70-mbstring -y
In Ubuntu if you execute the script with sh scriptname.sh
you get this problem.
Try executing the script with ./scriptname.sh
instead.
Python trim
method is called strip
:
str.strip() #trim
str.lstrip() #ltrim
str.rstrip() #rtrim
I found this was caused by adding a new scope variable to the login scope
Linq extension method. Will work with any IEnumerable object:
public static bool ContainsAny<T>(this IEnumerable<T> Collection, IEnumerable<T> Values)
{
return Collection.Any(x=> Values.Contains(x));
}
Usage:
string[] Array1 = {"1", "2"};
string[] Array2 = {"2", "4"};
bool Array2ItemsInArray1 = List1.ContainsAny(List2);
Adapted from Timmmm to PYQT5
from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import QResizeEvent
from PyQt5.QtWidgets import QLabel
class Label(QLabel):
def __init__(self):
super(Label, self).__init__()
self.pixmap_width: int = 1
self.pixmapHeight: int = 1
def setPixmap(self, pm: QPixmap) -> None:
self.pixmap_width = pm.width()
self.pixmapHeight = pm.height()
self.updateMargins()
super(Label, self).setPixmap(pm)
def resizeEvent(self, a0: QResizeEvent) -> None:
self.updateMargins()
super(Label, self).resizeEvent(a0)
def updateMargins(self):
if self.pixmap() is None:
return
pixmapWidth = self.pixmap().width()
pixmapHeight = self.pixmap().height()
if pixmapWidth <= 0 or pixmapHeight <= 0:
return
w, h = self.width(), self.height()
if w <= 0 or h <= 0:
return
if w * pixmapHeight > h * pixmapWidth:
m = int((w - (pixmapWidth * h / pixmapHeight)) / 2)
self.setContentsMargins(m, 0, m, 0)
else:
m = int((h - (pixmapHeight * w / pixmapWidth)) / 2)
self.setContentsMargins(0, m, 0, m)
I think you meant something like "*" (star) as a wildcard for example:
or in your example: "bird*" => everything that starts with bird
I had a similar problem and wrote a function with RegExp:
//Short code_x000D_
function matchRuleShort(str, rule) {_x000D_
var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");_x000D_
return new RegExp("^" + rule.split("*").map(escapeRegex).join(".*") + "$").test(str);_x000D_
}_x000D_
_x000D_
//Explanation code_x000D_
function matchRuleExpl(str, rule) {_x000D_
// for this solution to work on any string, no matter what characters it has_x000D_
var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");_x000D_
_x000D_
// "." => Find a single character, except newline or line terminator_x000D_
// ".*" => Matches any string that contains zero or more characters_x000D_
rule = rule.split("*").map(escapeRegex).join(".*");_x000D_
_x000D_
// "^" => Matches any string with the following at the beginning of it_x000D_
// "$" => Matches any string with that in front at the end of it_x000D_
rule = "^" + rule + "$"_x000D_
_x000D_
//Create a regular expression object for matching string_x000D_
var regex = new RegExp(rule);_x000D_
_x000D_
//Returns true if it finds a match, otherwise it returns false_x000D_
return regex.test(str);_x000D_
}_x000D_
_x000D_
//Examples_x000D_
alert(_x000D_
"1. " + matchRuleShort("bird123", "bird*") + "\n" +_x000D_
"2. " + matchRuleShort("123bird", "*bird") + "\n" +_x000D_
"3. " + matchRuleShort("123bird123", "*bird*") + "\n" +_x000D_
"4. " + matchRuleShort("bird123bird", "bird*bird") + "\n" +_x000D_
"5. " + matchRuleShort("123bird123bird123", "*bird*bird*") + "\n" +_x000D_
"6. " + matchRuleShort("s[pe]c 3 re$ex 6 cha^rs", "s[pe]c*re$ex*cha^rs") + "\n" +_x000D_
"7. " + matchRuleShort("should not match", "should noo*oot match") + "\n"_x000D_
);
_x000D_
If you want to read more about the used functions:
If you want to restrict your search only to files you should consider to use -type f
in your search
try to use also -iname
for case-insensitive search
Example:
find /path -iname 'yourstring*' -type f
You could also perform some operations on results without pipe sign or xargs
Example:
Search for files and show their size in MB
find /path -iname 'yourstring*' -type f -exec du -sm {} \;
This is better:
<?php
//* Permanently redirect page
header("Location: new_page.php",TRUE,301);
?>
Just one call including code 301. Also notice the relative path to the file in the same directory (not "/dir/dir/new_page.php", etc.), which all modern browsers seem to support.
I think this is valid since PHP 5.1.2, possibly earlier.
Casting to an int
truncates the value. Adding 0.5
causes it to do proper rounding.
int y = (int)(x + 0.5);
If you set the Content-Length HTTP header in your "Thank You For Registering" response, then the browser should close the connection after the specified number of bytes are received. This leaves the server side process running (assuming that ignore_user_abort is set) so it can finish working without making the end user wait.
Of course you will need to calculate the size of your response content before rendering the headers, but that's pretty easy for short responses (write output to a string, call strlen(), call header(), render string).
This approach has the advantage of not forcing you to manage a "front end" queue, and although you may need to do some work on the back end to prevent racing HTTP child processes from stepping on each other, that's something you needed to do already, anyway.
<a href="#" onclick="window.open('MyPDF.pdf', '_blank', 'fullscreen=yes'); return false;">MyPDF</a>
The above link will open the PDF in full screen mode, that's the best you can achieve.
Another similar solution:
>>> a=datetime.now()
>>> "%s:%s.%s" % (a.hour, a.minute, a.microsecond)
'14:28.971209'
Yes, I know I didn't get the string formatting perfect.
Not all cultures use the same format for dates and decimal / currency values.
This will matter for you when you are converting input values (read) that are stored as strings to DateTime
, float
, double
or decimal
. It will also matter if you try to format the aforementioned data types to strings (write) for display or storage.
If you know what specific culture that your dates and decimal / currency values will be in ahead of time, you can use that specific CultureInfo
property (i.e. CultureInfo("en-GB")
). For example if you expect a user input.
The CultureInfo.InvariantCulture
property is used if you are formatting or parsing a string that should be parseable by a piece of software independent of the user's local settings.
The default value is CultureInfo.InstalledUICulture
so the default CultureInfo is depending on the executing OS's settings. This is why you should always make sure the culture info fits your intention (see Martin's answer for a good guideline).
rebooted iPhone, closed all other open applications and unlocked phone worked
I think this and many of the answers around what the spec does or does not say is missing the point of the question.Should they be case sensitive? That's a loaded question really. From a user's point of view, case sensitivity is a pain point, not all know makes a difference. The question of whether URIs should or shouldn't be, depends on the context of the question. For technical flexibility, yes, they should be. For usability, no, they should not be.
The main reason to do this is to make the script portable across operating system environments.
For example under mingw, python scripts use :
#!/c/python3k/python
and under GNU/Linux distribution it is either:
#!/usr/local/bin/python
or
#!/usr/bin/python
and under the best commercial Unix sw/hw system of all (OS/X), it is:
#!/Applications/MacPython 2.5/python
or on FreeBSD:
#!/usr/local/bin/python
However all these differences can make the script portable across all by using:
#!/usr/bin/env python
// Excuse my beginner's english
There is msgHTML() method, which, also, call IsHTML().
Hrm... name IsHTML
is confusing...
/**
* Create a message from an HTML string.
* Automatically makes modifications for inline images and backgrounds
* and creates a plain-text version by converting the HTML.
* Overwrites any existing values in $this->Body and $this->AltBody
* @access public
* @param string $message HTML message string
* @param string $basedir baseline directory for path
* @param bool $advanced Whether to use the advanced HTML to text converter
* @return string $message
*/
public function msgHTML($message, $basedir = '', $advanced = false)
This looks like a CSV file, so you could use the python csv module to read it. For example:
import csv
crimefile = open(fileName, 'r')
reader = csv.reader(crimefile)
allRows = [row for row in reader]
Using the csv module allows you to specify how things like quotes and newlines are handled. See the documentation I linked to above.
You can try this:
Select To_date ('15/2/2007 00:00:00', 'DD/MM/YYYY HH24:MI:SS'),
To_date ('28/2/2007 10:12', 'DD/MM/YYYY HH24:MI:SS')
From DUAL;
Source: http://notsyncing.org/2008/02/manipulando-fechas-con-horas-en-plsql-y-sql/
The following query will find the documents with required string case insensitively and with global occurrence also
var name = 'Peter';
db.User.find({name:{
$regex: new RegExp(name, "ig")
}
},function(err, doc) {
//Your code here...
});
These are properties. You would use them like so:
Tom.Title = "Accountant";
string desc = Tom.Description;
But considering they are declared protected
their visibility may be a concern.
Here are the steps if you want to do this from Eclipse :
1) Create a folder 'sqlauth' in your C: drive, and copy the dll file sqljdbc_auth.dll to the folder
1) Go to Run> Run Configurations
2) Choose the 'Arguments' tab for your class
3) Add the below code in VM arguments:
-Djava.library.path="C:\\sqlauth"
4) Hit 'Apply' and click 'Run'
Feel free to try other methods .
I have implemented this in my code.
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 31.0f)];
view1.backgroundColor = [UIColor clearColor];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view1.bounds;
UIColor *topColor = [UIColor colorWithRed:132.0/255.0 green:222.0/255.0 blue:109.0/255.0 alpha:1.0];
UIColor *bottomColor = [UIColor colorWithRed:31.0/255.0 green:150.0/255.0 blue:99.0/255.0 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)[topColor CGColor], (id)[bottomColor CGColor], nil];
[view1.layer insertSublayer:gradient atIndex:0];
Now I can see a gradient on my view.
Update for 2019, if you want to create a folder with path bucket_name/folder1/folder2 you can use this code:
from boto3 import client, resource
class S3Helper:
def __init__(self):
self.client = client("s3")
self.s3 = resource('s3')
def create_folder(self, path):
path_arr = path.rstrip("/").split("/")
if len(path_arr) == 1:
return self.client.create_bucket(Bucket=path_arr[0])
parent = path_arr[0]
bucket = self.s3.Bucket(parent)
status = bucket.put_object(Key="/".join(path_arr[1:]) + "/")
return status
s3 = S3Helper()
s3.create_folder("bucket_name/folder1/folder2)
After discussion posting updated answer:
Option Explicit
Sub test()
Dim wk As String, yr As String
Dim fname As String, fpath As String
Dim owb As Workbook
With Application
.DisplayAlerts = False
.ScreenUpdating = False
.EnableEvents = False
End With
wk = ComboBox1.Value
yr = ComboBox2.Value
fname = yr & "W" & wk
fpath = "C:\Documents and Settings\jammil\Desktop\AutoFinance\ProjectControl\Data"
On Error GoTo ErrorHandler
Set owb = Application.Workbooks.Open(fpath & "\" & fname)
'Do Some Stuff
With owb
.SaveAs fpath & Format(Date, "yyyymm") & "DB" & ".xlsx", 51
.Close
End With
With Application
.DisplayAlerts = True
.ScreenUpdating = True
.EnableEvents = True
End With
Exit Sub
ErrorHandler: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then
Else: Call Clear
End Sub
Error Handling:
You could try something like this to catch a specific error:
On Error Resume Next
Set owb = Application.Workbooks.Open(fpath & "\" & fname)
If Err.Number = 1004 Then
GoTo FileNotFound
Else
End If
...
Exit Sub
FileNotFound: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then
Else: Call Clear
It's much easier with Swift 4
or Swift 4.2
inside your ViewDidLoad
method, define your button and add it to the navigation bar.
override func viewDidLoad() {
super.viewDidLoad()
let logoutBarButtonItem = UIBarButtonItem(title: "Logout", style: .done, target: self, action: #selector(logoutUser))
self.navigationItem.rightBarButtonItem = logoutBarButtonItem
}
then you need to define the function that you mentioned inside action parameter as below
@objc func logoutUser(){
print("clicked")
}
You need to add the @objc
prefix as it's still making use of the legacy stuff (Objective C).
You can get the events from pygame and then watch out for the KEYDOWN
event, instead of looking at the keys returned by get_pressed()
(which gives you keys that are currently pressed down, whereas the KEYDOWN
event shows you which keys were pressed down on that frame).
What's happening with your code right now is that if your game is rendering at 30fps, and you hold down the left arrow key for half a second, you're updating the location 15 times.
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
location -= 1
if event.key == pygame.K_RIGHT:
location += 1
To support continuous movement while a key is being held down, you would have to establish some sort of limitation, either based on a forced maximum frame rate of the game loop or by a counter which only allows you to move every so many ticks of the loop.
move_ticker = 0
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
if move_ticker == 0:
move_ticker = 10
location -= 1
if location == -1:
location = 0
if keys[K_RIGHT]:
if move_ticker == 0:
move_ticker = 10
location+=1
if location == 5:
location = 4
Then somewhere during the game loop you would do something like this:
if move_ticker > 0:
move_ticker -= 1
This would only let you move once every 10 frames (so if you move, the ticker gets set to 10, and after 10 frames it will allow you to move again)
You can put the data in a file and re-direct it like this:
$ cat file.sh
#!/bin/bash
read x
read y
echo $x
echo $y
Data for the script:
$ cat data.txt
2
3
Executing the script:
$ file.sh < data.txt
2
3
For me, the main difference is that a script is interpreted, while a program is executed (i.e. the source is first compiled, and the result of that compilation is expected).
Wikipedia seems to agree with me on this :
Script :
"Scripts" are distinct from the core code of the application, which is usually written in a different language, and are often created or at least modified by the end-user.
Scripts are often interpreted from source code or bytecode, whereas the applications they control are traditionally compiled to native machine code.
Program :
The program has an executable form that the computer can use directly to execute the instructions.
The same program in its human-readable source code form, from which executable programs are derived (e.g., compiled)
I use a NAnt Build Script to deploy to my different environments. I have it modify my config files via XPath depending on where they're being deployed to, and then it automagically puts them into that environment using Beyond Compare.
Takes a minute or two to setup, but you only need to do it once. Then batch files take over while I go get another cup of coffee. :)
Here's an article I found on it.
I am learning javascript and jquery and was going through all the answer,
i faced same issue when calling javascript function for loading div element.
I tried $('<divid>').ready(function(){alert('test'})
and it worked for me. I want to know is this good way to perform onload call on div element in the way i did using jquery selector.
thanks
You have misunderstood :hover
; it says the mouse is over an item, rather than the mouse has just entered the item.
You could add animation to the selector without :hover
to achieve the effect you want.
Transitions is a better option: http://jsfiddle.net/Cvx96/
for MacOS, make sure you know where the GO install
export GOPATH=/usr/local/go
PATH=$PATH:$GOPATH/bin
@ConfigurationProperties
can be used to map values from .properties
( .yml
also supported) to a POJO.
Consider the following Example file.
.properties
cust.data.employee.name=Sachin
cust.data.employee.dept=Cricket
Employee.java
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@ConfigurationProperties(prefix = "cust.data.employee")
@Configuration("employeeProperties")
public class Employee {
private String name;
private String dept;
//Getters and Setters go here
}
Now the properties value can be accessed by autowiring employeeProperties
as follows.
@Autowired
private Employee employeeProperties;
public void method() {
String employeeName = employeeProperties.getName();
String employeeDept = employeeProperties.getDept();
}
Any reason they can't just click on the tab for your sheet when they want it?
You want the CASE
statement:
SELECT
CASE
WHEN @SelectField1 = 1 THEN Field1
WHEN @SelectField2 = 1 THEN Field2
ELSE NULL
END AS NewField
FROM Table
EDIT: My example is for combining the two fields into one field, depending on the parameters supplied. It is a one-or-neither solution (not both). If you want the possibility of having both fields in the output, use Quassnoi's solution.
Another option is to rely on good old fashion equals
method. As long as the argument in the when
mock equals
the argument in the code being tested, then Mockito will match the mock.
Here is an example.
public class MyPojo {
public MyPojo( String someField ) {
this.someField = someField;
}
private String someField;
@Override
public boolean equals( Object o ) {
if ( this == o ) return true;
if ( o == null || getClass() != o.getClass() ) return false;
MyPojo myPojo = ( MyPojo ) o;
return someField.equals( myPojo.someField );
}
}
then, assuming you know what the value for someField
will be, you can mock it like this.
when(fooDao.getBar(new MyPojo(expectedSomeField))).thenReturn(myFoo);
pros: This is more explicit then any
matchers. As a reviewer of code, I keep an eye open for any
in the code junior developers write, as it glances over their code's logic to generate the appropriate object being passed.
con: Sometimes the field being passed to the object is a random ID. For this case you cannot easily construct the expected argument object in your mock code.
Another possible approach is to use Mockito's Answer
object that can be used with the when
method. Answer
lets you intercept the actual call and inspect the input argument and return a mock object. In the example below I am using any
to catch any request to the method being mocked. But then in the Answer
lambda, I can further inspect the Bazo argument... maybe to verify that a proper ID was passed to it. I prefer this over any
by itself so that at least some inspection is done on the argument.
Bar mockBar = //generate mock Bar.
when(fooDao.getBar(any(Bazo.class))
.thenAnswer( ( InvocationOnMock invocationOnMock) -> {
Bazo actualBazo = invocationOnMock.getArgument( 0 );
//inspect the actualBazo here and thrw exception if it does not meet your testing requirements.
return mockBar;
} );
So to sum it all up, I like relying on equals
(where the expected argument and actual argument should be equal to each other) and if equals is not possible (due to not being able to predict the actual argument's state), I'll resort to Answer
to inspect the argument.
Try this, I've used it in a personal wiki-like app:
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("foo://")) {
// magic
return true;
}
return false;
}
});
You should make your audioSounds and minTime members static:
public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;
But I would consider using singleton objects instead of static members instead:
public class SoundManager : MonoBehaviour
{
public List<AudioSource> audioSounds = new List<AudioSource>();
public double minTime = 0.5;
public static SoundManager Instance { get; private set; }
void Awake()
{
Instance = this;
}
public void playSound(AudioClip sourceSound, Vector3 objectPosition, int volume, float audioPitch, int dopplerLevel)
{
bool playsound = false;
foreach (AudioSource sound in audioSounds) // Loop through List with foreach
{
if (sourceSound.name != sound.name && sound.time <= minTime)
{
playsound = true;
}
}
if(playsound) {
AudioSource.PlayClipAtPoint(sourceSound, objectPosition);
}
}
}
Update from September 2020:
Six years later, it is still one of my most upvoted answers on StackOverflow, so I feel obligated to add: singleton is a pattern that creates a lot of problems down the road, and personally, I consider it to be an anti-pattern. It can be accessed from anywhere, and using singletons for different game systems creates a spaghetti of invisible dependencies between different parts of your project.
If you're just learning to program, using singletons is OK for now. But please, consider reading about Dependency Injection, Inversion of Control and other architectural patterns. At least file it under "stuff I will learn later". This may sound as an overkill when you first learn about them, but a proper architecture can become a life-saver on middle and big projects.
I don't understand, why you don't want to set the $HOME
environment variable since that solves exactly what you're asking for.
cd ~
doesn't mean change to the root directory, but change to the user's home directory, which is set by the $HOME
environment variable.
Edit C:\Program Files (x86)\Git\etc\profile
and set $HOME
variable to whatever you want (add it if it's not there). A good place could be for example right after a condition commented by # Set up USER's home directory
. It must be in the MinGW format, for example:
HOME=/c/my/custom/home
Save it, open Git Bash and execute cd ~
. You should be in a directory /c/my/custom/home
now.
Everything that accesses the user's profile should go into this directory instead of your Windows' profile on a network drive.
Note: C:\Program Files (x86)\Git\etc\profile
is shared by all users, so if the machine is used by multiple users, it's a good idea to set the $HOME
dynamically:
HOME=/c/Users/$USERNAME
Set the environment variable HOME
in Windows to whatever directory you want. In this case, you have to set it in Windows path format (with backslashes, e.g. c:\my\custom\home
), Git Bash will load it and convert it to its format.
If you want to change the home directory for all users on your machine, set it as a system environment variable, where you can use for example %USERNAME%
variable so every user will have his own home directory, for example:
HOME=c:\custom\home\%USERNAME%
If you want to change the home directory just for yourself, set it as a user environment variable, so other users won't be affected. In this case, you can simply hard-code the whole path:
HOME=c:\my\custom\home
Try autoplay="autoplay"
instead of the "true"
value. That's the documented way to enable autoplay. That sounds weirdly redundant, I know.
For people who are still struggling, I managed to get this working on all modern browsers IE11 and up.
base64 was no option for me because I wanted to use SASS to generate SVG icons based on any given color. For example: @include svg_icon(heart, #FF0000);
This way I can create a certain icon in any color, and only have to embed the SVG shape once in the CSS. (with base64 you'd have to embed the SVG in every single color you want to use)
There are three things you need be aware of:
URL ENCODE YOUR SVG
As others have suggested, you need to URL encode your entire SVG string for it to work in IE11. In my case, I left out the color values in fields such as fill="#00FF00"
and stroke="#FF0000"
and replaced them with a SASS variable fill="#{$color-rgb}"
so these can be replaced with the color I want. You can use any online converter to URL encode the rest of the string. You'll end up with an SVG string like this:
%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%20494.572%20494.572%27%20width%3D%27512%27%20height%3D%27512%27%3E%0A%20%20%3Cpath%20d%3D%27M257.063%200C127.136%200%2021.808%20105.33%2021.808%20235.266c0%2041.012%2010.535%2079.541%2028.973%20113.104L3.825%20464.586c345%2012.797%2041.813%2012.797%2015.467%200%2029.872-4.721%2041.813-12.797v158.184z%27%20fill%3D%27#{$color-rgb}%27%2F%3E%3C%2Fsvg%3E
OMIT THE UTF8 CHARSET IN THE DATA URL When creating your data URL, you need to leave out the charset for it to work in IE11.
NOT background-image: url( data:image/svg+xml;utf-8,%3Csvg%2....)
BUT background-image: url( data:image/svg+xml,%3Csvg%2....)
USE RGB() INSTEAD OF HEX colors Firefox does not like # in the SVG code. So you need to replace your color hex values with RGB ones.
NOT fill="#FF0000"
BUT fill="rgb(255,0,0)"
In my case I use SASS to convert a given hex to a valid rgb value. As pointed out in the comments, it's best to URL encode your RGB string as well (so comma becomes %2C)
@mixin svg_icon($id, $color) {
$color-rgb: "rgb(" + red($color) + "%2C" + green($color) + "%2C" + blue($color) + ")";
@if $id == heart {
background-image: url('data:image/svg+xml,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%20494.572%20494.572%27%20width%3D%27512%27%20height%3D%27512%27%3E%0A%20%20%3Cpath%20d%3D%27M257.063%200C127.136%200%2021.808%20105.33%2021.808%20235.266c0%204%27%20fill%3D%27#{$color-rgb}%27%2F%3E%3C%2Fsvg%3E');
}
}
I realize this might not be the best solution for very complex SVG's (inline SVG never is in that case), but for flat icons with only a couple of colors this really works great.
I was able to leave out an entire sprite bitmap and replace it with inline SVG in my CSS, which turned out to only be around 25kb after compression. So it's a great way to limit the amount of requests your site has to do, without bloating your CSS file.
For those having configuration in bin/www
, just add the timeout parameter after http server creation.
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces
*/
server.listen(port);
server.timeout=yourValueInMillisecond
Case: Light text with jaggy web font on dark background Firefox (v35)/Windows
Example: Google Web Font Ruda
Surprising solution -
adding following property to the applied selectors:
selector {
text-shadow: 0 0 0;
}
Actually, result is the same just with text-shadow: 0 0;
, but I like to explicitly set blur-radius.
It's not an universal solution, but might help in some cases. Moreover I haven't experienced (also not thoroughly tested) negative performance impacts of this solution so far.
TLS 1.0 and 1.1 are now End of Life. A package on our Amazon web server updated, and we started getting this error.
The answer is above, but you shouldn't use tls
or tls11
anymore.
Specifically for ASP.Net, add this to one of your startup methods.
public Startup()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
but I'm sure that something like this will work in many other cases.
There is another new library for reflection in C++, called RTTR (Run Time Type Reflection, see also github).
The interface is similar to reflection in C# and it works without any RTTI.
Not sure exactly what your problem is, but try the following:
Check here for examples, if they don't work for you then you have another problem
Edit:
You have a bunch of repeated declarations in your source, does this work?
@font-face { font-family: Gotham; src: url('../fonts/gothammedium.eot'); }
a { font-family:Gotham,Verdana,Arial; }
If you are using Tomcat 7 and Eclipse, click on the Tomcat server and then goto the modules tab. There you will find the duplicate entry. Remove both the entry and redeploy the application. You are good to go now.
double i = 2+Math.random()*100;
int j = (int)i;
System.out.print(j);
If you're happy to use the Microsoft Reactive Extensions, then this can work nicely:
public class Foo
{
public delegate void MyEventHandler(object source, MessageEventArgs args);
public event MyEventHandler _event;
public string ReadLine()
{
return Observable
.FromEventPattern<MyEventHandler, MessageEventArgs>(
h => this._event += h,
h => this._event -= h)
.Select(ep => ep.EventArgs.Message)
.First();
}
public void SendLine(string message)
{
_event(this, new MessageEventArgs() { Message = message });
}
}
public class MessageEventArgs : EventArgs
{
public string Message;
}
I can use it like this:
var foo = new Foo();
ThreadPoolScheduler.Instance
.Schedule(
TimeSpan.FromSeconds(5.0),
() => foo.SendLine("Bar!"));
var resp = foo.ReadLine();
Console.WriteLine(resp);
I needed to call the SendLine
message on a different thread to avoid locking, but this code shows that it works as expected.
To submit the form when the enter key is pressed create a javascript function along these lines.
function checkSubmit(e) {
if(e && e.keyCode == 13) {
document.forms[0].submit();
}
}
Then add the event to whatever scope you need eg on the div tag:
<div onKeyPress="return checkSubmit(event)"/>
This is also the default behaviour of Internet Explorer 7 anyway though (probably earlier versions as well).
Could it be simpler?!
uint8_t hex(char ch) {
uint8_t r = (ch > 57) ? (ch - 55) : (ch - 48);
return r & 0x0F;
}
int to_byte_array(const char *in, size_t in_size, uint8_t *out) {
int count = 0;
if (in_size % 2) {
while (*in && out) {
*out = hex(*in++);
if (!*in)
return count;
*out = (*out << 4) | hex(*in++);
*out++;
count++;
}
return count;
} else {
while (*in && out) {
*out++ = (hex(*in++) << 4) | hex(*in++);
count++;
}
return count;
}
}
int main() {
char hex_in[] = "deadbeef10203040b00b1e50";
uint8_t out[32];
int res = to_byte_array(hex_in, sizeof(hex_in) - 1, out);
for (size_t i = 0; i < res; i++)
printf("%02x ", out[i]);
printf("\n");
system("pause");
return 0;
}
Consider making your route:
_files_manage:
pattern: /files/management/{project}/{user}
defaults: { _controller: AcmeTestBundle:File:manage }
since they are required fields. It will make your url's prettier, and be a bit easier to manage.
Your Controller would then look like
public function projectAction($project, $user)
There are two cases:
const reference --good idea, sometimes, especially for heavy objects or proxy classes, compiler optimization
non-const reference --bad idea, sometimes, breaks encapsulations
Both share same issue -- can potentially point to destroyed object...
I would recommend using smart pointers for many situations where you require to return a reference/pointer.
Also, note the following:
There is a formal rule - the C++ Standard (section 13.3.3.1.4 if you are interested) states that a temporary can only be bound to a const reference - if you try to use a non-const reference the compiler must flag this as an error.
Go to the bar where you have file, edit, view etc Go on view -> Navigators -> Show Project Navigator -> Click on team -> Select yours.
Enjoy
For me.
Edit .gitattributes file.
add
*.dll binary
Then everything goes well.
EXEC sys.sp_configure N'max server memory (MB)', N'2147483646'
GO
RECONFIGURE WITH OVERRIDE
GO
What value you specify for the server memory is not important, as long as it differs from the current one.
Btw, the thing that causes the speedup is not the query cache, but the data cache.
List myList = new ArrayList();
Collections.addAll(myList, filesOrig);
In Oracle, (+) denotes the "optional" table in the JOIN. So in your query,
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id=b.id(+)
it's a LEFT OUTER JOIN of table 'b' to table 'a'. It will return all data of table 'a' without losing its data when the other side (optional table 'b') has no data.
The modern standard syntax for the same query would be
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
LEFT JOIN b ON a.id=b.id
or with a shorthand for a.id=b.id
(not supported by all databases):
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
LEFT JOIN b USING(id)
Older syntax, in both Oracle and other databases:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id=b.id
More modern syntax:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
INNER JOIN b ON a.id=b.id
Or simply:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
JOIN b ON a.id=b.id
It will only return all data where both 'a' & 'b' tables 'id' value is same, means common part.
This is just the same as a LEFT JOIN, but switches which table is optional.
Old Oracle syntax:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id(+)=b.id
Modern standard syntax:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
RIGHT JOIN b ON a.id=b.id
https://asktom.oracle.com/pls/asktom/f?p=100:11:::::P11_QUESTION_ID:6585774577187
An explicit default initialization can help:
struct foo {
bool a {};
bool b {};
bool c {};
} bar;
Behavior bool a {}
is same as bool b = bool();
and return false
.
Here is my answer for AWS using boto3
subject = "Hello"
html = "<b>Hello Consumer</b>"
client = boto3.client('ses', region_name='us-east-1', aws_access_key_id="your_key",
aws_secret_access_key="your_secret")
client.send_email(
Source='ACME <[email protected]>',
Destination={'ToAddresses': [email]},
Message={
'Subject': {'Data': subject},
'Body': {
'Html': {'Data': html}
}
}
Python 2
The error is caused because ElementTree did not expect to find non-ASCII strings set the XML when trying to write it out. You should use Unicode strings for non-ASCII instead. Unicode strings can be made either by using the u
prefix on strings, i.e. u'€'
or by decoding a string with mystr.decode('utf-8')
using the appropriate encoding.
The best practice is to decode all text data as it's read, rather than decoding mid-program. The io
module provides an open()
method which decodes text data to Unicode strings as it's read.
ElementTree will be much happier with Unicodes and will properly encode it correctly when using the ET.write()
method.
Also, for best compatibility and readability, ensure that ET encodes to UTF-8 during write()
and adds the relevant header.
Presuming your input file is UTF-8 encoded (0xC2
is common UTF-8 lead byte), putting everything together, and using the with
statement, your code should look like:
with io.open('myText.txt', "r", encoding='utf-8') as f:
data = f.read()
root = ET.Element("add")
doc = ET.SubElement(root, "doc")
field = ET.SubElement(doc, "field")
field.set("name", "text")
field.text = data
tree = ET.ElementTree(root)
tree.write("output.xml", encoding='utf-8', xml_declaration=True)
Output:
<?xml version='1.0' encoding='utf-8'?>
<add><doc><field name="text">data€</field></doc></add>
Try this:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:toolbar="http://schemas.android.com/apk/res-auto"
android:id="@+id/tool_drawer"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
toolbar:navigationIcon="@drawable/ic_navigation">
</android.support.v7.widget.Toolbar>
In case of SVN servers you have to creating a central repository with all projects. The contents of the repository can be uploaded with the Team/Share command; in case of the Subversive client it automatically runs a commit after the import, so you can upload your files.
This step cannot be circumvented in any way using a centralized version management system such as SVN.
You can also try using apply
with get
method of dictionary
, seems to be little faster than replace
:
data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)
Testing with timeit
:
%%timeit
data['sex'].replace([0,1],['Female','Male'],inplace=True)
Result:
The slowest run took 5.83 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 510 µs per loop
Using apply
:
%%timeit
data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)
Result:
The slowest run took 5.92 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 331 µs per loop
Note: apply
with dictionary should be used if all the possible values of the columns in the dataframe are defined in the dictionary else, it will have empty for those not defined in dictionary.
You can move to desired activity on button click. just add this line.
android:onClick="sendMessage"
xml:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendMessage"
android:text="@string/button" />
In your main activity just add this method:
public void sendMessage(View view) {
Intent intent = new Intent(FromActivity.this, ToActivity.class);
startActivity(intent);
}
And the most important thing: don't forget to define your activity in manifest.xml
<activity>
android:name=".ToActivity"
android:label="@string/app_name">
</activity>
there is component ready to use (rc5 compatible)
ng2-steps
which uses Compiler
to inject component to step container
and service for wiring everything together (data sync)
import { Directive , Input, OnInit, Compiler , ViewContainerRef } from '@angular/core';
import { StepsService } from './ng2-steps';
@Directive({
selector:'[ng2-step]'
})
export class StepDirective implements OnInit{
@Input('content') content:any;
@Input('index') index:string;
public instance;
constructor(
private compiler:Compiler,
private viewContainerRef:ViewContainerRef,
private sds:StepsService
){}
ngOnInit(){
//Magic!
this.compiler.compileComponentAsync(this.content).then((cmpFactory)=>{
const injector = this.viewContainerRef.injector;
this.viewContainerRef.createComponent(cmpFactory, 0, injector);
});
}
}
If you dataframe is df
you can simply use:
import matplotlib.pyplot as plt
import seaborn as sns
plt.figure(figsize=(15, 10))
sns.heatmap(df.corr(), annot=True)
If you are using the Git Bash shell, you can use the following trick:
> webpage.html
This is actually the same as:
echo "" > webpage.html
Then, you can use git add webpage.html
to stage the file.
The second one is fastest. Using strlen
will be close if the string is indeed empty, but strlen
will always iterate through every character of the string, so if it is not empty, it will do much more work than you need it to.
As James mentioned, the third option wipes the string out before checking, so the check will always succeed but it will be meaningless.
Use this:
public static void wait(int ms)
{
try
{
Thread.sleep(ms);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
and, then you can call this method anywhere like:
wait(1000);
"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."
http://www.sightspecific.com/~mosh/www_faq/multrec.html
For a quick fix to your problem, change your ;
to a comma ,
and eliminate the spaces between email addresses
<a href='mailto:[email protected],[email protected]'>Email Us</a>
If you look inside Math.abs you can probably find the best answer:
Eg, for floats:
/*
* Returns the absolute value of a {@code float} value.
* If the argument is not negative, the argument is returned.
* If the argument is negative, the negation of the argument is returned.
* Special cases:
* <ul><li>If the argument is positive zero or negative zero, the
* result is positive zero.
* <li>If the argument is infinite, the result is positive infinity.
* <li>If the argument is NaN, the result is NaN.</ul>
* In other words, the result is the same as the value of the expression:
* <p>{@code Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))}
*
* @param a the argument whose absolute value is to be determined
* @return the absolute value of the argument.
*/
public static float abs(float a) {
return (a <= 0.0F) ? 0.0F - a : a;
}
You could also take a look at a past sample project of mine, written for this purpose. I saves locally a name and retrieves it either upon a user's request or when the app starts.
But, at this time, it would be better to use commit
(instead of apply
) for persisting the data. More info here.
Either the parameter supplied for ZIP_CODE
is larger (in length) than ZIP_CODE
s column width or the parameter supplied for CITY
is larger (in length) than CITY
s column width.
It would be interesting to know the values supplied for the two ?
placeholders.
The "responsible" answer would be for me to suggest building a ViewModel for the dialog and use two-way databinding on the TextBox so that the ViewModel had some "ResponseText" property or what not. This is easy enough to do but probably overkill.
The pragmatic answer would be to just give your text box an x:Name so that it becomes a member and expose the text as a property in your code behind class like so:
<!-- Incredibly simplified XAML -->
<Window x:Class="MyDialog">
<StackPanel>
<TextBlock Text="Enter some text" />
<TextBox x:Name="ResponseTextBox" />
<Button Content="OK" Click="OKButton_Click" />
</StackPanel>
</Window>
Then in your code behind...
partial class MyDialog : Window {
public MyDialog() {
InitializeComponent();
}
public string ResponseText {
get { return ResponseTextBox.Text; }
set { ResponseTextBox.Text = value; }
}
private void OKButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
DialogResult = true;
}
}
Then to use it...
var dialog = new MyDialog();
if (dialog.ShowDialog() == true) {
MessageBox.Show("You said: " + dialog.ResponseText);
}
Within a module, to have a combination of flavors, flavor resources (layout, values) and flavors resource resources, the main thing to keep in mind are two things:
When adding resource directories in res.srcDirs
for flavor, keep in mind that in other modules and even in src/main/res
of the same module, resource directories are also added. Hence, the importance of using an add-on assignment (+=
) so as not to overwrite all existing resources with the new assignment.
The path that is declared as an element of the array is the one that contains the resource types, that is, the resource types are all the subdirectories that a res folder contains normally such as color, drawable, layout, values, etc. The name of the res folder can be changed.
An example would be to use the path "src/flavor/res/values/strings-ES"
but observe that the practice hierarchy has to have the subdirectory values
:
+-- module
+-- flavor
+-- res
+-- values
+-- strings-ES
+-- values
+-- strings.xml
+-- strings.xml
The framework recognizes resources precisely by type, that is why normally known subdirectories cannot be omitted.
Also keep in mind that all the strings.xml
files that are inside the flavor would form a union so that resources cannot be duplicated. And in turn this union that forms a file in the flavor has a higher order of precedence before the main of the module.
flavor {
res.srcDirs += [
"src/flavor/res/values/strings-ES"
]
}
Consider the strings-ES
directory as a custom-res which contains the resource types.
GL
Natural verses artifical keys is a kind of religious debate among the database community - see this article and others it links to. I'm neither in favour of always having artifical keys, nor of never having them. I would decide on a case-by-case basis, for example:
Wherever artificial keys are used, you should always also declare unique constraints on the natural keys. For example, use state_id if you must, but then you'd better declare a unique constraint on state_code, otherwise you are sure to eventually end up with:
state_id state_code state_name
137 TX Texas
... ... ...
249 TX Texas
You could use actionLayout
from the support library.
menu.xml
<?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/button_item"
android:title=""
app:actionLayout="@layout/button_layout"
app:showAsAction="always"
/>
</menu>
button_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
Activity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.button_item);
Button btn = item.getActionView().findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Toolbar Button Clicked!", Toast.LENGTH_SHORT).show();
}
});
return true;
}
This JavaScript function considers whether to use insert or replace to handle the swap.
(Insert or replace HTML line breaks)
/**
* This function is same as PHP's nl2br() with default parameters.
*
* @param {string} str Input text
* @param {boolean} replaceMode Use replace instead of insert
* @param {boolean} isXhtml Use XHTML
* @return {string} Filtered text
*/
function nl2br (str, replaceMode, isXhtml) {
var breakTag = (isXhtml) ? '<br />' : '<br>';
var replaceStr = (replaceMode) ? '$1'+ breakTag : '$1'+ breakTag +'$2';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, replaceStr);
}
You would need to enable https binding on server side. IISExpress in this case. Select Properties on website project in solution explorer (not double click). In the properties pane then you need to enable SSL.
According the android.com, you only need to set it in the AndroidManifest.xml file:
http://developer.android.com/guide/topics/ui/themes.html#ApplyATheme
Adding the theme attribute to your application element worked for me:
--AndroidManifest.xml--
...
<application ...
android:theme="@android:style/Theme.Holo"/>
...
</application>
Don't forget to change profile in Provision Profile sections:
Ideally you should see Automatic
in Code Signing Identity
after you choose provision profile you need. If you don't see any option that's mean you don't have private key for current provision profile.
If it is test code you want to time, then you can use the time
attribute:
@Test(timeout = 1000)
public void shouldTakeASecondOrLess()
{
}
If it is production code, there is no simple mechanism, and which solution you use depends upon whether you can alter the code to be timed or not.
If you can change the code being timed, then a simple approach is is to have your timed code remember it's start time, and periodically the current time against this. E.g.
long startTime = System.currentTimeMillis();
// .. do stuff ..
long elapsed = System.currentTimeMillis()-startTime;
if (elapsed>timeout)
throw new RuntimeException("tiomeout");
If the code itself cannot check for timeout, you can execute the code on another thread, and wait for completion, or timeout.
Callable<ResultType> run = new Callable<ResultType>()
{
@Override
public ResultType call() throws Exception
{
// your code to be timed
}
};
RunnableFuture future = new FutureTask(run);
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(future);
ResultType result = null;
try
{
result = future.get(1, TimeUnit.SECONDS); // wait 1 second
}
catch (TimeoutException ex)
{
// timed out. Try to stop the code if possible.
future.cancel(true);
}
service.shutdown();
}
Check that you are extending CI_Controller
class in your controller and in the view you have to echo base_url($path)
function, otherwise it will not work.
Just in case it helps someone, here's what caused this error for me: I needed a procedure to return json but I left out the for json path:
set @jsonout = (SELECT ID, SumLev, Census_GEOID, AreaName, Worksite
from CS_GEO G (nolock)
join @allids a on g.ID = a.[value]
where g.Worksite = @worksite)
When I tried to save the stored procedure, it threw the error. I fixed it by adding for json path to the code at the end of the procedure:
set @jsonout = (SELECT ID, SumLev, Census_GEOID, AreaName, Worksite
from CS_GEO G (nolock)
join @allids a on g.ID = a.[value]
where g.Worksite = @worksite for json path)
As a workaround to this limitation, I use two rules to cover all the cases.
For example, if I want to allow or deny these 18 ports:
465,110,995,587,143,11025,20,21,22,26,80,443,3000,10000,7080,8080,3000,5666
I use the below rules:
iptables -A INPUT -p tcp -i eth0 -m multiport --dports 465,110,995,587,143,11025,20,21,22,26,80,443 -j ACCEPT
iptables -A INPUT -p tcp -i eth0 -m multiport --dports 3000,10000,7080,8080,3000,5666 -j ACCEPT
The above rules should work for your scenario also. You can create another rule if you hit 15 ports limit on both first and second rule.
Simply...
$('#myForm').submit(function() {
return confirm("Click OK to continue?");
});
or
$('#myForm').submit(function() {
var status = confirm("Click OK to continue?");
if(status == false){
return false;
}
else{
return true;
}
});
I have same problem with the most basic situation and my problem was solved with inserting this meta in the head:
<meta charset="UTF-8">
the character encoding (which is actually UTF-8) of the html document was not declared
you need to have/create a HiveContext
import org.apache.spark.sql.hive.HiveContext;
HiveContext sqlContext = new org.apache.spark.sql.hive.HiveContext(sc.sc());
Then directly save dataframe or select the columns to store as hive table
df is dataframe
df.write().mode("overwrite").saveAsTable("schemaName.tableName");
or
df.select(df.col("col1"),df.col("col2"), df.col("col3")) .write().mode("overwrite").saveAsTable("schemaName.tableName");
or
df.write().mode(SaveMode.Overwrite).saveAsTable("dbName.tableName");
SaveModes are Append/Ignore/Overwrite/ErrorIfExists
I added here the definition for HiveContext from Spark Documentation,
In addition to the basic SQLContext, you can also create a HiveContext, which provides a superset of the functionality provided by the basic SQLContext. Additional features include the ability to write queries using the more complete HiveQL parser, access to Hive UDFs, and the ability to read data from Hive tables. To use a HiveContext, you do not need to have an existing Hive setup, and all of the data sources available to a SQLContext are still available. HiveContext is only packaged separately to avoid including all of Hive’s dependencies in the default Spark build.
on Spark version 1.6.2, using "dbName.tableName" gives this error:
org.apache.spark.sql.AnalysisException: Specifying database name or other qualifiers are not allowed for temporary tables. If the table name has dots (.) in it, please quote the table name with backticks ().`
The simplest way is to create a computed column in XLS that would generate the syntax of the insert statement. Then copy these insert into a text file and then execute on the SQL. The other alternatives are to buy database connectivity add-on's for Excel and write VBA code to accomplish the same.
As pointed in the comments, file
is a blob
:
file instanceof Blob; // true
And you can get its content with the file reader API https://developer.mozilla.org/en/docs/Web/API/FileReader
Read more: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
var input = document.querySelector('input[type=file]');
var textarea = document.querySelector('textarea');
function readFile(event) {
textarea.textContent = event.target.result;
console.log(event.target.result);
}
function changeFile() {
var file = input.files[0];
var reader = new FileReader();
reader.addEventListener('load', readFile);
reader.readAsText(file);
}
input.addEventListener('change', changeFile);
_x000D_
<input type="file">
<textarea rows="10" cols="50"></textarea>
_x000D_
Pattern class is the entry point of the regex engine.You can use it through Pattern.matches() and Pattern.comiple(). #Difference between these two. matches()- for quickly check if a text (String) matches a given regular expression comiple()- create the reference of Pattern. So can use multiple times to match the regular expression against multiple texts.
For reference:
public static void main(String[] args) {
//single time uses
String text="The Moon is far away from the Earth";
String pattern = ".*is.*";
boolean matches=Pattern.matches(pattern,text);
System.out.println("Matches::"+matches);
//multiple time uses
Pattern p= Pattern.compile("ab");
Matcher m=p.matcher("abaaaba");
while(m.find()) {
System.out.println(m.start()+ " ");
}
}
You are doing everything right, except passing your bundle path to asset()
function.
According to documentation - in your example this should look like below:
{{ asset('bundles/webshome/css/main.css') }}
Tip: you also can call assets:install with --symlink
key, so it will create symlinks in web folder. This is extremely useful when you often apply js
or css
changes (in this way your changes, applied to src/YouBundle/Resources/public
will be immediately reflected in web
folder without need to call assets:install
again):
app/console assets:install web --symlink
Also, if you wish to add some assets in your child template, you could call parent()
method for the Twig block. In your case it would be like this:
{% block stylesheets %}
{{ parent() }}
<link href="{{ asset('bundles/webshome/css/main.css') }}" rel="stylesheet">
{% endblock %}
I would add one more thing to Marc's answer: The memberOf attribute can't contain wildcards, so you can't say something like "memberof=CN=SPS*", and expect it to find all groups that start with "SPS".
You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run
ALTER USER <user> quota unlimited on <tablespace name>;
or
ALTER USER <user> quota 100M on <tablespace name>;
as a DBA user (depending on how much space you need / want to grant).
Use URLSessionDownloadTask
to download files in background so that they can completed even if the app is terminated.
For more information see:
https://www.ralfebert.de/snippets/ios/urlsession-background-downloads/
It also shows how to implement progress monitoring for multiple tasks running in parallel:
Try this:
<img v-bind:src="'/media/avatars/' + joke.avatar" />
Don't forget single quote around your path string. also in your data check you have correctly defined image variable.
joke: {
avatar: 'image.jpg'
}
A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output
Maybe you wrongly set permission on python3. For instance if for the file permission is set like
`os.chmod('spam.txt', 0777)` --> This will lead to SyntaxError
This syntax was used in Python2. Now if you change like:
os.chmod('spam.txt', 777)
--> This is still worst!! Your permission will be set wrongly since are not on "octal" but on decimal.
Afterwards you will get permission Error if you try for instance to remove the file: PermissionError: [WinError 5] Access is denied:
Solution for python3 is quite easy:
os.chmod('spam.txt', 0o777)
--> The syntax is now ZERO and o "0o"
The proper way to do it is using the ng-options
directive. The HTML would look like this.
<select ng-model="selectedTestAccount"
ng-options="item.Id as item.Name for item in testAccounts">
<option value="">Select Account</option>
</select>
JavaScript:
angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
$scope.selectedTestAccount = null;
$scope.testAccounts = [];
$http({
method: 'GET',
url: '/Admin/GetTestAccounts',
data: { applicationId: 3 }
}).success(function (result) {
$scope.testAccounts = result;
});
});
You'll also need to ensure angular is run on your html and that your module is loaded.
<html ng-app="test">
<body ng-controller="DemoCtrl">
....
</body>
</html>
Here's the calling order:
app.config()
app.run()
app.controller()
Here's a simple demo where you can watch each one executing (and experiment if you'd like).
From Angular's module docs:
Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.
Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
One situation where run blocks are used is during authentications.
The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.
Try using %lx
or %llx
. For more portability, include inttypes.h
and use the PRIx64
macro.
For example: printf("val = 0x%" PRIx64 "\n", val);
(note that it's string concatenation)
Have come across such issue. The root cause is the .m2 folder. You gotta make sure that whatever you're trying to access is present there in your .m2 folder (this is your local repo). If the stuff is there then you're good. This is usually present inside of users folder on your system (be it mac/linux or even windows)
extension Array where Element : Equatable {
public subscript(safe bounds: Range<Int>) -> ArraySlice<Element> {
if bounds.lowerBound > count { return [] }
let lower = Swift.max(0, bounds.lowerBound)
let upper = Swift.max(0, Swift.min(count, bounds.upperBound))
return self[lower..<upper]
}
public subscript(safe lower: Int?, _ upper: Int?) -> ArraySlice<Element> {
let lower = lower ?? 0
let upper = upper ?? count
if lower > upper { return [] }
return self[safe: lower..<upper]
}
}
returns a copy of this range clamped to the given limiting range.
var arr = [1, 2, 3]
arr[safe: 0..<1] // returns [1] assert(arr[safe: 0..<1] == [1])
arr[safe: 2..<100] // returns [3] assert(arr[safe: 2..<100] == [3])
arr[safe: -100..<0] // returns [] assert(arr[safe: -100..<0] == [])
arr[safe: 0, 1] // returns [1] assert(arr[safe: 0, 1] == [1])
arr[safe: 2, 100] // returns [3] assert(arr[safe: 2, 100] == [3])
arr[safe: -100, 0] // returns [] assert(arr[safe: -100, 0] == [])
Very simple, no library required:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
or you might prefer:
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
Some browsers will treat two digit years as being in the 20th century, so that:
new Date(14, 0, 1);
gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:
var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14
In my case I console.log(this.$route)
and returned the fullPath:
console.js:
fullPath: "/solicitud/MX/666",
params: {market: "MX", id: "666"},
path: "/solicitud/MX/666"
console.js: /solicitud/MX/666
It's often easier to think in the positive sense, and wrap it in a not:
elif not (var1 == 80 or var1 == 443 or (1024 <= var1 <= 65535)):
# fail
You could of course also go all out and be a bit more object-oriented:
class PortValidator(object):
@staticmethod
def port_allowed(p):
if p == 80: return True
if p == 443: return True
if 1024 <= p <= 65535: return True
return False
# ...
elif not PortValidator.port_allowed(var1):
# fail
your_string = 'Hello world';
words_array = your_tring.split(' ');
string_without_space = '';
for(i=0; i<words_array.length; i++){
new_text += words_array[i];
}
console.log("The new word:" new_text);
The output:
HelloWorld
There is a lot of good information here, but I wanted to add a simple snippet that I find useful.
How does it differ from some above?
_usage(){
_echoerr "Usage: $0 <args>"
}
_echoerr(){
echo "$*" >&2
}
if [ "$#" -eq 0 ]; then # NOTE: May need to customize this conditional
_usage
exit 2
fi
main "$@"
You can change it manually:
private void UpdateConfigFile(string appConfigPath, string key, string value)
{
var appConfigContent = File.ReadAllText(appConfigPath);
var searchedString = $"<add key=\"{key}\" value=\"";
var index = appConfigContent.IndexOf(searchedString) + searchedString.Length;
var currentValue = appConfigContent.Substring(index, appConfigContent.IndexOf("\"", index) - index);
var newContent = appConfigContent.Replace($"{searchedString}{currentValue}\"", $"{searchedString}{newValue}\"");
File.WriteAllText(appConfigPath, newContent);
}
This worked for me
<script>
function cancelBubble(e) {
var evt = e ? e:window.event;
if (evt.stopPropagation) evt.stopPropagation();
if (evt.cancelBubble!=null) evt.cancelBubble = true;
}
</script>
<div onclick="alert('Click!')">
<div onclick="cancelBubble(event)">Something inside the other div</div>
</div>
using recursion,
def gcd(a,b):
return a if not b else gcd(b, a%b)
using while,
def gcd(a,b):
while b:
a,b = b, a%b
return a
using lambda,
gcd = lambda a,b : a if not b else gcd(b, a%b)
>>> gcd(10,20)
>>> 10
You forgot to declare double as a return type
public double diameter()
{
double d = radius * 2;
return d;
}
document.getElementById("placehere").appendChild(elem);
not
document.getElementById("placehere").appendChild("elem");
and use the below to set the source
elem.src = 'images/hydrangeas.jpg';
1) To redirect to the login page / from the login page, don't use the Redirect() methods. Use FormsAuthentication.RedirectToLoginPage()
and FormsAuthentication.RedirectFromLoginPage()
!
2) You should just use RedirectToAction("action", "controller") in regular scenarios..
You want to redirect in side the Initialize method? Why? I don't see why would you ever want to do this, and in most cases you should review your approach imo.. If you want to do this for authentication this is DEFINITELY the wrong way (with very little chances foe an exception)
Use the [Authorize]
attribute on your controller or method instead :)
UPD: if you have some security checks in the Initialise method, and the user doesn't have access to this method, you can do a couple of things: a)
Response.StatusCode = 403;
Response.End();
This will send the user back to the login page. If you want to send him to a custom location, you can do something like this (cautios: pseudocode)
Response.Redirect(Url.Action("action", "controller"));
No need to specify the full url. This should be enough. If you completely insist on the full url:
Response.Redirect(new Uri(Request.Url, Url.Action("action", "controller")).ToString());
You can split date month year from current date as follows:
DateTime todaysDate = DateTime.Now.Date;
Day:
int day = todaysDate.Day;
Month:
int month = todaysDate.Month;
Year:
int year = todaysDate.Year;
The simplest way you can do this is to use java script.
For example, <input type="button" value="load" onclick="window.location='userpage.jsp'" >
At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut
is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.
If you have branch name including Forward Slash (using git flow for example), you will need to replace the Forward Slash with its Unicode character %2F within the branch name.
Here is an example for the pipeline My-Pipeline-Name and the branch release/my-release-branch-name
Jenkins.instance.getItemByFullName("My-Pipeline-Name/release%2Fmy-release-branch-name").updateNextBuildNumber(BUILD_NUMBER)
I was able to find out about this by running the following command which will list the different jobs (branches) for your pipeline
Jenkins.instance.getItem("My-Pipeline-Name").getAllJobs()
Hope it helps.
Set the asp_tags = On
and short_open_tag = On
in both the files \apache\Apache2.2.21\bin\php.ini
and \bin\php\php5.3.8\php.ini
and then restart the apache server.
This is not a direct answer to the question, but in practice I often want to have an estimate of the number of rows that will be in the result set. For most type of queries, MySQL's "EXPLAIN" delivers that.
I for example use that to refuse to run a client query if the explain looks bad enough.
Then also daily run "ANALYZE LOCAL TABLE" (outside of replication, to prevent cluster locks) on your tables, on each involved MySQL server.
This solution also helps in cases of more than one extension like "Avishay.student.DB"
FileInfo FileInf = new FileInfo(filePath);
string strExtention = FileInf.Name.Replace(System.IO.Path.GetFileNameWithoutExtension(FileInf.Name), "");
You can use jQuery click
instead of using onclick
attribute, Try the following:
$('table').on('click', 'input[type="button"]', function(e){
$(this).closest('tr').remove()
})
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/
$.post('someUri', { },
function(data){ doSomeStuff })
.fail(function(error) { alert(error.responseJSON) });
Here's a different way of doing it.
If you're using Windows the following acts like double-clicking the file in Explorer, or giving the file name as an argument to the DOS "start" command: the file is opened with whatever application (if any) its extension is associated with.
filepath = 'textfile.txt'
import os
os.startfile(filepath)
Example:
import os
os.startfile('textfile.txt')
This will open textfile.txt with Notepad if Notepad is associated with .txt files.
You have two objects both named bank_holiday
-- one a list and one a function. Disambiguate the two.
bank_holiday[month]
is raising an error because Python thinks bank_holiday
refers to the function (the last object bound to the name bank_holiday
), whereas you probably intend it to mean the list.
Just remember that string comparison like "x" > "X" is case-sensitive
"aa" < "ab" //true
"aa" < "Ab" //false
You can use .toLowerCase()
to compare without case sensitivity.
Exceptions are a somewhat costly effect, if for example you have a user that provides an invalid password, it is typically a better idea to pass back a failure flag, or some other indicator that it is invalid.
This is due to the way that exceptions are handled, true bad input, and unique critical stop items should be exceptions, but not failed login info.
For me above solutions didn't work then I tried
map.setCenter(new google.maps.LatLng(lat, lng));
and it worked as expected.
<?php
// what if we want to extend more than one class?
abstract class ExtensionBridge
{
// array containing all the extended classes
private $_exts = array();
public $_this;
function __construct() {$_this = $this;}
public function addExt($object)
{
$this->_exts[]=$object;
}
public function __get($varname)
{
foreach($this->_exts as $ext)
{
if(property_exists($ext,$varname))
return $ext->$varname;
}
}
public function __call($method,$args)
{
foreach($this->_exts as $ext)
{
if(method_exists($ext,$method))
return call_user_method_array($method,$ext,$args);
}
throw new Exception("This Method {$method} doesn't exists");
}
}
class Ext1
{
private $name="";
private $id="";
public function setID($id){$this->id = $id;}
public function setName($name){$this->name = $name;}
public function getID(){return $this->id;}
public function getName(){return $this->name;}
}
class Ext2
{
private $address="";
private $country="";
public function setAddress($address){$this->address = $address;}
public function setCountry($country){$this->country = $country;}
public function getAddress(){return $this->address;}
public function getCountry(){return $this->country;}
}
class Extender extends ExtensionBridge
{
function __construct()
{
parent::addExt(new Ext1());
parent::addExt(new Ext2());
}
public function __toString()
{
return $this->getName().', from: '.$this->getCountry();
}
}
$o = new Extender();
$o->setName("Mahdi");
$o->setCountry("Al-Ahwaz");
echo $o;
?>
Or you can do it like as well:
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true" onchange="javascript:CalcTotalAmt();" OnSelectedIndexChanged="ddl_SelectedIndexChanged"></asp:DropDownList>
In my case that happened when uninstalling AspNet 5 RC1 Update 1 to update it for .Net Core 1.0 RC2. so I installed Visual Studio 2015 update 2, selected Microsoft Web Developer tools and everything went back to normal.
In my case I used Framework64 like below
cd\
cd "C:\Windows\Microsoft.NET\Framework64\v4.0.30319"
installutil.exe "C:\XXX\Bin\ABC.exe"
pause
I had a similiar problem, where I had a grid with "ajax textfields" (Yii CGridView) and just one submit button. Everytime I did a search on a textfield and hit enter the form submitted. I had to do something with the button because it was the only common button between the views (MVC pattern). All I had to do was remove type="submit"
and put onclick="document.forms[0].submit()
I had this problem when I got the latest on TFS while other projects were open in multiple instances of VS. I already have all the fixes above. Reopening VS fixed the problem.
I found some more information from this blog.
Here is sample code that might can be helpful.
var Human = function() {
name = "Shohanur Rahaman"; // Global variable
this.name = "Tuly"; // Constructor variable
var age = 21;
};
var shohan = new Human();
document.write(shohan.name + "<br>");
document.write(name);
document.write(age); // Undefined because it's a local variable
Here I found a nice answer: How can one declare a global variable in JavaScript?
For an unknow reason, the accepted answer partially works when I send email to my gmail address. I have the attachement but not the text of the email.
If you want both attachment and text try this based on the accepted answer :
Properties props = new java.util.Properties();
props.put("mail.smtp.host", "yourHost");
props.put("mail.smtp.port", "yourHostPort");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Session session = Session.getDefaultInstance(props, null);
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "password");
}
});
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(mailFrom));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
msg.setSubject("your subject");
Multipart multipart = new MimeMultipart();
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText("your text");
MimeBodyPart attachmentBodyPart= new MimeBodyPart();
DataSource source = new FileDataSource(attachementPath); // ex : "C:\\test.pdf"
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(fileName); // ex : "test.pdf"
multipart.addBodyPart(textBodyPart); // add the text part
multipart.addBodyPart(attachmentBodyPart); // add the attachement part
msg.setContent(multipart);
Transport.send(msg);
} catch (MessagingException e) {
LOGGER.log(Level.SEVERE,"Error while sending email",e);
}
Update :
If you want to send a mail as an html content formated you have to do
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setContent(content, "text/html");
So basically setText
is for raw text and will be well display on every server email including gmail, setContent
is more for an html template and if you content is formatted as html it will maybe also works in gmail
I have seen instances where the remote became out of sync and needed to be updated. If a reset --hard
or a branch -D
fail to work, try
git pull origin
git reset --hard
As other answers have said, the best way to do this involves making a new list - either iterate over a copy, or construct a list with only the elements you want and assign it back to the same variable. The difference between these depends on your use case, since they affect other variables for the original list differently (or, rather, the first affects them, the second doesn't).
If a copy isn't an option for some reason, you do have one other option that relies on an understanding of why modifying a list you're iterating breaks. List iteration works by keeping track of an index, incrementing it each time around the loop until it falls off the end of the list. So, if you remove at (or before) the current index, everything from that point until the end shifts one spot to the left. But the iterator doesn't know about this, and effectively skips the next element since it is now at the current index rather than the next one. However, removing things that are after the current index doesn't affect things.
This implies that if you iterate the list back to front, if you remove an item at the current index, everything to it's right shifts left - but that doesn't matter, since you've already dealt with all the elements to the right of the current position, and you're moving left - the next element to the left is unaffected by the change, and so the iterator gives you the element you expect.
TL;DR:
>>> a = list(range(5))
>>> for b in reversed(a):
if b == 3:
a.remove(b)
>>> a
[0, 1, 2, 4]
However, making a copy is usually better in terms of making your code easy to read. I only mention this possibility for sake of completeness.
The JSONArray.length() returns the number of elements in the JSONObject contained in the Array. Not the size of the array itself.
If you are looking for tools like the the mysql and mysqldump command line client for Windows for versions around mysql Ver 14.14 Distrib 5.6.13, for Win32 (x86) it seems to be in HOMEDRIVE:\Program Files (x86)\MySQL\MySQL Workbench version
This directory is also not placed in the path by default so you will need to add it to your PATH environment variable before you can easily run it from the command prompt.
Also, there is a mysql utilities console but it does not work for my needs. Below is a list of the capabilities on the mysql utilities console in case it works for you:
Utility Description ---------------- --------------------------------------------------------- mysqlauditadmin audit log maintenance utility mysqlauditgrep audit log search utility mysqldbcompare compare databases for consistency mysqldbcopy copy databases from one server to another mysqldbexport export metadata and data from databases mysqldbimport import metadata and data from files mysqldiff compare object definitions among objects where the difference is how db1.obj1 differs from db2.obj2 mysqldiskusage show disk usage for databases mysqlfailover automatic replication health monitoring and failover mysqlfrm show CREATE TABLE from .frm files mysqlindexcheck check for duplicate or redundant indexes mysqlmetagrep search metadata mysqlprocgrep search process information mysqlreplicate establish replication with a master mysqlrpladmin administration utility for MySQL replication mysqlrplcheck check replication mysqlrplshow show slaves attached to a master mysqlserverclone start another instance of a running server mysqlserverinfo show server information mysqluserclone clone a MySQL user account to one or more new users
You should not rely on a hash code being equal to a specific value. Just that it will return consistent results within the same execution. The API docs say the following :
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.
EDIT Since the javadoc for String.hashCode() specifies how a String's hash code is computed, any violation of this would violate the public API specification.
You have a method called getArguments()
that belongs to Fragment
class.
Try this:
<input type="button" onclick="function1();function2();" value="Call2Functions" />
Or, call second function at the end of first function:
function func1(){
//--- some logic
func2();
}
function func2(){
//--- some logic
}
...and call func1() onclick of button:
<input type="button" onclick="func1();" value="Call2Functions" />