Equal height columns is the default behaviour for Bootstrap 4 grids.
.col { background: red; }_x000D_
.col:nth-child(odd) { background: yellow; }
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col">_x000D_
1 of 3_x000D_
</div>_x000D_
<div class="col">_x000D_
1 of 3_x000D_
<br>_x000D_
Line 2_x000D_
<br>_x000D_
Line 3_x000D_
</div>_x000D_
<div class="col">_x000D_
1 of 3_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Just remove white space of all folders present in the given path for example Program Files You can remove it by following steps-> Open elevated cmd, In the command prompt execute: mklink /J C:\Program-Files "C:\Program Files" This will remove space and replace it with "-". Better do this with both sdk and jdk path. This works :)
As far as I understand, you have more than one form tag in your web page that causes the problem. Make sure you have only one server-side form tag for each page.
You don't need 2 style attributes - just use one:
<img src="http://img705.imageshack.us/img705/119/original120x75.png"
style="height:100px;width:100px;" alt="25"/>
Consider, however, using a CSS class instead:
CSS:
.100pxSquare
{
width: 100px;
height: 100px;
}
HTML:
<img src="http://img705.imageshack.us/img705/119/original120x75.png"
class="100pxSquare" alt="25"/>
I have tried directlabels
package for putting text labels. In the case of scatter plots it's not still perfect, but much better than manually adjusting the positions, specially in the cases that you are preparing the draft plots and not the final one - so you need to change and make plot again and again -.
jQuery(function ($) {
$('li#linkss').find('a').on('click', function (e) {
var
link_href = $(this).attr('href')
, $linkElem = $(link_href)
, $linkElem_scroll = $linkElem.get(0) && $linkElem.position().top - 115;
$('html, body')
.animate({
scrollTop: $linkElem_scroll
}, 'slow');
e.preventDefault();
});
});
It probably is the # sign like tho others have mentioned because this appears to work just fine.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<select id="#ticket_category_clone">
<option value="hw">Hardware</option>
<option>fsdf</option>
<option>sfsd</option>
<option>sdfs</option>
</select>
<script type="text/javascript">
(function check() {
var e = document.getElementById("#ticket_category_clone");
var str = e.options[e.selectedIndex].text;
alert(str);
if (str === "Hardware") {
alert('Hi');
}
})();
</script>
</body>
Personally, I find it both elegant and convenient to wrap the fill function.
To fill between two equally sized row vectors Y1
and Y2
that share the support X
(and color C):
fill_between_lines = @(X,Y1,Y2,C) fill( [X fliplr(X)], [Y1 fliplr(Y2)], C );
brief mnemonics:
git reset HEAD : index = HEAD
git checkout : file_tree = index
git reset --hard HEAD : file_tree = index = HEAD
Adding the following to your css should hide the text element for users and keep FB Happy
.connect_widget_not_connected_text
{
display:none !important; /*in your stylesheets to hide the counter!*/
}
-- Update
Try using a different approach.
file --mime works, but not --mime-type. at least for my RHEL 5.
I encountered this error working in Talend. I was able to store S3 CSV files created from Redshift without a problem. The error occurred when I was trying to load the same S3 CSV files into an Amazon RDS MySQL database. I tried the default timestamp Talend timestamp formats but they were throwing exception:unparseable date when loading into MySQL.
This from the accepted answer helped me solve this problem:
By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern
The key to my solution was changing the Talend schema. Talend set the timestamp field to "date" so I changed it to "timestamp" then I inserted "yyyy-MM-dd HH:mm:ss z" into the format string column view a screenshot here talend schema
I had other issues with 12 hour and 24 hour timestamp translations until I added the "z" at the end of the timestamp string.
man printf.1
has a note at the bottom: "...your shell may have its own version of printf
...". This question is tagged for bash
, but if at all possible, I try to write scripts portable to any shell. dash
is usually a good minimum baseline for portability - so the answer here works in bash
, dash
, & zsh
. If a script works in those 3, it's most likely portable to just about anywhere.
The latest implementation of printf
in dash
[1] doesn't colorize output given a %s
format specifier with an ANSI escape character \e
-- but, a format specifier %b
combined with octal \033
(equivalent to an ASCII ESC
) will get the job done. Please comment for any outliers, but AFAIK, all shells have implemented printf
to use the ASCII octal subset at a bare minimum.
To the title of the question "Using colors with printf", the most portable way to set formatting is to combine the %b
format specifier for printf
(as referenced in an earlier answer from @Vlad) with an octal escape \033
.
portable-color.sh
#/bin/sh
P="\033["
BLUE=34
printf "-> This is %s %-6s %s text \n" $P"1;"$BLUE"m" "blue" $P"0m"
printf "-> This is %b %-6s %b text \n" $P"1;"$BLUE"m" "blue" $P"0m"
Outputs:
$ ./portable-color.sh
-> This is \033[1;34m blue \033[0m text
-> This is blue text
...and 'blue' is blue in the second line.
The %-6s
format specifier from the OP is in the middle of the format string between the opening & closing control character sequences.
[1] Ref: man dash
Section "Builtins" :: "printf" :: "Format"
Case statement syntax in SQL SERVER:
CASE column
WHEN value1 THEN 1
WHEN value3 THEN 2
WHEN value3 THEN 3
WHEN value1 THEN 4
ELSE ''
END
And we can use like below also:
CASE
WHEN column=value1 THEN 1
WHEN column=value3 THEN 2
WHEN column=value3 THEN 3
WHEN column=value1 THEN 4
ELSE ''
END
The best
and the rest
It is rather messy but you need to do something like the following:
START "do something window" dir
FOR /F "tokens=2" %I in ('TASKLIST /NH /FI "WINDOWTITLE eq do something window"' ) DO SET PID=%I
ECHO %PID%
TASKKILL /PID %PID%
Found this on this page.
(This kind of thing is much easier if you have a UNIX / LINUX system ... or if you run Cygwin or similar on Windows.)
I have used Excel.dll library which is:
The documentation available over here: https://exceldatareader.codeplex.com/
Strongly recommendable.
Your request should be to the server, NOT the server.js file which instantiates it. So, the request should look something like this: xmlhttp.open("GET","http://localhost:8001/", true);
Also, you are trying to serve the front-end (index.html) AND serve AJAX requests at the same URI. To accomplish this, you are going to have to introduce logic to your server.js that will differentiate between your AJAX requests and a normal http access request. To do this, you'll want to either introduce GET/POST data (i.e. call http://localhost:8001/?getstring=true
) or use a different path for your AJAX requests (i.e. call http://localhost:8001/getstring
). On the server end then, you'll need to examine the request object to determine what to write on the response. For the latter option, you need to use the 'url' module to parse the request.
You are correctly calling listen()
but incorrectly writing the response. First of all, if you wish to serve index.html when navigating to http://localhost:8001/, you need to write the contents of the file to the response using response.write()
or response.end()
. First, you need to include fs=require('fs')
to get access to the filesystem. Then, you need to actually serve the file.
XMLHttpRequest needs a callback function specified if you use it asynchronously (third parameter = true, as you have done) AND want to do something with the response. The way you have it now, string
will be undefined
(or perhaps null
), because that line will execute before the AJAX request is complete (i.e. the responseText is still empty). If you use it synchronously (third parameter = false), you can write inline code as you have done. This is not recommended as it locks the browser during the request. Asynchronous operation is usually used with the onreadystatechange function, which can handle the response once it is complete. You need to learn the basics of XMLHttpRequest. Start here.
Here is a simple implementation that incorporates all of the above:
server.js:
var http = require('http'),
fs = require('fs'),
url = require('url'),
choices = ["hello world", "goodbye world"];
http.createServer(function(request, response){
var path = url.parse(request.url).pathname;
if(path=="/getstring"){
console.log("request recieved");
var string = choices[Math.floor(Math.random()*choices.length)];
console.log("string '" + string + "' chosen");
response.writeHead(200, {"Content-Type": "text/plain"});
response.end(string);
console.log("string sent");
}else{
fs.readFile('./index.html', function(err, file) {
if(err) {
// write an error response or nothing here
return;
}
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(file, "utf-8");
});
}
}).listen(8001);
console.log("server initialized");
frontend (part of index.html):
function newGame()
{
guessCnt=0;
guess="";
server();
displayHash();
displayGuessStr();
displayGuessCnt();
}
function server()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost:8001/getstring", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
string=xmlhttp.responseText;
}
}
xmlhttp.send();
}
You will need to be comfortable with AJAX. Use the mozilla learning center to learn about XMLHttpRequest. After you can use the basic XHR object, you will most likely want to use a good AJAX library instead of manually writing cross-browser AJAX requests (for example, in IE you'll need to use an ActiveXObject instead of XHR). The AJAX in jQuery is excellent, but if you don't need everything else jQuery offers, find a good AJAX library here: http://microjs.com/. You will also need to get comfy with the node.js docs, found here. Search http://google.com for some good node.js server and static file server tutorials. http://nodetuts.com is a good place to start.
UPDATE: I have changed response.sendHeader()
to the new response.writeHead()
in the code above !!!
For those who want to add multiple Python version in their system: I easily add multiple interpreters by running the following commands:
Keep in mind that gdb is a powerful command -capable of low level instructions- so is tied to assembly concepts.
What you are looking for is called de instruction pointer, i.e:
The instruction pointer register points to the memory address which the processor will next attempt to execute. The instruction pointer is called ip in 16-bit mode, eip in 32-bit mode,and rip in 64-bit mode.
more detail here
all registers available on gdb execution can be shown with:
(gdb) info registers
with it you can find which mode your program is running (looking which of these registers exist)
then (here using most common register rip nowadays, replace with eip or very rarely ip if needed):
(gdb)info line *$rip
will show you line number and file source
(gdb) list *$rip
will show you that line with a few before and after
but probably
(gdb) frame
should be enough in many cases.
keep it simple
<div align="center">
<div style="display: inline-block"> <img src="img1.png"> </div>
<div style="display: inline-block"> <img src="img2.png"> </div>
</div>
Fast:
SELECT TOP (1) CASE
WHEN **NOT_NULL_COLUMN** IS NULL
THEN 'empty table'
ELSE 'not empty table'
END AS info
FROM **TABLE_NAME**
To map a composite key, you can use the EmbeddedId
or the IdClass
annotations. I know this question is not strictly about JPA but the rules defined by the specification also applies. So here they are:
2.1.4 Primary Keys and Entity Identity
...
A composite primary key must correspond to either a single persistent field or property or to a set of such fields or properties as described below. A primary key class must be defined to represent a composite primary key. Composite primary keys typically arise when mapping from legacy databases when the database key is comprised of several columns. The
EmbeddedId
andIdClass
annotations are used to denote composite primary keys. See sections 9.1.14 and 9.1.15....
The following rules apply for composite primary keys:
- The primary key class must be public and must have a public no-arg constructor.
- If property-based access is used, the properties of the primary key class must be public or protected.
- The primary key class must be
serializable
.- The primary key class must define
equals
andhashCode
methods. The semantics of value equality for these methods must be consistent with the database equality for the database types to which the key is mapped.- A composite primary key must either be represented and mapped as an embeddable class (see Section 9.1.14, “EmbeddedId Annotation”) or must be represented and mapped to multiple fields or properties of the entity class (see Section 9.1.15, “IdClass Annotation”).
- If the composite primary key class is mapped to multiple fields or properties of the entity class, the names of primary key fields or properties in the primary key class and those of the entity class must correspond and their types must be the same.
IdClass
The class for the composite primary key could look like (could be a static inner class):
public class TimePK implements Serializable {
protected Integer levelStation;
protected Integer confPathID;
public TimePK() {}
public TimePK(Integer levelStation, Integer confPathID) {
this.levelStation = levelStation;
this.confPathID = confPathID;
}
// equals, hashCode
}
And the entity:
@Entity
@IdClass(TimePK.class)
class Time implements Serializable {
@Id
private Integer levelStation;
@Id
private Integer confPathID;
private String src;
private String dst;
private Integer distance;
private Integer price;
// getters, setters
}
The IdClass
annotation maps multiple fields to the table PK.
EmbeddedId
The class for the composite primary key could look like (could be a static inner class):
@Embeddable
public class TimePK implements Serializable {
protected Integer levelStation;
protected Integer confPathID;
public TimePK() {}
public TimePK(Integer levelStation, Integer confPathID) {
this.levelStation = levelStation;
this.confPathID = confPathID;
}
// equals, hashCode
}
And the entity:
@Entity
class Time implements Serializable {
@EmbeddedId
private TimePK timePK;
private String src;
private String dst;
private Integer distance;
private Integer price;
//...
}
The @EmbeddedId
annotation maps a PK class to table PK.
@EmbeddedId
somehow communicates more clearly that the key is a composite key and IMO makes sense when the combined pk is either a meaningful entity itself or it reused in your code.@IdClass
is useful to specify that some combination of fields is unique but these do not have a special meaning.They also affect the way you write queries (making them more or less verbose):
with IdClass
select t.levelStation from Time t
with EmbeddedId
select t.timePK.levelStation from Time t
A bit more old-school
svn diff -r 150:140 > ../r140.patch
patch -p0 < ../r140.patch
then the usual
svn diff
svn commit
One can also do this with a compact version of @TomAugspurger's answer, like so:
df = df1.merge(df2, how='left', on=['Year', 'Week', 'Colour']).merge(df3[['Week', 'Colour', 'Val3']], how='left', on=['Week', 'Colour'])
Using a bunch of different sections is not needed. The other answers use frame insets and CGRect and layers and... BLAH. Not good; use auto layout and a custom UITableViewCell. In that UITableViewCell, instead of sub viewing your content inside the contentView, make a new containerView (a UIView), subview the container view inside the contentView, then subview all your views inside the container view.
To make the spacing now, simply edit the layout margins of the container view, like so:
class CustomTableViewCell: UITableViewCell {
let containerView = UIView()
let imageView = UIImageView()
required init?(coder aDecoder: NSCoder) {super.init(coder: aDecoder)}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
containerView.translatesAutoResizingMaskIntoConstraints = false
imageView.translatesAutoResizingMaskIntoConstraints = false
contentView.addSubview(containerView)
containerView.addSubview(imageView)
contentView.layoutMargins = UIEdgeInsets(top: 15, left: 3, bottom: 15, right: 3)
containerView.layoutMargins = UIEdgeInsets(top: 15, left: 17, bottom: 15, right: 17) // It isn't really necessary unless you've got an extremely complex table view cell. Otherwise, you could just write e.g. containerView.topAnchor
let cg = contentView.layoutMarginsGuide
let lg = containerView.layoutMarginsGuide
NSLayoutConstraint.activate([
containerView.topAnchor.constraint(equalTo: cg.topAnchor),
containerView.leadingAnchor.constraint(equalTo: cg.leadingAnchor),
containerView.trailingAnchor.constraint(equalTo: cg.trailingAnchor),
containerView.bottomAnchor.constraint(equalTo: cg.bottomAnchor),
imageView.topAnchor.constraint(equalTo: lg.topAnchor),
imageView.leadingAnchor.constraint(equalTo: lg.leadingAnchor),
imageView.trailingAnchor.constraint(equalTo: lg.trailingAnchor),
imageView.bottomAnchor.constraint(equalTo: lg.bottomAnchor)
])
}
}
I'm surprised nobody has mentioned it before, but FindBin::libs will always find your libs as it searches in all reasonable places relative to the location of your script.
#!/usr/bin/perl
use FindBin::libs;
use <your lib>;
You can also add -oHostKeyAlgorithms=+ssh-dss
in your ssh line:
ssh -oHostKeyAlgorithms=+ssh-dss user@host
Complete the following steps in Eclipse to get plugins for JavaScript files:
http://download.eclipse.org/releases/juno
To add JavaScript Perspective: (Optional)
10. Go to "Window" -> "Open Perspective" -> "Other..."
11. Select "JavaScript". Click "OK"
To open .html or .js file with highlighted JavaScript syntax:
12. (Optional) Select JavaScript Perspective
13. Browse and Select .html or .js file in Script Explorer in [JavaScript Perspective] (Or Package Explorer [Java Perspective] Or PyDev Package Explorer [PyDev Perspective] Don't matter.)
14. Right-click on .html or .js file -> "Open With" -> "Other..."
15. Select "Internal editors"
16. Select "Java Script Editor". Click "OK" (see JavaScript syntax is now highlighted )
You get an apparently random set because ROWNUM is applied before the ORDER BY. So your query takes the first ten rows and sorts them.0 To select the top ten salaries you should use an analytic function in a subquery, then filter that:
select * from
(select empno,
ename,
sal,
row_number() over(order by sal desc nulls last) rnm
from emp)
where rnm<=10
container can not come front to inner container. but try this below :
Css :
----------------------
.container { position:relative; }
.div1 { width:100px; height:100px; background:#9C3; position:absolute;
z-index:1000; left:50px; top:50px; }
.div2 { width:200px; height:200px; background:#900; }
HTMl :
-----------------------
<div class="container">
<div class="div1">
Div1 content here .........
</div>
<div class="div2">
Div2 contenet here .........
</div>
</div>
SELECT f.name AS ForeignKey, OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ColumnName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
You don't need --header "Content-Length: $LENGTH".
curl --request POST --data-binary "@template_entry.xml" $URL
Note that GET request does not support content body widely.
Also remember that POST request have 2 different coding schema. This is first form:
$ nc -l -p 6666 & $ curl --request POST --data-binary "@README" http://localhost:6666 POST / HTTP/1.1 User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6 Host: localhost:6666 Accept: */* Content-Length: 9309 Content-Type: application/x-www-form-urlencoded Expect: 100-continue .. -*- mode: rst; coding: cp1251; fill-column: 80 -*- .. rst2html.py README README.html .. contents::
You probably request this:
-F/--form name=content (HTTP) This lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl to POST data using the Content- Type multipart/form-data according to RFC2388. This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.
window.WindowStyle = WindowStyle.None;
window.ResizeMode = ResizeMode.NoResize;
window.Left = 0;
window.Top = 0;
window.Width = SystemParameters.VirtualScreenWidth;
window.Height = SystemParameters.VirtualScreenHeight;
window.Topmost = true;
Works with multiple screens
A good option is AutoTable(a Table plugin for jsPDF), it includes themes, rowspan, colspan, extract data from html, works with json, you can also personalize your headers and make them horizontals. Here is a demo.
You can use the split()
function to break input on the basis of line break.
yourString.split("\n")
CookieManager.getInstance().setAcceptCookie(true);
Normally it should work if your webview is already initialized
or try this:
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
cookieManager.setAcceptCookie(true);
Sadly, no.
This is the way I would do it and it should be
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.get_json(silent=True)
# print(content) # Do your processing
return uuid
With silent=True
set, the get_json
function will fail silently when trying to retrieve the json body. By default this is set to False
. If you are always expecting a json body (not optionally), leave it as silent=False
.
Setting force=True
will ignore the
request.headers.get('Content-Type') == 'application/json'
check that flask does for you. By default this is also set to False
.
See flask documentation.
I would strongly recommend leaving force=False
and make the client send the Content-Type
header to make it more explicit.
Hope this helps!
In my case div position was fixed , adding left position was not enough it started working only after adding display block
left:0;
display:block;
this is how i did it
TabLayout.xml
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="@android:color/transparent"
app:tabGravity="fill"
app:tabMode="scrollable"
app:tabTextAppearance="@style/TextAppearance.Design.Tab"
app:tabSelectedTextColor="@color/myPrimaryColor"
app:tabIndicatorColor="@color/myPrimaryColor"
android:overScrollMode="never"
/>
Oncreate
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
mTabLayout = (TabLayout)findViewById(R.id.tab_layout);
mTabLayout.setOnTabSelectedListener(this);
setSupportActionBar(mToolbar);
mTabLayout.addTab(mTabLayout.newTab().setText("Dashboard"));
mTabLayout.addTab(mTabLayout.newTab().setText("Signature"));
mTabLayout.addTab(mTabLayout.newTab().setText("Booking/Sampling"));
mTabLayout.addTab(mTabLayout.newTab().setText("Calendar"));
mTabLayout.addTab(mTabLayout.newTab().setText("Customer Detail"));
mTabLayout.post(mTabLayout_config);
}
Runnable mTabLayout_config = new Runnable()
{
@Override
public void run()
{
if(mTabLayout.getWidth() < MainActivity.this.getResources().getDisplayMetrics().widthPixels)
{
mTabLayout.setTabMode(TabLayout.MODE_FIXED);
ViewGroup.LayoutParams mParams = mTabLayout.getLayoutParams();
mParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
mTabLayout.setLayoutParams(mParams);
}
else
{
mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
}
}
};
I made small changes of @Mario Velasco's solution on the runnable part
When attempting to troubleshoot this problem with svcutil
, I received the error referred to in dblood's answer ("referenced type cannot be used since it does not match imported DataContract").
In my case the underlying cause seemed to be an enum type that had the DataContract attribute, but whose members were not marked with the EnumMember attribute. The problem class svcutil
pointed at had a property with that enum type.
This would fit better as a comment to dblood's answer, but not enough rep for that...
I'd like to add a jQuery autocomplete based solution that does the job.
Step 1: Make the list fixed height and scrollable
Get the code from https://jqueryui.com/autocomplete/ "Scrollable" example, setting max height to the list of results so it behaves as a select box.
Step 2: Open the list on focus:
Display jquery ui auto-complete list on focus event
Step 3: Set minimum chars to 0 so it opens no matter how many chars are in the input
Final result:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Scrollable results</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
.ui-autocomplete {
max-height: 100px;
overflow-y: auto;
/* prevent horizontal scrollbar */
overflow-x: hidden;
}
/* IE 6 doesn't support max-height
* we use height instead, but this forces the menu to always be this tall
*/
* html .ui-autocomplete {
height: 100px;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
// source: availableTags, // uncomment this and comment the following to have normal autocomplete behavior
source: function (request, response) {
response( availableTags);
},
minLength: 0
}).focus(function(){
// $(this).data("uiAutocomplete").search($(this).val()); // uncomment this and comment the following to have autocomplete behavior when opening
$(this).data("uiAutocomplete").search('');
});
} );
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
Check jsfiddle here:
To get the titles for dates greater than a week ago today, use this:
SELECT title, MIN(date_key_no) AS intro_date FROM table HAVING MIN(date_key_no)>= TO_NUMBER(TO_CHAR(SysDate, 'YYYYMMDD')) - 7
In my development setup – missing a proper Groovy editor – a great deal of Jenkinsfile issues originates from simple syntax errors. To tackle this issue, you can validate the Jenkinsfile against your Jenkins instance (running at $JENKINS_HTTP_URL
):
curl -X POST -H $(curl '$JENKINS_HTTP_URL/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)') -F "jenkinsfile=<Jenkinsfile" $JENKINS_HTTP_URL/pipeline-model-converter/validate
The above command is a slightly modified version from https://github.com/jenkinsci/pipeline-model-definition-plugin/wiki/Validating-(or-linting)-a-Declarative-Jenkinsfile-from-the-command-line
According to PHPMailer Manual, full answer would be :
$mail->AddEmbeddedImage(filename, cid, name);
//Example
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');
Use Case :
$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Embedded Image: <img alt="PHPMailer" src="cid:my-attach"> Here is an image!';
If you want to display an image with a remote URL :
$mail->addStringAttachment(file_get_contents("url"), "filename");
git 2.7.1 (February 2016) clarifies that in commit b2c150d (05 Jan 2016) by David A. Wheeler (david-a-wheeler
).
(Merged by Junio C Hamano -- gitster
-- in commit 7aae9ba, 05 Feb 2016)
git commit
man page now includes:
-s::
--signoff::
Add
Signed-off-by
line by the committer at the end of the commit log message.
The meaning of a signoff depends on the project, but it typically certifies that committer has the rights to submit this work under the same license and agrees to a Developer Certificate of Origin (see https://developercertificate.org for more information).
Expand documentation describing
--signoff
Modify various document (man page) files to explain in more detail what
--signoff
means.This was inspired by "lwn article 'Bottomley: A modest proposal on the DCO'" (Developer Certificate of Origin) where paulj noted:
The issue I have with DCO is that there adding a "
-s
" argument to git commit doesn't really mean you have even heard of the DCO (thegit commit
man page makes no mention of the DCO anywhere), never mind actually seen it.So how can the presence of "
signed-off-by
" in any way imply the sender is agreeing to and committing to the DCO? Combined with fact I've seen replies on lists to patches without SOBs that say nothing more than "Resend this withsigned-off-by
so I can commit it".Extending git's documentation will make it easier to argue that developers understood
--signoff
when they use it.
Note that this signoff is now (for Git 2.15.x/2.16, Q1 2018) available for git pull
as well.
See commit 3a4d2c7 (12 Oct 2017) by W. Trevor King (wking
).
(Merged by Junio C Hamano -- gitster
-- in commit fb4cd88, 06 Nov 2017)
pull
: pass--signoff/--no-signoff
to "git merge
"merge can take
--signoff
, but without pull passing--signoff
down, it is inconvenient to use; allow 'pull
' to take the option and pass it through.
If you have no idea which Package you need to import:
import static org.mockito.ArgumentMatchers.any;
any(SomeClass.class)
OR
import org.mockito.ArgumentMatchers;
ArgumentMatchers.any(SomeClass.class)
It's worth noting that the QuerySet.values_list()
method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet
, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.
Somewhat irritatingly, though, this object has a custom __repr__
method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.
The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...
my_list = list(self.get_queryset().values_list('code', flat=True))
...then you can convert it to JSON with...
json_data = json.dumps(my_list)
You'll also have to place the resulting JSON data in an HttpResponse
object, which, apparently, should have a Content-Type
of application/json
, with...
response = HttpResponse(json_data, content_type='application/json')
...which you can then return from your function.
The current answers did not solve the problem for me, because I had node installed in /usr/bin/node and /usr/local/bin/node - so the system always resolved these first, and ignored the nvm version.
I solved the issue by moving the existing versions to /usr/bin/node-system and /usr/local/bin/node-system
Then I had no node command anymore, until I used nvm use :(
I solved this issue by creating a symlink to the version that would be installed by nvm.
sudo mv /usr/local/bin/node /usr/local/bin/node-system
sudo mv /usr/bin/node /usr/bin/node-system
nvm use node
Now using node v12.20.1 (npm v6.14.10)
which node
/home/paul/.nvm/versions/node/v12.20.1/bin/node
sudo ln -s /home/paul/.nvm/versions/node/v12.20.1/bin/node /usr/bin/node
Then open a new shell
node -v
v12.20.1
It's easier to help you if you say what's wrong as well, or what fails when you run it.
But from a quick glance you've confused a few things.
The following doesn't work because of a couple of issues.
if (Directory("C:\\csharp\\error report1.xls") = "")
What you are trying to do is creating a new Directory object that should point to a file and then check if there was any errors.
What you are actually doing is trying to call a function named Directory() and then assign a string to the result. This won't work since 1/ you don't have a function named Directory(string str) and you cannot assign to the result from a function (you can only assign a value to a variable).
What you should do (for this line at least) is the following
FileInfo fi = new FileInfo("C:\\csharp\\error report1.xls");
if(!fi.Exists)
{
// Create the xl file here
}
else
{
// Open file here
}
As to why the Excel code doesn't work, you have to check the documentation for the Excel library which google should be able to provide for you.
Technically, all Java objects are pointers. All primitive types are values though. There is no way to take manual control of those pointers. Java just internally uses pass-by-reference.
A BigDecimal
is an exact way of representing numbers. A Double
has a certain precision. Working with doubles of various magnitudes (say d1=1000.0
and d2=0.001
) could result in the 0.001
being dropped alltogether when summing as the difference in magnitude is so large. With BigDecimal
this would not happen.
The disadvantage of BigDecimal
is that it's slower, and it's a bit more difficult to program algorithms that way (due to +
-
*
and /
not being overloaded).
If you are dealing with money, or precision is a must, use BigDecimal
. Otherwise Doubles
tend to be good enough.
I do recommend reading the javadoc of BigDecimal
as they do explain things better than I do here :)
No need to care of whether before/after this digit having other type of words
To just match the pattern of 5 digits number anywhere in the string, no matter it is separated by space or not, use this regular expression (?<!\d)\d{5}(?!\d)
.
Sample JavaScript codes:
var regexp = new RegExp(/(?<!\d)\d{5}(?!\d)/g);
var matches = yourstring.match(regexp);
if (matches && matches.length > 0) {
for (var i = 0, len = matches.length; i < len; i++) {
// ... ydo something with matches[i] ...
}
}
Here's some quick results.
abc12345xyz (?)
12345abcd (?)
abcd12345 (?)
0000aaaa2 (?)
a1234a5 (?)
12345 (?)
<space>
12345<space>
12345 (??)
Maybe try this:
yum -y groupinstall "MYSQL Database Client"
SELECT DEPTNAME
FROM(SELECT D.DEPTNAME,COUNT(EMPID) AS TOTEMP
FROM DEPT AS D,EMPLOYEE AS E
WHERE D.DEPTID=E.DEPTID AND SALARY>1000
GROUP BY D.DEPTID
)
WHERE TOTEMP>2;
For this example you really should just use an outer join.
declare
begin
FOR attr_rec IN (
select attr
from USER_TABLE u
left outer join attribute_table a
on ( u.USERTYPE = 'X' and a.user_id = u.id )
) LOOP
<process records>
<if primary key of attribute_table is null
then the attribute does not exist for this user.>
END LOOP;
END;
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>teste4</groupId>
<artifactId>teste4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.primefaces.themes</groupId>
<artifactId>bootstrap</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.7.Final</version>
</dependency>
</dependencies>
</project>
window.location is just what you need. Other thing you can do is to create anchor element and simulate click on it
$("<a href='your url'></a>").click();
Why not use a Single liner ...
IEnumerable<Book> _Book_IE= _Book_List as IEnumerable<Book>;
In Android 2.0+ this would look like:
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
In earlier versions it would look like:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if(keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.quit)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
YourClass.this.finish();
}
})
.setNegativeButton(R.string.no, null)
.show();
return true;
}
else {
return super.onKeyDown(keyCode, event);
}
}
Hi there is my code for pagination: Use in blade @include('pagination.default', ['paginator' => $users])
Views/pagination/default.blade.php
@if ($paginator->lastPage() > 1)
si la pagina actual es distinto a 1 y hay mas de 5 hojas muestro el boton de 1era hoja --> if actual page is not equals 1, and there is more than 5 pages then I show first page button --> @if ($paginator->currentPage() != 1 && $paginator->lastPage() >= 5) << @endif
<!-- si la pagina actual es distinto a 1 muestra el boton de atras -->
@if($paginator->currentPage() != 1)
<li>
<a href="{{ $paginator->url($paginator->currentPage()-1) }}" >
<
</a>
</li>
@endif
<!-- dibuja las hojas... Tomando un rango de 5 hojas, siempre que puede muestra 2 hojas hacia atras y 2 hacia adelante -->
<!-- I draw the pages... I show 2 pages back and 2 pages forward -->
@for($i = max($paginator->currentPage()-2, 1); $i <= min(max($paginator->currentPage()-2, 1)+4,$paginator->lastPage()); $i++)
<li class="{{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
<a href="{{ $paginator->url($i) }}">{{ $i }}</a>
</li>
@endfor
<!-- si la pagina actual es distinto a la ultima muestra el boton de adelante -->
<!-- if actual page is not equal last page then I show the forward button-->
@if ($paginator->currentPage() != $paginator->lastPage())
<li>
<a href="{{ $paginator->url($paginator->currentPage()+1) }}" >
>
</a>
</li>
@endif
<!-- si la pagina actual es distinto a la ultima y hay mas de 5 hojas muestra el boton de ultima hoja -->
<!-- if actual page is not equal last page, and there is more than 5 pages then I show last page button -->
@if ($paginator->currentPage() != $paginator->lastPage() && $paginator->lastPage() >= 5)
<li>
<a href="{{ $paginator->url($paginator->lastPage()) }}" >
>>
</a>
</li>
@endif
</ul>
Olmo's suggestion is very good, but I'd add this: If you're not sure about the size, it's better to make it a little bigger than a little smaller. When a list is full, keep in mind it will double its size to add more elements.
For example: suppose you will need about 50 elements. If you use a 50 elements size and the final number of elements is 51, you'll end with a 100 sized list with 49 wasted positions.
No, that's pretty much it. In theory you could use visibility: collapse
on some <col>
?s to do it, but browser support isn't all there.
To improve what you've got slightly, you could use table-layout: fixed
on the <table>
to allow the browser to use the simpler, faster and more predictable fixed-table-layout algorithm. You could also drop the .show
rules as when a cell isn't made display: none
by a .hide
rule it will automatically be display: table-cell
. Allowing table display to revert to default rather than setting it explicitly avoids problems in IE<8, where the table display values are not supported.
I finally found the fix for this!
As we have found, IB doesn't allow us to change the height of the rounded corner border style. So change it to any of the other styles and set the desired height. In the code change the border style back.
textField.borderStyle = UITextBorderStyleRoundedRect;
For kotlin I use the following
val fcmtoken = FirebaseMessaging.getInstance().token.await()
and for the extension functions
public suspend fun <T> Task<T>.await(): T {
// fast path
if (isComplete) {
val e = exception
return if (e == null) {
if (isCanceled) {
throw CancellationException("Task $this was cancelled normally.")
} else {
@Suppress("UNCHECKED_CAST")
result as T
}
} else {
throw e
}
}
return suspendCancellableCoroutine { cont ->
addOnCompleteListener {
val e = exception
if (e == null) {
@Suppress("UNCHECKED_CAST")
if (isCanceled) cont.cancel() else cont.resume(result as T)
} else {
cont.resumeWithException(e)
}
}
}
}
You can add either -DskipTests
or -Dmaven.test.skip=true
to any mvn
command for skipping tests. In your case it would be like below:
mvn package -DskipTests
OR
mvn package -Dmaven.test.skip=true
You probably don't want to pass the car
object as a parameter, try just passing car.id
. What do you get when you inspect(params)
after clicking "Add to cart"?
If your classes are in packages then you have to cd
to the root directory of your project and run using the fully qualified name of the class (packageName.MainClassName).
Example:
My classes are in here:
D:\project\com\cse\
The fully qualified name of my main class is:
com.cse.Main
So I cd
back to the root project directory:
D:\project
Then issue the java
command:
java com.cse.Main
This answer is for rescuing newbie java programmers from the frustration caused by a common mistake, I recommend you read the accepted answer for more in depth knowledge about the java classpath.
If you could use something other than 'awk' , then try this instead
echo '1540 "A B"' | cut -d' ' -f2-
-d is a delimiter, -f is the field to cut and with -f2- we intend to cut the 2nd field until end.
Stegmenn nalied it for me but I had one change for when you have an IEnumerbale instead of a string = message like in his example.
private static string GetRoles(IEnumerable<External.Role> roles)
{
string[] switchStrings = { "Staff", "Board Member" };
switch (switchStrings.FirstOrDefault<string>(s => roles.Select(t => t.RoleName).Contains(s)))
{
case
"Staff":
roleNameValues += "Staff,";
break;
case
"Board Member":
roleNameValues += "Director,";
break;
default:
break;
}
Tried the cross, works nicely, but takes slightly longer. Adjusted line columns to have max and added group which kept speed and dropped the extra record.
Here's the adjusted query:
SELECT Orders.OrderNumber, max(LineItems.Quantity), max(LineItems.Description)
FROM Orders
INNER JOIN LineItems
ON Orders.OrderID = LineItems.OrderID
Group by Orders.OrderNumber
if result is None:
print "error parsing stream"
elif result:
print "result pass"
else:
print "result fail"
keep it simple and explicit. You can of course pre-define a dictionary.
messages = {None: 'error', True: 'pass', False: 'fail'}
print messages[result]
If you plan on modifying your simulate
function to include more return codes, maintaining this code might become a bit of an issue.
The simulate
might also raise an exception on the parsing error, in which case you'd either would catch it here or let it propagate a level up and the printing bit would be reduced to a one-line if-else statement.
Typescript supports default parameters now:
https://www.typescriptlang.org/docs/handbook/functions.html
Also, adding a default value allows you to omit the type declaration, because it can be inferred from the default value:
function sayName(firstName: string, lastName = "Smith") {
const name = firstName + ' ' + lastName;
alert(name);
}
sayName('Bob');
There is a difference between early performance optimization and using a best practice type of rule. If you are creating new tables where you will always have a fixed length field, it makes sense to use CHAR, you should be using it in that case. This isn't early optimization, but rather implementing a rule of thumb (or best practice).
i.e. - If you have a 2 letter state field, use CHAR(2). If you have a field with the actual state names, use VARCHAR.
Shallow copy:
Some members of the copy may reference the same objects as the original:
class X
{
private:
int i;
int *pi;
public:
X()
: pi(new int)
{ }
X(const X& copy) // <-- copy ctor
: i(copy.i), pi(copy.pi)
{ }
};
Here, the pi
member of the original and copied X
object will both point to the same int
.
Deep copy:
All members of the original are cloned (recursively, if necessary). There are no shared objects:
class X
{
private:
int i;
int *pi;
public:
X()
: pi(new int)
{ }
X(const X& copy) // <-- copy ctor
: i(copy.i), pi(new int(*copy.pi)) // <-- note this line in particular!
{ }
};
Here, the pi
member of the original and copied X
object will point to different int
objects, but both of these have the same value.
The default copy constructor (which is automatically provided if you don't provide one yourself) creates only shallow copies.
Correction: Several comments below have correctly pointed out that it is wrong to say that the default copy constructor always performs a shallow copy (or a deep copy, for that matter). Whether a type's copy constructor creates a shallow copy, or deep copy, or something in-between the two, depends on the combination of each member's copy behaviour; a member's type's copy constructor can be made to do whatever it wants, after all.
Here's what section 12.8, paragraph 8 of the 1998 C++ standard says about the above code examples:
The implicitly defined copy constructor for class
X
performs a memberwise copy of its subobjects. [...] Each subobject is copied in the manner appropriate to its type: [...] [I]f the subobject is of scalar type, the builtin assignment operator is used.
The code you posted gives the critical value for a one-sided test (Hence the answer to you question is simply:
abs(qt(0.25, 40)) # 75% confidence, 1 sided (same as qt(0.75, 40))
abs(qt(0.01, 40)) # 99% confidence, 1 sided (same as qt(0.99, 40))
Note that the t-distribution is symmetric. For a 2-sided test (say with 99% confidence) you can use the critical value
abs(qt(0.01/2, 40)) # 99% confidence, 2 sided
If you make
overflow: hidden
in the outer div and overflow-y: scroll
in the inner div it will work.
This can be done using the shuffle method:
private List<Integer> getJumbledList() {
List<Integer> myArrayList2 = new ArrayList<Integer>();
myArrayList2.add(8);
myArrayList2.add(4);
myArrayList2.add(9);
Collections.shuffle(myArrayList2);
return myArrayList2;
For anyone trying to use jQuery.active with JSONP requests (like I was) you'll need enable it with this:
jQuery.ajaxPrefilter(function( options ) {
options.global = true;
});
Keep in mind that you'll need a timeout on your JSONP request to catch failures.
If your compiler is GCC you can also use following syntax:
int array[256] = {[0 ... 255] = 0};
Please look at http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits.html#Designated-Inits, and note that this is a compiler-specific feature.
Type-safe means that programmatically, the type of data for a variable, return value, or argument must fit within a certain criteria.
In practice, this means that 7 (an integer type) is different from "7" (a quoted character of string type).
PHP, Javascript and other dynamic scripting languages are usually weakly-typed, in that they will convert a (string) "7" to an (integer) 7 if you try to add "7" + 3, although sometimes you have to do this explicitly (and Javascript uses the "+" character for concatenation).
C/C++/Java will not understand that, or will concatenate the result into "73" instead. Type-safety prevents these types of bugs in code by making the type requirement explicit.
Type-safety is very useful. The solution to the above "7" + 3 would be to type cast (int) "7" + 3 (equals 10).
An additional option is to go to your build folder and use the command ccmake .
This is like the GUI but terminal based. This obviously won't help with an installation script but at least it can be run without a UI.
The one warning I have is it won't let you generate sometimes when you have warnings. if that is the case, exit the interface and call cmake .
I also got the same error in my SQL Code, This solution works for me,
Check the data in Primary Table May be you are entering a column value which is not present in the primary key column.
UPDATE `table_name` SET `test` = `number`
You can also do any mathematical changes in the process or use MySQL functions to modify the values.
You could also go into XCode -> Preferences, select the Indentation tab, and turn on Line Wrapping.
That way, you won't have to type anything extra, and it will work for the stuff you already wrote. :-)
One annoying thing though is...
if (you're long on indentation
&& short on windows) {
then your code will
end up squished
against th
e side
li
k
e
t
h
i
s
}
The following is a solution extracted from Expert C Programming: Deep Secrets, which is supposed to work on SVr4. It uses stty and ioctl.
#include <sys/filio.h>
int kbhit()
{
int i;
ioctl(0, FIONREAD, &i);
return i; /* return a count of chars available to read */
}
main()
{
int i = 0;
intc='';
system("stty raw -echo");
printf("enter 'q' to quit \n");
for (;c!='q';i++) {
if (kbhit()) {
c=getchar();
printf("\n got %c, on iteration %d",c, i);
}
}
system("stty cooked echo");
}
height:500px;
min-width:100%;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size:100% 100%;
object-fit:cover;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size:cover;
You can have only one public class in a file else you will get the error what you are getting now and name of file must be the name of public class
Something like this, I think. find_if_counted.hpp
:
#ifndef FIND_IF_COUNTED_HPP
#define FIND_IF_COUNTED_HPP
#include <algorithm>
namespace find_if_counted_impl
{
template <typename Func>
struct func_counter
{
explicit func_counter(Func& func, unsigned &count) :
_func(func),
_count(count)
{
}
template <typename T>
bool operator()(const T& t)
{
++_count;
return _func(t);
}
private:
Func& _func;
unsigned& _count;
};
}
// generic find_if_counted,
// returns the index of the found element, otherwise returns find_if_not_found
const size_t find_if_not_found = static_cast<size_t>(-1);
template <typename InputIterator, typename Func>
size_t find_if_counted(InputIterator start, InputIterator finish, Func func)
{
unsigned count = 0;
find_if_counted_impl::func_counter<Func> f(func, count);
InputIterator result = find_if(start, finish, f);
if (result == finish)
{
return find_if_not_found;
}
else
{
return count - 1;
}
}
#endif
Example:
#include "find_if_counted.hpp"
#include <cstdlib>
#include <iostream>
#include <vector>
typedef std::vector<int> container;
int rand_number(void)
{
return rand() % 20;
}
bool is_even(int i)
{
return i % 2 == 0;
}
int main(void)
{
container vec1(10);
container vec2(10);
std::generate(vec1.begin(), vec1.end(), rand_number);
std::generate(vec2.begin(), vec2.end(), rand_number);
unsigned index = find_if_counted(vec1.begin(), vec1.end(), is_even);
if (index == find_if_not_found)
{
std::cout << "vec1 has no even numbers." << std::endl;
}
else
{
std::cout << "vec1 had an even number at index: " << index <<
" vec2's corresponding number is: " << vec2[index] << std::endl;
}
}
Though I feel like I'm doing something silly... :X Any corrections are welcome, of course.
If you are looking for just any selection from the drop-down box, I also find "select by index" method very useful.
if (IsElementPresent(By.XPath("//select[@id='Q43_0']")))
{
new SelectElement(driver.FindElement(By.Id("Q43_0")))**.SelectByIndex(1);** // This is selecting first value of the drop-down list
WaitForAjax();
Thread.Sleep(3000);
}
else
{
Console.WriteLine("Your comment here);
}
If you have numpy available:
>>> import numpy as np
>>> states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> np.where(states)[0]
array([4, 5, 7])
Just an addendum, so nobody else goes through the annoyance I recently did:
AFAIK, the best solution is one along the general lines of toast38coza's above. If it makes sense to tie your password files and your playbook together statically, then follow his template with vars_files
(or include_vars
). If you want to keep them separate, you can supply the vault contents on the command line like so:
ansible-playbook --ask-vault-pass -e@<PATH_TO_VAULT_FILE> <PLAYBOOK_FILE>
That's obvious in retrospect, but here are the gotchas:
That bloody @ sign. If you leave it out, parsing will fail silently, and ansible-playbook will proceed as though you'd never specified the file in the first place.
You must explicitly import the contents of the vault, either with a command-line --extra-vars/-e or within your YAML code. The --ask-vault-pass
flag doesn't do anything by itself (besides prompt you for a value which may or may not be used later).
May you include your "@"s and save an hour.
Try this out
CREATE FUNCTION [dbo].[Split]
(
@ListOfValues varchar(max),
@ValueSeparator varchar(10)
)
RETURNS @ListOfValuesInRows TABLE
(
Value varchar(max)
)
AS
BEGIN
IF Len(@ListOfValues) = 0
RETURN
if @ValueSeparator <> ' '
Begin
WHILE CHARINDEX(@ValueSeparator, @ListOfValues) > 0
BEGIN
INSERT INTO @ListOfValuesInRows
SELECT LTRIM(RTRIM(SUBSTRING(@ListOfValues, 1, CHARINDEX(@ValueSeparator, @ListOfValues)-1)))
SET @ListOfValues = SubString(@ListOfValues, CharIndex(@ValueSeparator, @ListOfValues)+Len(@ValueSeparator), Len(@ListOfValues))
END
INSERT INTO @ListOfValuesInRows
SELECT LTRIM(RTRIM(@ListOfValues))
End
Else
BEGIN
DECLARE @xml XML;
SET @xml = N'<t>' + REPLACE(@ListOfValues, @ValueSeparator, '</t><t>') + '</t>';
INSERT INTO @ListOfValuesInRows (Value)
SELECT LTRIM(RTRIM(r.value( '.', 'varchar(MAX)' ))) AS item
FROM @xml.nodes( '/t' ) AS records( r )
END
RETURN
END
Locks are a concept required in a multi-threaded system. Even with worker threads, messages are sent by value between workers so that locking is unnecessary.
I suspect you need to just set a semaphore (flagging system) between your buttons.
There is a Headers
property in the HttpRequestMessage
class. You can add custom headers there, which will be sent with each HTTP request. The DefaultRequestHeaders
in the HttpClient
class, on the other hand, sets headers to be sent with each request sent using that client object, hence the name Default Request Headers.
Hope this makes things more clear, at least for someone seeing this answer in future.
My solution to this issue was to create the function shown below. My requirements included that the number had to be a standard integer, not a BIGINT, and I needed to allow negative numbers and positive numbers. I have not found a circumstance where this fails.
CREATE FUNCTION [dbo].[udfIsInteger]
(
-- Add the parameters for the function here
@Value nvarchar(max)
)
RETURNS int
AS
BEGIN
-- Declare the return variable here
DECLARE @Result int = 0
-- Add the T-SQL statements to compute the return value here
DECLARE @MinValue nvarchar(11) = '-2147483648'
DECLARE @MaxValue nvarchar(10) = '2147483647'
SET @Value = ISNULL(@Value,'')
IF LEN(@Value)=0 OR
ISNUMERIC(@Value)<>1 OR
(LEFT(@Value,1)='-' AND LEN(@Value)>11) OR
(LEFT(@Value,1)='-' AND LEN(@Value)=11 AND @Value>@MinValue) OR
(LEFT(@Value,1)<>'-' AND LEN(@Value)>10) OR
(LEFT(@Value,1)<>'-' AND LEN(@Value)=10 AND @Value>@MaxValue)
GOTO FINISHED
DECLARE @cnt int = 0
WHILE @cnt<LEN(@Value)
BEGIN
SET @cnt=@cnt+1
IF SUBSTRING(@Value,@cnt,1) NOT IN ('-','0','1','2','3','4','5','6','7','8','9') GOTO FINISHED
END
SET @Result=1
FINISHED:
-- Return the result of the function
RETURN @Result
END
If you need fast lookup (basically constant time) of a object stored in your collection you should use Map instead of List.
If you need fast iteration of the objects you should use List.
So in your case...
Map<String,Customer> customers = new HashMap<String,Customer>();
//somewhere in the code you fill up the Map, assuming customer names are unique
customers.put(customer.getName(), customer)
// at some later point you retrieve it like this;
// this is fast, given a good hash
// been calculated for the "keys" in your map, in this case the keys are unique
// String objects so the default hash algorithm should be fine
Customer theCustomerYouLookFor = customers.get("Doe");
// modify it
theCustomerYouLookFor.setEmail("[email protected]")
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("parameter", "value").build();
return chain.proceed(request);
}
});
Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(url).client(httpClient.build()).build();
You need to parse the url first, so it goes like this:
$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
If you need to parse the actual url of the current browser, you need to request to call the server.
$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
SELECT * FROM
(SELECT [UserID] FROM [User]) a
LEFT JOIN (SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) b
ON a.UserId = b.TailUser
we can find length of array by using array_name.length attribute
int [] i = i.length;
Assume your file looks like this and is named test.txt (space delimited):
1 2
3 4
5 6
7 8
Then:
#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
with open("test.txt") as f:
data = f.read()
data = data.split('\n')
x = [row.split(' ')[0] for row in data]
y = [row.split(' ')[1] for row in data]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_title("Plot title...")
ax1.set_xlabel('your x label..')
ax1.set_ylabel('your y label...')
ax1.plot(x,y, c='r', label='the data')
leg = ax1.legend()
plt.show()
I find that browsing the gallery of plots on the matplotlib site helpful for figuring out legends and axes labels.
Similar to older answers, but a bit simpler, without the lambda:
filter_kwargs = {
'field_a': 123,
'field_b__in': (3, 4, 5, ),
}
To filter these two conditions using OR
:
Item.objects.filter(Q(field_a=123) | Q(field_b__in=(3, 4, 5, ))
To get the same result programmatically:
list_of_Q = [Q(**{key: val}) for key, val in filter_kwargs.items()]
Item.objects.filter(reduce(operator.or_, list_of_Q))
(broken in two lines here, for clarity)
operator
is in standard library: import operator
From docstring:
or_(a, b) -- Same as a | b.
For Python3, reduce
is not a builtin any more but is still in the standard library: from functools import reduce
P.S.
Don't forget to make sure list_of_Q
is not empty - reduce()
will choke on empty list, it needs at least one element.
I ran into similar problem a while back and what was happening in my case was the outer recycler view was working perfectly fine but the the adapter of inner/second recycler view had minor issues all the methods like constructor got initiated and even getCount() method was being called, although the final methods responsible to generate view ie..
1. onBindViewHolder() methods never got called. --> Problem 1.
2. When it got called finally it never show the list items/rows of recycler view. --> Problem 2.
Reason why this happened :: When you put a recycler view inside another recycler view, then height of the first/outer recycler view is not auto adjusted. It is defined when the first/outer view is created and then it remains fixed. At that point your second/inner recycler view has not yet loaded its items and thus its height is set as zero and never changes even when it gets data. Then when onBindViewHolder() in your second/inner recycler view is called, it gets items but it doesn't have the space to show them because its height is still zero. So the items in the second recycler view are never shown even when the onBindViewHolder() has added them to it.
Solution :: you have to create your custom LinearLayoutManager for the second recycler view and that is it.
To create your own LinearLayoutManager: Create a Java class with the name CustomLinearLayoutManager
and paste the code below into it. NO CHANGES REQUIRED
public class CustomLinearLayoutManager extends LinearLayoutManager {
private static final String TAG = CustomLinearLayoutManager.class.getSimpleName();
public CustomLinearLayoutManager(Context context) {
super(context);
}
public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i, View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
try {
View view = recycler.getViewForPosition(position);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
func copyToString(r io.Reader) (res string, err error) {
var sb strings.Builder
if _, err = io.Copy(&sb, r); err == nil {
res = sb.String()
}
return
}
You would want to use CSS to achieve that.
say you have a table with the attribute id="my_table"
You would want to write the following in your css file
#my_table{
margin-top:10px //moves your table 10pixels down
margin-left:10px //moves your table 10pixels right
}
if you do not have a CSS file then you may just add margin-top:10px, margin-left:10px
to the style attribute in your table element like so
<table style="margin-top:10px; margin-left:10px;">
....
</table>
There are a lot of resources on the net describing CSS and HTML in detail
I tried many different solutions and this for me was the best:
SpannableStringBuilder ssb = new SpannableStringBuilder(" Hello world!");
ssb.setSpan(new ImageSpan(context, R.drawable.image), 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
tv_text.setText(ssb, TextView.BufferType.SPANNABLE);
This code uses a minimum of memory.
You need to hook to console exit event and not your process.
http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx
I found that, some of you found that the IP address you get is :::1 or 0.0.0.1
This is the problem because of you try to get IP from your own machine, and the confusion of C# that try to return IPv6.
So, I implement the answer from @Johna (https://stackoverflow.com/a/41335701/812720) and @David (https://stackoverflow.com/a/8597351/812720), Thanks to them!
and here to solution:
add Microsoft.AspNetCore.HttpOverrides Package in your References (Dependencies/Packages)
add this line in Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// your current code
// start code to add
// to get ip address
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
// end code to add
}
to get IPAddress, use this code in any of your Controller.cs
IPAddress remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress;
string result = "";
if (remoteIpAddress != null)
{
// If we got an IPV6 address, then we need to ask the network for the IPV4 address
// This usually only happens when the browser is on the same machine as the server.
if (remoteIpAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{
remoteIpAddress = System.Net.Dns.GetHostEntry(remoteIpAddress).AddressList
.First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
}
result = remoteIpAddress.ToString();
}
and now you can get IPv4 address from remoteIpAddress or result
Assuming this example HTML:
<input type="text" name="email" id="email" />
<input type="text" name="first_name" id="first_name" />
<input type="text" name="last_name" id="last_name" />
You could have this javascript:
$("#email").bind("change", function(e){
$.getJSON("http://yourwebsite.com/lokup.php?email=" + $("#email").val(),
function(data){
$.each(data, function(i,item){
if (item.field == "first_name") {
$("#first_name").val(item.value);
} else if (item.field == "last_name") {
$("#last_name").val(item.value);
}
});
});
});
Then just you have a PHP script (in this case lookup.php) that takes an email in the query string and returns a JSON formatted array back with the values you want to access. This is the part that actually hits the database to look up the values:
<?php
//look up the record based on email and get the firstname and lastname
...
//build the JSON array for return
$json = array(array('field' => 'first_name',
'value' => $firstName),
array('field' => 'last_name',
'value' => $last_name));
echo json_encode($json );
?>
You'll want to do other things like sanitize the email input, etc, but should get you going in the right direction.
In Oracle 12c you can use the function STANDARD_HASH. It does not require any additional privileges.
select standard_hash('foo', 'MD5') from dual;
The dbms_obfuscation_toolkit is deprecated (see Note here). You can use DBMS_CRYPTO directly:
select rawtohex(
DBMS_CRYPTO.Hash (
UTL_I18N.STRING_TO_RAW ('foo', 'AL32UTF8'),
2)
) from dual;
Output:
ACBD18DB4CC2F85CEDEF654FCCC4A4D8
Add a lower function call if needed. More on DBMS_CRYPTO.
In my case this error was happening because I had an old version of ng cli in my computer.
The problem was solved after running:
ng update
ng update @angular/cli
This is the official documentation supporting the above answers.
Changing the icon font location Bootstrap assumes icon font files will be located in the ../fonts/ directory, relative to the compiled CSS files. Moving or renaming those font files means updating the CSS in one of three ways: Change the @icon-font-path and/or @icon-font-name variables in the source Less files. Utilize the relative URLs option provided by the Less compiler. Change the url() paths in the compiled CSS. Use whatever option best suits your specific development setup.
Other than this one mistake the new users would do is, after downloading the bootstrap zip from the official website. They would tend to skip the fonts folder for copying in their dev setup. So missing fonts folder can also lead to this problem
Check the below links:
Implicit Wait
- It instructs the web driver to wait for some time by poll the DOM. Once you declared implicit wait it will be available for the entire life of web driver instance. By default the value will be 0. If you set a longer default, then the behavior will poll the DOM on a periodic basis depending on the browser/driver implementation.
Explicit Wait
+ ExpectedConditions
- It is the custom one. It will be used if we want the execution to wait for some time until some condition achieved.
<?php
$first = reset($arr_nav); // Get the first element
$last = end($arr_nav); // Get the last element
// Ensure that we have a first element and that it's an array
if(is_array($first)) {
$first['class'] = 'first';
}
// Ensure we have a last element and that it differs from the first
if(is_array($last) && $last !== $first) {
$last['class'] = 'last';
}
Now you could just echo the class inside you html-generator. Would probably need some kind of check to ensure that the class is set, or provide a default empty class to the array.
File > Settings > Build, Execution, Deployment > Gradle > Offline work
please check if you have 2 lock files if yes then leave the package-lock.json and delete the other one like yarn.lock
Then execute these commands.
Use conditional formatting.
You can enter a condition using any cell you like and a format to apply if the formula is true.
In SQL, the 'WHERE' and 'ON' clause,are kind of Conditional Statemants, but the major difference between them are, the 'Where' Clause is used in Select/Update Statements for specifying the Conditions, whereas the 'ON' Clause is used in Joins, where it verifies or checks if the Records are Matched in the target and source tables, before the Tables are Joined
For Example: - 'WHERE'
SELECT * FROM employee WHERE employee_id=101
For Example: - 'ON'
There are two tables employee and employee_details, the matching columns are employee_id.
SELECT * FROM employee
INNER JOIN employee_details
ON employee.employee_id = employee_details.employee_id
Hope I have answered your Question. Revert for any clarifications.
In Visual Studio 2012, open the Options dialog (Tools -> Options). Under Environment -> General, the first setting is "Color theme." You can use this to switch between Light and Dark.
The shell theme is distinct from the editor theme--you can use any editor fonts and colors settings with either shell theme.
There is also a Color Theme Editor extension that can be used to create new themes.
Why use getters and setters?
let indexPathRow:Int = 0
let indexPosition = IndexPath(row: indexPathRow, section: 0)
tableView.reloadRows(at: [indexPosition], with: .none)
I tried deleting the lock file, but the real reason that this happened to me was because I was using ~/data/db as the data directory. Mongo needs an absolute path to the database. Once I changed it to /home//data/db, I was in business.
I created this table which contains both the heights of iPhone and iPad keyboards, both for landscape and portrait mode, both with the toolbar on and off.
I even explained how you can use these dimensions in your code here.
Note that you should only use these dimensions if you need to know the keyboard's dimension before you layout the view. Otherwise the solutions from the other answers work better.
A very basic approach is alert(arrayObj.join('\n'))
, which will display each array element in a row.
functional solution
function applyFilters(data, filters) {
return data.filter(item =>
Object.keys(filters)
.map(keyToFilterOn =>
item[keyToFilterOn].includes(filters[keyToFilterOn]),
)
.reduce((x, y) => x && y, true),
);
}
this should do the job
applyFilters(users, filter);
No trick necessary.
grep --with-filename 'pattern' file
With line numbers:
grep -n --with-filename 'pattern' file
You can also stringify the object and then again parse to make the normal object. For example like:-
const obj = JSON.parse(JSON.stringify(mongoObj))
instance.__class__.__name__
example:
>>> class A():
pass
>>> a = A()
>>> a.__class__.__name__
'A'
Use application/javascript
as content type instead of text/javascript
text/javascript
is mentioned obsolete. See reference docs.
http://www.iana.org/assignments/media-types/application
Also see this question on SO.
UPDATE:
I have tried executing the code you have given and the below didn't work.
res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);
This is what worked for me.
res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);
As robertklep has suggested, please refer to the node http docs, there is no response.send()
there.
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<b><centre>Redirecting to Google<br>");
response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url after 5 seconds
pw.close();
}
}
I would use the "Responsive Design View" available under Tools -> Web Developer -> Responsive Design View. It will let you test your CSS against different screen sizes.
Follow 2 steps-
1. First set the $locationProvider.html5Mode(true) in your app config file.
For eg -
angular.module('test', ['ui.router']) .config(function($stateProvider, $urlRouterProvider, $locationProvider) { $locationProvider.html5Mode(true); $urlRouterProvider.otherwise('/'); });
2.Second set the <base> inside your main page.
For eg ->
<base href="/">
The $location service will automatically fallback to the hash-part method for browsers that do not support the HTML5 History API.
why don't you give a try to inkscape command line, this is my bat file to convert all svg in this dir to png:
FOR %%x IN (*.svg) DO C:\Ink\App\Inkscape\inkscape.exe %%x -z --export-dpi=500 --export-area-drawing --export-png="%%~nx.png"
This issue got it solved.
/etc/nginx/nginx.conf
sudo chown -R nginx:nginx /var/lib/nginx
Now see the magic.
In latest git version like 2.7.4,
git checkout branch_name
#branch name which you want to change tracking branch
git branch --set-upstream-to=upstream/tracking_branch_name
#upstream - remote name
I am amazed how I've not been able to find a clear example of how to authenticate an user right from the login screen down to using the Authorize attribute over my ApiController methods after several hours of Googling.
That's because you are getting confused about these two concepts:
Authentication is the mechanism whereby systems may securely identify their users. Authentication systems provide an answers to the questions:
Authorization is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system. For example, a database management system might be designed so as to provide certain specified individuals with the ability to retrieve information from a database but not the ability to change data stored in the datbase, while giving other individuals the ability to change data. Authorization systems provide answers to the questions:
The Authorize
attribute in MVC is used to apply access rules, for example:
[System.Web.Http.Authorize(Roles = "Admin, Super User")]
public ActionResult AdministratorsOnly()
{
return View();
}
The above rule will allow only users in the Admin and Super User roles to access the method
These rules can also be set in the web.config file, using the location
element. Example:
<location path="Home/AdministratorsOnly">
<system.web>
<authorization>
<allow roles="Administrators"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
However, before those authorization rules are executed, you have to be authenticated to the current web site.
Even though these explain how to handle unauthorized requests, these do not demonstrate clearly something like a LoginController or something like that to ask for user credentials and validate them.
From here, we could split the problem in two:
Authenticate users when consuming the Web API services within the same Web application
This would be the simplest approach, because you would rely on the Authentication in ASP.Net
This is a simple example:
<authentication mode="Forms">
<forms
protection="All"
slidingExpiration="true"
loginUrl="account/login"
cookieless="UseCookies"
enableCrossAppRedirects="false"
name="cookieName"
/>
</authentication>
Users will be redirected to the account/login route, there you would render custom controls to ask for user credentials and then you would set the authentication cookie using:
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
Cross - platform authentication
This case would be when you are only exposing Web API services within the Web application therefore, you would have another client consuming the services, the client could be another Web application or any .Net application (Win Forms, WPF, console, Windows service, etc)
For example assume that you will be consuming the Web API service from another web application on the same network domain (within an intranet), in this case you could rely on the Windows authentication provided by ASP.Net.
<authentication mode="Windows" />
If your services are exposed on the Internet, then you would need to pass the authenticated tokens to each Web API service.
For more info, take a loot to the following articles:
SELECT id, GROUP_CONCAT( string SEPARATOR ' ') FROM table GROUP BY id
More details here.
From the link above, GROUP_CONCAT
: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.
To display a line from a <textfile>
by its <line#>
, just do this:
perl -wne 'print if $. == <line#>' <textfile>
If you want a more powerful way to show a range of lines with regular expressions -- I won't say why grep is a bad idea for doing this, it should be fairly obvious -- this simple expression will show you your range in a single pass which is what you want when dealing with ~20GB text files:
perl -wne 'print if m/<regex1>/ .. m/<regex2>/' <filename>
(tip: if your regex has /
in it, use something like m!<regex>!
instead)
This would print out <filename>
starting with the line that matches <regex1>
up until (and including) the line that matches <regex2>
.
It doesn't take a wizard to see how a few tweaks can make it even more powerful.
Last thing: perl, since it is a mature language, has many hidden enhancements to favor speed and performance. With this in mind, it makes it the obvious choice for such an operation since it was originally developed for handling large log files, text, databases, etc.
Remove the multiple="multiple" attribute and add SIZE=6 with the number of elements you want
you may want to check this site
if any(word in 'some one long two phrase three' for word in list_):
if ($("#Password").val() != $("#ConfirmPassword").val()) {
alert("Passwords do not match.");
}
A JQuery approach that will eliminate needless code.
my quick answer with basic java arithmetic calculation is this:
First consider the following values:
1 Minute = 60 Seconds
1 Hour = 3600 Seconds ( 60 * 60 )
1 Day = 86400 Second ( 24 * 3600 )
the code snippet is as follows:
int input=500000;
int numberOfDays;
int numberOfHours;
int numberOfMinutes;
int numberOfSeconds;
numberOfDays = input / 86400;
numberOfHours = (input % 86400 ) / 3600 ;
numberOfMinutes = ((input % 86400 ) % 3600 ) / 60
numberOfSeconds = ((input % 86400 ) % 3600 ) % 60 ;
I hope to be helpful to you.
This is not exactly the OP's scenario but an answer to those of some of the commenters. It is a solution based on Cordova and Angular 1, which should be adaptable to other frameworks like jQuery. It gives you a Blob from Base64 data which you can store somewhere and reference it from client side javascript / html.
It also answers the original question on how to get an image (file) from the Base 64 data:
The important part is the Base 64 - Binary conversion:
function base64toBlob(base64Data, contentType) {
contentType = contentType || '';
var sliceSize = 1024;
var byteCharacters = atob(base64Data);
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
Slicing is required to avoid out of memory errors.
Works with jpg and pdf files (at least that's what I tested). Should work with other mimetypes/contenttypes too. Check the browsers and their versions you aim for, they need to support Uint8Array, Blob and atob.
Here's the code to write the file to the device's local storage with Cordova / Android:
...
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {
// Setup filename and assume a jpg file
var filename = attachment.id + "-" + (attachment.fileName ? attachment.fileName : 'image') + "." + (attachment.fileType ? attachment.fileType : "jpg");
dirEntry.getFile(filename, { create: true, exclusive: false }, function(fileEntry) {
// attachment.document holds the base 64 data at this moment
var binary = base64toBlob(attachment.document, attachment.mimetype);
writeFile(fileEntry, binary).then(function() {
// Store file url for later reference, base 64 data is no longer required
attachment.document = fileEntry.nativeURL;
}, function(error) {
WL.Logger.error("Error writing local file: " + error);
reject(error.code);
});
}, function(errorCreateFile) {
WL.Logger.error("Error creating local file: " + JSON.stringify(errorCreateFile));
reject(errorCreateFile.code);
});
}, function(errorCreateFS) {
WL.Logger.error("Error getting filesystem: " + errorCreateFS);
reject(errorCreateFS.code);
});
...
Writing the file itself:
function writeFile(fileEntry, dataObj) {
return $q(function(resolve, reject) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function() {
WL.Logger.debug(LOG_PREFIX + "Successful file write...");
resolve();
};
fileWriter.onerror = function(e) {
WL.Logger.error(LOG_PREFIX + "Failed file write: " + e.toString());
reject(e);
};
// If data object is not passed in,
// create a new Blob instead.
if (!dataObj) {
dataObj = new Blob(['missing data'], { type: 'text/plain' });
}
fileWriter.write(dataObj);
});
})
}
I am using the latest Cordova (6.5.0) and Plugins versions:
I hope this sets everyone here in the right direction.
No, you do not need to check whether you’re already on the main thread. By dispatching the block to the main queue, you’re just scheduling the block to be executed serially on the main thread, which happens when the corresponding run loop is run.
If you already are on the main thread, the behaviour is the same: the block is scheduled, and executed when the run loop of the main thread is run.
What about this:
var txt="";
var nyc = {
fullName: "New York City",
mayor: "Michael Bloomberg",
population: 8000000,
boroughs: 5
};
for (var x in nyc){
txt += nyc[x];
}
You can use stuff and patindex.
stuff(Col, 1, patindex('%[0-9]%', Col)-1, '')
Check out Leland Kwong's code.
Basic idea is to bind the wheeling event to the child element, and then use the native javascript property scrollHeight
and the jquery property outerHeight
of the child element to detect the end of the scroll, upon which return false
to the wheeling event to prevent any scrolling.
var scrollableDist,curScrollPos,wheelEvent,dY;
$('#child-element').on('wheel', function(e){
scrollableDist = $(this)[0].scrollHeight - $(this).outerHeight();
curScrollPos = $(this).scrollTop();
wheelEvent = e.originalEvent;
dY = wheelEvent.deltaY;
if ((dY>0 && curScrollPos >= scrollableDist) ||
(dY<0 && curScrollPos <= 0)) {
return false;
}
});
This is the code that will add border for all the nodes and will remove the border for the last node(TD).
<style type="text/css">
body {
font-family:arial;font-size: 8pt;
}
table td{
border-right: #666 1px solid
}
table td {
h: expression(this.style.border = (this == this.parentNode.lastChild ? 'none' : 'border-right: 0px solid' ) );
}
</style>
<table>
<tr>
<td>Home</td>
<td>sunil</td>
<td>Kumar</td>
<td>Rayadurg</td>
<td>Five</td>
<td>Six</td>
</tr>
</table>
Enjoy ...
I want the same instead of border I wanted it using images ... :-)
Complete working code would look like this:
<script>
$(document).ready(function(){
setInterval(function(){
$("#here").load(window.location.href + " #here" );
}, 3000);
});
</script>
<div id="here">dynamic content ?</div>
self reloading div container refreshing every 3 sec.
[
and subset are not substitutable:
[
does return a vector if only one column is selected.
df = data.frame(a="a",b="b")
identical(
df[,c("a")],
subset(df,select="a")
)
identical(
df[,c("a","b")],
subset(df,select=c("a","b"))
)
Well even if what suggest by @Tauras just works I don't think it's the correct way to deal with this.
You said you have run php artisan make:auth
which should have also inserted Auth::routes();
in your routes/web.php
routing files. Which comes with default logout
route already defined and is named logout
.
You can see it here on GitHub, but I will also report the code here for simplicity:
/**
* Register the typical authentication routes for an application.
*
* @return void
*/
public function auth()
{
// Authentication Routes...
$this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
$this->post('login', 'Auth\LoginController@login');
$this->post('logout', 'Auth\LoginController@logout')->name('logout');
// Registration Routes...
$this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
$this->post('register', 'Auth\RegisterController@register');
// Password Reset Routes...
$this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
$this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
$this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
$this->post('password/reset', 'Auth\ResetPasswordController@reset');
}
Then again please note that logout
requires POST
as HTTP request method. There are many valid reason behind this, but just to mention one very important is that in this way you can prevent cross-site request forgery.
So according to what I have just pointed out a correct way to implement this could be just this:
<a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('frm-logout').submit();">
Logout
</a>
<form id="frm-logout" action="{{ route('logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
Finally note that I have inserted laravel out of the box ready function {{ csrf_field() }}
!
You can use
sessionStorage.SessionName = "SessionData"
,
sessionStorage.getItem("SessionName")
and
sessionStorage.setItem("SessionName","SessionData");
See the supported browsers on http://caniuse.com/namevalue-storage
Try with this:
SELECT to_char (2/3::float, 'FM999999990.00');
-- RESULT: 0.67
Or simply:
SELECT round (2/3::DECIMAL, 2)::TEXT
-- RESULT: 0.67
From your SQL Server Management Studio, you open Object Explorer, go to your database where you want to load the data into, right click, then pick Tasks > Import Data.
This opens the Import Data Wizard, which typically works pretty well for importing from Excel. You can pick an Excel file, pick what worksheet to import data from, you can choose what table to store it into, and what the columns are going to be. Pretty flexible indeed.
You can run this as a one-off, or you can store it as a SQL Server Integration Services (SSIS) package into your file system, or into SQL Server itself, and execute it over and over again (even scheduled to run at a given time, using SQL Agent).
Update: yes, yes, yes, you can do all those things you keep asking - have you even tried at least once to run that wizard??
OK, here it comes - step by step:
Step 1: pick your Excel source
Step 2: pick your SQL Server target database
Step 3: pick your source worksheet (from Excel) and your target table in your SQL Server database; see the "Edit Mappings" button!
Step 4: check (and change, if needed) your mappings of Excel columns to SQL Server columns in the table:
Step 5: if you want to use it later on, save your SSIS package to SQL Server:
Step 6: - success! This is on a 64-bit machine, works like a charm - just do it!!
If you can't close windows that aren't opened by the script, then you can destroy your page using this code:
document.getElementsByTagName ('html') [0] .remove ();
Evaluating "1,2,3" results in (1, 2, 3)
, a tuple
. As you've discovered, tuples are immutable. Convert to a list before processing.
this Func may help you . it add every list object to grid view
private void show_data()
{
BindingSource Source = new BindingSource();
for (int i = 0; i < CC.Contects.Count; i++)
{
Source.Add(CC.Contects.ElementAt(i));
};
Data_View.DataSource = Source;
}
I write this for simple database app
Check if you have the Startup class created in your project. This is an example:
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof({project_name}.Startup))]
namespace AuctionPortal
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
To get the type, use the builtin type
function. With the in
operator, you can test if the type is a numpy type by checking if it contains the string numpy
;
In [1]: import numpy as np
In [2]: a = np.array([1, 2, 3])
In [3]: type(a)
Out[3]: <type 'numpy.ndarray'>
In [4]: 'numpy' in str(type(a))
Out[4]: True
(This example was run in IPython, by the way. Very handy for interactive use and quick tests.)
I find it surprising that no one mentions data
as an object. For me it's the cleanest and easiest way to pass data:
$('form#foo').submit(function () {
$.ajax({
url: 'http://foo.bar/some-ajax-script',
type: 'POST',
dataType: 'json',
data: {
'foo': 'some-foo-value',
'bar': $('#bar').val()
}
}).always(function (response) {
console.log(response);
});
return false;
});
Then, in the backend:
// Example in PHP
$_POST['foo'] // some-foo-value
$_POST['bar'] // value in #bar
It worked for me
You can use this css code:
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
The text-overflow property in CSS deals with situations where text is clipped when it overflows the element's box. It can be clipped (i.e. cut off, hidden), display an ellipsis ('…', Unicode Range Value U+2026).
Note that text-overflow only occurs when the container's overflow property has the value hidden, scroll or auto and white-space: nowrap;.
Text overflow can only happen on block or inline-block level elements, because the element needs to have a width in order to be overflow-ed. The overflow happens in the direction as determined by the direction property or related attributes.
A Ternary is not a good solution for what you want. It will not be readable in your code, and there are much better solutions available.
Why not use an array lookup "map" or "dictionary", like so:
$vocations = array(
1 => "Sorcerer",
2 => "Druid",
3 => "Paladin",
...
);
echo $vocations[$result->vocation];
A ternary for this application would end up looking like this:
echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));
Why is this bad? Because - as a single long line, you would get no valid debugging information if something were to go wrong here, the length makes it difficult to read, plus the nesting of the multiple ternaries just feels odd.
A Standard Ternary is simple, easy to read, and would look like this:
$value = ($condition) ? 'Truthy Value' : 'Falsey Value';
or
echo ($some_condition) ? 'The condition is true!' : 'The condition is false.';
A ternary is really just a convenient / shorter way to write a simple if else
statement. The above sample ternary is the same as:
if ($some_condition) {
echo 'The condition is true!';
} else {
echo 'The condition is false!';
}
However, a ternary for a complex logic quickly becomes unreadable, and is no longer worth the brevity.
echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));
Even with some attentive formatting to spread it over multiple lines, it's not very clear:
echo($result->group_id == 1
? "Player"
: ($result->group_id == 2
? "Gamemaster"
: ($result->group_id == 3
? "God"
: "unknown")));
For API 23:
Top level build.gradle - /build.gradle
buildscript {
...
dependencies {
classpath 'com.android.tools.build:gradle:1.3.1'
}
}
...
Module specific build.gradle - /app/build.gradle
android {
compileSdkVersion 23
buildToolsVersion "23.0.0"
useLibrary 'org.apache.http.legacy'
...
}
Official docs (for preview though): http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client
Latest android gradle plugin changelog: http://tools.android.com/tech-docs/new-build-system
Using regex, the result is in $matches[1]:
$str = "test.txt ; 131 136 80 89 119 17 60 123 210 121 188 42 136 200 131 198"
$str -match "^(.*?)\s\;"
$matches[1]
test.txt
On HTC mini one 2, besides enabling the Developer Options, the following worked for me:
I find this code useful when I need a path outside of a controller, such as when I'm initializing components in Global.asax.cs:
HostingEnvironment.MapPath("~/Data/data.html")
To access the properties of an object without knowing the names of those properties you can use a for ... in
loop:
for(key in data) {
if(data.hasOwnProperty(key)) {
var value = data[key];
//do something with value;
}
}
For future reference to people who come here. after you run the command that was given in the third answer here(I am using now Laravel 5.3).
php artisan config:cache
You may encounter this problem:
[ReflectionException]
Class view does not exist
In that case, you need to add it back manually to your provider list under the app.php file. GO-TO:
app->config->app.php->'providers[]'
and add it, like so:
Illuminate\View\ViewServiceProvider::class,
Hope That helps someone.
Python opens files almost in the same way as in C:
r+
Open for reading and writing. The stream is positioned at the beginning of the file.
a+
Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is appended to the end of the file (but in some Unix systems regardless of the current seek position).
Amusingly, git checkout foo
will not work if the working copy is in a directory named foo
; however, both git checkout HEAD foo
and git checkout ./foo
will:
$ pwd
/Users/aaron/Documents/work/foo
$ git checkout foo
D foo
Already on "foo"
$ git checkout ./foo
$ git checkout HEAD foo
Both invocations of the identical code below if decreased by 1 work in Chrome 32 on my computer e.g. 17905 vs 17904. If run as is they will produce the error "RangeError: Maximum call stack size exceeded". It appears to be this limit is not hardcoded but dependant on the hardware of your machine. It does appear that if invoked as a function this self-imposed limit is higher than if invoked as a method i.e. this particular code uses less memory when invoked as a function.
Invoked as a method:
var ninja = {
chirp: function(n) {
return n > 1 ? ninja.chirp(n-1) + "-chirp" : "chirp";
}
};
ninja.chirp(17905);
Invoked as a function:
function chirp(n) {
return n > 1 ? chirp( n - 1 ) + "-chirp" : "chirp";
}
chirp(20889);
Please visit this ODP site set up by oracle for Microsoft OracleClient Developers: http://www.oracle.com/technetwork/topics/dotnet/index-085703.html
Also below is a sample code that can get you started to call a stored procedure from C# to Oracle. PKG_COLLECTION.CSP_COLLECTION_HDR_SELECT is the stored procedure built on Oracle accepting parameters PUNIT, POFFICE, PRECEIPT_NBR and returning the result in T_CURSOR.
using Oracle.DataAccess;
using Oracle.DataAccess.Client;
public DataTable GetHeader_BySproc(string unit, string office, string receiptno)
{
using (OracleConnection cn = new OracleConnection(DatabaseHelper.GetConnectionString()))
{
OracleDataAdapter da = new OracleDataAdapter();
OracleCommand cmd = new OracleCommand();
cmd.Connection = cn;
cmd.InitialLONGFetchSize = 1000;
cmd.CommandText = DatabaseHelper.GetDBOwner() + "PKG_COLLECTION.CSP_COLLECTION_HDR_SELECT";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("PUNIT", OracleDbType.Char).Value = unit;
cmd.Parameters.Add("POFFICE", OracleDbType.Char).Value = office;
cmd.Parameters.Add("PRECEIPT_NBR", OracleDbType.Int32).Value = receiptno;
cmd.Parameters.Add("T_CURSOR", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
I was able to make the navigation bar transparent by adding a new .transparent class to the .navbar and setting the CSS like this:
.navbar.transparent.navbar-inverse .navbar-inner {
border-width: 0px;
-webkit-box-shadow: 0px 0px;
box-shadow: 0px 0px;
background-color: rgba(0,0,0,0.0);
background-image: -webkit-gradient(linear, 50.00% 0.00%, 50.00% 100.00%, color-stop( 0% , rgba(0,0,0,0.00)),color-stop( 100% , rgba(0,0,0,0.00)));
background-image: -webkit-linear-gradient(270deg,rgba(0,0,0,0.00) 0%,rgba(0,0,0,0.00) 100%);
background-image: linear-gradient(180deg,rgba(0,0,0,0.00) 0%,rgba(0,0,0,0.00) 100%);
}
My markup is like this
<div class="navbar transparent navbar-inverse">
<div class="navbar-inner">....
In bootstrap.css line 4784 we see:
.navbar-inverse .navbar-inner {
background-color: #FFFFFFF;
background-image: -moz-linear-gradient(top, #222222, #111111);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#222222), to(#111111));
background-image: -webkit-linear-gradient(top, #222222, #111111);
background-image: -o-linear-gradient(top, #222222, #111111);
background-image: linear-gradient(to bottom, #222222, #111111);
background-repeat: repeat-x;
border-color: #252525;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222', endColorstr='#ff111111', GradientType=0);
}
You need to remove all the 'background-image' property declarations to get the desired effect.
Following is how you can do this:
<?php
$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('kitchen', $rooms)){
echo 'this array contains kitchen';
}
Make sure that you search for kitchen and not Kitchen. This function is case sensitive. So, the below function simply won't work:
$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('KITCHEN', $rooms)){
echo 'this array contains kitchen';
}
If you rather want a quick way to make this search case insensitive, have a look at the proposed solution in this reply: https://stackoverflow.com/a/30555568/8661779
Source: http://dwellupper.io/post/50/understanding-php-in-array-function-with-examples
They are both instances of Context, but the application instance is tied to the lifecycle of the application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to different information about the application environment.
If you read the docs at getApplicationContext it notes that you should only use this if you need a context whose lifecycle is separate from the current context. This doesn't apply in either of your examples.
The Activity context presumably has some information about the current activity that is necessary to complete those calls. If you show the exact error message, might be able to point to what exactly it needs.
But in general, use the activity context unless you have a good reason not to.
border:0;
outline:none;
box-shadow:none;
This should do the trick.
Moq cannot mock a static member of a class.
When designing code for testability it's important to avoid static members (and singletons). A design pattern that can help you refactoring your code for testability is Dependency Injection.
This means changing this:
public class Foo
{
public Foo()
{
Bar = new Bar();
}
}
to
public Foo(IBar bar)
{
Bar = bar;
}
This allows you to use a mock from your unit tests. In production you use a Dependency Injection tool like Ninject or Unity wich can wire everything together.
I wrote a blog about this some time ago. It explains which patterns an be used for better testable code. Maybe it can help you: Unit Testing, hell or heaven?
Another solution could be to use the Microsoft Fakes Framework. This is not a replacement for writing good designed testable code but it can help you out. The Fakes framework allows you to mock static members and replace them at runtime with your own custom behavior.
$.validator.addMethod("mydate", function (value, element) {
return this.optional(element) || /^(\d{4})(-|\/)(([0-1]{1})([1-2]{1})|([0]{1})([0-9]{1}))(-|\/)(([0-2]{1})([1-9]{1})|([3]{1})([0-1]{1}))/.test(value);
});
you can input like yyyy-mm-dd
also yyyy/mm/dd
but can't judge the the size of the month sometime Feb just 28 or 29 days.
From char and varchar (Transact-SQL)
varchar [ ( n | max ) ]
Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.
py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.
You can redirect anything or more URL via javascript, Just simple window.location.href
with if else
Use this code,
<script>
if(window.location.href == 'old_url')
{
window.location.href="new_url";
}
//Another url redirect
if(window.location.href == 'old_url2')
{
window.location.href="new_url2";
}
</script>
You can redirect many URL's by this procedure. Thanks.
While Orion Edwards Answer works for any situation, it may be a pain to add the border and set the properties of the border every time you want to do this. Another quick way is to set the padding of the text block:
<TextBlock Height="22" Padding="3" />
FYI,
Trim() does that already.
The following LINQPad sample:
void Main()
{
var s = " \rsdsdsdsd\nsadasdasd\r\n ";
s.Length.Dump();
s.Trim().Length.Dump();
}
Outputs:
23
18
You can tweak it to a command line utility,
python-which <package name>
Create /usr/local/bin/python-which
#!/usr/bin/env python
import importlib
import os
import sys
args = sys.argv[1:]
if len(args) > 0:
module = importlib.import_module(args[0])
print os.path.dirname(module.__file__)
Make it executable
sudo chmod +x /usr/local/bin/python-which
I have been getting this error too, but my project is built on the command line using Maven and the tycho compiler (it's a set of OSGi plugins). After masses of sifting through people having the same problem but fixing it in Eclipse rather than on the command line, I found a message on the Tycho developer forum that answered my question, using configuration in pom.xml
to ignore the compiler warning about the access restriction:
<plugin>
<groupId>org.eclipse.tycho</groupId>
<artifactId>tycho-compiler-plugin</artifactId>
<version>${tycho.version}</version>
<configuration>
<compilerArgument>-warn:+discouraged,forbidden</compilerArgument>
</configuration>
</plugin>
More information can be found in the Tycho FAQ. This took me AGES to work out, so I figured I would assist anyone else trying to fix these access restriction errors from the command line by posting this answer.
Try this:
-- http://lua-users.org/wiki/FileInputOutput
-- see if the file exists
function file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function lines_from(file)
if not file_exists(file) then return {} end
lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
-- tests the functions above
local file = 'test.lua'
local lines = lines_from(file)
-- print all line numbers and their contents
for k,v in pairs(lines) do
print('line[' .. k .. ']', v)
end
Simply using below code in Kotlin works for me
WebView(applicationContext).clearCache(true)
You can't access the method fxn since it's not static. Static methods can only access other static methods directly. If you want to use fxn in your main method you need to:
...
Two two = new Two();
x = two.fxn(x)
...
That is, make a Two-Object and call the method on that object.
...or make the fxn method static.
For completeness:
https://developer.chrome.com/multidevice/android/installtohomescreen
Does Add to homescreen work on Chrome for iOS?
No.
public static String getFileName(URL extUrl) {
//URL: "http://photosaaaaa.net/photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg"
String filename = "";
//PATH: /photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg
String path = extUrl.getPath();
//Checks for both forward and/or backslash
//NOTE:**While backslashes are not supported in URL's
//most browsers will autoreplace them with forward slashes
//So technically if you're parsing an html page you could run into
//a backslash , so i'm accounting for them here;
String[] pathContents = path.split("[\\\\/]");
if(pathContents != null){
int pathContentsLength = pathContents.length;
System.out.println("Path Contents Length: " + pathContentsLength);
for (int i = 0; i < pathContents.length; i++) {
System.out.println("Path " + i + ": " + pathContents[i]);
}
//lastPart: s659629384_752969_4472.jpg
String lastPart = pathContents[pathContentsLength-1];
String[] lastPartContents = lastPart.split("\\.");
if(lastPartContents != null && lastPartContents.length > 1){
int lastPartContentLength = lastPartContents.length;
System.out.println("Last Part Length: " + lastPartContentLength);
//filenames can contain . , so we assume everything before
//the last . is the name, everything after the last . is the
//extension
String name = "";
for (int i = 0; i < lastPartContentLength; i++) {
System.out.println("Last Part " + i + ": "+ lastPartContents[i]);
if(i < (lastPartContents.length -1)){
name += lastPartContents[i] ;
if(i < (lastPartContentLength -2)){
name += ".";
}
}
}
String extension = lastPartContents[lastPartContentLength -1];
filename = name + "." +extension;
System.out.println("Name: " + name);
System.out.println("Extension: " + extension);
System.out.println("Filename: " + filename);
}
}
return filename;
}
You're almost correct, just misplaced a few quotes. Wrapping the whole thing in regular quotes will literally give you the string #demo + {this.state.id}
- you need to indicate which are variables and which are string literals. Since anything inside {}
is an inline JSX expression, you can do:
href={"#demo" + this.state.id}
This will use the string literal #demo
and concatenate it to the value of this.state.id
. This can then be applied to all strings. Consider this:
var text = "world";
And this:
{"Hello " + text + " Andrew"}
This will yield:
Hello world Andrew
You can also use ES6 string interpolation/template literals with ` (backticks) and ${expr}
(interpolated expression), which is closer to what you seem to be trying to do:
href={`#demo${this.state.id}`}
This will basically substitute the value of this.state.id
, concatenating it to #demo
. It is equivalent to doing: "#demo" + this.state.id
.
The Chromium team is currently developing the Idle Detection API. It is available as an origin trial since Chrome 88, which is already the 2nd origin trial for this feature. An earlier origin trial went from Chrome 84 through Chrome 86.
It can also be enabled via a flag:
Enabling via chrome://flags
To experiment with the Idle Detection API locally, without an origin trial token, enable the
#enable-experimental-web-platform-features
flag in chrome://flags.
A demo can be found here:
It has to be noted though that this API is permission-based (as it should be, otherwise this could be misused to monitor a user's behaviour!).
Well, it better not be Eclipse 3.1.x and Java 7. I resolved this combination by upgrading to Eclipse 3.8.x.
I think it's generally browser specific. To be on the safe side, base64 encode a JSON object, and store everything in that. That way you just have to decode it and parse the JSON. All the characters used in base64 should play fine with most, if not all browsers.
var clonedArray = array.concat();
An iterative version in python/numpy for answer https://stackoverflow.com/a/22640362/6029703 is here. This code is faster than computing average and standard deviation every lag for large data (100000+).
def peak_detection_smoothed_zscore_v2(x, lag, threshold, influence):
'''
iterative smoothed z-score algorithm
Implementation of algorithm from https://stackoverflow.com/a/22640362/6029703
'''
import numpy as np
labels = np.zeros(len(x))
filtered_y = np.array(x)
avg_filter = np.zeros(len(x))
std_filter = np.zeros(len(x))
var_filter = np.zeros(len(x))
avg_filter[lag - 1] = np.mean(x[0:lag])
std_filter[lag - 1] = np.std(x[0:lag])
var_filter[lag - 1] = np.var(x[0:lag])
for i in range(lag, len(x)):
if abs(x[i] - avg_filter[i - 1]) > threshold * std_filter[i - 1]:
if x[i] > avg_filter[i - 1]:
labels[i] = 1
else:
labels[i] = -1
filtered_y[i] = influence * x[i] + (1 - influence) * filtered_y[i - 1]
else:
labels[i] = 0
filtered_y[i] = x[i]
# update avg, var, std
avg_filter[i] = avg_filter[i - 1] + 1. / lag * (filtered_y[i] - filtered_y[i - lag])
var_filter[i] = var_filter[i - 1] + 1. / lag * ((filtered_y[i] - avg_filter[i - 1]) ** 2 - (
filtered_y[i - lag] - avg_filter[i - 1]) ** 2 - (filtered_y[i] - filtered_y[i - lag]) ** 2 / lag)
std_filter[i] = np.sqrt(var_filter[i])
return dict(signals=labels,
avgFilter=avg_filter,
stdFilter=std_filter)
New average = old average * (n-1)/n + new value /n
This is assuming the count only changed by one value. In case it is changed by M values then:
new average = old average * (n-len(M))/n + (sum of values in M)/n).
This is the mathematical formula (I believe the most efficient one), believe you can do further code by yourselves
If it really is a List<string>
you don't need LINQ, just use:
int GetItemIndex(string search)
{
return _list == null ? -1 : _list.IndexOf(search);
}
If you are looking for the item itself, try:
string GetItem(string search)
{
return _list == null ? null : _list.FirstOrDefault(s => s.Equals(search));
}
def isPrime(x):
if x<2:
return False
for i in range(2,x):
if not x%i:
return False
return True
print isPrime(2)
True
print isPrime(3)
True
print isPrime(9)
False
This slice syntax makes a copy of the list and does what you want:
l = range(100)
for i in l[:]:
print i,
print l.pop(0),
print l.pop(0)
<div id="video_box">
<div id="video_overlays"></div>
<div>
<video id="player" src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" type="video/webm" onclick="this.play();">Your browser does not support this streaming content.</video>
</div>
</div>
for this you need to just add css like this:
#video_overlays {
position: absolute;
background-color: rgba(0, 0, 0, 0.46);
z-index: 2;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
#video_box{position: relative;}
Why Server.Transfer
? Response.Redirect(Request.RawUrl)
would get you what you need.
As John Saunders says, check if the class/property names matches the capital casing of your XML. If this isn't the case, the problem will also occur.
The answer is (almost) ALL
(7-bit ASCII).
If the inclusion rules is "...allowed under some/any/none conditions..."
Just by looking at one of several possible inclusion rules for allowed text in the "domain text" part in RFC 5322 at the top of page 17 we find:
dtext = %d33-90 / ; Printable US-ASCII
%d94-126 / ; characters not including
obs-dtext ; "[", "]", or "\"
the only three missing chars in this description are used in domain-literal []
, to form a quoted-pair \
, and the white space character (%d32). With that the whole range 32-126 (decimal) is used. A similar requirement appear as "qtext" and "ctext". Many control characters are also allowed/used. One list of such control chars appears in page 31 section 4.1 of RFC 5322 as obs-NO-WS-CTL.
obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
%d11 / ; characters that do not
%d12 / ; include the carriage
%d14-31 / ; return, line feed, and
%d127 ; white space characters
All this control characters are allowed as stated at the start of section 3.5:
.... MAY be used, the use of US-ASCII control characters (values
1 through 8, 11, 12, and 14 through 31) is discouraged ....
And such an inclusion rule is therefore "just too wide". Or, in other sense, the expected rule is "too simplistic".