'raw string' means it is stored as it appears. For example, '\'
is just a backslash instead of an escaping.
Remember for jQuery 1.6+ you should use the .prop()
function.
$("input").prop('disabled', true);
$("input").prop('disabled', false);
You can also use the FileReader class :
var reader = new FileReader();
reader.onload = function (e) {
var data = this.result;
}
reader.readAsDataURL( file );
If you running windows 7 docker Registry
**Docker Quick Start terminal**
run (this terminal enables connection ) Until you pushed images , that will keep token alive .docker login
Make sure you tag the image with username
docker build -f Dockerfile -t 'username'/imagename
push image
docker image push username/imagename
Note: image name all lowercase
+
means "one or more characters" and without the plus it means "one character." In your case both result in the same output.
When your native query is based on joins, in that case you can get the result as list of objects and process it.
one simple example.
@Autowired
EntityManager em;
String nativeQuery = "select name,age from users where id=?";
Query query = em.createNativeQuery(nativeQuery);
query.setParameter(1,id);
List<Object[]> list = query.getResultList();
for(Object[] q1 : list){
String name = q1[0].toString();
//..
//do something more on
}
from Object import Object
or
From Class_Name import Class_name
If Object is a .py
file.
Similar problem - same error message. I got the same message when trying to clone something from bitbucket with ssh. The problem was in my ssh configuration configured in the mercurial.ini: I used the wrong bitbucket username. After I corrected the user name things worked.
Toast toast = Toast.makeText(this, "Custom toast creation", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT,0,0);
toast.show();
Feel free to disregard this solution as subtracting a list from an Index does not preserve the order of the original Index, if that's important.
In [61]: df.reindex(columns=pd.Index(['x', 'y']).append(df.columns - ['x', 'y']))
Out[61]:
x y a b
0 3 -1 1 2
1 6 -2 2 4
2 9 -3 3 6
3 12 -4 4 8
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
Depending on your requirements, you might use a Generic class like the one below to make access easier:
import java.util.ArrayList;
class TwoDimentionalArrayList<T> extends ArrayList<ArrayList<T>> {
public void addToInnerArray(int index, T element) {
while (index >= this.size()) {
this.add(new ArrayList<T>());
}
this.get(index).add(element);
}
public void addToInnerArray(int index, int index2, T element) {
while (index >= this.size()) {
this.add(new ArrayList<T>());
}
ArrayList<T> inner = this.get(index);
while (index2 >= inner.size()) {
inner.add(null);
}
inner.set(index2, element);
}
}
In swift3
you can easily remove optional
if let value = optionalvariable{
//in value you will get non optional value
}
You can do with json
.
In [124]: import json
In [125]: json.loads('false')
Out[125]: False
In [126]: json.loads('true')
Out[126]: True
Below is example to call synchronously but you can easily change to async by using await-sync:
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("login", "abc")
};
var content = new FormUrlEncodedContent(pairs);
var client = new HttpClient {BaseAddress = new Uri("http://localhost:6740")};
// call sync
var response = client.PostAsync("/api/membership/exist", content).Result;
if (response.IsSuccessStatusCode)
{
}
As explained on another answer using pandas.DataFrame()
directly here will not act as you think.
What you can do is use pandas.DataFrame.from_dict
with orient='index'
:
In[7]: pandas.DataFrame.from_dict({u'2012-06-08': 388,
u'2012-06-09': 388,
u'2012-06-10': 388,
u'2012-06-11': 389,
u'2012-06-12': 389,
.....
u'2012-07-05': 392,
u'2012-07-06': 392}, orient='index', columns=['foo'])
Out[7]:
foo
2012-06-08 388
2012-06-09 388
2012-06-10 388
2012-06-11 389
2012-06-12 389
........
2012-07-05 392
2012-07-06 392
I'm surprised none of these answers used the built in MVC features for this.
I wrote a blog post about this here, which even actually links the labels to the checkbox. I used the EditorTemplate folder to accomplish this in a clean and modular way.
You will simply end up with a new file in the EditorTemplate folder that looks like this:
@model SampleObject
@Html.CheckBoxFor(m => m.IsChecked)
@Html.HiddenFor(m => m.Id)
@Html.LabelFor(m => m.IsChecked, Model.Id)
in your actual view, there will be no need to loop this, simply 1 line of code:
@Html.EditorFor(x => ViewData.Model)
Visit my blog post for more details.
This will work to both load and save a file into TXT from a HTML page with a save as choice
<html>
<body>
<table>
<tr><td>Text to Save:</td></tr>
<tr>
<td colspan="3">
<textarea id="inputTextToSave" cols="80" rows="25"></textarea>
</td>
</tr>
<tr>
<td>Filename to Save As:</td>
<td><input id="inputFileNameToSaveAs"></input></td>
<td><button onclick="saveTextAsFile()">Save Text to File</button></td>
</tr>
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
</table>
<script type="text/javascript">
function saveTextAsFile()
{
var textToSave = document.getElementById("inputTextToSave").value;
var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
</script>
</body>
</html>
MySQL create function syntax:
DELIMITER //
CREATE FUNCTION GETFULLNAME(fname CHAR(250),lname CHAR(250))
RETURNS CHAR(250)
BEGIN
DECLARE fullname CHAR(250);
SET fullname=CONCAT(fname,' ',lname);
RETURN fullname;
END //
DELIMITER ;
Use This Function In Your Query
SELECT a.*,GETFULLNAME(a.fname,a.lname) FROM namedbtbl as a
SELECT GETFULLNAME("Biswarup","Adhikari") as myname;
Watch this Video how to create mysql function and how to use in your query
In .Net 2.0, you can use Console.Beep().
// Default beep
Console.Beep();
You can also specify the frequency and length of the beep in milliseconds.
// Beep at 5000 Hz for 1 second
Console.Beep(5000, 1000);
For more information refer http://msdn.microsoft.com/en-us/library/8hftfeyw%28v=vs.110%29.aspx
I think you're asking about a REPL (Read, Evaluate, Print, Loop) interface to perl. There are a few ways to do this:
Try below Alphanumeric regex
"^[a-zA-Z0-9]*$"
^ - Start of string
[a-zA-Z0-9]* - multiple characters to include
$ - End of string
See more: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
I've discovered in Excel 2007, if the results are a Table from an embedded query, the ss.000 does not work. I can paste the query results (from SQL Server Management Studio), and format the time just fine. But when I embed the query as a Data Connection in Excel, the format always gives .000 as the milliseconds.
You would need to add a property to your Production class and set it to point back at its parent, this doesn't exist by default.
You can deploy your angular application on github
using
angular-cli-ghpages
check out the link to find how to deploy using this cli.
the deployed website will be stored in some branch in github
typically
gh-pages
use can clone the git branch and use it like static website in your server
C is the bare-bones, simple, clean language that makes you do everything yourself. It doesn't hold your hand, it doesn't stop you from shooting yourself in the foot. But it has everything you need to do what you want.
C++ is C with classes added, and then a whole bunch of other things, and then some more stuff. It doesn't hold your hand, but it'll let you hold your own hand, with add-on GC, or RAII and smart-pointers. If there's something you want to accomplish, chances are there's a way to abuse the template system to give you a relatively easy syntax for it. (moreso with C++0x). This complexity also gives you the power to accidentally create a dozen instances of yourself and shoot them all in the foot.
C# is Microsoft's stab at improving on C++ and Java. Tons of syntactical features, but no where near the complexity of C++. It runs in a full managed environment, so memory management is done for you. It does let you "get dirty" and use unsafe code if you need to, but it's not the default, and you have to do some work to shoot yourself.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
The above links need to be included
<context:property-placeholder location="classpath:sport.properties" />
<bean id="myFortune" class="com.kiran.springdemo.HappyFortuneService"></bean>
<bean id="myCoach" class="com.kiran.springdemo.setterinjection.MyCricketCoach">
<property name="fortuner" ref="myFortune" />
<property name="emailAddress" value="${ipl.email}" />
<property name="team" value="${ipl.team}" />
</bean>
</beans>
This is how we do it in our application
def store_location
session[:return_to] = request.fullpath if request.get? and controller_name != "user_sessions" and controller_name != "sessions"
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
end
This way you only store last GET request in :return_to
session param, so all forms, even when multiple time POSTed would work with :return_to
.
var length = $('#selected ul').children('li').length
// or the same:
var length = $('#selected ul > li').length
You probably could also omit li
in the children's selector.
See .length
.
Maybe placing the jquery.ui.widget.js
as second after jquery.ui.core.js
.
I'm not completely sure how your data is handled, so this may or may not work, but have you considered paginating with a timestamp field?
When you query /foos you get 100 results. Your API should then return something like this (assuming JSON, but if it needs XML the same principles can be followed):
{
"data" : [
{ data item 1 with all relevant fields },
{ data item 2 },
...
{ data item 100 }
],
"paging": {
"previous": "http://api.example.com/foo?since=TIMESTAMP1"
"next": "http://api.example.com/foo?since=TIMESTAMP2"
}
}
Just a note, only using one timestamp relies on an implicit 'limit' in your results. You may want to add an explicit limit or also use an until
property.
The timestamp can be dynamically determined using the last data item in the list. This seems to be more or less how Facebook paginates in its Graph API (scroll down to the bottom to see the pagination links in the format I gave above).
One problem may be if you add a data item, but based on your description it sounds like they would be added to the end (if not, let me know and I'll see if I can improve on this).
When you make the input, set it to be readonly.
<input type="text" name="datepicker" id="datepicker" readonly="readonly" />
AkashG's solution don't work for me. When I set up check.xml to background it's just stratched in vertical direction. To solve this problem you should set up check.xml to "android:button" property:
<ToggleButton
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/check" //check.xml
android:background="@null"/>
check.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use grey -->
<item android:drawable="@drawable/selected_image"
android:state_checked="true" />
<!-- When not selected, use white-->
<item android:drawable="@drawable/unselected_image"
android:state_checked="false"/>
</selector>
Set up a batch file which you can invoke. Pass the path the batch file, and have the batch file set the environment variable and then invoke NUnit.
Write-Output
should be used when you want to send data on in the pipe line, but not necessarily want to display it on screen. The pipeline will eventually write it to out-default
if nothing else uses it first.
Write-Host
should be used when you want to do the opposite.
[console]::WriteLine
is essentially what Write-Host
is doing behind the scenes.
Run this demonstration code and examine the result.
function Test-Output {
Write-Output "Hello World"
}
function Test-Output2 {
Write-Host "Hello World" -foreground Green
}
function Receive-Output {
process { Write-Host $_ -foreground Yellow }
}
#Output piped to another function, not displayed in first.
Test-Output | Receive-Output
#Output not piped to 2nd function, only displayed in first.
Test-Output2 | Receive-Output
#Pipeline sends to Out-Default at the end.
Test-Output
You'll need to enclose the concatenation operation in parentheses, so that PowerShell processes the concatenation before tokenizing the parameter list for Write-Host
, or use string interpolation
write-host ("count=" + $count)
# or
write-host "count=$count"
BTW - Watch this video of Jeffrey Snover explaining how the pipeline works. Back when I started learning PowerShell I found this to be the most useful explanation of how the pipeline works.
You can do:
<form action="" method="post">
<table>
{% for field in form %}
<tr><td>{{field}}</td></tr>
{% endfor %}
</table>
<input type="submit" value="Submit">
</form>
Then you can add classes/id's to for example the <td>
tag. You can of course use any others tags you want. Check Working with Django forms as an example what is available for each field
in the form ({{field}}
for example is just outputting the input tag, not the label and so on).
You can rename a file using git
's mv
command:
$ git mv file_from file_to
Example:
$ git mv helo.txt hello.txt
$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# renamed: helo.txt -> hello.txt
#
$ git commit -m "renamed helo.txt to hello.txt"
[master 14c8c4f] renamed helo.txt to hello.txt
1 files changed, 0 insertions(+), 0 deletions(-)
rename helo.txt => hello.txt (100%)
Disclaimer: Avoid !important at all cost.
This is a dirty, dirty hack, but you can override an !important, without an !important, by using an (infinitely looping or very long lasting) animation on the property you're trying to override the importants on.
@keyframes forceYellow {_x000D_
from {_x000D_
background-color: yellow;_x000D_
}_x000D_
to {_x000D_
background-color: yellow;_x000D_
}_x000D_
}_x000D_
_x000D_
div {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
margin: 0 auto;_x000D_
background: red !important;_x000D_
animation: 1s linear infinite forceYellow;_x000D_
}
_x000D_
<div></div>
_x000D_
i use (and recommend):
$(document).attr("title", "Another Title");
and it works in IE as well this is an alias to
document.title = "Another Title";
Some will debate on wich is better, prop or attr, and since prop call DOM properties and attr Call HTML properties, i think this is actually better...
use this after the DOM Load
$(function(){
$(document).attr("title", "Another Title");
});
hope this helps.
This might help //Printing The Array
for (int i = 0; i < n; i++)
{cout << numbers[i];}
n is the size of the array
I think that is a bad solution, that opens up for race conditions. What if the process dies between your test and your call to kill? Then kill will fail. So why not just try the kill in all cases, and check its return value to find out how it went?
For the merge commit message, I found that I cannot amend it by using rebase
, at least on gitlab. It shows the merge as a commit but I cannot rebase onto that #sha. I found this post is helpful.
git checkout <sha of merge>
git commit --amend # edit message
git rebase HEAD previous_branch
This three lines of code did the job for changing the merge commit message (like author).
spring.data.mongodb.host
and spring.data.mongodb.port
are not supported if you’re using the Mongo 3.0 Java driver. In such cases, spring.data.mongodb.uri
should be used to provide all of the configuration, like this:
spring.data.mongodb.uri=mongodb://user:[email protected]:12345
dict
does not keep its elements' order. What you need is an OrderedDict: http://docs.python.org/library/collections.html#collections.OrderedDict
edit
Usage example:
>>> from collections import OrderedDict
>>> a = {'foo': 1, 'bar': 2}
>>> a
{'foo': 1, 'bar': 2}
>>> b = OrderedDict(sorted(a.items()))
>>> b
OrderedDict([('bar', 2), ('foo', 1)])
>>> b['foo']
1
>>> b['bar']
2
Best way is,
SELECT to_number(replace(:Str,',','')/100) --into num2
FROM dual;
Finally solved issue of reinitialization of select2 after ajax call.
You can call this in success function of ajax.
Note : Don't forget to replace ".selector" to your class of <select class="selector">
element.
jQuery('.select2-container').remove();
jQuery('.selector').select2({
placeholder: "Placeholder text",
allowClear: true
});
jQuery('.select2-container').css('width','100%');
You can use PyPdf2s PdfMerger
class.
File Concatenation
You can simply concatenate files by using the append
method.
from PyPDF2 import PdfFileMerger
pdfs = ['file1.pdf', 'file2.pdf', 'file3.pdf', 'file4.pdf']
merger = PdfFileMerger()
for pdf in pdfs:
merger.append(pdf)
merger.write("result.pdf")
merger.close()
You can pass file handles instead file paths if you want.
File Merging
If you want more fine grained control of merging there is a merge
method of the PdfMerger
, which allows you to specify an insertion point in the output file, meaning you can insert the pages anywhere in the file. The append
method can be thought of as a merge
where the insertion point is the end of the file.
e.g.
merger.merge(2, pdf)
Here we insert the whole pdf into the output but at page 2.
Page Ranges
If you wish to control which pages are appended from a particular file, you can use the pages
keyword argument of append
and merge
, passing a tuple in the form (start, stop[, step])
(like the regular range
function).
e.g.
merger.append(pdf, pages=(0, 3)) # first 3 pages
merger.append(pdf, pages=(0, 6, 2)) # pages 1,3, 5
If you specify an invalid range you will get an IndexError
.
Note: also that to avoid files being left open, the PdfFileMerger
s close method should be called when the merged file has been written. This ensures all files are closed (input and output) in a timely manner. It's a shame that PdfFileMerger
isn't implemented as a context manager, so we can use the with
keyword, avoid the explicit close call and get some easy exception safety.
You might also want to look at the pdfcat
script provided as part of pypdf2. You can potentially avoid the need to write code altogether.
The PyPdf2 github also includes some example code demonstrating merging.
right way is
import datetime
isinstance(x, datetime.date)
When I try this on my machine it works fine. You need to look into why datetime.date
is not a class. Are you perhaps masking it with something else? or not referencing it correctly for your import?
Quick and dirty way is to do a global search for '\n'
. You can filter it any way you like on file extensions etc.
Ctrl-Shift-F -> Text to find = '\n'
-> Find.
Edit: And 'regular expression' has to be checked.
The class
attribute can be used with multiple HTML elements/tags and all will take the effect. Where as the id
is meant for a single element/tag and is considered unique.
Moreoever the id
has a higher specificity value than the class
.
And another useful command to do this (after git fetch) is:
git log origin/master ^master
This shows the commits that are in origin/master but not in master. You can also do it in opposite when doing git pull, to check what commits will be submitted to remote.
You can use the following command:
git checkout HEAD -- my-file.txt
... which will update both the working copy of my-file.txt
and its state in the index with that from HEAD.
--
basically means: treat every argument after this point as a file name. More details in this answer. Thanks to VonC for pointing this out.
I think a solution is to put count in back ticks
.filter("`count` >= 2")
jQuery stores events in the following:
$("a#somefoo").data("events")
Doing a console.log($("a#somefoo").data("events"))
should list the events attached to that element.
This refers to the object you’re “in” right now. In other words,this refers to the receiving object. You use this to clarify which variable you’re referring to.Java_whitepaper page :37
class Point extends Object
{
public double x;
public double y;
Point()
{
x = 0.0;
y = 0.0;
}
Point(double x, double y)
{
this.x = x;
this.y = y;
}
}
In the above example code this.x/this.y refers to current class that is Point class x and y variables where (double x,double y) are double values passed from different class to assign values to current class .
This should do the trick:
$('#thisElement').find('.classToSelect')
Wireshark if you want to see everything going on in the network.
Fiddler if you want to just monitor HTTP/s traffic.
Live HTTP Headers if you're in Firefox and want a quick plugin just to see the headers.
Also FireBug can get you that information too and provides a nice interface when your working on a single page during development. I've used it to monitor AJAX transactions.
REM
Search for the CONFIG file, if this doesn't exit then the user doesn't have the .Net framework 2.0
`
SET FileName=%windir%\Microsoft.NET\Framework\v2.0.50727\CONFIG
IF EXIST %FileName% GOTO INSTALL_DIALER
ECHO.You currently do not have the Microsoft(c) .NET Framework 2.0 installed.
When you log on Windows creates an access token. This identifies you, the groups you are a member of and your privileges. And note that whether a user is an administrator or not is determined by whether the user is a member of the Administrators group.
Without UAC, when you run a program it gets a copy of the access token, and this controls what the program can access.
With UAC, when you run a program it gets a restricted access token. This is the original access token with "Administrators" removed from the list of groups (and some other changes). Even though your user is a member of the Administrators group, the program can't use Administrator privileges.
When you select "Run as Administrator" and your user is an administrator the program is launched with the original unrestricted access token. If your user is not an administrator you are prompted for an administrator account, and the program is run under that account.
In addition to the good advice already given, I would add this:
It is probably best to avoid using require()
unless you actually will be using the value it returns e.g in some error checking loop such as given by thierry.
In most other cases it is better to use library()
, because this will give an error message at package loading time if the package is not available. require()
will just fail without an error if the package is not there. This is the best time to find out if the package needs to be installed (or perhaps doesn't even exist because it it spelled wrong). Getting error feedback early and at the relevant time will avoid possible headaches with tracking down why later code fails when it attempts to use library routines
Use the WebRequest class
This is to get an image:
Try
Dim _WebRequest As System.Net.WebRequest = Nothing
_WebRequest = System.Net.WebRequest.Create(http://api.hostip.info/?ip=68.180.206.184)
Catch ex As Exception
Windows.Forms.MessageBox.Show(ex.Message)
Exit Sub
End Try
Try
_NormalImage = Image.FromStream(_WebRequest.GetResponse().GetResponseStream())
Catch ex As Exception
Windows.Forms.MessageBox.Show(ex.Message)
Exit Sub
End Try
You can place an AP overlay like...
#overlay {
position: absolute;
top: -79px;
left: -60px;
height: 80px;
width: 380px;
z-index: 2;
background: url(fake.gif);
}
<div id="overlay"></div>
just put it over where you dont want ie cliked. Works in all.
Python 3.6 windows7: There is several way to launch a python you could use the python console (which has a python logo on it) or the windows console (it's written cmd.exe on it).
I could not print utf8 characters in the windows console. Printing utf-8 characters throw me this error:
OSError: [winError 87] The paraneter is incorrect
Exception ignored in: (_io-TextIOwrapper name='(stdout)' mode='w' ' encoding='utf8')
OSError: [WinError 87] The parameter is incorrect
After trying and failing to understand the answer above I discovered it was only a setting problem. Right click on the top of the cmd console windows, on the tab font
chose lucida console.
You're defining the same class twice is why.
If your intent is to implement the methods in the CPP file then do so something like this:
gameObject::gameObject()
{
x = 0;
y = 0;
}
gameObject::~gameObject()
{
//
}
int gameObject::add()
{
return x+y;
}
That error means that a function call is only matched by an existing function if all its arguments are of the same type and passed in same order. So if the next f()
function
create function f() returns integer as $$
select 1;
$$ language sql;
is called as
select f(1);
It will error out with
ERROR: function f(integer) does not exist
LINE 1: select f(1);
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
because there is no f()
function that takes an integer as argument.
So you need to carefully compare what you are passing to the function to what it is expecting. That long list of table columns looks like bad design.
Could write a udf and take a value to tell it which day of the week should be 1 would look like this (drawing on answer from John to use MOD instead of CASE):
DROP FUNCTION IF EXISTS `reporting`.`udfDayOfWeek`;
DELIMITER |
CREATE FUNCTION `reporting`.`udfDayOfWeek` (
_date DATETIME,
_firstDay TINYINT
) RETURNS tinyint(4)
FUNCTION_BLOCK: BEGIN
DECLARE _dayOfWeek, _offset TINYINT;
SET _offset = 8 - _firstDay;
SET _dayOfWeek = (DAYOFWEEK(_date) + _offset) MOD 7;
IF _dayOfWeek = 0 THEN
SET _dayOfWeek = 7;
END IF;
RETURN _dayOfWeek;
END FUNCTION_BLOCK
To call this function to give you the current day of week value when your week starts on a Tuesday for instance, you'd call:
SELECT udfDayOfWeek(NOW(), 3);
Nice thing about having it as a udf is you could also call it on a result set field like this:
SELECT
udfDayOfWeek(p.SignupDate, 3) AS SignupDayOfWeek,
p.FirstName,
p.LastName
FROM Profile p;
You can be used this step is very useful:
for i in `ls -l folder1 | grep -v total | awk '{print $ ( ? )}'`
do
cd folder1
cp $i folder2/$i.`date +%m%d%Y`
done
Your error is quite literally saying "you're trying to use Windows Authentication, but your login isn't from a trusted domain". Which is odd, because you're connecting to the local machine.
Perhaps you're logged into Windows using a local account rather than a domain account? Ensure that you're logging in with a domain account that is also a SQL Server principal on your SQL2008 instance.
I used the RowHeight
property of a range (which means cells as well). If it's zero then it's hidden.
So just loop through all rows as you would normally but in the if
condition check for that property as in If myRange.RowHeight > 0 then DoStuff
where DoStuff
is something you want to do with the visible cells.
You must use Rect.width()
and Rect.Height()
which returned from getTextBounds()
instead. That works for me.
Use the following
<div style="max-width:980px; overflow-x: scroll; white-space: nowrap;">
<table border="1" style="cellpadding:0; cellspacing:0; border:0; width=:100%;" >
Althugh you asked for Google Maps API, I suggest an open source, working, legal, free and crowdsourced API by Open street maps
https://nominatim.openstreetmap.org/search?q=Mumbai&format=json
Here is the API documentation for reference.
Edit: It looks like there are discrepancies occasionally, at least in terms of postal codes, when compared to the Google Maps API, and the latter seems to be more accurate. This was the case when validating addresses in Canada with the Canada Post search service, however, it might be true for other countries too.
There is a very nice PHP library for detecting mobile clients here: http://mobiledetect.net
Using that it's quite easy to only display content for a mobile:
include 'Mobile_Detect.php';
$detect = new Mobile_Detect();
// Check for any mobile device.
if ($detect->isMobile()){
// mobile content
}
else {
// other content for desktops
}
$gender = $_POST['gender'];
echo $gender;
it will echoes the selected value.
scope.$watch returns a function that you can call and that will unregister the watch.
Something like:
var unbindWatch = $scope.$watch("myvariable", function() {
//...
});
setTimeout(function() {
unbindWatch();
}, 1000);
I quote from http://www.php.net/manual/en/language.oop5.visibility.php
Note: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an
E_STRICT
warning.
I had the same when following MvcMusicStore Tutorial in Part 4 and replaced the given connection String with this:
add name="MusicStoreEntities" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;database=MvcMusicStore;User ID=sa;password=" providerName="System.Data.SqlClient"/>
It worked for me.
Use array notation like name="checkbox[]"
in your input
element. This will give you $_POST['checkbox']
as array. In the query you can utilize it as
$sql = "DELETE FROM links WHERE link_id in ";
$sql.= "('".implode("','",array_values($_POST['checkbox']))."')";
Thats one single query to delete them all.
Note: You need to escape the values passed in $_POST['checkbox']
with mysql_real_escape_string
or similar to prevent SQL Injection.
Why parse the query string yourself when you can let the browser do it for you?
function changeQS(key, value) {
let urlParams = new URLSearchParams(location.search.substr(1));
urlParams.set(key, value);
location.search = urlParams.toString();
}
Use this:
$('a[href^="#"]').on('click', function(event) {
var target = $( $(this).attr('href') );
if( target.length ) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 500);
}
});
It appears that my max ports weren't configured correctly. I ran the following code and it worked...
echo fs.inotify.max_user_watches=582222 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
What this command does is to increase the number of watches allowed for a single user. By the default the number can be low (8192 for example). When nodemon
tries to watch large numbers of directories for changes it has to create several watches, which can surpass that limit.
You could also solve this problem by:
sudo sysctl fs.inotify.max_user_watches=582222 && sudo sysctl -p
But the way it was written first will make this change permanent.
You can use gridspec
and figure
:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
fig = plt.figure(figsize=(8, 6))
gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1])
ax0 = plt.subplot(gs[0])
ax0.plot(x, y)
ax1 = plt.subplot(gs[1])
ax1.plot(y, x)
plt.tight_layout()
plt.savefig('grid_figure.pdf')
if you want to get text of a selected option (chosen get display selected value)
$("#select-id").chosen().find("option:selected" ).text();
Your insertion function assumes that the given array is sorted, it searches directly for the location where the new element can be inserted, usually by just looking at a few of the elements in the array.
The general sort function of an array can't take these shortcuts. Obviously it at least has to inspect all elements in the array to see if they are already correctly ordered. This fact alone makes the general sort slower than the insertion function.
A generic sort algorithm is usually on average O(n ⋅ log(n)) and depending on the implementation it might actually be the worst case if the array is already sorted, leading to complexities of O(n2). Directly searching for the insertion position instead has just a complexity of O(log(n)), so it will always be much faster.
Please read the whole answer before attempting to run with sudo
Try running sudo /dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme
The sudo command executes the commands which follow it with 'superuser' or 'root' privileges. This should allow you to execute almost anything from the command line. That said, DON'T DO THIS! If you are running a script on your computer and don't need it to access core components of your operating system (I'm guessing you're not since you are invoking the script on something inside your home directory (~/)), then it should be running from your home directory, ie:
~/dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme
Move it to ~/ or a sub directory and execute from there. You should never have permission issues there and there wont be a risk of it accessing or modifying anything critical to your OS.
If you are still having problems you can check the permissions on the file by running ls -l
while in the same directory as the ruby script. You will get something like this:
$ ls -l
total 13
drwxr-xr-x 4 or019268 Administ 12288 Apr 10 18:14 TestWizard
drwxr-xr-x 4 or019268 Administ 4096 Aug 27 12:41 Wizard.Controls
drwxr-xr-x 5 or019268 Administ 8192 Sep 5 00:03 Wizard.UI
-rw-r--r-- 1 or019268 Administ 1375 Sep 5 00:03 readme.txt
You will notice that the readme.txt file says -rw-r--r--
on the left. This shows the permissions for that file. The 9 characters from the right can be split into groups of 3 characters of 'rwx' (read, write, execute). If I want to add execute rights to this file I would execute chmod 755 readme.txt
and that permissions portion would become rwxr-xr-x
. I can now execute this file if I want to by running ./readme.txt
(./ tells the bash to look in the current directory for the intended command rather that search the $PATH variable).
schluchc alludes to looking at the man page for chmod, do this by running man chmod
. This is the best way to get documentation on a given command, man <command>
In short you have to do like this
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "https://maven.fabric.io/public" }
}
Detail:
You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:
apply plugin: 'java'
sourceCompatibility = 1.7
version = '1.0'
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "http://maven.restlet.org" }
mavenCentral()
}
dependencies {
compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
testCompile group:'junit', name:'junit', version:'4.11'
}
TL;DR:
A DTO describes the pattern of state transfer. A POCO doesn't describe anything. It's another way of saying "object" in OOP. It comes from POJO (Java), coined by Martin Fowler who literally just describes it as a fancier name for 'object' because 'object' isn't very sexy.
A DTO is an object pattern used to transfer state between layers of concern. They can have behavior (i.e. can technically be a poco) so long as that behavior doesn't mutate the state. For example, it may have a method that serializes itself.
A POCO is a plain object, but what is meant by 'plain' is that it is not special. It just means it's a CLR object with no implied pattern to it. A generic term. It isn't made to work with some other framework. So if your POCO has [JsonProperty]
or EF decorations all over it's properties, for example, then it I'd argue that it isn't a POCO.
Here some examples of different kinds of object patterns to compare:
These are all just objects, but notice that most of them are generally tied to a pattern. So you could call them "objects" or you could be more specific about its intent and call it by what it is. This is also why we have design patterns; to describe complex concepts in a few works. DTO is a pattern. Aggregate root is a pattern, View Model is a pattern (e.g. MVC & MVVM). POCO is not a pattern.
A POCO doesn't describe a pattern. It is just a different way of referring to classes/objects in OOP. Think of it as an abstract concept; they can be referring to anything. IMO, there's a one-way relationship though because once an object reaches the point where it can only serve one purpose cleanly, it is no longer a POCO. For example, once you mark up your class with decorations to make it work with some framework, it is no longer a POCO. Therefore:
The point in making a distinction between the two is about keeping patterns clear and consistent in effort to not cross concerns and lead to tight coupling. For example if you have a business object that has methods to mutate state, but is also decorated to hell with EF decorations for saving to SQL Server AND JsonProperty so that it can be sent back over an API endpoint. That object would be intolerant to change, and would likely be littered with variants of properties (e.g. UserId, UserPk, UserKey, UserGuid, where some of them are marked up to not be saved to the DB and others marked up to not be serialized to JSON at the API endpoint).
So if you were to tell me something was a DTO, then I'd probably make sure it was never used for anything other than moving state around. If you told me something was a view model, then I'd probably make sure it wasn't getting saved to a database. If you told me something was a Domain Model, then I'd probably make sure it had no dependencies on anything outside of the domain. But if you told me something was a POCO, you wouldn't really be telling me much at all.
Another python3 implementation that involves the use of Abstract classes with super(). You should remember that
super().__init__(name, 10)
has the same effect as
Person.__init__(self, name, 10)
Remember there's a hidden 'self' in super(), So the same object passes on to the superclass init method and the attributes are added to the object that called it.
Hence super()
gets translated to Person
and then if you include the hidden self, you get the above code frag.
from abc import ABCMeta, abstractmethod
class Person(metaclass=ABCMeta):
name = ""
age = 0
def __init__(self, personName, personAge):
self.name = personName
self.age = personAge
@abstractmethod
def showName(self):
pass
@abstractmethod
def showAge(self):
pass
class Man(Person):
def __init__(self, name, height):
self.height = height
# Person.__init__(self, name, 10)
super().__init__(name, 10) # same as Person.__init__(self, name, 10)
# basically used to call the superclass init . This is used incase you want to call subclass init
# and then also call superclass's init.
# Since there's a hidden self in the super's parameters, when it's is called,
# the superclasses attributes are a part of the same object that was sent out in the super() method
def showIdentity(self):
return self.name, self.age, self.height
def showName(self):
pass
def showAge(self):
pass
a = Man("piyush", "179")
print(a.showIdentity())
If you are on a linux machine running Python 2 you can run this commands:
1st make sure python 2 is installed:
python2 --version
2nd check to see if pip is installed:
pip --version
If you are running Python 3 you can run this command:
1st make sure python 3 is installed:
python3 --version
2nd check to see if pip3 is installed:
pip3 --version
If you do not have pip installed you can run these commands to install pip (it is recommended you install pip for Python 2 and Python 3):
Install pip for Python 2:
sudo apt install python-pip
Then verify if it is installed correctly:
pip --version
Install pip for Python 3:
sudo apt install python3-pip
Then verify if it is installed correctly:
pip3 --version
For more info see: https://itsfoss.com/install-pip-ubuntu/
UPDATE
I would like to mention a few things. When working with Django I learned that my Linux install requires me to use python 2.7, so switching my default python version for the python
and pip
command alias's to python 3 with alias python=python3
is not recommended. Therefore I use the python3
and pip3
commands when installing software like Django 3.0, which works better with Python 3. And I keep their alias's pointed towards whatever Python 3 version I want like so alias python3=python3.8
.
Keep In Mind
When you are going to use your package in the future you will want to use the pip
or pip3
command depending on which one you used to initially install the package. So for example if I wanted to change my change my Django package version I would use the pip3
command and not pip
like so, pip3 install Django==3.0.11
.
Notice
When running checking the packages version for python: $ python -m django --version
and python3: $ python3 -m django --version
, two different versions of django will show because I installed django v3.0.11 with pip3
and django v1.11.29 with pip
.
Not exactly zipping, but you can compact files in Windows with the compact command:
compact /c /s:<directory or file>
And to uncompress:
compact /u /s:<directory or file>
NOTE: These commands only mark/unmark files or directories as compressed in the file system. They do not produces any kind of archive (like zip, 7zip, rar, etc.)
You can use numpy.shape
.
import numpy as np
x = np.array([[1, 2],[3, 4],[5, 6]])
Result:
>>> x
array([[1, 2],
[3, 4],
[5, 6]])
>>> np.shape(x)
(3, 2)
First value in the tuple is number rows = 3; second value in the tuple is number of columns = 2.
Your "localhost" cannot resolve the name www.google.com, which means your machine doesn't/can't reach a valid dns server.
Try ping google.com on the console of that machine to verify this.
Minimal POSIX C exit status example
To understand $?
, you must first understand the concept of process exit status which is defined by POSIX. In Linux:
when a process calls the exit
system call, the kernel stores the value passed to the system call (an int
) even after the process dies.
The exit system call is called by the exit()
ANSI C function, and indirectly when you do return
from main
.
the process that called the exiting child process (Bash), often with fork
+ exec
, can retrieve the exit status of the child with the wait
system call
Consider the Bash code:
$ false
$ echo $?
1
The C "equivalent" is:
false.c
#include <stdlib.h> /* exit */
int main(void) {
exit(1);
}
bash.c
#include <unistd.h> /* execl */
#include <stdlib.h> /* fork */
#include <sys/wait.h> /* wait, WEXITSTATUS */
#include <stdio.h> /* printf */
int main(void) {
if (fork() == 0) {
/* Call false. */
execl("./false", "./false", (char *)NULL);
}
int status;
/* Wait for a child to finish. */
wait(&status);
/* Status encodes multiple fields,
* we need WEXITSTATUS to get the exit status:
* http://stackoverflow.com/questions/3659616/returning-exit-code-from-child
**/
printf("$? = %d\n", WEXITSTATUS(status));
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o bash bash.c
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o false false.c
./bash
Output:
$? = 1
In Bash, when you hit enter, a fork + exec + wait happens like above, and bash then sets $?
to the exit status of the forked process.
Note: for built-in commands like echo
, a process need not be spawned, and Bash just sets $?
to 0 to simulate an external process.
Standards and documentation
POSIX 7 2.5.2 "Special Parameters" http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_05_02 :
? Expands to the decimal exit status of the most recent pipeline (see Pipelines).
man bash
"Special Parameters":
The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed. [...]
? Expands to the exit status of the most recently executed foreground pipeline.
ANSI C and POSIX then recommend that:
0
means the program was successful
other values: the program failed somehow.
The exact value could indicate the type of failure.
ANSI C does not define the meaning of any vaues, and POSIX specifies values larger than 125: What is the meaning of "POSIX"?
Bash uses exit status for if
In Bash, we often use the exit status $?
implicitly to control if
statements as in:
if true; then
:
fi
where true
is a program that just returns 0.
The above is equivalent to:
true
result=$?
if [ $result = 0 ]; then
:
fi
And in:
if [ 1 = 1 ]; then
:
fi
[
is just an program with a weird name (and Bash built-in that behaves like it), and 1 = 1 ]
its arguments, see also: Difference between single and double square brackets in Bash
Import view and wrap in View
. Wrapping in a div
did not work for me.
import { View } from 'react-native';
...
render() {
return (
<View>
<h1>foo</h1>
<h2>bar</h2>
</View>
);
}
If you cannot disable the expose_php directive to mute PHP’s talkativeness (requires access to the php.ini), you could use Apache’s Header
directive to remove the header field:
Header unset X-Powered-By
You can consider this project: https://github.com/fengdai/AlertDialogPro
It can provide you material theme alert dialogs almost the same as lollipop's. Compatible with Android 2.1.
If you are using Spring 3.0, an easy way to avoid the org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type exception, is to include the jackson jar files in your classpath, and use mvc:annotation-driven
config element. As specified here.
I was pulling my hair out trying to figure out why the mvc-ajax app worked without any special config for the MappingJacksonHttpMessageConverter
. If you read the article I linked above closely:
Underneath the covers, Spring MVC delegates to a HttpMessageConverter to perform the serialization. In this case, Spring MVC invokes a MappingJacksonHttpMessageConverter built on the Jackson JSON processor. This implementation is enabled automatically when you use the mvc:annotation-driven configuration element with Jackson present in your classpath.
For the problem you're having about the batch file asking the user if the destination is a folder or file, if you know the answer in advance, you can do as such:
If destination is a file: echo f | [batch file path]
If folder: echo d | [batch file path]
It will essentially just pipe the letter after "echo" to the input of the batch file.
Many in the community would prefer no limit with warnings about performance, see this comment for a well reasoned argument: https://jira.mongodb.org/browse/SERVER-431?focusedCommentId=22283&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-22283
My take, the lead developers are stubborn about this issue because they decided it was an important "feature" early on. They're not going to change it anytime soon because their feelings are hurt that anyone questioned it. Another example of personality and politics detracting from a product in open source communities but this is not really a crippling issue.
Also, this might help finding the actual location the btsnoop_hci.log is being saved:
adb shell "cat /etc/bluetooth/bt_stack.conf | grep FileName"
Encapsulation require modularity. It requires you to create objects that has the data and the methods to process the data. In this case you can view it as a module.
Abstraction provides you a generalized view of your classes.
For Numbers with leading zeroes and comma separated:
You can put 'A' to affect the entire column'.
$objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
Then you can write to the cell as you normally would.
Public Function TestError() As String()
Return {"foo", "bar"}
End Function
Works fine for me and should work for you, but you may need allow using implicit declarations in your project. I believe this is turning off Options strict in the Compile section of the program settings.
Since you are using VS 2008 (VB.NET 9.0) you have to declare create the new instance
New String() {"foo", "Bar"}
You can also use df.assign
:
In [1559]: df
Out[1559]:
A B C
0 0 NaN NaN
1 4 NaN NaN
2 5 NaN NaN
3 6 NaN NaN
4 7 NaN NaN
5 7 NaN NaN
6 6 NaN NaN
7 5 NaN NaN
In [1560]: mylist = [2,5,6,8,12,16,26,32]
In [1567]: df = df.assign(D=mylist)
In [1568]: df
Out[1568]:
A B C D
0 0 NaN NaN 2
1 4 NaN NaN 5
2 5 NaN NaN 6
3 6 NaN NaN 8
4 7 NaN NaN 12
5 7 NaN NaN 16
6 6 NaN NaN 26
7 5 NaN NaN 32
I suspect you haven't set up last_name
properly in the caller.
With the statement Worksheets(data_sheet).Range("C2").Value = ProcessString(last_name)
this will only work if last_name
is a string, i.e.
Dim last_name as String
appears in the caller somewhere.
The reason for this is that VBA passes in variables by reference by default which means that the data types have to match exactly between caller and callee.
1) Force ByVal -- Change your function to pass variable ByVal: Public Function ProcessString(ByVal input_string As String) As String
, or
2) Dim varname -- put Dim last_name As String
in the caller before you use it.
(1) works because for ByVal
, a copy of input_string is taken when passing to the function which will coerce it into the correct data type. It also leads to better program stability since the function cannot modify the variable in the caller.
I believe it was already mentioned in other threads:
calc(){ awk "BEGIN { print "$*" }"; }
then you can simply type :
calc 7.5/3.2
2.34375
In your case it will be:
x=20; y=3;
calc $x/$y
or if you prefer, add this as a separate script and make it available in $PATH so you will always have it in your local shell:
#!/bin/bash
calc(){ awk "BEGIN { print $* }"; }
When converting datetime to integers one must keep in mind the tens, hundreds and thousands.... like "2018-11-03" must be like 20181103 in int for that you have to 2018*10000 + 100* 11 + 3
Similarly another example, "2018-11-03 10:02:05" must be like 20181103100205 in int
dt = datetime(2018,11,3,10,2,5)
print (dt)
#print (dt.timestamp()) # unix representation ... not useful when converting to int
print (dt.strftime("%Y-%m-%d"))
print (dt.year*10000 + dt.month* 100 + dt.day)
print (int(dt.strftime("%Y%m%d")))
print (dt.strftime("%Y-%m-%d %H:%M:%S"))
print (dt.year*10000000000 + dt.month* 100000000 +dt.day * 1000000 + dt.hour*10000 + dt.minute*100 + dt.second)
print (int(dt.strftime("%Y%m%d%H%M%S")))
To avoid that doing manually use below function
def datetime_to_int(dt):
return int(dt.strftime("%Y%m%d%H%M%S"))
Had the same problem, it was indeed caused by weblogic stupidly using its own opensaml implementation. To solve it, you have to tell it to load classes from WEB-INF/lib
for this package in weblogic.xml
:
<prefer-application-packages>
<package-name>org.opensaml.*</package-name>
</prefer-application-packages>
maybe <prefer-web-inf-classes>true</prefer-web-inf-classes>
would work too.
Remove existing files from the repository:
find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch
Add the line
.DS_Store
to the file .gitignore
, which can be found at the top level of your repository (or created if it isn't there already). You can do this easily with this command in the top directory
echo .DS_Store >> .gitignore
Then
git add .gitignore
git commit -m '.DS_Store banished!'
(JavaScript) Using regexp, this checks for alphanumeric palindrome and disregards space and punctuation.
function palindrome(str) {
str = str.match(/[A-Za-z0-9]/gi).join("").toLowerCase();
// (/[A-Za-z0-9]/gi) above makes str alphanumeric
for(var i = 0; i < Math.floor(str.length/2); i++) { //only need to run for half the string length
if(str.charAt(i) !== str.charAt(str.length-i-1)) { // uses !== to compare characters one-by-one from the beginning and end
return "Try again.";
}
}
return "Palindrome!";
}
palindrome("A man, a plan, a canal. Panama.");
//palindrome("4_2 (: /-\ :) 2-4"); // This solution would also work on something like this.
You can try to host the analytics.js locally and update it's contents with a caching script or manually.
The js file is updated only few times a year and if you don't need any new tracking features update it manually.
https://developers.google.com/analytics/devguides/collection/analyticsjs/changelog
I use this css positioning for most of my vertical elements:
<div class="vertical-line" style="height: 250px;
width: 1px;
background-color: #81F781;
margin-left: 0px;
margin-top: -100px;
postion: absolute;
border-radius: 2px;">
</div>
Change the height and width to fit the page, or to make a horizontal line swap the height to width:
<div class="vertical-line" style="height: 250px;
width: 1px;
<div class="vertical-line" style="width: 250px;
height: 1px;
instead of a standard html line.
First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="file">
<input type="submit" value="Submit">
</form>
Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:
const http = require("http");
const path = require("path");
const fs = require("fs");
const express = require("express");
const app = express();
const httpServer = http.createServer(app);
const PORT = process.env.PORT || 3000;
httpServer.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));
Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).
In Express 3.x you could use express.bodyParser
middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:
You need to define a route to handle form posts:
const multer = require("multer");
const handleError = (err, res) => {
res
.status(500)
.contentType("text/plain")
.end("Oops! Something went wrong!");
};
const upload = multer({
dest: "/path/to/temporary/directory/to/store/uploaded/files"
// you might also want to set some limits: https://github.com/expressjs/multer#limits
});
app.post(
"/upload",
upload.single("file" /* name attribute of <file> element in your form */),
(req, res) => {
const tempPath = req.file.path;
const targetPath = path.join(__dirname, "./uploads/image.png");
if (path.extname(req.file.originalname).toLowerCase() === ".png") {
fs.rename(tempPath, targetPath, err => {
if (err) return handleError(err, res);
res
.status(200)
.contentType("text/plain")
.end("File uploaded!");
});
} else {
fs.unlink(tempPath, err => {
if (err) return handleError(err, res);
res
.status(403)
.contentType("text/plain")
.end("Only .png files are allowed!");
});
}
}
);
In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.
In order to show the uploaded image, assuming you already have an HTML page containing an img element:
<img src="/image.png" />
you can define another route in your express app and use res.sendFile
to serve the stored image:
app.get("/image.png", (req, res) => {
res.sendFile(path.join(__dirname, "./uploads/image.png"));
});
I'm not an SQL expert so bear with me. I'm sure you'll get a better answer soon enough. Here's how you can find the duplicate records.
select t1.empid, t1.empssn, count(*)
from employee as t1
inner join employee as t2 on (t1.empid=t2.empid and t1.empssn = t2.empssn)
group by t1.empid, t1.empssn
having count(*) > 1
Deleting them will be more tricky because there is nothing in the data that you could use in a delete statement to differentiate the duplicates. I suspect the answer will involve row_number() or adding an identity column.
import pandas as pd
import io
texts = ['''\
id Name score isEnrolled Comment
111 Jack 2.17 True He was late to class
112 Nick 1.11 False Graduated
113 Zoe 4.12 True ''',
'''\
id Name score isEnrolled Comment
111 Jack 2.17 True He was late to class
112 Nick 1.21 False Graduated
113 Zoe 4.12 False On vacation''']
df1 = pd.read_fwf(io.StringIO(texts[0]), widths=[5,7,25,21,20])
df2 = pd.read_fwf(io.StringIO(texts[1]), widths=[5,7,25,21,20])
df = pd.concat([df1,df2])
print(df)
# id Name score isEnrolled Comment
# 0 111 Jack 2.17 True He was late to class
# 1 112 Nick 1.11 False Graduated
# 2 113 Zoe 4.12 True NaN
# 0 111 Jack 2.17 True He was late to class
# 1 112 Nick 1.21 False Graduated
# 2 113 Zoe 4.12 False On vacation
df.set_index(['id', 'Name'], inplace=True)
print(df)
# score isEnrolled Comment
# id Name
# 111 Jack 2.17 True He was late to class
# 112 Nick 1.11 False Graduated
# 113 Zoe 4.12 True NaN
# 111 Jack 2.17 True He was late to class
# 112 Nick 1.21 False Graduated
# 113 Zoe 4.12 False On vacation
def report_diff(x):
return x[0] if x[0] == x[1] else '{} | {}'.format(*x)
changes = df.groupby(level=['id', 'Name']).agg(report_diff)
print(changes)
prints
score isEnrolled Comment
id Name
111 Jack 2.17 True He was late to class
112 Nick 1.11 | 1.21 False Graduated
113 Zoe 4.12 True | False nan | On vacation
One of the best online tools currently available to extract pdf fonts is http://www.pdfconvertonline.com/extract-pdf-fonts-online.html
Pickle is great but I think it's worth mentioning literal_eval
from the ast
module for an even lighter weight solution if you're only serializing basic python types. It's basically a "safe" version of the notorious eval
function that only allows evaluation of basic python types as opposed to any valid python code.
Example:
>>> d = {}
>>> d[0] = range(10)
>>> d['1'] = {}
>>> d['1'][0] = range(10)
>>> d['1'][1] = 'hello'
>>> data_string = str(d)
>>> print data_string
{0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], '1': {0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 1: 'hello'}}
>>> from ast import literal_eval
>>> d == literal_eval(data_string)
True
One benefit is that the serialized data is just python code, so it's very human friendly. Compare it to what you would get with pickle.dumps
:
>>> import pickle
>>> print pickle.dumps(d)
(dp0
I0
(lp1
I0
aI1
aI2
aI3
aI4
aI5
aI6
aI7
aI8
aI9
asS'1'
p2
(dp3
I0
(lp4
I0
aI1
aI2
aI3
aI4
aI5
aI6
aI7
aI8
aI9
asI1
S'hello'
p5
ss.
The downside is that as soon as the the data includes a type that is not supported by literal_ast
you'll have to transition to something else like pickling.
You are mixing mysqli
and mysql
function.
If your are using mysql function then instead mysqli_real_escape_string($your_variable);
use
$username = mysql_real_escape_string($_POST['username']);
$pass = mysql_real_escape_string($_POST['pass']);
$pass1 = mysql_real_escape_string($_POST['pass1']);
$email = mysql_real_escape_string($_POST['email']);
If your using mysqli_* function then you have to include your connection to database into mysqli_real_escape function :
$username = mysqli_real_escape_string($your_connection, $_POST['username']);
$pass = mysqli_real_escape_string($your_connection, $_POST['pass']);
$pass1 = mysqli_real_escape_string($your_connection, $_POST['pass1']);
$email = mysqli_real_escape_string($your_connection, $_POST['email']);
Note : Use mysqli_* function since mysql has been deprecated. For information please read mysqli_*
Use Controller to render your normal views. ApiController action only return data that is serialized and sent to the client.
Quote:
Note If you have worked with ASP.NET MVC, then you are already familiar with controllers. They work similarly in Web API, but controllers in Web API derive from the ApiController class instead of Controller class. The first major difference you will notice is that actions on Web API controllers do not return views, they return data.
ApiControllers are specialized in returning data. For example, they take care of transparently serializing the data into the format requested by the client. Also, they follow a different routing scheme by default (as in: mapping URLs to actions), providing a REST-ful API by convention.
You could probably do anything using a Controller instead of an ApiController with the some(?) manual coding. In the end, both controllers build upon the ASP.NET foundation. But having a REST-ful API is such a common requirement today that WebAPI was created to simplify the implementation of a such an API.
It's fairly simple to decide between the two: if you're writing an HTML based web/internet/intranet application - maybe with the occasional AJAX call returning json here and there - stick with MVC/Controller. If you want to provide a data driven/REST-ful interface to a system, go with WebAPI. You can combine both, of course, having an ApiController cater AJAX calls from an MVC page.
To give a real world example: I'm currently working with an ERP system that provides a REST-ful API to its entities. For this API, WebAPI would be a good candidate. At the same time, the ERP system provides a highly AJAX-ified web application that you can use to create queries for the REST-ful API. The web application itself could be implemented as an MVC application, making use of the WebAPI to fetch meta-data etc.
maybe system install jdk package, but maybe some devel tools or plugin.
I find this problem under opensuse env. and I install java-1_6_0-openjdk-devel
the problem is disppeared..
nohup some_command &> nohup2.out &
and voila.
Older syntax for Bash version < 4:
nohup some_command > nohup2.out 2>&1 &
Another option is to inherit from the appropriate abstract base class from the `collections module as documented here.
In case the container is its own iterator, you can inherit from
collections.Iterator
. You only need to implement the next
method then.
An example is:
>>> from collections import Iterator
>>> class MyContainer(Iterator):
... def __init__(self, *data):
... self.data = list(data)
... def next(self):
... if not self.data:
... raise StopIteration
... return self.data.pop()
...
...
...
>>> c = MyContainer(1, "two", 3, 4.0)
>>> for i in c:
... print i
...
...
4.0
3
two
1
While you are looking at the collections
module, consider inheriting from Sequence
, Mapping
or another abstract base class if that is more appropriate. Here is an example for a Sequence
subclass:
>>> from collections import Sequence
>>> class MyContainer(Sequence):
... def __init__(self, *data):
... self.data = list(data)
... def __getitem__(self, index):
... return self.data[index]
... def __len__(self):
... return len(self.data)
...
...
...
>>> c = MyContainer(1, "two", 3, 4.0)
>>> for i in c:
... print i
...
...
1
two
3
4.0
NB: Thanks to Glenn Maynard for drawing my attention to the need to clarify the difference between iterators on the one hand and containers that are iterables rather than iterators on the other.
I've found a solution that works for me.
In My Device (Nexus 7) Android 5.0. Lollipop I follow these steps.
After Uninstalling App You will find App Name
under Apps List of the Downloaded
tab.
YourApp
with a "NOT INSTALLED" Tag OptionMenu
and Select "Uninstall for all Users"After these steps, I successfully install the new app and it's running well.
just add C:\Program Files\Java\jdk1.7.0_80\bin as the path in environmental variables. no need to add java.exe and javac.exe to that path. IT WORKS
Had the same issue on Windows7 64bit. The reason why it didn't was missing emulator-x86.exe
file under sdk/tools. Fixed it by deleting Android SDK Tools using Android SDK Manager and installing it again. The file now exists and emulator works as expected.
As an exteme turnaround, when you cannot do an alter to your date column or to update the values, or while these modifications take place, you can do a select using a case/when.
SELECT CASE ModificationDate WHEN '0000-00-00 00:00:00' THEN '1970-01-01 01:00:00' ELSE ModificationDate END AS ModificationDate FROM Project WHERE projectId=1;
For unsigned long you can use UnsignedLong class from Guava library:
It supports various operations:
The thing that seems missing at the moment are byte shift operators. If you need those you can use BigInteger from Java.
Unfortunately there is no SELECT statement that will always work regardless of database.
Most databases support:
SELECT 1
Some databases don't support this but have a table called DUAL that you can use when you don't need a table:
SELECT 1 FROM DUAL
MySQL also supports this for compatibility reasons, but not all databases do. A workaround for databases that don't support either of the above is to create a table called DUAL that contains a single row, then the above will work.
HSQLDB supports neither of the above, so you can either create the DUAL table or else use:
SELECT 1 FROM any_table_that_you_know_exists_in_your_database
For those who are learning node/express (just like me): do not use wildcard routing if possible!
I also wanted to implement the routing for GET /users/:id/whatever using wildcard routing. This is how I got here.
More info: https://blog.praveen.science/wildcard-routing-is-an-anti-pattern/
Maybe this can help
string input = "hello123world";
bool isDigitPresent = input.Any(c => char.IsDigit(c));
answer from msdn.
Create Bean for Rest Template to auto wiring the Rest Template object.
@SpringBootApplication
public class ChatAppApplication {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ChatAppApplication.class, args);
}
}
Consume the GET/POST API by using RestTemplate - exchange() method. Below is for the post api which is defined in the controller.
@RequestMapping(value = "/postdata",method = RequestMethod.POST)
public String PostData(){
return "{\n" +
" \"value\":\"4\",\n" +
" \"name\":\"David\"\n" +
"}";
}
@RequestMapping(value = "/post")
public String getPostResponse(){
HttpHeaders headers=new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity=new HttpEntity<String>(headers);
return restTemplate.exchange("http://localhost:8080/postdata",HttpMethod.POST,entity,String.class).getBody();
}
Refer this tutorial[1]
[1] https://www.tutorialspoint.com/spring_boot/spring_boot_rest_template.htm
JPA doesn't provide any specification on mapping annotations to select fetch strategy. In general, related entities can be fetched in any one of the ways given below
So SELECT
and JOIN
are two extremes and SUBSELECT
falls in between. One can choose suitable strategy based on her/his domain model.
By default SELECT
is used by both JPA/EclipseLink and Hibernate. This can be overridden by using:
@Fetch(FetchMode.JOIN)
@Fetch(FetchMode.SUBSELECT)
in Hibernate. It also allows to set SELECT
mode explicitly using @Fetch(FetchMode.SELECT)
which can be tuned by using batch size e.g. @BatchSize(size=10)
.
Corresponding annotations in EclipseLink are:
@JoinFetch
@BatchFetch
Found this tip: LOC with VS Find and replace
Not a plugin though if thats what you are looking for.
Why not this:
rsq <- function(x, y) summary(lm(y~x))$r.squared
rsq(obs, mod)
#[1] 0.8560185
My pycharm ce had the same error, was easy to fix it, if someone has that error, just uninstall and delete the folder, use ctrl+h
if you can't find the folder in your documents, install the software again and should work again.
Remember to save the scratches folder before erasing the pycharm folder.
File.renameTo
from Java IO can be used to move a file in Java. Also see this SO question.
A more general approach:
if ( ($("body").hasClass("homepage") || $("body").hasClass("contact")) && (theLanguage == 'en-gb') ) {
// Do something
}
I'd like Grommit answer, except it require dupe values. I found solution where it may appear once: http://forums.devshed.com/showpost.php?p=1182653&postcount=2
MERGE INTO KBS.NUFUS_MUHTARLIK B
USING (
SELECT '028-01' CILT, '25' SAYFA, '6' KUTUK, '46603404838' MERNIS_NO
FROM DUAL
) E
ON (B.MERNIS_NO = E.MERNIS_NO)
WHEN MATCHED THEN
UPDATE SET B.CILT = E.CILT, B.SAYFA = E.SAYFA, B.KUTUK = E.KUTUK
WHEN NOT MATCHED THEN
INSERT ( CILT, SAYFA, KUTUK, MERNIS_NO)
VALUES (E.CILT, E.SAYFA, E.KUTUK, E.MERNIS_NO);
Works for both iOS and Android
import 'package:flutter/services.dart';
@override
Widget build(BuildContext context) {
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
return Scaffold();
}
Running your code shows an image for me, after adjusting the path. Can you verify that your image path is correct, try absolute path for instance?
This exact example is present on mozilla developers page:
As you can see it even allows you to create tooltips! :) Also, instead of embedding the actual text in your CSS, you may use content: attr(data-descr);
, and store it in data-descr="ADD"
attribute of your HTML tag (which is nice because you can e.g translate it)
CSS content
can only be usef with :after
and :before
pseudo-elements, so you can try to proceed with something like this:
.item a p.new-label span:after{
position: relative;
content: 'NEW'
}
.item:hover a p.new-label span:after {
content: 'ADD';
}
The CSS :after pseudo-element matches a virtual last child of the selected element. Typically used to add cosmetic content to an element, by using the content CSS property. This element is inline by default.
Decide a width and check how many characters one line could hold, and then for each key pressed you call a function that looks something like:
function changeHeight()
{
var chars_per_row = 100;
var pixles_per_row = 16;
this.style.height = Math.round((this.value.length / chars_per_row) * pixles_per_row) + 'px';
}
Havn't tested the code.
In my case Win 10. the file applicationHost.config is corrupted by VS 2012. And you can get the copy the history of this file under C:\inetpub\history. Then restart IIS and it works properly.
private void CleanForm(Control ctrl)
{
foreach (var c in ctrl.Controls)
{
if (c is TextBox)
{
((TextBox)c).Text = String.Empty;
}
if( c.Controls.Count > 0)
{
CleanForm(c);
}
}
}
When you initially call ClearForm, pass in this, or Page (I assume that is what 'this' is).
You can't avoid a server call here, JavaScript simply cannot (for security reasons) save a file to the user's file system. You'll have to submit your data to the server and have it send the .csv
as a link or an attachment directly.
HTML5 has some ability to do this (though saving really isn't specified - just a use case, you can read the file if you want), but there's no cross-browser solution in place now.
This example uses an inverted scanset, so scanf keeps taking in values until it encounters a '\n'-- newline, so spaces get saved as well
#include <stdio.h>
int main (int argc, char const *argv[])
{
char name[20];
scanf("%[^\n]s",name);
printf("%s\n", name);
return 0;
}
I needed to process the entire line as a whole. Here is what I found to work.
for /F "tokens=*" %%A in (myfile.txt) do [process] %%A
The tokens keyword with an asterisk (*) will pull all text for the entire line. If you don't put in the asterisk it will only pull the first word on the line. I assume it has to do with spaces.
If there are spaces in your file path, you need to use usebackq
. For example.
for /F "usebackq tokens=*" %%A in ("my file.txt") do [process] %%A
Alternatively if you do not want a gradual transition between show and hide (e.g. a blinking text cursor) you could use something like:
/* Also use prefixes with @keyframes and animation to support current browsers */
@keyframes blinker {
from { visibility: visible }
to { visibility: hidden }
/* Alternatively you can do this:
0% { visibility: visible; }
50% { visibility: hidden; }
100% { visibility: visible; }
if you don't want to use `alternate` */
}
.cursor {
animation: blinker steps(1) 500ms infinite alternate;
}
Every 1s
.cursor
will go from visible
to hidden
.
If CSS animation is not supported (e.g. in some versions of Safari) you can fallback to this simple JS interval:
(function(){
var show = 'visible'; // state var toggled by interval
var time = 500; // milliseconds between each interval
setInterval(function() {
// Toggle our visible state on each interval
show = (show === 'hidden') ? 'visible' : 'hidden';
// Get the cursor elements
var cursors = document.getElementsByClassName('cursor');
// We could do this outside the interval callback,
// but then it wouldn't be kept in sync with the DOM
// Loop through the cursor elements and update them to the current state
for (var i = 0; i < cursors.length; i++) {
cursors[i].style.visibility = show;
}
}, time);
})()
This simple JavaScript is actually very fast and in many cases may even be a better default than the CSS. It's worth noting that it is lots of DOM calls that make JS animations slow (e.g. JQuery's $.animate()).
It also has the second advantage that if you add .cursor
elements later, they will still animate at exactly the same time as other .cursor
s since the state is shared, this is impossible with CSS as far as I am aware.
If column number are varing you can use this
package com.org.tests;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelSimpleTest
{
String path;
public FileInputStream fis = null;
private XSSFWorkbook workbook = null;
private XSSFSheet sheet = null;
private XSSFRow row =null;
private XSSFCell cell = null;
public ExcelSimpleTest() throws IOException
{
path = System.getProperty("user.dir")+"\\resources\\Book1.xlsx";
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
}
public void ExelWorks()
{
int index = workbook.getSheetIndex("Sheet1");
sheet = workbook.getSheetAt(index);
int rownumber=sheet.getLastRowNum()+1;
for (int i=1; i<rownumber; i++ )
{
row = sheet.getRow(i);
int colnumber = row.getLastCellNum();
for (int j=0; j<colnumber; j++ )
{
cell = row.getCell(j);
System.out.println(cell.getStringCellValue());
}
}
}
public static void main(String[] args) throws IOException
{
ExcelSimpleTest excelwork = new ExcelSimpleTest();
excelwork.ExelWorks();
}
}
The corresponding mavendependency can be found here
You can also use js map function:
$("#multipleSelect :selected").map(function(i, el) {
return $(el).val();
}).get();
And then you can get any property of the option
element:
return $(el).text();
return $(el).data("mydata");
return $(el).prop("disabled");
etc...
Lots of answers so far, which are all excellent pointers to API's and tutorials. One thing I'd like to add is that I work out how far the markers are from my location using something like:
float distance = (float) loc.distanceTo(loc2);
Hope this helps refine the detail for your problem. It returns a rough estimate of distance (in m) between points, and is useful for getting rid of POI that might be too far away - good to declutter your map?
When you go and write you shell script always put first line as #!/usr/bin/env bash . This shell doesn't omit or manipulate escape sequences. ex echo "This is first \n line" prints This is first \n line.
In addition, if you have a FileInfo fi
, you can simply do:
string ext = fi.Extension;
and it'll hold the extension of the file (note: it will include the .
, so a result of the above could be: .jpg
.txt
, and so on....
Ref - JWT Structure and Security
It is important to note that JWT are used for authorization and not authentication.
So a JWT will be created for you only after you have been authenticated by the server by may be specifying the credentials. Once JWT has been created for all future interactions with server JWT can be used. So JWT tells that server that this user has been authenticated, let him access the particular resource if he has the role.
Information in the payload of the JWT is visible to everyone. There can be a "Man in the Middle" attack and the contents of the JWT can be changed. So we should not pass any sensitive information like passwords in the payload. We can encrypt the payload data if we want to make it more secure. If Payload is tampered with server will recognize it.
So suppose a user has been authenticated and provided with a JWT. Generated JWT has a claim specifying role of Admin. Also the Signature is generated with
This JWT is now tampered with and suppose the
role is changed to Super Admin
Then when the server receives this token it will again generate the signature using the secret key(which only the server has) and the payload. It will not match the signature
in the JWT. So the server will know that the JWT has been tampered with.
I converted the answer to the kotlin, hope this helps for kotlin users.
private fun checkKeyboardVisibility() {
var isKeyboardShowing = false
binding.coordinator.viewTreeObserver.addOnGlobalLayoutListener {
val r = Rect()
binding.coordinator.getWindowVisibleDisplayFrame(r)
val screenHeight = binding.coordinator.rootView.height
// r.bottom is the position above soft keypad or device button.
// if keypad is shown, the r.bottom is smaller than that before.
val keypadHeight = screenHeight - r.bottom
if (keypadHeight > screenHeight * 0.15) { // 0.15 ratio is perhaps enough to determine keypad height.
// keyboard is opened
if (!isKeyboardShowing) {
isKeyboardShowing = true
}
} else {
// keyboard is closed
if (isKeyboardShowing) {
isKeyboardShowing = false
}
}
}
}
Probably a duplicate of this post: A customized input text box in html/html5
input {_x000D_
border: 0;_x000D_
outline: 0;_x000D_
background: transparent;_x000D_
border-bottom: 1px solid black;_x000D_
}
_x000D_
<input></input>
_x000D_
get_curr_date () {
# get unix time
DATE=$(date +%s)
echo "DATE_CURR : "$DATE
}
conv_utime_hread () {
# convert unix time to human readable format
DATE_HREAD=$(date -d @$DATE +%Y%m%d_%H%M%S)
echo "DATE_HREAD : "$DATE_HREAD
}
This is what I use:
var result = [];
for (var l in someObject){
if (someObject.hasOwnProperty(l){
result.push(l+': '+someObject[l]);
}
}
alert(result.join('\n'));
If you want to show nested objects too, you could use something recursive:
function alertObject(obj){
var result = [];
function traverse(obj){
for (var l in obj){
if (obj.hasOwnProperty(l)){
if (obj[l] instanceof Object){
result.push(l+'=>[object]');
traverse(obj[l]);
} else {
result.push(l+': '+obj[l]);
}
}
}
}
traverse(obj);
return result;
}
Just for convenient reference as I see that there are a lot of people searching for this topic and are too laz... sorry, busy, to check themselves (including me). Here a list of the default set of colour schemes for Vim 7.4:
blue.vim
darkblue.vim,
delek.vim
desert.vim
elflord.vim
evening.vim
industry.vim
koehler.vim
morning.vim
murphy.vim
pablo.vim
peachpuff.vim
ron.vim
shine.vim
slate.vim
torte.vim
zellner.vim
DateTime.Now.DayOfWeek
quite easy to guess actually.
for any given date:
DateTime dt = //....
DayOfWeek dow = dt.DayOfWeek; //enum
string str = dow.ToString(); //string
Please write following code in menu.xml file:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:my_menu_tutorial_app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.mymenus.menu_app.MainActivity">
<item android:id="@+id/item_one"
android:icon="@drawable/menu_icon"
android:orderInCategory="l01"
android:title="Item One"
my_menu_tutorial_app:showAsAction="always">
<!--sub-menu-->
<menu>
<item android:id="@+id/sub_one"
android:title="Sub-menu item one" />
<item android:id="@+id/sub_two"
android:title="Sub-menu item two" />
</menu>
Also write this java code in activity class file:
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
Toast.makeText(this, "Menus item selected: " +
item.getTitle(), Toast.LENGTH_SHORT).show();
switch (item.getItemId())
{
case R.id.sub_one:
isItemOneSelected = true;
supportInvalidateOptionsMenu();
return true;
case MENU_ITEM + 1:
isRemoveItem = true;
supportInvalidateOptionsMenu();
return true;
default:
return false;
}
}
This is the easiest way to display menus in action bar.
I came up with a hacky solution that totally removes "No file chosen" plus the extra space that is added after that text (in Chrome I get something like: "No file chosen ").
This was totally messing up my page alignment, so I really fought with it to find a solution. Inside the input tag's style attribute, setting "width" to the width of the button will eliminate the trailing text and spaces. Since the width of the button is not the same in all browsers (it's a little smaller in Firefox, for example), you'll also want to set the style's color to the same color as the background of the page (otherwise a stray "No" may show through). My input file tag looks like this:
<input style="float:left; **width:88px;** **color:#000000;**" type="file" id="fileInput" onclick="fileOpen()">
document.getElementsByClassName('CLASSNAME')[0].style.display = 'none';
Acyually by using getElementsByClassName, it returns an array of multiple classes. Because same class name could be used in more than one instance inside same HTML page. We use array element id to target the class we need, in my case, it's first instance of the given class name.So I've used [0]
Consider the hex() method of the bytes
type on Python 3.5 and up:
>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print(bytes(array_alpha).hex())
8535eaf1
EDIT: it's also much faster than hexlify
(modified @falsetru's benchmarks above)
from timeit import timeit
N = 10000
print("bytearray + hexlify ->", timeit(
'binascii.hexlify(data).decode("ascii")',
setup='import binascii; data = bytearray(range(255))',
number=N,
))
print("byte + hex ->", timeit(
'data.hex()',
setup='data = bytes(range(255))',
number=N,
))
Result:
bytearray + hexlify -> 0.011218150997592602
byte + hex -> 0.005952142993919551
I will recommend you not to use any third party libraries for auto fetch OTP from SMS Inbox. This can be done easily if you have basic understanding of Broadcast Receiver and how it works. Just Try following approach :
Step 1) Create single interface i.e SmsListner
package com.wnrcorp.reba;
public interface SmsListener{
public void messageReceived(String messageText);}
Step 2) Create single Broadcast Receiver i.e SmsReceiver
package com.wnrcorp.reba;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class SmsReceiver extends BroadcastReceiver {
private static SmsListener mListener;
Boolean b;
String abcd,xyz;
@Override
public void onReceive(Context context, Intent intent) {
Bundle data = intent.getExtras();
Object[] pdus = (Object[]) data.get("pdus");
for(int i=0;i<pdus.length;i++){
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
String sender = smsMessage.getDisplayOriginatingAddress();
// b=sender.endsWith("WNRCRP"); //Just to fetch otp sent from WNRCRP
String messageBody = smsMessage.getMessageBody();
abcd=messageBody.replaceAll("[^0-9]",""); // here abcd contains otp
which is in number format
//Pass on the text to our listener.
if(b==true) {
mListener.messageReceived(abcd); // attach value to interface
object
}
else
{
}
}
}
public static void bindListener(SmsListener listener) {
mListener = listener;
}
}
Step 3) Add Listener i.e broadcast receiver in android manifest file
<receiver android:name=".SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
and add permission
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
Final Step 4) The activity where you going to auto fetch otp when it is received in inbox. In my case I'm fetching otp and setting on edittext field.
public class OtpVerificationActivity extends AppCompatActivity {
EditText ed;
TextView tv;
String otp_generated,contactNo,id1;
GlobalData gd = new GlobalData();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp_verification);
ed=(EditText)findViewById(R.id.otp);
tv=(TextView) findViewById(R.id.verify_otp);
/*This is important because this will be called every time you receive
any sms */
SmsReceiver.bindListener(new SmsListener() {
@Override
public void messageReceived(String messageText) {
ed.setText(messageText);
}
});
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try
{
InputMethodManager imm=
(InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0);
}
catch(Exception e)
{}
if (ed.getText().toString().equals(otp_generated))
{
Toast.makeText(OtpVerificationActivity.this, "OTP Verified
Successfully !", Toast.LENGTH_SHORT).show();
}
});
}
}
Layout File for OtpVerificationActivity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_otp_verification"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.wnrcorp.reba.OtpVerificationActivity">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/firstcard"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
card_view:cardCornerRadius="10dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@android:color/white">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OTP Confirmation"
android:textSize="18sp"
android:textStyle="bold"
android:id="@+id/dialogTitle"
android:layout_margin="5dp"
android:layout_gravity="center"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/otp"
android:layout_margin="5dp"
android:hint="OTP Here"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Verify"
android:textSize="18sp"
android:id="@+id/verify_otp"
android:gravity="center"
android:padding="10dp"
android:layout_gravity="center"
android:visibility="visible"
android:layout_margin="5dp"
android:background="@color/colorPrimary"
android:textColor="#ffffff"
/>
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
Screenshots for OTP Verification Activity where you fetch OTP as soons as messages received
JSON_UNESCAPED_UNICODE is available on PHP Version 5.4 or later.
The following code is for Version 5.3.
UPDATED
html_entity_decode
is a bit more efficient than pack
+ mb_convert_encoding
.(*SKIP)(*FAIL)
skips backslashes itself and specified characters by JSON_HEX_*
flags.
function raw_json_encode($input, $flags = 0) {
$fails = implode('|', array_filter(array(
'\\\\',
$flags & JSON_HEX_TAG ? 'u003[CE]' : '',
$flags & JSON_HEX_AMP ? 'u0026' : '',
$flags & JSON_HEX_APOS ? 'u0027' : '',
$flags & JSON_HEX_QUOT ? 'u0022' : '',
)));
$pattern = "/\\\\(?:(?:$fails)(*SKIP)(*FAIL)|u([0-9a-fA-F]{4}))/";
$callback = function ($m) {
return html_entity_decode("&#x$m[1];", ENT_QUOTES, 'UTF-8');
};
return preg_replace_callback($pattern, $callback, json_encode($input, $flags));
}
Single dimensional array decays to a pointer pointer pointing to the first element in the array. While a 2D array decays to a pointer pointing to first row. So, the function prototype should be -
void myFunction(double (*myArray) [10]);
I would prefer std::vector
over raw arrays.
If you want to see which IP addresses are in use on a specific subnet then there are several different IP Address managers.
Try Angry IP Scanner or Solarwinds or Advanced IP Scanner
Take a look at the java.sql.PreparedStatement class, specifically the function
Then take a look at the java.sql.ResultSet class, specifically the function
http://java.sun.com/javase/6/docs/api/java/sql/ResultSet.html#getBinaryStream(int)
Keep in mind that if you are serializing an object into a database, and then you change the object in your code in a new version, the deserialization process can easily fail because your object's signature changed. I once made this mistake with storing a custom Preferences serialized and then making a change to the Preferences definition. Suddenly I couldn't read any of the previously serialized information.
You might be better off writing clunky per property columns in a table and composing and decomposing the object in this manner instead, to avoid this issue with object versions and deserialization. Or writing the properties into a hashmap of some sort, like a java.util.Properties object, and then serializing the properties object which is extremely unlikely to change.
You can achieve it through code. Obtain the back arrow drawable, modify its color with a filter, and set it as back button.
final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.grey), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
Revision 1:
Starting from API 23 (Marshmallow) the drawable resource abc_ic_ab_back_mtrl_am_alpha
is changed to abc_ic_ab_back_material
.
EDIT:
You can use this code to achieve the results you want:
toolbar.getNavigationIcon().setColorFilter(getResources().getColor(R.color.blue_gray_15), PorterDuff.Mode.SRC_ATOP);
I just wanted to share some of my results...
I have text files, which apparently came from a Linux system, so I only have a vbLF
/Chr(10)
at the end of each line and not vbCR
/Chr(13)
.
Note 1:
- This meant that the
Line Input
method would read in the entire file, instead of just one line at a time.
From my research testing small (152KB) & large (2778LB) files, both on and off the network I found the following:
Open FileName For Input: Line Input
was the slowest (See Note 1 above)
Open FileName For Binary Access Read: Input
was the fastest for reading the whole file
FSO.OpenTextFile: ReadLine
was fast, but a bit slower then Binary Input
Note 2:
If I just needed to check the file header (first 1-2 lines) to check if I had the proper file/format, then
FSO.OpenTextFile
was the fastest, followed very closely byBinary Input
.The drawback with the
Binary Input
is that you have to know how many characters you want to read.- On normal files,
Line Input
would also be a good option as well, but I couldn't test due to Note 1.
Note 3:
- Obviously, the files on the network showed the largest difference in read speed. They also showed the greatest benefit from reading the file a second time (although there are certainly memory buffers that come into play here).
An event in .net is a designated combination of an Add method and a Remove method, both of which expect some particular type of delegate. Both C# and vb.net can auto-generate code for the add and remove methods which will define a delegate to hold the event subscriptions, and add/remove the passed in delegagte to/from that subscription delegate. VB.net will also auto-generate code (with the RaiseEvent statement) to invoke the subscription list if and only if it is non-empty; for some reason, C# doesn't generate the latter.
Note that while it is common to manage event subscriptions using a multicast delegate, that is not the only means of doing so. From a public perspective, a would-be event subscriber needs to know how to let an object know it wants to receive events, but it does not need to know what mechanism the publisher will use to raise the events. Note also that while whoever defined the event data structure in .net apparently thought there should be a public means of raising them, neither C# nor vb.net makes use of that feature.
In my case I had a previous mySQL server installation (with non-standard port), and I re-installed to a different directory & port. Then I got the same issue (in windows). To resolve, you click on home + add new connection.
If you need to know the port of your server, you can find it when you start My SQL command line client and run command status (as below). In windows it is via All Programs -> MySQL -> MySQL ServerX.Y -> MySQL X.Y Command Line Client
Here is an example from my HOW TO Matlab page:
close all; clear all;
img = imread('lena.tif','tif');
imagesc(img)
img = fftshift(img(:,:,2));
F = fft2(img);
figure;
imagesc(100*log(1+abs(fftshift(F)))); colormap(gray);
title('magnitude spectrum');
figure;
imagesc(angle(F)); colormap(gray);
title('phase spectrum');
This gives the magnitude spectrum and phase spectrum of the image. I used a color image, but you can easily adjust it to use gray image as well.
ps. I just noticed that on Matlab 2012a the above image is no longer included. So, just replace the first line above with say
img = imread('ngc6543a.jpg');
and it will work. I used an older version of Matlab to make the above example and just copied it here.
On the scaling factor
When we plot the 2D Fourier transform magnitude, we need to scale the pixel values using log transform to expand the range of the dark pixels into the bright region so we can better see the transform. We use a c
value in the equation
s = c log(1+r)
There is no known way to pre detrmine this scale that I know. Just need to
try different values to get on you like. I used 100
in the above example.
Characters that need escaping are different in Bourne or POSIX shell than Bash. Generally (very) Bash is a superset of those shells, so anything you escape in shell
should be escaped in Bash.
A nice general rule would be "if in doubt, escape it". But escaping some characters gives them a special meaning, like \n
. These are listed in the man bash
pages under Quoting
and echo
.
Other than that, escape any character that is not alphanumeric, it is safer. I don't know of a single definitive list.
The man pages list them all somewhere, but not in one place. Learn the language, that is the way to be sure.
One that has caught me out is !
. This is a special character (history expansion) in Bash (and csh) but not in Korn shell. Even echo "Hello world!"
gives problems. Using single-quotes, as usual, removes the special meaning.
You have to use Kendo UI DropDownList select
method (documentation in here).
Basically you should:
// get a reference to the dropdown list
var dropdownlist = $("#Instrument").data("kendoDropDownList");
If you know the index you can use:
// selects by index
dropdownlist.select(1);
If not, use:
// selects item if its text is equal to "test" using predicate function
dropdownlist.select(function(dataItem) {
return dataItem.symbol === "test";
});
JSFiddle example here
There was a problem once in ruby where files in windows needed an "fsync" to actually be able to turn around and re-read the file after writing it and closing it. Maybe this is a similar manifestation (and if so, I think a windows bug, really).
The solution was to give the "Network Service" account read permission on the EventLog/Security key.
I know this is a seriously old post - but my answer might be useful to others anyway, so here goes. I found that if my CSS style definition for the contenteditable div has a min-height of 200 instead of a height of 200 , then the div scales automatically.
Here is another one liner using lambdas (create column with constant value = 10)
df['newCol'] = df.apply(lambda x: 10, axis=1)
before
df
A B C
1 1.764052 0.400157 0.978738
2 2.240893 1.867558 -0.977278
3 0.950088 -0.151357 -0.103219
after
df
A B C newCol
1 1.764052 0.400157 0.978738 10
2 2.240893 1.867558 -0.977278 10
3 0.950088 -0.151357 -0.103219 10
I would recommend you to use background-image instead of default list.
.listStyle {
list-style: none;
background: url(image_path.jpg) no-repeat left center;
padding-left: 30px;
width: 20px;
height: 20px;
}
Or, if you don't want to use background-image as bullet, there is an option to do it with pseudo element:
.liststyle{
list-style: none;
margin: 0;
padding: 0;
}
.liststyle:before {
content: "• ";
color: red; /* or whatever color you prefer */
font-size: 20px;/* or whatever the bullet size you prefer */
}
The easiest way is:
s = '"sajdkasjdsaasdasdasds"'
import json
s = json.loads(s)
Tried all above/older brew installation answers, none is working for my laptop.
Only below method could fix my issue.
1) Run following commands:
sudo rm -rf /usr/local/lib/node_modules/npm
brew uninstall --force node
2) Then, proceed to Node.js Official Website https://nodejs.org/en/download/current/ to download latest package for new installation.
3) Run your npm command again, which should longer have any errors.
This method is working on macOS Mojave Version 10.14.4.
You can change the value in the XML like this:
<Button
android:background="#FFFFFF"
../>
Here, you can add any other color, from the resources or hex.
Similarly, you can also change these values form the code like this:
demoButton.setBackgroundColor(Color.WHITE);
Another easy way is to make a drawable, customize the corners and shape according to your preference and set the background color and stroke of the drawable. For eg.
button_background.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="2dp" android:color="#ff207d94" />
<corners android:radius="5dp" />
<solid android:color="#FFFFFF" />
</shape>
And then set this shape as the background of your button.
<Button
android:background="@drawable/button_background.xml"
../>
Hope this helps, good luck!
Thanks for the responses. I think I've solved the problem just now.
Since LD_PRELOAD is for setting some library proloaded, I check the library that ld preloads with LD_PRELOAD, one of which is "liblunar-calendar-preload.so", that is not existing in the path "/usr/lib/liblunar-calendar-preload.so", but I find a similar library "liblunar-calendar-preload-2.0.so", which is a difference version of the former one.
Then I guess maybe liblunar-calendar-preload.so was updated to a 2.0 version when the system updated, leaving LD_PRELOAD remain to be "/usr/lib/liblunar-calendar-preload.so". Thus the preload library name was not updated to the newest version.
To avoid changing environment variable, I create a symbolic link under the path "/usr/lib"
sudo ln -s liblunar-calendar-preload-2.0.so liblunar-calendar-preload.so
Then I restart bash, the error is gone.
I do not know much about JavaScript, but I think Timers may be what you are looking for.
http://developer.android.com/reference/java/util/Timer.html
From the link:
One-shot are scheduled to run at an absolute time or after a relative delay. Recurring tasks are scheduled with either a fixed period or a fixed rate.
@IBOutlet weak var yourButton: UIButton! {
didSet{
yourButton.backgroundColor = .clear
yourButton.layer.cornerRadius = 10
yourButton.layer.borderWidth = 2
yourButton.layer.borderColor = UIColor.white.cgColor
}
}
The problem is using with statement:
with open('strings.json') as json_data:
d = json.load(json_data)
pprint(d)
The file is going to be implicitly closed already. There is no need to call json_data.close()
again.
I know I'm coming to this very late. However, for anyone who's searching, I thought I'd publish what FINALLY worked for me. I'm not claiming it's the best solution - only that it worked.
Our WebApi service uses the config.EnableCors(corsAttribute) method. However, even with that, it would still fail on the pre-flight requests. @Mihai-Andrei Dinculescu's answer provided the clue for me. First of all, I added his Application_BeginRequest() code to flush the options requests. That STILL didn't work for me. The issue is that WebAPI still wasn't adding any of the expected headers to the OPTIONS request. Flushing it alone didn't work - but it gave me an idea. I added the custom headers that would otherwise be added via the web.config to the response for the OPTIONS request. Here's my code:
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.Headers.Add("Access-Control-Allow-Origin", "https://localhost:44343");
Response.Headers.Add("Access-Control-Allow-Headers",
"Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
Response.Headers.Add("Access-Control-Allow-Credentials", "true");
Response.Flush();
}
}
Obviously, this only applies to the OPTIONS requests. All other verbs are handled by the CORS configuration. If there's a better approach to this, I'm all ears. It feels like a cheat to me and I would prefer if the headers were added automatically, but this is what finally worked and allowed me to move on.
I got a similar error, and it's caused by incorrect proxy setting. This command saved me:
git config --global --unset http.proxy
https version:
git config --global --unset https.proxy
In gameprofile.html
please change the tag {% endblock content %}
to {% endblock %}
then it works otherwise django will not load the endblock and give error.
Do as follows for milliseconds:
select round(date_format(CURTIME(3), "%f")/1000)
You can get microseconds by the following:
select date_format(CURTIME(6), "%f")
For me, passing ($event.target.value) as suggested by @microniks did not work. What worked was ($event.value) instead. I am using Angular 4.2.x and Angular Material 2
<select (change)="onItemChange($event.value)">
<option *ngFor="#value of values" [value]="value.key">
{{value.value}}
</option>
</select>
RABL is probably the nicest solution to this that I've seen if you're looking for a cleaner alternative to ERb syntax. json_builder and argonaut, which are other solutions, both seem somewhat outdated and won't work with Rails 3.1 without some patching.
RABL is available via a gem or check out the GitHub repository; good examples too
You can use following commands to extract public/private key from a PKCS#12 container:
PKCS#1 Private key
openssl pkcs12 -in yourP12File.pfx -nocerts -out privateKey.pem
Certificates:
openssl pkcs12 -in yourP12File.pfx -clcerts -nokeys -out publicCert.pem
Is there something that prevents you from merging all revisions on trunk since the last merge?
svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc
should work just fine. At least if you want to merge all changes on trunk to your branch.
You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the ${}
things) in JSP to access/display them. You can put JSP files in /WEB-INF
folder to prevent users from directly accessing them without invoking the preprocessing servlet.
Kickoff example:
@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "Hello World";
request.setAttribute("message", message); // This will be available as ${message}
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
}
And /WEB-INF/hello.jsp
look like:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: ${message}</p>
</body>
</html>
When opening http://localhost:8080/contextpath/hello this will show
Message: Hello World
in the browser.
This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.
Also browse the "Frequent" tab of all questions tagged [servlets] to find frequently asked questions.
If you have spaces in the name of the file and you have a character you need to escape:
You can use single AND double quotes to avoid any misnomers in the command.
scp ./'files name with spaces/internal folder with spaces/"text & files stored.txt"' .
The ^
character escapes the quotes otherwise.
public static void main(String[] args) {
String test = "something hear - to - find some to or tows";
System.out.println("1.result: " + contains("- to -( \\w+) som", test, null));
System.out.println("2.result: " + contains("- to -( \\w+) som", test, 5));
}
static boolean contains(String pattern, String text, Integer fromIndex){
if(fromIndex != null && fromIndex < text.length())
return Pattern.compile(pattern).matcher(text).find();
return Pattern.compile(pattern).matcher(text).find();
}
1.result: true
2.result: true