In case of WSS 3.0 recently I experienced same issue. It was because of column that was accessed from code was not present in the wss list.
AdventureWorksDataContext db = new AdventureWorksDataContext();
db.Log = Console.Out;
// Get hte first customer record
Customer c = from cust in db.Customers select cust where id = 5;
Console.WriteLine(c.CustomerType);
c.CustomerType = 'I';
db.SubmitChanges(); // Save the changes away
These methods select from the same table twice. If the source data are coming from an expensive query, this is a way to avoid running it twice:
select KEY_FIELD, AVG(VALUE_FIELD) MEDIAN_VALUE
from (
select KEY_FIELD, VALUE_FIELD, RANKF
, @rownumr := IF(@prevrowidr=KEY_FIELD,@rownumr+1,1) RANKR
, @prevrowidr := KEY_FIELD
FROM (
SELECT KEY_FIELD, VALUE_FIELD, RANKF
FROM (
SELECT KEY_FIELD, VALUE_FIELD
, @rownumf := IF(@prevrowidf=KEY_FIELD,@rownumf+1,1) RANKF
, @prevrowidf := KEY_FIELD
FROM (
SELECT KEY_FIELD, VALUE_FIELD
FROM (
-- some expensive query
) B
ORDER BY KEY_FIELD, VALUE_FIELD
) C
, (SELECT @rownumf := 1) t_rownum
, (SELECT @prevrowidf := '*') t_previd
) D
ORDER BY KEY_FIELD, RANKF DESC
) E
, (SELECT @rownumr := 1) t_rownum
, (SELECT @prevrowidr := '*') t_previd
) F
WHERE RANKF-RANKR BETWEEN -1 and 1
GROUP BY KEY_FIELD
This warning comes because your dataframe x
is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.
You can either create a proper dataframe
out of x by doing
x = x.copy()
This will remove the warning, but it is not the proper way
You should be using the DataFrame.loc
method, as the warning suggests, like this:
x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)
its simple... use this piece of code
bool anyname = your_string_Name.All(char.IsDigit);
it will return true if your string have integer other wise false...
You can set the calendar to use only AM or PM using
calendar.set(Calendar.AM_PM, int);
0 = AM
1 = PM
Hope this helps
Now use np.array_equal
. From documentation:
np.array_equal([1, 2], [1, 2])
True
np.array_equal(np.array([1, 2]), np.array([1, 2]))
True
np.array_equal([1, 2], [1, 2, 3])
False
np.array_equal([1, 2], [1, 4])
False
As from Laravel 5.5 you can use firstWhere()
In you case:
$green_foods = $foods->firstWhere('color', 'green');
You could use display: table-row-group
for your div.
<table>
<div style="display: table-row-group">
<tr><td></td></tr>
</div>
<div style="display: table-row-group">
<tr><td></td></tr>
</div>
</table>
Either use
SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1
from tablename
or
SELECT case when field1 IS NULL or field1 = ''
then 'empty'
else field1
end as field1
from tablename
If you only want to check for null
and not for empty strings then you can also use ifnull()
or coalesce(field1, 'empty')
. But that is not suitable for empty strings.
Just Add AjaxControlToolkit.dll to your Reference folder.
On your Project Solution
Right Click on Reference Folder > Add Reference > browse AjaxControlToolkit.dll .
Then build.
Regards
NB: this is LINQ to objects, I am not 100% sure if it work in LINQ to entities, and have no time to check it right now. In fact it isn't too difficult to translate it to x in [A, B, C] but you have to check for yourself.
So, instead of Contains as a replacement of the ???? in your code you can use Any which is more LINQ-uish:
// Filter the orders based on the order status
var filteredOrders = from order in orders.Order
where new[] { "A", "B", "C" }.Any(s => s == order.StatusCode)
select order;
It's the opposite to what you know from SQL this is why it is not so obvious.
Of course, if you prefer fluent syntax here it is:
var filteredOrders = orders.Order.Where(order => new[] {"A", "B", "C"}.Any(s => s == order.StatusCode));
Here we again see one of the LINQ surprises (like Joda-speech which puts select at the end). However it is quite logical in this sense that it checks if at least one of the items (that is any) in a list (set, collection) matches a single value.
This works for me:
RewriteCond %{HTTP_HOST} ^(?!www.domain.com).*$ [NC]
RewriteRule ^(.*)$ http://www.domain.com$1 [R=301,L]
I use the look-ahead pattern (?!www.domain.com)
to exclude the www
subdomain when redirecting all domains to the www
subdomain in order to avoid an infinite redirect loop in Apache.
The original request has been answered already.
However, I am posting the below answer for those who might be looking for generic transliteration code to transliterate any charset to Latin/English in Java.
Naive meaning of tranliteration: Translated string in it's final form/target charset sounds like the string in it's original form. If we want to transliterate any charset to Latin(English alphabets), then ICU4(ICU4J library in java ) will do the job.
Here is the code snippet in java:
import com.ibm.icu.text.Transliterator; //ICU4J library import
public static String TRANSLITERATE_ID = "NFD; Any-Latin; NFC";
public static String NORMALIZE_ID = "NFD; [:Nonspacing Mark:] Remove; NFC";
/**
* Returns the transliterated string to convert any charset to latin.
*/
public static String transliterate(String input) {
Transliterator transliterator = Transliterator.getInstance(TRANSLITERATE_ID + "; " + NORMALIZE_ID);
String result = transliterator.transliterate(input);
return result;
}
I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path
But the main issue was not here. The problem was with these 2 lines of code
strFile = Dir(strPath & "*.csv")
Which should have written as
strFile = Dir(strPath & "\*.csv")
and
With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _
Which should have written as
With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _
Try this instead, tested on Chrome/Safari
ul {
list-style: none;
}
I had (have) a similar problem in a Java application. I wrote a JDBC driver wrapper around the Oracle driver so all output is sent to a log file.
Steps to resolve the issue:
1.Open your solution/Web Application in VS 2012 in administrator mode.
2.Go to IIS and Note down the settings for your application (e.g.Virtual directory name, Physical Path, Authentication setting and App pool used).
3.Remove (right click and select Remove) your application from Default Web Site. Refresh IIS.
4.Go back to VS 2012 and open settings (right click and select properties) for your web application.
5.Select Web.In Servers section make sure you have selected "Use Local IIS Web Server".
6.In Project Url textbox enter your application path (http://localhost
/Application Path). Click on Create Virtual Directory.
7.Go to IIS and apply settings noted in step 2. Refresh IIS.
8.Go to VS 2012 and set this project as startup Project with appropriate page as startup page.
9.Click run button to start project in debug mode.
This resolved issue for me for web application which was migrated from VS 2010 to 2012.Hope this helps anyone looking for specific issue.
My machine configuration is: IIS 7.5.7600.16385
VS 2012 Professional
Windows 7 Enterprise (Version 6.1 - Build 7601:Service Pack 1)
If you want to do it using .map()
or just want to know how it works you can do it like this:
var added=false;
$.map(arr, function(elementOfArray, indexInArray) {
if (elementOfArray.id == productID) {
elementOfArray.price = productPrice;
added = true;
}
}
if (!added) {
arr.push({id: productID, price: productPrice})
}
The function handles each element separately. The .inArray()
proposed in other answers is probably the more efficient way to do it.
If you've got a Mac the easiest way to split those would be to use DfontSplitter, available at https://peter.upfold.org.uk/projects/dfontsplitter
The Windows version they provide doesn't work with ttc files.
ko.applyBindings
accepts a second parameter that is a DOM element to use as the root.
This would let you do something like:
<div id="one">
<input data-bind="value: name" />
</div>
<div id="two">
<input data-bind="value: name" />
</div>
<script type="text/javascript">
var viewModelA = {
name: ko.observable("Bob")
};
var viewModelB = {
name: ko.observable("Ted")
};
ko.applyBindings(viewModelA, document.getElementById("one"));
ko.applyBindings(viewModelB, document.getElementById("two"));
</script>
So, you can use this technique to bind a viewModel to the dynamic content that you load into your dialog. Overall, you just want to be careful not to call applyBindings
multiple times on the same elements, as you will get multiple event handlers attached.
This should help.
Integer startIn = null;
// (optional below but a good practice, to prevent errors.)
boolean dontContinue = false;
try {
Integer.parseInt (startField.getText());
} catch (NumberFormatException e){
e.printStackTrace();
}
// in java = assigns a boolean in if statements oddly.
// Thus double equal must be used. So if startIn is null, display the message
if (startIn == null) {
JOptionPane.showMessageDialog(null,
"You must enter a number between 0-16.","Input Error",
JOptionPane.ERROR_MESSAGE);
}
// (again optional)
if (dontContinue == true) {
//Do-some-error-fix
}
This can get more complicated depending on where PHP sits in your environment, since your question is quite broad. This may depend on whether there's a load-balancer and how it's configured. Here are are a few related questions:
Probably the easiest way to do it is to have a php file return JSON. So let's say you have a file query.php
,
$result = mysql_query("SELECT field_name, field_value
FROM the_table");
$to_encode = array();
while($row = mysql_fetch_assoc($result)) {
$to_encode[] = $row;
}
echo json_encode($to_encode);
If you're constrained to using document.write (as you note in the comments below) then give your fields an id attribute like so: <input type="text" id="field1" />
. You can reference that field with this jQuery: $("#field1").val()
.
Here's a complete example with the HTML. If we're assuming your fields are called field1
and field2
, then
<!DOCTYPE html>
<html>
<head>
<title>That's about it</title>
</head>
<body>
<form>
<input type="text" id="field1" />
<input type="text" id="field2" />
</form>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$.getJSON('data.php', function(data) {
$.each(data, function(fieldName, fieldValue) {
$("#" + fieldName).val(fieldValue);
});
});
</script>
</html>
That's insertion after the HTML has been constructed, which might be easiest. If you mean to populate data while you're dynamically constructing the HTML, then you'd still want the PHP file to return JSON, you would just add it directly into the value
attribute.
In python many things are iterable including files and strings. Iterating over a filehandler gives you a list of all the lines in that file. Iterating over a string gives you a list of all the characters in that string.
charsFromFile = []
filePath = r'path\to\your\file.txt' #the r before the string lets us use backslashes
for line in open(filePath):
for char in line:
charsFromFile.append(char)
#apply code on each character here
or if you want a one liner
#the [0] at the end is the line you want to grab.
#the [0] can be removed to grab all lines
[list(a) for a in list(open('test.py'))][0]
.
.
Edit: as agf mentions you can use itertools.chain.from_iterable
His method is better, unless you want the ability to specify which lines to grab
list(itertools.chain.from_iterable(open(filename, 'rU)))
This does however require one to be familiar with itertools, and as a result looses some readablity
If you only want to iterate over the chars, and don't care about storing a list, then I would use the nested for loops. This method is also the most readable.
until passwd
do
echo "Try again"
done
or
while ! passwd
do
echo "Try again"
done
Here's a javascript example from mozilla:
var o = { a:0 } // `o` is now a basic object
Object.defineProperty(o, "b", {
get: function () {
return this.a + 1;
}
});
console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
I've used these A LOT because they are awesome. I would use it when getting fancy with my coding + animation. For example, make a setter that deals with an Number
which displays that number on your webpage. When the setter is used it animates the old number to the new number using a tweener. If the initial number is 0 and you set it to 10 then you would see the numbers flip quickly from 0 to 10 over, let's say, half a second. Users love this stuff and it's fun to create.
Example from sof
<?php
class MyClass {
private $firstField;
private $secondField;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
return $this;
}
}
?>
citings:
before any apt-get command in your Dockerfile you should put this line
COPY apt.conf /etc/apt/apt.conf
Dont'f forget to create apt.conf in the same folder that you have the Dockerfile, the content of the apt.conf file should be like this:
Acquire::socks::proxy "socks://YOUR-PROXY-IP:PORT/";
Acquire::http::proxy "http://YOUR-PROXY-IP:PORT/";
Acquire::https::proxy "http://YOUR-PROXY-IP:PORT/";
if you use username and password to connect to your proxy then the apt.conf should be like as below:
Acquire::socks::proxy "socks://USERNAME:PASSWORD@YOUR-PROXY-IP:PORT/";
Acquire::http::proxy "http://USERNAME:PASSWORD@YOUR-PROXY-IP:PORT/";
Acquire::https::proxy "http://USERNAME:PASSWORD@YOUR-PROXY-IP:PORT/";
for example :
Acquire::https::proxy "http://foo:[email protected]:8080/";
Where the foo is the username and bar is the password.
One can ask with some Java code:
long maxBytes = Runtime.getRuntime().maxMemory();
System.out.println("Max memory: " + maxBytes / 1024 / 1024 + "M");
See javadoc.
Most of the possible solution has been covered above. From my experience of this issue, i have placed the mysql-connector-jar in the /WEB-INF/lib folder of the webapp module and it worked fine for me.
<form>
cannot go inside <p>
, no. The browser is going to abruptly close your <p>
element when it hits the opening <form>
tag as it tries to handle what it thinks is an unclosed paragraph element:
<p>Read this sentence
</p><form style='display:inline;'>
You need to print
to get that output.
You should do
>>> x = "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
>>> x # this is the value, returned by the join() function
'I\nwould\nexpect\nmultiple\nlines'
>>> print x # this prints your string (the type of output you want)
I
would
expect
multiple
lines
This depends on what content do you have. You need to initialize your requestMessage.Content
property with new HttpContent. For example:
...
// Add request body
if (isPostRequest)
{
requestMessage.Content = new ByteArrayContent(content);
}
...
where content
is your encoded content. You also should include correct Content-type header.
Oh, it can be even nicer (from this answer):
requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");
Many of the answers listed here have inherent issues:
The RootTools library from Stericson seems to be checking for root more legitimately. It also has lots of extra tools and utilities so I highly recommend it. However, there's no explanation of how it specifically checks for root, and it may be a bit heavier than most apps really need.
I've made a couple of utility methods that are loosely based on the RootTools library. If you simply want to check if the "su" executable is on the device you can use the following method:
public static boolean isRootAvailable(){
for(String pathDir : System.getenv("PATH").split(":")){
if(new File(pathDir, "su").exists()) {
return true;
}
}
return false;
}
This method simply loops through the directories listed in the "PATH" environment variable and checks if a "su" file exists in one of them.
In order to truly check for root access the "su" command must actually be run. If an app like SuperUser is installed, then at this point it may ask for root access, or if its already been granted/denied a toast may be shown indicating whether access was granted/denied. A good command to run is "id" so that you can verify that the user id is in fact 0 (root).
Here's a sample method to determine whether root access has been granted:
public static boolean isRootGiven(){
if (isRootAvailable()) {
Process process = null;
try {
process = Runtime.getRuntime().exec(new String[]{"su", "-c", "id"});
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String output = in.readLine();
if (output != null && output.toLowerCase().contains("uid=0"))
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (process != null)
process.destroy();
}
}
return false;
}
It's important to actually test running the "su" command because some emulators have the "su" executable pre-installed, but only allow certain users to access it like the adb shell.
It's also important to check for the existence of the "su" executable before trying to run it, because android has been known to not properly dispose of processes that try to run missing commands. These ghost processes can run up memory consumption over time.
There are many questions about REST auth patterns here on SO. These are the most relevant for your question:
Basically you need to choose between using API keys (least secure as the key may be discovered by an unauthorized user), an app key and token combo (medium), or a full OAuth implementation (most secure).
when you create an object using predefine class, at first you want to create a variable for storing that object. Then you can create object and store variable that you created.
class Student:
def __init__(self):
# creating an object....
student1=Student()
Actually this init method is the constructor of class.you can initialize that method using some attributes.. In that point , when you creating an object , you will have to pass some values for particular attributes..
class Student:
def __init__(self,name,age):
self.name=value
self.age=value
# creating an object.......
student2=Student("smith",25)
Expanding on mjswensen's answer, the command without the filter could take minutes, but the filtered command is almost instant.
PowerShell - List local user accounts
Fast way
Get-WmiObject -Class Win32_UserAccount -Filter "LocalAccount='True'" | select name, fullname
Slow way
Get-WmiObject -Class Win32_UserAccount |? {$_.localaccount -eq $true} | select name, fullname
The code of @ThePracticalOne is great for showing the usage except for one thing:
Somtimes the output would be incomplete.(session.recv_ready()
turns true after the if session.recv_ready():
while session.recv_stderr_ready()
and session.exit_status_ready()
turned true before entering next loop)
so my thinking is to retrieving the data when it is ready to exit the session.
while True:
if session.exit_status_ready():
while True:
while True:
print "try to recv stdout..."
ret = session.recv(nbytes)
if len(ret) == 0:
break
stdout_data.append(ret)
while True:
print "try to recv stderr..."
ret = session.recv_stderr(nbytes)
if len(ret) == 0:
break
stderr_data.append(ret)
break
The way you are doing it is indeed the recommended one (for Python 2.x).
The issue of whether the class is passed explicitly to super
is a matter of style rather than functionality. Passing the class to super
fits in with Python's philosophy of "explicit is better than implicit".
Make sure you aren't caching the page/view that your form is showing up on. It could be caching your CSRF_TOKEN. Happened to me!
Go to "Window -> Preferences -> General -> C/C++ -> Code analysis" and disable "Syntax and Semantics Errors -> Abstract class cannot be instantiated"
Are you looking for something like this?
SELECT CASE WHEN LEFT(created_ts, 1) LIKE '[0-9]'
THEN CONVERT(VARCHAR(10), CONVERT(datetime, created_ts, 1), 101)
ELSE CONVERT(VARCHAR(10), CONVERT(datetime, created_ts, 109), 101)
END created_ts
FROM table1
Output:
| CREATED_TS | |------------| | 02/20/2012 | | 11/29/2012 | | 02/20/2012 | | 11/29/2012 | | 02/20/2012 | | 11/29/2012 | | 11/16/2011 | | 02/20/2012 | | 11/29/2012 |
Here is SQLFiddle demo
A working example to implement the accepted answer by adding a "Boolean" column to an existing table in an oracle database (using number
type):
ALTER TABLE my_table_name ADD (
my_new_boolean_column number(1) DEFAULT 0 NOT NULL
CONSTRAINT my_new_boolean_column CHECK (my_new_boolean_column in (1,0))
);
This creates a new column in my_table_name
called my_new_boolean_column
with default values of 0. The column will not accept NULL
values and restricts the accepted values to either 0
or 1
.
This should do what you want (file contents in a list, by line, without \n)
with open(filename) as f:
mylist = f.read().splitlines()
startup chrome with --disable-web-security
On Windows:
chrome.exe --disable-web-security
On Mac:
open /Applications/Google\ Chrome.app/ --args --disable-web-security
This will allow for cross-domain requests.
I'm not aware of if this also works for local files, but let us know !
And mention, this does exactly what you expect, it disables the web security, so be careful with it.
It's a pity that both of the answers analyze the problem but didn't give a direct answer. Let's see the code.
Z = np.array([1.0, 1.0, 1.0, 1.0])
def func(TempLake, Z):
A = TempLake
B = Z
return A * B
Nlayers = Z.size
N = 3
TempLake = np.zeros((N+1, Nlayers))
kOUT = np.zeros(N + 1)
for i in xrange(N):
# store the i-th result of
# function "func" in i-th item in kOUT
kOUT[i] = func(TempLake[i], Z)
The error shows that you set the ith item of kOUT(dtype:int) into an array. Here every item in kOUT is an int, can't directly assign to another datatype. Hence you should declare the data type of kOUT when you create it. For example, like:
Change the statement below:
kOUT = np.zeros(N + 1)
into:
kOUT = np.zeros(N + 1, dtype=object)
or:
kOUT = np.zeros((N + 1, N + 1))
All code:
import numpy as np
Z = np.array([1.0, 1.0, 1.0, 1.0])
def func(TempLake, Z):
A = TempLake
B = Z
return A * B
Nlayers = Z.size
N = 3
TempLake = np.zeros((N + 1, Nlayers))
kOUT = np.zeros(N + 1, dtype=object)
for i in xrange(N):
kOUT[i] = func(TempLake[i], Z)
Hope it can help you.
This error creeps in if we make some spelling mistake in entering the variable name. Like in stored proc, I have the variable name x and in my insert statement I am using
insert into tablename values(y);
It will throw an error column not allowed here.
<script>
function onSelectedOption(sel) {
if ((sel.selectedIndex) == 0) {
document.getElementById("edit").action =
"http://www.example.co.uk/index.php";
document.getElementById("edit").submit();
}
else
{
document.getElementById("edit").action =
"http://www.example.co.uk/different.php";
document.getElementById("edit").submit();
}
}
</script>
<form name="edit" id="edit" action="" method="GET">
<input type="hidden" name="id" value="{ID}" />
</form>
<select name="option" id="option" onchange="onSelectedOption(this);">
<option name="contactBuyer">Edit item</option>
<option name="relist">End listing</option>
</select>
WCF completely replaces ASMX web services. ASMX is the old way to do web services and WCF is the current way to do web services. All new SOAP web service development, on the client or the server, should be done using WCF.
An answer to a slightly different question: You can use vh
units to pad elements to the center of the viewport:
.centerme {
margin-top: 50vh;
background: red;
}
<div class="centerme">middle</div>
Your NewClass
inherits from UIViewController
. You declared signedIn
in ViewController
. If you want NewClass
to be able to identify that variable it will have to be declared in a class that your NewClass
inherits from.
As someone who has been interested in this for a VERY LONG TIME. See from the manual:
$XDG_CONFIG_HOME/git/config - Second user-specific configuration file. If $XDG_CONFIG_HOME
is not set or empty, $HOME/.config/git/config will be used. Any single-valued variable set in this file will be overwritten by whatever is in ~/.gitconfig. It is a good idea not to create this file if you sometimes use older versions of Git, as support for this file was added fairly recently.
Which was only recently added. This dump is from 2.15.0.
Works for me.
Very close! In your select
expression, you have to use a pipe (|
) before contains
.
This filter produces the expected output.
. - map(select(.Names[] | contains ("data"))) | .[] .Id
The jq Cookbook has an example of the syntax.
Filter objects based on the contents of a key
E.g., I only want objects whose genre key contains "house".
$ json='[{"genre":"deep house"}, {"genre": "progressive house"}, {"genre": "dubstep"}]' $ echo "$json" | jq -c '.[] | select(.genre | contains("house"))' {"genre":"deep house"} {"genre":"progressive house"}
Colin D asks how to preserve the JSON structure of the array, so that the final output is a single JSON array rather than a stream of JSON objects.
The simplest way is to wrap the whole expression in an array constructor:
$ echo "$json" | jq -c '[ .[] | select( .genre | contains("house")) ]'
[{"genre":"deep house"},{"genre":"progressive house"}]
You can also use the map function:
$ echo "$json" | jq -c 'map(select(.genre | contains("house")))'
[{"genre":"deep house"},{"genre":"progressive house"}]
map unpacks the input array, applies the filter to every element, and creates a new array. In other words, map(f)
is equivalent to [.[]|f]
.
You need to install this extension to Visual Studio 2017/2019 in order to get access to the Installer Projects.
According to the page:
This extension provides the same functionality that currently exists in Visual Studio 2015 for Visual Studio Installer projects. To use this extension, you can either open the Extensions and Updates dialog, select the online node, and search for "Visual Studio Installer Projects Extension," or you can download directly from this page.
Once you have finished installing the extension and restarted Visual Studio, you will be able to open existing Visual Studio Installer projects, or create new ones.
I believe this is what you're looking for. It automatically scaled the video to fit the container.
DEMO: http://jsfiddle.net/t8qhgxuy/
Video need to have height and width always set to 100% of the parent.
HTML:
<div class="one"> CONTENT OVER VIDEO
<video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video>
</div>
<div class="two">
<video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video> CONTENT OVER VIDEO
</div>
CSS:
body {
overflow: scroll;
padding: 60px 20px;
}
.one {
width: 90%;
height: 30vw;
overflow: hidden;
border: 15px solid red;
margin-bottom: 40px;
position: relative;
}
.two{
width: 30%;
height: 300px;
overflow: hidden;
border: 15px solid blue;
position: relative;
}
.video-background { /* class name used in javascript too */
width: 100%; /* width needs to be set to 100% */
height: 100%; /* height needs to be set to 100% */
position: absolute;
left: 0;
top: 0;
z-index: -1;
}
JS:
function scaleToFill() {
$('video.video-background').each(function(index, videoTag) {
var $video = $(videoTag),
videoRatio = videoTag.videoWidth / videoTag.videoHeight,
tagRatio = $video.width() / $video.height(),
val;
if (videoRatio < tagRatio) {
val = tagRatio / videoRatio * 1.02; <!-- size increased by 2% because value is not fine enough and sometimes leaves a couple of white pixels at the edges -->
} else if (tagRatio < videoRatio) {
val = videoRatio / tagRatio * 1.02;
}
$video.css('transform','scale(' + val + ',' + val + ')');
});
}
$(function () {
scaleToFill();
$('.video-background').on('loadeddata', scaleToFill);
$(window).resize(function() {
scaleToFill();
});
});
In my case a has to add my classes, when building the SessionFactory
, with addAnnotationClass
Configuration configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration
.addAnnotatedClass(MyEntity1.class)
.addAnnotatedClass(MyEntity2.class)
.buildSessionFactory(builder.build());
Sometimes when your table has a similar name to the database name you should use back tick. so instead of:
INSERT INTO books.book(field1, field2) VALUES ('value1', 'value2');
You should have this:
INSERT INTO `books`.`book`(`field1`, `field2`) VALUES ('value1', 'value2');
Another approach is to add a toString()
method to your Car
class and just let the toString()
method of ArrayList do all the work.
@Override
public String toString()
{
return "Car{" +
"make=" + make +
", registration='" + registration + '\'' +
'}';
}
You don't get one car per line in the output, but it is quick and easy if you just want to see what is in the array.
List<Car> cars = c1.getAll();
System.out.println(cars);
Output would be something like this:
[Car{make=FORD, registration='ABC 123'},
Car{make=TOYOTA, registration='ZYZ 999'}]
I had the error below while running on a dataset smaller than had worked previously.
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 4096 bytes) in C:\workspace\image_management.php on line 173
As the search for the fault brought me here, I thought I'd mention that it's not always the technical solutions in previous answers, but something more simple. In my case it was Firefox. Before I ran the program it was already using 1,157 MB.
It turns out that I'd been watching a 50 minute video a bit at a time over a period of days and that messed things up. It's the sort of fix that experts correct without even thinking about it, but for the likes of me it's worth bearing in mind.
Terminate the Timer once after awake at a specific time in milliseconds.
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(" Run spcific task at given time.");
t.cancel();
}
}, 10000);
When you execute the flutter doctor
command it checks your environment and displays a report to the terminal window. In your case it seems that you did not install the dart and flutter plugin to be able to use them in Android Studio.
To install a plugin, click on Files>Settings>Plugins>install jetbrain plugins
The plugins will add new functionalities to android studio related to flutter. Example it will add the flutter inspector, outliner.
The SDK that you added to the path, will be needed when creating a new flutter project.
Either declare set1 and set2 as floats instead of integers or cast them to floats as part of the calculation:
SET @weight= CAST(@set1 AS float) / CAST(@set2 AS float);
You should install node.js with nvm, because that way you do not have to provide superuser privileges when installing global packages (you can simply execute "npm install -g packagename" without prepending 'sudo').
Brew is fantastic for other things, however. I tend to be biased towards Bower whenever I have the option to install something with Bower.
The other answers are fine. However, you can also pass Collectors.toList() as parameter to Stream.collect() to return the elements as an ArrayList.
System.out.println( list.stream().map( e -> e.toString() ).collect( toList() ) );
select table1.price, table2.price as other_price .....
iOS12 Swift 4 and Swift 5
If you just want to check the connection, and your lowest target is iOS12, then you can use NWPathMonitor
import Network
It needs a little setup with some properties.
let internetMonitor = NWPathMonitor()
let internetQueue = DispatchQueue(label: "InternetMonitor")
private var hasConnectionPath = false
I created a function to get it going. You can do this on view did load or anywhere else. I put a guard in so you can call it all you want to get it going.
func startInternetTracking() {
// only fires once
guard internetMonitor.pathUpdateHandler == nil else {
return
}
internetMonitor.pathUpdateHandler = { update in
if update.status == .satisfied {
print("Internet connection on.")
self.hasConnectionPath = true
} else {
print("no internet connection.")
self.hasConnectionPath = false
}
}
internetMonitor.start(queue: internetQueue)
}
/// will tell you if the device has an Internet connection
/// - Returns: true if there is some kind of connection
func hasInternet() -> Bool {
return hasConnectionPath
}
Now you can just call the helper function hasInternet()
to see if you have one. It updates in real time. See Apple documentation for NWPathMonitor
. It has lots more functionality like cancel()
if you need to stop tracking the connection, type of internet you are looking for, etc.
https://developer.apple.com/documentation/network/nwpathmonitor
Found the simple official way after wading through the walls of text above that would make you think there is none.
Create a complete bundle with:
$ git bundle create <filename> --all
Restore it with:
$ git clone <filename> <folder>
This operation is atomic AFAIK. Check official docs for the gritty details.
Regarding "zip": git bundles are compressed and surprisingly small compared to the .git folder size.
Since rows already exist in the table, the ALTER
statement is trying to insert NULL
into the newly created column for all of the existing rows. You would have to add the column as allowing NULL
, then fill the column with the values you want, and then set it to NOT NULL
afterwards.
\n was not working for me. I was able to fix the issue by changing the xml to text and building the textview text property like below.
android:text="Line 1
Line 2
Line 3
DoubleSpace"
Hopefully This helps those who have said that \n did not work for them.
Batch files are processed row by row and terminate whenever you call an executable directly.
- To make the batch file wait for the process to terminate and continue, put call
in front of it.
- To make the batch file continue without waiting, put start ""
in front of it.
I recommend using this single line script to accomplish your goal:
@call cscript "%~dp0necdaily.vbs"
(because this is a single line, you can use @ instead of @echo off)
If you believe your script can only be called from the SysWOW64 versions of cmd.exe, you might try:
@%WINDIR%\SysWOW64\cmd.exe /c call cscript "%~dp0necdaily.vbs"
If you need the window to remain, you can replace /c with /k
Do this Html and the CSS is in the head tag. Just make a new class and in the css use this code snippet:
pointer-events:none;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.buttonDisabled {
pointer-events: none;
}
</style>
</head>
<body>
<button class="buttonDisabled">Not-a-button</button>
</body>
</html>
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
.setChannelId(CHANNEL_ID)
.build();
Right code will be :
Notification.Builder notification=new Notification.Builder(this)
with dependency 26.0.1 and new updated dependencies such as 28.0.0.
Some users use this code in the form of this :
Notification notification=new NotificationCompat.Builder(this)//this is also wrong code.
So Logic is that which Method you will declare or initilize then the same methode on Right side will be use for Allocation. if in Leftside of = you will use some method then the same method will be use in right side of = for Allocation with new.
Try this code...It will sure work
if you want to call click event:
SomeButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
And if you want the button looks like it is pressed:
typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(SomeButton, new object[] { true });
and unpressed after that:
typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(SomeButton, new object[] { false });
or use the ToggleButton
To get a timestamp
from Date()
, you'll need to divide getTime()
by 1000
, i.e. :
Date currentDate = new Date();
currentDate.getTime() / 1000;
// 1397132691
or simply:
long unixTime = System.currentTimeMillis() / 1000L;
name
attribute in IE, please add ID to the element if you want to use getElementByIdA great alternative is
All
- it is a collection. The [0] will get the elements of the first form on the page. The "form" is a valid CSS selectorIn all of the above, the .elements
can be replaced by for example .querySelectorAll("[type=text]")
to get all text elements
Found the chrome Options class in the Selenium source code.
Usage to create a Chrome driver instance:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=chrome_options)
You have so many choices, how could you be confused :-)? The main controls are:
# \pset format
# \H
# \x
# \pset pager off
Each has options and interactions with the others. The most automatic options are:
# \x off;\pset format wrapped
# \x auto
The newer "\x auto" option switches to line-by-line display only "if needed".
-[ RECORD 1 ]---------------
id | 6
description | This is a gallery of oilve oil brands.
authority | I love olive oil, and wanted to create a place for
reviews and comments on various types.
-[ RECORD 2 ]---------------
id | 19
description | XXX Test A
authority | Testing
The older "\pset format wrapped" is similar in that it tries to fit the data neatly on screen, but falls back to unaligned if the headers won't fit. Here's an example of wrapped:
id | description | authority
----+--------------------------------+---------------------------------
6 | This is a gallery of oilve | I love olive oil, and wanted to
; oil brands. ; create a place for reviews and
; ; comments on various types.
19 | Test Test A | Testing
In case you want to write fallback code, decoding from base64 has been present in iOS since the very beginning by caveat of NSURL
:
NSURL *URL = [NSURL URLWithString:
[NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
base64String]];
return [NSData dataWithContentsOfURL:URL];
use this(assume that your table name is emails):
select * from emails as a
inner join
(select EmailAddress, min(Id) as id from emails
group by EmailAddress ) as b
on a.EmailAddress = b.EmailAddress
and a.Id = b.id
hope this help..
For radio buttons use the following script:
var myRadio = $('input[name=meme_wall_share]');
var checkedValue = myRadio.filter(':checked').val();
Many answer above are correct but same time convoluted with other aspects of authN/authZ. What actually resolves the exception in question is this line:
services.AddScheme<YourAuthenticationOptions, YourAuthenticationHandler>(YourAuthenticationSchemeName, options =>
{
options.YourProperty = yourValue;
})
I got the same problem and its all snatching my hair. Thanks for this https://stackoverflow.com/a/35697105/5228412
What we can do..
favourite_fab.setImageDrawable(ContextCompat.getDrawable(getBaseContext(), R.drawable.favourite_selected));
it works fine for me and wish for others who'll reach here.
You can find ===
and !==
operators in several other dynamically-typed languages as well. It always means that the two values are not only compared by their "implied" value (i.e. either or both values might get converted to make them comparable), but also by their original type.
That basically means that if 0 == "0"
returns true, 0 === "0"
will return false because you are comparing a number and a string. Similarly, while 0 != "0"
returns false, 0 !== "0"
returns true.
Not sure if this is correct in any sense but this seems to work for me.
someHeader.h
inline int someVar;
I don't have linking/multiple definition issues and it "just works"... ;- )
It's quite handy for "quick" tests... Try to avoid global vars tho, because every says so... ;- )
I get this error whenever I use np.concatenate
the wrong way:
>>> a = np.eye(2)
>>> np.concatenate(a, a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<__array_function__ internals>", line 6, in concatenate
TypeError: only integer scalar arrays can be converted to a scalar index
The correct way is to input the two arrays as a tuple:
>>> np.concatenate((a, a))
array([[1., 0.],
[0., 1.],
[1., 0.],
[0., 1.]])
This disables the script errors and also disables other windows.. such as the NTLM login window or the client certificate accept window. The below will suppress only javascript errors.
// Hides script errors without hiding other dialog boxes.
private void SuppressScriptErrorsOnly(WebBrowser browser)
{
// Ensure that ScriptErrorsSuppressed is set to false.
browser.ScriptErrorsSuppressed = false;
// Handle DocumentCompleted to gain access to the Document object.
browser.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(
browser_DocumentCompleted);
}
private void browser_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
((WebBrowser)sender).Document.Window.Error +=
new HtmlElementErrorEventHandler(Window_Error);
}
private void Window_Error(object sender,
HtmlElementErrorEventArgs e)
{
// Ignore the error and suppress the error dialog box.
e.Handled = true;
}
If performance is the main concern then the irony, in my opinion, is the Java constructs to format the text that goes into the buffer, will be far more time consuming on the CPU than the allocation/reallocation/garbage collection ... well, possibly not the GC (garbage collection) depending on how many builders you create and discard.
But simply appending a compound string ("Hello World of " + 6E9 + " earthlings."
) to the buffer is likely to make the whole matter inconsequential.
And, really, if an instance of StringBuilder
is involved, then the content is complex and/or longer than a simple String str = "Hi";
(never mind that Java probably uses a builder in the background anyway).
Personally, I try not to abuse the GC. So if it's something that's going to be used a lot in a rapid fire scenario - like, say, writing debug output messages - I just assume declare it elsewhere and zero it out for reuse.
class MyLogger {
StringBuilder strBldr = new StringBuilder(256);
public void logMsg( String stuff, SomeLogWriterClass log ) {
// zero out strBldr's internal index count, not every
// index in strBldr's internal buffer
strBldr.setLength(0);
// ... append status level
strBldr.append("Info");
// ... append ' ' followed by timestamp
// assuming getTimestamp() returns a String
strBldr.append(' ').append(getTimestamp());
// ... append ':' followed by user message
strBldr.append(':').append(msg);
log.write(strBldr.toString());
}
}
You can check if the port is being used by other program using WAMP menu -
Click on WAMP icon select Apache -> Service -> Test Port 80
, this will check if the port is used by any other program
Also do this select Apache -> Service -> Install Service
, this will make apache use port 80 if the port is not already used by any other program like IIS or Skype
Restart the WAMP see if the problem is fixed.
If port 80 is already used by some program, then you can choose other listening port for WAMP. To do this -
click WAMP icon -> Apache -> httpd.conf
Now find listen 80
(where 80 is port number, it can be different on your system)
Now change that to something else like 3333, you can access WAMP homepage by typing localhost:3333
or 127.0.0.1:3333
in browser's address bar.
If you want WAMP to use port 80, uninstall the program that is using port 80 and then do things stated in step 2 or you can change port in that program's setting, also check httpd.conf
file for listen [port]
line.
MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU]
$f=fopen('myfile.txt','w');
fwrite($f,'new content');
fclose($f);
Warning for those using file_put_contents
It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time
If you have the milliseconds since the Epoch and want to convert them to a local date using the current local timezone, you can use
LocalDate date =
Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()).toLocalDate();
but keep in mind that even the system’s default time zone may change, thus the same long
value may produce different result in subsequent runs, even on the same machine.
Further, keep in mind that LocalDate
, unlike java.util.Date
, really represents a date, not a date and time.
Otherwise, you may use a LocalDateTime
:
LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
For Android, go to this path,
android > app > src > main > res > drawable > launcher_background.xml
default code is for white colour background screen. like this,
<!-- You can insert your own image assets here -->
<item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item>
You can changes its color or modify this by adding icon or any custom design. for more customisation detail checkout this for android.
for Ios
open Ios project in Xcode.
select Runner and then.inside Runner folder Main.Storyboard file is there, enter image description here
by default its colour is white, you can customise or change colour this by your requirement, for more customisation check out this Ios.
You can use the not
function rather than the :not
selector:
$(".content a").not(this).hide("slow")
CROS needs to be resolved from server side.
Create Filters as per requirement to allow access and add filters in web.xml
Example using spring:
Filter Class:
@Component
public class SimpleFilter implements Filter {
@Override
public void init(FilterConfig arg0) throws ServletException {}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response=(HttpServletResponse) resp;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, resp);
}
@Override
public void destroy() {}
}
Web.xml:
<filter>
<filter-name>simpleCORSFilter</filter-name>
<filter-class>
com.abc.web.controller.general.SimpleFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>simpleCORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if
condition is always true.
The simplest way to make it work, it seems to me, is to account for this case:
var value = $(this).val();
if ( value.length > 0 && value != "Default text" ) ...
x & 1
is equivalent to x % 2
.
x >> 1
is equivalent to x / 2
So, these things are basically the result and remainder of divide by two.
If you need simple mechanism to import from text/parse multiline CSV you could use:
CREATE TABLE t -- OR INSERT INTO tab(col_names)
AS
SELECT
t.f[1] AS col1
,t.f[2]::int AS col2
,t.f[3]::date AS col3
,t.f[4] AS col4
FROM (
SELECT regexp_split_to_array(l, ',') AS f
FROM regexp_split_to_table(
$$a,1,2016-01-01,bbb
c,2,2018-01-01,ddd
e,3,2019-01-01,eee$$, '\n') AS l) t;
This is hard to answer without more detail about the network architecture. Some things to investigate are:
In Visual Studio 2019, one of my projects target framework was .net core but it was referencing another project whose target framework was .net standard. I changed all of the projects to reference .net standard and the icons went away. To see what your project is right click it and click properties and look at Target framework. You can also normal click the project itself and look at the < TargetFramework > tag under < PropertyGroup >
Thank you OP for your question, and Roman for your answer. I had to search a bit to find this; I hope the following helps others.
Python 2.7
See: https://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html
import numpy as np
from StringIO import StringIO
data = "1, abc , 2\n 3, xxx, 4"
print type(data)
"""
<type 'str'>
"""
print '\n', np.genfromtxt(StringIO(data), delimiter=",", dtype="|S3", autostrip=True)
"""
[['1' 'abc' '2']
['3' 'xxx' '4']]
"""
print '\n', type(data)
"""
<type 'str'>
"""
print '\n', np.genfromtxt(StringIO(data), delimiter=",", autostrip=True)
"""
[[ 1. nan 2.]
[ 3. nan 4.]]
"""
Python 3.5:
import numpy as np
from io import StringIO
import io
data = "1, abc , 2\n 3, xxx, 4"
#print(data)
"""
1, abc , 2
3, xxx, 4
"""
#print(type(data))
"""
<class 'str'>
"""
#np.genfromtxt(StringIO(data), delimiter=",", autostrip=True)
# TypeError: Can't convert 'bytes' object to str implicitly
print('\n')
print(np.genfromtxt(io.BytesIO(data.encode()), delimiter=",", dtype="|S3", autostrip=True))
"""
[[b'1' b'abc' b'2']
[b'3' b'xxx' b'4']]
"""
print('\n')
print(np.genfromtxt(io.BytesIO(data.encode()), delimiter=",", autostrip=True))
"""
[[ 1. nan 2.]
[ 3. nan 4.]]
"""
Aside:
dtype="|Sx", where x = any of { 1, 2, 3, ...}:
dtypes. Difference between S1 and S2 in Python
"The |S1 and |S2 strings are data type descriptors; the first means the array holds strings of length 1, the second of length 2. ..."
Changed the set to remove % as that will write to text file as Echo on or off
echo off
title Custom Text File
cls
set /p txt=What do you want it to say? ;
echo %txt% > "D:\Testing\dblank.txt"
exit
HTTP Basic Access Authentication
Basic Authentication uses base64 encoding(not encryption) for generating our cryptographic string which contains the information of username and password. HTTP Basic doesn’t need to be implemented over SSL, but if you don’t, it isn’t secure at all. So I’m not even going to entertain the idea of using it without.
Pros:
Cons:
In Summary – if you have control of the clients, or can ensure they use SSL, HTTP Basic is a good choice. The slowness of the SSL can be cancelled out by the speed of only making one request
Syntax of basic Authentication
Value = username:password
Encoded Value = base64(Value)
Authorization Value = Basic <Encoded Value>
//at last Authorization key/value map added to http header as follows
Authorization: <Authorization Value>
HTTP Digest Access Authentication
Digest Access Authentication uses the hashing(i.e digest means cut into small pieces) methodologies to generate the cryptographic result. HTTP Digest access authentication is a more complex form of authentication that works as follows:
Pros:
Cons:
In Summary, HTTP Digest is inherently vulnerable to at least two attacks, whereas a server using strong encryption for passwords with HTTP Basic over SSL is less likely to share these vulnerabilities.
If you don’t have control over your clients however they could attempt to perform Basic authentication without SSL, which is much less secure than Digest.
RFC 2069 Digest Access Authentication Syntax
Hash1=MD5(username:realm:password)
Hash2=MD5(method:digestURI)
response=MD5(Hash1:nonce:Hash2)
RFC 2617 Digest Access Authentication Syntax
Hash1=MD5(username:realm:password)
Hash2=MD5(method:digestURI)
response=MD5(Hash1:nonce:nonceCount:cnonce:qop:Hash2)
//some additional parameters added
In Postman looks as follows:
Note:
This is the answer, hope it helps someone :)
First there are two variations on how the xml can be written:
<row>
<IdInvernadero>8</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>8</IdCaracteristica1>
<IdCaracteristica2>8</IdCaracteristica2>
<Cantidad>25</Cantidad>
<Folio>4568457</Folio>
</row>
<row>
<IdInvernadero>3</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>1</IdCaracteristica1>
<IdCaracteristica2>2</IdCaracteristica2>
<Cantidad>72</Cantidad>
<Folio>4568457</Folio>
</row>
Answer:
SELECT
Tbl.Col.value('IdInvernadero[1]', 'smallint'),
Tbl.Col.value('IdProducto[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica1[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica2[1]', 'smallint'),
Tbl.Col.value('Cantidad[1]', 'int'),
Tbl.Col.value('Folio[1]', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
<row IdInvernadero="8" IdProducto="3" IdCaracteristica1="8" IdCaracteristica2="8" Cantidad ="25" Folio="4568457" />
<row IdInvernadero="3" IdProducto="3" IdCaracteristica1="1" IdCaracteristica2="2" Cantidad ="72" Folio="4568457" />
Answer:
SELECT
Tbl.Col.value('@IdInvernadero', 'smallint'),
Tbl.Col.value('@IdProducto', 'smallint'),
Tbl.Col.value('@IdCaracteristica1', 'smallint'),
Tbl.Col.value('@IdCaracteristica2', 'smallint'),
Tbl.Col.value('@Cantidad', 'int'),
Tbl.Col.value('@Folio', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
Taken from:
I'm assuming you have multiple markers that you wish to display on a google map.
The solution is two parts, one to create and populate an array containing all the details of the markers, then a second to loop through all entries in the array to create each marker.
Not know what environment you're using, it's a little difficult to provide specific help.
My best advice is to take a look at this article & accepted answer to understand the principals of creating a map with multiple markers: Display multiple markers on a map with their own info windows
I had same problem, the solution was so easy
Right click on solotion install Microsoft.ASP.NET.WebApi from "Manage Nuget Package for Sulotion"
boom that's it ;)
s = 'hi how are you'
l = list(map(lambda x: x,s.split()))
print(l)
Output: ['hi', 'how', 'are', 'you']
Use <br />
OR <br>
-
<li>Post by<br /><a>Author</a></li>
OR
<li>Post by<br><a>Author</a></li>
or
make the a
element display:block;
<li>Post by <a style="display:block;">Author</a></li>
With the release of Java 5, the product version was made distinct from the developer version as described here
Every function inside a class, and every class variable must take the self argument as pointed.
class mystuff:
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
def sum(self,a,b):
return a+b
print mystuff.average(9,18,27) # should raise error
print mystuff.sum(18,27) # should be ok
If class variables are involved:
class mystuff:
def setVariables(self,a,b):
self.x = a
self.y = b
return a+b
def mult(self):
return x * y # This line will raise an error
def sum(self):
return self.x + self.y
print mystuff.setVariables(9,18) # Setting mystuff.x and mystuff.y
print mystuff.mult() # should raise error
print mystuff.sum() # should be ok
I couldn't find a single answer or a section in the official Django docs that had all the information I needed to override/extend the default admin templates, so I'm writing this answer as a complete guide, hoping that it would be helpful for others in the future.
Assuming the standard Django project structure:
mysite-container/ # project container directory
manage.py
mysite/ # project package
__init__.py
admin.py
apps.py
settings.py
urls.py
wsgi.py
app1/
app2/
...
static/
templates/
Here's what you need to do:
In mysite/admin.py
, create a sub-class of AdminSite
:
from django.contrib.admin import AdminSite
class CustomAdminSite(AdminSite):
# set values for `site_header`, `site_title`, `index_title` etc.
site_header = 'Custom Admin Site'
...
# extend / override admin views, such as `index()`
def index(self, request, extra_context=None):
extra_context = extra_context or {}
# do whatever you want to do and save the values in `extra_context`
extra_context['world'] = 'Earth'
return super(CustomAdminSite, self).index(request, extra_context)
custom_admin_site = CustomAdminSite()
Make sure to import custom_admin_site
in the admin.py
of your apps and register your models on it to display them on your customized admin site (if you want to).
In mysite/apps.py
, create a sub-class of AdminConfig
and set default_site
to admin.CustomAdminSite
from the previous step:
from django.contrib.admin.apps import AdminConfig
class CustomAdminConfig(AdminConfig):
default_site = 'admin.CustomAdminSite'
In mysite/settings.py
, replace django.admin.site
in INSTALLED_APPS
with apps.CustomAdminConfig
(your custom admin app config from the previous step).
In mysite/urls.py
, replace admin.site.urls
from the admin URL to custom_admin_site.urls
from .admin import custom_admin_site
urlpatterns = [
...
path('admin/', custom_admin_site.urls),
# for Django 1.x versions: url(r'^admin/', include(custom_admin_site.urls)),
...
]
Create the template you want to modify in your templates
directory, maintaining the default Django admin templates directory structure as specified in the docs. For example, if you were modifying admin/index.html
, create the file templates/admin/index.html
.
All of the existing templates can be modified this way, and their names and structures can be found in Django's source code.
Now you can either override the template by writing it from scratch or extend it and then override/extend specific blocks.
For example, if you wanted to keep everything as-is but wanted to override the content
block (which on the index page lists the apps and their models that you registered), add the following to templates/admin/index.html
:
{% extends 'admin/index.html' %}
{% block content %}
<h1>
Hello, {{ world }}!
</h1>
{% endblock %}
To preserve the original contents of a block, add {{ block.super }}
wherever you want the original contents to be displayed:
{% extends 'admin/index.html' %}
{% block content %}
<h1>
Hello, {{ world }}!
</h1>
{{ block.super }}
{% endblock %}
You can also add custom styles and scripts by modifying the extrastyle
and extrahead
blocks.
An easy solution is to have a boolean variable that the thread sets to true on regular intervals, and that is checked and set to false by the thread wanting to know the status. If the variable is false for to long then the thread is no longer considered active.
A more thread-safe way is to have a counter that is increased by the child thread, and the main thread compares the counter to a stored value and if the same after too long time then the child thread is considered not active.
Note however, there is no way in C++11 to actually kill or remove a thread that has hanged.
Edit How to check if a thread has cleanly exited or not: Basically the same technique as described in the first paragraph; Have a boolean variable initialized to false. The last thing the child thread does is set it to true. The main thread can then check that variable, and if true do a join on the child thread without much (if any) blocking.
Edit2 If the thread exits due to an exception, then have two thread "main" functions: The first one have a try
-catch
inside which it calls the second "real" main thread function. This first main function sets the "have_exited" variable. Something like this:
bool thread_done = false;
void *thread_function(void *arg)
{
void *res = nullptr;
try
{
res = real_thread_function(arg);
}
catch (...)
{
}
thread_done = true;
return res;
}
You missed the *
in front of NgIf (like we all have, dozens of times):
<div *ngIf="answer.accepted">✔</div>
Without the *
, Angular sees that the ngIf
directive is being applied to the div
element, but since there is no *
or <template>
tag, it is unable to locate a template, hence the error.
If you get this error with Angular v5:
Error: StaticInjectorError[TemplateRef]:
StaticInjectorError[TemplateRef]:
NullInjectorError: No provider for TemplateRef!
You may have <template>...</template>
in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>
.
You've got several options:
x
ecute permissions on that directory.x
ecute permissions.
chmod(1)
to change the permissions orsetfacl(1)
command to add an access control list entry for your user account. (This also requires mounting the filesystem with the acl
option; see mount(8)
and fstab(5)
for details on the mount parameter.)It's impossible to suggest the correct approach without knowing more about the problem; why are the directory permissions set the way they are? Why do you need access to that directory?
If you want to do this programmatically (no manual text entry with gedit) here's a version for a Dockerfile based on user1341296's answer above:
FROM spittet/ruby-mysql
MAINTAINER [email protected]
RUN cp -R -p /var/lib/mysql /dev/shm && \
rm -rf /var/lib/mysql && \
sed -i -e 's,/var/lib/mysql,/dev/shm/mysql,g' /etc/mysql/my.cnf && \
/etc/init.d/mysql restart
Available on Docker hub here: https://hub.docker.com/r/richardjecooke/ruby-mysql-in-memory/
Yes that is valid syntax but it may well not do what you want.
Execution will continue after your RAISERROR
except if you add a RETURN
. So you will need to add a block with BEGIN ... END
to hold the two statements.
Also I'm not sure why you plumped for severity 15. That usually indicates a syntax error.
Finally I'd simplify the conditions using IN
CREATE PROCEDURE [dbo].[AddApplicationUser] (@TenantId BIGINT,
@UserType TINYINT,
@UserName NVARCHAR(100),
@Password NVARCHAR(100))
AS
BEGIN
IF ( @TenantId IS NULL
AND @UserType IN ( 0, 1 ) )
BEGIN
RAISERROR('The value for @TenantID should not be null',15,1);
RETURN;
END
END
Without VBA...
If you can use a helper column, you can use the MATCH
function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match
To simply identify duplicates, use a helper column
Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:
=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")
Drag/copy this forumla down, and it should identify the duplicates.
To highlight cells, use conditional formatting:
With some tinkering, you can use this MATCH
function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.
Something like:
=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))
For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:
=B1="Duplicate"
This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.
Why not do two queries:
select top(M+N-1) * from table into temp tmp_final with no log;
select top(N-1) * from tmp_final order by id desc;
Try with:
@Scheduled(cron = "0 1 1 * * ?")
Below you can find the example patterns from the spring forum:
* "0 0 * * * *" = the top of every hour of every day.
* "*/10 * * * * *" = every ten seconds.
* "0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
* "0 0 8,10 * * *" = 8 and 10 o'clock of every day.
* "0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.
* "0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
* "0 0 0 25 12 ?" = every Christmas Day at midnight
Cron expression is represented by six fields:
second, minute, hour, day of month, month, day(s) of week
(*)
means match any
*/X
means "every X"
?
("no specific value") - useful when you need to specify something in one of the two fields in which the character is allowed, but not the other. For example, if I want my trigger to fire on a particular day of the month (say, the 10th), but I don't care what day of the week that happens to be, I would put "10" in the day-of-month field and "?" in the day-of-week field.
PS: In order to make it work, remember to enable it in your application context: https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-annotation-support
This will do it:
window.history.pushState(null,null,'https://www.google.com');
A simpler option:
return ( ! empty($a) && strpos($a, 'are'))? true : false;
i want to discuss this question more theoretically (since it has already enough practical answers)
.net has a very nice abstraction model for groups of data (a.k.a. collections)
IEnumerable
it's just a group of data that you can enumerate. It doesn't matter HOW you enumerate, it's just that you can enumerate some data. And that enumeration is done by a completely different object, an IEnumerator
these interfaces are defined is as follows:
//
// Summary:
// Exposes an enumerator, which supports a simple iteration over a non-generic collection.
public interface IEnumerable
{
//
// Summary:
// Returns an enumerator that iterates through a collection.
//
// Returns:
// An System.Collections.IEnumerator object that can be used to iterate through
// the collection.
IEnumerator GetEnumerator();
}
//
// Summary:
// Supports a simple iteration over a non-generic collection.
public interface IEnumerator
{
//
// Summary:
// Gets the element in the collection at the current position of the enumerator.
//
// Returns:
// The element in the collection at the current position of the enumerator.
object Current { get; }
//
// Summary:
// Advances the enumerator to the next element of the collection.
//
// Returns:
// true if the enumerator was successfully advanced to the next element; false if
// the enumerator has passed the end of the collection.
//
// Exceptions:
// T:System.InvalidOperationException:
// The collection was modified after the enumerator was created.
bool MoveNext();
//
// Summary:
// Sets the enumerator to its initial position, which is before the first element
// in the collection.
//
// Exceptions:
// T:System.InvalidOperationException:
// The collection was modified after the enumerator was created.
void Reset();
}
as you might have noticed, the IEnumerator
interface doesn't "know" what an index is, it just knows what element it's currently pointing to, and how to move to the next one.
now here is the trick: foreach
considers every input collection an IEnumerable
, even if it is a more concrete implementation like an IList<T>
(which inherits from IEnumerable
), it will only see the abstract interface IEnumerable
.
what foreach
is actually doing, is calling GetEnumerator
on the collection, and calling MoveNext
until it returns false.
so here is the problem, you want to define a concrete concept "Indices" on an abstract concept "Enumerables", the built in foreach
construct doesn't give you that option, so your only way is to define it yourself, either by what you are doing originally (creating a counter manually) or just use an implementation of IEnumerator
that recognizes indices AND implement a foreach
construct that recognizes that custom implementation.
personally i would create an extension method like this
public static class Ext
{
public static void FE<T>(this IEnumerable<T> l, Action<int, T> act)
{
int counter = 0;
foreach (var item in l)
{
act(counter, item);
counter++;
}
}
}
and use it like this
var x = new List<string>() { "hello", "world" };
x.FE((ind, ele) =>
{
Console.WriteLine($"{ind}: {ele}");
});
this also avoids any unnecessary allocations seen in other answers.
It might be that you do not have the necessary .jar files that give you access to the Java Mail API. These can be downloaded from here.
You could also create a custom model field type - see http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields
In this case, you could 'inherit' from the built-in IntegerField and override its validation logic.
The more I think about this, I realize how useful this would be for many Django apps. Perhaps a IntegerRangeField type could be submitted as a patch for the Django devs to consider adding to trunk.
This is working for me:
from django.db import models
class IntegerRangeField(models.IntegerField):
def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
self.min_value, self.max_value = min_value, max_value
models.IntegerField.__init__(self, verbose_name, name, **kwargs)
def formfield(self, **kwargs):
defaults = {'min_value': self.min_value, 'max_value':self.max_value}
defaults.update(kwargs)
return super(IntegerRangeField, self).formfield(**defaults)
Then in your model class, you would use it like this (field being the module where you put the above code):
size = fields.IntegerRangeField(min_value=1, max_value=50)
OR for a range of negative and positive (like an oscillator range):
size = fields.IntegerRangeField(min_value=-100, max_value=100)
What would be really cool is if it could be called with the range operator like this:
size = fields.IntegerRangeField(range(1, 50))
But, that would require a lot more code since since you can specify a 'skip' parameter - range(1, 50, 2) - Interesting idea though...
My solution is to go straight to reflection to create the serializer. This bypasses the strange file loading that causes the exception. I packaged this in a helper function that also takes care of caching the serializer.
private static readonly Dictionary<Type,XmlSerializer> _xmlSerializerCache = new Dictionary<Type, XmlSerializer>();
public static XmlSerializer CreateDefaultXmlSerializer(Type type)
{
XmlSerializer serializer;
if (_xmlSerializerCache.TryGetValue(type, out serializer))
{
return serializer;
}
else
{
var importer = new XmlReflectionImporter();
var mapping = importer.ImportTypeMapping(type, null, null);
serializer = new XmlSerializer(mapping);
return _xmlSerializerCache[type] = serializer;
}
}
Not clear where My_ConnectionString
is coming from in your example, but try this
System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString
like this
Dim DBConnection As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString)
Stephen Darlington makes a very good point, and you can see that if you change my benchmark to use a more realistically sized table if I fill the table out to 10000 rows using the following:
begin
for i in 2 .. 10000 loop
insert into t (NEEDED_FIELD, cond) values (i, 10);
end loop;
end;
Then re-run the benchmarks. (I had to reduce the loop counts to 5000 to get reasonable times).
declare
otherVar number;
cnt number;
begin
for i in 1 .. 5000 loop
select count(*) into cnt from t where cond = 0;
if (cnt = 1) then
select NEEDED_FIELD INTO otherVar from t where cond = 0;
else
otherVar := 0;
end if;
end loop;
end;
/
PL/SQL procedure successfully completed.
Elapsed: 00:00:04.34
declare
otherVar number;
begin
for i in 1 .. 5000 loop
begin
select NEEDED_FIELD INTO otherVar from t where cond = 0;
exception
when no_data_found then
otherVar := 0;
end;
end loop;
end;
/
PL/SQL procedure successfully completed.
Elapsed: 00:00:02.10
The method with the exception is now more than twice as fast. So, for almost all cases,the method:
SELECT NEEDED_FIELD INTO var WHERE condition;
EXCEPTION
WHEN NO_DATA_FOUND....
is the way to go. It will give correct results and is generally the fastest.
The same thing happened to me and i found that i forgot to put the " at the end of the
#import "CPDConstants.h
so instead
#import "CPDConstants.h"
This one helped me,
res.format({
json:function(){
var responseData = {};
responseData['status'] = 200;
responseData['outputPath'] = outputDirectoryPath;
responseData['sourcePath'] = url;
responseData['message'] = 'Scraping of requested resource initiated.';
responseData['logfile'] = logFileName;
res.json(JSON.stringify(responseData));
}
});
You can also use the code snippet below, with this manner the existence of google maps is checked before the intent is started.
Uri gmmIntentUri = Uri.parse(String.format(Locale.ENGLISH,"geo:%f,%f", latitude, longitude));
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivity(mapIntent);
}
Reference: https://developers.google.com/maps/documentation/android-api/intents
I had this problem when I was trying to connect my phone and trying to use adb. I did the following
export PATH=$PATH{}:/path/to/android-sdk/tools:/path/to/android/platform-tools
apt-get install ia32-libs
Connected my phone in USB debug mode and In the terminal type lsusb to get a list of all usb devices. Noted the 9 character (xxxx:xxxx) ID to the left of my phone.
sudo gedit /etc/udev/rules.d/99-android.rules
Add [ SUBSYSTEM=="usb", ATTRS{idVendor}=="####:####", SYMLINK+="android_adb", MODE="0666" GROUP="plugdev" TEST=="/var/run/ConsoleKit/database", \ RUN+="udev-acl --action=$env{action} --device=$env{DEVNAME}" ] (whatever is in [...] )to the file and replace "####:####" with the number from step 3cop
sudo service udev restart
Restarted my System
open terminal browse to adb directory and run ./adb devices
And it shows my phone hence adb starts working without error.
I hope it helps others
for followers, this error message can also mean "you have it referencing a foreign object that hasn't been saved to the DB yet" (even though it's there, and is non null).
You can try this regular expression : [^\W\d_]
or [a-zA-Z]
.
If local.properties file is missing, just create one in the "project/android" folder with 'sdk.dir=/Users/apple/Library/Android/sdk' and make sure your SDK in on that location.
for creating a file with custom extensions on mac refer the following link
How do I save a TextEdit (mac) file with a custom extension (.sas)?
In bash, the following would be appropriate:
find /dir -type f -print0 | xargs -0i cat {} | grep whatever
This will find all files in the /dir
directory, and safely pipe the filenames into xargs
, which will safely drive grep
.
Skipping xargs
is not a good idea if you have many thousands of files in /dir
; cat
will break due to excessive argument list length. xargs
will sort that all out for you.
The -print0
argument to find
meshes with the -0
argument to xargs
to handle filenames with spaces properly. The -i
argument to xargs
allows you to insert the filename where required in the cat
command line. The brackets are replaced by the filename piped into the cat
command from find
.
I have faced this error, Previous I had push in root directory, and now I have push another directory, so I could be remove this error and run below commands.
git add .
git commit -m "some comments"
git push --set-upstream origin master
Make sure the real source file is saved as UTF-8 (You may even want to try the non-recommended BOM Chars with UTF-8 to make sure).
Also in case of HTML, make sure you have declared the correct encoding using meta
tags:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
If it's a CMS (as you've tagged your question with Joomla) you may need to configure appropriate settings for the encoding.
This worked for me on my VM instance of Ubuntu.
hdfs dfs -copyToLocal [hadoop directory] [local directory]
This is not an error just simple a message. To execute this message change
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
(example)
to
<!DOCTYPE html>
(the Firefox source expect this)
The message was shown in Google Chrome 74 and Opera 60 . After changing it was clear, 0 verbose.
A solution approach
I had to re-install my adb driver to snap out of this probelm. I had install "Universal Naked Driver" in an effort to recover my phone. I uninstalled that and re-installed the driver out of the android sdk.
set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
The single quotes do not indicate a string, they make it starts: 'C:\
instead of C:\
so
%name%
is the usual syntax for expanding a variable, the !name!
syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION
first, or by running the command prompt with CMD /V:ON
.
Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4
to keep the current PATH content, and add something to the end.
Regarding GOROOT
specifically, Go 1.9 will set it automatically to its installation path.
Even if you have multiple Go installed, calling the 1.9.x one will set GOROOT
to /path/to/go/1.9
(before, if not set, it assumed a default path like /usr/local/go
or c:\Go
).
See CL Go Review 53370:
The
go tool
will now use the path from which it was invoked to attempt to locate the root of the Go install tree.
This means that if the entire Go installation is moved to a new location, thego tool
should continue to work as usual.This may be overriden by setting
GOROOT
in the environment, which should only be done in unusual circumstances.
Note that this does not affect the result of theruntime.GOROOT()
function, which will continue to report the original installation location; this may be fixed in later releases.
You can make a custom border using a span. Make a span with a class (Specifying the direction in which the border is going) and an id:
<html>
<body>
<div class="mdiv">
<span class="VerticalBorder" id="Span1"></span>
<header class="mheader">
<span class="HorizontalBorder" id="Span2"></span>
</header>
</div>
</body>
</html>
Then, go to you CSS and set the class to position:absolute
, height:100%
(For Vertical Borders), width:100%
(For Horizontal Borders), margin:0%
and background-color:#000000;
. Add everthing else that is necessary:
body{
margin:0%;
}
div.mdiv{
position:absolute;
width:100%;
height:100%;
top:0%;
left:0%;
margin:0%;
}
header.mheader{
position:absolute;
width:100%;
height:20%; /* You can set this to whatever. I will use 20 for easier calculations. You don't need a header. I'm using it to show you the difference. */
top:0%;
left:0%;
margin:0%;
}
span.HorizontalBorder{
position:absolute;
width:100%;
margin:0%;
background-color:#000000;
}
span.VerticalBorder{
position:absolute;
height:100%;
margin:0%;
background-color:#000000;
}
Then set the id that corresponds to class="VerticalBorder"
to top:0%;
, left:0%;
, width:1%;
(Since the width of the mdiv is equal to the width of the mheader at 100%, the width will be 100% of what you set it. If you set the width to 1% the border will be 1% of the window's width). Set the id that corresponds to the class="HorizontalBorder"
to top:99%
(Since it's in a header container the top refers to the position it is in according to the header. This + the height should add up to 100% if you want it to reach the bottom), left:0%;
and height:1%
(Since the height of the mdiv is 5 times greater than the mheader height [100% = 100, 20% = 20, 100/20 = 5], the height will be 20% of what you set it. If you set the height to 1% the border will be .2% of the window's height). Here is how it will look:
span#Span1{
top:0%;
left:0%;
width:.4%;
}
span#Span2{
top:99%;
left:0%;
width:1%;
}
DISCLAIMER: If you resize the window to a small enough size, the borders will disappear. A solution would be to cap of the size of the border if the window is resized to a certain point. Here is what I did:
window.addEventListener("load", Loaded);
function Loaded() {
window.addEventListener("resize", Resized);
function Resized() {
var WindowWidth = window.innerWidth;
var WindowHeight = window.innerHeight;
var Span1 = document.getElementById("Span1");
var Span2 = document.getElementById("Span2");
if (WindowWidth <= 800) {
Span1.style.width = .4;
}
if (WindowHeight <= 600) {
Span2.style.height = 1;
}
}
}
If you did everything right, it should look like how it is in this link: https://jsfiddle.net/umhgkvq8/12/ For some odd reason, the the border will disappear in jsfiddle but not if you launch it to a browser.
How can I remove the middle character, i.e., M from it?
You can't, because strings in Python are immutable.
Do strings in Python end in any special character?
No. They are similar to lists of characters; the length of the list defines the length of the string, and no character acts as a terminator.
Which is a better way - shifting everything right to left starting from the middle character OR creation of a new string and not copying the middle character?
You cannot modify the existing string, so you must create a new one containing everything except the middle character.
You should be able to use the /quiet
or /qn
options with msiexec
to perform a silent install.
MSI packages export public properties, which you can set with the PROPERTY=value
syntax on the end of the msiexec
parameters.
For example, this command installs a package with no UI and no reboot, with a log and two properties:
msiexec /i c:\path\to\package.msi /quiet /qn /norestart /log c:\path\to\install.log PROPERTY1=value1 PROPERTY2=value2
You can read the options for msiexec
by just running it with no options from Start -> Run.
Note that -(NSString *)tableView:
titleForHeaderInSection:
is not called by UITableView if - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
is implemented in delegate of UITableView;
Assuming you understand the consequences of using the MEMORY engine as mentioned in comments, and here, as well as some others you'll find by searching about (no transaction safety, locking issues, etc) - you can proceed as follows:
MEMORY tables are stored differently than InnoDB, so you'll need to use an export/import strategy. First dump each table separately to a file using SELECT * FROM tablename INTO OUTFILE 'table_filename'
. Create the MEMORY database and recreate the tables you'll be using with this syntax: CREATE TABLE tablename (...) ENGINE = MEMORY;
. You can then import your data using LOAD DATA INFILE 'table_filename' INTO TABLE tablename
for each table.
If you want to change the statusBar
's color to white, for all of the views contained in a UINavigationController
, add this inside AppDelegate
:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UINavigationBar.appearance().barStyle = .blackOpaque
return true
}
This code:
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
does not work for UIViewControllers
contained in a UINavigationController
, because the compiler looks for the statusBarStyle
of the UINavigationController
, not for the statusBarStyle
of the ViewControllers
contained by it.
Hope this helps those who haven't succeeded with the accepted answer!
This is an adapter for HashMaps which I implemented for a recent project. Works in a way similart to what @SandyR does, but encapsulates conversion logic so you don't manually convert strings to a wrapper object.
I used Java 8 features but with a few changes, you can adapt it to previous versions. I tested it for most common scenarios, except new Java 8 stream functions.
Basically it wraps a HashMap, directs all functions to it while converting strings to/from a wrapper object. But I had to also adapt KeySet and EntrySet because they forward some functions to the map itself. So I return two new Sets for keys and entries which actually wrap the original keySet() and entrySet().
One note: Java 8 has changed the implementation of putAll method which I could not find an easy way to override. So current implementation may have degraded performance especially if you use putAll() for a large data set.
Please let me know if you find a bug or have suggestions to improve the code.
package webbit.collections;
import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class CaseInsensitiveMapAdapter<T> implements Map<String,T>
{
private Map<CaseInsensitiveMapKey,T> map;
private KeySet keySet;
private EntrySet entrySet;
public CaseInsensitiveMapAdapter()
{
}
public CaseInsensitiveMapAdapter(Map<String, T> map)
{
this.map = getMapImplementation();
this.putAll(map);
}
@Override
public int size()
{
return getMap().size();
}
@Override
public boolean isEmpty()
{
return getMap().isEmpty();
}
@Override
public boolean containsKey(Object key)
{
return getMap().containsKey(lookupKey(key));
}
@Override
public boolean containsValue(Object value)
{
return getMap().containsValue(value);
}
@Override
public T get(Object key)
{
return getMap().get(lookupKey(key));
}
@Override
public T put(String key, T value)
{
return getMap().put(lookupKey(key), value);
}
@Override
public T remove(Object key)
{
return getMap().remove(lookupKey(key));
}
/***
* I completely ignore Java 8 implementation and put one by one.This will be slower.
*/
@Override
public void putAll(Map<? extends String, ? extends T> m)
{
for (String key : m.keySet()) {
getMap().put(lookupKey(key),m.get(key));
}
}
@Override
public void clear()
{
getMap().clear();
}
@Override
public Set<String> keySet()
{
if (keySet == null)
keySet = new KeySet(getMap().keySet());
return keySet;
}
@Override
public Collection<T> values()
{
return getMap().values();
}
@Override
public Set<Entry<String, T>> entrySet()
{
if (entrySet == null)
entrySet = new EntrySet(getMap().entrySet());
return entrySet;
}
@Override
public boolean equals(Object o)
{
return getMap().equals(o);
}
@Override
public int hashCode()
{
return getMap().hashCode();
}
@Override
public T getOrDefault(Object key, T defaultValue)
{
return getMap().getOrDefault(lookupKey(key), defaultValue);
}
@Override
public void forEach(final BiConsumer<? super String, ? super T> action)
{
getMap().forEach(new BiConsumer<CaseInsensitiveMapKey, T>()
{
@Override
public void accept(CaseInsensitiveMapKey lookupKey, T t)
{
action.accept(lookupKey.key,t);
}
});
}
@Override
public void replaceAll(final BiFunction<? super String, ? super T, ? extends T> function)
{
getMap().replaceAll(new BiFunction<CaseInsensitiveMapKey, T, T>()
{
@Override
public T apply(CaseInsensitiveMapKey lookupKey, T t)
{
return function.apply(lookupKey.key,t);
}
});
}
@Override
public T putIfAbsent(String key, T value)
{
return getMap().putIfAbsent(lookupKey(key), value);
}
@Override
public boolean remove(Object key, Object value)
{
return getMap().remove(lookupKey(key), value);
}
@Override
public boolean replace(String key, T oldValue, T newValue)
{
return getMap().replace(lookupKey(key), oldValue, newValue);
}
@Override
public T replace(String key, T value)
{
return getMap().replace(lookupKey(key), value);
}
@Override
public T computeIfAbsent(String key, final Function<? super String, ? extends T> mappingFunction)
{
return getMap().computeIfAbsent(lookupKey(key), new Function<CaseInsensitiveMapKey, T>()
{
@Override
public T apply(CaseInsensitiveMapKey lookupKey)
{
return mappingFunction.apply(lookupKey.key);
}
});
}
@Override
public T computeIfPresent(String key, final BiFunction<? super String, ? super T, ? extends T> remappingFunction)
{
return getMap().computeIfPresent(lookupKey(key), new BiFunction<CaseInsensitiveMapKey, T, T>()
{
@Override
public T apply(CaseInsensitiveMapKey lookupKey, T t)
{
return remappingFunction.apply(lookupKey.key, t);
}
});
}
@Override
public T compute(String key, final BiFunction<? super String, ? super T, ? extends T> remappingFunction)
{
return getMap().compute(lookupKey(key), new BiFunction<CaseInsensitiveMapKey, T, T>()
{
@Override
public T apply(CaseInsensitiveMapKey lookupKey, T t)
{
return remappingFunction.apply(lookupKey.key,t);
}
});
}
@Override
public T merge(String key, T value, BiFunction<? super T, ? super T, ? extends T> remappingFunction)
{
return getMap().merge(lookupKey(key), value, remappingFunction);
}
protected Map<CaseInsensitiveMapKey,T> getMapImplementation() {
return new HashMap<>();
}
private Map<CaseInsensitiveMapKey,T> getMap() {
if (map == null)
map = getMapImplementation();
return map;
}
private CaseInsensitiveMapKey lookupKey(Object key)
{
return new CaseInsensitiveMapKey((String)key);
}
public class CaseInsensitiveMapKey {
private String key;
private String lookupKey;
public CaseInsensitiveMapKey(String key)
{
this.key = key;
this.lookupKey = key.toUpperCase();
}
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CaseInsensitiveMapKey that = (CaseInsensitiveMapKey) o;
return lookupKey.equals(that.lookupKey);
}
@Override
public int hashCode()
{
return lookupKey.hashCode();
}
}
private class KeySet implements Set<String> {
private Set<CaseInsensitiveMapKey> wrapped;
public KeySet(Set<CaseInsensitiveMapKey> wrapped)
{
this.wrapped = wrapped;
}
private List<String> keyList() {
return stream().collect(Collectors.toList());
}
private Collection<CaseInsensitiveMapKey> mapCollection(Collection<?> c) {
return c.stream().map(it -> lookupKey(it)).collect(Collectors.toList());
}
@Override
public int size()
{
return wrapped.size();
}
@Override
public boolean isEmpty()
{
return wrapped.isEmpty();
}
@Override
public boolean contains(Object o)
{
return wrapped.contains(lookupKey(o));
}
@Override
public Iterator<String> iterator()
{
return keyList().iterator();
}
@Override
public Object[] toArray()
{
return keyList().toArray();
}
@Override
public <T> T[] toArray(T[] a)
{
return keyList().toArray(a);
}
@Override
public boolean add(String s)
{
return wrapped.add(lookupKey(s));
}
@Override
public boolean remove(Object o)
{
return wrapped.remove(lookupKey(o));
}
@Override
public boolean containsAll(Collection<?> c)
{
return keyList().containsAll(c);
}
@Override
public boolean addAll(Collection<? extends String> c)
{
return wrapped.addAll(mapCollection(c));
}
@Override
public boolean retainAll(Collection<?> c)
{
return wrapped.retainAll(mapCollection(c));
}
@Override
public boolean removeAll(Collection<?> c)
{
return wrapped.removeAll(mapCollection(c));
}
@Override
public void clear()
{
wrapped.clear();
}
@Override
public boolean equals(Object o)
{
return wrapped.equals(lookupKey(o));
}
@Override
public int hashCode()
{
return wrapped.hashCode();
}
@Override
public Spliterator<String> spliterator()
{
return keyList().spliterator();
}
@Override
public boolean removeIf(Predicate<? super String> filter)
{
return wrapped.removeIf(new Predicate<CaseInsensitiveMapKey>()
{
@Override
public boolean test(CaseInsensitiveMapKey lookupKey)
{
return filter.test(lookupKey.key);
}
});
}
@Override
public Stream<String> stream()
{
return wrapped.stream().map(it -> it.key);
}
@Override
public Stream<String> parallelStream()
{
return wrapped.stream().map(it -> it.key).parallel();
}
@Override
public void forEach(Consumer<? super String> action)
{
wrapped.forEach(new Consumer<CaseInsensitiveMapKey>()
{
@Override
public void accept(CaseInsensitiveMapKey lookupKey)
{
action.accept(lookupKey.key);
}
});
}
}
private class EntrySet implements Set<Map.Entry<String,T>> {
private Set<Entry<CaseInsensitiveMapKey,T>> wrapped;
public EntrySet(Set<Entry<CaseInsensitiveMapKey,T>> wrapped)
{
this.wrapped = wrapped;
}
private List<Map.Entry<String,T>> keyList() {
return stream().collect(Collectors.toList());
}
private Collection<Entry<CaseInsensitiveMapKey,T>> mapCollection(Collection<?> c) {
return c.stream().map(it -> new CaseInsensitiveEntryAdapter((Entry<String,T>)it)).collect(Collectors.toList());
}
@Override
public int size()
{
return wrapped.size();
}
@Override
public boolean isEmpty()
{
return wrapped.isEmpty();
}
@Override
public boolean contains(Object o)
{
return wrapped.contains(lookupKey(o));
}
@Override
public Iterator<Map.Entry<String,T>> iterator()
{
return keyList().iterator();
}
@Override
public Object[] toArray()
{
return keyList().toArray();
}
@Override
public <T> T[] toArray(T[] a)
{
return keyList().toArray(a);
}
@Override
public boolean add(Entry<String,T> s)
{
return wrapped.add(null );
}
@Override
public boolean remove(Object o)
{
return wrapped.remove(lookupKey(o));
}
@Override
public boolean containsAll(Collection<?> c)
{
return keyList().containsAll(c);
}
@Override
public boolean addAll(Collection<? extends Entry<String,T>> c)
{
return wrapped.addAll(mapCollection(c));
}
@Override
public boolean retainAll(Collection<?> c)
{
return wrapped.retainAll(mapCollection(c));
}
@Override
public boolean removeAll(Collection<?> c)
{
return wrapped.removeAll(mapCollection(c));
}
@Override
public void clear()
{
wrapped.clear();
}
@Override
public boolean equals(Object o)
{
return wrapped.equals(lookupKey(o));
}
@Override
public int hashCode()
{
return wrapped.hashCode();
}
@Override
public Spliterator<Entry<String,T>> spliterator()
{
return keyList().spliterator();
}
@Override
public boolean removeIf(Predicate<? super Entry<String, T>> filter)
{
return wrapped.removeIf(new Predicate<Entry<CaseInsensitiveMapKey, T>>()
{
@Override
public boolean test(Entry<CaseInsensitiveMapKey, T> entry)
{
return filter.test(new FromCaseInsensitiveEntryAdapter(entry));
}
});
}
@Override
public Stream<Entry<String,T>> stream()
{
return wrapped.stream().map(it -> new Entry<String, T>()
{
@Override
public String getKey()
{
return it.getKey().key;
}
@Override
public T getValue()
{
return it.getValue();
}
@Override
public T setValue(T value)
{
return it.setValue(value);
}
});
}
@Override
public Stream<Map.Entry<String,T>> parallelStream()
{
return StreamSupport.stream(spliterator(), true);
}
@Override
public void forEach(Consumer<? super Entry<String, T>> action)
{
wrapped.forEach(new Consumer<Entry<CaseInsensitiveMapKey, T>>()
{
@Override
public void accept(Entry<CaseInsensitiveMapKey, T> entry)
{
action.accept(new FromCaseInsensitiveEntryAdapter(entry));
}
});
}
}
private class EntryAdapter implements Map.Entry<String,T> {
private Entry<String,T> wrapped;
public EntryAdapter(Entry<String, T> wrapped)
{
this.wrapped = wrapped;
}
@Override
public String getKey()
{
return wrapped.getKey();
}
@Override
public T getValue()
{
return wrapped.getValue();
}
@Override
public T setValue(T value)
{
return wrapped.setValue(value);
}
@Override
public boolean equals(Object o)
{
return wrapped.equals(o);
}
@Override
public int hashCode()
{
return wrapped.hashCode();
}
}
private class CaseInsensitiveEntryAdapter implements Map.Entry<CaseInsensitiveMapKey,T> {
private Entry<String,T> wrapped;
public CaseInsensitiveEntryAdapter(Entry<String, T> wrapped)
{
this.wrapped = wrapped;
}
@Override
public CaseInsensitiveMapKey getKey()
{
return lookupKey(wrapped.getKey());
}
@Override
public T getValue()
{
return wrapped.getValue();
}
@Override
public T setValue(T value)
{
return wrapped.setValue(value);
}
}
private class FromCaseInsensitiveEntryAdapter implements Map.Entry<String,T> {
private Entry<CaseInsensitiveMapKey,T> wrapped;
public FromCaseInsensitiveEntryAdapter(Entry<CaseInsensitiveMapKey, T> wrapped)
{
this.wrapped = wrapped;
}
@Override
public String getKey()
{
return wrapped.getKey().key;
}
@Override
public T getValue()
{
return wrapped.getValue();
}
@Override
public T setValue(T value)
{
return wrapped.setValue(value);
}
}
}
No, the HTML5 range input only accepts one input. I would recommend you to use something like the jQuery UI range slider for that task.
@Xeon06, nice but just as a fyi for those that read this thread and tried like me...
when returning the array from php => json_encode($theArray)
. converts to a string which to me isn't easy to manipulate esp for soft js users like myself.
Inside js, you are trying to get the array values and/or keys of the array u r better off using JSON.parse as in var jsArray = JSON.parse(data)
where data is return array from php. the json encoded string is converted to js object that can now be manipulated easily.
e.g. foo={one:1, two:2, three:3} - gotten after JSON.parse
for (key in foo){ console.log("foo["+ key +"]="+ foo[key]) }
- prints to ur firebug console. voila!
In C#, I would normally use multiple forms of the method:
void GetFooBar(int a) { int defaultBValue; GetFooBar(a, defaultBValue); }
void GetFooBar(int a, int b)
{
// whatever here
}
UPDATE: This mentioned above WAS the way that I did default values with C# 2.0. The projects I'm working on now are using C# 4.0 which now directly supports optional parameters. Here is an example I just used in my own code:
public EDIDocument ApplyEDIEnvelop(EDIVanInfo sender,
EDIVanInfo receiver,
EDIDocumentInfo info,
EDIDocumentType type
= new EDIDocumentType(EDIDocTypes.X12_814),
bool Production = false)
{
// My code is here
}
Passing []
as second argument to dict.fromkeys()
gives a rather useless result – all values in the dictionary will be the same list object.
In Python 2.7 or above, you can use a dicitonary comprehension instead:
data = {k: [] for k in range(2)}
In earlier versions of Python, you can use
data = dict((k, []) for k in range(2))
This variant looks more simple and elegant.
CollectionType typeReference =
TypeFactory.defaultInstance().constructCollectionType(List.class, Dto.class);
List<Dto> resultDto = objectMapper.readValue(content, typeReference);
Swift Version --> Remove the object from your data array before you call
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
print("Deleted")
currentCart.remove(at: indexPath.row) //Remove element from your array
self.tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
It means litraly that, your trying to use the wrong http verb when accessing some http content. A lot of content on webservices you need to use a POST
to consume. I suspect your trying to access the facebook API using the wrong http verb.
Collections.sort(listToSort, String.CASE_INSENSITIVE_ORDER);
I just came up with the same problem since we still use bootstrap 2.3.2.
My solution for this: http://jsfiddle.net/KnuU6/281/
css:
.myCollapse {
display: none;
}
.myCollapse.in {
display: block;
}
javascript:
$("[data-toggle=myCollapse]").click(function( ev ) {
ev.preventDefault();
var target;
if (this.hasAttribute('data-target')) {
target = $(this.getAttribute('data-target'));
} else {
target = $(this.getAttribute('href'));
};
target.toggleClass("in");
});
html:
<table>
<tr><td><a href="#demo" data-toggle="myCollapse">Click me to toggle next row</a></td></tr>
<tr class="collapse" id="#demo"><td>You can collapse and expand me.</td></tr>
</table>
THIS IS NOT AN ANSWER TO THE ORIGINAL QUESTION, IT'S AN ANSWER TO @Teddy's QUESTION IN @Dudi's ANSWER'S COMMENTS
Here's a way to list id's in the active presentation to the immediate window (Ctrl + G) in VBA editor:
Sub ListAllShapes()
Dim curSlide As Slide
Dim curShape As Shape
For Each curSlide In ActivePresentation.Slides
Debug.Print curSlide.SlideID
For Each curShape In curSlide.Shapes
If curShape.TextFrame.HasText Then
Debug.Print curShape.Id
End If
Next curShape
Next curSlide
End Sub
The several answers that purport to show how to do this are all wrong because Java characters are not ASCII characters. Java uses a multibyte encoding of Unicode characters. The Unicode character set is a super set of ASCII. So there can be characters in a Java string that do not belong to ASCII. Such characters do not have an ASCII numeric value, so asking how to get the ASCII numeric value of a Java character is unanswerable.
But why do you want to do this anyway? What are you going to do with the value?
If you want the numeric value so you can convert the Java String to an ASCII string, the real question is "how do I encode a Java String as ASCII". For that, use the object StandardCharsets.US_ASCII
.
If you use numpy
, this is easy:
slice = arr[:2,:2]
or if you want the 0's,
slice = arr[0:2,0:2]
You'll get the same result.
*note that slice
is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".
Another way, if you're working with lists of lists*:
slice = [arr[i][0:2] for i in range(0,2)]
(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)]
would also work.).
What I did here is that I take each desired row 1 at a time (arr[i]
). I then slice the columns I want out of that row and add it to the list that I'm building.
If you naively try: arr[0:2]
You get the first 2 rows which if you then slice again arr[0:2][0:2]
, you're just slicing the first two rows over again.
*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.
Those are all slightly different, and generally have an acceptable usage.
var.
ToString
()
is going to give you the string representation of an object, regardless of what type it is. Use this if var
is not a string already.CStr
(var)
is the VB string cast operator. I'm not a VB guy, so I would suggest avoiding it, but it's not really going to hurt anything. I think it is basically the same as CType
.CType
(var, String)
will convert the given type into a string, using any provided conversion operators.DirectCast
(var, String)
is used to up-cast an object into a string. If you know that an object variable is, in fact, a string, use this. This is the same as (string)var
in C#.TryCast
(as mentioned by @NotMyself) is like DirectCast
, but it will return Nothing
if the variable can't be converted into a string, rather than throwing an exception. This is the same as var as string
in C#. The TryCast
page on MSDN has a good comparison, too.Let's see how we get the params, headers and body in Flask. I'm gonna explain with the help of postman.
The params keys and values are reflected in the API endpoint. for example key1 and key2 in the endpoint : https://127.0.0.1/upload?key1=value1&key2=value2
from flask import Flask, request
app = Flask(__name__)
@app.route('/upload')
def upload():
key_1 = request.args.get('key1')
key_2 = request.args.get('key2')
print(key_1)
#--> value1
print(key_2)
#--> value2
After params, let's now see how to get the headers:
header_1 = request.headers.get('header1')
header_2 = request.headers.get('header2')
print(header_1)
#--> header_value1
print(header_2)
#--> header_value2
Now let's see how to get the body
file_name = request.files['file'].filename
ref_id = request.form['referenceId']
print(ref_id)
#--> WWB9838yb3r47484
so we fetch the uploaded files with request.files and text with request.form
I also have this problem. That is very stupid when i add a namespace the same with System. I try to remove all references, but it is not resolved. I use "global::System.ComponentModel", it is working as well. When i remove my namespace, this problem has been resolved.
string * and string& differ in a couple of ways. First of all, the pointer points to the address location of the data. The reference points to the data. If you had the following function:
int foo(string *param1);
You would have to check in the function declaration to make sure that param1 pointed to a valid location. Comparatively:
int foo(string ¶m1);
Here, it is the caller's responsibility to make sure the pointed to data is valid. You can't pass a "NULL" value, for example, int he second function above.
With regards to your second question, about the method return values being a reference, consider the following three functions:
string &foo();
string *foo();
string foo();
In the first case, you would be returning a reference to the data. If your function declaration looked like this:
string &foo()
{
string localString = "Hello!";
return localString;
}
You would probably get some compiler errors, since you are returning a reference to a string that was initialized in the stack for that function. On the function return, that data location is no longer valid. Typically, you would want to return a reference to a class member or something like that.
The second function above returns a pointer in actual memory, so it would stay the same. You would have to check for NULL-pointers, though.
Finally, in the third case, the data returned would be copied into the return value for the caller. So if your function was like this:
string foo()
{
string localString = "Hello!";
return localString;
}
You'd be okay, since the string "Hello" would be copied into the return value for that function, accessible in the caller's memory space.
In addition to the solution you accepted, you could also implement the special __lt__()
("less than") method on the class. The sort()
method (and the sorted()
function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.
class Foo(object):
def __init__(self, score):
self.score = score
def __lt__(self, other):
return self.score < other.score
l = [Foo(3), Foo(1), Foo(2)]
l.sort()
It seems that you are asking multiple things. To answer them:
You can extract the numbers by catching them in capturing parentheses:
.*(\d+) rofl.*
and using $1
to get the string out (.*
is for "the rest before and after on the same line)
With sed as example, the idea becomes this to replace all strings in a file with only the matching number:
sed -e 's/.*(\d+) rofl.*/$1/g' inputFileName > outputFileName
or:
echo "12 BBQ ,45 rofl, 89 lol" | sed -e 's/.*(\d+) rofl.*/$1/g'
Use sysdate-1 to subtract one day from system date.
select sysdate, sysdate -1 from dual;
Output:
SYSDATE SYSDATE-1
-------- ---------
22-10-13 21-10-13
The object of the exercise is to find the row that contains the information. When we get there, we can easily extract the required information.
$(".use-address").click(function() {
var $item = $(this).closest("tr") // Finds the closest row <tr>
.find(".nr") // Gets a descendent with class="nr"
.text(); // Retrieves the text within <td>
$("#resultas").append($item); // Outputs the answer
});
Now let's focus on some frequently asked questions in such situations.
Using .closest()
:
var $row = $(this).closest("tr");
Using .parent()
:
You can also move up the DOM tree using .parent()
method. This is just an alternative that is sometimes used together with .prev()
and .next()
.
var $row = $(this).parent() // Moves up from <button> to <td>
.parent(); // Moves up from <td> to <tr>
<td>
valuesSo we have our $row
and we would like to output table cell text:
var $row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td"); // Finds all children <td> elements
$.each($tds, function() { // Visits every single <td> element
console.log($(this).text()); // Prints out the text within the <td>
});
<td>
valueSimilar to the previous one, however we can specify the index of the child <td>
element.
var $row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td:nth-child(2)"); // Finds the 2nd <td> element
$.each($tds, function() { // Visits every single <td> element
console.log($(this).text()); // Prints out the text within the <td>
});
.closest()
- get the first element that matches the selector.parent()
- get the parent of each element in the current set of matched elements.parents()
- get the ancestors of each element in the current set of matched elements.children()
- get the children of each element in the set of matched elements.siblings()
- get the siblings of each element in the set of matched elements.find()
- get the descendants of each element in the current set of matched elements.next()
- get the immediately following sibling of each element in the set of matched elements.prev()
- get the immediately preceding sibling of each element in the set of matched elementsTry this:
@echo off
set /p id="Enter ID: "
You can then use %id%
as a parameter to another batch file like jstack %id%
.
For example:
set /P id=Enter id:
jstack %id% > jstack.txt
My experience in this matter tells me , most of these software work good with small projects .
But what about big projects? e.g: Zend Framework 2 and some things like that.
Some of them need browser to run and this is difficult to tell customer "please type http://localhost/
" in your browser address bar !!
I create a simple project to do this : PHPPy
This is not complete way for create stand alone executable file for running php projects but helps you to do this.
I couldn't compile python file with PyInstaller or Py2exe to .exe file , hope you can.
You don't need uniformserver executable files.
The problem is where you are executing:
rankings[kvp.Key] = rankings[kvp.Key] + 4;
You cannot modify the collection you are iterating through in a foreach loop. A foreach loop requires the loop to be immutable during iteration.
Instead, use a standard 'for' loop or create a new loop that is a copy and iterate through that while updating your original.
Import lodash
using
$ npm i --save lodash
var _ = require('lodash');
var objArrayList =
[
{ name: "user1"},
{ name: "user2"},
{ name: "user2"}
];
var Obj = _.find(objArrayList, { name: "user2" });
// Obj ==> { name: "user2"}
There should be the problem, when you generate the <form>
. I bet the variables $name
, $price
are NULL
or empty string when you echo
them into the value
of the <input>
field. Empty input fields are not sent by the browser, so $_POST
will not have their keys.
Anyway, you can check that with isset()
.
Test variables with the following:
if(isset($_POST['key'])) ? $variable=$_POST['key'] : $variable=NULL
You better set it to NULL
, because
NULL value represents a variable with no value.
As purrrminator
says, the answer by elitalon
is not completely right, since your stuff
would be executed even when popping the controller programmatically.
The solution I have found so far is not very nice, but it works for me. Besides what elitalon
said, I also check whether I'm popping programmatically or not:
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if ((self.isMovingFromParentViewController || self.isBeingDismissed)
&& !self.isPoppingProgrammatically) {
// Do your stuff here
}
}
You have to add that property to your controller and set it to YES before popping programmatically:
self.isPoppingProgrammatically = YES;
[self.navigationController popViewControllerAnimated:YES];
Thanks for your help!
Easily can be solved this problem.
Ex:- in Huawei GR3 mobile,
Goto Setting in your mobile -> Storage -> Storage Cleaner
Like this... I used it to read Chinese characters...
Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(filetoimport.Text)
Dim a as String
Do
a = reader.ReadLine
'
' Code here
'
Loop Until a Is Nothing
reader.Close()
I use something like this (you should add code to deal with the various fails):
var response = RunTaskWithTimeout<ReturnType>(
(Func<ReturnType>)delegate { return SomeMethod(someInput); }, 30);
/// <summary>
/// Generic method to run a task on a background thread with a specific timeout, if the task fails,
/// notifies a user
/// </summary>
/// <typeparam name="T">Return type of function</typeparam>
/// <param name="TaskAction">Function delegate for task to perform</param>
/// <param name="TimeoutSeconds">Time to allow before task times out</param>
/// <returns></returns>
private T RunTaskWithTimeout<T>(Func<T> TaskAction, int TimeoutSeconds)
{
Task<T> backgroundTask;
try
{
backgroundTask = Task.Factory.StartNew(TaskAction);
backgroundTask.Wait(new TimeSpan(0, 0, TimeoutSeconds));
}
catch (AggregateException ex)
{
// task failed
var failMessage = ex.Flatten().InnerException.Message);
return default(T);
}
catch (Exception ex)
{
// task failed
var failMessage = ex.Message;
return default(T);
}
if (!backgroundTask.IsCompleted)
{
// task timed out
return default(T);
}
// task succeeded
return backgroundTask.Result;
}
Draw the image on the background of a JPanel that is added to the frame. Use a layout manager to normally add your buttons and other components to the panel. If you add other child panels, perhaps you want to set child.setOpaque(false).
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.URL;
public class BackgroundImageApp {
private JFrame frame;
private BackgroundImageApp create() {
frame = createFrame();
frame.getContentPane().add(createContent());
return this;
}
private JFrame createFrame() {
JFrame frame = new JFrame(getClass().getName());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
return frame;
}
private void show() {
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private Component createContent() {
final Image image = requestImage();
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
};
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
for (String label : new String[]{"One", "Dois", "Drei", "Quatro", "Peace"}) {
JButton button = new JButton(label);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(Box.createRigidArea(new Dimension(15, 15)));
panel.add(button);
}
panel.setPreferredSize(new Dimension(500, 500));
return panel;
}
private Image requestImage() {
Image image = null;
try {
image = ImageIO.read(new URL("http://www.johnlennon.com/wp-content/themes/jl/images/home-gallery/2.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new BackgroundImageApp().create().show();
}
});
}
}
The simplest syntax to redirect both is:
command &> logfile
If you want to append to the file instead of overwrite:
command &>> logfile
Add cellpadding and cellspacing to solve it. Edit: Also removed double pixel border.
<style>
td
{border-left:1px solid black;
border-top:1px solid black;}
table
{border-right:1px solid black;
border-bottom:1px solid black;}
</style>
<html>
<body>
<table cellpadding="0" cellspacing="0">
<tr>
<td width="350" >
Foo
</td>
<td width="80" >
Foo1
</td>
<td width="65" >
Foo2
</td>
</tr>
<tr>
<td>
Bar1
</td>
<td>
Bar2
</td>
<td>
Bar3
</td>
</tr>
<tr >
<td>
Bar1
</td>
<td>
Bar2
</td>
<td>
Bar3
</td>
</tr>
</table>
</body>
</html>
As @kirbyfan64sos notes in a comment, /home
is NOT your home directory (a.k.a. home folder):
The fact that /home
is an absolute, literal path that has no user-specific component provides a clue.
While /home
happens to be the parent directory of all user-specific home directories on Linux-based systems, you shouldn't even rely on that, given that this differs across platforms: for instance, the equivalent directory on macOS is /Users
.
What all Unix platforms DO have in common are the following ways to navigate to / refer to your home directory:
cd
with NO argument changes to your home dir., i.e., makes your home dir. the working directory.
cd # changes to home dir; e.g., '/home/jdoe'
~
by itself / unquoted ~/
at the start of a path string represents your home dir. / a path starting at your home dir.; this is referred to as tilde expansion (see man bash
)
echo ~ # outputs, e.g., '/home/jdoe'
$HOME
- as part of either unquoted or preferably a double-quoted string - refers to your home dir. HOME
is a predefined, user-specific environment variable:
cd "$HOME/tmp" # changes to your personal folder for temp. files
Thus, to create the desired folder, you could use:
mkdir "$HOME/bin" # same as: mkdir ~/bin
Note that most locations outside your home dir. require superuser (root user) privileges in order to create files or directories - that's why you ran into the Permission denied
error.
File file = new File("src/test/resources/validation.txt");
DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length() , file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
You need the
fileItem.getOutputStream();
because it will throw NPE otherwise.
Xcode Workspace vs Project
- What is the difference between the two of them?
Workspace
is a set of projects
- What are they responsible for?
Workspace
is responsible for dependencies between projects.
Project
is responsible for the source code.
- Which one of them should I work with when I'm developing my Apps in team/alone?
You choice should depends on a type of your project. For example if your project relies on CocoaPods dependency manager it creates a workspace.
- Is there anything else I should be aware of in matter of these two files?
A competitor of workspace is cross-project references
[About]
you can also use jquery for this
var phoneNumber = 8882070980;
var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
if (filter.test(phoneNumber)) {
if(phoneNumber.length==10){
var validate = true;
} else {
alert('Please put 10 digit mobile number');
var validate = false;
}
}
else {
alert('Not a valid number');
var validate = false;
}
if(validate){
//number is equal to 10 digit or number is not string
enter code here...
}
Use SimpleDateFormat
to format any Date
object you want:
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
Using a new Date()
as shown above will format the current time.
xsd.exe as mentioned by Marc Gravell. The fastest way to get up and running IMO.
Or if you need more flexibility/options :
xsd2code VS add-in (Codeplex)
This is a way to create tables dynamically using T-SQL stored procedures:
declare @cmd nvarchar(1000), @MyTableName nvarchar(100);
set @MyTableName = 'CustomerDetails';
set @cmd = 'CREATE TABLE dbo.' + quotename(@MyTableName, '[') + '(ColumnName1 int not null,ColumnName2 int not null);';
Execute it as:
exec(@cmd);
Your script is blocked from executing due to the execution policy.
You need to run PowerShell as administrator and set it on the client PC to Unrestricted. You can do that by calling Invoke with:
Set-ExecutionPolicy Unrestricted
Follow this: Open your config file
vi /etc/nginx/conf.d/default.conf
Change port number on which you are listening;
listen 81;
server_name localhost;
Add a rule to iptables
vi /etc/sysconfig/iptables
-A INPUT -m state --state NEW -m tcp -p tcp --dport 81 -j ACCEPT
Restart IPtables
service iptables restart;
Restart the nginx server
service nginx restart
Access yr nginx server files on port 81
The solution by tremendows worked well for me. However , file was not getting saved in Internet Explorer 10+ also. The below code worked for me for IE browser.
var file = new Blob(([data]), { type: 'application/pdf' });
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(file, 'fileName.pdf');
}
Some cases where I have found it useful:
try{ // do stuff... fail("Exception not thrown"); }catch(Exception e){ assertTrue(e.hasSomeFlag()); }
Note:
Since JUnit4, there is a more elegant way to test that an exception is being thrown:
Use the annotation @Test(expected=IndexOutOfBoundsException.class)
However, this won't work if you also want to inspect the exception, then you still need fail()
.
The canonical T-SQL (SqlServer) answer is to use a DELETE
with JOIN
as such
DELETE o
FROM Orders o
INNER JOIN Customers c
ON o.CustomerId = c.CustomerId
WHERE c.FirstName = 'sklivvz'
This will delete all orders which have a customer with first name Sklivvz.
Your regex says the following:
/^ - if the line starts with
( - start a capture group
Clinton| - "Clinton"
| - or
[^Bush] - Any single character except "B", "u", "s" or "h"
| - or
Reagan) - "Reagan". End capture group.
/i - Make matches case-insensitive
So, in other words, your middle part of the regex is screwing you up. As it is a "catch-all" kind of group, it will allow any line that does not begin with any of the upper or lower case letters in "Bush". For example, these lines would match your regex:
Our president, George Bush
In the news today, pigs can fly
012-3123 33
You either make a negative look-ahead, as suggested earlier, or you simply make two regexes:
if( ($string =~ m/^(Clinton|Reagan)/i) and
($string !~ m/^Bush/i) ) {
print "$string\n";
}
As mirod has pointed out in the comments, the second check is quite unnecessary when using the caret (^
) to match only beginning of lines, as lines that begin with "Clinton" or "Reagan" could never begin with "Bush".
However, it would be valid without the carets.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var video = document.getElementById('video');
video.addEventListener('play', function () {
var $this = this; //cache
(function loop() {
if (!$this.paused && !$this.ended) {
ctx.drawImage($this, 0, 0);
setTimeout(loop, 1000 / 30); // drawing at 30fps
}
})();
}, 0);
I guess the above code is self Explanatory, If not drop a comment below, I will try to explain the above few lines of code
Edit :
here's an online example, just for you :)
Demo
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
var video = document.getElementById('video');_x000D_
_x000D_
// set canvas size = video size when known_x000D_
video.addEventListener('loadedmetadata', function() {_x000D_
canvas.width = video.videoWidth;_x000D_
canvas.height = video.videoHeight;_x000D_
});_x000D_
_x000D_
video.addEventListener('play', function() {_x000D_
var $this = this; //cache_x000D_
(function loop() {_x000D_
if (!$this.paused && !$this.ended) {_x000D_
ctx.drawImage($this, 0, 0);_x000D_
setTimeout(loop, 1000 / 30); // drawing at 30fps_x000D_
}_x000D_
})();_x000D_
}, 0);
_x000D_
<div id="theater">_x000D_
<video id="video" src="http://upload.wikimedia.org/wikipedia/commons/7/79/Big_Buck_Bunny_small.ogv" controls="false"></video>_x000D_
<canvas id="canvas"></canvas>_x000D_
<label>_x000D_
<br />Try to play me :)</label>_x000D_
<br />_x000D_
</div>
_x000D_
I assume that the text "username1" is just a placeholder for what will eventually be an actual username. Assuming that,
span
tag server-side, before sending it to the client, and then just working with the span tags.You can change from the "build.gradle" file the line:
compileSdkVersion 18
to the sdk that you want to be used.
The best practice is definitely to avoid loops or recursions in Matlab.
Between sum(A(:))
and sum(sum(A))
.
In my experience, arrays in Matlab seems to be stored in a continuous block in memory as stacked column vectors. So the shape of A does not quite matter in sum()
. (One can test reshape()
and check if reshaping is fast in Matlab. If it is, then we have a reason to believe that the shape of an array is not directly related to the way the data is stored and manipulated.)
As such, there is no reason sum(sum(A))
should be faster. It would be slower if Matlab actually creates a row vector recording the sum of each column of A first and then sum over the columns. But I think sum(sum(A))
is very wide-spread amongst users. It is likely that they hard-code sum(sum(A))
to be a single loop, the same to sum(A(:))
.
Below I offer some testing results. In each test, A=rand(size) and size is specified in the displayed texts.
First is using tic toc.
Size 100x100
sum(A(:))
Elapsed time is 0.000025 seconds.
sum(sum(A))
Elapsed time is 0.000018 seconds.
Size 10000x1
sum(A(:))
Elapsed time is 0.000014 seconds.
sum(A)
Elapsed time is 0.000013 seconds.
Size 1000x1000
sum(A(:))
Elapsed time is 0.001641 seconds.
sum(A)
Elapsed time is 0.001561 seconds.
Size 1000000
sum(A(:))
Elapsed time is 0.002439 seconds.
sum(A)
Elapsed time is 0.001697 seconds.
Size 10000x10000
sum(A(:))
Elapsed time is 0.148504 seconds.
sum(A)
Elapsed time is 0.155160 seconds.
Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.
Error in test27 (line 70)
A=rand(100000000,1);
Below is using cputime
Size 100x100
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 10000x1
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 1000x1000
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 1000000
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.312
The cputime for sum(sum(A)) in seconds is
0.312
Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.
Error in test27_2 (line 70)
A=rand(100000000,1);
In my experience, both timers are only meaningful up to .1s. So if you have similar experience with Matlab timers, none of the tests can discern sum(A(:))
and sum(sum(A))
.
I tried the largest size allowed on my computer a few more times.
Size 10000x10000
sum(A(:))
Elapsed time is 0.151256 seconds.
sum(A)
Elapsed time is 0.143937 seconds.
Size 10000x10000
sum(A(:))
Elapsed time is 0.149802 seconds.
sum(A)
Elapsed time is 0.145227 seconds.
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.2808
The cputime for sum(sum(A)) in seconds is
0.312
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.312
The cputime for sum(sum(A)) in seconds is
0.312
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.312
The cputime for sum(sum(A)) in seconds is
0.312
They seem equivalent.
Either one is good. But sum(sum(A))
requires that you know the dimension of your array is 2.
You can use this PHP library available on packagist:
https://github.com/CoreProc/gcm-php
After installing it you can do this:
$gcmClient = new GcmClient('your-gcm-api-key-here');
$message = new Message($gcmClient);
$message->addRegistrationId('xxxxxxxxxx');
$message->setData([
'title' => 'Sample Push Notification',
'message' => 'This is a test push notification using Google Cloud Messaging'
]);
try {
$response = $message->send();
// The send() method returns a Response object
print_r($response);
} catch (Exception $exception) {
echo 'uh-oh: ' . $exception->getMessage();
}
I was looking for this, but my example was to take a number, such as 4.2769 and drop it in a span as just 4.3. Not exactly the same, but if this helps:
Model.Statistics.AverageReview <= it's just a double from the model
Then:
@Model.Statistics.AverageReview.ToString("n1") <=gives me 4.3
@Model.Statistics.AverageReview.ToString("n2") <=gives me 4.28
etc...
Click is an event. In your code behind, you need to have a corresponding event handler to whatever you have in the XAML. In this case, you would need to have the following:
private void Command(object sender, RoutedEventArgs e)
{
}
Commands are different. If you need to wire up a command, you'd use the Commmand property of the button and you would either use some pre-built Commands or wire up your own via the CommandManager class (I think).