Try:
$data = file_get_contents ("file.json");
$json = json_decode($data, true);
foreach ($json as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br/>';
} else {
foreach ($value as $key => $val) {
echo $key . '=>' . $val . '<br/>';
}
}
}
git config core.editor "\"C:\Program Files (x86)\Notepad++\notepad++.exe\""
One potential downside with setting the field value to "" (empty string) in the constructor is if the field is an optional field and is left unedited. Unless you do some massaging before posting your form, the field will be persisted to your data storage as an empty string instead of NULL.
This alternative will avoid empty strings:
constructor(props) {
super(props);
this.state = {
name: null
}
}
...
<input name="name" type="text" value={this.state.name || ''}/>
There is no built-in functionality for this. This count is in its whole user-specific. Maintain a counter or whatever.
Disabling "Google App Engine Support" in pycharm preferences fixed this issue for me.
I wrote a very tiny plugin called "once" which do that:
$.fn.once = function(a, b) {
return this.each(function() {
$(this).off(a).on(a,b);
});
};
And simply:
$(element).once('click', function(){
});
Null check in an enhanced for loop
public static <T> Iterable<T> emptyIfNull(Iterable<T> iterable) {
return iterable == null ? Collections.<T>emptyList() : iterable;
}
Then use:
for (Object object : emptyIfNull(someList)) { ... }
try something like this FIDDLE
try
{
navigator.device.capture.captureImage(function(mediaFiles) {
console.log("works");
});
}
catch(err)
{
alert('hi');
$("#captureImage").prop('checked', false);
}
If the primary key happens to be an auto_increment value, you have to remove the auto increment, then drop the primary key then re-add the auto-increment
ALTER TABLE `xx`
MODIFY `auto_increment_field` INT,
DROP PRIMARY KEY,
ADD PRIMARY KEY (new_primary_key);
then add back the auto increment
ALTER TABLE `xx` ADD INDEX `auto_increment_field` (auto_increment_field),
MODIFY `auto_increment_field` int auto_increment;
then set auto increment back to previous value
ALTER TABLE `xx` AUTO_INCREMENT = 5;
Position the cursor inside the class, then press ALT + Ins and select Getters and Setters
from the contextual menu.
Just go to the SQL Server Management Studio -> Tools -> Options -> Designer; and Uncheck the option "prevent saving changes that require table re-creation".
I have met with the exact same problem.
And it turns out that the configuration file generated by gradle asks for java1.7.
While my system has java1.8 installed.
After modifying the compiler compliance level to 1.8. All things are working as expected.
This is my JavaScript implementation of Algorithm P (Polar method for normal deviates) from Section 3.4.1 of Donald Knuth's book The Art of Computer Programming:
function normal_random(mean,stddev)
{
var V1
var V2
var S
do{
var U1 = Math.random() // return uniform distributed in [0,1[
var U2 = Math.random()
V1 = 2*U1-1
V2 = 2*U2-1
S = V1*V1+V2*V2
}while(S >= 1)
if(S===0) return 0
return mean+stddev*(V1*Math.sqrt(-2*Math.log(S)/S))
}
// How to send value using intent from one class to another class
// class A(which will send data)
Intent theIntent = new Intent(this, B.class);
theIntent.putExtra("name", john);
startActivity(theIntent);
// How to get these values in another class
// Class B
Intent i= getIntent();
i.getStringExtra("name");
// if you log here i than you will get the value of i i.e. john
From what I can tell, per the documentation here: http://jqueryui.com/demos/tabs/#event-select, it seems as though you're not quite initializing it right. The demos state that you need a main wrapped <div>
element, with a <ul>
or possibly <ol>
element representing the tabs, and then an element for each tab page (presumable a <div>
or <p>
, possibly a <section>
if we're using HTML5). Then you call $().tabs() on the main <div>
, not the <ul>
element.
After that, you can bind to the tabsselect event no problem. Check out this fiddle for basic, basic example:
It could be that Pytest is not reading the package as a Python module while Python is (likely due to path issues). Try changing the directory of the pytest script or adding the module explicitly to your PYTHONPATH.
Or it could be that you have two versions of Python installed on your machine. Check your Python source for pytest and for the python shell that you run. If they are different (i.e. Python 2 vs 3), use source activate
to make sure that you are running the pytest installed for the same python that the module is installed in.
To add multiple files use below code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.fileUpload{
width:255px;
font-size:11px;
color:#000000;
border:solid;
border-width:1px;
border-color:#7f9db9;
height:17px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="fileUploadarea"><asp:FileUpload ID="fuPuzzleImage" runat="server" CssClass="fileUpload" /><br /></div><br />
<div><input style="display:block;" id="btnAddMoreFiles" type="button" value="Add more images" onclick="AddMoreImages();" /><br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload" />
</div>
</div>
<script language="javascript" type="text/javascript">
function AddMoreImages() {
if (!document.getElementById && !document.createElement)
return false;
var fileUploadarea = document.getElementById("fileUploadarea");
if (!fileUploadarea)
return false;
var newLine = document.createElement("br");
fileUploadarea.appendChild(newLine);
var newFile = document.createElement("input");
newFile.type = "file";
newFile.setAttribute("class", "fileUpload");
if (!AddMoreImages.lastAssignedId)
AddMoreImages.lastAssignedId = 100;
newFile.setAttribute("id", "FileUpload" + AddMoreImages.lastAssignedId);
newFile.setAttribute("name", "FileUpload" + AddMoreImages.lastAssignedId);
var div = document.createElement("div");
div.appendChild(newFile);
div.setAttribute("id", "div" + AddMoreImages.lastAssignedId);
fileUploadarea.appendChild(div);
AddMoreImages.lastAssignedId++;
}
</script>
</form>
</body>
</html>
Server side code:
try
{
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
hpf.SaveAs(Server.MapPath("~/uploads/") +System.IO.Path.GetFileName(hpf.FileName);
}
}
}
catch (Exception)
{
throw;
}
It is a unicode char \u003C = <
Oracle specific, and doesn't rely on pre-existing large tables or complicated system views over data dictionary objects.
SELECT c1 from dual
MODEL DIMENSION BY (1 as rn) MEASURES (sysdate as c1)
RULES ITERATE (365)
(c1[ITERATION_NUMBER]=SYSDATE-ITERATION_NUMBER)
order by 1
This will update the new characters in the file to be unix style. More info on "Newline Representation" in Emacs can be found here:
http://ergoemacs.org/emacs/emacs_line_ending_char.html
Note: The above steps could be made into an Emacs script if one preferred to execute this from the command line.
It's 10 digits, so pretend it's a phone number (assuming you're in the US). 214-748-3647. I don't recommend calling it.
The CSS uses only the data in the DOM tree, which has little to do with how the renderer decides what to do with elements with missing attributes.
So either let the CSS reflect the HTML
input:not([type]), input[type="text"]
{
background:red;
}
or make the HTML explicit.
<input name='t1' type='text'/> /* Is Not Red */
If it didn't do that, you'd never be able to distinguish between
element { ...properties... }
and
element[attr] { ...properties... }
because all attributes would always be defined on all elements. (For example, table
always has a border
attribute, with 0
for a default.)
Let say you have string contains anchor tag and you want to remove this tag with content then this method will helpful.
$srting = '<a title="" href="/index.html"><b>Some Text</b></a>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.';
echo strip_tags_content($srting);
function strip_tags_content($text) {
return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
}
Output:
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
It is very simple, just add a property:
public string Value {
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
This solution worked for me in swift 4:
let VCCount = self.navigationController!.viewControllers.count
self.navigationController?.viewControllers.removeSubrange(Range(VCCount-3..<VCCount - 1))
your current view controller index in stack is:
self.navigationController!.viewControllers.count - 1
This is just another workaround.
And you are good to go.
Here you go:
USE information_schema;
SELECT *
FROM
KEY_COLUMN_USAGE
WHERE
REFERENCED_TABLE_NAME = 'X'
AND REFERENCED_COLUMN_NAME = 'X_id';
If you have multiple databases with similar tables/column names you may also wish to limit your query to a particular database:
SELECT *
FROM
KEY_COLUMN_USAGE
WHERE
REFERENCED_TABLE_NAME = 'X'
AND REFERENCED_COLUMN_NAME = 'X_id'
AND TABLE_SCHEMA = 'your_database_name';
A cleaner alternative of putting your config file into a subfolder of src/main/resources would be to enhance your classpath locations. This is extremely easy to do with Maven.
For instance, place your property file in a new folder src/main/config, and add the following to your pom:
<build>
<resources>
<resource>
<directory>src/main/config</directory>
</resource>
</resources>
</build>
From now, every files files under src/main/config is considered as part of your classpath (note that you can exclude some of them from the final jar if needed: just add in the build section:
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<excludes>
<exclude>my-config.properties</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
so that my-config.properties can be found in your classpath when you run your app from your IDE, but will remain external from your jar in your final distribution).
If you do not want to include the brackets in the match, here's the regex: (?<=\[).*?(?=\])
The .
matches any character except for line terminators. The ?=
is a positive lookahead. A positive lookahead finds a string when a certain string comes after it. The ?<=
is a positive lookbehind. A positive lookbehind finds a string when a certain string precedes it. To quote this,
Look ahead positive (?=)
Find expression A where expression B follows:
A(?=B)
Look behind positive (?<=)
Find expression A where expression B precedes:
(?<=B)A
If your regex engine does not support lookaheads and lookbehinds, then you can use the regex \[(.*?)\]
to capture the innards of the brackets in a group and then you can manipulate the group as necessary.
The parentheses capture the characters in a group. The .*?
gets all of the characters between the brackets (except for line terminators, unless you have the s
flag enabled) in a way that is not greedy.
My answer won't probably be useful to the writer of this question (I am 8 months late so not the right timing I guess) but I think it will probably be useful for many other developers that might come across this answer.
Today, I just released (in the name of my company) an HTML to POJO complete framework that you can use to map HTML to any POJO class with simply some annotations. The library itself is quite handy and features many other things all the while being very pluggable. You can have a look to it right here : https://github.com/whimtrip/jwht-htmltopojo
Imagine we need to parse the following html page :
<html>
<head>
<title>A Simple HTML Document</title>
</head>
<body>
<div class="restaurant">
<h1>A la bonne Franquette</h1>
<p>French cuisine restaurant for gourmet of fellow french people</p>
<div class="location">
<p>in <span>London</span></p>
</div>
<p>Restaurant n*18,190. Ranked 113 out of 1,550 restaurants</p>
<div class="meals">
<div class="meal">
<p>Veal Cutlet</p>
<p rating-color="green">4.5/5 stars</p>
<p>Chef Mr. Frenchie</p>
</div>
<div class="meal">
<p>Ratatouille</p>
<p rating-color="orange">3.6/5 stars</p>
<p>Chef Mr. Frenchie and Mme. French-Cuisine</p>
</div>
</div>
</div>
</body>
</html>
Let's create the POJOs we want to map it to :
public class Restaurant {
@Selector( value = "div.restaurant > h1")
private String name;
@Selector( value = "div.restaurant > p:nth-child(2)")
private String description;
@Selector( value = "div.restaurant > div:nth-child(3) > p > span")
private String location;
@Selector(
value = "div.restaurant > p:nth-child(4)"
format = "^Restaurant n\*([0-9,]+). Ranked ([0-9,]+) out of ([0-9,]+) restaurants$",
indexForRegexPattern = 1,
useDeserializer = true,
deserializer = ReplacerDeserializer.class,
preConvert = true,
postConvert = false
)
// so that the number becomes a valid number as they are shown in this format : 18,190
@ReplaceWith(value = ",", with = "")
private Long id;
@Selector(
value = "div.restaurant > p:nth-child(4)"
format = "^Restaurant n\*([0-9,]+). Ranked ([0-9,]+) out of ([0-9,]+) restaurants$",
// This time, we want the second regex group and not the first one anymore
indexForRegexPattern = 2,
useDeserializer = true,
deserializer = ReplacerDeserializer.class,
preConvert = true,
postConvert = false
)
// so that the number becomes a valid number as they are shown in this format : 18,190
@ReplaceWith(value = ",", with = "")
private Integer rank;
@Selector(value = ".meal")
private List<Meal> meals;
// getters and setters
}
And now the Meal
class as well :
public class Meal {
@Selector(value = "p:nth-child(1)")
private String name;
@Selector(
value = "p:nth-child(2)",
format = "^([0-9.]+)\/5 stars$",
indexForRegexPattern = 1
)
private Float stars;
@Selector(
value = "p:nth-child(2)",
// rating-color custom attribute can be used as well
attr = "rating-color"
)
private String ratingColor;
@Selector(
value = "p:nth-child(3)"
)
private String chefs;
// getters and setters.
}
We provided some more explanations on the above code on our github page.
For the moment, let's see how to scrap this.
private static final String MY_HTML_FILE = "my-html-file.html";
public static void main(String[] args) {
HtmlToPojoEngine htmlToPojoEngine = HtmlToPojoEngine.create();
HtmlAdapter<Restaurant> adapter = htmlToPojoEngine.adapter(Restaurant.class);
// If they were several restaurants in the same page,
// you would need to create a parent POJO containing
// a list of Restaurants as shown with the meals here
Restaurant restaurant = adapter.fromHtml(getHtmlBody());
// That's it, do some magic now!
}
private static String getHtmlBody() throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(MY_HTML_FILE));
return new String(encoded, Charset.forName("UTF-8"));
}
Another short example can be found here
Hope this will help someone out there!
I can't help but notice that most answers here are implementing a Binary Search Tree. Binary Search Tree != Binary Tree.
A Binary Search Tree has a very specific property: for any node X, X's key is larger than the key of any descendent of its left child, and smaller than the key of any descendant of its right child.
A Binary Tree imposes no such restriction. A Binary Tree is simply a data structure with a 'key' element, and two children, say 'left' and 'right'.
A Tree is an even more general case of a Binary Tree where each node can have an arbitrary number of children. Typically, each node has a 'children' element which is of type list/array.
Now, to answer the OP's question, I am including a full implementation of a Binary Tree in Python. The underlying data structure storing each BinaryTreeNode is a dictionary, given it offers optimal O(1) lookups. I've also implemented depth-first and breadth-first traversals. These are very common operations performed on trees.
from collections import deque
class BinaryTreeNode:
def __init__(self, key, left=None, right=None):
self.key = key
self.left = left
self.right = right
def __repr__(self):
return "%s l: (%s) r: (%s)" % (self.key, self.left, self.right)
def __eq__(self, other):
if self.key == other.key and \
self.right == other.right and \
self.left == other.left:
return True
else:
return False
class BinaryTree:
def __init__(self, root_key=None):
# maps from BinaryTreeNode key to BinaryTreeNode instance.
# Thus, BinaryTreeNode keys must be unique.
self.nodes = {}
if root_key is not None:
# create a root BinaryTreeNode
self.root = BinaryTreeNode(root_key)
self.nodes[root_key] = self.root
def add(self, key, left_key=None, right_key=None):
if key not in self.nodes:
# BinaryTreeNode with given key does not exist, create it
self.nodes[key] = BinaryTreeNode(key)
# invariant: self.nodes[key] exists
# handle left child
if left_key is None:
self.nodes[key].left = None
else:
if left_key not in self.nodes:
self.nodes[left_key] = BinaryTreeNode(left_key)
# invariant: self.nodes[left_key] exists
self.nodes[key].left = self.nodes[left_key]
# handle right child
if right_key == None:
self.nodes[key].right = None
else:
if right_key not in self.nodes:
self.nodes[right_key] = BinaryTreeNode(right_key)
# invariant: self.nodes[right_key] exists
self.nodes[key].right = self.nodes[right_key]
def remove(self, key):
if key not in self.nodes:
raise ValueError('%s not in tree' % key)
# remove key from the list of nodes
del self.nodes[key]
# if node removed is left/right child, update parent node
for k in self.nodes:
if self.nodes[k].left and self.nodes[k].left.key == key:
self.nodes[k].left = None
if self.nodes[k].right and self.nodes[k].right.key == key:
self.nodes[k].right = None
return True
def _height(self, node):
if node is None:
return 0
else:
return 1 + max(self._height(node.left), self._height(node.right))
def height(self):
return self._height(self.root)
def size(self):
return len(self.nodes)
def __repr__(self):
return str(self.traverse_inorder(self.root))
def bfs(self, node):
if not node or node not in self.nodes:
return
reachable = []
q = deque()
# add starting node to queue
q.append(node)
while len(q):
visit = q.popleft()
# add currently visited BinaryTreeNode to list
reachable.append(visit)
# add left/right children as needed
if visit.left:
q.append(visit.left)
if visit.right:
q.append(visit.right)
return reachable
# visit left child, root, then right child
def traverse_inorder(self, node, reachable=None):
if not node or node.key not in self.nodes:
return
if reachable is None:
reachable = []
self.traverse_inorder(node.left, reachable)
reachable.append(node.key)
self.traverse_inorder(node.right, reachable)
return reachable
# visit left and right children, then root
# root of tree is always last to be visited
def traverse_postorder(self, node, reachable=None):
if not node or node.key not in self.nodes:
return
if reachable is None:
reachable = []
self.traverse_postorder(node.left, reachable)
self.traverse_postorder(node.right, reachable)
reachable.append(node.key)
return reachable
# visit root, left, then right children
# root is always visited first
def traverse_preorder(self, node, reachable=None):
if not node or node.key not in self.nodes:
return
if reachable is None:
reachable = []
reachable.append(node.key)
self.traverse_preorder(node.left, reachable)
self.traverse_preorder(node.right, reachable)
return reachable
Here's one solution. Of course, this function doesn't need to load into a "window.params" option -- that can be customized.
window.params = function(){
var params = {};
var param_array = window.location.href.split('?')[1].split('&');
for(var i in param_array){
x = param_array[i].split('=');
params[x[0]] = x[1];
}
return params;
}();
Example API call on http://www.mints.com/myurl.html?name=something&goal=true:
if(window.params.name == 'something') doStuff();
else if( window.params.goal == 'true') shoutGOOOOOAAALLL();
"The $.browser property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery."
Laravel 4+ offers you these methods: whereDay()
, whereMonth()
, whereYear()
(#3946) and whereDate()
(#6879).
They do the SQL DATE()
work for you, and manage the differences of SQLite.
Your result can be achieved as so:
->whereDate('date', '<=', '2014-07-10')
For more examples, see first message of #3946 and this Laravel Daily article.
Update: Though the above method is convenient, as noted by Arth it is inefficient on large datasets, because the DATE()
SQL function has to be applied on each record, thus discarding the possible index.
Here are some ways to make the comparison (but please read notes below):
->where('date', '<=', '2014-07-10 23:59:59')
->where('date', '<', '2014-07-11')
// '2014-07-11'
$dayAfter = (new DateTime('2014-07-10'))->modify('+1 day')->format('Y-m-d');
->where('date', '<', $dayAfter)
Notes:
The main difference is that ChildA.__init__
will unconditionally call Base.__init__
whereas ChildB.__init__
will call __init__
in whatever class happens to be ChildB
ancestor in self
's line of ancestors
(which may differ from what you expect).
If you add a ClassC
that uses multiple inheritance:
class Mixin(Base):
def __init__(self):
print "Mixin stuff"
super(Mixin, self).__init__()
class ChildC(ChildB, Mixin): # Mixin is now between ChildB and Base
pass
ChildC()
help(ChildC) # shows that the Method Resolution Order is ChildC->ChildB->Mixin->Base
then Base
is no longer the parent of ChildB
for ChildC
instances. Now super(ChildB, self)
will point to Mixin
if self
is a ChildC
instance.
You have inserted Mixin
in between ChildB
and Base
. And you can take advantage of it with super()
So if you are designed your classes so that they can be used in a Cooperative Multiple Inheritance scenario, you use super
because you don't really know who is going to be the ancestor at runtime.
The super considered super post and pycon 2015 accompanying video explain this pretty well.
There are many ways you can import Text file to the current sheet. Here are three (including the method that you are using above)
Cells.Copy
Using a QueryTable
Here is a simple macro that I recorded. Please amend it to suit your needs.
Sub Sample()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Sample.txt", Destination:=Range("$A$1") _
)
.Name = "Sample"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Open the text file in memory
Sub Sample()
Dim MyData As String, strData() As String
Open "C:\Sample.txt" For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, vbCrLf)
End Sub
Once you have the data in the array you can export it to the current sheet.
Using the method that you are already using
Sub Sample()
Dim wbI As Workbook, wbO As Workbook
Dim wsI As Worksheet
Set wbI = ThisWorkbook
Set wsI = wbI.Sheets("Sheet1") '<~~ Sheet where you want to import
Set wbO = Workbooks.Open("C:\Sample.txt")
wbO.Sheets(1).Cells.Copy wsI.Cells
wbO.Close SaveChanges:=False
End Sub
FOLLOWUP
You can use the Application.GetOpenFilename
to choose the relevant file. For example...
Sub Sample()
Dim Ret
Ret = Application.GetOpenFilename("Prn Files (*.prn), *.prn")
If Ret <> False Then
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & Ret, Destination:=Range("$A$1"))
'~~> Rest of the code
End With
End If
End Sub
Code for A Breadth First Search to make sure both nodes are in the tree. Only then move forward with the LCA search. Please comment if you have any suggestions to improve. I think we can probably mark them visited and restart the search at a certain point where we left off to improve for the second node (if it isn't found VISITED)
public class searchTree {
static boolean v1=false,v2=false;
public static boolean bfs(Treenode root, int value){
if(root==null){
return false;
}
Queue<Treenode> q1 = new LinkedList<Treenode>();
q1.add(root);
while(!q1.isEmpty())
{
Treenode temp = q1.peek();
if(temp!=null) {
q1.remove();
if (temp.value == value) return true;
if (temp.left != null) q1.add(temp.left);
if (temp.right != null) q1.add(temp.right);
}
}
return false;
}
public static Treenode lcaHelper(Treenode head, int x,int y){
if(head==null){
return null;
}
if(head.value == x || head.value ==y){
if (head.value == y){
v2 = true;
return head;
}
else {
v1 = true;
return head;
}
}
Treenode left = lcaHelper(head.left, x, y);
Treenode right = lcaHelper(head.right,x,y);
if(left!=null && right!=null){
return head;
}
return (left!=null) ? left:right;
}
public static int lca(Treenode head, int h1, int h2) {
v1 = bfs(head,h1);
v2 = bfs(head,h2);
if(v1 && v2){
Treenode lca = lcaHelper(head,h1,h2);
return lca.value;
}
return -1;
}
}
A quick google indicates that pwdencrypt() is not deterministic, and your statement select pwdencrypt('AAAA') returns a different value on my installation!
See also this article http://www.theregister.co.uk/2002/07/08/cracking_ms_sql_server_passwords/
do like this
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//codes..,.,,
Uri sound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(sound);
}
The second parameter of window.open() is a string representing the name of the target window.
Set it to: "_self".
<a href="javascript:q=(document.location.href);void(open('http://example.com/submit.php?url='+escape(q),'_self','resizable,location,menubar,toolbar,scrollbars,status'));">click here</a>
Sidenote:
The following question gives an overview of an arguably better way to bind event handlers to HTML links.
Use the DataGridView.ReadOnly
property
The code in the MSDN example illustrates the use of this property in a DataGridView
control intended primarily for display. In this example, the visual appearance of the control is customized in several ways and the control is configured for limited interactivity.
Observe these settings in the sample code:
// Set property values appropriate for read-only
// display and limited interactivity
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToOrderColumns = true;
dataGridView1.ReadOnly = true;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.MultiSelect = false;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
dataGridView1.AllowUserToResizeColumns = false;
dataGridView1.ColumnHeadersHeightSizeMode =
DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
dataGridView1.AllowUserToResizeRows = false;
dataGridView1.RowHeadersWidthSizeMode =
DataGridViewRowHeadersWidthSizeMode.DisableResizing;
It's !=
without type coercion. See the MDN documentation for comparison operators.
Also see this StackOverflow answer, which includes a quote from "JavaScript: The Good Parts" about the problems with ==
and !=
. (null == undefined
, false == "0"
, etc.)
Short answer: always use ===
and !==
unless you have a compelling reason to do otherwise. (Tools like JSLint, JSHint, ESLint, etc. will give you this same advice.)
The 2 highest upvoted answers are correct. As of today, the only thing I needed to change (from default settings) was to enable generation using dot instead of the built-in generator.
Some important notes:
html/inherits.html
or (from the website navigation) classes => class hierarchy => "Go to the textual class hierarchy".T
.
foo
inherits from T
and the T
template type parameter has a default, such default will be assumed. If there is a type bar
which inherits from foo<U>
where U
is different than the default, bar
will have a foo<U>
parent. foo<>
and bar<U>
will not have a common parent.variant
instantiation will be displayed to inherit from variant<Ts...>
.<...>
string in their name representing type and non-type parameters which did not have defaults.Here is the solution as described in the Doctrine2 Documentation
<?php
use Doctrine\Common\Collections\ArrayCollection;
/** @Entity */
class Order
{
/** @Id @Column(type="integer") @GeneratedValue */
private $id;
/** @ManyToOne(targetEntity="Customer") */
private $customer;
/** @OneToMany(targetEntity="OrderItem", mappedBy="order") */
private $items;
/** @Column(type="boolean") */
private $payed = false;
/** @Column(type="boolean") */
private $shipped = false;
/** @Column(type="datetime") */
private $created;
public function __construct(Customer $customer)
{
$this->customer = $customer;
$this->items = new ArrayCollection();
$this->created = new \DateTime("now");
}
}
/** @Entity */
class Product
{
/** @Id @Column(type="integer") @GeneratedValue */
private $id;
/** @Column(type="string") */
private $name;
/** @Column(type="decimal") */
private $currentPrice;
public function getCurrentPrice()
{
return $this->currentPrice;
}
}
/** @Entity */
class OrderItem
{
/** @Id @ManyToOne(targetEntity="Order") */
private $order;
/** @Id @ManyToOne(targetEntity="Product") */
private $product;
/** @Column(type="integer") */
private $amount = 1;
/** @Column(type="decimal") */
private $offeredPrice;
public function __construct(Order $order, Product $product, $amount = 1)
{
$this->order = $order;
$this->product = $product;
$this->offeredPrice = $product->getCurrentPrice();
}
}
It's used in case of a class method. Check this reference for further details.
EDIT: As clarified by Adrien, it's a convention. You can actually use anything but cls
and self
are used (PEP8).
You can also use Date.now() function.
Other answers that use pip list
or pip freeze
must include --local
else it will also uninstall packages that are found in the common namespaces.
So here are the snippet I regularly use
pip freeze --local | xargs pip uninstall -y
Ref: pip freeze --help
It's because there is no long
in javascript.
This is the solution I have working in Firefox 3, Opera and Google Chrome. The list still displays in IE7 (but without the close bracket and left align numbers):
ol {_x000D_
counter-reset: item;_x000D_
margin-left: 0;_x000D_
padding-left: 0;_x000D_
}_x000D_
li {_x000D_
display: block;_x000D_
margin-bottom: .5em;_x000D_
margin-left: 2em;_x000D_
}_x000D_
li::before {_x000D_
display: inline-block;_x000D_
content: counter(item) ") ";_x000D_
counter-increment: item;_x000D_
width: 2em;_x000D_
margin-left: -2em;_x000D_
}
_x000D_
<ol>_x000D_
<li>One</li>_x000D_
<li>Two</li>_x000D_
<li>Three</li>_x000D_
<li>Four</li>_x000D_
<li>Five</li>_x000D_
<li>Six</li>_x000D_
<li>Seven</li>_x000D_
<li>Eight</li>_x000D_
<li>Nine<br>Items</li>_x000D_
<li>Ten<br>Items</li>_x000D_
</ol>
_x000D_
EDIT: Included multiple line fix by strager
Also is there a CSS solution to change from numbers to alphabetic/roman lists instead of using the type attribute on the ol element.
Refer to list-style-type CSS property. Or when using counters the second argument accepts a list-style-type value. For example the following will use upper roman:
li::before {
content: counter(item, upper-roman) ") ";
counter-increment: item;
/* ... */
To add to @BrianBeech's answer, this is even more trimmed down in java 8:
jdbcTemplate.query("select string1,string2 from table where x=1", (ResultSet rs) -> {
HashMap<String,String> results = new HashMap<>();
while (rs.next()) {
results.put(rs.getString("string1"), rs.getString("string2"));
}
return results;
});
For doing this you can use this
title.setPaintFlags(title.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
and for remove you can use this
title.setPaintFlags(title.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
To get the form that the submit is inside why not just
this.form
Easiest & quickest path to the result.
Using res.json with Express:
function random(response) {
console.log("response.json sets the appropriate header and performs JSON.stringify");
response.json({
anObject: { item1: "item1val", item2: "item2val" },
anArray: ["item1", "item2"],
another: "item"
});
}
Alternatively:
function random(response) {
console.log("Request handler random was called.");
response.writeHead(200, {"Content-Type": "application/json"});
var otherArray = ["item1", "item2"];
var otherObject = { item1: "item1val", item2: "item2val" };
var json = JSON.stringify({
anObject: otherObject,
anArray: otherArray,
another: "item"
});
response.end(json);
}
using filter:
from nltk.corpus import stopwords
# ...
filtered_words = list(filter(lambda word: word not in stopwords.words('english'), word_list))
Here's another way to do it :) The concept is to create a clip-path polygon with the wave as one side.
This approach is fairly flexible. You can change the position (left, right, top or bottom) in which the wave appears, change the wave function to any function(t) which maps to [0,1]). The polygon can also be used for shape-outside, which lets text flow around the wave when in 'left' or 'right' orientation.
At the end, an example you can uncomment which demonstrates animating the wave.
_x000D_
_x000D_
function PolyCalc(f /*a function(t) from [0, infinity) => [0, 1]*/, _x000D_
s, /*a slice function(y, i) from y [0,1] => [0, 1], with slice index, i, in [0, n]*/_x000D_
w /*window size in seconds*/,_x000D_
n /*sample size*/,_x000D_
o /*orientation => left/right/top/bottom - the 'flat edge' of the polygon*/ _x000D_
) _x000D_
{_x000D_
this.polyStart = "polygon(";_x000D_
this.polyLeft = this.polyStart + "0% 0%, "; //starts in the top left corner_x000D_
this.polyRight = this.polyStart + "100% 0%, "; //starts in the top right corner_x000D_
this.polyTop = this.polyStart + "0% 0%, "; // starts in the top left corner_x000D_
this.polyBottom = this.polyStart + "0% 100%, ";//starts in the bottom left corner_x000D_
_x000D_
var self = this;_x000D_
self.mapFunc = s;_x000D_
this.func = f;_x000D_
this.window = w;_x000D_
this.count = n;_x000D_
var dt = w/n; _x000D_
_x000D_
switch(o) {_x000D_
case "top":_x000D_
this.poly = this.polyTop; break;_x000D_
case "bottom":_x000D_
this.poly = this.polyBottom; break;_x000D_
case "right":_x000D_
this.poly = this.polyRight; break;_x000D_
case "left":_x000D_
default:_x000D_
this.poly = this.polyLeft; break;_x000D_
}_x000D_
_x000D_
this.CalcPolygon = function(t) {_x000D_
var p = this.poly;_x000D_
for (i = 0; i < this.count; i++) {_x000D_
x = 100 * i/(this.count-1.0);_x000D_
y = this.func(t + i*dt);_x000D_
if (typeof self.mapFunc !== 'undefined')_x000D_
y=self.mapFunc(y, i);_x000D_
y*=100;_x000D_
switch(o) {_x000D_
case "top": _x000D_
p += x + "% " + y + "%, "; break;_x000D_
case "bottom":_x000D_
p += x + "% " + (100-y) + "%, "; break;_x000D_
case "right":_x000D_
p += (100-y) + "% " + x + "%, "; break;_x000D_
case "left":_x000D_
default:_x000D_
p += y + "% " + x + "%, "; break; _x000D_
}_x000D_
}_x000D_
_x000D_
switch(o) { _x000D_
case "top":_x000D_
p += "100% 0%)"; break;_x000D_
case "bottom":_x000D_
p += "100% 100%)";_x000D_
break;_x000D_
case "right":_x000D_
p += "100% 100%)"; break;_x000D_
case "left":_x000D_
default:_x000D_
p += "0% 100%)"; break;_x000D_
}_x000D_
_x000D_
return p;_x000D_
}_x000D_
};_x000D_
_x000D_
var text = document.querySelector("#text");_x000D_
var divs = document.querySelectorAll(".wave");_x000D_
var freq=2*Math.PI; //angular frequency in radians/sec_x000D_
var windowWidth = 1; //the time domain window which determines the range from [t, t+windowWidth] that will be evaluated to create the polygon_x000D_
var sampleSize = 60;_x000D_
divs.forEach(function(wave) {_x000D_
var loc = wave.classList[1];_x000D_
_x000D_
var polyCalc = new PolyCalc(_x000D_
function(t) { //The time domain wave function_x000D_
return (Math.sin(freq * t) + 1)/2; //sine is [-1, -1], so we remap to [0,1]_x000D_
},_x000D_
function(y, i) { //slice function, takes the time domain result and the slice index and returns a new value in [0, 1] _x000D_
return MapRange(y, 0.0, 1.0, 0.65, 1.0); //Here we adjust the range of the wave to 'flatten' it out a bit. We don't use the index in this case, since it is irrelevant_x000D_
},_x000D_
windowWidth, //1 second, which with an angular frequency of 2pi rads/sec will produce one full period._x000D_
sampleSize, //the number of samples to make, the larger the number, the smoother the curve, but the more pionts in the final polygon_x000D_
loc //the location_x000D_
);_x000D_
_x000D_
var polyText = polyCalc.CalcPolygon(0);_x000D_
wave.style.clipPath = polyText;_x000D_
wave.style.shapeOutside = polyText;_x000D_
wave.addEventListener("click",function(e) {document.querySelector("#polygon").innerText = polyText;});_x000D_
});_x000D_
_x000D_
function MapRange(value, min, max, newMin, newMax) {_x000D_
return value * (newMax - newMin)/(max-min) + newMin;_x000D_
}_x000D_
_x000D_
//Animation - animate the wave by uncommenting this section_x000D_
//Also demonstrates a slice function which uses the index of the slice to alter the output for a dampening effect._x000D_
/*_x000D_
var t = 0;_x000D_
var speed = 1/180;_x000D_
_x000D_
var polyTop = document.querySelector(".top");_x000D_
_x000D_
var polyTopCalc = new PolyCalc(_x000D_
function(t) {_x000D_
return (Math.sin(freq * t) + 1)/2;_x000D_
},_x000D_
function(y, i) { _x000D_
return MapRange(y, 0.0, 1.0, (sampleSize-i)/sampleSize, 1.0);_x000D_
},_x000D_
windowWidth, sampleSize, "top"_x000D_
);_x000D_
_x000D_
function animate() {_x000D_
var polyT = polyTopCalc.CalcPolygon(t); _x000D_
t+= speed;_x000D_
polyTop.style.clipPath = polyT; _x000D_
requestAnimationFrame(animate);_x000D_
}_x000D_
_x000D_
requestAnimationFrame(animate);_x000D_
*/
_x000D_
div div {_x000D_
padding:10px;_x000D_
/*overflow:scroll;*/_x000D_
}_x000D_
_x000D_
.left {_x000D_
height:100%;_x000D_
width:35%;_x000D_
float:left;_x000D_
}_x000D_
_x000D_
.right {_x000D_
height:200px;_x000D_
width:35%;_x000D_
float:right;_x000D_
}_x000D_
_x000D_
.top { _x000D_
width:100%;_x000D_
height: 200px; _x000D_
}_x000D_
_x000D_
.bottom {_x000D_
width:100%;_x000D_
height:200px;_x000D_
}_x000D_
_x000D_
.green {_x000D_
background:linear-gradient(to bottom, #b4ddb4 0%,#83c783 17%,#52b152 33%,#008a00 67%,#005700 83%,#002400 100%); _x000D_
} _x000D_
_x000D_
.mainContainer {_x000D_
width:100%;_x000D_
float:left;_x000D_
}_x000D_
_x000D_
#polygon {_x000D_
padding-left:20px;_x000D_
margin-left:20px;_x000D_
width:100%;_x000D_
}
_x000D_
<div class="mainContainer">_x000D_
_x000D_
<div class="wave top green">_x000D_
Click to see the polygon CSS_x000D_
</div>_x000D_
_x000D_
<!--div class="wave left green">_x000D_
</div-->_x000D_
<!--div class="wave right green">_x000D_
</div--> _x000D_
<!--div class="wave bottom green"></div--> _x000D_
</div>_x000D_
<div id="polygon"></div>
_x000D_
You should use the Time.IsZero() function instead:
func (Time) IsZero
func (t Time) IsZero() bool
IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.
ZBar
Pre-requisites:
choco install zbar
pip install pyzbar
To decode:
from PIL import Image
from pyzbar import pyzbar
img = Image.open('My-Image.jpg')
output = pyzbar.decode(img)
print(output)
Alternatively, you can also try using ZBarLight
by setting it up as mentioned here:
https://pypi.org/project/zbarlight/
Another option:
UPDATE `table` SET the_col = current_timestamp
Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now()
.
Enable this option in VS: Just My Code option
Tools -> Options -> Debugging -> General -> Enable Just My Code (Managed only)
Template Syntax Error: is due to many reasons one of them is {{ post.date_posted|date: "F d, Y" }} is the space between colon(:) and quote (") if u remove the space then it work like this ..... {{ post.date_posted|date:"F d, Y" }}
Simply do this, with genymotion device running you can open Virtual Box , and see that there is a VM for you device , then go to network Settings of the VM, NAT and do port forwarding of local 5555 to remote 5555 screen attachedVirtual Box Nat Network Port forwarding
I tried all above steps to resolve the problem but nothing worked. I had installed both JDK and JRE.
In my case, one jar file was being opened by double click while other was not being opened. I examined those files and the probable reason was that which was being opened, was created using JAVA SE 6 and the one not being opened was created using JAVA SE 7. Although, the problematic jar file was being run via command prompt (java -jar myfile.jar).
I tried Right Click -> Properties -> Change to javaw.exe with both in JDK\bin directory and JRE\bin directory.
I was finally able to fix the problem by changing javaw.exe path (from JDK\bin to JRE\bin) in registry editor.
Go to HKEY_CLASSES_ROOT\jarfile\shell\open\command, the value was,
"C:\Program Files\Java\jdk-11.0.1\bin\javaw.exe" -jar "%1" %*
I changed it to,
"C:\Program Files\Java\jre1.8.0_191\bin\javaw.exe" -jar "%1" %*
and it worked. Now the jar file can be opened by double click.
Instead of sorting the results and keeping only the last modified ones, you could use awk to print only the one with greatest modification time (in unix time):
find . -type f -printf "%T@\0%p\0" | awk '
{
if ($0>max) {
max=$0;
getline mostrecent
} else
getline
}
END{print mostrecent}' RS='\0'
This should be a faster way to solve your problem if the number of files is big enough.
I have used the NUL character (i.e. '\0') because, theoretically, a filename may contain any character (including space and newline) but that.
If you don't have such pathological filenames in your system you can use the newline character as well:
find . -type f -printf "%T@\n%p\n" | awk '
{
if ($0>max) {
max=$0;
getline mostrecent
} else
getline
}
END{print mostrecent}' RS='\n'
In addition, this works in mawk too.
In addition to cemkalyoncu's solution:
next record:
SELECT * FROM foo WHERE id > 4 ORDER BY id LIMIT 1;
previous record:
SELECT * FROM foo WHERE id < 4 ORDER BY id DESC LIMIT 1;
edit: Since this answer has been getting a few upvotes lately, I really want to stress the comment I made earlier about understanding that a primary key colum is not meant as a column to sort by, because MySQL does not guarantee that higher, auto incremented, values are necessarily added at a later time.
If you don't care about this, and simply need the record with a higher (or lower) id
then this will suffice. Just don't use this as a means to determine whether a record is actually added later (or earlier). In stead, consider using a datetime column to sort by, for instance.
Edit:
Are you trying to do sth like this? See: http://twitter.github.com/bootstrap/javascript.html#tabs
See the working example: http://jsfiddle.net/U6aKT/
<a href="#id">go to id</a>
<div style="margin-top:2000px;"></div>
<a id="id">id</a>
See Arrays.fill method:
char f = '+';
char [] c = new char [50];
Arrays.fill(c, f);
I took the Ned Rockson's version and adjusted it to allow upwards scrolls as well.
var smoothScroll = function(elementId) {
var MIN_PIXELS_PER_STEP = 16;
var MAX_SCROLL_STEPS = 30;
var target = document.getElementById(elementId);
var scrollContainer = target;
do {
scrollContainer = scrollContainer.parentNode;
if (!scrollContainer) return;
scrollContainer.scrollTop += 1;
} while (scrollContainer.scrollTop === 0);
var targetY = 0;
do {
if (target === scrollContainer) break;
targetY += target.offsetTop;
} while (target = target.offsetParent);
var pixelsPerStep = Math.max(MIN_PIXELS_PER_STEP,
Math.abs(targetY - scrollContainer.scrollTop) / MAX_SCROLL_STEPS);
var isUp = targetY < scrollContainer.scrollTop;
var stepFunc = function() {
if (isUp) {
scrollContainer.scrollTop = Math.max(targetY, scrollContainer.scrollTop - pixelsPerStep);
if (scrollContainer.scrollTop <= targetY) {
return;
}
} else {
scrollContainer.scrollTop = Math.min(targetY, scrollContainer.scrollTop + pixelsPerStep);
if (scrollContainer.scrollTop >= targetY) {
return;
}
}
window.requestAnimationFrame(stepFunc);
};
window.requestAnimationFrame(stepFunc);
};
Try this one,
Create rounded_edittext.xml
file in your Drawable
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="15dp">
<solid android:color="#FFFFFF" />
<corners
android:bottomRightRadius="0dp"
android:bottomLeftRadius="0dp"
android:topLeftRadius="0dp"
android:topRightRadius="0dp" />
<stroke android:width="1dip" android:color="#f06060" />
</shape>
Apply background for your EditText
in xml file
<EditText
android:id="@+id/edit_expiry_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:background="@drawable/rounded_edittext"
android:hint="@string/shop_name"
android:inputType="text" />
You will get output like this
You need a git client to upload your project to git servers. For eclipse EGIT is a nice plugin to use GIT.
to learn the basic of git , see here // i think you should have the basic first
Note: this is JQuery. See Sébastien answer for Javascript
$(function() {
var temp="a";
$("#MySelect").val(temp);
});
<select name="MySelect" id="MySelect">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
I got same problem if i understand your question correctly, I want to know the last inserted id after every insert performance in SQLite operation. i tried the following statement:
select * from table_name order by id desc limit 1
The id is the first column and primary key of the table_name, the mentioned statement show me the record with the largest id.
But the premise is u never deleted any row so the numbers of id equal to the numbers of rows.
There was a time when adding strings into an array and finalising the string by using join
was the fastest/best method. These days browsers have highly optimised string routines and it is recommended that +
and +=
methods are fastest/best
Here in simpler words:
DOM
Tree model parser (Object based) (Tree of nodes).
DOM loads the file into the memory and then parse- the file.
Has memory constraints since it loads the whole XML file before parsing.
DOM is read and write (can insert or delete nodes).
If the XML content is small, then prefer DOM parser.
Backward and forward search is possible for searching the tags and evaluation of the information inside the tags. So this gives the ease of navigation.
Slower at run time.
SAX
Event based parser (Sequence of events).
SAX parses the file as it reads it, i.e. parses node by node.
No memory constraints as it does not store the XML content in the memory.
SAX is read only i.e. can’t insert or delete the node.
Use SAX parser when memory content is large.
SAX reads the XML file from top to bottom and backward navigation is not possible.
Faster at run time.
One way is to call A's constructor and pass self
as an argument, like so:
class B(A):
def __init__(self):
A.__init__(self)
print "hello"
The advantage of this style is that it's very clear. It call A's initialiser. The downside is that it doesn't handle diamond-shaped inheritance very well, since you may end up calling the shared base class's initialiser twice.
Another way is to use super(), as others have shown. For single-inheritance, it does basically the same thing as letting you call the parent's initialiser.
However, super() is quite a bit more complicated under-the-hood and can sometimes be counter-intuitive in multiple inheritance situations. On the plus side, super() can be used to handle diamond-shaped inheritance. If you want to know the nitty-gritty of what super() does, the best explanation I've found for how super() works is here (though I'm not necessarily endorsing that article's opinions).
Does this help?
User userObj1 = new User();
User userObj2 = userObj1;
.
.
.
rtsession.save(userObj1);
rtsession.save(userObj2);
object-fit: cover
is the best answer with this IE, Safari polyfill.
https://github.com/constancecchen/object-fit-polyfill
It is supporting img
, video
and picture
elements.
Here if you mention .getPath()
then that will return the path of Jar and I guess
you will need its parent to refer to all other config files placed with the jar.
This code works on Windows. Add the code within the main class.
File jarDir = new File(MyAppName.class.getProtectionDomain().getCodeSource().getLocation().getPath());
String jarDirpath = jarDir.getParent();
System.out.println(jarDirpath);
There are various symbols which could be considered adequate replacements, including:
| | - two standard (bolded) vertical bars.
▋▋ - ▋
and another▋
▌▌ - ▌
and another▌
▍▍ - ▍
and another▍
▎▎ - ▎
and another▎
❚❚ - ❚
and another ❚
I may have missed out one or two, but I think these are the better ones. Here's a list of symbols just in case.
From the documentation (help copy-item -full
):
-force <SwitchParameter>
Allows cmdlet to override restrictions such as renaming existing files as long as security is not compromised.
Required? false
Position? named
Default value False
Accept pipeline input? false
Accept wildcard characters? false
Add attributed text color in swift code.
Swift 4:
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
let attributedStringColor = [NSAttributedStringKey.foregroundColor : greenColor];
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor)
label.attributedText = attributedString
for Swift 3:
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
let attributedStringColor : NSDictionary = [NSForegroundColorAttributeName : greenColor];
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor as? [String : AnyObject])
label.attributedText = attributedString
Check out this snippet:
Private Sub openDialog()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file."
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
End Sub
I think this is what you are asking for.
ViewBag is of type dynamic. More, you cannot do ViewBag["Foo"]
. You will get exception - Cannot apply indexing with [] to an expression of type 'System.Dynamic.DynamicObject'.
Internal implementation of ViewBag
actually stores Foo into ViewData["Foo"]
(type of ViewDataDictionary), so those 2 are interchangeable. ViewData["Foo"]
and ViewBag.Foo
.
And scope. ViewBag and ViewData are ment to pass data between Controller's Actions and View it renders.
Woohoo my first post even though this is a year old. To avoid the background-coloring issues with wrappers, you could use inline-block with hr (nobody said that explicitly). Text-align should center correctly since they are inline elements.
<div style="text-align:center">
<hr style="display:inline-block; position:relative; top:4px; width:45%" />
New Section
<hr style="display:inline-block; position:relative; top:4px; width:45%" />
</div>
You can use IEnumerable.First()
or IEnumerable.FirstOrDefault()
.
The difference is that First()
will throw if no element is found (or if no element matches the conditions, if you use the conditions). FirstOrDefault()
will return default(T)
(null
if it's a reference type).
You install as assemblies by using:
gacutil.exe
tool with the -i
option from the command line.%windir%\Assembly
(only up to .NET 3.5, CLR 2.0)You view the content of the GAC using:
gacutil.exe
tool with the -l
option.%windir%\assembly
using the Windows Explorer.Note that the (physical) GAC location has changed for .NET 4.0. It is no longer in %windir%\Assembly
, but now in %windir%\Microsoft.NET\assembly
. However, you should never write any code that depends on the physical location anyway, because given the tools available that is hardly necessary (some "cool" homegrown system diagnostics tools aside).
In your case
Employee emp = (Employee)mgr; //mgr is Manager
you are doing an upcasting.
An upcast always succeeds unlike a downcast that requires an explicit cast because it can potentially fail at runtime.(InvalidCastException).
C# offers two operators to avoid this exception to be thrown:
Starting from:
Employee e = new Employee();
First:
Manager m = e as Manager; // if downcast fails m is null; no exception thrown
Second:
if (e is Manager){...} // the predicate is false if the downcast is not possible
Warning: When you do an upcast you can only access to the superclass' methods, properties etc...
What is the difference between them?
Image: the generic Linux kernel binary image file.
zImage: a compressed version of the Linux kernel image that is self-extracting.
uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.
Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:
Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.
(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)
Which type of kernel image do I have to use?
You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.
ADDENDUM
I know that u-boot needs a kernel in uImage format.
That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.
I am not going to pretend I know why this particular function works, however window.getComputedStyle works 100% of the time for me whenever I need to access DOM elements with a Ref in a useEffect — I can only presume it will work with componentDidMount as well.
I put it at the top of the code in a useEffect and it appears as if it forces the effect to wait for the elements to be painted before it continues with the next line of code, but without any noticeable delay such as using a setTimeout or an async sleep function. Without this, the Ref element returns as undefined when I try to access it.
const ref = useRef(null);
useEffect(()=>{
window.getComputedStyle(ref.current);
// Next lines of code to get element and do something after getComputedStyle().
});
return(<div ref={ref}></div>);
ACCESSING LOCAL WEBSITE WITH IIS without Physical Path Authentication
I hope it helps. That's what I did.
WinSCp now supports S3 protocol
First, make sure your AWS user with S3 access permissions has an “Access key ID” created. You also have to know the “Secret access key”. Access keys are created and managed on Users page of IAM Management Console.
Make sure New site node is selected.
On the New site node, select Amazon S3 protocol.
Enter your AWS user Access key ID and Secret access key
Save your site settings using the Save button.
Login using the Login button.
I'm pretty sure it's manufacturer dependent, since they will be accessed through an I/O port. If you have a specific board you're trying to work with, try looking through the manuals and/or contacting the manufacturer.
If you want to do this for a lot of different boards, I'd recommend contacting someone at something like SiSoftware or be prepared to read a LOT of motherboard manuals.
As another note, not all boards have temperature monitors.
You also might run into problems getting privileged access from the kernel.
run pod install inside ios folder then go back to root folder and run npx react-native run-ios
Suppose your program doesn't have memory leakage, objects accumulates and cannot be GC-ed in Gen 0 because: 1) They are referenced for long time so get into Gen1 & Gen2; 2) They are large objects (>80K) so get into LOH (Large Object Heap). And LOH doesn't do compacting as in Gen0, Gen1 & Gen2.
Check the performance counter of ".NET Memory" can you can see that the 1) problem is really not a problem. Generally, every 10 Gen0 GC will trigger 1 Gen1 GC, and every 10 Gen1 GC will trigger 1 Gen2 GC. Theoretically, GC1 & GC2 can never be GC-ed if there is no pressure on GC0 (if the program memory usage is really wired). It never happens to me.
For problem 2), you can check ".NET Memory" performance counter to verify whether LOH is getting bloated. If it is really a issue to your problem, perhaps you can create a large-object-pool as this blog suggests http://blogs.msdn.com/yunjin/archive/2004/01/27/63642.aspx.
I solved that problem.
I was implementing an OSI Layer (slider window, Level 2) for a network simulation in C++ (Eclipse Juno). I had frames (template <class T>
) and its states (state pattern, forward declaration).
The solution is as follows:
In the *.cpp
file, you must include the Header file that you forward, i.e.
ifndef STATE_H_
#define STATE_H_
#include <stdlib.h>
#include "Frame.h"
template <class T>
class LinkFrame;
using namespace std;
template <class T>
class State {
protected:
LinkFrame<int> *myFrame;
}
Its cpp:
#include "State.h"
#include "Frame.h"
#include "LinkFrame.h"
template <class T>
bool State<T>::replace(Frame<T> *f){
And... another class.
In Windows 10 I had to run the batch file as an administrator.
In PowerShell pwd
is an alias to Get-Location
so you can simply run pwd
in it like in bash
It can also be called from cmd like this powershell -Command pwd
although cd
or echo %cd%
in cmd would work just fine
If you use vue cli with the Webpack template (default config), you can create and add your environment variables to a .env file.
The variables will automatically be accessible under process.env.variableName
in your project. Loaded variables are also available to all vue-cli-service commands, plugins and dependencies.
You have a few options, this is from the Environment Variables and Modes documentation:
.env # loaded in all cases
.env.local # loaded in all cases, ignored by git
.env.[mode] # only loaded in specified mode
.env.[mode].local # only loaded in specified mode, ignored by git
Your .env file should look like this:
VUE_APP_MY_ENV_VARIABLE=value
VUE_APP_ANOTHER_VARIABLE=value
It is my understanding that all you need to do is create the .env file and add your variables then you're ready to go! :)
As noted in comment below: If you are using Vue cli 3, only variables that start with VUE_APP_ will be loaded.
Don't forget to restart serve if it is currently running.
Modern browsers do not currently implement JSONRequest (as far as I know) since it is only a draft right now. I have found someone who has implemented it as a library that you can include in your page: http://devpro.it/JSON/files/JSONRequest-js.html (please note that it has a few dependencies).
Otherwise, you might want to go with another JS library like jQuery or Mootools.
In my case function eval() works very good. Below I generate 10 variables and assign them 10 values.
lhs <- rnorm(10)
rhs <- paste("perf.a", 1:10, "<-", lhs, sep="")
eval(parse(text=rhs))
Sometimes the problem is in the composer memory limit. In my case, I tried increasing the php memory limit but still got the error.
You can use COMPOSER_MEMORY_LIMIT=-1
to get around that.
Use it as a prefix:
COMPOSER_MEMORY_LIMIT=-1 composer require the/library
You have to prefix it again in the future.
Hope this helps.
-Sorry this is very late reply.
The easiest way i have found to delete any row (and all other rows through iteration) is this
$('#rowid','#tableid').remove();
The rest is easy.
I wrote a very light-weight alternative to PHP's var_dump for using in Python and made it open source later.
GitHub: https://github.com/sha256/python-var-dump
You can simply install it using pip
:
pip install var_dump
using httrack software you can download all the website content in your local. httrack : http://www.httrack.com/
As the above people stated, select PostGIS_full_version(); will answer your question. On my machine, where I'm running PostGIS 2.0 from trunk, I get the following output:
postgres=# select PostGIS_full_version();
postgis_full_version
-------------------------------------------------------------------------------------------------------------------------------------------------------
POSTGIS="2.0.0alpha4SVN" GEOS="3.3.2-CAPI-1.7.2" PROJ="Rel. 4.7.1, 23 September 2009" GDAL="GDAL 1.8.1, released 2011/07/09" LIBXML="2.7.3" USE_STATS
(1 row)
You do need to care about the versions of PROJ and GEOS that are included if you didn't install an all-inclusive package - in particular, there's some brokenness in GEOS prior to 3.3.2 (as noted in the postgis 2.0 manual) in dealing with geometry validity.
Just use a onchnage Event
for select box.
<select id="selectbox" name="" onchange="javascript:location.href = this.value;">
<option value="https://www.yahoo.com/" selected>Option1</option>
<option value="https://www.google.co.in/">Option2</option>
<option value="https://www.gmail.com/">Option3</option>
</select>
And if selected option to be loaded at the page load then add some javascript code
<script type="text/javascript">
window.onload = function(){
location.href=document.getElementById("selectbox").value;
}
</script>
for jQuery: Remove the onchange event from <select>
tag
jQuery(function () {
// remove the below comment in case you need chnage on document ready
// location.href=jQuery("#selectbox").val();
jQuery("#selectbox").change(function () {
location.href = jQuery(this).val();
})
})
listView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
return false;
}
});
Definitely does the trick.
You can use * for import all jars into a folder when adding in conf/spark-defaults.conf .
spark.driver.extraClassPath /fullpath/*
spark.executor.extraClassPath /fullpath/*
session_start();
if(isset($_SESSION['current'])){
$_SESSION['oldlink']=$_SESSION['current'];
}else{
$_SESSION['oldlink']='no previous page';
}
$_SESSION['current']=$_SERVER['PHP_SELF'];
Maybe this is what you're looking for? It will remember the old link/page you're coming from (within your website).
Put that piece on top of each page.
If you want to make it 'refresh proof' you can add another check:
if(isset($_SESSION['current']) && $_SESSION['current']!=$_SERVER['PHP_SELF'])
This will make the page not remember itself.
UPDATE: Almost the same as @Brandon though... Just use a php variable, I know this looks like a security risk, but when done correct it isn't.
<a href="home.php?a=register">Register Now!</a>
PHP:
if(isset($_GET['a']) /*you can validate the link here*/){
$_SESSION['link']=$_GET['a'];
}
Why even store the GET in a session? Just use it. Please tell me why you do not want to use GET. « Validate for more security. I maybe can help you with a better script.
fs.exists(path, callback)
and fs.existsSync(path)
are deprecated now, see https://nodejs.org/api/fs.html#fs_fs_exists_path_callback and https://nodejs.org/api/fs.html#fs_fs_existssync_path.
To test the existence of a file synchronously one can use ie. fs.statSync(path)
. An fs.Stats
object will be returned if the file exists, see https://nodejs.org/api/fs.html#fs_class_fs_stats, otherwise an error is thrown which will be catched by the try / catch statement.
var fs = require('fs'),
path = '/path/to/my/file',
stats;
try {
stats = fs.statSync(path);
console.log("File exists.");
}
catch (e) {
console.log("File does not exist.");
}
Yes it's an issue in webkit and also reported in chromium: http://code.google.com/p/chromium/issues/detail?id=773 It's there since 2008... and still not fixed!!
I'm using a piece of javacsript and jQuery to make my way around this.
function showAlt(){$(this).replaceWith(this.alt)};
function addShowAlt(selector){$(selector).error(showAlt).attr("src", $(selector).src)};
addShowAlt("img");
If you only want one some images:
addShowAlt("#myImgID");
If nothing works then find the Jenkins process by
ps aux | grep java
and then kill it:
kill -9 [PID]
sudo service jenkins start
Edit : Look for the java process which is related to jenkins
No.
Equality is equality.
The function you wrote will not test two doubles for equality, as its name promises. It will only test if two doubles are "close enough" to each other.
If you really want to test two doubles for equality, use this one:
inline bool isEqual(double x, double y)
{
return x == y;
}
Coding standards usually recommend against comparing two doubles for exact equality. But that is a different subject. If you actually want to compare two doubles for exact equality, x == y
is the code you want.
10.000000000000001 is not equal to 10.0, no matter what they tell you.
An example of using exact equality is when a particular value of a double is used as a synonym of some special state, such as "pending calulation" or "no data available". This is possible only if the actual numeric values after that pending calculation are only a subset of the possible values of a double. The most typical particular case is when that value is nonnegative, and you use -1.0 as an (exact) representation of a "pending calculation" or "no data available". You could represent that with a constant:
const double NO_DATA = -1.0;
double myData = getSomeDataWhichIsAlwaysNonNegative(someParameters);
if (myData != NO_DATA)
{
...
}
//This will sort your array
function SortByName(a, b){
var aName = a.name.toLowerCase();
var bName = b.name.toLowerCase();
return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}
array.sort(SortByName);
Create vector, push_back element, then modify it as so:
struct subject {
string name;
int marks;
int credits;
};
int main() {
vector<subject> sub;
//Push back new subject created with default constructor.
sub.push_back(subject());
//Vector now has 1 element @ index 0, so modify it.
sub[0].name = "english";
//Add a new element if you want another:
sub.push_back(subject());
//Modify its name and marks.
sub[1].name = "math";
sub[1].marks = 90;
}
You cant access a vector with [#] until an element exists in the vector at that index. This example populates the [#] and then modifies it afterward.
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(444, 25);
this.toolStrip1.TabIndex = 0;
this.toolStrip1.Text = "toolStrip1";
object O = global::WindowsFormsApplication1.Properties.Resources.ResourceManager.GetObject("best_robust_ghost");
ToolStripButton btn = new ToolStripButton("m1");
btn.DisplayStyle = ToolStripItemDisplayStyle.Image;
btn.Image = (Image)O;
this.toolStrip1.Items.Add(btn);
this.Controls.Add(this.toolStrip1);
If working in Java 1.8 you can leverage the DateTimeFormatterBuilder
public static boolean isTimeStampValid(String inputString)
{
DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ofPattern("" + "[yyyy-MM-dd'T'HH:mm:ss.SSSZ]" + "[yyyy-MM-dd]"));
DateTimeFormatter dateTimeFormatter = dateTimeFormatterBuilder.toFormatter();
try {
dateTimeFormatter.parse(inputString);
return true;
} catch (DateTimeParseException e) {
return false;
}
}
See post: Java 8 Date equivalent to Joda's DateTimeFormatterBuilder with multiple parser formats?
The excellent book "Algorithm Design Manual" by Skienna contains a huge repository of Algorithms and Data structure.
For tons of problems, data structures and algorithm are described, compared, and discusses the practical usage. The author also provides references to implementations and the original research papers.
The book is great to have it on your desk if you search the best data structure for your problem to solve. It is also very helpful for interview preparation.
Another great resource is the NIST Dictionary of Data structures and algorithms.
John's answer is correct. When I'm dealing with params I also need URLSearchParams
interface:
this.props.history.push({
pathname: '/client',
search: "?" + new URLSearchParams({clientId: clientId}).toString()
})
You might also need to wrap your component with a withRouter
HOC eg. export default withRouter(YourComponent);
.
I know it is an old question, but I just managed to do so without a pseudo child (but a pseudo wrapper).
If you set the parent to be with no pointer-events
, and then a child div
with pointer-events
set to auto
, it works:)
Note that <img>
tag (for example) doesn't do the trick.
Also remember to set pointer-events
to auto
for other children which have their own event listener, or otherwise they will lose their click functionality.
div.parent { _x000D_
pointer-events: none;_x000D_
}_x000D_
_x000D_
div.child {_x000D_
pointer-events: auto;_x000D_
}_x000D_
_x000D_
div.parent:hover {_x000D_
background: yellow;_x000D_
}
_x000D_
<div class="parent">_x000D_
parent - you can hover over here and it won't trigger_x000D_
<div class="child">hover over the child instead!</div>_x000D_
</div>
_x000D_
Edit:
As Shadow Wizard kindly noted: it's worth to mention this won't work for IE10 and below. (Old versions of FF and Chrome too, see here)
Proper answer is here: http://scratching.psybermonkey.net/2011/02/ssh-how-to-pipe-output-from-local-to.html
your_command | ssh username@server "cat > filename.txt"
If user enters 34abc and you pass them to atoi it will return 34. If you want to validate the value entered then you have to use isdigit on the entered string iteratively
First of all, a ternary expression is not a replacement for an if/else construct - it's an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.
This means several things:
=
that is to be assigned the return valuex = true
returns true as all expressions return the last value, but it also changes x without x having any effect on the returned value)In short - the 'correct' use of a ternary expression is
var resultofexpression = conditionasboolean ? truepart: falsepart;
Instead of your example condition ? x=true : null ;
, where you use a ternary expression to set the value of x
, you can use this:
condition && (x = true);
This is still an expression and might therefore not pass validation, so an even better approach would be
void(condition && x = true);
The last one will pass validation.
But then again, if the expected value is a boolean, just use the result of the condition expression itself
var x = (condition); // var x = (foo == "bar");
In relation to your sample, this is probably more appropriate:
defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';
I am Write this code in xml file ...
<Button
android:id="@+id/btn_register"
android:layout_margin="1dp"
android:layout_marginLeft="3dp"
android:layout_marginTop="10dp"
android:layout_weight="2"
android:onClick="register"
android:text="Register"
android:textColor="#000000"/>
And write this code in fragment...
public void register(View view) {
}
C++03 (Source: Iterator Invalidation Rules (C++03))
Sequence containers
vector
: all iterators and references before the point of insertion are unaffected, unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated) [23.2.4.3/1]deque
: all iterators and references are invalidated, unless the inserted member is at an end (front or back) of the deque (in which case all iterators are invalidated, but references to elements are unaffected) [23.2.1.3/1]list
: all iterators and references unaffected [23.2.2.3/1]Associative containers
[multi]{set,map}
: all iterators and references unaffected [23.1.2/8]Container adaptors
stack
: inherited from underlying containerqueue
: inherited from underlying containerpriority_queue
: inherited from underlying containerSequence containers
vector
: every iterator and reference after the point of erase is invalidated [23.2.4.3/3]deque
: all iterators and references are invalidated, unless the erased members are at an end (front or back) of the deque (in which case only iterators and references to the erased members are invalidated) [23.2.1.3/4]list
: only the iterators and references to the erased element is invalidated [23.2.2.3/3]Associative containers
[multi]{set,map}
: only iterators and references to the erased elements are invalidated [23.1.2/8]Container adaptors
stack
: inherited from underlying containerqueue
: inherited from underlying containerpriority_queue
: inherited from underlying containervector
: as per insert/erase [23.2.4.2/6]deque
: as per insert/erase [23.2.1.2/1]list
: as per insert/erase [23.2.2.2/1]Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [23.1/11]
It's not clear in C++2003 whether "end" iterators are subject to the above rules; you should assume, anyway, that they are (as this is the case in practice).
The rules for invalidation of pointers are the sames as the rules for invalidation of references.
YOUR-COMMAND &> YOUR-LOG.log &
This should run the command and assign a process id you can simply tail -f YOUR-LOG.log to see results written to it as they happen. you can log out anytime and the process will carry on
EDIT: previous answer was backwards of what you wanted. Use str_replace.
replace <br>
with \n
echo str_replace('<br>', "\n", $var1);
StringUtils.abbreviate
from Apache Commons Lang library could be your friend:
StringUtils.abbreviate("abcdefg", 6) = "abc..."
StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
StringUtils.abbreviate("abcdefg", 4) = "a..."
Commons Lang3 even allow to set a custom String as replacement marker. With this you can for example set a single character ellipsis.
StringUtils.abbreviate("abcdefg", "\u2026", 6) = "abcde…"
"Upstream" would refer to the main repo that other people will be pulling from, e.g. your GitHub repo. The -u option automatically sets that upstream for you, linking your repo to a central one. That way, in the future, Git "knows" where you want to push to and where you want to pull from, so you can use git pull
or git push
without arguments. A little bit down, this article explains and demonstrates this concept.
This Worked for me
Your Array :
DummyArray: any = [
{"id": 1, "name": 'A'},
{"id": 2, "name": 'B'},
{"id": 3, "name": 'C'},
{"id": 4, "name": 'D'}]
Function:
remove(){
this.DummyArray = this.DummyArray.filter(item => item !== item);}
Note: This function deletes all the objects form your array. If you want to delete a specific object from array then use this method:
remove(id){
this.DummyArray = this.DummyArray.filter(item => item.id !== id);}
Just to clarify -- as noted above when rebasing the sense is reversed, so if you see
<<<<<<< HEAD
foo = 12;
=======
foo = 22;
>>>>>>> [your commit message]
Resolve using 'mine' -> foo = 12
Resolve using 'theirs' -> foo = 22
a simple way would be to cast the dates into timestamps and take their difference and then extract the DAY part.
if you want real difference
select extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp);
if you want absolute difference
select abs(extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp));
Adding to Tim's answer:
#search:placeholder-shown {
// show background image, I like svg
// when using svg, do not use HEX for colour; you can use rbg/a instead
// also notice the single quotes
background-image url('data:image/svg+xml; utf8, <svg>... <g fill="grey"...</svg>')
// other background props
}
#search:not(:placeholder-shown) { background-image: none;}
Click somewhere on the chart to select it.
You should now see 3 new tabs appear at the top of the screen called "Design", "Layout" and "Format".
Click on the "Design" tab.
There will be a button called "Switch Row/Column" within the "data" group, click it.
Why not use .style
of the DOM element? It's an object which contains members such as width
and backgroundColor
.
Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here
Open the sources.list
file:
sudo nano /etc/apt/sources.list
Add a line with the source from where the packages will be retrieved. For example:
deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
Replace https://cloud.r-project.org
with whatever mirror you would like to use, and replace
version/
with whatever version of Ubuntu you are using (eg, trusty/
, xenial/
, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/
and version/
.
Fetch the secure APT key:
gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
or
gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
Add it to keyring:
gpg -a --export E084DAB9 | sudo apt-key add -
Update your sources and upgrade your installation:
sudo apt-get update && sudo apt-get upgrade
Install the new version
sudo apt-get install r-base-dev
Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:
-- copy the packages from R-oldversion/library
to R-newversion/library
, (do not overwrite a package if it already exists in the new version!).
-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE)
.
The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:
ffmpeg -i input.mov -qscale 0 output.mp4
Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0
):
ffmpeg -i input.mov -q:v 0 output.mp4
jminix is an embedded web based JMX console. Not sure if it's maintained any longer, but still.
You can do this from ECMAScript 6 onwards using arrays and "destructuring assignments". Note that these are not available in older Javascript versions (meaning — neither with ECMAScript 3rd nor 5th editions).
It allows you to assign to 1+ variables simultaneously:
var [x, y] = [1, 2];
x; // 1
y; // 2
// or
[x, y] = (function(){ return [3, 4]; })();
x; // 3
y; // 4
You can also use object destructuring combined with property value shorthand to name the return values in an object and pick out the ones you want:
let {baz, foo} = (function(){ return {foo: 3, bar: 500, baz: 40} })();
baz; // 40
foo; // 3
And by the way, don't be fooled by the fact that ECMAScript allows you to return 1, 2, ...
. What really happens there is not what might seem. An expression in return statement — 1, 2, 3
— is nothing but a comma operator applied to numeric literals (1
, 2
, and 3
) sequentially, which eventually evaluates to the value of its last expression — 3
. That's why return 1, 2, 3
is functionally identical to nothing more but return 3
.
return 1, 2, 3;
// becomes
return 2, 3;
// becomes
return 3;
One way would be to use a nested query:
SELECT count(*)
FROM (
SELECT COUNT(Genre) AS count
FROM movies
GROUP BY ID
HAVING (count = 4)
) AS x
The inner query gets all the movies that have exactly 4 genres, then outer query counts how many rows the inner query returned.
A really simple implementation is:
out = "".join(c for c in asking if c not in ('!','.',':'))
and keep adding any other types of punctuation.
A more efficient way would be
import string
stringIn = "string.with.punctuation!"
out = stringIn.translate(stringIn.maketrans("",""), string.punctuation)
Edit: There is some more discussion on efficiency and other implementations here: Best way to strip punctuation from a string in Python
Slightly off topic:
I found this question while looking for a way to format a number as currency, like so:
$100
($50) # negative numbers without '-' and in parens
I ended up doing:
{% if var >= 0 %} ${{ var|stringformat:"d" }}
{% elif var < 0 %} $({{ var|stringformat:"d"|cut:"-" }})
{% endif %}
You could also do, e.g. {{ var|stringformat:"1.2f"|cut:"-" }}
to display as $50.00
(with 2 decimal places if that's what you want.
Perhaps slightly on the hacky side, but maybe someone else will find it useful.
public abstract class Refl {
/** Use: Refl.<TargetClass>get(myObject,"x.y[0].z"); */
public static<T> T get(Object obj, String fieldPath) {
return (T) getValue(obj, fieldPath);
}
public static Object getValue(Object obj, String fieldPath) {
String[] fieldNames = fieldPath.split("[\\.\\[\\]]");
String success = "";
Object res = obj;
for (String fieldName : fieldNames) {
if (fieldName.isEmpty()) continue;
int index = toIndex(fieldName);
if (index >= 0) {
try {
res = ((Object[])res)[index];
} catch (ClassCastException cce) {
throw new RuntimeException("cannot cast "+res.getClass()+" object "+res+" to array, path:"+success, cce);
} catch (IndexOutOfBoundsException iobe) {
throw new RuntimeException("bad index "+index+", array size "+((Object[])res).length +" object "+res +", path:"+success, iobe);
}
} else {
Field field = getField(res.getClass(), fieldName);
field.setAccessible(true);
try {
res = field.get(res);
} catch (Exception ee) {
throw new RuntimeException("cannot get value of ["+fieldName+"] from "+res.getClass()+" object "+res +", path:"+success, ee);
}
}
success += fieldName + ".";
}
return res;
}
public static Field getField(Class<?> clazz, String fieldName) {
Class<?> tmpClass = clazz;
do {
try {
Field f = tmpClass.getDeclaredField(fieldName);
return f;
} catch (NoSuchFieldException e) {
tmpClass = tmpClass.getSuperclass();
}
} while (tmpClass != null);
throw new RuntimeException("Field '" + fieldName + "' not found in class " + clazz);
}
private static int toIndex(String s) {
int res = -1;
if (s != null && s.length() > 0 && Character.isDigit(s.charAt(0))) {
try {
res = Integer.parseInt(s);
if (res < 0) {
res = -1;
}
} catch (Throwable t) {
res = -1;
}
}
return res;
}
}
It supports fetching fields and array items, e.g.:
System.out.println(""+Refl.getValue(b,"x.q[0].z.y"));
there is no difference between dots and braces, they are just delimiters, and empty field names are ignored:
System.out.println(""+Refl.getValue(b,"x.q[0].z.y[value]"));
System.out.println(""+Refl.getValue(b,"x.q.1.y.z.value"));
System.out.println(""+Refl.getValue(b,"x[q.1]y]z[value"));
Just to contribute with my approach. As already answered, RetryPolicy
is the way to go. But if you need a policy different the than default for all your requests, you can set it in a base Request class, so you don't need to set the policy for all the instances of your requests.
Something like this:
public class BaseRequest<T> extends Request<T> {
public BaseRequest(int method, String url, Response.ErrorListener listener) {
super(method, url, listener);
setRetryPolicy(getMyOwnDefaultRetryPolicy());
}
}
In my case I have a GsonRequest which extends from this BaseRequest, so I don't run the risk of forgetting to set the policy for an specific request and you can still override it if some specific request requires to.
first you should make sure that you are put your python path in your system variables .. Then try run this
python -m pip install jupyter --user
and then run this
py -m notebook or jupyter notebook
The easiest way would be:
String[] myArray = ...;
List<String> strs = Arrays.asList(myArray);
using the handy Arrays utility class. Note, that you can even do
List<String> strs = Arrays.asList("a", "b", "c");
This is an update of Baz1nga's answer. Since options.data
is not an object but a string I just resorted to concatenating the timestamp:
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (originalOptions.type == "post" || options.type == "post") {
if (options.data && options.data.length)
options.data += "&";
else
options.data = "";
options.data += "timeStamp=" + new Date().getTime();
}
});
move
in windows is equivalent of mv
command in Linux
del
in windows is equivalent of rm
command in Linux
You could try a formatter like this
They will always be limited because they don't (and can't) know what user defined functions you may have defined in your database (or which built-in functions you have or don't have access to).
You could also look at ANTLR (but that would be an offline solution)
Gmail: OAuth
Client ID
and Secret ID
. Finally click OK to close the credentials pop up.Google API
. Click on Overview in the left pane.Google API
under Social APIs section.That’s all from the Google part.
Come back to your application, open App_start/Startup.Auth.cs
and uncomment the following snippet
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = "",
ClientSecret = ""
});
Update the ClientId
and ClientSecret
with the values from Google API
credentials which you have created already.
Gmail
id.Gmail
id into your application database.As the other answers have described, lit
and typedLit
are how to add constant columns to DataFrames. lit
is an important Spark function that you will use frequently, but not for adding constant columns to DataFrames.
You'll commonly be using lit
to create org.apache.spark.sql.Column
objects because that's the column type required by most of the org.apache.spark.sql.functions
.
Suppose you have a DataFrame with a some_date
DateType column and would like to add a column with the days between December 31, 2020 and some_date
.
Here's your DataFrame:
+----------+
| some_date|
+----------+
|2020-09-23|
|2020-01-05|
|2020-04-12|
+----------+
Here's how to calculate the days till the year end:
val diff = datediff(lit(Date.valueOf("2020-12-31")), col("some_date"))
df
.withColumn("days_till_yearend", diff)
.show()
+----------+-----------------+
| some_date|days_till_yearend|
+----------+-----------------+
|2020-09-23| 99|
|2020-01-05| 361|
|2020-04-12| 263|
+----------+-----------------+
You could also use lit
to create a year_end
column and compute the days_till_yearend
like so:
import java.sql.Date
df
.withColumn("yearend", lit(Date.valueOf("2020-12-31")))
.withColumn("days_till_yearend", datediff(col("yearend"), col("some_date")))
.show()
+----------+----------+-----------------+
| some_date| yearend|days_till_yearend|
+----------+----------+-----------------+
|2020-09-23|2020-12-31| 99|
|2020-01-05|2020-12-31| 361|
|2020-04-12|2020-12-31| 263|
+----------+----------+-----------------+
Most of the time, you don't need to use lit
to append a constant column to a DataFrame. You just need to use lit
to convert a Scala type to a org.apache.spark.sql.Column
object because that's what's required by the function.
See the datediff
function signature:
As you can see, datediff
requires two Column arguments.
@eldar: I had the same issue with 3.6.7 running in 'normal mode'; and neither triggerSave or save() were working.
I changed to the jQuery TinyMCE plugin and without having to do anything else it's working now. I'm assuming somewhere along the line they implemented some kind of auto triggerSave for the jQuery version of TinyMCE.
td {
padding: npx; /* For cellpadding */
margin: npx; /* For cellspacing */
border-collapse: collapse; /* For showing borders in a better shape. */
}
If margin
didn't work, try to set display
of tr
to block
and then margin will work.
It's not about a plugin. It's about prompt tricks in the shell.
For a cool setup in bash, check out the dotfiles
project of this guy:
https://github.com/mathiasbynens/dotfiles
To get a fancy prompt, include the .bash_prompt
in your ~/.bash_profile
or ~/.bashrc
.
To get the exact same prompt as in your question, change the export PS1
line at the end of .bash_prompt
like this:
export PS1="\[${BOLD}${MAGENTA}\]\u\[$WHITE\]@\[$ORANGE\]\h\[$WHITE\]: [\[$GREEN\]\w\[$WHITE\]\$([[ -n \$(git branch 2> /dev/null) ]] && echo \" - \")\[$PURPLE\]\$(parse_git_branch)\[$WHITE\]] \$ \[$RESET\]"
I ended up using all the .bash*
files from this repository about a month ago, and it's been really useful for me.
For Git, there are extra goodies in .gitconfig
.
And since you're a mac user, there are even more goodies in .osx
.
I moved my Database First DataModel to a different project midway through development. Poor planning (or lack there of) on my part.
Initially I had a solution with one project. Then I added another project to the solution and recreated my Database First DataModel from the Sql Server Dataase.
To fix the problem - MetadataException when using Entity Framework Entity Connection. I copied my the ConnectionString from the new Project Web.Config to the original project Web.Config. However, this occurred after I updated my all the references in the original project to new DataModel project.
I don't have enough reputation to reply to @complex857 solution. It works great, but I had to add ; at the end of the Content-Disposition header. Without it the browser adds two dashes at the end of the filename (e.g. instead of "export.csv" the file gets saved as "export.csv--"). Probably it tries to sanitize \r\n at the end of the header line.
Correct line should look like this:
header('Content-Disposition: attachment;filename="'.$filename.'";');
In case when CSV has UTF-8 chars in it, you have to change the encoding to UTF-8 by changing the Content-Type line:
header('Content-Type: application/csv; charset=UTF-8');
Also, I find it more elegant to use rewind() instead of fseek():
rewind($f);
Thanks for your solution!
You can do this with bash also:
#!/bin/bash
PGPASSWORD='' psql -h 127.0.0.1 -Upostgres sng --tuples-only --command "SELECT 'TRUNCATE TABLE ' || schemaname || '.' || tablename || ';' FROM pg_tables WHERE schemaname in ('cms_test', 'ids_test', 'logs_test', 'sps_test');" |
tr "\\n" " " |
xargs -I{} psql -h 127.0.0.1 -Upostgres sng --command "{}"
You will need to adjust schema names, passwords and usernames to match your schemas.
Once I'd discovered all the information of how my client was handling the encryption/decryption at their end it was straight forward using the AesManaged example suggested by dtb.
The finally implemented code started like this:
try
{
// Create a new instance of the AesManaged class. This generates a new key and initialization vector (IV).
AesManaged myAes = new AesManaged();
// Override the cipher mode, key and IV
myAes.Mode = CipherMode.ECB;
myAes.IV = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // CRB mode uses an empty IV
myAes.Key = CipherKey; // Byte array representing the key
myAes.Padding = PaddingMode.None;
// Create a encryption object to perform the stream transform.
ICryptoTransform encryptor = myAes.CreateEncryptor();
// TODO: perform the encryption / decryption as required...
}
catch (Exception ex)
{
// TODO: Log the error
throw ex;
}
Be careful to realize that there are some differences between OneToOneField(SomeModel)
and ForeignKey(SomeModel, unique=True)
. As stated in The Definitive Guide to Django:
OneToOneField
A one-to-one relationship. Conceptually, this is similar to a
ForeignKey
withunique=True
, but the "reverse" side of the relation will directly return a single object.
In contrast to the OneToOneField
"reverse" relation, a ForeignKey
"reverse" relation returns a QuerySet
.
For example, if we have the following two models (full model code below):
Car
model uses OneToOneField(Engine)
Car2
model uses ForeignKey(Engine2, unique=True)
From within python manage.py shell
execute the following:
OneToOneField
Example>>> from testapp.models import Car, Engine
>>> c = Car.objects.get(name='Audi')
>>> e = Engine.objects.get(name='Diesel')
>>> e.car
<Car: Audi>
ForeignKey
with unique=True
Example>>> from testapp.models import Car2, Engine2
>>> c2 = Car2.objects.get(name='Mazda')
>>> e2 = Engine2.objects.get(name='Wankel')
>>> e2.car2_set.all()
[<Car2: Mazda>]
from django.db import models
class Engine(models.Model):
name = models.CharField(max_length=25)
def __unicode__(self):
return self.name
class Car(models.Model):
name = models.CharField(max_length=25)
engine = models.OneToOneField(Engine)
def __unicode__(self):
return self.name
class Engine2(models.Model):
name = models.CharField(max_length=25)
def __unicode__(self):
return self.name
class Car2(models.Model):
name = models.CharField(max_length=25)
engine = models.ForeignKey(Engine2, unique=True, on_delete=models.CASCADE)
def __unicode__(self):
return self.name
I could solve this problem by adding the following content to my CSS file:
.ui-autocomplete {
max-height: 200px;
overflow-y: auto;
overflow-x: hidden;
}
use your code within
<script type="text/javascript">
function window.onload()
{
var d = new Date()
var gmtOffSet = -d.getTimezoneOffset();
var gmtHours = Math.floor(gmtOffSet / 60);
var GMTMin = Math.abs(gmtOffSet % 60);
var dot = ".";
var retVal = "" + gmtHours + dot + GMTMin;
document.getElementById('<%= offSet.ClientID%>').value = retVal;
}
</script>
The follow fix work for me
Windos server 2003 64 Reporting Services Windows Vista and Windows XP
Fix KB967511 and KB953752
http://support.microsoft.com/kb/967511/es
work for me
var val = $("#checkboxId").is(":checked");
you could do:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def rgb_to_gray(img):
grayImage = np.zeros(img.shape)
R = np.array(img[:, :, 0])
G = np.array(img[:, :, 1])
B = np.array(img[:, :, 2])
R = (R *.299)
G = (G *.587)
B = (B *.114)
Avg = (R+G+B)
grayImage = img
for i in range(3):
grayImage[:,:,i] = Avg
return grayImage
image = mpimg.imread("your_image.png")
grayImage = rgb_to_gray(image)
plt.imshow(grayImage)
plt.show()
Most times, it's not a login issue, but an issue with creating the database itself. So if there is an error creating your database, it would not be created in the first place. In which case if you tried to log in, regardless of the user, login would fail. This usually happens due to logical misinterpretation of the db context.
Visit the site in a browser and REALLY read those error logs, this can help you spot the problem with you code (usually conflicting logic problems with the model).
In my case, the code compiled fine, same login problem, while I was still downloading management studio, I went through the error log, fixed my db context constraints and site started running fine....meanwhile management studio is still downloading
Use
//$arr should be array as you mentioned as below
foreach($arr as $key=>$value){
echo $value->sm_id;
}
OR
//$arr should be array as you mentioned as below
foreach($arr as $value){
echo $value->sm_id;
}
Using the following script, based on SLaks answer, I determined that the correct answer is:
echo The name of this file is: %~n0%~x0
echo The name of this file is: %~nx0
And here is my test script:
@echo off
echo %0
echo %~0
echo %n0
echo %x0
echo %~n0
echo %dp0
echo %~dp0
pause
What I find interesting is that %nx0 won't work, given that we know the '~' char usually is used to strip/trim quotes off of a variable.
Just to be clear, you are wanting to launch a program from a batch file and then have the batch file press keys (in your example, the arrow keys) within that launched program?
If that is the case, you aren't going to be able to do that with simply a ".bat" file as the launched would stop the batch file from continuing until it terminated--
My first recommendation would be to use something like AutoHotkey or AutoIt if possible, simply because they both have active forums where you'd find countless examples of people launching applications and sending key presses not to mention tools to simply "record" what you want to do. However you said this is a work computer and you may not be able to load a 3rd party program.. but you aren't without options.
You can use Windows Scripting Host from something like a .vbs file to launch a program and send keys to that process. If you're running a version of Windows that includes PowerShell 2.0 (Windows XP with Service Pack 3, Windows Vista with Service Pack 1, Windows 7, etc.) you can use Windows Scripting Host as a COM object from your PS script or use VB's Intereact class.
The specifics of how to do it are outside the scope of this answer but you can find numerous examples using the methods I just described by searching on SO or Google.
edit: Just to help you get started you can look here:
You can use mailto
, here is the HTML code:
<a href="mailto:EMAILADDRESS">
Replace EMAILADDRESS
with your email.
On window
import os
os.system("start \"\" https://example.com")
On macOS
import os
os.system("open \"\" https://example.com")
On Linux
import os
os.system("xdg-open \"\" https://example.com")
Cross-Platform
import webbrowser
webbrowser.open('https://example.com')
You can stash your local changes first, then pull, then pop the stash.
git stash
git pull origin master
git stash pop
Anything that overrides changes from remote will have conflicts which you will have to manually resolve.
if you want to use HEX instead of RGBA, just drag a new empty .swift and add below mentioned code:
import UIKit
extension UIColor {
convenience init(rgba: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
let index = advance(rgba.startIndex, 1)
let hex = rgba.substringFromIndex(index)
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexLongLong(&hexValue) {
switch (count(hex)) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8")
}
} else {
println("Scan hex error")
}
} else {
print("Invalid RGB string, missing '#' as prefix")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
}
similarly, drag another empty .swift file and add below mentioned code:
class Colors {
let colorTop = UIColor(rgba: "##8968CD").CGColor
let colorBottom = UIColor(rgba: "#5D478B").CGColor
let gl: CAGradientLayer
init() {
gl = CAGradientLayer()
gl.colors = [ colorTop, colorBottom]
gl.locations = [ 0.0, 1.0]
}
}
after that in view controller, under class instantiate your 'Color' class like this:
let colors = Colors()
add a new function:
func refresh() {
view.backgroundColor = UIColor.clearColor()
var backgroundLayer = colors.gl
backgroundLayer.frame = view.frame
view.layer.insertSublayer(backgroundLayer, atIndex: 0)
}
state that function in viewDidLoad:
refresh()
you're done :)) using HEX is way too easy if compared to RGBA. :D
The Trace.WriteLine method is a conditionally compiled method. That means that it will only be executed if the TRACE constant is defined when the code is compiled. By default in Visual Studio, TRACE is only defined in DEBUG mode.
Right Click on the Project and Select Properties. Go to the Compile tab. Select Release mode and add TRACE to the defined preprocessor constants. That should fix the issue for you.
<!DOCTYPE html>
<html lang="en">
<head>
<!-- core CSS -->
<link href="http://webdesign9.in/css/bootstrap.min.css" rel="stylesheet">
<link href="http://webdesign9.in/css/font-awesome.min.css" rel="stylesheet">
<link href="http://webdesign9.in/css/responsive.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<![endif]-->
</head><!--/head-->
<body class="homepage">
<header id="header">
<nav class="navbar navbar-inverse" role="banner">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" title="Web Design Company in Mumbai" href="index.php"><img src="images/logo.png" alt="The Best Web Design Company in Mumbai" /></a>
</div>
<div class="collapse navbar-collapse navbar-right">
<ul class="nav navbar-nav">
<li class="active"><a href="index.php">Home</a></li>
<li><a href="about.php">About Us</a></li>
<li><a href="services.php">Services</a></li>
<li><a href="term-condition.php">Terms & Condition</a></li></li>
<li><a href="contact.php">Contact</a></li>
</ul>
</div>
</div><!--/.container-->
</nav><!--/nav-->
</header><!--/header-->
<script src="http://webdesign9.in/js/jquery.js"></script>
<script src="http://webdesign9.in/js/bootstrap.min.js"></script>
</body>
</html>
I've solved the problem by add attribute 'defer' to the 'script' element.
I have hit this issue, and have a case where I needed to hit pause() then play() but when using pause().then() I get undefined.
I found that if I started play 150ms after pause it resolved the issue. (Hopefully Google fixes soon)
playerMP3.volume = 0;
playerMP3.pause();
//Avoid the Promise Error
setTimeout(function () {
playerMP3.play();
}, 150);
If you are developing a .Net Core WebApi or WebSite you dont not need to install newtownsoft.json to perform json serialization/deserealization
Just make sure that your controller method returns a JsonResult
and call return Json(<objectoToSerialize>);
like this example
namespace WebApi.Controllers
{
[Produces("application/json")]
[Route("api/Accounts")]
public class AccountsController : Controller
{
// GET: api/Transaction
[HttpGet]
public JsonResult Get()
{
List<Account> lstAccounts;
lstAccounts = AccountsFacade.GetAll();
return Json(lstAccounts);
}
}
}
If you are developing a .Net Framework WebApi or WebSite you need to use NuGet to download and install the newtonsoft json
package
"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".
namespace WebApi.Controllers
{
[Produces("application/json")]
[Route("api/Accounts")]
public class AccountsController : Controller
{
// GET: api/Transaction
[HttpGet]
public JsonResult Get()
{
List<Account> lstAccounts;
lstAccounts = AccountsFacade.GetAll();
//This line is different !!
return new JsonConvert.SerializeObject(lstAccounts);
}
}
}
More details can be found here - https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-2.1
If you are looking for a more generalized way to apply to many columns, what you can do is to build a list of column names and pass it as the index of the grouped dataframe. In your case, for example:
columns = ['Y'+str(i) for year in range(1967, 2011)]
df.groupby('Country')[columns].agg('sum')
You can use this command to clone your repo with all the submodules:
git clone --recursive YOUR-GIT-REPO-URL
Or if you have already cloned the project, you can use:
git submodule init
git submodule update
According to Javascript Date Documentation, you can easily do this way:
var twoHoursBefore = new Date();
twoHoursBefore.setHours(twoHoursBefore.getHours() - 2);
And don't worry about if hours you set will be out of 0..23
range.
Date() object will update the date accordingly.
The Java 7 Files utility type is useful for working with files:
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.*;
public class WriteReadUtf8 {
public static void main(String[] args) throws IOException {
List<String> lines = Arrays.asList("These", "are", "lines");
Path textFile = Paths.get("foo.txt");
Files.write(textFile, lines, StandardCharsets.UTF_8);
List<String> read = Files.readAllLines(textFile, StandardCharsets.UTF_8);
System.out.println(lines.equals(read));
}
}
The Java 8 version allows you to omit the Charset argument - the methods default to UTF-8.
Well it was very simple. I was missing the format of the date in the json file, so I should write :
st = datetime.strptime(st, '%A %d %B %H %M')
because in the json file the date was like :
"start": "Friday 06 December 02:05",
When is del useful in python?
You can use it to remove a single element of an array instead of the slice syntax x[i:i+1]=[]
. This may be useful if for example you are in os.walk
and wish to delete an element in the directory. I would not consider a keyword useful for this though, since one could just make a [].remove(index)
method (the .remove
method is actually search-and-remove-first-instance-of-value).
With the information provided, I'd model the database to have the following:
...and so on, because I'd expect there to be different attributes associated with each section of the policy. Otherwise, there could be a single SECTIONS
table and in addition to the policy_id
, there'd be a section_type_code
...
Either way, this would allow you to support optional sections per policy...
I don't understand what you find unsatisfactory about this approach - this is how you store data while maintaining referential integrity and not duplicating data. The term is "normalized"...
Because SQL is SET based, it's rather alien to procedural/OO programming concepts & requires code to transition from one realm to the other. ORMs are often considered, but they don't work well in high volume, complex systems.
This is an old question, and this is somewhat subtly mentioned in the other posts, but the explanation that made this click for me is that non fast forward merges will require a separate commit.
You can do it by controlling the width of a div via css. Something roughly along these lines:
<div id="container" style="width:100%; height:50px; border:1px solid black;">
<div id="progress-bar" style="width:50%;/*change this width */
background-image:url(someImage.png);
height:45px;">
</div>
</div>
That width value can be sent in from php if you so desire.
You can use an object as a map:
var hasName = ({
"true" : "Y",
"false" : "N"
})[name];
This also scales nicely for many options
var hasName = ({
"true" : "Y",
"false" : "N",
"fileNotFound" : "O"
})[name];
(Bonus point for people getting the reference)
Note: you should use actual booleans instead of the string value "true" for your variables indicating truth values.
If you use lightweight html ux lang, check here an example, write:
div root
.onmouseover = ev => {root.style.backgroundColor='red'}
.onmouseleave = ev => {root.style.backgroundColor='initial'}
The code above performes the css :hover metatag.
Here is the complete programme please check this
static void Main(string[] args)
{
List<string> li = new List<string>();
li.Add("Ram");
li.Add("shyam");
li.Add("Ram");
li.Add("Kumar");
li.Add("Kumar");
var x = from obj in li group obj by obj into g select new { Name = g.Key, Duplicatecount = g.Count() };
foreach(var m in x)
{
Console.WriteLine(m.Name + "--" + m.Duplicatecount);
}
Console.ReadLine();
}
Shelf is a JetBrains feature while Stash is a Git feature for same work. You can switch to different branch without commit and loss of work using either of features. My personal experience is to use Shelf.
You could do:
select sum(counts) total_records from (
select count(*) as counts
from temptable
group by column_1, column_2, column_3, column_4
) as tmp
Another mysteriously unknown RDBMS. Your Syntax is perfectly fine in PostgreSQL. Other query styles may perform faster (especially the NOT EXISTS
variant or a LEFT JOIN
), but your query is perfectly legit.
Be aware of pitfalls with NOT IN
, though, when involving any NULL
values:
Variant with LEFT JOIN:
SELECT *
FROM friend f
LEFT JOIN likes l USING (id1, id2)
WHERE l.id1 IS NULL;
See @Michal's answer for the NOT EXISTS
variant.
A more detailed assessment of four basic variants:
I've been struggling recently with the implementation of complex parameter switches in a batch file so here is the result of my research. None of the provided answers are fully safe, examples:
"%1"=="-?"
will not match if the parameter is enclosed in quotes (needed for file names etc.) or will crash if the parameter is in quotes and has spaces (again often seen in file names)
@ECHO OFF
SETLOCAL
echo.
echo starting parameter test...
echo.
rem echo First parameter is %1
if "%1"=="-?" (echo Condition is true, param=%1) else (echo Condition is false, param=%1)
C:\>test.bat -?
starting parameter test...
Condition is true, param=-?
C:\>test.bat "-?"
starting parameter test...
Condition is false, param="-?"
Any combination with square brackets [%1]==[-?]
or [%~1]==[-?]
will fail in case the parameter has spaces within quotes:
@ECHO OFF
SETLOCAL
echo.
echo starting parameter test...
echo.
echo First parameter is %1
if [%~1]==[-?] (echo Condition is true, param=%1) else (echo Condition is false, param=%1)
C:\>test.bat "long file name"
starting parameter test...
First parameter is "long file name"
file was unexpected at this time.
The proposed safest solution "%~1"=="-?"
will crash with a complex parameter that includes text outside the quotes and text with spaces within the quotes:
@ECHO OFF
SETLOCAL
echo.
echo starting parameter test...
echo.
echo First parameter is %1
if "%~1"=="-?" (echo Condition is true, param=%1) else (echo Condition is false, param=%1)
C:\>test.bat -source:"long file name"
starting parameter test...
First parameter is -source:"long file name"
file was unexpected at this time.
The only way to ensure all above scenarios are covered is to use EnableDelayedExpansion and to pass the parameters by reference (not by value) using variables. Then even the most complex scenario will work fine:
@ECHO OFF
SETLOCAL EnableDelayedExpansion
echo.
echo starting parameter test...
echo.
echo First parameter is %1
:: we assign the parameter to a variable to pass by reference with delayed expansion
set "var1=%~1"
echo var1 is !var1!
:: we assign the value to compare with to a second variable to pass by reference with delayed expansion
set "var2=-source:"c:\app images"\image.png"
echo var2 is !var2!
if "!var1!"=="!var2!" (echo Condition is true, param=!var1!) else (echo Condition is false, param=!var1!)
C:\>test.bat -source:"c:\app images"\image.png
starting parameter test...
First parameter is -source:"c:\app images"\image.png
var1 is -source:"c:\app images"\image.png
var2 is -source:"c:\app images"\image.png
Condition is true, param=-source:"c:\app images"\image.png
C:\>test.bat -source:"c:\app images"\image1.png
starting parameter test...
First parameter is -source:"c:\app images"\image1.png
var1 is -source:"c:\app images"\image1.png
var2 is -source:"c:\app images"\image.png
Condition is false, param=-source:"c:\app images"\image1.png
C:\>test.bat -source:"c:\app images\image.png"
starting parameter test...
First parameter is -source:"c:\app images\image.png"
var1 is -source:"c:\app images\image.png"
var2 is -source:"c:\app images"\image.png
Condition is false, param=-source:"c:\app images\image.png"
Copy config.sample.inc.php
to config.inc.php
.
In most cases you will find the config file
/etc/phpmyadmin/config.inc.php
/Library/WebServer/Documents/phpmyadmin/config.inc.php
If you are trying to log in as root, you should have the following lines in your config:
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
You can put simply a flag variable, in this case is_successed.
def preorder_view(request, pk, template_name='preorders/preorder_form.html'):
is_successed=0
formset = PreorderHasProductsForm(request.POST)
client= get_object_or_404(Client, pk=pk)
if request.method=='POST':
#populate the form with data from the request
# formset = PreorderHasProductsForm(request.POST)
if formset.is_valid():
is_successed=1
preorder_date=formset.cleaned_data['preorder_date']
product=formset.cleaned_data['preorder_has_products']
return render(request, template_name, {'preorder_date':preorder_date,'product':product,'is_successed':is_successed,'formset':formset})
return render(request, template_name, {'object':client,'formset':formset})
afterwards in your template you can just put the code below
{%if is_successed == 1 %}
<h1>{{preorder_date}}</h1>
<h2> {{product}}</h2>
{%endif %}
I've had something similar before and used normally tags
<a href="path_of_your_pdf/your_pdf_file.pdf" tabindex="-1"><strong>click here</strong></a>
but it's interesting to find out some other ways as above!
In modern browsers you can build on top of @Sushil's answer with pure JavaScript and the DOM:
function validateEmail(value) {
var input = document.createElement('input');
input.type = 'email';
input.required = true;
input.value = value;
return typeof input.checkValidity === 'function' ? input.checkValidity() : /\S+@\S+\.\S+/.test(value);
}
I've put together an example in the fiddle http://jsfiddle.net/boldewyn/2b6d5/. Combined with feature detection and the bare-bones validation from Squirtle's Answer, it frees you from the regular expression massacre and does not bork on old browsers.
I went with "manually" using the same breakpoints in Bootstrap 4 as media queries...
/* Equal-height card images, cf. https://stackoverflow.com/a/47698201/1375163*/
.card-img-top {
/*height: 11vw;*/
object-fit: cover;
}
/* Small devices (landscape phones, 576px and up) */
@media (min-width: 576px) {
.card-img-top {
height: 19vw;
}
}
/* Medium devices (tablets, 768px and up) */
@media (min-width: 768px) {
.card-img-top {
height: 16vw;
}
}
/* Large devices (desktops, 992px and up) */
@media (min-width: 992px) {
.card-img-top {
height: 11vw;
}
}
/* Extra large devices (large desktops, 1200px and up) */
@media (min-width: 992px) {
.card-img-top {
height: 11vw;
}
}
It works, though I wish there were more native responsiveness of this sort.
Partial suggestion from @sepuckett86 and I.