My solution was to use the "-OutBuffer 2147483647" parameter in my query, which is part of the Common Parameters. PS C:> Get-Help about_CommonParameters -Full
If you are using fpdf, in order to be able to use line breaks you will need to use a multi-line text cell as described here.
If you use this, then line breaks in your text should be interpreted and converted correctly.
Just a quick example:
$pdf->Multicell(0,2,"This is a multi-line text string\nNew line\nNew line");
Here, 2 is the height of the multi-line text box. I don't know what units that's measured in or if you can just set it to 0 and ignore it. Perhaps try it with a large number if at first it doesn't work.
If you have Python installed then the easiest way you can check the version number is by typing "python" in your command prompt. It will show you the version number and if it is running on 32 bit or 64 bit and some other information. For some applications you would want to have a latest version and sometimes not. It depends on what packages you want to install or use.
The read_sql
docs say this params
argument can be a list, tuple or dict (see docs).
To pass the values in the sql query, there are different syntaxes possible: ?
, :1
, :name
, %s
, %(name)s
(see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2
in your case I suppose).
In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2
documentation, they support the %(name)s
style (and so not the :name
I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:
df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
index_col=['Timestamp'])
Yes it's the exact same thing in Python 2:
d.values()
In Python 3 (where dict.values
returns a view of the dictionary’s values instead):
list(d.values())
i've had to do this quite often. i have a directive and need to do some jquery stuff after model stuff is fully loaded into the DOM. so i put my logic in the link: function of the directive and wrap the code in a setTimeout(function() { ..... }, 1); the setTimout will fire after the DOM is loaded and 1 milisecond is the shortest amount of time after DOM is loaded before code would execute. this seems to work for me but i do wish angular raised an event once a template was done loading so that directives used by that template could do jquery stuff and access DOM elements. hope this helps.
I often have several statements at the start of a method to return for "easy" situations. For example, this:
public void DoStuff(Foo foo)
{
if (foo != null)
{
...
}
}
... can be made more readable (IMHO) like this:
public void DoStuff(Foo foo)
{
if (foo == null) return;
...
}
So yes, I think it's fine to have multiple "exit points" from a function/method.
You may not need to do with group by , using sort_values
+ drop_duplicates
df.sort_values('count').drop_duplicates(['Sp','Mt'],keep='last')
Out[190]:
Sp Mt Value count
0 MM1 S1 a 3
2 MM1 S3 cb 5
8 MM4 S2 uyi 7
3 MM2 S3 mk 8
4 MM2 S4 bg 10
Also almost same logic by using tail
df.sort_values('count').groupby(['Sp', 'Mt']).tail(1)
Out[52]:
Sp Mt Value count
0 MM1 S1 a 3
2 MM1 S3 cb 5
8 MM4 S2 uyi 7
3 MM2 S3 mk 8
4 MM2 S4 bg 10
Just use:
if file_name.endswith(tuple(extensions)):
Run the following command to retrieve the SHA256 fingerprint of your SSH key (-l
means "list" instead of create a new key, -f
means "filename"):
$ ssh-keygen -lf /path/to/ssh/key
So for example, on my machine the command I ran was (using RSA public key):
$ ssh-keygen -lf ~/.ssh/id_rsa.pub
2048 00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff /Users/username/.ssh/id_rsa.pub (RSA)
To get the GitHub (MD5) fingerprint format with newer versions of ssh-keygen, run:
$ ssh-keygen -E md5 -lf <fileName>
Bonus information:
ssh-keygen -lf
also works on known_hosts
and authorized_keys
files.
To find most public keys on Linux/Unix/OS X systems, run
$ find /etc/ssh /home/*/.ssh /Users/*/.ssh -name '*.pub' -o -name 'authorized_keys' -o -name 'known_hosts'
(If you want to see inside other users' homedirs, you'll have to be root or sudo.)
The ssh-add -l
is very similar, but lists the fingerprints of keys added to your agent. (OS X users take note that magic passwordless SSH via Keychain is not the same as using ssh-agent.)
AssertJ assertions can be used to compare the values without #equals
method properly overridden, e.g.:
import static org.assertj.core.api.Assertions.assertThat;
// ...
assertThat(actual)
.usingRecursiveComparison()
.isEqualTo(expected);
Since I don't have a high enough reputation to comment I'll answer liang question on Feb 20 at 10:01 as an answer to the original question.
In order for the for the line labels to show you need to add plt.legend to your code. to build on the previous example above that also includes title, ylabel and xlabel:
import matplotlib.pyplot as plt
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.title('title')
plt.ylabel('ylabel')
plt.xlabel('xlabel')
plt.legend()
plt.show()
list1 = (x[0] for x in source_list)
list2 = (x[1] for x in source_list)
Taking a look at the source code of OpenPyXL (IterableWorksheet) I've figured out how to get the column and row count from an iterator worksheet:
wb = load_workbook(path, use_iterators=True)
sheet = wb.worksheets[0]
row_count = sheet.get_highest_row() - 1
column_count = letter_to_index(sheet.get_highest_column()) + 1
IterableWorksheet.get_highest_column
returns a string with the column letter that you can see in Excel, e.g. "A", "B", "C" etc. Therefore I've also written a function to translate the column letter to a zero based index:
def letter_to_index(letter):
"""Converts a column letter, e.g. "A", "B", "AA", "BC" etc. to a zero based
column index.
A becomes 0, B becomes 1, Z becomes 25, AA becomes 26 etc.
Args:
letter (str): The column index letter.
Returns:
The column index as an integer.
"""
letter = letter.upper()
result = 0
for index, char in enumerate(reversed(letter)):
# Get the ASCII number of the letter and subtract 64 so that A
# corresponds to 1.
num = ord(char) - 64
# Multiply the number with 26 to the power of `index` to get the correct
# value of the letter based on it's index in the string.
final_num = (26 ** index) * num
result += final_num
# Subtract 1 from the result to make it zero-based before returning.
return result - 1
I still haven't figured out how to get the column sizes though, so I've decided to use a fixed-width font and automatically scaled columns in my application.
As thirtydot said, you can use the CSS3 background-size
syntax:
For example:
-o-background-size:35% auto;
-webkit-background-size:35% auto;
-moz-background-size:35% auto;
background-size:35% auto;
However, as also stated by thirtydot, this does not work in IE6, 7 and 8.
See the following links for more information about background-size
:
http://www.w3.org/TR/css3-background/#the-background-size
$path = "C:\temp\NewFolder"
If(!(test-path $path))
{
New-Item -ItemType Directory -Force -Path $path
}
Test-Path
checks to see if the path exists. When it does not, it will create a new directory.
Joachim Sauer's answer will work in scenarios like this. But there are some instances where adding parentheses won’t help.
For example: You are passing “sum of value of an input element and an integer” as an argument to a function.
arg1 = $("#elemId").val(); // value is treated as string
arg2 = 1;
someFuntion(arg1 + arg2); // and so the values are merged here
someFuntion((arg1 + arg2)); // and here
You can make it work by using Number()
arg1 = Number($("#elemId").val());
arg2 = 1;
someFuntion(arg1 + arg2);
or
arg1 = $("#elemId").val();
arg2 = 1;
someFuntion(Number(arg1) + arg2);
You can use http://www.fontsquirrel.com/fontface/generator to encode any font for websites. It'll generate the code to include the font.
I don't really use it for fonts over 30px. They look much better as an image (because images are anti-aliased, and some browsers don't anti-alias fonts in the browser).
See: http://www.truetype-typography.com/ttalias.htm
Hope that helps...
try like this
if (!(a | b)) {
//blahblah
}
It's same with
if (a | b) {}
else {
// blahblah
}
EDIT: As of Go 1.8 (Released February 2017) the recommended way of doing this is with os.Executable
:
func Executable() (string, error)
Executable returns the path name for the executable that started the current process. There is no guarantee that the path is still pointing to the correct executable. If a symlink was used to start the process, depending on the operating system, the result might be the symlink or the path it pointed to. If a stable result is needed, path/filepath.EvalSymlinks might help.
To get just the directory of the executable you can use path/filepath.Dir
.
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
ex, err := os.Executable()
if err != nil {
panic(err)
}
exPath := filepath.Dir(ex)
fmt.Println(exPath)
}
OLD ANSWER:
You should be able to use os.Getwd
func Getwd() (pwd string, err error)
Getwd returns a rooted path name corresponding to the current directory. If the current directory can be reached via multiple paths (due to symbolic links), Getwd may return any one of them.
For example:
package main
import (
"fmt"
"os"
)
func main() {
pwd, err := os.Getwd()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(pwd)
}
I personal recommended that the sql below because when i try use date function in the condition clause, its slow down my query speed very much.
anyway feel free to try this.
select CONCAT(DATEPART(YYYY,@mydate),'-',DATEPART(MM,@mydate),'-01')
simple way to use modals is with eModal!
Ex from github:
<script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
var options = {_x000D_
message: "The famouse question?",_x000D_
title: 'Header title',_x000D_
size: 'sm',_x000D_
callback: function(result) { result ? doActionTrue(result) : doActionFalse(); },_x000D_
subtitle: 'smaller text header',_x000D_
label: "True" // use the possitive lable as key_x000D_
//..._x000D_
};_x000D_
_x000D_
eModal.confirm(options);
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>_x000D_
<script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
_x000D_
Tip: You can use change the default label name! { label: 'Yes' | 'True'| 'OK' }
your nested for loop
for(int j = 0; j < array2.size(); i++){
is infinite as j will always equal to zero, on the other hand, i will be increased at will in this loop. You get OutOfBoundaryException when i is larger than plusArray.size()
You could try to use the --path= option to define the specific sub-folder you're wanting to execute and place specific migrations in there.
Alternatively you would need to remove reference and tables from the DB and migrations tables which isn't ideal :/
count = 0 if count == N else N+1
- the ternary operator. Although I'd say your solution is more readable than this.
Seems like the most exhaustive solution can be found at http://www.elfboy.com/blog/text-shadow_anti-aliasing/. Works in Firefox and Chrome, although Firefox is not quite as effective as Chrome.
Putting #pragma once
at the top of your header file will ensure that it is only included once. Note that #pragma once
is not standard C99, but supported by most modern compilers.
An alternative is to use include guards (e.g. #ifndef MY_FILE #define MY_FILE ... #endif /* MY_FILE */
)
This might help to match balanced parenthesis.
\s*\w+[(][^+]*[)]\s*
.htaccess
is in DOS format, change it to UNIX format (in Notepad++, click Edit>Convert
).htaccess
is in UTF8 Without-BOM, make it WITH BOM.The classes of problem that are well suited for a mapreduce style solution are problems of aggregation. Of extracting data from a dataset. In C#, one could take advantage of LINQ to program in this style.
From the following article: http://codecube.net/2009/02/mapreduce-in-c-using-linq/
the GroupBy method is acting as the map, while the Select method does the job of reducing the intermediate results into the final list of results.
var wordOccurrences = words
.GroupBy(w => w)
.Select(intermediate => new
{
Word = intermediate.Key,
Frequency = intermediate.Sum(w => 1)
})
.Where(w => w.Frequency > 10)
.OrderBy(w => w.Frequency);
For the distributed portion, you could check out DryadLINQ: http://research.microsoft.com/en-us/projects/dryadlinq/default.aspx
If for some reasons while trying to add headers or set control policy you're still getting nowhere you may consider using apache ProxyPass…
For example in one <VirtualHost>
that uses SSL add the two following directives:
SSLProxyEngine On
ProxyPass /oauth https://remote.tld/oauth
Make sure the following apache modules are loaded (load them using a2enmod):
Obviously you'll have to change your AJAX requests url in order to use the apache proxy…
... onkeydown="if(value.length>500)value=value.substr(0,500); if(value.length==500)return false;" ...
It ought to work.
Window-->Web Browser--> Firefox
Just to complement @Marcus Ekwall 's answer. Doing like this will get only anchor links. And you aren't going to have problems if you have a mix of anchor links and regular ones.
jQuery(document).ready(function(jQuery) {
var topMenu = jQuery("#top-menu"),
offset = 40,
topMenuHeight = topMenu.outerHeight()+offset,
// All list items
menuItems = topMenu.find('a[href*="#"]'),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
var href = jQuery(this).attr("href"),
id = href.substring(href.indexOf('#')),
item = jQuery(id);
//console.log(item)
if (item.length) { return item; }
});
// so we can get a fancy scroll animation
menuItems.click(function(e){
var href = jQuery(this).attr("href"),
id = href.substring(href.indexOf('#'));
offsetTop = href === "#" ? 0 : jQuery(id).offset().top-topMenuHeight+1;
jQuery('html, body').stop().animate({
scrollTop: offsetTop
}, 300);
e.preventDefault();
});
// Bind to scroll
jQuery(window).scroll(function(){
// Get container scroll position
var fromTop = jQuery(this).scrollTop()+topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function(){
if (jQuery(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
menuItems.parent().removeClass("active");
if(id){
menuItems.parent().end().filter("[href*='#"+id+"']").parent().addClass("active");
}
})
})
Basically i replaced
menuItems = topMenu.find("a"),
by
menuItems = topMenu.find('a[href*="#"]'),
To match all links with anchor somewhere, and changed all that what was necessary to make it work with this
See it in action on jsfiddle
Your example is perfect: the field is private and it has a getter. This is the normal way to access a field. If you need a direct access to an object field, use reflection. Using reflection to get a field's value is a hack and should be used in extreme cases such as using a library whose code you cannot change.
SAP is notoriously bad at making these downloads available... or in an easily accessible location so hopefully this link still works by the time you read this answer.
< original link no longer active >
http://scn.sap.com/docs/DOC-7824 Updated Link 2/6/13:
https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads - "Updated 10/31/2017"
http://www.crystalreports.com/crvs/confirm/ - "Updated 10/31/2017"
Uncomment the .php location in /etc/nginx/sites-available/default
sudo vi /etc/nginx/sites-available/default:
location ~ \.php$ {
include snippets/fastcgi-php.conf;
# With php5-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
}
Here's an example where the absence of b
would throw a TypeError
exception in Python 3.x
>>> f=open("new", "wb")
>>> f.write("Hello Python!")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface
Adding a b
prefix would fix the problem.
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 ().`
Acording to your first code snipet seems ok, but I've got similar behavior caused by bad programing. Have you checked the "options" variable is not null before the put call?
I'm using Struts2 (2.3.3) webapp and use a HashMap for displaying results. When is executed (in a class initialized by an Action class) :
if(value != null) pdfMap.put("date",value.toString());
else pdfMap.put("date","");
Got this error:
Struts Problem Report
Struts has detected an unhandled exception:
Messages:
File: aoc/psisclient/samples/PDFValidation.java
Line number: 155
Stacktraces
java.lang.NullPointerException
aoc.psisclient.samples.PDFValidation.getRevisionsDetail(PDFValidation.java:155)
aoc.action.signature.PDFUpload.execute(PDFUpload.java:66)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
...
Seems the NullPointerException points to the put method (Line number 155), but the problem was that de Map hasn't been initialized before. It compiled ok since the variable is out of the method that set the value.
I wrote a JavaScript analogue of a PHP function number_format on a base of Abe Miessler addCommas function. Could be usefull.
number_format = function (number, decimals, dec_point, thousands_sep) {
number = number.toFixed(decimals);
var nstr = number.toString();
nstr += '';
x = nstr.split('.');
x1 = x[0];
x2 = x.length > 1 ? dec_point + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1))
x1 = x1.replace(rgx, '$1' + thousands_sep + '$2');
return x1 + x2;
}
For example:
var some_number = number_format(42661.55556, 2, ',', ' '); //gives 42 661,56
Googling brings you to android.content.ClipboardManager and you could decide, as I did, that Clipboard is not available on API < 11, because the documentation page says "Since: API Level 11".
There are actually two classes, second one extending the first - android.text.ClipboardManager and android.content.ClipboardManager.
android.text.ClipboardManager is existing since API 1, but it works only with text content.
android.content.ClipboardManager is the preferred way to work with clipboard, but it's not available on API Level < 11 (Honeycomb).
To get any of them you need the following code:
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
But for API < 11 you have to import android.text.ClipboardManager
and for API >= 11 android.content.ClipboardManager
Apparently, the question never says to run on local mode not on yarn. Somehow I couldnt get spark-default.conf change to work. Instead I tried this and it worked for me
bin/spark-shell --master yarn --num-executors 6 --driver-memory 5g --executor-memory 7g
( couldnt bump executor-memory to 8g there is some restriction from yarn configuration.)
In ES6 2 new methods are added for Number Object.
In it Number.isInteger() method returns true if the argument is an integer.
Example usage :
Number.isInteger(10); // returns true
Number.isInteger(10.5); // returns false
Number.isInteger("10"); // returns false
Update your last wrong commit message with the new commit message in one line:
git commit --amend -m "your new commit message"
Or, try Git reset like below:
# You can reset your head to n number of commit
# NOT a good idea for changing last commit message,
# but you can get an idea to split commit into multiple commits
git reset --soft HEAD^
# It will reset you last commit. Now, you
# can re-commit it with new commit message.
git reset
can help you to break one commit into multiple commits too:
# Reset your head. I am resetting to last commits:
git reset --soft HEAD^
# (You can reset multiple commit by doing HEAD~2(no. of commits)
# Now, reset your head for splitting it to multiple commits
git reset HEAD
# Add and commit your files separately to make multiple commits: e.g
git add app/
git commit -m "add all files in app directory"
git add config/
git commit -m "add all files in config directory"
Here you have successfully broken your last commit into two commits.
Paul Welter's ASP.NET blog has a dictionary that is serializeable. But it does not use attributes. I will explain why below the code.
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue>
: Dictionary<TKey, TValue>, IXmlSerializable
{
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
return;
while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
reader.ReadStartElement("item");
reader.ReadStartElement("key");
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement("value");
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement("item");
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement("value");
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
#endregion
}
First, there is one gotcha with this code. Say you read a dictionary from another source that has this:
<dictionary>
<item>
<key>
<string>key1</string>
</key>
<value>
<string>value1</string>
</value>
</item>
<item>
<key>
<string>key1</string>
</key>
<value>
<string>value2</string>
</value>
</item>
</dictionary>
This will throw a exception on de-seariazation because you can only have one key for a dictionary.
The reason you MUST use a XElement in a seriazed dictionary is dictionary is not defined as Dictionary<String,String>
, a dictionary is Dictionary<TKey,TValue>
.
To see the problem, ask your self: Lets say we have a TValue
that serializes in to something that uses Elements it describes itself as XML (lets say a dictionary of dictionaries Dictionary<int,Dictionary<int,string>>
(not that uncommon of a pattern, it's a lookup table)), how would your Attribute only version represent a dictionary entirely inside a attribute?
The regular expression you are after will most likely be huge and a nightmare to maintain especially for people who are not that familiar with regular expressions.
I think it would be easier to break your regex down and do it one bit at a time. It might take a bit more to do, but I am pretty sure that maintaining it and debugging it would be easier. This would also allow you to provide more directed error messages to your users (other than just Invalid Password
) which should improve user experience.
From what I am seeing you are pretty fluent in regex, so I would presume that giving you the regular expressions to do what you need would be futile.
Seeing your comment, this is how I would go about it:
Must be eight characters Long: You do not need a regex for this. Using the .Length
property should be enough.
Including one uppercase letter: You can use the [A-Z]+
regular expression. If the string contains at least one upper case letter, this regular expression will yield true
.
One special character: You can use either the \W
which will match any character which is not a letter or a number or else, you can use something like so [!@#]
to specify a custom list of special characters. Note though that characters such as $
, ^
, (
and )
are special characters in the regular expression language, so they need to be escaped like so: \$
. So in short, you might use the \W
.
Alphanumeric characters: Using the \w+
should match any letter and number and underscore.
Take a look at this tutorial for more information.
I guess your code uses somewhere in the second case a singular matrix (i.e. not invertible), and the solve function needs to invert it. This has nothing to do with the size but with the fact that some of your vectors are (probably) colinear.
I always use the time-stamp - so its not possible, that the file exists already:
import os
import shutil
import datetime
now = str(datetime.datetime.now())[:19]
now = now.replace(":","_")
src_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand.xlsx"
dst_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand_"+str(now)+".xlsx"
shutil.copy(src_dir,dst_dir)
but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?
That is what xrange(n)
is for. It avoids creating a list of numbers, and instead just provides an iterator object.
In Python 3, xrange()
was renamed to range()
- if you want a list, you have to specifically request it via list(range(n))
.
Maybe use JXHyperlink
from SwingX instead. It extends JButton
. Some useful links:
Check whether your app has the needed permissions.I was also getting the same error and I checked the logcat debug log which showed this:
04-15 13:38:25.387: E/AndroidRuntime(694): java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:555-555-5555 cmp=com.android.phone/.OutgoingCallBroadcaster } from ProcessRecord{44068640 694:rahulserver.test/10055} (pid=694, uid=10055) requires android.permission.CALL_PHONE
I then gave the needed permission in my android-manifest which worked for me.
Use insert
:
In [1]: ls = [1,2,3]
In [2]: ls.insert(0, "new")
In [3]: ls
Out[3]: ['new', 1, 2, 3]
I use the following alternative to get default/optional params and "kind-of-overloaded" constructors with variable number of params:
private x?: number;
private y?: number;
constructor({x = 10, y}: {x?: number, y?: number}) {
this.x = x;
this.y = y;
}
I know it's not the prettiest code ever, but one gets used to it. No need for the additional Interface and it allows private members, which is not possible when using the Interface.
In .NET Framework 4 there is enhancement System.Guid structure, These includes new TryParse and TryParseExact methods to Parse GUID. Here is example for this.
//Generate New GUID
Guid objGuid = Guid.NewGuid();
//Take invalid guid format
string strGUID = "aaa-a-a-a-a";
Guid newGuid;
if (Guid.TryParse(objGuid.ToString(), out newGuid) == true)
{
Response.Write(string.Format("<br/>{0} is Valid GUID.", objGuid.ToString()));
}
else
{
Response.Write(string.Format("<br/>{0} is InValid GUID.", objGuid.ToString()));
}
Guid newTmpGuid;
if (Guid.TryParse(strGUID, out newTmpGuid) == true)
{
Response.Write(string.Format("<br/>{0} is Valid GUID.", strGUID));
}
else
{
Response.Write(string.Format("<br/>{0} is InValid GUID.", strGUID));
}
In this example we create new guid object and also take one string variable which has invalid guid. After that we use TryParse method to validate that both variable has valid guid format or not. By running example you can see that string variable has not valid guid format and it gives message of "InValid guid". If string variable has valid guid than this will return true in TryParse method.
This is a linker issue. Try:
g++ -o test_1 test_1.cpp `pkg-config opencv --cflags --libs`
This should work to compile the source. However, if you recently compiled OpenCV from source, you will meet linking issue in run-time, the library will not be found. In most cases, after compiling libraries from source, you need to do finally:
sudo ldconfig
This solution works with Swift 4 (Xcode 9.2) and also with Swift 5 (Xcode 10.2.1+):
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
do {
let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
// process files
} catch {
print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
}
Here's a reusable FileManager extension that also lets you skip or include hidden files in the results:
import Foundation
extension FileManager {
func urls(for directory: FileManager.SearchPathDirectory, skipsHiddenFiles: Bool = true ) -> [URL]? {
let documentsURL = urls(for: directory, in: .userDomainMask)[0]
let fileURLs = try? contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil, options: skipsHiddenFiles ? .skipsHiddenFiles : [] )
return fileURLs
}
}
// Usage
print(FileManager.default.urls(for: .documentDirectory) ?? "none")
Above comments are both solid responses, however note that they aren't thread safe. If you are writing to the console with multiple threads, changing colors will add a race condition that can create some strange looking output. It is simple to fix though:
public class ConsoleWriter
{
private static object _MessageLock= new object();
public void WriteMessage(string message)
{
lock (_MessageLock)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine(message);
Console.ResetColor();
}
}
}
Just put the following code on the top of the page
@{
Layout = "";
}
like this Working demo http://jsfiddle.net/7e2XU/21/show/# * Update: http://jsfiddle.net/kz5kjmbt/
<div class="container">
<div class="row" style="padding-top: 240px;"> <a href="#" class="btn btn-large btn-primary" rel="popover" data-content='
<form id="mainForm" name="mainForm" method="post" action="">
<p>
<label>Name :</label>
<input type="text" id="txtName" name="txtName" />
</p>
<p>
<label>Address 1 :</label>
<input type="text" id="txtAddress" name="txtAddress" />
</p>
<p>
<label>City :</label>
<input type="text" id="txtCity" name="txtCity" />
</p>
<p>
<input type="submit" name="Submit" value="Submit" />
</p>
</form>
data-placement="top" data-original-title="Fill in form">Open form</a>
</div>
</div>
JavaScript code:
$('a[rel=popover]').popover({
html: 'true',
placement: 'right'
})
ScreenShot
You can make use of the React.createClone method. Create your element, than create a clone of it. During the clone's creation, you can inject props. Inject an onClick : method prop like this
{ onClick : () => this.changeColor(originalElement, index) }
the changeColor method will set the state with the duplicate, allowing you sto set the color in the process.
render()_x000D_
{_x000D_
return(_x000D_
<ul>_x000D_
_x000D_
{this.state.items.map((val, ind) => {_x000D_
let item = <li key={ind}>{val}</li>;_x000D_
let props = { _x000D_
onClick: () => this.Click(item, ind),_x000D_
key : ind,_x000D_
ind_x000D_
}_x000D_
let clone = React.cloneElement(item, props, [val]);_x000D_
return clone;_x000D_
})}_x000D_
_x000D_
</ul>_x000D_
)_x000D_
}
_x000D_
#include <stdint.h> // uint32_t [available since C99]
/// Determine the number of digits for a 32 bit integer.
/// - Uses at most 4 comparisons.
/// - (cX) 2014 [email protected]
/// - \see http://stackoverflow.com/questions/1489830/#27669966
/** #d == Number length vs Number of comparisons == #c
\code
#d | #c #d | #c
---+--- ---+---
10 | 4 5 | 4
9 | 4 4 | 4
8 | 3 3 | 3
7 | 3 2 | 3
6 | 3 1 | 3
\endcode
*/
unsigned NumDigits32bs(uint32_t x) {
return // Num-># Digits->[0-9] 32->bits bs->Binary Search
( x >= 100000u // [6-10] [1-5]
? // [6-10]
( x >= 10000000u // [8-10] [6-7]
? // [8-10]
( x >= 100000000u // [9-10] [8]
? // [9-10]
( x >= 1000000000u // [10] [9]
? 10
: 9
)
: 8
)
: // [6-7]
( x >= 1000000u // [7] [6]
? 7
: 6
)
)
: // [1-5]
( x >= 100u // [3-5] [1-2]
? // [3-5]
( x >= 1000u // [4-5] [3]
? // [4-5]
( x >= 10000u // [5] [4]
? 5
: 4
)
: 3
)
: // [1-2]
( x >= 10u // [2] [1]
? 2
: 1
)
)
);
}
#
indicates that the following line is a preprocessor directive and should be processed by the preprocessor before compilation by the compiler.
So, #include
is a preprocessor directive that tells the preprocessor to include header files in the program.
< >
indicate the start and end of the file name to be included.
iostream
is a header file that contains functions for input/output operations (cin
and cout
).
Now to sum it up C++ to English translation of the command, #include <iostream>
is:
Dear preprocessor, please include all the contents of the header file iostream
at the very beginning of this program before compiler starts the actual compilation of the code.
from s in db.Services
join sa in db.ServiceAssignments on s.Id equals sa.ServiceId
where sa.LocationId == 1
select s
Where db
is your DbContext
. Generated query will look like (sample for EF6):
SELECT [Extent1].[Id] AS [Id]
-- other fields from Services table
FROM [dbo].[Services] AS [Extent1]
INNER JOIN [dbo].[ServiceAssignments] AS [Extent2]
ON [Extent1].[Id] = [Extent2].[ServiceId]
WHERE [Extent2].[LocationId] = 1
If you are using Java 8+, use java.time.LocalDate type instead.
LocalDate now = LocalDate.now();
System.out.println(now.toString());
The output:
2019-05-30
https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
2^31-1 bytes. So, a little less than 2^31-1 characters for varchar(max) and half that for nvarchar(max).
Such problem might occur when you use surfire plugin 3.x.x+ with JUnit5 and by mistake annotate the test class with @Test
annotation from JUnit4.
Use: org.junit.jupiter.api.Test
(JUnit5) instead of org.junit.Test
(Junit4)
NOTE: this might be hard to notice as the IDE might run this wihout problems just as JUnit4 test.
I don't think you will get a good answer to this, partly because nobody really agrees on what REST is. The wikipedia page is heavy on buzzwords and light on explanation. The discussion page is worth a skim just to see how much people disagree on this. As far as I can tell however, REST means this:
Instead of having randomly named setter and getter URLs and using GET
for all the getters and POST
for all the setters, we try to have the URLs identify resources, and then use the HTTP actions GET
, POST
, PUT
and DELETE
to do stuff to them. So instead of
GET /get_article?id=1
POST /delete_article id=1
You would do
GET /articles/1/
DELETE /articles/1/
And then POST
and PUT
correspond to "create" and "update" operations (but nobody agrees which way round).
I think the caching arguments are wrong, because query strings are generally cached, and besides you don't really need to use them. For example django makes something like this very easy, and I wouldn't say it was REST:
GET /get_article/1/
POST /delete_article/ id=1
Or even just include the verb in the URL:
GET /read/article/1/
POST /delete/article/1/
POST /update/article/1/
POST /create/article/
In that case GET
means something without side-effects, and POST
means something that changes data on the server. I think this is perhaps a bit clearer and easier, especially as you can avoid the whole PUT
-vs-POST
thing. Plus you can add more verbs if you want to, so you aren't artificially bound to what HTTP offers. For example:
POST /hide/article/1/
POST /show/article/1/
(Or whatever, it's hard to think of examples until they happen!)
So in conclusion, there are only two advantages I can see:
synchronize("/articles/1/")
or whatever. This depends heavily on your code.However I think there are some pretty big disadvantages:
PUT
and POST
are. In English they mean similar things ("I'm going to put/post a notice on the wall.").So in conclusion I would say: unless you really want to go to the extra effort, or if your service maps really well to CRUD operations, save REST for the second version of your API.
I just came across another problem with REST: It's not easy to do more than one thing in one request or specify which parts of a compound object you want to get. This is especially important on mobile where round-trip-time can be significant and connections are unreliable. For example, suppose you are getting posts on a facebook timeline. The "pure" REST way would be something like
GET /timeline_posts // Returns a list of post IDs.
GET /timeline_posts/1/ // Returns a list of message IDs in the post.
GET /timeline_posts/2/
GET /timeline_posts/3/
GET /message/10/
GET /message/11/
....
Which is kind of ridiculous. Facebook's API is pretty great IMO, so let's see what they do:
By default, most object properties are returned when you make a query. You can choose the fields (or connections) you want returned with the "fields" query parameter. For example, this URL will only return the id, name, and picture of Ben: https://graph.facebook.com/bgolub?fields=id,name,picture
I have no idea how you'd do something like that with REST, and if you did whether it would still count as REST. I would certainly ignore anyone who tries to tell you that you shouldn't do that though (especially if the reason is "because it isn't REST")!
Here is another thing to try (I'm using Windows 10):
This is what worked for me. I have no idea why the service wasn't started in the first place and it used to work fine with my IPhone 7. Good luck.
$("input[required]").attr("oninvalid", "this.setCustomValidity('Say Somthing!')");
this work if you move to previous or next field by mouse, but by enter key, this is not work !!!
This is correct formula to find integers from i
to j
where i <= R <= j
FLOOR(min+RAND()*(max-min))
The other way around, if you have problems ADDING the lines to your panel dont forget to add the to your TABLE. By default (http://getbootstrap.com/components/#panels), it is suppose to add the line but It helped me to add the tag so now the row lines are shown.
The following example "probably" wont display the lines between rows:
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">Panel heading</div>
<!-- Table -->
<table class="table">
<tr><td> Hi 1! </td></tr>
<tr><td> Hi 2! </td></tr>
</table>
</div>
The following example WILL display the lines between rows:
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">Panel heading</div>
<!-- Table -->
<table class="table">
<thead></thead>
<tr><td> Hi 1! </td></tr>
<tr><td> Hi 2! </td></tr>
</table>
</div>
As mentioned, the difference is primarily the size of the underlying variables, which in each case get larger to allow more characters to be represented.
However, fonts, encoding and things are wickedly complicated (unnecessarily?), so a big link is needed to fill in more detail:
http://www.cs.tut.fi/~jkorpela/chars.html#ascii
Don't expect to understand it all, but if you don't want to have problems later it's worth learning as much as you can, as early as you can (or just getting someone else to sort it out for you).
Paul.
Just use something like:
var author = $('meta[name=author]').attr('content');
In adition to the other answers mentioning the Tasks view:
It is also possible to filter the Tasks that are listed to only show the TODOs that contain the text // TODO Auto-generated method stub
.
To achieve this you can click on the Filters... button in the top right of the Tasks View and define custom filters like this:
This way it's a bit easier and faster to find only some of the TODOs in the project in the Tasks View, and you don't have to search for the text in all files using the eclipse search tool (which can take quite some time).
The following query is very helpful
select * from
(select count(*) used from pg_stat_activity) q1,
(select setting::int res_for_super from pg_settings where name=$$superuser_reserved_connections$$) q2,
(select setting::int max_conn from pg_settings where name=$$max_connections$$) q3;
java.math.BigInteger has a nextProbablePrime() method. Whilst I'm guessing this is meant for cryptography you could use it for you work.
BigInteger prime = BigInteger.valueOf(0);
for (int i = 0; i < n; i++) {
prime = prime.nextProbablePrime();
}
System.out.println(prime.intValue());
<a [routerLink]="['../']" [queryParams]="{name: 'ferret'}" [fragment]="nose">Ferret Nose</a>
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
For more info - https://angular.io/guide/router#query-parameters-and-fragments
<div class = "solTitle"> <a href = "#" id = "solution0" onClick = "openSolution();">Solution0 </a></div> <br>
<div class= "solTitle"> <a href = "#" id = "solution1" onClick = "openSolution();">Solution1 </a></div> <br>
$(document).ready(function(){
$('.solTitle a').click(function(e) {
e.preventDefault();
alert('here in');
var divId = 'summary' +$(this).attr('id');
document.getElementById(divId).className = ''; /* or $('#'+divid).removeAttr('class'); */
});
});
I changed few things:
If preg_match
did not find a match, $matches
is an empty array. So you should check if preg_match
found an match before accessing $matches[0]
, for example:
function get_match($regex,$content)
{
if (preg_match($regex,$content,$matches)) {
return $matches[0];
} else {
return null;
}
}
I recently ran into the same problem, and found a workaround though it'll only be useful if you can change the html code to suit.
I used tables to achieve my padded layout, so to create the equivalent of a div with internal padding I made a table with 3 columns/3 rows and put the content in the centre row/column. The first and last columns/rows are used for the padding.
eg.
<table>
<tr>
<td width="10"> </td>
<td> </td>
<td width="10"> </td>
</tr>
<tr>
<td> </td>
<td>content goes here</td>
<td> </td>
</tr>
<tr>
<td width="10"> </td>
<td> </td>
<td width="10"> </td>
</tr>
</table>
Hope that helps.
Joe
To make it work with both text and numbers:
Exact match:
=query(D:E,"select * where D like '"&C1&"'", 0)
Convert search string to lowercase:
=query(D:E,"select * where D like lower('"&C1&"')", 0)
Convert to lowercase and contain part of the search string:
=query(D:E,"select * where D like lower('%"&C1&"%')", 0)
A1 = query/formula
yellow / A:B = result area
green / C1 = search area
blue / D:E = data area
If you get error when the input is text and not numbers; move the data and delete the (now empty) columns. Then move the data back.
From Activity Class:
Send the data using bundle arguments to the fragment and load the fragment
Fragment fragment = new myFragment();
Bundle bundle = new Bundle();
bundle.putString("pName", personName);
bundle.putString("pEmail", personEmail);
bundle.putString("pId", personId);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
fragment).commit();
From myFragment Class:
Get the arguments from the bundle and set them to xml
Bundle arguments = getArguments();
String personName = arguments.getString("pName");
String personEmail = arguments.getString("pEmail");
String personId = arguments.getString("pId");
nameTV = v.findViewById(R.id.name);
emailTV = v.findViewById(R.id.email);
idTV = v.findViewById(R.id.id);
nameTV.setText("Name: "+ personName);
emailTV.setText("Email: "+ personEmail);
idTV.setText("ID: "+ personId);
An example using jQuery is below. Hope this helps
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<title>My jQuery JSON Web Page</title>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
JSONTest = function() {
var resultDiv = $("#resultDivContainer");
$.ajax({
url: "https://example.com/api/",
type: "POST",
data: { apiKey: "23462", method: "example", ip: "208.74.35.5" },
dataType: "json",
success: function (result) {
switch (result) {
case true:
processResponse(result);
break;
default:
resultDiv.html(result);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
};
</script>
</head>
<body>
<h1>My jQuery JSON Web Page</h1>
<div id="resultDivContainer"></div>
<button type="button" onclick="JSONTest()">JSON</button>
</body>
</html>
Firebug debug process
Use the os.EOL constant instead.
var os = require("os");
function processInput ( text )
{
fs.open('H://log.txt', 'a', 666, function( e, id ) {
fs.write( id, text + os.EOL, null, 'utf8', function(){
fs.close(id, function(){
console.log('file is updated');
});
});
});
}
OK, so we have to do splitting as you already got the answer I would generalize it.
If you want to split any string by spaces, delimiter(special chars).
First, remove the leading space as they create most of the issues.
str1 = " Hello I'm your String ";
str2 = " Are you serious about this question_ boy, aren't you? ";
First remove the leading space which can be space, tab etc.
String s = str1.replaceAll("^\\s+","");//starting with whitespace one or more
Now if you want to split by space or any special char.
String[] sa = s.split("[^\\w]+");//split by any non word char
But as w contains [a-zA-Z_0-9] ,so if you want to split by underscore(_) also use
String[] sa = s.split("[!,? ._'@]+");//for str2 after removing leading space
Since Python 3.9 you can use the merge operator |
to merge two dictionaries. The dict on the right takes precedence:
new_dict = old_dict | { key: val }
For example:
new_dict = { 'a': 1, 'b': 2 } | { 'b': 42 }
print(new_dict} # {'a': 1, 'b': 42}
Note: this creates a new dictionary with the updated values.
Try this one for current selection:
Sub A_SelectAllMakeTable2()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
or equivalent of your macro (for Ctrl+Shift+End range selection):
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
I think this list should also include samples of each view engine so users can get a flavour of each without having to visit every website.
Pictures say a thousand words and markup samples are like screenshots for view engines :) So here's one from my favourite Spark View Engine
<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
<li each="var p in products">${p.Name}</li>
</ul>
<else>
<p>No products available</p>
</else>
If you have that same problem in MySql 5.7.+ :
Access denied for user 'root'@'localhost'
it's because MySql 5.7 by default allow to connect with socket, which means you just connect with sudo mysql
. If you run sql :
SELECT user,authentication_string,plugin,host FROM mysql.user;
then you will see it :
+------------------+-------------------------------------------+-----------------------+-----------+
| user | authentication_string | plugin | host |
+------------------+-------------------------------------------+-----------------------+-----------+
| root | | auth_socket | localhost |
| mysql.session | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| mysql.sys | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| debian-sys-maint | *497C3D7B50479A812B89CD12EC3EDA6C0CB686F0 | mysql_native_password | localhost |
+------------------+-------------------------------------------+-----------------------+-----------+
4 rows in set (0.00 sec)
To allow connection with root and password, then update the values in the table with command :
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Current-Root-Password';
FLUSH PRIVILEGES;
Then run the select command again and you'll see it has changed :
+------------------+-------------------------------------------+-----------------------+-----------+
| user | authentication_string | plugin | host |
+------------------+-------------------------------------------+-----------------------+-----------+
| root | *2F2377C1BC54BE827DC8A4EE051CBD57490FB8C6 | mysql_native_password | localhost |
| mysql.session | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| mysql.sys | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| debian-sys-maint | *497C3D7B50479A812B89CD12EC3EDA6C0CB686F0 | mysql_native_password | localhost |
+------------------+-------------------------------------------+-----------------------+-----------+
4 rows in set (0.00 sec)
And that's it. You can run this process after running and completing the sudo mysql_secure_installation
command.
For mariadb, use
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('manager');
to set password. More at https://mariadb.com/kb/en/set-password/
DOMContentLoaded
==window.onDomReady()
Load
==window.onLoad()
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside
$(document).ready()
will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside$(window).load(function() { ... })
will run once the entire page (images or iframes), not just the DOM, is ready.
The problem appears to be that despite listing your dependencies in the pom.xml, IntelliJ IDEA does not rebuild those dependencies when you run your project.
What worked for me is this:
Go to 'Run' -> 'Edit Configurations...', find your application, make sure the "Before launch:" section is expanded, click the green plus sign, and select "Build Project".
I have created a javascript function that looks if he has enough space on the right side. If it has he will show it on the right side, else he will display it on the left side
Tested in:
Javascript:
$(document).ready(function(){
//little fix for the poisition.
var newPos = $(".fixed-menuprofile .dropdown-submenu").offset().left - $(this).width();
$(".fixed-menuprofile .dropdown-submenu").find('ul').offset({ "left": newPos });
$(".fixed-menu .dropdown-submenu").mouseover(function() {
var submenuPos = $(this).offset().left + 325;
var windowPos = $(window).width();
var oldPos = $(this).offset().left + $(this).width();
var newPos = $(this).offset().left - $(this).width();
if( submenuPos > windowPos ){
$(this).find('ul').offset({ "left": newPos });
} else {
$(this).find('ul').offset({ "left": oldPos });
}
});
});
because I don't want to add this fix on every menu items I created a new class on it. place the fixed-menu on the ul:
<ul class="dropdown-menu fixed-menu">
I hope this works out for you.
ps. little bug in safari and chrome, first hover will place it to mutch to the left will update this post if I fixed it.
Note that when you insert into a List at a position, you are really inserting at a dynamic position within the List's current elements. See here:
package com.tutorialspoint;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// create an empty array list with an initial capacity
ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
// use add() method to add elements in the list
arrlist.add(15, 15);
arrlist.add(22, 22);
arrlist.add(30, 30);
arrlist.add(40, 40);
// adding element 25 at third position
arrlist.add(2, 25);
// let us print all the elements available in list
for (Integer number : arrlist) {
System.out.println("Number = " + number);
}
}
}
$javac com/tutorialspoint/ArrayListDemo.java
$java -Xmx128M -Xms16M com/tutorialspoint/ArrayListDemo
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 15, Size: 0 at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:661) at java.util.ArrayList.add(ArrayList.java:473) at com.tutorialspoint.ArrayListDemo.main(ArrayListDemo.java:12)
If you want to extract just a simple piece of information, you can get that using git show
with the --format=<string>
option...and ask it not to give you the diff with --no-patch
. This means you can get a printf-style output of whatever you want, which might often be a single field.
For instance, to get just the shortened hash (%h
) you could say:
$ git show --format="%h" --no-patch
4b703eb
If you're looking to save that into an environment variable in bash (a likely thing for people to want to do) you can use the $()
syntax:
$ GIT_COMMIT="$(git show --format="%h" --no-patch)"
$ echo $GIT_COMMIT
4b703eb
The full list of what you can do is in git show --help
. But here's an abbreviated list of properties that might be useful:
%H
commit hash%h
abbreviated commit hash%T
tree hash%t
abbreviated tree hash%P
parent hashes%p
abbreviated parent hashes%an
author name%ae
author email%at
author date, UNIX timestamp%aI
author date, strict ISO 8601 format%cn
committer name%ce
committer email%ct
committer date, UNIX timestamp%cI
committer date, strict ISO 8601 format%s
subject%f
sanitized subject line, suitable for a filename%gD
reflog selector, e.g., refs/stash@{1}%gd
shortened reflog selector, e.g., stash@{1}I had the same problem even use
<uses-permission android:name="android.permission.INTERNET" />
If you want connect web api using http
not https
. Maybe you use android device using Android 9 (Pie) or API level 28 or higher . android:usesCleartextTraffic
default value is false
. You have to set be
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true" <!-- this line -->
...>
...
</application>
</manifest>
Finally, should be https
https://developer.android.com/guide/topics/manifest/application-element#usesCleartextTraffic
This got it working for me:
:set tabstop=2 shiftwidth=2 expandtab | retab
Try bellow code. This is help your code.
$("#btnUpdate").on("click", function () {
//alert("Alert Test");
var url = 'http://cooktv.sndimg.com/webcook/sandbox/perf/topics.json';
$.ajax({
type: "GET",
url: url,
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
debugger;
$.each(result.callback, function (index, value) {
alert(index + ': ' + value.Name);
});
},
failure: function (result) { alert('Fail'); }
});
});
I could not access your url. Bellow error is shows
XMLHttpRequest cannot load http://cooktv.sndimg.com/webcook/sandbox/perf/topics.json. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:19829' is therefore not allowed access. The response had HTTP status code 501.
Without jQuery:
textContent:
var text = document.querySelector('.someClassname').textContent;
Markup:
var text = document.querySelector('.someClassname').innerHTML;
Markup including the matched element:
var text = document.querySelector('.someClassname').outerHTML;
though outerHTML may not be supported by all browsers of interest and document.querySelector requires IE 8 or higher.
Short answer: I think tgbaggio is right. You hit HDFS throughput limits on your executors.
I think the answer here may be a little simpler than some of the recommendations here.
The clue for me is in the cluster network graph. For run 1 the utilization is steady at ~50 M bytes/s. For run 3 the steady utilization is doubled, around 100 M bytes/s.
From the cloudera blog post shared by DzOrd, you can see this important quote:
I’ve noticed that the HDFS client has trouble with tons of concurrent threads. A rough guess is that at most five tasks per executor can achieve full write throughput, so it’s good to keep the number of cores per executor below that number.
So, let's do a few calculations see what performance we expect if that is true.
If the job is 100% limited by concurrency (the number of threads). We would expect runtime to be perfectly inversely correlated with the number of threads.
ratio_num_threads = nthread_job1 / nthread_job3 = 15/24 = 0.625
inv_ratio_runtime = 1/(duration_job1 / duration_job3) = 1/(50/31) = 31/50 = 0.62
So ratio_num_threads ~= inv_ratio_runtime
, and it looks like we are network limited.
This same effect explains the difference between Run 1 and Run 2.
Comparing the number of effective threads and the runtime:
ratio_num_threads = nthread_job2 / nthread_job1 = 12/15 = 0.8
inv_ratio_runtime = 1/(duration_job2 / duration_job1) = 1/(55/50) = 50/55 = 0.91
It's not as perfect as the last comparison, but we still see a similar drop in performance when we lose threads.
Now for the last bit: why is it the case that we get better performance with more threads, esp. more threads than the number of CPUs?
A good explanation of the difference between parallelism (what we get by dividing up data onto multiple CPUs) and concurrency (what we get when we use multiple threads to do work on a single CPU) is provided in this great post by Rob Pike: Concurrency is not parallelism.
The short explanation is that if a Spark job is interacting with a file system or network the CPU spends a lot of time waiting on communication with those interfaces and not spending a lot of time actually "doing work". By giving those CPUs more than 1 task to work on at a time, they are spending less time waiting and more time working, and you see better performance.
In JavaScript multiple ways are there, below are some of them
Method 1:
throw new Error("Something went badly wrong!");
Method 2:
return;
Method 3:
return false;
Method 4:
new new
Method 5:
write your custom function use above method and call where you needed
Note: If you want to just pause the code execution you can use
debugger;
Don't loop through a file this way. Instead use a for
loop.
for line in f:
vowel += sum(ch.isvowel() for ch in line)
In fact your whole program is just:
VOWELS = {'A','E','I','O','U','a','e','i','o','u'}
# I'm assuming this is what isvowel checks, unless you're doing something
# fancy to check if 'y' is a vowel
with open('filename.txt') as f:
vowel = sum(ch in VOWELS for line in f for ch in line.strip())
That said, if you really want to keep using a while
loop for some misguided reason:
while True:
line = f.readline().strip()
if line == '':
# either end of file or just a blank line.....
# we'll assume EOF, because we don't have a choice with the while loop!
break
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
<button type="button">
to override default submission behaviorevent.preventDefault()
in the onSubmit event to prevent form submissionInsert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
.serialize()
to serialize your form, but remember to add name
attributes to your input:The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
Extend the string prototype to use throughout your project
String.prototype.alphaNumeric = function() {
return this.replace(/[^a-z0-9]/gi,'');
}
Usage:
"I don't know what to say?".alphaNumeric();
//Idontknowwhattosay
ReduceByKey reduceByKey(func, [numTasks])
-
Data is combined so that at each partition there should be at least one value for each key. And then shuffle happens and it is sent over the network to some particular executor for some action such as reduce.
GroupByKey - groupByKey([numTasks])
It doesn't merge the values for the key but directly the shuffle process happens and here lot of data gets sent to each partition, almost same as the initial data.
And the merging of values for each key is done after the shuffle. Here lot of data stored on final worker node so resulting in out of memory issue.
AggregateByKey - aggregateByKey(zeroValue)(seqOp, combOp, [numTasks])
It is similar to reduceByKey but you can provide initial values when performing aggregation.
Use of reduceByKey
reduceByKey
can be used when we run on large data set.
reduceByKey
when the input and output value types are of same type
over aggregateByKey
Moreover it recommended not to use groupByKey
and prefer reduceByKey
. For details you can refer here.
You can also refer this question to understand in more detail how reduceByKey
and aggregateByKey
.
To retrieve text of an auto generated span value just do this :
var al = $("#id-span-name").text();
alert(al);
Unlike maths-on-paper
notation, most programming languages (Java included) need a *
sign to do multiplication. Your distance calculation should therefore read:
distance = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
Or alternatively:
distance = Math.sqrt(Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2));
I encountered this error, and the fix appears to be turning off SNI, which Python 2.7 does not support:
If you call your created method in the lifecycle methods like componentDidMount... then you can only use the this.onToggleLoop = this.onToogleLoop.bind(this)
and the fat arrow function onToggleLoop = (event) => {...}
.
The normal approach of the declaration of a function in the constructor wont work because the lifecycle methods are called earlier.
You can use below command to see who have changed what in a file.
git blame <filename>
I found the simpler solution, similar to Dale Ragan's, but slightly modified. It does practically everything you need and based on the standard Microsoft WindowsFormsApplicationBase class.
Firstly, you create SingleInstanceController class, which you can use in all other single-instance applications, which use Windows Forms:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;
namespace SingleInstanceController_NET
{
public class SingleInstanceController
: WindowsFormsApplicationBase
{
public delegate Form CreateMainForm();
public delegate void StartNextInstanceDelegate(Form mainWindow);
CreateMainForm formCreation;
StartNextInstanceDelegate onStartNextInstance;
public SingleInstanceController(CreateMainForm formCreation, StartNextInstanceDelegate onStartNextInstance)
{
// Set whether the application is single instance
this.formCreation = formCreation;
this.onStartNextInstance = onStartNextInstance;
this.IsSingleInstance = true;
this.StartupNextInstance += new StartupNextInstanceEventHandler(this_StartupNextInstance);
}
void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e)
{
if (onStartNextInstance != null)
{
onStartNextInstance(this.MainForm); // This code will be executed when the user tries to start the running program again,
// for example, by clicking on the exe file.
} // This code can determine how to re-activate the existing main window of the running application.
}
protected override void OnCreateMainForm()
{
// Instantiate your main application form
this.MainForm = formCreation();
}
public void Run()
{
string[] commandLine = new string[0];
base.Run(commandLine);
}
}
}
Then you can use it in your program as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using SingleInstanceController_NET;
namespace SingleInstance
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static Form CreateForm()
{
return new Form1(); // Form1 is used for the main window.
}
static void OnStartNextInstance(Form mainWindow) // When the user tries to restart the application again,
// the main window is activated again.
{
mainWindow.WindowState = FormWindowState.Maximized;
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SingleInstanceController controller = new SingleInstanceController(CreateForm, OnStartNextInstance);
controller.Run();
}
}
}
Both the program and the SingleInstanceController_NET solution should reference Microsoft.VisualBasic . If you just want to reactivate the running application as a normal window when the user tries to restart the running program, the second parameter in the SingleInstanceController can be null. In the given example, the window is maximized.
You can always set the options, based on this page you can set, to get rid of the seconds, something like this
var dateWithouthSecond = new Date();
dateWithouthSecond.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
Supported by Firefox, Chrome, IE9+ and Opera. Try it on your web browser console.
Checked the evironment path, I have two paths navigated to two pip.exe and this caused this error. After deleting the redundant one and restart the PC, this issue has been fixed. The same issue for the jupyter command fixed as well.
The result of Modulo operation depends on the sign of numerator, and thus you're getting -2 for y and z
Here's the reference
http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_14.html
Integer Division
This section describes functions for performing integer division. These functions are redundant in the GNU C library, since in GNU C the '/' operator always rounds towards zero. But in other C implementations, '/' may round differently with negative arguments. div and ldiv are useful because they specify how to round the quotient: towards zero. The remainder has the same sign as the numerator.
Depending on the encoding you wish to use:
var str = System.Text.Encoding.Default.GetString(result);
With TypeScript generics you can do something like this.
class Person {
constructor (public Name : string, public Age: number) {}
}
var list = new Array<Person>();
list.push(new Person("Baby", 1));
list.push(new Person("Toddler", 2));
list.push(new Person("Teen", 14));
list.push(new Person("Adult", 25));
var oldest_person = list.reduce( (a, b) => a.Age > b.Age ? a : b );
alert(oldest_person.Name);
@ECHO off set "dir1=C:\TicketDownload"
FOR %%X in ("%dir1%*.pdf") DO ( "C:\Program Files (x86)\Adobe\Reader 9.0\Reader\AcroRd32.exe" /t "%%~dpnX.pdf" "Microsoft XPS Document Writer" )
FOR %%X in ("%dir1%*.pdf") DO (move "%%~dpnX.pdf" p/)
Try this..May be u have some other version of Reader so that is the problem..
<html>
tag in Elements.<!DOCTYPE html>
before the <html>
.As of this writing, it was necessary to:
I am using Debian 8 live off a USB. I was locked out of the system after 10 min of inactivity. The password that was required to log back in to the system for the user was:
login : Debian Live User
password : live
I hope this helps
It skips to the start of the next page. (Applies mostly to terminals where the output device is a printer rather than a VDU.)
With keys as tuples, you just filter the keys with given second component and sort it:
blue_fruit = sorted([k for k in data.keys() if k[1] == 'blue'])
for k in blue_fruit:
print k[0], data[k] # prints 'banana 24', etc
Sorting works because tuples have natural ordering if their components have natural ordering.
With keys as rather full-fledged objects, you just filter by k.color == 'blue'
.
You can't really use dicts as keys, but you can create a simplest class like class Foo(object): pass
and add any attributes to it on the fly:
k = Foo()
k.color = 'blue'
These instances can serve as dict keys, but beware their mutability!
EventArgs e
is a parameter called e that contains the event data, see the EventArgs MSDN page for more information.
Object Sender
is a parameter called Sender that contains a reference to the control/object that raised the event.
Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx
Example:
protected void btn_Click (object sender, EventArgs e){
Button btn = sender as Button;
btn.Text = "clicked!";
}
Edit: When Button is clicked, the btn_Click event handler will be fired. The "object sender" portion will be a reference to the button which was clicked
The reasonable way how to launch apps from HTML is through url schemes. So you can launch email via mailto:
links and irc through irc:
links. Individual apps can implement these schemes, but I'm not sure WinMerge does this.
ThomasH has already added a good answer, but I want to show what happens:
>>> a = [[1, 2], [3, 4]]
>>> [x for x in b for b in a]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>> [x for b in a for x in b]
[1, 2, 3, 4]
>>> [x for x in b for b in a]
[3, 3, 4, 4]
I guess Python parses the list comprehension from left to right. This means, the first for
loop that occurs will be executed first.
The second "problem" of this is that b
gets "leaked" out of the list comprehension. After the first successful list comprehension b == [3, 4]
.
Open the project's properties---> Java Build Path ---> Libraries tab ---> Add External Jars
will allow you to add jars.
You need to download commonsIO from here.
the answers above doesn't work in my case. You need to specify utf-8 in meta tag
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<!-- you content goes here -->
</body>
</html>
From yanl (yet-another-library) sklearn.metrics
has an r2_score
function;
from sklearn.metrics import r2_score
coefficient_of_dermination = r2_score(y, p(x))
One other scenario which I encountered.
String imageName ="Hello" and then when it is passed into getIdentifier function as first argument, it will pass the name with string null termination and will always return zero. Pass this imageName.substring(0, imageName.length()-1)
Applying the text-align:center
style to an element containing elements will center those elements.
<div id="method-one" style="text-align:center">
CSS `text-align:center`
</div>
Thomas Shields mentions this method
Applying the margin:0 auto
style to a block element will center it within the element it is in.
<div id="method-two" style="background-color:green">
<div style="margin:0 auto;width:50%;background-color:lightblue">
CSS `margin:0 auto` to have left and right margin set to center a block element within another element.
</div>
</div>
user1468562 mentions this method
My original answer was that you can use the <center></center>
tag. To do this, just place the content you want centered between the tags. As of HTML4, this tag has been deprecated, though. <center>
is still technically supported today (9 years later at the time of updating this), but I'd recommend the CSS alternatives I've included above.
<h3>Method 3</h1>
<div id="method-three">
<center>Center tag (not recommended and deprecated in HTML4)</center>
</div>
You can see these three code samples in action in this jsfiddle.
I decided I should revise this answer as the previous one I gave was outdated. It was already deprecated when I suggested it as a solution and that's all the more reason to avoid it now 9 years later.
name = "John" // your variable
result = (name+" ")[:15] # this adds 15 spaces to the "name"
# but cuts it at 15 characters
If you write software, or use software written, which stores program window coordinates or sizes to be resused when starting a program, check there for any occurrence(s) of such sizes and positions which would be causing this. I've seen it time and time again from various vendors lazily producing code which resizes and repositions controls on a "form" (a program window) based on the size of said form. Look in HKLM\Software\Vendor\Program and HKCU\Software\Vendor\Program. Look for specific keys which might be offending. I once had a program store -48000 for the program window position in keys called WindowsPosX and WindowPosY. You could see the program start and running on the taskbar but since the program window itself was smaller than 48000 (the absolute value of -48000), it was positioned completely off the screen. If you're not comfortable with editing regstry information - most people aren't - then uninstall the software, use a registry cleaner to remove any leftover entries then reinstall the software and see if that doesn't fix the problem.
Take a look at http://dev.mysql.com/doc/refman/5.0/en/declare-handler.html
Basically you declare error handler which will call rollback
START TRANSACTION;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
EXIT PROCEDURE;
END;
COMMIT;
Another one answer with some tips, can be helpful for somebody:
remember to separate your commands with the following rule:
command1 && command2 - means, that command2 will be executed, only if command1 success
command1 ; command2 - means, that command 2 will be executed despite on result of command1
for example:
String run_tests = sh(script: "set +e && cd ~/development/tests/ && gmake test ;set -e;echo 0 ", returnStdout: true).trim()
println run_tests
will be executed successfully with set -e
and echo 0
commands if gmake test
failed (your tests failed), while the following code snipped:
String run_tests = sh(script: "set +e && cd ~/development/tests/ && gmake test && set -e && echo 0 ", returnStdout: true).trim()
println run_tests
a bit wrong and commands set -e
and echo 0
in&& gmake test && set -e && echo 0
will be skipped, with the println run_tests
statement, because failed gmake test
will abort the jenkins build. As workaround you can switch to returnStatus:true
, but then you will miss the output from your command.
As the other answer correctly notes, you cannot use dynamic functions as a default value. You could use TIMESTAMP
with the CURRENT_TIMESTAMP
attribute, but this is not always possible, for example if you want to keep both a creation and updated timestamp, and you'd need the only allowed TIMESTAMP
column for the second.
In this case, use a trigger instead.
Check out std::stringstream
.
XDocument
is from the LINQ to XML API, and XmlDocument
is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument
. If you're new to both, check out this page that compares the two, and pick which one you like the looks of better.
I've just started using LINQ to XML, and I love the way you create an XML document using functional construction. It's really nice. DOM is clunky in comparison.
In addition to the above I personally recommend
onKeyUp():
Programatically Speaking keydown will fire when the user depresses a key initially but It will repeat while the user keeps the key depressed.*
This remains true for all development platforms.
Google development suggested that if you are intercepting the BACK button in a view you should track the KeyEvent with starttracking on keydown then invoke with keyup.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
event.startTracking();
return true;
}
return super.onKeyDown(keyCode, event);
}
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
&& !event.isCanceled()) {
// *** Your Code ***
return true;
}
return super.onKeyUp(keyCode, event);
}
This should work.
$foo = someFunction 2>$null
I am adding this answer in case someone else would like to store the host entry set in a txt file formatted like the normal host file. This looks for a TAB delimiter. This is based off of the answers from @Rashy and @that0n3guy. The differences can be noticed around the FOR command.
@echo off
TITLE Modifying your HOSTS file
ECHO.
:: BatchGotAdmin
:-------------------------------------
REM --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
echo Requesting administrative privileges...
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"="
echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------
:LOOP
SET Choice=
SET /P Choice="Do you want to modify HOSTS file ? (Y/N)"
IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%
ECHO.
IF /I '%Choice%'=='Y' GOTO ACCEPTED
IF /I '%Choice%'=='N' GOTO REJECTED
ECHO Please type Y (for Yes) or N (for No) to proceed!
ECHO.
GOTO Loop
:REJECTED
ECHO Your HOSTS file was left unchanged.
ECHO Finished.
GOTO END
:ACCEPTED
setlocal enabledelayedexpansion
::Create your list of host domains
for /F "tokens=1,2 delims= " %%A in (%WINDIR%\System32\drivers\etc\storedhosts.txt) do (
SET _host=%%B
SET _ip=%%A
SET NEWLINE=^& echo.
ECHO Adding !_ip! !_host!
REM REM ::strip out this specific line and store in tmp file
type %WINDIR%\System32\drivers\etc\hosts | findstr /v !_host! > tmp.txt
REM REM ::re-add the line to it
ECHO %NEWLINE%^!_ip! !_host! >> tmp.txt
REM ::overwrite host file
copy /b/v/y tmp.txt %WINDIR%\System32\drivers\etc\hosts
del tmp.txt
)
ipconfig /flushdns
ECHO.
ECHO.
ECHO Finished, you may close this window now.
GOTO END
:END
ECHO.
PAUSE
EXIT
Example "storedhosts.txt" (tab delimited)
127.0.0.1 mysite.com
168.1.64.2 yoursite.com
192.1.0.1 internalsite.com
your code compiles here fine (even with that line uncommented. had to change it to
num3 = 100000000000000000000;
to start getting the warning.
This is the batch script I wrote for renaming a database on Windows:
@echo off
set olddb=olddbname
set newdb=newdbname
SET count=1
SET act=mysql -uroot -e "select table_name from information_schema.tables where table_schema='%olddb%'"
mysql -uroot -e "create database %newdb%"
echo %act%
FOR /f "tokens=*" %%G IN ('%act%') DO (
REM echo %count%:%%G
echo mysql -uroot -e "RENAME TABLE %olddb%.%%G to %newdb%.%%G"
mysql -uroot -e "RENAME TABLE %olddb%.%%G to %newdb%.%%G"
set /a count+=1
)
mysql -uroot -e "drop database %olddb%"
try this ^^
$(document).ready(function() {
$("form").bind("keypress", function(e) {
if (e.keyCode == 13) {
return false;
}
});
});
Hope this helps
This is a dual problem (as many in the world wide web world).
You need to evaluate if the browser supports html5 (I use Modernizr to do it). In this case if you have a normal form the browser will do the job for you, but if you need ajax/json (as many of everyday case) you need to perform manual verification anyway.
.. so, my suggestion is to use a regular expression to evaluate anytime before submit. The expression I use is the following:
var email = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/;
This one is taken from http://www.regular-expressions.info/ . This is a hard world to understand and master, so I suggest you to read this page carefully.
Assign the response to a value and test the attributes of it. These should tell you something useful.
response = requests.post(url,params=data,headers=headers)
response.status_code
response.text
<div id="app">
<a :href="path" />Link</a>
</div>
<script>
new Vue({
el: '#app',
data: {
path: 'https://www.google.com/'
}
});
</script> enter code here
Add your test.js file after the jQuery libraries. This way your test.js file can use the libraries.
In Java create the pattern with Pattern p = Pattern.compile("^\\w{14}$");
for further information see the javadoc
Another way to get Monday with integer value 1 and Sunday with integer value 7
int day = ((int)DateTime.Now.DayOfWeek + 6) % 7 + 1;
Some time this happens when your Java folder get updated.
Open Eclipse folder and search file eclipse.ini. Open the eclipse.ini file and check whether jre version is same as jre available in your java folder.
I faced same problem when my jre got changed from jre1.8.0_101 to jre1.8.0_111.
C:\Program Files\Java\jre1.8.0_101\bin to C:\Program Files\Java\jre1.8.0_111\bin
You can do this without any code behind by using a IValueConverter
.
<Grid>
<ComboBox
x:Name="comboBox1"
ItemsSource="{Binding MyItemSource}" />
<TextBlock
Visibility="{Binding SelectedItem, ElementName=comboBox1, Converter={StaticResource NullToVisibilityConverter}}"
IsHitTestVisible="False"
Text="... Select Team ..." />
</Grid>
Here you have the converter class that you can re-use.
public class NullToVisibilityConverter : IValueConverter
{
#region Implementation of IValueConverter
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
And finally, you need to declare your converter in a resource section.
<Converters:NullToVisibilityConverter x:Key="NullToVisibilityConverter" />
Where Converters is the place you have placed the converter class. An example is:
xmlns:Converters="clr-namespace:MyProject.Resources.Converters"
The very nice thing about this approach is no repetition of code in your code behind.
The reason you shouldn't use new Array
is demonstrated by this code:
var Array = function () {};
var x = new Array(4);
alert(x.length); // undefined...
Some other code could mess with the Array variable. I know it's a bit far fetched that anyone would write such code, but still...
Also, as Felix King said, the interface is a little inconsistent, and could lead to some very difficult-to-track-down bugs.
If you wanted an array with length = x, filled with undefined (as new Array(x)
would do), you could do this:
var x = 4;
var myArray = [];
myArray[x - 1] = undefined;
alert(myArray.length); // 4
IndexOf seems to be useful here.
@foreach (myItemClass ts in Model.ItemList.Where(x => x.Type == "something"))
{
int currentIndex = Model.ItemList.IndexOf(ts);
@Html.HiddenFor(x=>Model.ItemList[currentIndex].Type)
...
If you are working with heavy queries, you better move the request for the latest row in the where clause. It is a lot faster and looks cleaner.
SELECT c.*,
FROM client AS c
LEFT JOIN client_calling_history AS cch ON cch.client_id = c.client_id
WHERE
cch.cchid = (
SELECT MAX(cchid)
FROM client_calling_history
WHERE client_id = c.client_id AND cal_event_id = c.cal_event_id
)
I use this statement in Django to convert an unaware time to an aware:
from django.utils import timezone
dt_aware = timezone.make_aware(dt_unaware, timezone.get_current_timezone())
vector<string> getseq(char * db_file)
And if you want to print it on main() you should do it in a loop.
int main() {
vector<string> str_vec = getseq(argv[1]);
for(vector<string>::iterator it = str_vec.begin(); it != str_vec.end(); it++) {
cout << *it << endl;
}
}
std::string some_str = SOME_VAL;
if ( some_str.size() > 0 && some_str[some_str.length()-1] == '\n' )
some_str.resize( some_str.length()-1 );
or (removes several newlines at the end)
some_str.resize( some_str.find_last_not_of(L"\n")+1 );
I have done it by the following way
Like the following image. See for more information.
Used zoom-master/jquery.zoom.js. The zoom for the image worked perfectly. Here is a link to the page. http://www.jacklmoore.com/zoom/
<script>
$(document).ready(function(){
$('#ex1').zoom();
});
</script>
If your problem is like the following while using Google Chrome:
[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]
Then create a batch file by following these steps:
Open notepad in Desktop.
start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit
This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.
Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.
Supplemental answer
I was originally having trouble getting a reference to the ViewPager
from other class methods because the addOnTabSelectedListener
made an anonymous inner class, which in turn required the ViewPager
variable to be declared final
. The solution was to use a class member variable and not use the anonymous inner class.
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
// don't use an anonymous inner class here
tabLayout.addOnTabSelectedListener(tabListener);
}
TabLayout.OnTabSelectedListener tabListener = new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
// The view pager can now be accessed here, too.
public void someMethod() {
viewPager.setCurrentItem(0);
}
}
you can do it by two ways
import file_name
exec(open('file_name').read())
but make sure that file should be stored where your program is running
Django's Model
class specifically handles having an attribute named Meta
which is a class. It's not a general Python thing.
Python metaclasses are completely different.
Easiest way is probably using command status; In the output you'll find database, user, host and port:
mysql> status;
--------------
mysql Ver 8.0.13 for Win64 on x86_64 (MySQL Community Server - GPL)
Connection id: 43
Current database: mysql
Current user: user@localhost
SSL: Cipher in use is DHE-RSA-AES128-GCM-SHA256
Using delimiter: ;
Server version: 8.0.13 MySQL Community Server - GPL
Protocol version: 10
Connection: localhost via TCP/IP
Server characterset: utf8mb4
Db characterset: utf8mb4
Client characterset: cp852
Conn. characterset: cp852
TCP port: 3306
Uptime: 3 hours 32 min 40 sec
Threads: 3 Questions: 197 Slow queries: 0 Opens: 214 Flush tables: 2 Open tables: 190 Queries per second avg: 0.015
--------------
To export the output to file on a continuous basis (here every five seconds) and save to a CSV file with the Unix date as the filename:
while ($true) {
[int]$date = get-date -Uformat %s
$exportlocation = New-Item -type file -path "c:\$date.csv"
Get-Counter -Counter "\Processor(_Total)\% Processor Time" | % {$_} | Out-File $exportlocation
start-sleep -s 5
}
According to @Data description you can use:
All generated getters and setters will be public. To override the access level, annotate the field or class with an explicit @Setter and/or @Getter annotation. You can also use this annotation (by combining it with AccessLevel.NONE) to suppress generating a getter and/or setter altogether.
If you add this to your meta tags:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
IE8 will render the page like IE7.
I compiled python3.7 from the source code, with the following command
./configure --prefix=/opt/python3.7.4 --with-ssl
make
make install
after pip3.7 install jupyter
I found the executable is under /opt/python3.7.4/bin
check my answer here Missing sqlite3 after Python3 compile to get more detail comping python3.7 and pip under ubuntu14.04
The issue occurred in my case because spring framework couldn't fetch the properties of nested objects. Getters/Setters is one way of solving. Making the properties public is another quick and dirty solution to validate if this is indeed the problem.
The simplest way to extract a number from a string is to use regular expressions and findall
.
>>> import re
>>> s = '300 gm'
>>> re.findall('\d+', s)
['300']
>>> s = '300 gm 200 kgm some more stuff a number: 439843'
>>> re.findall('\d+', s)
['300', '200', '439843']
It might be that you need something more complex, but this is a good first step.
Note that you'll still have to call int
on the result to get a proper numeric type (rather than another string):
>>> map(int, re.findall('\d+', s))
[300, 200, 439843]
if(new File("/sdcard/your_filename.txt").exists())){
// Your code goes here...
}
<body onload="window.print()">
or
window.onload = function() { window.print(); }
wget is capable of doing what you are asking. Just try the following:
wget -p -k http://www.example.com/
The -p
will get you all the required elements to view the site correctly (css, images, etc).
The -k
will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.
From the Wget docs:
‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.
Each link will be changed in one of the two ways:
The links to files that have been downloaded by Wget will be changed to refer
to the file they point to as a relative link.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
downloaded, then the link in doc.html will be modified to point to
‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
combinations of directories.
The links to files that have not been downloaded by Wget will be changed to
include host name and absolute path of the location they point to.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
../bar/img.gif), then the link in doc.html will be modified to point to
http://hostname/bar/img.gif.
Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.
Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads.
This is what I use to get the minimum date in SQL Server. Please note that it is globalisation friendly:
CREATE FUNCTION [dbo].[DateTimeMinValue]()
RETURNS datetime
AS
BEGIN
RETURN (SELECT
CAST('17530101' AS datetime))
END
Call using:
SELECT [dbo].[DateTimeMinValue]()
I had the same issue, after accepting the license launching XCode or running sudo xcodebuild -license accept
i had to restart my Mac – otherwise it did not worked.
I am using texmaker as the editor. you have to compile it in terminal as following:
but sometimes, when you use \citep{}
, the names of the references don't show up. In this case, I had to open the references.bib
file , so that texmaker could capture the references from the references.bib file. After every edition of the bib file, I had to close and reopen it!! So that texmaker could capture the content of new .bbl file each time. But remember, you have to also run your code in texmaker too.
Something you can try is using the bind method, I think this achieves what you were asking for. If nothing else, it's still very useful.
function doClick(elem, func) {
var diffElem = document.getElementById('some_element'); //could be the same or different element than the element in the doClick argument
diffElem.addEventListener('click', func.bind(diffElem, elem))
}
function clickEvent(elem, evt) {
console.log(this);
console.log(elem);
// 'this' and elem can be the same thing if the first parameter
// of the bind method is the element the event is being attached to from the argument passed to doClick
console.log(evt);
}
var elem = document.getElementById('elem_to_do_stuff_with');
doClick(elem, clickEvent);
it depends on your php settings...
use phpinfo()
and take a look at the session chapter. There are values like session.gc_maxlifetime
and session.cache_expire
and session.cookie_lifetime
which affects the sessions lifetime
EDIT: it's like Martin write before
It's as simple as this:
unsigned int foo;
int bar = 10;
foo = (unsigned int)bar;
Or vice versa...
"PHP message: PHP Warning: Unknown: Input variables exceeded 1000. To increase the limit change max_input_vars in php.ini.
This php configuration parameter max_input_vars will affect not only your GET / POST / COOKIES parameters it also controls your any Form Input.
To set or change its value follow the below steps.
1) check the existing setting / value by viewing it in your php.ini file Locate php.ini file by using
<?php echo getinfo(); ?>
find below key: Loaded Configuration File : /etc/php/5.6/fpm/php.ini
2) Open the php.ini file in editable mode and do search for max_input_vars This line may be commented in your existing default setting with default value of 1000 , So remove ; to uncomment it and Edit it with your suitable value e.g. 2500.
3) Save the file and Restart the Services of PHP by using below
sudo service php5.6-fpm restart
Similarly you can update any other similar PHP Configuration to your ease.
select t1.id, t1.SomeNumt, SUM(t2.SomeNumt) as sum
from @t t1
inner join @t t2 on t1.id >= t2.id
group by t1.id, t1.SomeNumt
order by t1.id
Output
| ID | SOMENUMT | SUM |
-----------------------
| 1 | 10 | 10 |
| 2 | 12 | 22 |
| 3 | 3 | 25 |
| 4 | 15 | 40 |
| 5 | 23 | 63 |
Edit: this is a generalized solution that will work across most db platforms. When there is a better solution available for your specific platform (e.g., gareth's), use it!
An ioctl
, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.
An alternative is the sysfs
interface, where you set up a file under /sys/
and read/write that to get information from and to the driver. An example of how to set this up:
static ssize_t mydrvr_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", DRIVER_RELEASE);
}
static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);
And during driver setup:
device_create_file(dev, &dev_attr_version);
You would then have a file for your device in /sys/
, for example, /sys/block/myblk/version
for a block driver.
Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl
or libnl3
libraries.
try this... obviously you need to set each div to 25%. You then will need to add your content as needed :) Hope that helps.
<html>
<head>
<title>CSS devide window by 25% horizontally</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<style type="text/css" media="screen">
body {
margin:0;
padding:0;
height:100%;
}
#top_div
{
height:25%;
width:100%;
background-color:#009900;
margin:auto;
text-align:center;
}
#mid1_div
{
height:25%;
width:100%;
background-color:#990000;
margin:auto;
text-align:center;
color:#FFFFFF;
}
#mid2_div
{
height:25%;
width:100%;
background-color:#000000;
margin:auto;
text-align:center;
color:#FFFFFF;
}
#bottom_div
{
height:25%;
width:100%;
background-color:#990000;
margin:auto;
text-align:center;
color:#FFFFFF;
}
</style>
</head>
<body>
<div id="top_div">Top- height is 25% of window height</div>
<div id="mid1_div">Middle 1 - height is 25% of window height</div>
<div id="mid2_div">Middle 2 - height is 25% of window height</div>
<div id="bottom_div">Bottom - height is 25% of window height</div>
</body>
</html>
Tested and works fine, copy the code above into a HTML file, and open with your browser.
This script generates insert statements of your existing data. This is a stored procedure which you need to run once and then it is tailor made for you.
I tried to find this kind of stuff for a while but wasn't satisfied with the results, so I wrote this stored procedure.
Example:
Exec [dbo].[INS] 'Dbo.test where 1=1'
(1) Here dbo
is schema and test is tablename and 1=1
is condition.
Exec [dbo].[INS] 'Dbo.test where name =''neeraj''' * for string
(2) Here dbo
is schema and test is tablename and name='neeraj'
is condition.
Here is the stored procedure
/*
Authore : neeraj prasad sharma (please dont remove this :))
Example (1) Exec [dbo].[INS] 'Dbo.test where 1=1'
(2) Exec [dbo].[INS] 'Dbo.test where name =''neeraj''' * for string
here Dbo is schema and test is tablename and 1=1 is condition
*/
CREATE procedure [dbo].[INS]
(
@Query Varchar(MAX)
)
AS
SET nocount ON
DECLARE @WithStrINdex as INT
DECLARE @WhereStrINdex as INT
DECLARE @INDExtouse as INT
DECLARE @SchemaAndTAble VArchar(270)
DECLARE @Schema_name varchar(30)
DECLARE @Table_name varchar(240)
DECLARE @Condition Varchar(MAX)
SET @WithStrINdex=0
SELECT @WithStrINdex=CHARINDEX('With',@Query )
, @WhereStrINdex=CHARINDEX('WHERE', @Query)
IF(@WithStrINdex!=0)
SELECT @INDExtouse=@WithStrINdex
ELSE
SELECT @INDExtouse=@WhereStrINdex
SELECT @SchemaAndTAble=Left (@Query,@INDExtouse-1)
SELECT @SchemaAndTAble=Ltrim (Rtrim( @SchemaAndTAble))
SELECT @Schema_name= Left (@SchemaAndTAble, CharIndex('.',@SchemaAndTAble )-1)
, @Table_name = SUBSTRING( @SchemaAndTAble , CharIndex('.',@SchemaAndTAble )+1,LEN(@SchemaAndTAble) )
, @CONDITION=SUBSTRING(@Query,@WhereStrINdex+6,LEN(@Query))--27+6
DECLARE @COLUMNS table (Row_number SmallINT , Column_Name VArchar(Max) )
DECLARE @CONDITIONS as varchar(MAX)
DECLARE @Total_Rows as SmallINT
DECLARE @Counter as SmallINT
DECLARE @ComaCol as varchar(max)
SELECT @ComaCol=''
SET @Counter=1
SET @CONDITIONS=''
INSERT INTO @COLUMNS
SELECT Row_number()Over (Order by ORDINAL_POSITION ) [Count], Column_Name
FROM INformation_schema.columns
WHERE Table_schema=@Schema_name AND table_name=@Table_name
SELECT @Total_Rows= Count(1)
FROM @COLUMNS
SELECT @Table_name= '['+@Table_name+']'
SELECT @Schema_name='['+@Schema_name+']'
While (@Counter<=@Total_Rows )
begin
--PRINT @Counter
SELECT @ComaCol= @ComaCol+'['+Column_Name+'],'
FROM @COLUMNS
WHERE [Row_number]=@Counter
SELECT @CONDITIONS=@CONDITIONS+ ' + Case When ['+Column_Name+'] is null then ''Null'' Else '''''''' + Replace( Convert(varchar(Max),['+Column_Name+'] ) ,'''''''','''' ) +'''''''' end+'+''','''
FROM @COLUMNS
WHERE [Row_number]=@Counter
SET @Counter=@Counter+1
End
SELECT @CONDITIONS=Right(@CONDITIONS,LEN(@CONDITIONS)-2)
SELECT @CONDITIONS=LEFT(@CONDITIONS,LEN(@CONDITIONS)-4)
SELECT @ComaCol= substring (@ComaCol,0, len(@ComaCol) )
SELECT @CONDITIONS= '''INSERT INTO '+@Schema_name+'.'+@Table_name+ '('+@ComaCol+')' +' Values( '+'''' + '+'+@CONDITIONS
SELECT @CONDITIONS=@CONDITIONS+'+'+ ''')'''
SELECT @CONDITIONS= 'Select '+@CONDITIONS +'FRom ' +@Schema_name+'.'+@Table_name+' With(NOLOCK) ' + ' Where '+@Condition
print(@CONDITIONS)
Exec(@CONDITIONS)
You can use == to compare with a zero value composite literal because all fields are comparable:
if (Session{}) == session {
fmt.Println("is zero value")
}
Because of a parsing ambiguity, parentheses are required around the composite literal in the if condition.
The use of ==
above applies to structs where all fields are comparable. If the struct contains a non-comparable field (slice, map or function), then the fields must be compared one by one to their zero values.
An alternative to comparing the entire value is to compare a field that must be set to a non-zero value in a valid session. For example, if the player id must be != "" in a valid session, use
if session.playerId == "" {
fmt.Println("is zero value")
}
You can use this class:
using System.Collections.Specialized;
class Post_File
{
public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] boundarybytesF = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); // the first time it itereates, you need to make sure it doesn't put too many new paragraphs down or it completely messes up poor webbrick.
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
wr.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
var nvc2 = new NameValueCollection();
nvc2.Add("Accepts-Language", "en-us,en;q=0.5");
wr.Headers.Add(nvc2);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
Stream rs = wr.GetRequestStream();
bool firstLoop = true;
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
if (firstLoop)
{
rs.Write(boundarybytesF, 0, boundarybytesF.Length);
firstLoop = false;
}
else
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
}
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, new FileInfo(file).Name, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
}
catch (Exception ex)
{
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
}
}
use it:
NameValueCollection nvc = new NameValueCollection();
//nvc.Add("id", "TTR");
nvc.Add("table_name", "uploadfile");
nvc.Add("commit", "uploadfile");
Post_File.HttpUploadFile("http://example/upload_file.php", @"C:\user\yourfile.docx", "uploadfile", "application/vnd.ms-excel", nvc);
example server upload_file.php
:
m('File upload '.(@copy($_FILES['uploadfile']['tmp_name'],getcwd().'\\'.'/'.$_FILES['uploadfile']['name']) ? 'success' : 'failed'));
function m($msg) {
echo '<div style="background:#f1f1f1;border:1px solid #ddd;padding:15px;font:14px;text-align:center;font-weight:bold;">';
echo $msg;
echo '</div>';
}
At first, you must specify your path, the path that your *.csv
files are in there
path = 'f:\project\dataset'
You can change it based on your system.
then,
use dir
function :
files = dir (strcat(path,'\*.csv'))
L = length (files);
for i=1:L
image{i}=csvread(strcat(path,'\',file(i).name));
% process the image in here
end
pwd
also can be used.
From the moment.js docs: format('E')
stands for day of week. thus your diff is being computed on which day of the week, which has to be between 1 and 7.
From the moment.js docs again, here is what they suggest:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1
Here is a JSFiddle for your particular case:
$('#test').click(function() {_x000D_
var startDate = moment("13.04.2016", "DD.MM.YYYY");_x000D_
var endDate = moment("28.04.2016", "DD.MM.YYYY");_x000D_
_x000D_
var result = 'Diff: ' + endDate.diff(startDate, 'days');_x000D_
_x000D_
$('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: #ffb;_x000D_
padding: 10px;_x000D_
border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
import java.util.Scanner;
public class Q3{
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
System.out.println("Enter a number:");
int num=scn.nextInt();
int numB=Integer.parseInt(Integer.toBinaryString(num));
String strB=String.format("%08d",numB);//makes a 8 character code
if(num>=1 && num<=255){
System.out.println(strB);
}else{
System.out.println("Number should be in range between 1 and 255");
}
}
}
I had the same error because i had not installed mongoDB. Make sure that you have mongodb installed and if not, you can download it from here https://www.mongodb.com/download-center/community
In this an arrow on compass shows the direction from your location to Kaaba(destination Location)
you can simple use bearingTo in this way.bearing to will give you the direct angle from your location to destination location
Location userLoc=new Location("service Provider");
//get longitudeM Latitude and altitude of current location with gps class and set in userLoc
userLoc.setLongitude(longitude);
userLoc.setLatitude(latitude);
userLoc.setAltitude(altitude);
Location destinationLoc = new Location("service Provider");
destinationLoc.setLatitude(21.422487); //kaaba latitude setting
destinationLoc.setLongitude(39.826206); //kaaba longitude setting
float bearTo=userLoc.bearingTo(destinationLoc);
bearingTo will give you a range from -180 to 180, which will confuse things a bit. We will need to convert this value into a range from 0 to 360 to get the correct rotation.
This is a table of what we really want, comparing to what bearingTo gives us
+-----------+--------------+
| bearingTo | Real bearing |
+-----------+--------------+
| 0 | 0 |
+-----------+--------------+
| 90 | 90 |
+-----------+--------------+
| 180 | 180 |
+-----------+--------------+
| -90 | 270 |
+-----------+--------------+
| -135 | 225 |
+-----------+--------------+
| -180 | 180 |
+-----------+--------------+
so we have to add this code after bearTo
// If the bearTo is smaller than 0, add 360 to get the rotation clockwise.
if (bearTo < 0) {
bearTo = bearTo + 360;
//bearTo = -100 + 360 = 260;
}
you need to implements the SensorEventListener and its functions(onSensorChanged,onAcurracyChabge) and write all the code inside onSensorChanged
Complete code is here for Direction of Qibla compass
public class QiblaDirectionCompass extends Service implements SensorEventListener{
public static ImageView image,arrow;
// record the compass picture angle turned
private float currentDegree = 0f;
private float currentDegreeNeedle = 0f;
Context context;
Location userLoc=new Location("service Provider");
// device sensor manager
private static SensorManager mSensorManager ;
private Sensor sensor;
public static TextView tvHeading;
public QiblaDirectionCompass(Context context, ImageView compass, ImageView needle,TextView heading, double longi,double lati,double alti ) {
image = compass;
arrow = needle;
// TextView that will tell the user what degree is he heading
tvHeading = heading;
userLoc.setLongitude(longi);
userLoc.setLatitude(lati);
userLoc.setAltitude(alti);
mSensorManager = (SensorManager) context.getSystemService(SENSOR_SERVICE);
sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
if(sensor!=null) {
// for the system's orientation sensor registered listeners
mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);//SensorManager.SENSOR_DELAY_Fastest
}else{
Toast.makeText(context,"Not Supported", Toast.LENGTH_SHORT).show();
}
// initialize your android device sensor capabilities
this.context =context;
@Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(context, "Started", Toast.LENGTH_SHORT).show();
mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME); //SensorManager.SENSOR_DELAY_Fastest
super.onCreate();
}
@Override
public void onDestroy() {
mSensorManager.unregisterListener(this);
Toast.makeText(context, "Destroy", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
Location destinationLoc = new Location("service Provider");
destinationLoc.setLatitude(21.422487); //kaaba latitude setting
destinationLoc.setLongitude(39.826206); //kaaba longitude setting
float bearTo=userLoc.bearingTo(destinationLoc);
//bearTo = The angle from true north to the destination location from the point we're your currently standing.(asal image k N se destination taak angle )
//head = The angle that you've rotated your phone from true north. (jaise image lagi hai wo true north per hai ab phone jitne rotate yani jitna image ka n change hai us ka angle hai ye)
GeomagneticField geoField = new GeomagneticField( Double.valueOf( userLoc.getLatitude() ).floatValue(), Double
.valueOf( userLoc.getLongitude() ).floatValue(),
Double.valueOf( userLoc.getAltitude() ).floatValue(),
System.currentTimeMillis() );
head -= geoField.getDeclination(); // converts magnetic north into true north
if (bearTo < 0) {
bearTo = bearTo + 360;
//bearTo = -100 + 360 = 260;
}
//This is where we choose to point it
float direction = bearTo - head;
// If the direction is smaller than 0, add 360 to get the rotation clockwise.
if (direction < 0) {
direction = direction + 360;
}
tvHeading.setText("Heading: " + Float.toString(degree) + " degrees" );
RotateAnimation raQibla = new RotateAnimation(currentDegreeNeedle, direction, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
raQibla.setDuration(210);
raQibla.setFillAfter(true);
arrow.startAnimation(raQibla);
currentDegreeNeedle = direction;
// create a rotation animation (reverse turn degree degrees)
RotateAnimation ra = new RotateAnimation(currentDegree, -degree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
// how long the animation will take place
ra.setDuration(210);
// set the animation after the end of the reservation status
ra.setFillAfter(true);
// Start the animation
image.startAnimation(ra);
currentDegree = -degree;
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
xml code is here
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/flag_pakistan">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/heading"
android:textColor="@color/colorAccent"
android:layout_centerHorizontal="true"
android:layout_marginBottom="100dp"
android:layout_marginTop="20dp"
android:text="Heading: 0.0" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/heading"
android:scaleType="centerInside"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true">
<ImageView
android:id="@+id/imageCompass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerInside"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:src="@drawable/images_compass"/>
<ImageView
android:id="@+id/needle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:scaleType="centerInside"
android:src="@drawable/arrow2"/>
</RelativeLayout>
</RelativeLayout>
SQL Server Browser Service http://msdn.microsoft.com/en-us/library/ms181087.aspx
So if you are using bootstrap4 then this will work.
<style>
.tooltip-inner {
white-space: pre-wrap;
}
</style>
<script>
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
</script>
<a data-toggle="tooltip" data-placement="auto" title=" first line 
 next line" href= ""> Hover me </a>
If you are using in Django project then we can also display dynamic data in tooltips like:
<a class="black-text pb-2 pt-1" data-toggle="tooltip" data-placement="auto" title="{{ post.location }} 
 {{ post.updated_on }}" href= "{% url 'blog:get_user_profile' post.author.id %}">{{ post.author }}</a>
Long time no Perl
while(<STDIN>) {
next unless /:\s*(\S+)\s+\(([^\)]+)\)\s*(\*?)/;
print "|$1|$2|$3|\n";
}
Did you check
console.table(yourArray);
More infos here: https://developer.mozilla.org/en-US/docs/Web/API/Console/table
Request.QueryString
returns you a collection of Key/Value pairs representing the Query String. Not a String. Don't think that would cause a Object Reference error though. The reason your getting that is because as Mauro pointed out in the comments. It's QueryString and not Querystring.
Try:
Request.QueryString.ToString();
or
<%
string URL = Request.Url.AbsoluteUri
System.Net.WebClient wc = new System.Net.WebClient();
string data = wc.DownloadString(URL);
Response.Output.Write(data);
%>
Same as your code but Request.Url.AbsoluteUri
will return the full path, including the query string.
You can try to use TCPView utility.
Try to find in the localport column is there any process worked on "busy" port. Right click and end the process. Then try to start the Tomcat.
Its really works for me.