I was solving this leetcode problem and I came across this beautiful solution by a user named Zitao Wang.
The problem goes like this for each element in the given array find the product of all the remaining numbers without making use of divison and in O(n)
time
The standard solution is:
Pass 1: For all elements compute product of all the elements to the left of it
Pass 2: For all elements compute product of all the elements to the right of it
and then multiplying them for the final answer
His solution uses only one for loop by making use of. He computes the left product and right product on the fly using ~
def productExceptSelf(self, nums):
res = [1]*len(nums)
lprod = 1
rprod = 1
for i in range(len(nums)):
res[i] *= lprod
lprod *= nums[i]
res[~i] *= rprod
rprod *= nums[~i]
return res
Your selector doesn't need to be inside your remove.
It should look something like:
$("#tableID tr:gt(0)").remove();
Which means select every row except the first in the table with ID of tableID and remove them from the DOM.
I know, this question is already answered but probably somebody like me needs to access a column name from DatabaseMetaData
by label instead of index:
ResultSet resultSet = null;
DatabaseMetaData metaData = null;
try {
metaData = connection.getMetaData();
resultSet = metaData.getColumns(null, null, tableName, null);
while (resultSet.next()){
String name = resultSet.getString("COLUMN_NAME");
}
}
tl;dr: git diff <local branch> <remote branch>
When using git on the shell, I like to first orient myself by looking around. Here's a command to show all branches
$ git branch -a # (or git branch --all)
* my-branch
master
remotes/origin/some-branch
remotes/origin/HEAD -> origin/master
remotes/origin/my-branch
remotes/origin/some-other-branch
remotes/origin/master
Here I have two local branches (my-branch
and master
) and 4 remote (some-branch
, some-other-branch
, master
, and my-branch
).
Also, the asterisk next to my-branch
signals the fact that I'm currently in that branch (you would also know that by using the command git status
that would output: On branch my-branch.
).
Note: the remote branches in the git bash shell are shown in red while the local ones are shown in green.
If you just want to show remote branches:
$ git branch -r # (or git branch --remotes)
origin/some-branch
origin/HEAD -> origin/master
origin/my-branch
origin/some-other-branch
origin/master
To show just local branches you might be tempted to use git branch -l
but that's a completely different command. To show local branches use git branch
with no options
$ git branch
* my-branch
master
To complete a review of the basic branch options there's the --list
that contrary to what you might expect is there to allow filtering. Use it with a pattern like this:
$ git branch --list 'my*'
* my-branch
You can also combine --list
with the options -a
and -r
but make sure to adapt your pattern accordingly (remember: remote branches start with "remotes").
Example:
# this will show all branches (local & remote) that start with my
$ git branch --list 'my*' -a
* my-branch
# better: the pattern includes the remote
$ git branch --list '*my*' -a
* my-branch
remotes/origin/my-branch
Docs: https://git-scm.com/docs/git-branch
Now you can compare any two branches from all the available ones (you can also compare two locals or two remotes).
Here I'm comparing the local with the remote my-branch
, they're synchronized so I don't get any output:
$ git diff my-branch remotes/origin/my-branch
Note: you have to give the full names of the branches with no quotation marks.
I can also compare the local my-branch
to the remote master
. Here I get some output because the remote my-branch
hasn't been merged into the master branch.
$ git diff my-branch remotes/origin/master
diff --git a/src/controllers/call.controller.js b/src/controllers/call.controller.js
index fd79b98..df3d798 100644
--- a/src/controllers/call.controller.js
+++ b/src/controllers/call.controller.js
@@ -261,7 +261,7 @@ function callController() {
/*
* Function: doCall
[ . . . ]
One more answer for this. I'm posting a separate answer, because it's more of an "exact" attempt at a solution than a list of possible solutions:
Here's a filter that will do an "immediate if" (aka iif):
app.filter('iif', function () {
return function(input, trueValue, falseValue) {
return input ? trueValue : falseValue;
};
});
and can be used like this:
{{foo == "bar" | iif : "it's true" : "no, it's not"}}
One more thing that might be the problem in a case similar to described - X is not forwarded and $DISPLAY is not set when 'xauth' program is not installed on the remote side. You can see it searches for it when you run "ssh -Xv ip_address", and, if not found, fails, which's not seen unless you turn on verbose mode (a fail IMO). You can usually find 'xauth' in a package with the same name.
Don't declare the variable in the userform. Declare it as Public
in the module.
Public pass As String
In the Userform
Private Sub CommandButton1_Click()
pass = UserForm1.TextBox1
Unload UserForm1
End Sub
In the Module
Public pass As String
Public Sub Login()
'
'~~> Rest of the code
'
UserForm1.Show
driver.findElementByName("PASSWORD").SendKeys pass
'
'~~> Rest of the code
'
End Sub
You might want to also add an additional check just before calling the driver.find...
line?
If Len(Trim(pass)) <> 0 Then
This will ensure that a blank string is not passed.
As JavaScript is client side and JSP is Server side.
So Javascript does not execute until it gets to the browser, But Java executes on the server. So, Java does not know the value of the JavaScript variable.
However you assign value of Java variable to JavaScript variable.
Similar approach to @Samuel-bergström:
@font-face {_x000D_
font-family: 'FontAwesome';_x000D_
//src: url('@{fa-font-path}/fontawesome-webfont.eot?v=@{fa-version}');_x000D_
src: _x000D_
//url('@{fa-font-path}/fontawesome-webfont.eot?#iefix&v=@{fa-version}') format('embedded-opentype'),_x000D_
//url('@{fa-font-path}/fontawesome-webfont.woff2?v=@{fa-version}') format('woff2'),_x000D_
url('@{fa-font-path}/fontawesomeregular.woff?v=@{fa-version}') format('woff'),_x000D_
url('@{fa-font-path}/fontawesomeregular.ttf?v=@{fa-version}') format('truetype'),_x000D_
url('@{fa-font-path}/fontawesomeregular.svg?v=@{fa-version}#fontawesomeregular') format('svg');_x000D_
// src: url('@{fa-font-path}/FontAwesome.otf') format('opentype'); // used when developing fonts_x000D_
font-weight: normal;_x000D_
font-style: normal;_x000D_
}
_x000D_
I know it may be 'controversial' to comment out other file types, but happy to hear how to generate .eot or .otf files in the comments.
and finally, as Samuel mentions, update your CSS/LESS with:
.fa-XXX:before { content: "\f501"; }
You should use the following:
$('#gentab').on('click', 'a.tabclick', function(event) {
event.preventDefault();
var liId = $(this).closest("li").attr("id");
alert(liId);
});
This will attach your event to any anchors within the #gentab
element,
reducing the scope of having to check the whole document
element tree and increasing efficiency.
Here is an alternative for that experiment (Swift 3.0). This tells you exactly which kind of number was the largest.
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
var whichKind: String? = nil
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
whichKind = kind
largest = number
}
}
}
print(whichKind)
print(largest)
OUTPUT:
Optional("Square")
25
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
HTML
<form id="some_form">
<!-- some form elements -->
</form>
and jquery
$("#some_form").reset();
Swift 4, simply use:
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return range.location < 10
}
var path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)?.Replace("file:\\", "");
Complete code with error handling and added file stream closes. Add it to your class that you want to be able to serialize and deserialize. In my case the class name is CreateResumeForm
. You should change it to your own class name. Android
interface Serializable
is not sufficient to save your objects to the file, it only creates streams.
// Constant with a file name
public static String fileName = "createResumeForm.ser";
// Serializes an object and saves it to a file
public void saveToFile(Context context) {
try {
FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(this);
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Creates an object by reading it from a file
public static CreateResumeForm readFromFile(Context context) {
CreateResumeForm createResumeForm = null;
try {
FileInputStream fileInputStream = context.openFileInput(fileName);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
createResumeForm = (CreateResumeForm) objectInputStream.readObject();
objectInputStream.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
return createResumeForm;
}
Use it like this in your Activity
:
form = CreateResumeForm.readFromFile(this);
To add to the end of the list:
list.append('foo')
To insert at the beginning:
list.insert(0, 'foo')
import * as utils from './utils.js';
If you do the above, you will be able to use functions in utils.js as
utils.someFunction()
This is a very simple RegEx for validating US Zipcode (not ZipCode Plus Four):
(?!([089])\1{4})\d{5}
Seems all five digit numeric are valid zipcodes except 00000
, 88888
& 99999
.
I have tested this RegEx with http://regexpal.com/
SP
A quick solution (error free)
function getClientIP():string
{
$keys=array('HTTP_CLIENT_IP','HTTP_X_FORWARDED_FOR','HTTP_X_FORWARDED','HTTP_FORWARDED_FOR','HTTP_FORWARDED','REMOTE_ADDR');
foreach($keys as $k)
{
if (!empty($_SERVER[$k]) && filter_var($_SERVER[$k], FILTER_VALIDATE_IP))
{
return $_SERVER[$k];
}
}
return "UNKNOWN";
}
For multiple files input using lodash or underscore:
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
return _.map(changeEvent.target.files, function(file){
scope.fileread = [];
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread.push(loadEvent.target.result);
});
}
reader.readAsDataURL(file);
});
});
}
}
}]);
grep 'search this' *.txt
worked for me to search through all .txt files (enter your own search value, of course).
I ran into this issue with a Web Application - my .cshtml
files got stuck on the System.Web.WebPages.WebViewPage
base class when I needed the System.Web.Mvc.WebViewPage
.
First, ensure your ~/Views/web.config file has the correct pageBaseType
. In my case, I set to System.Web.Mvc.WebViewPage
.
<configuration>
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<!-- ... -->
</pages>
</system.web.webPages.razor>
</configuration>
Then, importantly, some people have found this is key if the above is already good:
.user
file that Visual Studio generated next to the project. For VS2015, the .user
and .sln
files have moved to the .vs
hidden folder that is created next to the .sln
file. However, from comments below, the error messages imply to me that the tooling is using the wrong version of MVC entirely, and deleting this folder does not fix the issue. To my knowledge, there is not a known solution.
Give your img tag an id, then you can
document.getElementById("imageid").src="../template/save.png";
This code will only ever be run against test servers so I don't want to go to the hassle of adding new trusted certs each time we set up a new test server.
This is the kind of code that will eventually find its way in production (if not from you, someone else who's reading this question will copy and paste the insecure trust managers that have been suggested into their applications). It's just so easy to forget to remove this sort of code when you have a deadline, since it doesn't show up as a problem.
If you're worried about having to add new certificates every time you have a test server, create your own little CA, issue all the certificates for the test servers using that CA and import this CA certificate into your client trust store. (Even if you don't deal with things like online certificate revocation in a local environment, this is certainly better than using a trust manager that lets anything through.)
There are tools to help you do this, for example TinyCA or XCA.
shape()
consists of array having two arguments rows and columns.
if you search shape[0]
then it will gave you the number of rows.
shape[1]
will gave you number of columns.
1/3
uses integer division as both sides are integers.
You need at least one of them to be float
or double
.
If you are entering the values in the source code like your question, you can do 1.0/3
; the 1.0
is a double.
If you get the values from elsewhere you can use (double)
to turn the int
into a double
.
int x = ...;
int y = ...;
double value = ((double) x) / y;
I prefer this way, not using a cell but a range
Dim cell_to_test As Range, cells_changed As Range
Set cells_changed = Target(1, 1)
Set cell_to_test = Range( RANGE_OF_CELLS_TO_DETECT )
If Not Intersect(cells_changed, cell_to_test) Is Nothing Then
Macro
End If
It's wrong. Use a span.
To see a list of which commits are on one branch but not another, use git log:
git log --no-merges oldbranch ^newbranch
...that is, show commit logs for all commits on oldbranch that are not on newbranch. You can list multiple branches to include and exclude, e.g.
git log --no-merges oldbranch1 oldbranch2 ^newbranch1 ^newbranch2
Note: on Windows ^
is an escape key, so it needs to be escaped with another ^
:
git log --no-merges oldbranch ^^newbranch
I think that this will do the trick:
table{
table-layout: fixed;
width: 300px;
}
does it work with an antislash before the [
?
\[
or \\[
?
If you want to get
localhost:2806
from
http://localhost:2806/Pages/
then use:
HttpContext.Current.Request.Url.Authority
Check that the connection string is in your Web.Config. I removed that node and put it in my Web.Debug.config and this is the error I received. Moved it back to the Web.config and worked great.
Should you want to clear the array with something other than a value, std::file wont cut it; instead I found std::generate useful. e.g. I had a vector of lists I wanted to initialize
std::generate(v.begin(), v.end(), [] () { return std::list<X>(); });
You can do ints too e.g.
std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; });
or just
std::generate(v.begin(), v.end(), [] (){ return 0; });
but I imagine std::fill is faster for the simplest case
With arrays in php, the foreach loop is always a pretty solution.
In this case it could be for example:
foreach($my_array as $number => $number_array)
{
foreach($number_array as $data = > $user_data)
{
print "Array number: $number, contains $data with $user_data. <br>";
}
}
Could you post the exact query? The ExecuteNonQuery
method returns the @@ROWCOUNT
Sql Server variable what ever it is after the last query has executed is what the ExecuteNonQuery
method returns.
Just want to throw something in to help people still having this problem. (for me at least) the css is showing that it puts default classes of level1, level2, and level3 on each piece of the menu(level 1 being the menu, level2 being the first dropdown, level3 being the third popout). Setting the padding in css
.level2
{
padding: 2px 2px 2px 2px;
}
does work for adding the padding to each li in the first dropdown.
=AND(LEN($A1), COLUMN()<3, COUNTBLANK($E1:$H1))
=AND(LEN($A1), OR(COLUMN()<3, AND(COLUMN()>4, COUNTBLANK(A1))), COUNTBLANK($E1:$H1))
=$A:$H
.Results should be similar to the following.
¹ The COUNTBLANK function was introduced with Excel 2007. It will count both true blanks and zero-length strings left by formulas (e.g. ""
).
Hope this can help!
pd.DataFrame(np.nan, index = np.arange(<num_rows>), columns = ['A'])
The following two snippets are semantically equivalent:
for item in iterator:
a_list.append(item)
and
a_list.extend(iterator)
The latter may be faster as the loop is implemented in C.
So it would become:
List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
while(true)
Iterator<Integer> myListIterator = myCoords.iterator();
while (myListIterator.hasNext()) {
Integer coord = myListIterator.next();
System.out.print("\r" + coord);
try{
Thread.sleep(2000);
}catch(Exception e){
// handle the exception...
}
}
}
The easiest way is to use PyHive.
To install you'll need these libraries:
pip install sasl
pip install thrift
pip install thrift-sasl
pip install PyHive
After installation, you can connect to Hive like this:
from pyhive import hive
conn = hive.Connection(host="YOUR_HIVE_HOST", port=PORT, username="YOU")
Now that you have the hive connection, you have options how to use it. You can just straight-up query:
cursor = conn.cursor()
cursor.execute("SELECT cool_stuff FROM hive_table")
for result in cursor.fetchall():
use_result(result)
...or to use the connection to make a Pandas dataframe:
import pandas as pd
df = pd.read_sql("SELECT cool_stuff FROM hive_table", conn)
From version 1.6.1 on, it's advisable to use the method prop for boolean attributes/properties such as selected, readonly, enabled,...
var theValue = "whatever";
$("#selectID").val( theValue ).prop('selected',true);
For more info, please refer to to http://blog.jquery.com/2011/05/12/jquery-1-6-1-released/
View page
<a href="<?php echo base_url();?>products_controller/delete_controller/<?php echo $product_id;?>"><?php echo $name; ?></a>
controller page
function delete_controller( $product_id) {
echo $product_id;
//add your logic
}
Place a second copy of the image in the same spot, then remove the original image.
ele.insertAdjacentHTML('beforebegin',ele.outerHTML);
ele.parentNode.removeChild(ele);
This will effectively refresh the image.
to pass the event
object:
<p id="p" onclick="doSomething(event)">
to get the clicked child element
(should be used with event
parameter:
function doSomething(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
}
to pass the element
itself (DOMElement):
<p id="p" onclick="doThing(this)">
see live example on jsFiddle.
You can specify the name of the event
as above, but alternatively your handler can access the event
parameter as described here: "When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters". There's much more additional documentation at the link.
My solution is:
I hope this can help.
This is simple code to do it, I avoided all checks but this is the main idea.
public String parse(String jsonLine) {
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("data");
JsonArray jarray = jobject.getAsJsonArray("translations");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("translatedText").getAsString();
return result;
}
To make the use more generic - you will find that Gson's javadocs are pretty clear and helpful.
Remove Padding: 10%;
or use px instead of percent for .wrap
see the example : http://jsfiddle.net/C93mk/493/
HTML :
<div id="wrapper">
<div id="wrap">
Some relative item placed item
<div id="fixed"></div>
</div>
</div>
CSS:
body{ height:20000px }
#wrapper {padding:10%;}
#wrap{
float: left;
position: relative;
width: 200px;
background:#ccc;
}
#fixed{
position:fixed;
width:inherit;
padding:0px;
height:10px;
background-color:#333;
}
Use the .replace
[MDN] function to replace the lowercase letters that begin a word with the capital letter.
var str = "hello world";_x000D_
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {_x000D_
return letter.toUpperCase();_x000D_
});_x000D_
alert(str); //Displays "Hello World"
_x000D_
Edit: If you are dealing with word characters other than just a-z, then the following (more complicated) regular expression might better suit your purposes.
var str = "???? ????????? björn über ñaque a?fa";_x000D_
str = str.toLowerCase().replace(/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g, function(letter) {_x000D_
return letter.toUpperCase();_x000D_
});_x000D_
alert(str); //Displays "???? ????????? Björn Über Ñaque ??fa"
_x000D_
Subtract char '0' or int 48 like this:
char c = '5';
int i = c - '0';
Explanation: Internally it works with ASCII value. From the ASCII table, decimal value of character 5 is 53 and 0 is 48. So 53 - 48 = 5
OR
char c = '5';
int i = c - 48; // Because decimal value of char '0' is 48
That means if you deduct 48 from any numeral character, it will convert integer automatically.
You can use the shell for this purpose.
Set shl = CreateObject("WScript.Shell")
shl.Run "cmd mkdir YourDir" & copy "
It seems that, according to the HTML5 spec, the value property of the textarea element should return '\r\n' for a newline:
The element's value is defined to be the element's raw value with the following transformation applied:
Replace every occurrence of a "CR" (U+000D) character not followed by a "LF" (U+000A) character, and every occurrence of a "LF" (U+000A) character not preceded by a "CR" (U+000D) character, by a two-character string consisting of a U+000D CARRIAGE RETURN "CRLF" (U+000A) character pair.
Following the link to 'value' makes it clear that it refers to the value property accessed in javascript:
Form controls have a value and a checkedness. (The latter is only used by input elements.) These are used to describe how the user interacts with the control.
However, in all five major browsers (using Windows, 11/27/2015), if '\r\n' is written to a textarea, the '\r' is stripped. (To test: var e=document.createElement('textarea'); e.value='\r\n'; alert(e.value=='\n');) This is true of IE since v9. Before that, IE was returning '\r\n' and converting both '\r' and '\n' to '\r\n' (which is the HTML5 spec). So... I'm confused.
To be safe, it's usually enough to use '\r?\n' in regular expressions instead of just '\n', but if the newline sequence must be known, a test like the above can be performed in the app.
Update 2016
As this answer receives some attention, I want to hint to a more recommended way on doing this using Virtual Hosts: Apache: Redirect SSL
<VirtualHost *:80>
ServerName mysite.example.com
Redirect permanent / https://mysite.example.com/
</VirtualHost>
<VirtualHost _default_:443>
ServerName mysite.example.com
DocumentRoot /usr/local/apache2/htdocs
SSLEngine On
# etc...
</VirtualHost>
Old answer, hacky thing given that your ssl-port is not set to 80, this will work:
RewriteEngine on
# force ssl
RewriteCond %{SERVER_PORT} ^80$
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]
Note that this should be your first rewrite rule.
Edit: This code does the following. The RewriteCond(ition) checks wether the ServerPort of the request is 80 (which is the default http-port, if you specified another port, you would have to adjust the condition to it). If so, we match the whole url (.*)
and redirect it to a https-url. %{SERVER_NAME}
may be replaced with a specific url, but this way you don't have to alter the code for other projects. %{REQUEST_URI}
is the portion of the url after the TLD (top-level-domain), so you will be redirected to where you came from, but as https.
I think you probably want to view the minification of each set of css as a separate task
task minifyBrandACss(type: com.eriwen.gradle.css.tasks.MinifyCssTask) {
source = "src/main/webapp/css/brandA/styles.css"
dest = "${buildDir}/brandA/styles.css"
}
etc etc
BTW executing your minify tasks in an action of the war task seems odd to me - wouldn't it make more sense to make them a dependency of the war task?
in C#:
new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1)
new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1)
You can please try this code to call the handler every 15 seconds via onResume() and stop it when the activity is not visible, via onPause().
Handler handler = new Handler();
Runnable runnable;
int delay = 15*1000; //Delay for 15 seconds. One second = 1000 milliseconds.
@Override
protected void onResume() {
//start handler as activity become visible
handler.postDelayed( runnable = new Runnable() {
public void run() {
//do something
handler.postDelayed(runnable, delay);
}
}, delay);
super.onResume();
}
// If onPause() is not included the threads will double up when you
// reload the activity
@Override
protected void onPause() {
handler.removeCallbacks(runnable); //stop handler when activity not visible
super.onPause();
}
To quote the documentation:
Key words and unquoted identifiers are case insensitive. Therefore:
UPDATE MY_TABLE SET A = 5;
can equivalently be written as:
uPDaTE my_TabLE SeT a = 5;
You could also write it using quoted identifiers:
UPDATE "my_table" SET "a" = 5;
Quoting an identifier makes it case-sensitive, whereas unquoted names are always folded to lower case (unlike the SQL standard where unquoted names are folded to upper case). For example, the identifiers FOO
, foo
, and "foo"
are considered the same by PostgreSQL, but "Foo"
and "FOO"
are different from these three and each other.
If you want to write portable applications you are advised to always quote a particular name or never quote it.
} means move cursor to next paragraph. so, use v}
to select entire paragraph.
Local Windows 10 ActiveMQ server :
@echo off
start /min "" "C:\Install\apache-activemq\5.15.10\bin\win64\activemq.bat" start
Below is the pseudocode that may help you:
public String getBase64FromFile(String path)
{
Bitmap bmp = null;
ByteArrayOutputStream baos = null;
byte[] baat = null;
String encodeString = null;
try
{
bmp = BitmapFactory.decodeFile(path);
baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
baat = baos.toByteArray();
encodeString = Base64.encodeToString(baat, Base64.DEFAULT);
}
catch (Exception e)
{
e.printStackTrace();
}
return encodeString;
}
A later answer, but because no one gave this solution...
If you do not want to set the header on the HttpClient
instance by adding it to the DefaultRequestHeaders
, you could set headers per request.
But you will be obliged to use the SendAsync()
method.
This is the right solution if you want to reuse the HttpClient
-- which is a good practice for
Use it like this:
using (var requestMessage =
new HttpRequestMessage(HttpMethod.Get, "https://your.site.com"))
{
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", your_token);
httpClient.SendAsync(requestMessage);
}
I do not think that this can be done. Here is some code copied with no modifications from Chip Pearson's site: http://www.cpearson.com/excel/UnSelect.aspx.
UnSelectActiveCell
This procedure will remove the Active Cell from the Selection.
Sub UnSelectActiveCell()
Dim R As Range
Dim RR As Range
For Each R In Selection.Cells
If StrComp(R.Address, ActiveCell.Address, vbBinaryCompare) <> 0 Then
If RR Is Nothing Then
Set RR = R
Else
Set RR = Application.Union(RR, R)
End If
End If
Next R
If Not RR Is Nothing Then
RR.Select
End If
End Sub
UnSelectCurrentArea
This procedure will remove the Area containing the Active Cell from the Selection.
Sub UnSelectCurrentArea()
Dim Area As Range
Dim RR As Range
For Each Area In Selection.Areas
If Application.Intersect(Area, ActiveCell) Is Nothing Then
If RR Is Nothing Then
Set RR = Area
Else
Set RR = Application.Union(RR, Area)
End If
End If
Next Area
If Not RR Is Nothing Then
RR.Select
End If
End Sub
This has now been fixed in Firefox Nightly and will be in the next firefox build.
Please see this bug for more information https://bugzilla.mozilla.org/show_bug.cgi?id=610733
Microsoft: Because VBScript is a subset of Visual Basic for Applications,...
The code below is derived from Codo's post should it also be helpful to have in class form, and usable as VBScript:
class JsonParser
' adapted from: http://stackoverflow.com/questions/6627652/parsing-json-in-excel-vba
private se
private sub Class_Initialize
set se = CreateObject("MSScriptControl.ScriptControl")
se.Language = "JScript"
se.AddCode "function getValue(jsonObj, valueName) { return jsonObj[valueName]; } "
se.AddCode "function enumKeys(jsonObj) { var keys = new Array(); for (var i in jsonObj) { keys.push(i); } return keys; } "
end sub
public function Decode(ByVal json)
set Decode = se.Eval("(" + cstr(json) + ")")
end function
public function GetValue(ByVal jsonObj, ByVal valueName)
GetValue = se.Run("getValue", jsonObj, valueName)
end function
public function GetObject(ByVal jsonObject, ByVal valueName)
set GetObjet = se.Run("getValue", jsonObject, valueName)
end function
public function EnumKeys(ByVal jsonObject)
dim length, keys, obj, idx, key
set obj = se.Run("enumKeys", jsonObject)
length = GetValue(obj, "length")
redim keys(length - 1)
idx = 0
for each key in obj
keys(idx) = key
idx = idx + 1
next
EnumKeys = keys
end function
end class
Usage:
set jp = new JsonParser
set jo = jp.Decode("{value: true}")
keys = jp.EnumKeys(jo)
value = jp.GetValue(jo, "value")
This worked in my case:
sudo apt-get install libpq-dev
I used:
Take a look at THREE.PointerLockControls
Check the variables before building the query, if they are empty, change them to the string NULL
From angular's documentation,
ng-init SHOULD NOT be used for any initialization. It should be used only for aliasing. https://docs.angularjs.org/api/ng/directive/ngInit
onload should be used if any expression needs to be evaluated after a partial view is loaded (by ng-include). https://docs.angularjs.org/api/ng/directive/ngInclude
The major difference between them is when used with ng-include.
<div ng-include="partialViewUrl" onload="myFunction()"></div>
In this case, myFunction is called everytime the partial view is loaded.
<div ng-include="partialViewUrl" ng-init="myFunction()"></div>
Whereas, in this case, myFunction is called only once when the parent view is loaded.
If
in_array('mod_rewrite', apache_get_modules())
returns true
then mod-rewrite is enabled.
You can use jQuery's css
function to test the CSS properties, eg. if ($('node').css('display') == 'block')
.
Colin is right, that there is no explicit event that gets fired when a specific CSS property gets changed. But you may be able to flip it around, and trigger an event that sets the display, and whatever else.
Also consider using adding CSS classes to get the behavior you want. Often you can add a class to a containing element, and use CSS to affect all elements. I often slap a class onto the body element to indicate that an AJAX response is pending. Then I can use CSS selectors to get the display I want.
Not sure if this is what you're looking for.
Here are a couple of complete working examples that build on the @bendewey & @dommer examples. I needed to tweak each one a bit to get it to work, but in case another LINQ noob is looking for working examples, here you go:
//bendewey's example using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ1
{
static void Main( )
{
//Load xml
XDocument xdoc = XDocument.Load(@"c:\\data.xml"); //you'll have to edit your path
//Run query
var lv1s = from lv1 in xdoc.Descendants("level1")
select new
{
Header = lv1.Attribute("name").Value,
Children = lv1.Descendants("level2")
};
StringBuilder result = new StringBuilder(); //had to add this to make the result work
//Loop through results
foreach (var lv1 in lv1s)
{
result.AppendLine(" " + lv1.Header);
foreach(var lv2 in lv1.Children)
result.AppendLine(" " + lv2.Attribute("name").Value);
}
Console.WriteLine(result.ToString()); //added this so you could see the output on the console
}
}
And next:
//Dommer's example, using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ
{
static void Main( )
{
XElement rootElement = XElement.Load(@"c:\\data.xml"); //you'll have to edit your path
Console.WriteLine(GetOutline(0, rootElement));
}
static private string GetOutline(int indentLevel, XElement element)
{
StringBuilder result = new StringBuilder();
if (element.Attribute("name") != null)
{
result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
}
foreach (XElement childElement in element.Elements())
{
result.Append(GetOutline(indentLevel + 1, childElement));
}
return result.ToString();
}
}
These both compile & work in VS2010 using csc.exe version 4.0.30319.1 and give the exact same output. Hopefully these help someone else who's looking for working examples of code.
EDIT: added @eglasius' example as well since it became useful to me:
//@eglasius example, still using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ2
{
static void Main( )
{
StringBuilder result = new StringBuilder(); //needed for result below
XDocument xdoc = XDocument.Load(@"c:\\deg\\data.xml"); //you'll have to edit your path
var lv1s = xdoc.Root.Descendants("level1");
var lvs = lv1s.SelectMany(l=>
new string[]{ l.Attribute("name").Value }
.Union(
l.Descendants("level2")
.Select(l2=>" " + l2.Attribute("name").Value)
)
);
foreach (var lv in lvs)
{
result.AppendLine(lv);
}
Console.WriteLine(result);//added this so you could see the result
}
}
If the machine you are on is part of the AD domain, it should have its name servers set to the AD name servers (or hopefully use a DNS server path that will eventually resolve your AD domains). Using your example of dc=domain,dc=com, if you look up domain.com in the AD name servers it will return a list of the IPs of each AD Controller. Example from my company (w/ the domain name changed, but otherwise it's a real example):
mokey 0 /home/jj33 > nslookup example.ad Server: 172.16.2.10 Address: 172.16.2.10#53 Non-authoritative answer: Name: example.ad Address: 172.16.6.2 Name: example.ad Address: 172.16.141.160 Name: example.ad Address: 172.16.7.9 Name: example.ad Address: 172.19.1.14 Name: example.ad Address: 172.19.1.3 Name: example.ad Address: 172.19.1.11 Name: example.ad Address: 172.16.3.2
Note I'm actually making the query from a non-AD machine, but our unix name servers know to send queries for our AD domain (example.ad) over to the AD DNS servers.
I'm sure there's a super-slick windowsy way to do this, but I like using the DNS method when I need to find the LDAP servers from a non-windows server.
Therefore, before starting '$ sqlplus' on OS, run the followings:
On Windows
set NLS_LANG=AMERICAN_AMERICA.UTF8
On Unix (Solaris and Linux, centos etc)
export NLS_LANG=AMERICAN_AMERICA.UTF8
It would also be advisable to set env variable in your '.bash_profile' [on start up script]
This is the place where other ORACLE env variables (ORACLE_SID, ORACLE_HOME) are usually set.
just fyi - SQL Developer is good at displaying/handling non-English UTF8 characters.
This is very classic case: If you end up having to check for any data provided by the http instance then consider moving that code under the BeginRequest
event.
void Application_BeginRequest(Object source, EventArgs e)
This is the right place to check for http headers, query string and etc...
Application_Start
is for the settings that apply for the application entire run time, such as routing, filters, logging and so on.
Please, don't apply any workarounds such as static .ctor or switching to the Classic mode unless there's no way to move the code from the Start
to BeginRequest
. that should be doable for the vast majority of your cases.
In "References", import DAO 3.6 object reference.
private sub showTableData
dim db as dao.database
dim rs as dao.recordset
set db = currentDb
set rs = db.OpenRecordSet("myTable") 'myTable is a MS-Access table created previously
'populate the table
rs.movelast
rs.movefirst
do while not rs.EOF
debug.print(rs!myField) 'myField is a field name in table myTable
rs.movenext 'press Ctrl+G to see debuG window beneath
loop
msgbox("End of Table")
end sub
You can interate data objects like queries and filtered tables in different ways:
Trhough query:
private sub showQueryData
dim db as dao.database
dim rs as dao.recordset
dim sqlStr as string
sqlStr = "SELECT * FROM customers as c WHERE c.country='Brazil'"
set db = currentDb
set rs = db.openRecordset(sqlStr)
rs.movefirst
do while not rs.EOF
debug.print("cust ID: " & rs!id & " cust name: " & rs!name)
rs.movenext
loop
msgbox("End of customers from Brazil")
end sub
You should also look for "Filter" property of the recordset object to filter only the desired records and then interact with them in the same way (see VB6 Help in MS-Access code window), or create a "QueryDef" object to run a query and use it as a recordset too (a little bit more tricky). Tell me if you want another aproach.
I hope I've helped.
Here is the script i used and it works like a charm. I used the boolean method Ender suggested as the other ones using only the IE specific script adds something to IE but doesn´t take the original code out.
<script>runFancy = true;</script>
<!--[if IE]>
<script type="text/javascript">
runFancy = false;
</script> // <div>The HTML version for IE went here</div>
<![endif]-->
// Below is the script used for all other browsers:
<script src="accmenu/acac1.js" charset="utf-8" type="text/javascript"></script><script>ac1init_doc('',0)</script>
Another option - to convert to C++ besides Shed Skin - is Pythran.
To quote High Performance Python by Micha Gorelick and Ian Ozsvald:
Pythran is a Python-to-C++ compiler for a subset of Python that includes partial
numpy
support. It acts a little like Numba and Cython—you annotate a function’s arguments, and then it takes over with further type annotation and code specialization. It takes advantage of vectorization possibilities and of OpenMP-based parallelization possibilities. It runs using Python 2.7 only.One very interesting feature of Pythran is that it will attempt to automatically spot parallelization opportunities (e.g., if you’re using a
map
), and turn this into parallel code without requiring extra effort from you. You can also specify parallel sections usingpragma omp
> directives; in this respect, it feels very similar to Cython’s OpenMP support.Behind the scenes, Pythran will take both normal Python and numpy code and attempt to aggressively compile them into very fast C++—even faster than the results of Cython.
You should note that this project is young, and you may encounter bugs; you should also note that the development team are very friendly and tend to fix bugs in a matter of hours.
If you are using the Underscore.js library, you can use function keys:
_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]
The function fromJSON() in RJSONIO, rjson and jsonlite don't return a simple 2D data.frame for complex nested json objects.
To overcome this you can use tidyjson. It takes in a json and always returns a data.frame. It is currently not availble in CRAN, you can get it here: https://github.com/sailthru/tidyjson
Update: tidyjson is now available in cran, you can install it directly using install.packages("tidyjson")
There is also another option. Adobe Acrobat Pro is also able to display the internal tree structure of the PDF.
On top Adobe Acrobat Pro can also display the internal structure of the Document Fonts in the PDF most of other "PDF tree structure viewer" don't have this otion
Let's review a few useful concepts about scrolling first:
When should you scroll?
Programmatically that is:
if (firstTime) {
container.scrollTop = container.scrollHeight;
firstTime = false;
} else if (container.scrollTop + container.clientHeight === container.scrollHeight) {
container.scrollTop = container.scrollHeight;
}
Full chat simulator (with JavaScript):
https://jsfiddle.net/apvtL9xa/
const messages = document.getElementById('messages');_x000D_
_x000D_
function appendMessage() {_x000D_
const message = document.getElementsByClassName('message')[0];_x000D_
const newMessage = message.cloneNode(true);_x000D_
messages.appendChild(newMessage);_x000D_
}_x000D_
_x000D_
function getMessages() {_x000D_
// Prior to getting your messages._x000D_
shouldScroll = messages.scrollTop + messages.clientHeight === messages.scrollHeight;_x000D_
/*_x000D_
* Get your messages, we'll just simulate it by appending a new one syncronously._x000D_
*/_x000D_
appendMessage();_x000D_
// After getting your messages._x000D_
if (!shouldScroll) {_x000D_
scrollToBottom();_x000D_
}_x000D_
}_x000D_
_x000D_
function scrollToBottom() {_x000D_
messages.scrollTop = messages.scrollHeight;_x000D_
}_x000D_
_x000D_
scrollToBottom();_x000D_
_x000D_
setInterval(getMessages, 100);
_x000D_
#messages {_x000D_
height: 200px;_x000D_
overflow-y: auto;_x000D_
}
_x000D_
<div id="messages">_x000D_
<div class="message">_x000D_
Hello world_x000D_
</div>_x000D_
</div>
_x000D_
I think sim serial Number and sim number is unique. You can try this for get sim serial number and get sim number and Don't forget to add permission in manifest file.
TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String getSimSerialNumber = telemamanger.getSimSerialNumber();
String getSimNumber = telemamanger.getLine1Number();
And add below permission into your Androidmanifest.xml
file.
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Let me know if there is any issue.
setTimeout('$("#someDivId").hide()',1500);
sudo is a command for Linux so it cant be used in windows so you will get that error
From similar question DB2 - find and compare the lentgh of the value in a table field - add RTRIM since LENGTH will return length of column definition. This should be correct:
select * from table where length(RTRIM(fieldName))=10
UPDATE 27.5.2019: maybe on older db2 versions the LENGTH function returned the length of column definition. On db2 10.5 I have tried the function and it returns data length, not column definition length:
select fieldname
, length(fieldName) len_only
, length(RTRIM(fieldName)) len_rtrim
from (values (cast('1234567890 ' as varchar(30)) ))
as tab(fieldName)
FIELDNAME LEN_ONLY LEN_RTRIM
------------------------------ ----------- -----------
1234567890 12 10
One can test this by using this term:
where length(fieldName)!=length(rtrim(fieldName))
Here's a performance test for the solutions posted here. https://github.com/tedgonzalez/MaxElementInCollectionPerformance
This is the fastest for Swift 5
array.max()
Try this basic example for better understanding of race condition:
public class ThreadRaceCondition {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Account myAccount = new Account(22222222);
// Expected deposit: 250
for (int i = 0; i < 50; i++) {
Transaction t = new Transaction(myAccount,
Transaction.TransactionType.DEPOSIT, 5.00);
t.start();
}
// Expected withdrawal: 50
for (int i = 0; i < 50; i++) {
Transaction t = new Transaction(myAccount,
Transaction.TransactionType.WITHDRAW, 1.00);
t.start();
}
// Temporary sleep to ensure all threads are completed. Don't use in
// realworld :-)
Thread.sleep(1000);
// Expected account balance is 200
System.out.println("Final Account Balance: "
+ myAccount.getAccountBalance());
}
}
class Transaction extends Thread {
public static enum TransactionType {
DEPOSIT(1), WITHDRAW(2);
private int value;
private TransactionType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
};
private TransactionType transactionType;
private Account account;
private double amount;
/*
* If transactionType == 1, deposit else if transactionType == 2 withdraw
*/
public Transaction(Account account, TransactionType transactionType,
double amount) {
this.transactionType = transactionType;
this.account = account;
this.amount = amount;
}
public void run() {
switch (this.transactionType) {
case DEPOSIT:
deposit();
printBalance();
break;
case WITHDRAW:
withdraw();
printBalance();
break;
default:
System.out.println("NOT A VALID TRANSACTION");
}
;
}
public void deposit() {
this.account.deposit(this.amount);
}
public void withdraw() {
this.account.withdraw(amount);
}
public void printBalance() {
System.out.println(Thread.currentThread().getName()
+ " : TransactionType: " + this.transactionType + ", Amount: "
+ this.amount);
System.out.println("Account Balance: "
+ this.account.getAccountBalance());
}
}
class Account {
private int accountNumber;
private double accountBalance;
public int getAccountNumber() {
return accountNumber;
}
public double getAccountBalance() {
return accountBalance;
}
public Account(int accountNumber) {
this.accountNumber = accountNumber;
}
// If this method is not synchronized, you will see race condition on
// Remove syncronized keyword to see race condition
public synchronized boolean deposit(double amount) {
if (amount < 0) {
return false;
} else {
accountBalance = accountBalance + amount;
return true;
}
}
// If this method is not synchronized, you will see race condition on
// Remove syncronized keyword to see race condition
public synchronized boolean withdraw(double amount) {
if (amount > accountBalance) {
return false;
} else {
accountBalance = accountBalance - amount;
return true;
}
}
}
you may use yourArray.length
to findout number of elements in an array.
Make sure yourArray is not null before doing yourArray.length
, otherwise you will end up with NullPointerException
.
In your specific example they are the same, because the optimizer has figured out what you are trying to do is the same in both examples. But it is possible that in non-trivial examples the optimizer may not do this, and in that case there are reasons to prefer one to other on occasion.
NOT IN
should be preferred if you are testing multiple rows in your outer select. The subquery inside the NOT IN
statement can be evaluated at the beginning of the execution, and the temporary table can be checked against each value in the outer select, rather than re-running the subselect every time as would be required with the NOT EXISTS
statement.
If the subquery must be correlated with the outer select, then NOT EXISTS
may be preferable, since the optimizer may discover a simplification that prevents the creation of any temporary tables to perform the same function.
Continue Statment stop the itration and start next ittration Ex:
System.out.println("continue when i is 2:");
for (int i = 1; i <= 3; i++) {
if (i == 2) {
System.out.print("[continue]");
continue;
}
System.out.print("[i:" + i + "]");
}
and Break Statment stop the loop or Exit from the loop
To push specific, one tag do following
git push origin tag_name
(note: this is answer to the updated question)
You can just do this on the CLI:
echo DBQuery.prototype._prettyShell = true >> ~/.mongorc.js
And it's always going to output pretty results.
We use Sphinx in a Vertical Search project with 10.000.000 + of MySql records and 10+ different database . It has got very excellent support for MySQL and high performance on indexing , research is fast but maybe a little less than Lucene. However it's the right choice if you need quickly indexing every day and use a MySQL db.
No it won't, Java will short-circuit and stop evaluating once it knows the result.
\b matches a word boundary. I think you can use ^$ for empty string.
It specifies an "Anchor", or a position on the page, and allows you to "jump" or "scroll" to that position on the page.
Please see this page for more details.
If there is no ORDER BY
clause, then TOP 100 PERCENT
is redundant. (As you mention, this was the 'trick' with views)
[Hopefully the optimizer will optimize this away.]
In my opinion, it would be a cleaner and easier solution to just set a class on the body and set the font-family in css according to that class.
don't know if that's an option in your case though.
I came through this error. The problem was The developer identity and Mobile Provisioning Profile mismatch.
Delete keychain certificates and fresh install matching provisioning profile and developer certificate fixed the problem.
Maybe this tool (archived version ) could help? It doesn't return the time, but it is a good tool to measure the time a command takes.
I had a similar issue trying to fix the item size to fit the background image width. This worked (at least with Firefox 35) for me :
.navcontainer-top li
{
display: inline-block;
background: url("../images/nav-button.png") no-repeat;
width: 117px;
height: 26px;
}
You can still get it, from microsoft servers, see my answer on this question: Where is Visual Studio 2005 Express?
If you by any chance using java for configuration, you may need to check the below bean
declaration if you have package level changes. Eg: com.abc.spring
package changed to com.bbc.spring
@Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
//builder.scanPackages("com.abc.spring"); //Comment this line as this package no longer valid.
builder.scanPackages("com.bbc.spring");
builder.addProperties(getHibernationProperties());
return builder.buildSessionFactory();
}
As a oneliner guide:
minSdkVersion <= targetSdkVersion <= compileSdkVersion
Ideally:
minSdkVersion (lowest possible) <= targetSdkVersion == compileSdkVersion (latest SDK)
For anyone who is using anaconda, you would install the certifi
package, see more at:
https://anaconda.org/anaconda/certifi
To install, type this line in your terminal:
conda install -c anaconda certifi
This is one way
<div style="position: relative;
width: 200px;
height: 150px;
border: 1px solid black;">
<div style="position: absolute;
bottom: 0;
width: 100%;
height: 50px;
border: 1px solid red;">
</div>
</div>
But because the inner div is positioned absolutely, you'll always have to worry about other content in the outer div overlapping it (and you'll always have to set fixed heights).
If you can do it, it's better to make that inner div the last DOM object in your outer div and have it set to "clear: both".
I solved the same issue setting 'laravel/framework'
dependency version from "^8.0"
to "^7.0"
.
After that running composer update --ignore-platform-reqs
simply worked
I tried a few of the answers on this page, but a lot of them didn't work for me. Maybe because I'm using Vim on Windows 7 (don't mock, just have pity on me :p)?
Here's the easiest one that I found that works on Vim in Windows 7:
:v/\S/d
Here's a longer answer on the Vim Wikia: http://vim.wikia.com/wiki/Remove_unwanted_empty_lines
Try this one:
Data objt = new Data(name, address, contact);
Contacts.add(objt);
"Unable to load the requested file"
Can be also caused by access permissions under linux , make sure you set the correct read permissions for the directory "views/home"
According to gurus, I define LINQ as motorcycle and SP as car. If you want to go for a short trip and only have small passengers(in this case 2), go gracefully with LINQ. But if you want to go for a journey and have large band, i think you should choose SP.
As a conclusion, choosing between motorcycle or car is depend on your route (business), length (time), and passengers (data).
Hope it helps, I may be wrong. :D
Here is a codepen, it worked for me.
I was searching for the simplest solution for embedding the YT video within an iframe, and I feel this is it.
What I needed was to have the video appear in a modal window and stop playing when it was closed
Here is the code : (from: https://codepen.io/anon/pen/GBjqQr)
<div><a href="#" class="play-video">Play Video</a></div>
<div><a href="#" class="stop-video">Stop Video</a></div>
<div><a href="#" class="pause-video">Pause Video</a></div>
<iframe class="youtube-video" width="560" height="315" src="https://www.youtube.com/embed/glEiPXAYE-U?enablejsapi=1&version=3&playerapiid=ytplayer" frameborder="0" allowfullscreen></iframe>
$('a.play-video').click(function(){
$('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'playVideo' + '","args":""}', '*');
});
$('a.stop-video').click(function(){
$('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
});
$('a.pause-video').click(function(){
$('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');
});
Additionally, if you want it to autoplay in a DOM-object that is not yet visible, such as a modal window, if I used the same button to play the video that I was using to show the modal it would not work so I used THIS:
https://www.youtube.com/embed/EzAGZCPSOfg?autoplay=1&enablejsapi=1&version=3&playerapiid=ytplayer
Note: The ?autoplay=1&
where it's placed and the use of the '&' before the next property to allow the pause to continue to work.
This is what you want:
>>> string1 = "go"
>>> string2 = "now"
>>> string3 = "great"
>>> mystring = """
... I will {string1} there
... I will go {string2}
... {string3}
... """
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, 'string3': 'great', '__package__': None, 'mystring': "\nI will {string1} there\nI will go {string2}\n{string3}\n", '__name__': '__main__', 'string2': 'now', '__doc__': None, 'string1': 'go'}
>>> print(mystring.format(**locals()))
I will go there
I will go now
great
R defines a ~
(tilde) operator for use in formulas. Formulas have all sorts of uses, but perhaps the most common is for regression:
library(datasets)
lm( myFormula, data=iris)
help("~")
or help("formula")
will teach you more.
@Spacedman has covered the basics. Let's discuss how it works.
First, being an operator, note that it is essentially a shortcut to a function (with two arguments):
> `~`(lhs,rhs)
lhs ~ rhs
> lhs ~ rhs
lhs ~ rhs
That can be helpful to know for use in e.g. apply
family commands.
Second, you can manipulate the formula as text:
oldform <- as.character(myFormula) # Get components
myFormula <- as.formula( paste( oldform[2], "Sepal.Length", sep="~" ) )
Third, you can manipulate it as a list:
myFormula[[2]]
myFormula[[3]]
Finally, there are some helpful tricks with formulae (see help("formula")
for more):
myFormula <- Species ~ .
For example, the version above is the same as the original version, since the dot means "all variables not yet used." This looks at the data.frame you use in your eventual model call, sees which variables exist in the data.frame but aren't explicitly mentioned in your formula, and replaces the dot with those missing variables.
For those who want a quick solution:
There is a way to get a output to the console similar to the output from tree, by typing the following command into your terminal:
ls -R YOURFOLDER | grep ':$' | sed -e 's/:$//' -e 's/[^\/]*\//| /g' -e 's/| \([^|]\)/|–– \1/g'
This alternative is mentioned in this documentation: https://wiki.ubuntuusers.de/tree/
Then the output can be copied and encapsuled inside a .md file with code block back tics, like mentioned in Jonathas B.C.'s answer.
But be aware that it also outputs all node modules folders in a node project. And in tree you can do something like
tree -I node_modules
to exlude the node modules folder.
Just add a >NUL
at the end of the lines producing the messages.
For example,
COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat >NUL
Based on Brian Digg's post, here are two helpful functions for filtering lists:
#Returns all items in a list that are not contained in toMatch
#toMatch can be a single item or a list of items
exclude <- function (theList, toMatch){
return(setdiff(theList,include(theList,toMatch)))
}
#Returns all items in a list that ARE contained in toMatch
#toMatch can be a single item or a list of items
include <- function (theList, toMatch){
matches <- unique (grep(paste(toMatch,collapse="|"),
theList, value=TRUE))
return(matches)
}
If this isn't a good solution for any reason, please let me know. It worked fine for me.
What I did is to hide the Sidebar and then make appear the navbar with breakpoints
@media screen and (max-width: 771px) {
#fixed-sidebar {
display: none;
}
#navbar-superior {
display: block !important;
}
}
Below are two methods that are superior to looping. Both handle a "no-find" case.
VLOOKUP
with error-handling if the variable doesn't exist (INDEX/MATCH
may be a better route than VLOOKUP
, ie if your two columns A and B were in reverse order, or were far apart)VBAs FIND
method (matching a whole string in column A given I use the xlWhole
argument)
Sub Method1()
Dim strSearch As String
Dim strOut As String
Dim bFailed As Boolean
strSearch = "trees"
On Error Resume Next
strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
If Err.Number <> 0 Then bFailed = True
On Error GoTo 0
If Not bFailed Then
MsgBox "corresponding value is " & vbNewLine & strOut
Else
MsgBox strSearch & " not found"
End If
End Sub
Sub Method2()
Dim rng1 As Range
Dim strSearch As String
strSearch = "trees"
Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
Else
MsgBox strSearch & " not found"
End If
End Sub
What worked for me was:
sudo chmod -R 777 data
cd support-files/
sudo ./mysql.server start
After that the server started running.
But the problem with this method is that I have to repeat this every time I want to start the mysql now. Don't know why it started behaving like this suddenly.
I don't think that you can - but then again, this kind of logic should probably be handled in your controller and passed into the view already set.
I solved this, without having to completely reinstall Visual Studio 2013.
For those who may come across this in the future, the following steps worked for me:
vs_professional.exe
).If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3
Click the link for 'examine the log file' and look near the bottom of the log, for this line:
open regedit.exe
and do an Edit > Find...
for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
. This was found in:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
Edit the BundleVersion
value and change it to a lower version. I changed mine from 12.0.21005.13
to 12.0.21000.13
:
Exit the registry
Run the ISO (or vs_professional.exe
) again. If it has a repair button like the image below, you can skip to step 4.
Run the ISO (or vs_professional.exe
) again. This time repair should be visible.
Click Repair
and let it update your installation and apply its embedded license key. This took about 20 minutes.
Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product
:
Hope this helps somebody in the future!
Accepting as valid the response of Prajeet Shrestha in this thread, I would like to extend his solution using the Label if it is known and the traits of the font.
Swift 4
extension NSMutableAttributedString {
@discardableResult func normal(_ text: String) -> NSMutableAttributedString {
let normal = NSAttributedString(string: text)
append(normal)
return self
}
@discardableResult func bold(_ text: String, withLabel label: UILabel) -> NSMutableAttributedString {
//generate the bold font
var font: UIFont = UIFont(name: label.font.fontName , size: label.font.pointSize)!
font = UIFont(descriptor: font.fontDescriptor.withSymbolicTraits(.traitBold) ?? font.fontDescriptor, size: font.pointSize)
//generate attributes
let attrs: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font]
let boldString = NSMutableAttributedString(string:text, attributes: attrs)
//append the attributed text
append(boldString)
return self
}
}
I'm able to run an SQL query by piping it to SQL*Plus:
@echo select count(*) from table; | sqlplus username/password@database
Give
@echo execute some_procedure | sqlplus username/password@databasename
a try.
this
is the current Object instance. Whenever you have a non-static method, it can only be called on an instance of your object.
This is a common question, and I was heavily on the side wanting the ability to mock HttpClient, but I think I finally came to the realization that you shouldn't be mocking HttpClient. It seems logical to do so, but I think we've been brainwashed by things we see in open source libraries.
We often see "Clients" out there that we mock in our code so that we can test in isolation, so we automatically try to apply the same principle to HttpClient. HttpClient actually does a lot; you can think of it as a manager for HttpMessageHandler, so you don't wanna mock that, and that's why it still doesn't have an interface. The part that you're really interested in for unit testing, or designing your services, even, is the HttpMessageHandler since that is what returns the response, and you can mock that.
It's also worth pointing out that you should probably start treating HttpClient like a bigger deal. For example: Keep your instatiating of new HttpClients to a minimum. Reuse them, they're designed to be reused and use a crap ton less resources if you do. If you start treating it like a bigger deal, it'll feel much more wrong wanting to mock it and now the message handler will start to be the thing that you're injecting, not the client.
In other words, design your dependencies around the handler instead of the client. Even better, abstract "services" that use HttpClient which allow you to inject a handler, and use that as your injectable dependency instead. Then in your tests, you can fake the handler to control the response for setting up your tests.
Wrapping HttpClient is an insane waste of time.
Update: See Joshua Dooms's example. It's exactly what I'm recommending.
Declare password like DB_PASSWORD="2o0@#5TGR1NG" in .env file
If # sign include in your password then password will declare in between " ".
as of 1.8.X IDE C:\Users***\Documents\Arduino\Libraries\
Construct your client as such
HostnameVerifier hostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
ClientConfig config = new DefaultClientConfig();
SSLContext ctx = SSLContext.getInstance("SSL");
ctx.init(null, myTrustManager, null);
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hostnameVerifier, ctx));
Client client = Client.create(config);
Ripped from this blog post with more details: http://blogs.oracle.com/enterprisetechtips/entry/consuming_restful_web_services_with
For information on setting up your certs, see this nicely answered SO question: Using HTTPS with REST in Java
For Android 2.0 or later you can use the startForeground()
method to start your Service in the foreground.
The documentation says the following:
A started service can use the
startForeground(int, Notification)
API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)
The is primarily intended for when killing the service would be disruptive to the user, e.g. killing a music player service would stop music playing.
You'll need to supply a Notification
to the method which is displayed in the Notifications Bar in the Ongoing section.
You can also use this open source library called Wormholy (and made by me).
You just need to integrate it in your project (no code needed), and that's it, you will be able to monitor all the API requests of your app, also on a real device.
And you don't need to manage certificates like with Charles. It all works by magic!
Problem ->
Class A {
private final B b; // must initialize in ctor/instance block
public A(B b) { this.b = b };
}
Class B {
private final A a; // must initialize in ctor/instance block
public B(A a) { this.a = a };
}
// Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'A': Requested bean is currently in creation: Is there an unresolvable circular reference?
Solution 1 ->
Class A {
private B b;
public A( ) { };
//getter-setter for B b
}
Class B {
private A a;
public B( ) { };
//getter-setter for A a
}
Solution 2 ->
Class A {
private final B b; // must initialize in ctor/instance block
public A(@Lazy B b) { this.b = b };
}
Class B {
private final A a; // must initialize in ctor/instance block
public B(A a) { this.a = a };
}
I know it's a bit late but I had issues with a modal window not allowing some links on the menu bar to work, even when it has not been triggered. But I solved it by doing the following:
.modal{
display:none;
}
Using Java createBitmap()
method you can pass the degrees.
Bitmap bInput /*your input bitmap*/, bOutput;
float degrees = 45; //rotation degree
Matrix matrix = new Matrix();
matrix.setRotate(degrees);
bOutput = Bitmap.createBitmap(bInput, 0, 0, bInput.getWidth(), bInput.getHeight(), matrix, true);
I don't think you can!
/home/export/user1 $ sqlplus /
> @script1.sql
> HOST CD /home/export/user2
> @script2.sql
script2.sql has to be in /home/export/user1
.
You either use the full path, or exit the script and start sqlplus
again from the right directory.
#!/bin/bash
oraenv .
cd /home/export/user1
sqlplus / @script1.sql
cd /home/export/user2
sqlplus / @script2.sql
(something like that - doing this from memory!)
UPDATE
You can use Apache Commons Codec (version 1.7+) to do this job for you.
DigestUtils.sha1Hex(stringToConvertToSHexRepresentation)
Thanks to @Jon Onstott for this suggestion.
Old Answer
Convert your Byte Array to Hex String. Real's How To tells you how.
return byteArrayToHexString(md.digest(convertme))
and (copied from Real's How To)
public static String byteArrayToHexString(byte[] b) {
String result = "";
for (int i=0; i < b.length; i++) {
result +=
Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
}
return result;
}
BTW, you may get more compact representation using Base64. Apache Commons Codec API 1.4, has this nice utility to take away all the pain. refer here
import numpy as np
def Haversine(lat1,lon1,lat2,lon2, **kwarg):
"""
This uses the ‘haversine’ formula to calculate the great-circle distance between two points – that is,
the shortest distance over the earth’s surface – giving an ‘as-the-crow-flies’ distance between the points
(ignoring any hills they fly over, of course!).
Haversine
formula: a = sin²(?f/2) + cos f1 · cos f2 · sin²(??/2)
c = 2 · atan2( va, v(1-a) )
d = R · c
where f is latitude, ? is longitude, R is earth’s radius (mean radius = 6,371km);
note that angles need to be in radians to pass to trig functions!
"""
R = 6371.0088
lat1,lon1,lat2,lon2 = map(np.radians, [lat1,lon1,lat2,lon2])
dlat = lat2 - lat1
dlon = lon2 - lon1
a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2) **2
c = 2 * np.arctan2(a**0.5, (1-a)**0.5)
d = R * c
return round(d,4)
Well actually your only need $.each to get all values, it will help you jsfiddle.net/NdQbw/5
<div class="divright">
<select id="drp_Books_Ill_Illustrations" class="leaderMultiSelctdropdown Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
<option value=" ">No illustrations</option>
<option value="a" selected>Illustrations</option>
<option value="b">Maps</option>
<option value="c" selected>selectedPortraits</option>
</select>
</div>
<div class="divright">
<select id="drp_Books_Ill_Illustrations1" class=" Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
<option value=" ">No illustrations</option>
<option value="a">Illustrations</option>
<option value="b">Maps</option>
<option value="c">selectedPortraits</option>
</select>
</div>
<button class="getValue">Get Value</button>
<button class="setValue"> Set value </button>
<div class="divright">
<select id="drp_Books_Ill_Illustrations2" class="leaderMultiSelctdropdown Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
<option value=" ">No illustrations</option>
<option value="a" selected>Illustrations</option>
<option value="b">Maps</option>
<option value="c" selected>selectedPortraits</option>
</select>
</div>
<div class="divright">
<select id="drp_Books_Ill_Illustrations3" class=" Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
<option value=" ">No illustrations</option>
<option value="a">Illustrations</option>
<option value="b">Maps</option>
<option value="c">selectedPortraits</option>
</select>
</div>
<button class="getValue1">Get Value</button>
<button class="setValue1"> Set value </button>
The script:
var selectedValues = new Array();
selectedValues[0] = "a";
selectedValues[1] = "c";
$(".getValue").click(function() {
alert($(".leaderMultiSelctdropdown").val());
});
$(".setValue").click(function() {
$(".Books_Illustrations").val(selectedValues);
});
$('#drp_Books_Ill_Illustrations2, #drp_Books_Ill_Illustrations3').select2();
$(".getValue1").click(function() {
alert($(".leaderMultiSelctdropdown").val());
});
$(".setValue1").click(function() {
//You need a id for set values
$.each($(".Books_Illustrations"), function(){
$(this).select2('val', selectedValues);
});
});
Despite the fact that this is a very old question and probably many of the beforementioned ideas solved many problems, I still want to share the solution with the community that fixed my problem.
I found that the problem was a function called "hasItem" which I was using to check whether or not a JSON-Array contains a specific item. In my case I checked for a value of type Long.
And this led to the problem.
Somehow, the Matchers have problems with values of type Long. (I do not use JUnit or Rest-Assured so much so idk. exactly why, but I guess that the returned JSON-data does just contain Integers.)
So what I did to actually fix the problem was the following. Instead of using:
long ID = ...;
...
.then().assertThat()
.body("myArray", hasItem(ID));
you just have to cast to Integer. So the working code looked like this:
long ID = ...;
...
.then().assertThat()
.body("myArray", hasItem((int) ID));
That's probably not the best solution, but I just wanted to mention that the exception can also be thrown because of wrong/unknown data types.
You can make your own "lifecycle methods" using hooks for maximum nostalgia.
Utility functions:
import { useEffect, useRef } from "react";
export const useComponentDidMount = handler => {
return useEffect(() => {
return handler();
}, []);
};
export const useComponentDidUpdate = (handler, deps) => {
const isInitialMount = useRef(true);
useEffect(() => {
if (isInitialMount.current) {
isInitialMount.current = false;
return;
}
return handler();
}, deps);
};
Usage:
import { useComponentDidMount, useComponentDidUpdate } from "./utils";
export const MyComponent = ({ myProp }) => {
useComponentDidMount(() => {
console.log("Component did mount!");
});
useComponentDidUpdate(() => {
console.log("Component did update!");
});
useComponentDidUpdate(() => {
console.log("myProp did update!");
}, [myProp]);
};
xy <- data.frame(x=1:10, y=10:1)
plot <- ggplot(data = xy)+geom_point(aes(x = x, y = y))
plot
panel = grid.get("panel-3-3")
grid.newpage()
pushViewport(viewport(w=1, h=1, name="layout"))
pushViewport(viewport(w=1, h=1, name="panel-3-3"))
upViewport(1)
upViewport(1)
grid.draw(panel)
You should return the line that redirects
return res.redirect('/UserHomePage');
This is one of my favorite questions. UDP is so misunderstood.
In situations where you really want to get a simple answer to another server quickly, UDP works best. In general, you want the answer to be in one response packet, and you are prepared to implement your own protocol for reliability or to resend. DNS is the perfect description of this use case. The costs of connection setups are way too high (yet, DNS does support a TCP mode as well).
Another case is when you are delivering data that can be lost because newer data coming in will replace that previous data/state. Weather data, video streaming, a stock quotation service (not used for actual trading), or gaming data comes to mind.
Another case is when you are managing a tremendous amount of state and you want to avoid using TCP because the OS cannot handle that many sessions. This is a rare case today. In fact, there are now user-land TCP stacks that can be used so that the application writer may have finer grained control over the resources needed for that TCP state. Prior to 2003, UDP was really the only game in town.
One other case is for multicast traffic. UDP can be multicasted to multiple hosts whereas TCP cannot do this at all.
You can also go through following:
Example:
my_list=[1,2,3,4,5,"abc","def"]
with open('your_file.txt', 'w') as file:
for item in my_list:
file.write("%s\n" % item)
Output:
In your_file.txt
items are saved like:
1
2
3
4
5
abc
def
Your script also saves as above.
Otherwise, you can use pickle
import pickle
my_list=[1,2,3,4,5,"abc","def"]
#to write
with open('your_file.txt', 'wb') as file:
pickle.dump(my_list, file)
#to read
with open ('your_file.txt', 'rb') as file:
Outlist = pickle.load(file)
print(Outlist)
Output: [1, 2, 3, 4, 5, 'abc', 'def']
It save dump the list same as a list when we load it we able to read.
Also by simplejson
possible same as above output
import simplejson as sj
my_list=[1,2,3,4,5,"abc","def"]
#To write
with open('your_file.txt', 'w') as file:
sj.dump(my_list, file)
#To save
with open('your_file.txt', 'r') as file:
mlist=sj.load(file)
print(mlist)
If you have two DateTime that looks the same, but Compare or Equals doesn't return what you expect, this is how to compare them.
Here an example with 1-millisecond precision:
bool areSame = (date1 - date2) > TimeSpan.FromMilliseconds(1d);
Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.
http://www.rgagnon.com/javadetails/java-0542.html
Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.
package filesendtest;
import java.io.*;
import java.net.*;
class TCPServer {
private final static String fileToSend = "C:\\test1.pdf";
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File( fileToSend );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
package filesendtest;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
private final static String serverIP = "127.0.0.1";
private final static int serverPort = 3248;
private final static String fileOutput = "C:\\testout.pdf";
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket( serverIP , serverPort );
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream( fileOutput );
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
Related
Byte array of unknown length in java
Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):
public static String md5String(File file) {
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0) {
md5er.update(buffer, 0, read);
}
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null) {
return null;
}
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
} catch (Exception e) {
return null;
}
}
you have to replace empty strings ('') with np.nan before converting to float. ie:
df['a']=df.a.replace('',np.nan).astype(float)
a) Open the "php.ini". For XAMPP,it is located in C:\XAMPP\php\php.ini. Find out if you are using WAMP or LAMP server. Note : Make a backup of php.ini file
b) Search [mail function] in the php.ini file.
You can find like below.
[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25
; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = postmaster@localhost
Change the localhost to the smtp server name of your ISP. No need to change the smtp_port. Leave it as 25. Change sendmail_from from postmaster@localhost to your domain email address which will be used as from address..
So for me, it will become like this.
[mail function]
; For Win32 only.
SMTP = smtp.planetghost.com
smtp_port = 25
; For Win32 only.
sendmail_from = [email protected]
auth_username = [email protected]
auth_password = example_password
c) Restart the XAMPP or WAMP(apache server) so that changes will start working.
d) Now try to send the mail using the mail() function ,
mail("[email protected]","Success","Great, Localhost Mail works");
================================================================================
Another way
Gmail servers use SMTP Authentication under SSL. I think that there is no way to use the mail() function under that circumstances, so you might want to check these alternatives:
They both support SMTP auth under SSL.
Credit : Check reference answer here
Yes, it is possible:
public class Foo {
private int x;
public Foo() {
this(1);
}
public Foo(int x) {
this.x = x;
}
}
To chain to a particular superclass constructor instead of one in the same class, use super
instead of this
. Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.
See also this related question, which is about C# but where the same principles apply.
You have to take whole columns under resizebox. This code worked for me
\begin{table}[htbp]
\caption{Sample Table.}\label{tab1}
\resizebox{\columnwidth}{!}{\begin{tabular}{|l|l|l|l|l|}
\hline
URL & First Time Visit & Last Time Visit & URL Counts & Value\\
\hline
https://web.facebook.com/ & 1521241972 & 1522351859 & 177 & 56640\\
http://localhost/phpmyadmin/ & 1518413861 & 1522075694 & 24 & 39312\\
https://mail.google.com/mail/u/ & 1516596003 & 1522352010 & 36 & 33264\\
https://github.com/shawon100& 1517215489 & 1522352266 & 37 & 27528\\
https://www.youtube.com/ & 1517229227 & 1521978502 & 24 & 14792\\
\hline
\end{tabular}}
\end{table}
To open and read a text file line per line, you could use the following:
// define your file name
string file_name = "data.txt";
// attach an input stream to the wanted file
ifstream input_stream(file_name);
// check stream status
if (!input_stream) cerr << "Can't open input file!";
// file contents
vector<string> text;
// one line
string line;
// extract all the text from the input file
while (getline(input_stream, line)) {
// store each line in the vector
text.push_back(line);
}
To open and read a binary file you need to explicitly declare the reading format in your input stream to be binary, and read memory that has no explicit interpretation using stream member function read()
:
// define your file name
string file_name = "binary_data.bin";
// attach an input stream to the wanted file
ifstream input_stream(file_name, ios::binary);
// check stream status
if (!input_stream) cerr << "Can't open input file!";
// use function that explicitly specifies the amount of block memory read
int memory_size = 10;
// allocate 10 bytes of memory on heap
char* dynamic_buffer = new char[memory_size];
// read 10 bytes and store in dynamic_buffer
file_name.read(dynamic_buffer, memory_size);
When doing this you'll need to #include
the header : <iostream>
//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]
The reason why I add this answer is that I want to explain the relationship of .
and text()
.
The first thing is when using []
, there are only two types of data:
[number]
to select a node from node-set[bool]
to filter a node-set from node-setIn this case, the value is evaluated to boolean by function boolean()
, and there is a rule:
Filters are always evaluated with respect to a context.
When you need to compare text()
or .
with a string "Data"
, it first uses string()
function to transform those to string type, than gets a boolean result.
There are two important rule about string()
:
The string()
function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.
text()
is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]
.
When it is evaluated by string(["Data"])
, it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.
If you want the string()
function to concatenate all child text, you must then pass a single node instead of a node-set.
For example, we get a node-set ['a', 'b']
, you can pass there parent node to string(parent)
, this will return 'ab'
, and of cause string(.)
in you case will return an concatenated string "Data"
.
Both way will get same result only when there is a text node.
/tmp/myfile
first line text
wanted text
other text
the command
$ grep -n "wanted text" /tmp/myfile | awk -F ":" '{print $1}'
2
C++14 brings generic lambdas. Meaning we can use std::for_each very easily:
std::map<int, int> myMap{{1, 2}, {3, 4}, {5, 6}, {7, 8}};
std::for_each(myMap.begin(), myMap.end(), [](const auto &myMapPair) {
std::cout << "first " << myMapPair.first << " second "
<< myMapPair.second << std::endl;
});
I think std::for_each is sometimes better suited than a simple range based for loop. For example when you only want to loop through a subset of a map.
In theory and by the specification, these are safe basically anywhere, except the domain name. Percent-encode anything not listed, and you're good to go.
A-Z a-z 0-9 - . _ ~ ( ) ' ! * : @ , ;
Only safe when used within specific URL components; use with care.
Paths: + & =
Queries: ? /
Fragments: ? / # + & =
According to the URI specification (RFC 3986), all other characters must be percent-encoded. This includes:
<space> <control-characters> <extended-ascii> <unicode>
% < > [ ] { } | \ ^
If maximum compatibility is a concern, limit the character set to A-Z a-z 0-9 - _ . (with periods only for filename extensions).
Even if valid per the specification, a URL can still be "unsafe", depending on context. Such as a file:/// URL containing invalid filename characters, or a query component containing "?", "=", and "&" when not used as delimiters. Correct handling of these cases are generally up to your scripts and can be worked around, but it's something to keep in mind.
If none of the above worked, try these as well:
In Component services >Computes >My Computer>Dcom config>Microsoft Excel Application>Properties
, go to security tab, click on customize on all three sections and add the user that want to run the application, and give full permissions to the user.
Go to C:\Windows\Temp
make sure it exists and it doesn't prompt you for entering.
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);
See Here for more details.
Or
DateTime dt = DateTime.Now;
Console.WriteLine( dt.ToString( "MMMM" ) );
Or if you want to get the culture-specific abbreviated name.
GetAbbreviatedMonthName(1);
I would recommend Apache HttpComponents HttpClient, a successor of Commons HttpClient
I would also recommend to take a look at HtmlUnit. HtmlUnit is a "GUI-Less browser for Java programs". http://htmlunit.sourceforge.net/
This is the fully working code for jquery .load() api and ckeditor, in my case I am loading a page with ckeditor into div with some jquery effects. I hope it will help you.
$(function() {
runEffect = function(fileload,lessonid,act) {
var selectedEffect = 'drop';
var options = {};
$( "#effect" ).effect( selectedEffect, options, 200, callback(fileload,lessonid,act) );
};
function callback(fileload,lessonid,act) {
setTimeout(function() {//load the page in effect div
$( "#effect" ).load(fileload,{lessonid:lessonid,act:act});
$("#effect").show( "drop",
{direction: "right"}, 200 );
$("#effect").ajaxComplete(function(event, XMLHttpRequest, ajaxOptions) {
loadCKeditor(); //call the function after loading page
});
}, 100 );
};
function loadCKeditor()
{//you need to destroy the instance if already exist
if (CKEDITOR.instances['introduction'])
{
CKEDITOR.instances['introduction'].destroy();
}
CKEDITOR.replace('introduction').getSelection().getSelectedText();
}
});
===================== button for call the function ================================
<input type="button" name="button" id="button" onclick="runEffect('lesson.php','','add')" >
The []
makes no sense in the moment of making an ArrayList of Integers because I imagine you just want to add Integer values.
Just use
List<Integer> list = new ArrayList<>();
to create the ArrayList and it will work.
Excel
SQL
Identity Specification
is Yes, so it will auto increment your
Identity column.Edit Top 200 Rows
from the dialog-box.A good resource start off point would be MSDN as your looking into a microsoft product
I'm surprised nobody has mentioned the static method built right into System.Char
...
int val = (int)Char.GetNumericValue('8');
// val == 8
Here's an easy way for Windows users.
so it's easy)))
Watch this...
var stuff = {};
$('input[type=checkbox]').each(function(i, e) {
stuff[i] = e.checked;
});
And you will have:
Object {0: true, 1: false, 2: false, 3: false}
Or:
$('input[type=checkbox]').each(function(i, e) {
stuff['row'+i] = e.checked;
});
You will have:
Object {row0: true, row1: false, row2: false, row3: false}
Or:
$('input[type=checkbox]').each(function(i, e) {
stuff[e.className+i] = e.checked;
});
You will have:
Object {checkbox0: true, checkbox1: false, checkbox2: false, checkbox3: false}
Google Mobile Ads SDK FAQ states that:
I keep getting the error 'The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.'
You can safely ignore this message. Your app will still fetch and serve banner ads.
So if you included the google-play-services_lib correctly, and you're getting ads, you have nothing to worry about (I guess...)
document.getElementsByTagName("html")[0].classList.add('theme-dark');
document.getElementsByTagName("html")[0].classList.remove('theme-dark')
document.getElementsByTagName("html")[0].classList.toggle('theme-dark')
Please try this
<!DOCTYPE html>
<html>
<head>
<title>Jquery</title>
<meta charset="utf-8">
<script src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
</head>
<body>
<input type="text" id="message" value="" />
<input type="button" id="sendButton" value="Send">
<script>
$(document).ready(function(){
var checkField;
//checking the length of the value of message and assigning to a variable(checkField) on load
checkField = $("input#message").val().length;
var enableDisableButton = function(){
if(checkField > 0){
$('#sendButton').removeAttr("disabled");
}
else {
$('#sendButton').attr("disabled","disabled");
}
}
//calling enableDisableButton() function on load
enableDisableButton();
$('input#message').keyup(function(){
//checking the length of the value of message and assigning to the variable(checkField) on keyup
checkField = $("input#message").val().length;
//calling enableDisableButton() function on keyup
enableDisableButton();
});
});
</script>
</body>
</html>
I just wanted to point out my answer since I know for
loop is faster then $.each
loop
here it is:
just add class="required"
to inputs you want to be required and then in jquery do:
$('#signup_form').submit(function(){
var fields = $('input.required');
for(var i=0;i<fields.length;i++){
if($(fields[i]).val() != ''){
//whatever
}
}
});
color
and fill
are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:
d + scale_color_manual(values=c("#CC6666", "#9999CC"))
is what you want.
If you've exported the environment variable:
export demoPath=/usr/local/demo
you can simply refer to it by name in the makefile
(make
imports all the environment variables you have set):
DEMOPATH = ${demoPath} # Or $(demoPath) if you prefer.
If you've not exported the environment variable, it is not accessible until you do export it, or unless you pass it explicitly on the command line:
make DEMOPATH="${demoPath}" …
If you are using a C shell derivative, substitute setenv demoPath /usr/local/demo
for the export
command.
clone row with update fields and auto increment value
CREATE TEMPORARY TABLE `temp` SELECT * FROM `testing` WHERE id = 14;
UPDATE `temp` SET id = (SELECT id FROM testing ORDER by id DESC LIMIT 1
)+1, user_id = 252 ,policy_no = "mysdddd12" where id = 14;
INSERT INTO `testing` SELECT * FROM `temp`;
DROP TEMPORARY TABLE IF EXISTS `temp`;
tested fastest way to remove diacritics from the string that covers almost all characters is this. found highest performance among all the other methods
Diacritics Map
var diacriticsMap = {
'\u0041': 'A','\u24B6': 'A','\uFF21': 'A','\u00C0': 'A','\u00C1': 'A','\u00C2': 'A','\u1EA6': 'A','\u1EA4': 'A','\u1EAA': 'A','\u1EA8': 'A',
'\u00C3': 'A','\u0100': 'A','\u0102': 'A','\u1EB0': 'A','\u1EAE': 'A','\u1EB4': 'A','\u1EB2': 'A','\u0226': 'A','\u01E0': 'A','\u00C4': 'A',
'\u01DE': 'A','\u1EA2': 'A','\u00C5': 'A','\u01FA': 'A','\u01CD': 'A','\u0200': 'A','\u0202': 'A','\u1EA0': 'A','\u1EAC': 'A','\u1EB6': 'A',
'\u1E00': 'A','\u0104': 'A','\u023A': 'A','\u2C6F': 'A',
'\uA732': 'AA',
'\u00C6': 'AE','\u01FC': 'AE','\u01E2': 'AE',
'\uA734': 'AO',
'\uA736': 'AU',
'\uA738': 'AV','\uA73A': 'AV',
'\uA73C': 'AY',
'\u0042': 'B','\u24B7': 'B','\uFF22': 'B','\u1E02': 'B','\u1E04': 'B','\u1E06': 'B','\u0243': 'B','\u0182': 'B','\u0181': 'B',
'\u0043': 'C','\u24B8': 'C','\uFF23': 'C','\u0106': 'C','\u0108': 'C','\u010A': 'C','\u010C': 'C','\u00C7': 'C','\u1E08': 'C','\u0187': 'C',
'\u023B': 'C','\uA73E': 'C',
'\u0044': 'D','\u24B9': 'D','\uFF24': 'D','\u1E0A': 'D','\u010E': 'D','\u1E0C': 'D','\u1E10': 'D','\u1E12': 'D','\u1E0E': 'D','\u0110': 'D',
'\u018B': 'D','\u018A': 'D','\u0189': 'D','\uA779': 'D',
'\u01F1': 'DZ','\u01C4': 'DZ',
'\u01F2': 'Dz','\u01C5': 'Dz',
'\u0045': 'E','\u24BA': 'E','\uFF25': 'E','\u00C8': 'E','\u00C9': 'E','\u00CA': 'E','\u1EC0': 'E','\u1EBE': 'E','\u1EC4': 'E','\u1EC2': 'E',
'\u1EBC': 'E','\u0112': 'E','\u1E14': 'E','\u1E16': 'E','\u0114': 'E','\u0116': 'E','\u00CB': 'E','\u1EBA': 'E','\u011A': 'E','\u0204': 'E',
'\u0206': 'E','\u1EB8': 'E','\u1EC6': 'E','\u0228': 'E','\u1E1C': 'E','\u0118': 'E','\u1E18': 'E','\u1E1A': 'E','\u0190': 'E','\u018E': 'E',
'\u0046': 'F','\u24BB': 'F','\uFF26': 'F','\u1E1E': 'F','\u0191': 'F','\uA77B': 'F',
'\u0047': 'G','\u24BC': 'G','\uFF27': 'G','\u01F4': 'G','\u011C': 'G','\u1E20': 'G','\u011E': 'G','\u0120': 'G','\u01E6': 'G','\u0122': 'G',
'\u01E4': 'G','\u0193': 'G','\uA7A0': 'G','\uA77D': 'G','\uA77E': 'G',
'\u0048': 'H','\u24BD': 'H','\uFF28': 'H','\u0124': 'H','\u1E22': 'H','\u1E26': 'H','\u021E': 'H','\u1E24': 'H','\u1E28': 'H','\u1E2A': 'H',
'\u0126': 'H','\u2C67': 'H','\u2C75': 'H','\uA78D': 'H',
'\u0049': 'I','\u24BE': 'I','\uFF29': 'I','\u00CC': 'I','\u00CD': 'I','\u00CE': 'I','\u0128': 'I','\u012A': 'I','\u012C': 'I','\u0130': 'I',
'\u00CF': 'I','\u1E2E': 'I','\u1EC8': 'I','\u01CF': 'I','\u0208': 'I','\u020A': 'I','\u1ECA': 'I','\u012E': 'I','\u1E2C': 'I','\u0197': 'I',
'\u004A': 'J','\u24BF': 'J','\uFF2A': 'J','\u0134': 'J','\u0248': 'J',
'\u004B': 'K','\u24C0': 'K','\uFF2B': 'K','\u1E30': 'K','\u01E8': 'K','\u1E32': 'K','\u0136': 'K','\u1E34': 'K','\u0198': 'K','\u2C69': 'K',
'\uA740': 'K','\uA742': 'K','\uA744': 'K','\uA7A2': 'K',
'\u004C': 'L','\u24C1': 'L','\uFF2C': 'L','\u013F': 'L','\u0139': 'L','\u013D': 'L','\u1E36': 'L','\u1E38': 'L','\u013B': 'L','\u1E3C': 'L',
'\u1E3A': 'L','\u0141': 'L','\u023D': 'L','\u2C62': 'L','\u2C60': 'L','\uA748': 'L','\uA746': 'L','\uA780': 'L',
'\u01C7': 'LJ',
'\u01C8': 'Lj',
'\u004D': 'M','\u24C2': 'M','\uFF2D': 'M','\u1E3E': 'M','\u1E40': 'M','\u1E42': 'M','\u2C6E': 'M','\u019C': 'M',
'\u004E': 'N','\u24C3': 'N','\uFF2E': 'N','\u01F8': 'N','\u0143': 'N','\u00D1': 'N','\u1E44': 'N','\u0147': 'N','\u1E46': 'N','\u0145': 'N',
'\u1E4A': 'N','\u1E48': 'N','\u0220': 'N','\u019D': 'N','\uA790': 'N','\uA7A4': 'N',
'\u01CA': 'NJ',
'\u01CB': 'Nj',
'\u004F': 'O','\u24C4': 'O','\uFF2F': 'O','\u00D2': 'O','\u00D3': 'O','\u00D4': 'O','\u1ED2': 'O','\u1ED0': 'O','\u1ED6': 'O','\u1ED4': 'O',
'\u00D5': 'O','\u1E4C': 'O','\u022C': 'O','\u1E4E': 'O','\u014C': 'O','\u1E50': 'O','\u1E52': 'O','\u014E': 'O','\u022E': 'O','\u0230': 'O',
'\u00D6': 'O','\u022A': 'O','\u1ECE': 'O','\u0150': 'O','\u01D1': 'O','\u020C': 'O','\u020E': 'O','\u01A0': 'O','\u1EDC': 'O','\u1EDA': 'O',
'\u1EE0': 'O','\u1EDE': 'O','\u1EE2': 'O','\u1ECC': 'O','\u1ED8': 'O','\u01EA': 'O','\u01EC': 'O','\u00D8': 'O','\u01FE': 'O','\u0186': 'O',
'\u019F': 'O','\uA74A': 'O','\uA74C': 'O',
'\u01A2': 'OI',
'\uA74E': 'OO',
'\u0222': 'OU',
'\u0050': 'P','\u24C5': 'P','\uFF30': 'P','\u1E54': 'P','\u1E56': 'P','\u01A4': 'P','\u2C63': 'P','\uA750': 'P','\uA752': 'P','\uA754': 'P',
'\u0051': 'Q','\u24C6': 'Q','\uFF31': 'Q','\uA756': 'Q','\uA758': 'Q','\u024A': 'Q',
'\u0052': 'R','\u24C7': 'R','\uFF32': 'R','\u0154': 'R','\u1E58': 'R','\u0158': 'R','\u0210': 'R','\u0212': 'R','\u1E5A': 'R','\u1E5C': 'R',
'\u0156': 'R','\u1E5E': 'R','\u024C': 'R','\u2C64': 'R','\uA75A': 'R','\uA7A6': 'R','\uA782': 'R',
'\u0053': 'S','\u24C8': 'S','\uFF33': 'S','\u1E9E': 'S','\u015A': 'S','\u1E64': 'S','\u015C': 'S','\u1E60': 'S','\u0160': 'S','\u1E66': 'S',
'\u1E62': 'S','\u1E68': 'S','\u0218': 'S','\u015E': 'S','\u2C7E': 'S','\uA7A8': 'S','\uA784': 'S',
'\u0054': 'T','\u24C9': 'T','\uFF34': 'T','\u1E6A': 'T','\u0164': 'T','\u1E6C': 'T','\u021A': 'T','\u0162': 'T','\u1E70': 'T','\u1E6E': 'T',
'\u0166': 'T','\u01AC': 'T','\u01AE': 'T','\u023E': 'T','\uA786': 'T',
'\uA728': 'TZ',
'\u0055': 'U','\u24CA': 'U','\uFF35': 'U','\u00D9': 'U','\u00DA': 'U','\u00DB': 'U','\u0168': 'U','\u1E78': 'U','\u016A': 'U','\u1E7A': 'U',
'\u016C': 'U','\u00DC': 'U','\u01DB': 'U','\u01D7': 'U','\u01D5': 'U','\u01D9': 'U','\u1EE6': 'U','\u016E': 'U','\u0170': 'U','\u01D3': 'U',
'\u0214': 'U','\u0216': 'U','\u01AF': 'U','\u1EEA': 'U','\u1EE8': 'U','\u1EEE': 'U','\u1EEC': 'U','\u1EF0': 'U','\u1EE4': 'U','\u1E72': 'U',
'\u0172': 'U','\u1E76': 'U','\u1E74': 'U','\u0244': 'U',
'\u0056': 'V','\u24CB': 'V','\uFF36': 'V','\u1E7C': 'V','\u1E7E': 'V','\u01B2': 'V','\uA75E': 'V','\u0245': 'V',
'\uA760': 'VY',
'\u0057': 'W','\u24CC': 'W','\uFF37': 'W','\u1E80': 'W','\u1E82': 'W','\u0174': 'W','\u1E86': 'W','\u1E84': 'W','\u1E88': 'W','\u2C72': 'W',
'\u0058': 'X','\u24CD': 'X','\uFF38': 'X','\u1E8A': 'X','\u1E8C': 'X',
'\u0059': 'Y','\u24CE': 'Y','\uFF39': 'Y','\u1EF2': 'Y','\u00DD': 'Y','\u0176': 'Y','\u1EF8': 'Y','\u0232': 'Y','\u1E8E': 'Y','\u0178': 'Y',
'\u1EF6': 'Y','\u1EF4': 'Y','\u01B3': 'Y','\u024E': 'Y','\u1EFE': 'Y',
'\u005A': 'Z','\u24CF': 'Z','\uFF3A': 'Z','\u0179': 'Z','\u1E90': 'Z','\u017B': 'Z','\u017D': 'Z','\u1E92': 'Z','\u1E94': 'Z','\u01B5': 'Z',
'\u0224': 'Z','\u2C7F': 'Z','\u2C6B': 'Z','\uA762': 'Z',
'\u0061': 'a','\u24D0': 'a','\uFF41': 'a','\u1E9A': 'a','\u00E0': 'a','\u00E1': 'a','\u00E2': 'a','\u1EA7': 'a','\u1EA5': 'a','\u1EAB': 'a',
'\u1EA9': 'a','\u00E3': 'a','\u0101': 'a','\u0103': 'a','\u1EB1': 'a','\u1EAF': 'a','\u1EB5': 'a','\u1EB3': 'a','\u0227': 'a','\u01E1': 'a',
'\u00E4': 'a','\u01DF': 'a','\u1EA3': 'a','\u00E5': 'a','\u01FB': 'a','\u01CE': 'a','\u0201': 'a','\u0203': 'a','\u1EA1': 'a','\u1EAD': 'a',
'\u1EB7': 'a','\u1E01': 'a','\u0105': 'a','\u2C65': 'a','\u0250': 'a',
'\uA733': 'aa',
'\u00E6': 'ae','\u01FD': 'ae','\u01E3': 'ae',
'\uA735': 'ao',
'\uA737': 'au',
'\uA739': 'av','\uA73B': 'av',
'\uA73D': 'ay',
'\u0062': 'b','\u24D1': 'b','\uFF42': 'b','\u1E03': 'b','\u1E05': 'b','\u1E07': 'b','\u0180': 'b','\u0183': 'b','\u0253': 'b',
'\u0063': 'c','\u24D2': 'c','\uFF43': 'c','\u0107': 'c','\u0109': 'c','\u010B': 'c','\u010D': 'c','\u00E7': 'c','\u1E09': 'c','\u0188': 'c',
'\u023C': 'c','\uA73F': 'c','\u2184': 'c',
'\u0064': 'd','\u24D3': 'd','\uFF44': 'd','\u1E0B': 'd','\u010F': 'd','\u1E0D': 'd','\u1E11': 'd','\u1E13': 'd','\u1E0F': 'd','\u0111': 'd',
'\u018C': 'd','\u0256': 'd','\u0257': 'd','\uA77A': 'd',
'\u01F3': 'dz','\u01C6': 'dz',
'\u0065': 'e','\u24D4': 'e','\uFF45': 'e','\u00E8': 'e','\u00E9': 'e','\u00EA': 'e','\u1EC1': 'e','\u1EBF': 'e','\u1EC5': 'e','\u1EC3': 'e',
'\u1EBD': 'e','\u0113': 'e','\u1E15': 'e','\u1E17': 'e','\u0115': 'e','\u0117': 'e','\u00EB': 'e','\u1EBB': 'e','\u011B': 'e','\u0205': 'e',
'\u0207': 'e','\u1EB9': 'e','\u1EC7': 'e','\u0229': 'e','\u1E1D': 'e','\u0119': 'e','\u1E19': 'e','\u1E1B': 'e','\u0247': 'e','\u025B': 'e',
'\u01DD': 'e',
'\u0066': 'f','\u24D5': 'f','\uFF46': 'f','\u1E1F': 'f','\u0192': 'f','\uA77C': 'f',
'\u0067': 'g','\u24D6': 'g','\uFF47': 'g','\u01F5': 'g','\u011D': 'g','\u1E21': 'g','\u011F': 'g','\u0121': 'g','\u01E7': 'g','\u0123': 'g',
'\u01E5': 'g','\u0260': 'g','\uA7A1': 'g','\u1D79': 'g','\uA77F': 'g',
'\u0068': 'h','\u24D7': 'h','\uFF48': 'h','\u0125': 'h','\u1E23': 'h','\u1E27': 'h','\u021F': 'h','\u1E25': 'h','\u1E29': 'h','\u1E2B': 'h',
'\u1E96': 'h','\u0127': 'h','\u2C68': 'h','\u2C76': 'h','\u0265': 'h',
'\u0195': 'hv',
'\u0069': 'i','\u24D8': 'i','\uFF49': 'i','\u00EC': 'i','\u00ED': 'i','\u00EE': 'i','\u0129': 'i','\u012B': 'i','\u012D': 'i','\u00EF': 'i',
'\u1E2F': 'i','\u1EC9': 'i','\u01D0': 'i','\u0209': 'i','\u020B': 'i','\u1ECB': 'i','\u012F': 'i','\u1E2D': 'i','\u0268': 'i','\u0131': 'i',
'\u006A': 'j','\u24D9': 'j','\uFF4A': 'j','\u0135': 'j','\u01F0': 'j','\u0249': 'j',
'\u006B': 'k','\u24DA': 'k','\uFF4B': 'k','\u1E31': 'k','\u01E9': 'k','\u1E33': 'k','\u0137': 'k','\u1E35': 'k','\u0199': 'k','\u2C6A': 'k',
'\uA741': 'k','\uA743': 'k','\uA745': 'k','\uA7A3': 'k',
'\u006C': 'l','\u24DB': 'l','\uFF4C': 'l','\u0140': 'l','\u013A': 'l','\u013E': 'l','\u1E37': 'l','\u1E39': 'l','\u013C': 'l','\u1E3D': 'l',
'\u1E3B': 'l','\u017F': 'l','\u0142': 'l','\u019A': 'l','\u026B': 'l','\u2C61': 'l','\uA749': 'l','\uA781': 'l','\uA747': 'l',
'\u01C9': 'lj',
'\u006D': 'm','\u24DC': 'm','\uFF4D': 'm','\u1E3F': 'm','\u1E41': 'm','\u1E43': 'm','\u0271': 'm','\u026F': 'm',
'\u006E': 'n','\u24DD': 'n','\uFF4E': 'n','\u01F9': 'n','\u0144': 'n','\u00F1': 'n','\u1E45': 'n','\u0148': 'n','\u1E47': 'n','\u0146': 'n',
'\u1E4B': 'n','\u1E49': 'n','\u019E': 'n','\u0272': 'n','\u0149': 'n','\uA791': 'n','\uA7A5': 'n',
'\u01CC': 'nj',
'\u006F': 'o','\u24DE': 'o','\uFF4F': 'o','\u00F2': 'o','\u00F3': 'o','\u00F4': 'o','\u1ED3': 'o','\u1ED1': 'o','\u1ED7': 'o','\u1ED5': 'o',
'\u00F5': 'o','\u1E4D': 'o','\u022D': 'o','\u1E4F': 'o','\u014D': 'o','\u1E51': 'o','\u1E53': 'o','\u014F': 'o','\u022F': 'o','\u0231': 'o',
'\u00F6': 'o','\u022B': 'o','\u1ECF': 'o','\u0151': 'o','\u01D2': 'o','\u020D': 'o','\u020F': 'o','\u01A1': 'o','\u1EDD': 'o','\u1EDB': 'o',
'\u1EE1': 'o','\u1EDF': 'o','\u1EE3': 'o','\u1ECD': 'o','\u1ED9': 'o','\u01EB': 'o','\u01ED': 'o','\u00F8': 'o','\u01FF': 'o','\u0254': 'o',
'\uA74B': 'o','\uA74D': 'o','\u0275': 'o',
'\u01A3': 'oi',
'\u0223': 'ou',
'\uA74F': 'oo',
'\u0070': 'p','\u24DF': 'p','\uFF50': 'p','\u1E55': 'p','\u1E57': 'p','\u01A5': 'p','\u1D7D': 'p','\uA751': 'p','\uA753': 'p','\uA755': 'p',
'\u0071': 'q','\u24E0': 'q','\uFF51': 'q','\u024B': 'q','\uA757': 'q','\uA759': 'q',
'\u0072': 'r','\u24E1': 'r','\uFF52': 'r','\u0155': 'r','\u1E59': 'r','\u0159': 'r','\u0211': 'r','\u0213': 'r','\u1E5B': 'r','\u1E5D': 'r',
'\u0157': 'r','\u1E5F': 'r','\u024D': 'r','\u027D': 'r','\uA75B': 'r','\uA7A7': 'r','\uA783': 'r',
'\u0073': 's','\u24E2': 's','\uFF53': 's','\u00DF': 's','\u015B': 's','\u1E65': 's','\u015D': 's','\u1E61': 's','\u0161': 's','\u1E67': 's',
'\u1E63': 's','\u1E69': 's','\u0219': 's','\u015F': 's','\u023F': 's','\uA7A9': 's','\uA785': 's','\u1E9B': 's',
'\u0074': 't','\u24E3': 't','\uFF54': 't','\u1E6B': 't','\u1E97': 't','\u0165': 't','\u1E6D': 't','\u021B': 't','\u0163': 't','\u1E71': 't',
'\u1E6F': 't','\u0167': 't','\u01AD': 't','\u0288': 't','\u2C66': 't','\uA787': 't',
'\uA729': 'tz',
'\u0075': 'u','\u24E4': 'u','\uFF55': 'u','\u00F9': 'u','\u00FA': 'u','\u00FB': 'u','\u0169': 'u','\u1E79': 'u','\u016B': 'u','\u1E7B': 'u',
'\u016D': 'u','\u00FC': 'u','\u01DC': 'u','\u01D8': 'u','\u01D6': 'u','\u01DA': 'u','\u1EE7': 'u','\u016F': 'u','\u0171': 'u','\u01D4': 'u',
'\u0215': 'u','\u0217': 'u','\u01B0': 'u','\u1EEB': 'u','\u1EE9': 'u','\u1EEF': 'u','\u1EED': 'u','\u1EF1': 'u','\u1EE5': 'u','\u1E73': 'u',
'\u0173': 'u','\u1E77': 'u','\u1E75': 'u','\u0289': 'u',
'\u0076': 'v','\u24E5': 'v','\uFF56': 'v','\u1E7D': 'v','\u1E7F': 'v','\u028B': 'v','\uA75F': 'v','\u028C': 'v',
'\uA761': 'vy',
'\u0077': 'w','\u24E6': 'w','\uFF57': 'w','\u1E81': 'w','\u1E83': 'w','\u0175': 'w','\u1E87': 'w','\u1E85': 'w','\u1E98': 'w','\u1E89': 'w',
'\u2C73': 'w',
'\u0078': 'x','\u24E7': 'x','\uFF58': 'x','\u1E8B': 'x','\u1E8D': 'x',
'\u0079': 'y','\u24E8': 'y','\uFF59': 'y','\u1EF3': 'y','\u00FD': 'y','\u0177': 'y','\u1EF9': 'y','\u0233': 'y','\u1E8F': 'y','\u00FF': 'y',
'\u1EF7': 'y','\u1E99': 'y','\u1EF5': 'y','\u01B4': 'y','\u024F': 'y','\u1EFF': 'y',
'\u007A': 'z','\u24E9': 'z','\uFF5A': 'z','\u017A': 'z','\u1E91': 'z','\u017C': 'z','\u017E': 'z','\u1E93': 'z','\u1E95': 'z','\u01B6': 'z',
'\u0225': 'z','\u0240': 'z','\u2C6C': 'z','\uA763': 'z',
};
Use
function removeDicretics(str) {
return str.replace(/[^\u0000-\u007E]/g, function (weirdo) {
return diacriticsMap[weirdo] || weirdo;
});
}
// Call
var cleanStr = removeDicretics("bullshìt"); // bullshit
This exception can occur when you try to execute HTTPS request from client on endpoint which isn't HTTPS enabled. Client will encrypt request data when server is expecting raw data.
thatLine = thatLine.replace('\n', '<br />')
str.replace() returns a copy of the string, it doesn't modify the string you pass in.
use the arguments -Xms<memory>
-Xmx<memory>
. Use M
or G
after the numbers for indicating Megs and Gigs of bytes respectively. -Xms
indicates the minimum and -Xmx
the maximum.
ResponseEntity<Resource>
from a handler methodContent-Type
explicitlyContent-Disposition
if necessary:
inline
to force preview in a browserattachment
to force a download@Controller
public class DownloadController {
@GetMapping("/downloadPdf.pdf")
// 1.
public ResponseEntity<Resource> downloadPdf() {
FileSystemResource resource = new FileSystemResource("/home/caco3/Downloads/JMC_Tutorial.pdf");
// 2.
MediaType mediaType = MediaTypeFactory
.getMediaType(resource)
.orElse(MediaType.APPLICATION_OCTET_STREAM);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(mediaType);
// 3
ContentDisposition disposition = ContentDisposition
// 3.2
.inline() // or .attachment()
// 3.1
.filename(resource.getFilename())
.build();
headers.setContentDisposition(disposition);
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}
}
Return ResponseEntity<Resource>
When you return a ResponseEntity<Resource>
, the ResourceHttpMessageConverter
kicks in and writes an appropriate response.
The resource
could be:
Be aware of possibly wrong Content-Type
header set (see FileSystemResource is returned with content type json). That's why this answer suggests setting the Content-Type
explicitly.
Specify Content-Type
explicitly:
Some options are:
MediaTypeFactory
from Spring.The MediaTypeFactory
allows to discover the MediaType
appropriate for the Resource
(see also /org/springframework/http/mime.types
file)
Set Content-Disposition
if necessary:
Sometimes it is necessary to force a download in a browser or to make the browser open a file as a preview. You can use the Content-Disposition
header to satisfy this requirement:
The first parameter in the HTTP context is either
inline
(default value, indicating it can be displayed inside the Web page, or as the Web page) orattachment
(indicating it should be downloaded; most browsers presenting a 'Save as' dialog, prefilled with the value of the filename parameters if present).
In the Spring Framework a ContentDisposition
can be used.
To preview a file in a browser:
ContentDisposition disposition = ContentDisposition
.builder("inline") // Or .inline() if you're on Spring MVC 5.3+
.filename(resource.getFilename())
.build();
To force a download:
ContentDisposition disposition = ContentDisposition
.builder("attachment") // Or .attachment() if you're on Spring MVC 5.3+
.filename(resource.getFilename())
.build();
Use InputStreamResource
carefully:
Since an InputStream
can be read only once, Spring won't write Content-Length
header if you return an InputStreamResource
(here is a snippet of code from ResourceHttpMessageConverter
):
@Override
protected Long getContentLength(Resource resource, @Nullable MediaType contentType) throws IOException {
// Don't try to determine contentLength on InputStreamResource - cannot be read afterwards...
// Note: custom InputStreamResource subclasses could provide a pre-calculated content length!
if (InputStreamResource.class == resource.getClass()) {
return null;
}
long contentLength = resource.contentLength();
return (contentLength < 0 ? null : contentLength);
}
In other cases it works fine:
~ $ curl -I localhost:8080/downloadPdf.pdf | grep "Content-Length"
Content-Length: 7554270
I had a similar issue uploading to an S3 bucket protected with KWS encryption. I have a minimal policy that allows the addition of objects under a specific s3 key.
I needed to add the following KMS permissions to my policy to allow the role to put objects in the bucket. (Might be slightly more than are strictly required)
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"kms:ListKeys",
"kms:GenerateRandom",
"kms:ListAliases",
"s3:PutAccountPublicAccessBlock",
"s3:GetAccountPublicAccessBlock",
"s3:ListAllMyBuckets",
"s3:HeadBucket"
],
"Resource": "*"
},
{
"Sid": "VisualEditor1",
"Effect": "Allow",
"Action": [
"kms:ImportKeyMaterial",
"kms:ListKeyPolicies",
"kms:ListRetirableGrants",
"kms:GetKeyPolicy",
"kms:GenerateDataKeyWithoutPlaintext",
"kms:ListResourceTags",
"kms:ReEncryptFrom",
"kms:ListGrants",
"kms:GetParametersForImport",
"kms:TagResource",
"kms:Encrypt",
"kms:GetKeyRotationStatus",
"kms:GenerateDataKey",
"kms:ReEncryptTo",
"kms:DescribeKey"
],
"Resource": "arn:aws:kms:<MY-REGION>:<MY-ACCOUNT>:key/<MY-KEY-GUID>"
},
{
"Sid": "VisualEditor2",
"Effect": "Allow",
"Action": [
<The S3 actions>
],
"Resource": [
"arn:aws:s3:::<MY-BUCKET-NAME>",
"arn:aws:s3:::<MY-BUCKET-NAME>/<MY-BUCKET-KEY>/*"
]
}
]
}
You can use Get External Data
(dispite its name), located in the 'Data' tab of Excel 2010, to set up a connection
in a workbook to query data from itself. Use From Other Sources
From Microsoft Query
to connect to Excel
Once set up you can use VBA
to manipulate the connection
to, among other thing, view and modify the SQL command that drives the query. This query does reference the in memory workbook, so doen't require a save to refresh the latest data.
Here's a quick Sub
to demonstrate accessing the connection objects
Sub DemoConnection()
Dim c As Connections
Dim wb As Workbook
Dim i As Long
Dim strSQL As String
Set wb = ActiveWorkbook
Set c = wb.Connections
For i = 1 To c.Count
' Reresh the data
c(i).Refresh
' view the SQL query
strSQL = c(i).ODBCConnection.CommandText
MsgBox strSQL
Next
End Sub
I used update method to update my record.
models.users.update( { "name":'sam', "city":'USA' }, where:{ id:1 } )
Try this -
select * from table where id in (3,4) or [name] in ('andy','paul');
gt
= next Tap
gT
= previous Tab
The graphicx
package provides the command \resizebox{width}{height}{object}
:
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\hrule
%%%
\makeatletter%
\setlength{\@tempdima}{\the\columnwidth}% the, well columnwidth
\settowidth{\@tempdimb}{(\ref{Equ:TooLong})}% the width of the "(1)"
\addtolength{\@tempdima}{-\the\@tempdimb}% which cannot be used for the math
\addtolength{\@tempdima}{-1em}%
% There is probably some variable giving the required minimal distance
% between math and label, but because I do not know it I used 1em instead.
\addtolength{\@tempdima}{-1pt}% distance must be greater than "1em"
\xdef\Equ@width{\the\@tempdima}% space remaining for math
\begin{equation}%
\resizebox{\Equ@width}{!}{$\displaystyle{% to get everything inside "big"
A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z}$}%
\label{Equ:TooLong}%
\end{equation}%
\makeatother%
%%%
\hrule
\end{document}
If each user has its own SQL Server login you could try this
select
so.name, su.name, so.crdate
from
sysobjects so
join
sysusers su on so.uid = su.uid
order by
so.crdate
This works for me for the iphone 6
/*iPhone 6 Portrait*/
@media only screen and (min-device-width: 375px) and (max-device-width: 667px) and (orientation : portrait) {
}
/*iPhone 6 landscape*/
@media only screen and (min-device-width: 375px) and (max-device-width: 667px) and (orientation : landscape) {
}
/*iPhone 6+ Portrait*/
@media only screen and (min-device-width: 414px) and (max-device-width: 736px) and (orientation : portrait) {
}
/*iPhone 6+ landscape*/
@media only screen and (min-device-width: 414px) and (max-device-width: 736px) and (orientation : landscape) {
}
/*iPhone 6 and iPhone 6+ portrait and landscape*/
@media only screen and (max-device-width: 640px), only screen and (max-device-width: 667px), only screen and (max-width: 480px){
}
/*iPhone 6 and iPhone 6+ portrait*/
@media only screen and (max-device-width: 640px), only screen and (max-device-width: 667px), only screen and (max-width: 480px) and (orientation : portrait){
}
/*iPhone 6 and iPhone 6+ landscape*/
@media only screen and (max-device-width: 640px), only screen and (max-device-width: 667px), only screen and (max-width: 480px) and (orientation : landscape){
}
Just a thought, but Have you tried using application.undo
This will set the values back again. You can then simply read the original value. It should not be too difficult to store the new values first, so you change them back again if you like.
The problem was that the working copy was checked out via svn+ssh (thanks, Thomas). Instead of setting up ssh keys as was suggested, I just checked out a new working copy using svn://domain.com/path/to/repo rather than svn+ssh://domain.com/path/to/repo. Because this working copy is on the same machine as the repository itself, I'm not really missing out on anything, and I can now use the --password and --username options gratuitously. Seems obvious now that I think about it.
You can't do this: {this.state.arrayFromJson}
As your error suggests what you are trying to do is not valid. You are trying to render the whole array as a React child. This is not valid. You should iterate through the array and render each element. I use .map
to do that.
I am pasting a link from where you can learn how to render elements from an array with React.
http://jasonjl.me/blog/2015/04/18/rendering-list-of-elements-in-react-with-jsx/
Hope it helps!
In the adapter you can set the first item as disabled. Below is the sample code
@Override
public boolean isEnabled(int position) {
if (position == 0) {
// Disable the first item from Spinner
// First item will be use for hint
return false;
} else {
return true;
}
}
And set the first item to grey color.
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if (position == 0) {
// Set the hint text color gray
tv.setTextColor(Color.GRAY);
} else {
tv.setTextColor(Color.BLACK);
}
return view;
}
And if the user selects the first item then do nothing.
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedItemText = (String) parent.getItemAtPosition(position);
// If user change the default selection
// First item is disable and it is used for hint
if (position > 0) {
// Notify the selected item text
Toast.makeText(getApplicationContext(), "Selected : " + selectedItemText, Toast.LENGTH_SHORT).show();
}
}
Refer the below link for detail.
Follow the below steps it will helps you.
step 1: Go to to your site root folder and you can find the .htaccess
file there. Open it with a text editor and find the line #RewriteBase /magento/
. Just replace it with #RewriteBase /
take out just the 'magento/'
step 2: Then go to your admin panel and enable the Rewrites(set yes for Use Web Server Rewrites). You can find it at System->Configuration->Web->Search Engine Optimization.
step 3: Then go to Cache management page (system cache management ) and refresh your cache and refresh to check the site.
The second question is actually easier to answer. Look at the stringWithContentsOfURL:encoding:error:
method of NSString - it lets you pass in a URL as an instance of NSURL (which can easily be instantiated from NSString) and returns a string with the complete contents of the page at that URL. For example:
NSString *googleString = @"http://www.google.com";
NSURL *googleURL = [NSURL URLWithString:googleString];
NSError *error;
NSString *googlePage = [NSString stringWithContentsOfURL:googleURL
encoding:NSASCIIStringEncoding
error:&error];
After running this code, googlePage
will contain the HTML for www.google.com, and error
will contain any errors encountered in the fetch. (You should check the contents of error
after the fetch.)
Going the other way (from a UIWebView) is a bit trickier, but is basically the same concept. You'll have to pull the request from the view, then do the fetch as before:
NSURL *requestURL = [[yourWebView request] URL];
NSError *error;
NSString *page = [NSString stringWithContentsOfURL:requestURL
encoding:NSASCIIStringEncoding
error:&error];
EDIT: Both these methods take a performance hit, however, since they do the request twice. You can get around this by grabbing the content from a currently-loaded UIWebView using its stringByEvaluatingJavascriptFromString:
method, as such:
NSString *html = [yourWebView stringByEvaluatingJavaScriptFromString:
@"document.body.innerHTML"];
This will grab the current HTML contents of the view using the Document Object Model, parse the JavaScript, then give it to you as an NSString* of HTML.
Another way is to do your request programmatically first, then load the UIWebView from what you requested. Let's say you take the second example above, where you have NSString *page
as the result of a call to stringWithContentsOfURL:encoding:error:
. You can then push that string into the web view using loadHTMLString:baseURL:
, assuming you also held on to the NSURL you requested:
[yourWebView loadHTMLString:page baseURL:requestURL];
I'm not sure, however, if this will run JavaScript found in the page you load (the method name, loadHTMLString
, is somewhat ambiguous, and the docs don't say much about it).
For more info:
I already had running postgres on host machine and didn't want to allow connections from network, so I did run temporary postgres instance in container and created database in just two lines:
# Run PostgreSQL
docker run --name postgres-container -e POSTGRES_PASSWORD=password -it -p 5433:5432 postgres
# Create database
docker exec -it postgres-container createdb -U postgres my-db
This setting useOldUTF8Behavior=true worked fine for me. It gave no incorrect string errors but it converted special characters like à into multiple characters and saved in the database.
To avoid such situations, I removed this property from the JDBC parameter and instead converted the datatype of my column to BLOB. This worked perfect.
Try using below Query:
SELECT
GROUP,
COUNT(*) AS Total_Count
FROM
TABLE
GROUP BY
GROUP
ORDER BY
Total_Count DESC
Solution1:
Solution2: Restarting the device will also solve problem.
Solution3: Wait for 4 to 5 minutes will also works.
You don't have to track whether you've already changed the character from upper to lower. Your code is already doing that since it's basically:
1 for each character x:
2 if x is uppercase:
3 convert x to lowercase
4 else:
5 if x is lowercase:
6 convert x to uppercase.
The fact that you have that else
in there (on line 4) means that a character that was initially uppercase will never be checked in the second if
statement (on line 5).
Example, start with A
. Because that's uppercase, it will be converted to lowercase on line
3 and then you'll go back up to line 1 for the next character.
If you start with z
, the if
on line 2 will send you directly to line 5 where it will be converted to uppercase. Anything that's neither upper nor lowercase will fail both if
statements and therefore remain untouched.
Warning: This solution is deprecated since Angular 5.5, please refer to Trent's answer below
=====================
Yes, you need to import the operator:
import 'rxjs/add/operator/catch';
Or import Observable
this way:
import {Observable} from 'rxjs/Rx';
But in this case, you import all operators.
See this question for more details: