I only use Elastic-search. Since I found solr is very hard to start. Elastic-search's features:
I've used this request to delete all my records but sometimes it's necessary to commit this.
For that, add &commit=true
to your request :
http://host:port/solr/core/update?stream.body=<delete><query>*:*</query></delete>&commit=true
According to SolrQuerySyntax, you can use q=-id:[* TO *]
.
We use Lucene regularly to index and search tens of millions of documents. Searches are quick enough, and we use incremental updates that do not take a long time. It did take us some time to get here. The strong points of Lucene are its scalability, a large range of features and an active community of developers. Using bare Lucene requires programming in Java.
If you are starting afresh, the tool for you in the Lucene family is Solr, which is much easier to set up than bare Lucene, and has almost all of Lucene's power. It can import database documents easily. Solr are written in Java, so any modification of Solr requires Java knowledge, but you can do a lot just by tweaking configuration files.
I have also heard good things about Sphinx, especially in conjunction with a MySQL database. Have not used it, though.
IMO, you should choose according to:
Putting together comments from a couple different answers here, in the Solr docs and on the other SO question, I found that the following syntax produces the correct result for my use case
(my_field=my_value or my_field is null):
(my_field:"my_value" OR (*:* NOT my_field:*))
This works for solr 4.1.0. This is slightly different than the use case in the OP; but, I thought that others would find it useful.
It's actually not really clearly stated in the standard (RFC 3986) whether a percent-encoded version of .
or ..
is supposed to have the same this-folder/up-a-folder meaning as the unescaped version. Section 3.3 only talks about “The path segments .
and ..
”, without clarifying whether they match .
and ..
before or after pct-encoding.
Personally I find Firefox's interpretation that %2E
does not mean .
most practical, but unfortunately all the other browsers disagree. This would mean that you can't have a path component containing only .
or ..
.
I think the only possible suggestion is “don't do that”! There are other path components that are troublesome too, typically due to server limitations: %2F
, %00
and %5C
sequences in paths may also be blocked by some web servers, and the empty path segment can also cause problems. So in general it's not possible to fit all possible byte sequences into a path component.
Try:
#!/bin/bash
# .... some previous code ...
# help set exec | less
set -- 1 2 3 4 5 # fake command line arguments
exec bash --login -c '
echo $0
echo $@
echo my script continues here
' arg0 "$@"
To summarize what was mentioned by Breno above
Say you have a variable with a path to a file
path = '/home/User/Desktop/myfile.py'
os.path.basename(path)
returns the string 'myfile.py'
and
os.path.dirname(path)
returns the string '/home/User/Desktop'
(without a trailing slash '/')
These functions are used when you have to get the filename/directory name given a full path name.
In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py'
you just have myfile.py
), os.path.dirname(path)
returns an empty string.
The value of a button element isn't the displayed text, contrary to what happens to input
elements of type button.
You can do this :
b.appendChild(document.createTextNode('test value'));
If the e.target
is the same element as this
, you've not clicked on a descendant.
$('.foobar').on('click', function(e) {_x000D_
if (e.target !== this)_x000D_
return;_x000D_
_x000D_
alert( 'clicked the foobar' );_x000D_
});
_x000D_
.foobar {_x000D_
padding: 20px; background: yellow;_x000D_
}_x000D_
span {_x000D_
background: blue; color: white; padding: 8px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class='foobar'> .foobar (alert) _x000D_
<span>child (no alert)</span>_x000D_
</div>
_x000D_
Perl really only has three types: scalars, arrays, and hashes. And even that distinction is arguable. ;) The way each variable is treated depends on what you do with it:
% perl -e "print 5.4 . 3.4;"
5.43.4
% perl -e "print '5.4' + '3.4';"
8.8
You can use these kind of programs to emulate an apache web server and run PHP on your computer:
If you are using Ubuntu or Debian and you serve .json files through Apache, you might want to serve the files with the correct content type. I am doing this primarily because I want to use the Firefox extension JSONView
The Apache module mod_mime will help to do this easily. However, with Ubuntu you need to edit the file /etc/mime.types and add the line
application/json json
Then restart Apache:
sudo service apache2 restart
It compares crash logs retrieved from the device to archived (symbolized to be correct) version of your applications to try to retrieved where on your code the crash occurred.
Look at xcode symbol file location for details
For future seekers who might have dropped simple details like me, in my case I just have forgotten to call my action function with parentheses.
actions.js:
export function addNewComponent() {
return {
type: ADD_NEW_COMPONENT,
};
}
myComponent.js:
import React, { useEffect } from 'react';
import { addNewComponent } from '../../redux/actions';
useEffect(() => {
dispatch(refreshAllComponents); // <= Here was what I've missed.
}, []);
I've forgotten to dispatch the action function with ()
. So doing this solved my issue.
useEffect(() => {
dispatch(refreshAllComponents());
}, []);
Again this might have nothing to do with OP's problem, but I hope I helps people with the same problem as mine.
Sometimes this error comes, when HTML has some commented code and browser is trying to look for something. Like in my case I had commented code for a web form in flask and I was getting this.
After spending 2 hours I fixed it in the following ways:
1) I created a new python environment and then it threw an error on the commented HTML line, before this I was only thrown error 'GET /favicon.ico HTTP/1.1" 404'
2) Sometimes, when I had a duplicate code, like python file existing with the same name, then also I saw this error, try removing those too
I have solved this problem by importing the following dependency. you must manually import httpclient
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
Constant variables cannot be changed. Static variable are private to the file and only accessible within the program code and not to anyone else.
If you need to scroll to a point of an element. You can use Jquery function to scroll it up/down.
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 'slow');
Temp tables are always on disk - so as long as your CTE can be held in memory, it would most likely be faster (like a table variable, too).
But then again, if the data load of your CTE (or temp table variable) gets too big, it'll be stored on disk, too, so there's no big benefit.
In general, I prefer a CTE over a temp table since it's gone after I used it. I don't need to think about dropping it explicitly or anything.
So, no clear answer in the end, but personally, I would prefer CTE over temp tables.
I like to use a TreeWalker if the set of elements are children of a root node.
#!/bin/bash
req=$(curl -s -X GET http://host:8080/some/resource -H "Accept: application/json") 2>&1
echo "${req}"
To set the range of the x-axis, you can use set_xlim(left, right)
, here are the docs
Update:
It looks like you want an identical plot, but only change the 'tick values', you can do that by getting the tick values and then just changing them to whatever you want. So for your need it would be like this:
ticks = your_plot.get_xticks()*10**9
your_plot.set_xticklabels(ticks)
I have use this method
function getString()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var buisnessArea = getString();
If you're using Twitter Bootstrap, you can just use the checkbox
class on the <label>
:
<label class="checkbox">
<input type="checkbox"> Remember me
</label>
As Alex Filipovici mentioned the issue was a wrong encoding. The file I read in was UTF-8-BOM
and threw the above error on Convert.FromBase64String()
. Changing to UTF-8
did work without problems.
A call to EntityManager.flush();
will force the data to be persist in the database immediately as EntityManager.persist()
will not (depending on how the EntityManager is configured : FlushModeType (AUTO or COMMIT) by default it's set to AUTO and a flush will be done automatically by if it's set to COMMIT the persitence of the data to the underlying database will be delayed when the transaction is commited).
Instead of wasting your time to design a JFrame
just to display a error message, you can use an JOptionPane
which is by default modal:
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Your message goes here!","Message", JOptionPane.ERROR_MESSAGE);
}
}
P.S. Stop using Windowbuilder if you want to learn Swing.
Another option if you are using Guava Collections is Ints.indexOf
// Perfect storm:
final int needle = 42;
final int[] haystack = [1, 2, 3, 42];
// Spoiler alert: index == 3
final int index = Ints.indexOf(haystack, needle);
This is a great choice when space, time and code reuse are at a premium. It is also very terse.
It seems you now do not need to reverse geocode and now get the address directly from ClientLocation:
google.loader.ClientLocation.address.city
pyspark version:
df = <source data>
df.printSchema()
from pyspark.sql.types import *
# Change column type
df_new = df.withColumn("myColumn", df["myColumn"].cast(IntegerType()))
df_new.printSchema()
df_new.select("myColumn").show()
def rotate(image, angle, center = None, scale = 1.0):
(h, w) = image.shape[:2]
if center is None:
center = (w / 2, h / 2)
# Perform the rotation
M = cv2.getRotationMatrix2D(center, angle, scale)
rotated = cv2.warpAffine(image, M, (w, h))
return rotated
For users of modern DataTables (1.10 and above), all the answers and examples on this page are for the old api, not the new. I had a very hard time finding a newer example but finally did find this DT forum post (TL;DR for most folks) which led me to this concise example.
The example code worked for me after I finally noticed the $() selector syntax immediately surrounding the html string. You have to add a node not a string.
That example really is worth looking at but, in the spirit of SO, if you just want to see a snippet of code that works:
var table = $('#example').DataTable();
table.rows.add( $(
'<tr>'+
' <td>Tiger Nixon</td>'+
' <td>System Architect</td>'+
' <td>Edinburgh</td>'+
' <td>61</td>'+
' <td>2011/04/25</td>'+
' <td>$3,120</td>'+
'</tr>'
) ).draw();
The careful reader might note that, since we are adding only one row of data, that table.row.add(...) should work as well and did for me.
Try this which uses globs rather than regular expressions so it will only pick out the file names that end in .dbf
filenames <- Sys.glob("*.dbf")
Just create hide and show methods yourself for all elements, as follows
Element.prototype.hide = function() {
this.style.display = 'none';
}
Element.prototype.show = function() {
this.style.display = '';
}
After this you can use the methods with the usual element identifiers like in these examples:
document.getElementByTagName('div')[3].hide();
document.getElementById('thing').show();
or:
<img src="removeME.png" onclick="this.hide()">
I ran into this related issue even after having already successfully run composer. I updated composer, and when running composer install
or php composer.phar install
I got:
...failed to open stream: Permission denied...
It turns out after much research that the previous answers regarding changing permissions for the folder worked. They are just slightly different directories now.
In my install, on OS X, the cache file is in /Users/[USER]/.composer/cache
, and I was having trouble because the cache file was owned by root. Changing ownership of '.composer' recursively to my user solved the issue.
This is what I did:
sudo chown -R [USER] cache
Then I ran the composer install again and voila!
Static memory allocation. Memory allocated will be in stack.
int a[10];
Dynamic memory allocation. Memory allocated will be in heap.
int *a = malloc(sizeof(int) * 10);
and the latter should be freed since there is no Garbage Collector(GC) in C.
free(a);
You can use GetCustomAttributesData()
and GetCustomAttributes()
:
var attributeData = typeof(Book).GetProperty("Name").GetCustomAttributesData();
var attributes = typeof(Book).GetProperty("Name").GetCustomAttributes(false);
basically inline-table
is for element table, I guess what you really need here is inline-block
, if you have to use inline-table
anyway, try it this way:
<div style="width:50%; display:inline-table;">A</div><!--
--><div style="width:50%; display:inline-table;">B</div>
I am assuming that you are making a quiz kind of application. For this kind of application I have written a function which is as follows:
def shuffle(q):
"""
The input of the function will
be the dictionary of the question
and answers. The output will
be a random question with answer
"""
selected_keys = []
i = 0
while i < len(q):
current_selection = random.choice(q.keys())
if current_selection not in selected_keys:
selected_keys.append(current_selection)
i = i+1
print(current_selection+'? '+str(q[current_selection]))
If I will give the input of questions = {'VENEZUELA':'CARACAS', 'CANADA':'TORONTO'}
and call the function shuffle(questions)
Then the output will be as follows:
VENEZUELA? CARACAS CANADA? TORONTO
You can extend this further more by shuffling the options also
The following also works:
select dump(a,1016), a from (
SELECT REGEXP_REPLACE (
CONVERT (
'3735844533120%$03 ',
'US7ASCII',
'WE8ISO8859P1'),
'[^!@/\.,;:<>#$%&()_=[:alnum:][:blank:]]') a
FROM DUAL);
this workes for me:
private int GetaRandom()
{
Thread.Sleep(1);
return new Random(DateTime.Now.Millisecond).Next();
}
probably overkill, I often use this UDF:
CREATE FUNCTION [dbo].[f_pad_before](@string VARCHAR(255), @desired_length INTEGER, @pad_character CHAR(1))
RETURNS VARCHAR(255) AS
BEGIN
-- Prefix the required number of spaces to bulk up the string and then replace the spaces with the desired character
RETURN ltrim(rtrim(
CASE
WHEN LEN(@string) < @desired_length
THEN REPLACE(SPACE(@desired_length - LEN(@string)), ' ', @pad_character) + @string
ELSE @string
END
))
END
So that you can do things like:
select dbo.f_pad_before('aaa', 10, '_')
__VA_ARGS__
is the standard way to do it. Don't use compiler-specific hacks if you don't have to.
I'm really annoyed that I can't comment on the original post. In any case, C++ is not a superset of C. It is really silly to compile your C code with a C++ compiler. Don't do what Donny Don't does.
pretty sure you just want the plain old replace function. use like this:
myString.replace('username1','');
i suppose if you want to remove the trailing comma do this instead:
myString.replace('username1,','');
edit:
here is your site specific code:
jQuery("#post_like_list-510").text().replace(...)
You can add full text to an existing instance by changing the SQL Server program in Programs and Features. Follow the steps below. You might need the original disk or ISO for the installation to complete. (Per HotN's comment: If you have SQL Server Express, make sure it is SQL Server Express With Advanced Services.)
Directions:
On the Installation Type screen, select the appropriate SQL Server instance.
Advance through the rest of the wizard.
Source (with screenshots): http://www.techrepublic.com/blog/networking/adding-sql-full-text-search-to-an-existing-sql-server/5546
$image_folder = APPPATH . "../images/owner_profile/" . $_POST ['mob_no'] [0] . $na;
if (isset ( $_FILES ['image'] ) && $_FILES ['image'] ['error'] == 0) {
list ( $a, $b ) = explode ( '.', $_FILES ['image'] ['name'] );
$b = end ( explode ( '.', $_FILES ['image'] ['name'] ) );
$up = move_uploaded_file ( $_FILES ['image'] ['tmp_name'], $image_folder . "." . $b );
$path = ($_POST ['mob_no'] [0] . $na . "." . $b);
I'm not sure if you can alter the original element but how about switch from using the id attr to something else like data-id? Then just read the value of data-id for your hash value and it won't jump.
You can use white-space: nowrap;
to define this behaviour:
// HTML:
.nowrap {_x000D_
white-space: nowrap ;_x000D_
}
_x000D_
<p>_x000D_
<span class="nowrap">How do I wrap this line of text</span>_x000D_
<span class="nowrap">- asked by Peter 2 days ago</span>_x000D_
</p>
_x000D_
// CSS:
.nowrap {
white-space: nowrap ;
}
ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
Try it like this
public OnClickListener moreListener = new OnClickListener() {
@Override
public void onClick(View v) {
adapter = null;
myStringArray1.add("Andrea");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
In javascript use the preventDefault() method of the event args parameter.
<a href="no-script.html">Download now!</a>
$('a').click(function(e) {
e.preventDefault(); // stop the browser from following
window.location.href = 'downloads/file.pdf';
});
Typically, you can copy the .classpath file from a working project since there isn’t anything project specific here assuming you’re structured as a standard Maven project.
This may also happen when you have a submodule pointing to a repository that was rebased and the given commit is "gone". While the commit may still be in the remote repository, it is not in a branch. If you can't create a new branch (e.g. not your repository), you're stuck with having to update the super project to point to a new commit. Alternatively you can push one of your copies of the submodules elsewhere and then update the super-project to point to that repository instead.
I used maptoInt() with Lambda operation for converting string to Integer
int[] arr = Arrays.stream(stringArray).mapToInt(item -> Integer.parseInt(item)).toArray();
I use the following on win32/linux(32/64 bit):
#include <iostream>
#include <iomanip>
template <typename T>
std::string HexToString(T uval)
{
std::stringstream ss;
ss << "0x" << std::setw(sizeof(uval) * 2) << std::setfill('0') << std::hex << +uval;
return ss.str();
}
Multi purpose function for thread
public enum QueueType {
case Main
case Background
case LowPriority
case HighPriority
var queue: DispatchQueue {
switch self {
case .Main:
return DispatchQueue.main
case .Background:
return DispatchQueue(label: "com.app.queue",
qos: .background,
target: nil)
case .LowPriority:
return DispatchQueue.global(qos: .userInitiated)
case .HighPriority:
return DispatchQueue.global(qos: .userInitiated)
}
}
}
func performOn(_ queueType: QueueType, closure: @escaping () -> Void) {
queueType.queue.async(execute: closure)
}
Use it like :
performOn(.Background) {
//Code
}
You might also want to check for Heroku telling you there's a typo in your CSS file.
Read through the long boring messages in the terminal closely after you push. There may be something like this: Invalid CSS after
. It means Heroku has found a typo and you need to fix it in the CSS file.
You can do a find for rake aborted!
and directly after that it should say why the push failed.
Here is an article (with source code) that explains how to determine and use localized time in an ASP.NET (VB.NET, C#) application:
In short, the described approach relies on the JavaScript getTimezoneOffset
function, which returns the value that is saved in the session cookie and used by code-behind to adjust time values between GMT and local time. The nice thing is that the user does not need to specify the time zone (the code does it automatically). There is more involved (this is why I link to the article), but provided code makes it really easy to use. I suspect that you can convert the logic to PHP and other languages (as long as you understand ASP.NET).
Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.
$("legend").each(function() {
var SoftwareItem = $(this).text();
itemCost = GetItemCost(SoftwareItem);
$("input:checked").each(function() {
var Component = $(this).next("label").text();
itemCost += GetItemCost(Component);
});
$(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
});
Its an XML namespace. It is required when you use XHTML 1.0 or 1.1 doctypes or application/xhtml+xml mimetypes.
You should be using HTML5 doctype, then you don't need it for text/html. Better start from template like this :
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>domcument title</title>
<link rel="stylesheet" href="/stylesheet.css" type="text/css" />
</head>
<body>
<!-- your html content -->
<script src="/script.js"></script>
</body>
</html>
When you have put your Doctype straight - do and validate you html and your css .
That usually will sove you layout issues.
vi can show all characters.
Yes, this is an old question. But it's misleading, as this was the first result in my search, and both the answers aren't correct anymore.
You can change your Github account name at any time.
To do this, click your profile picture > Settings
> Account Settings
> Change Username
.
Links to your repositories will redirect to the new URLs, but they should be updated on other sites because someone who chooses your abandoned username can override the links. Links to your profile page will be 404'd.
For more information, see the official help page.
And furthermore, if you want to change your username to something else, but that specific username is being taken up by someone else who has been completely inactive for the entire time their account has existed, you can report their account for name squatting.
Quick One. Simple, clean and consistent format if that is what you want
$pw = chr(mt_rand(97,122)).mt_rand(0,9).chr(mt_rand(97,122)).mt_rand(10,99).chr(mt_rand(97,122)).mt_rand(100,999);
Just to build upon solving the namespace issues, in my case I've been running into documents with multiple namespaces and needed to handle namespaces properly. I wrote the function below to get a namespace manager to deal with any namespace in the document:
private XmlNamespaceManager GetNameSpaceManager(XmlDocument xDoc)
{
XmlNamespaceManager nsm = new XmlNamespaceManager(xDoc.NameTable);
XPathNavigator RootNode = xDoc.CreateNavigator();
RootNode.MoveToFollowing(XPathNodeType.Element);
IDictionary<string, string> NameSpaces = RootNode.GetNamespacesInScope(XmlNamespaceScope.All);
foreach (KeyValuePair<string, string> kvp in NameSpaces)
{
nsm.AddNamespace(kvp.Key, kvp.Value);
}
return nsm;
}
Update 2018-11-28:
Here is a summary of experiments with Python 2 and 3. With
main.py - runs foo.py
foo.py - runs lib/bar.py
lib/bar.py - prints filepath expressions
| Python | Run statement | Filepath expression |
|--------+---------------------+----------------------------------------|
| 2 | execfile | os.path.abspath(inspect.stack()[0][1]) |
| 2 | from lib import bar | __file__ |
| 3 | exec | (wasn't able to obtain it) |
| 3 | import lib.bar | __file__ |
For Python 2, it might be clearer to switch to packages so can use from lib import bar
- just add empty __init__.py
files to the two folders.
For Python 3, execfile
doesn't exist - the nearest alternative is exec(open(<filename>).read())
, though this affects the stack frames. It's simplest to just use import foo
and import lib.bar
- no __init__.py
files needed.
See also Difference between import and execfile
Original Answer:
Here is an experiment based on the answers in this thread - with Python 2.7.10 on Windows.
The stack-based ones are the only ones that seem to give reliable results. The last two have the shortest syntax, i.e. -
print os.path.abspath(inspect.stack()[0][1]) # C:\filepaths\lib\bar.py
print os.path.dirname(os.path.abspath(inspect.stack()[0][1])) # C:\filepaths\lib
Here's to these being added to sys as functions! Credit to @Usagi and @pablog
Based on the following three files, and running main.py from its folder with python main.py
(also tried execfiles with absolute paths and calling from a separate folder).
C:\filepaths\main.py: execfile('foo.py')
C:\filepaths\foo.py: execfile('lib/bar.py')
C:\filepaths\lib\bar.py:
import sys
import os
import inspect
print "Python " + sys.version
print
print __file__ # main.py
print sys.argv[0] # main.py
print inspect.stack()[0][1] # lib/bar.py
print sys.path[0] # C:\filepaths
print
print os.path.realpath(__file__) # C:\filepaths\main.py
print os.path.abspath(__file__) # C:\filepaths\main.py
print os.path.basename(__file__) # main.py
print os.path.basename(os.path.realpath(sys.argv[0])) # main.py
print
print sys.path[0] # C:\filepaths
print os.path.abspath(os.path.split(sys.argv[0])[0]) # C:\filepaths
print os.path.dirname(os.path.abspath(__file__)) # C:\filepaths
print os.path.dirname(os.path.realpath(sys.argv[0])) # C:\filepaths
print os.path.dirname(__file__) # (empty string)
print
print inspect.getfile(inspect.currentframe()) # lib/bar.py
print os.path.abspath(inspect.getfile(inspect.currentframe())) # C:\filepaths\lib\bar.py
print os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # C:\filepaths\lib
print
print os.path.abspath(inspect.stack()[0][1]) # C:\filepaths\lib\bar.py
print os.path.dirname(os.path.abspath(inspect.stack()[0][1])) # C:\filepaths\lib
print
Your problem seams to be located here:
SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(Voucher_No,LEN(@startFrom)+1,LEN(Voucher_No)- LEN(@Prefix)) AS INT)) AS varchar(100)) FROM dbo.Journal_Entry;
SET @sCode=CAST(@maxCode AS INT)
As the error says, you're casting a string that contains a letter 'J' to an INT
which for obvious reasons is not possible.
Either fix SUBSTRING
or don't store the letter 'J' in the database and only prepend it when reading.
Replace a hard coded version to + example:
implementation 'com.google.android.gms:play-services-base:+'
implementation 'com.google.android.gms:play-services-maps:+'
if(!$('#select-box').find("option:contains('" + thevalue + "')").length){_x000D_
//do stuff_x000D_
}
_x000D_
According to the documentation you can simply return false;
to break:
$(xml).find("strengths").each(function() {
if (iWantToBreak)
return false;
});
Demo: http://jsfiddle.net/u1s62Lj8/1/
You need the jQuery and Boostrap Javascript files included in your HTML page for the toggle to work. (Make sure you include jQuery before Bootstrap.)
<html>
<head>
// stylesheets here
<link rel="stylesheet" href=""/>
</head>
<body>
//your html code here
// js scripts here
// note jquery tag has to go before boostrap
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
</body>
</html>
Since glibc version 2.17, the library linking -lrt
is no longer required.
The clock_*
are now part of the main C library. You can see the change history of glibc 2.17 where this change was done explains the reason for this change:
+* The `clock_*' suite of functions (declared in <time.h>) is now available
+ directly in the main C library. Previously it was necessary to link with
+ -lrt to use these functions. This change has the effect that a
+ single-threaded program that uses a function such as `clock_gettime' (and
+ is not linked with -lrt) will no longer implicitly load the pthreads
+ library at runtime and so will not suffer the overheads associated with
+ multi-thread support in other code such as the C++ runtime library.
If you decide to upgrade glibc, then you can check the compatibility tracker of glibc if you are concerned whether there would be any issues using the newer glibc.
To check the glibc version installed on the system, run the command:
ldd --version
(Of course, if you are using old glibc (<2.17) then you will still need -lrt
.)
You use the alter table ... change ...
method, for example:
mysql> create table yar (id int);
Query OK, 0 rows affected (0.01 sec)
mysql> insert into yar values(5);
Query OK, 1 row affected (0.01 sec)
mysql> alter table yar change id id varchar(255);
Query OK, 1 row affected (0.03 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> desc yar;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id | varchar(255) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
1 row in set (0.00 sec)
You don't need CURL for that... Too much overhead for just wanting to check if a file exists or not...
Use PHP's get_header.
$headers=get_headers($url);
Then check if $result[0] contains 200 OK (which means the file is there)
A function to check if a URL works could be this:
function UR_exists($url){
$headers=get_headers($url);
return stripos($headers[0],"200 OK")?true:false;
}
/* You can test a URL like this (sample) */
if(UR_exists("http://www.amazingjokes.com/"))
echo "This page exists";
else
echo "This page does not exist";
The methods within org.apache.commons.io.FileUtils
may also be very handy, e.g.:
/**
* Reads the contents of a file line by line to a List
* of Strings using the default encoding for the VM.
*/
static List readLines(File file)
I'd say @Wim is right. You should use ToString()
for logfiles - assuming a technical audience - and Message
, if at all, to display to the user. One could argue that even that is not suitable for a user, for every exception type and occurance out there (think of ArgumentExceptions, etc.).
Also, in addition to the StackTrace, ToString()
will include information you will not get otherwise. For example the output of fusion, if enabled to include log messages in exception "messages".
Some exception types even include additional information (for example from custom properties) in ToString()
, but not in the Message.
It's too late, but just to update I got it done with below syntax
import org.hamcrest.core.StringContains;
import org.junit.Assert;
Assert.assertThat("this contains test", StringContains.containsString("test"));
subprocess.call
Automatically waits , you can also use:
p1.wait()
The simplest and most elegant way is as follows:
all(x==myList[0] for x in myList)
(Yes, this even works with the empty list! This is because this is one of the few cases where python has lazy semantics.)
Regarding performance, this will fail at the earliest possible time, so it is asymptotically optimal.
You can compute pairwise cosine similarity on the rows of a sparse matrix directly using sklearn. As of version 0.17 it also supports sparse output:
from sklearn.metrics.pairwise import cosine_similarity
from scipy import sparse
A = np.array([[0, 1, 0, 0, 1], [0, 0, 1, 1, 1],[1, 1, 0, 1, 0]])
A_sparse = sparse.csr_matrix(A)
similarities = cosine_similarity(A_sparse)
print('pairwise dense output:\n {}\n'.format(similarities))
#also can output sparse matrices
similarities_sparse = cosine_similarity(A_sparse,dense_output=False)
print('pairwise sparse output:\n {}\n'.format(similarities_sparse))
Results:
pairwise dense output:
[[ 1. 0.40824829 0.40824829]
[ 0.40824829 1. 0.33333333]
[ 0.40824829 0.33333333 1. ]]
pairwise sparse output:
(0, 1) 0.408248290464
(0, 2) 0.408248290464
(0, 0) 1.0
(1, 0) 0.408248290464
(1, 2) 0.333333333333
(1, 1) 1.0
(2, 1) 0.333333333333
(2, 0) 0.408248290464
(2, 2) 1.0
If you want column-wise cosine similarities simply transpose your input matrix beforehand:
A_sparse.transpose()
Try
$("#link1").text()
to access the text inside your element. The # indicates you're searching by id. You aren't looking for a child element, so you don't need children(). Instead you want to access the text inside the element your jQuery function returns.
You should add a line with:
*.pyc
to the .gitignore
file in the root folder of your git repository tree right after repository initialization.
As ralphtheninja said, if you forgot to to do it beforehand, if you just add the line to the .gitignore
file, all previously committed .pyc
files will still be tracked, so you'll need to remove them from the repository.
If you are on a Linux system (or "parents&sons" like a MacOSX), you can quickly do it with just this one line command that you need to execute from the root of the repository:
find . -name "*.pyc" -exec git rm -f "{}" \;
This just means:
starting from the directory i'm currently in, find all files whose name ends with extension
.pyc
, and pass file name to the commandgit rm -f
After *.pyc
files deletion from git as tracked files, commit this change to the repository, and then you can finally add the *.pyc
line to the .gitignore
file.
(adapted from http://yuji.wordpress.com/2010/10/29/git-remove-all-pyc/)
Actually you can find very easy the day a video was created, right-click, property but remember it will only give the details of any copy date of the video but if you do click where it says DETAILS JUST there is the information you need, the original date that the archive was created on. Note that most modern devices will produce this information when you take pictures and videos but others will not.
If, like me, you want to make a function pack or something that people can download then it's very simple. Just write your function in a python file and save it as the name you want IN YOUR PYTHON DIRECTORY. Now, in your script where you want to use this, you type:
from FILE NAME import FUNCTION NAME
Note - the parts in capital letters are where you type the file name and function name.
Now you just use your function however it was meant to be.
Example:
FUNCTION SCRIPT - saved at C:\Python27 as function_choose.py
def choose(a):
from random import randint
b = randint(0, len(a) - 1)
c = a[b]
return(c)
SCRIPT USING FUNCTION - saved wherever
from function_choose import choose
list_a = ["dog", "cat", "chicken"]
print(choose(list_a))
OUTPUT WILL BE DOG, CAT, OR CHICKEN
Hoped this helped, now you can create function packs for download!
--------------------------------This is for Python 2.7-------------------------------------
You can try this simple android dialog popup library to cut the cluttered dialog code. It is very simple to use on your activity. after that you can have this code in your activity to show dialog
Pop.on(this).with().title(R.string.title).layout(R.layout.custom_pop).show();
where R.layout.custom_pop is your custom layout the way you want to decorate your dialog.
If you are using Visual Studio then yes, you can do this.
The library builder tool that comes with Visual Studio allows you to join libraries together on the command line. I don't know of any way to do this in the visual editor though.
lib.exe /OUT:compositelib.lib lib1.lib lib2.lib
Keep in mind that you must enable the @Autowired
annotation by adding element <context:annotation-config/>
into the spring configuration file. This will register the AutowiredAnnotationBeanPostProcessor
which takes care the processing of annotation.
And then you can autowire your service by using the field injection method.
public class YourController{
@Autowired
private UserService userService;
}
I found this from the post Spring @autowired annotation
In JavaScript you declare variables or functions by using the keywords var, let or function. In TypeScript classes you declare class members or methods without these keywords followed by a colon and the type or interface of that class member.
It’s just syntax sugar, there is no difference between:
var el: HTMLElement = document.getElementById('content');
and:
var el = document.getElementById('content');
On the other hand, because you specify the type you get all the information of your HTMLElement object.
I have a more compact approach:
release: DESTDIR = build/release
debug: DESTDIR = build/debug
OBJECTS_DIR = $$DESTDIR/.obj
MOC_DIR = $$DESTDIR/.moc
RCC_DIR = $$DESTDIR/.qrc
UI_DIR = $$DESTDIR/.ui
You can tailor how your object is represented as a string by implementing a __toString()
method in your class, so that when your object is type cast as a string (explicit type cast $str = (string) $myObject;
, or automatic echo $myObject
) you can control what is included and the string format.
If you only want to display your object's data, the method above would work. If you want to store your object in a session or database, you need to serialize it, so PHP knows how to reconstruct your instance.
Some code to demonstrate the difference:
class MyObject {
protected $name = 'JJ';
public function __toString() {
return "My name is: {$this->name}\n";
}
}
$obj = new MyObject;
echo $obj;
echo serialize($obj);
Output:
My name is: JJ
O:8:"MyObject":1:{s:7:"*name";s:2:"JJ";}
If you want to be correct, use INFORMATION_SCHEMA.
SELECT *
FROM information_schema.tables
WHERE table_schema = 'yourdb'
AND table_name = 'testtable'
LIMIT 1;
Alternatively, you can use SHOW TABLES
SHOW TABLES LIKE 'yourtable';
If there is a row in the resultset, table exists.
I just faced the same issue and these are the steps that I follow in order to provide Python version. I wanted to run my PySpark jobs with Python 2.7 instead of 2.6.
Go to the folder where $SPARK_HOME
is pointing to (in my case is /home/cloudera/spark-2.1.0-bin-hadoop2.7/
)
Under folder conf
, there is a file called spark-env.sh
. In case you have a file called spark-env.sh.template
you will need to copy the file to a new file called spark-env.sh
.
Edit the file and write the next three lines
export PYSPARK_PYTHON=/usr/local/bin/python2.7
export PYSPARK_DRIVER_PYTHON=/usr/local/bin/python2.7
export SPARK_YARN_USER_ENV="PYSPARK_PYTHON=/usr/local/bin/python2.7"
Save it and launch your application again :)
In that way, if you download a new Spark standalone version, you can set the Python version which you want to run PySpark to.
you all forget about quantifier n{X,} http://www.w3schools.com/jsref/jsref_regexp_nxcomma.asp
here best solution
str = str.replace(/\s{2,}/g, ' ');
Here's a one-liner I've been using:
@echo off
if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b)
echo main code here
pause
Notes:
I guess you are using an old version of hibernate. You can download the latest version, 5.2, from here.
Use this instead
echo $LINE | sed -e 's/12345678/$replace/g'
this works for me just simply remove the quotes
Is there a way to get it via $event->getComposer()->getRepositoryManager()->getAllPackages()
The solution that worked for me is that:- I moved my data.json file from src to public directory. Then used fetch API to fetch the file
fetch('./data.json').then(response => {
console.log(response);
return response.json();
}).then(data => {
// Work with JSON data here
console.log(data);
}).catch(err => {
// Do something for an error here
console.log("Error Reading data " + err);
});
The problem was that after compiling react app the fetch request looks for the file at URL "http://localhost:3000/data.json" which is actually the public directory of my react app. But unfortunately while compiling react app data.json file is not moved from src to public directory. So we have to explicitly move data.json file from src to public directory.
try this as well, when you have a invalid number error
In this a.emplid is number and b.emplid is an varchar2 so if you got to convert one of the sides
where to_char(a.emplid)=b.emplid
Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.
To get the file path from the user use this function:
Private Function get_user_specified_filepath() As String
'or use the other code example here.
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Please select the file."
get_user_specified_filepath = fd.SelectedItems(1)
End Function
Then just open the file read only and assign it to a variable:
dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)
Well,
Just worked it out. While having both installations we have two ORACLE_HOME directories and both have SQAORA32.dll files. While looking up for ORACLE_HOMe my app was getting confused..I just removed the Client oracle home entry as oracle client is by default present in oracle DB Now its working...Thanks!!
A unit test is done in (as far as possible) total isolation.
An integration test is done when the tested object or module is working like it should be, with other bits of code.
There is a problem with objects such as PACKAGE_BODY:
SELECT DBMS_METADATA.get_ddl(object_Type, object_name, owner) FROM ALL_OBJECTS WHERE OWNER = 'WEBSERVICE';
ORA-31600 invalid input value PACKAGE BODY parameter OBJECT_TYPE in function GET_DDL
ORA-06512: ?? "SYS.DBMS_METADATA", line 4018
ORA-06512: ?? "SYS.DBMS_METADATA", line 5843
ORA-06512: ?? line 1
31600. 00000 - "invalid input value %s for parameter %s in function %s"
*Cause: A NULL or invalid value was supplied for the parameter.
*Action: Correct the input value and try the call again.
SELECT DBMS_METADATA.GET_DDL(REPLACE(object_type,' ','_'), object_name, owner)
FROM all_OBJECTS
WHERE (OWNER = 'OWNER1');
Hmm..i tried everything to get url to user image.The perfect solution was fql use like this->
$fql_b = 'SELECT pic from user where uid = ' . $user_id;
$ret_obj_b = $facebook->api(array(
'method' => 'fql.query',
'query' => $fql_b,
));
$dp_url =$ret_obj_b[0]['pic'];
replace pic by big,pic_square to get other desired results. Hope IT HELPED....
It depends how easy you find the following, which uses simple String methods (in this case slice()
).
var str = "Hello World";_x000D_
str = str.slice(0, 3) + str.slice(4);_x000D_
console.log(str)
_x000D_
Yes there is:
ARRAY=()
ARRAY+=('foo')
ARRAY+=('bar')
In the context where an assignment statement is assigning a value to a shell variable or array index (see Arrays), the ‘+=’ operator can be used to append to or add to the variable's previous value.
Procedure never returns a value.You have to use a output parameter in store procedure.
ALTER PROC TESTLOGIN
@UserName varchar(50),
@password varchar(50)
@retvalue int output
as
Begin
declare @return int
set @return = (Select COUNT(*)
FROM CPUser
WHERE UserName = @UserName AND Password = @password)
set @retvalue=@return
End
Then you have to add a sqlparameter from c# whose parameter direction is out. Hope this make sense.
If you want to do the following by using JSTL Tag Libe, please follow the following steps:
[Requirement] if a number is a grater than equal 40 and lower than 50 then display "Two digit number starting with 4" otherwise "Other numbers".
[Solutions]
1. Please Add the JSTL tag lib on the top of the page.`
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>`
2. Please Write the following code
`
<c:choose>
<c:when test="${params.number >=40 && params.number <50}">
<p> Two digit number starting with 4. </p>
</c:when>
<c:otherwise>
<p> Other numbers. </p>
</c:otherwise>
</c:choose>`
File [menu] -> Settings -> maven -> importing and uncheck "use maven3 to import project"
ref: http://youtrack.jetbrains.com/issue/IDEA-98425 (which may have a few other ideas too)
Ran into this again, with IntelliJ 15 this time, which has no "use maven3 to import" option available anymore. The cause was that sometimes IntelliJ "doesn't parse maven dependencies right" and if it can't parse one of them right, it gives up on all of them, apparently. You can tell if this is the case by opening the maven projects tool window (View menu -> Tool Windows -> Maven Projects). Then expand one of your maven projects and its dependencies. If the dependencies are all underlined in red, "Houston, we have a problem".
You can actually see the real failure by mousing over the project name itself.
In my instance it said "Problems: No versions available for XXX" or "Failed to read descriptor for artifact org.xy.z" ref: https://youtrack.jetbrains.com/issue/IDEA-128846 and https://youtrack.jetbrains.com/issue/IDEA-152555
It seems in this case I was dealing with a jar that didn't have an associated pom file (in our maven nexus repo, and also my local repository). If this is also your problem, "urrent work around: if you do not actually need to use classes from that jar in your own code (for instance a transitive maven dependency only), you can actually get away with commenting it out from the pom (temporarily), maven project reload, and then uncomment it. Somehow after that point IntelliJ "remembers" its old working dependencies. Adding a maven transitive exclude temporarily might also do it, if you're running into it from transitive chain of dependencies."
Another thing that might help is to use a "newer version" of maven than the bundled 3.0.5. In order to set it up to use this as the default, close all your intellij windows, then open preferences -> build, execution and deployment -> build tools -> maven, and change the maven home directory, it should say "For default project" at the top when you adjust this, though you can adjust it for a particular project as well, as long as you "re import" after adjusting it.
Deleting your intellij cache folders (windows: HOMEPATH/.{IntellijIdea,IdeaC}XXX linux ~/.IdeaIC15) and/or uninstalling and reinstalling IntelliJ itself. This can also be done by going to File [menu] -> Invalidate Caches / Restart...
. Click invalidate and restart
. This will reindex your whole project and solve many hard-to-trace issues with IntelliJ.
print "bla: ", $myvar =~ tr{a}{b},"\n";
I don't want any dependency for this and only these worked for me on OS X. All other samples from answers here gave me Octal literal
errors.
Reset = "\x1b[0m"
Bright = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"
FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"
BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"
source: https://coderwall.com/p/yphywg/printing-colorful-text-in-terminal-when-run-node-js-script
As far as I know, there are simply two safe ways: ssh or passwd encrypted using a keystore.
cat ~/.ssh/id_rsa.pub
, paste it there, name and save it (if you have no such file, generate one for yourself by ssh-keygen -t rsa
- just Enter for all prompts);git remote set-url origin git+ssh://[email protected]/username/reponame.git
- you can check it first by git remote -v
);touch t; git add t; git commit -m "test"; git push
and confirm yes to enjoy the password-free world.If you just use git config --global credential.helper store
as others mentioned, your unencrypted passwords will be just stored in a plain text under ~/.git-credentials
which is not safe as it sounds.
Try to encrypt it as
sudo apt-get install libgnome-keyring-dev
sudo make --directory=/usr/share/doc/git/contrib/credential/gnome-keyring
git config --global credential.helper /usr/share/doc/git/contrib/credential/gnome-keyring/git-credential-gnome-keyring
git config --global credential.helper store
In this case, you are using
https://[email protected]/username/reponame.git
.
If I understand correctly, you should be able to do what you want by dropping the foreign key constraint, adding a new one (which will cascade), doing your stuff, and recreating the restricting foreign key constraint.
For example:
testing=# create table a (id integer primary key);
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "a_pkey" for table "a"
CREATE TABLE
testing=# create table b (id integer references a);
CREATE TABLE
-- put some data in the table
testing=# insert into a values(1);
INSERT 0 1
testing=# insert into a values(2);
INSERT 0 1
testing=# insert into b values(2);
INSERT 0 1
testing=# insert into b values(1);
INSERT 0 1
-- restricting works
testing=# delete from a where id=1;
ERROR: update or delete on table "a" violates foreign key constraint "b_id_fkey" on table "b"
DETAIL: Key (id)=(1) is still referenced from table "b".
-- find the name of the constraint
testing=# \d b;
Table "public.b"
Column | Type | Modifiers
--------+---------+-----------
id | integer |
Foreign-key constraints:
"b_id_fkey" FOREIGN KEY (id) REFERENCES a(id)
-- drop the constraint
testing=# alter table b drop constraint b_a_id_fkey;
ALTER TABLE
-- create a cascading one
testing=# alter table b add FOREIGN KEY (id) references a(id) on delete cascade;
ALTER TABLE
testing=# delete from a where id=1;
DELETE 1
testing=# select * from a;
id
----
2
(1 row)
testing=# select * from b;
id
----
2
(1 row)
-- it works, do your stuff.
-- [stuff]
-- recreate the previous state
testing=# \d b;
Table "public.b"
Column | Type | Modifiers
--------+---------+-----------
id | integer |
Foreign-key constraints:
"b_id_fkey" FOREIGN KEY (id) REFERENCES a(id) ON DELETE CASCADE
testing=# alter table b drop constraint b_id_fkey;
ALTER TABLE
testing=# alter table b add FOREIGN KEY (id) references a(id) on delete restrict;
ALTER TABLE
Of course, you should abstract stuff like that into a procedure, for the sake of your mental health.
Even after @Mickey Perlstein's answer and his 3 hours of detective work, it still took me a few more minutes to apply this to my own mess. In case anyone else is like me and needs a little more help, here's what was going on in my situation.
Initial GeoJsonResponse class:
from pyexample.responses import Response
class GeoJsonResponse(Response):
def __init__(self, geo_json_data):
Looks fine. No problems until you try to debug the thing, which is when you get a bunch of seemingly vague error messages like this:
from pyexample.responses import GeoJsonResponse ..\pyexample\responses\GeoJsonResponse.py:12: in (module) class GeoJsonResponse(Response):
E TypeError: module() takes at most 2 arguments (3 given)
=================================== ERRORS ====================================
___________________ ERROR collecting tests/test_geojson.py ____________________
test_geojson.py:2: in (module) from pyexample.responses import GeoJsonResponse ..\pyexample\responses \GeoJsonResponse.py:12: in (module)
class GeoJsonResponse(Response): E TypeError: module() takes at most 2 arguments (3 given)
ERROR: not found: \PyExample\tests\test_geojson.py::TestGeoJson::test_api_response
C:\Python37\lib\site-packages\aenum__init__.py:163
(no name 'PyExample\ tests\test_geojson.py::TestGeoJson::test_api_response' in any of [])
The errors were doing their best to point me in the right direction, and @Mickey Perlstein's answer was dead on, it just took me a minute to put it all together in my own context:
I was importing the module:
from pyexample.responses import Response
when I should have been importing the class:
from pyexample.responses.Response import Response
Hope this helps someone. (In my defense, it's still pretty early.)
This is an interesting question, and I started thinking about how I would implement something like this.
I came up with this (fiddle);
Basically, instead of trying to call a directive from a controller, I created a module to house all the popdown logic:
var PopdownModule = angular.module('Popdown', []);
I put two things in the module, a factory
for the API which can be injected anywhere, and the directive
for defining the behavior of the actual popdown element:
The factory just defines a couple of functions success
and error
and keeps track of a couple of variables:
PopdownModule.factory('PopdownAPI', function() {
return {
status: null,
message: null,
success: function(msg) {
this.status = 'success';
this.message = msg;
},
error: function(msg) {
this.status = 'error';
this.message = msg;
},
clear: function() {
this.status = null;
this.message = null;
}
}
});
The directive gets the API injected into its controller, and watches the api for changes (I'm using bootstrap css for convenience):
PopdownModule.directive('popdown', function() {
return {
restrict: 'E',
scope: {},
replace: true,
controller: function($scope, PopdownAPI) {
$scope.show = false;
$scope.api = PopdownAPI;
$scope.$watch('api.status', toggledisplay)
$scope.$watch('api.message', toggledisplay)
$scope.hide = function() {
$scope.show = false;
$scope.api.clear();
};
function toggledisplay() {
$scope.show = !!($scope.api.status && $scope.api.message);
}
},
template: '<div class="alert alert-{{api.status}}" ng-show="show">' +
' <button type="button" class="close" ng-click="hide()">×</button>' +
' {{api.message}}' +
'</div>'
}
})
Then I define an app
module that depends on Popdown
:
var app = angular.module('app', ['Popdown']);
app.controller('main', function($scope, PopdownAPI) {
$scope.success = function(msg) { PopdownAPI.success(msg); }
$scope.error = function(msg) { PopdownAPI.error(msg); }
});
And the HTML looks like:
<html ng-app="app">
<body ng-controller="main">
<popdown></popdown>
<a class="btn" ng-click="success('I am a success!')">Succeed</a>
<a class="btn" ng-click="error('Alas, I am a failure!')">Fail</a>
</body>
</html>
I'm not sure if it's completely ideal, but it seemed like a reasonable way to set up communication with a global-ish popdown directive.
Again, for reference, the fiddle.
If you want to overwrite any css in bootstrap use !important
Let's say here is the page header class in bootstrap which have 40px margin on top, my client don't like it and he want it to be 15 on top and 10 on bottom only
.page-header {
border-bottom: 1px solid #EEEEEE;
margin: 40px 0 20px;
padding-bottom: 9px;
}
So I added on class in my site.css file with the same name like this
.page-header
{
padding-bottom: 9px;
margin: 15px 0 10px 0px !important;
}
Note the !important with my margin, which will overwrite the margin of bootstarp page-header class margin.
If (1) you need a favicon that is different for some parts of the domain, or (2) you want this to work with IE 8 or older (haven't tested any newer version), then you have to edit the html to specify the favicon
The Navigation Drawer pattern is officially described in the Android documentation!
Check out the following links:
Roman Nurik (an Android design engineer at Google) has confirmed that the recommended behavior is to not move the Action Bar when opening the drawer (like the YouTube app). See this Google+ post.
I answered this question a while ago, but I'm back to re-emphasize that Prixing has the best fly-out menu out there... by far. It's absolutely beautiful, perfectly smooth, and it puts Facebook, Google+, and YouTube to shame. EverNote is pretty good too... but still not as perfect as Prixing. Check out this series of posts on how the flyout menu was implemented (from none other than the head developer at Prixing himself!).
Adam Powell and Richard Fulcher talk about this at 49:47 - 52:50 in the Google I/O talk titled "Navigation in Android".
To summarize their answer, as of the date of this posting the slide out navigation menu is not officially part of the Android application design standard. As you have probably discovered, there's currently no native support for this feature, but there was talk about making this an addition to an upcoming revision of the support package.
With regards to the YouTube and G+ apps, it does seem odd that they behave differently. My best guess is that the reason the YouTube app fixes the position of the action bar is,
One of the most important navigational options for users using the YouTube app is search, which is performed in the SearchView
in the action bar. It would make sense to make the action bar static in this regard, since it would allow the user to always have the option to search for new videos.
The G+ app uses a ViewPager
to display its content, so making the pull out menu specific to the layout content (i.e. everything under the action bar) wouldn't make much sense. Swiping is supposed to provide a means of navigating between pages, not a means of global navigation. This might be why they decided to do it differently in the G+ app than they did in the YouTube app.
On another note, check out the Google Play app for another version of the "pull out menu" (when you are at the left most page, swipe left and a pull out, "half-page" menu will appear).
You're right in that this isn't very consistent behavior, but it doesn't seem like there is a 100% consensus within the Android team on how this behavior should be implemented yet. I wouldn't be surprised if in the future the apps are updated so that the navigation in both apps are identical (they seemed very keen on making navigation consistent across all Google-made apps in the talk).
Your code looks pretty good.
Be careful, however, for your call to Range("H5")
is a shortcut command to Application.Range("H5")
, which is equivalent to Application.ActiveSheet.Range("H5")
. This could be fine, if the only changes are user-changes -- which is the most typical -- but it is possible for the worksheet's cell values to change when it is not the active sheet via programmatic changes, e.g. VBA.
With this in mind, I would utilize Target.Worksheet.Range("H5")
:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Target.Worksheet.Range("H5")) Is Nothing Then Macro
End Sub
Or you can use Me.Range("H5")
, if the event handler is on the code page for the worksheet in question (it usually is):
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Me.Range("H5")) Is Nothing Then Macro
End Sub
Hope this helps...
You must declare
int add(int a, int b);
(note to the semicolon)
in a header file and include the file into both files.
Including it into Main.c will tell compiler how the function should be called.
Including into the second file will allow you to check that declaration is valid (compiler would complain if declaration and implementation were not matched).
Then you must compile both *.c files into one project. Details are compiler-dependent.
Using a ListView
to make it not scroll is extremely expensive and goes against the whole purpose of ListView
. You should NOT do this. Just use a LinearLayout
instead.
Well, not always. Using cookies, you are good. But the "can I safely rely on the id being present" urged me to extend the discussion with an important point (mostly for reference, as the visitor count of this page seems quite high).
PHP can be configured to maintain sessions by URL-rewriting, instead of cookies. (How it's good or bad (<-- see e.g. the topmost comment there) is a separate question, let's now stick to the current one, with just one side-note: the most prominent issue with URL-based sessions -- the blatant visibility of the naked session ID -- is not an issue with internal Ajax calls; but then, if it's turned on for Ajax, it's turned on for the rest of the site, too, so there...)
In case of URL-rewriting (cookieless) sessions, Ajax calls must take care of it themselves that their request URLs are properly crafted. (Or you can roll your own custom solution. You can even resort to maintaining sessions on the client side, in less demanding cases.) The point is the explicit care needed for session continuity, if not using cookies:
If the Ajax calls just extract URLs verbatim from the HTML (as received from PHP), that should be OK, as they are already cooked (umm, cookified).
If they need to assemble request URIs themselves, the session ID needs to be added to the URL manually. (Check here, or the page sources generated by PHP (with URL-rewriting on) to see how to do it.)
From OWASP.org:
Effectively, the web application can use both mechanisms, cookies or URL parameters, or even switch from one to the other (automatic URL rewriting) if certain conditions are met (for example, the existence of web clients without cookies support or when cookies are not accepted due to user privacy concerns).
From a Ruby-forum post:
When using php with cookies, the session ID will automatically be sent in the request headers even for Ajax XMLHttpRequests. If you use or allow URL-based php sessions, you'll have to add the session id to every Ajax request url.
After some tries, these are the samples I am using in order to connect:
Specifying the username and the password:
sqlcmd -S 211.11.111.111 -U NotSA -P NotTheSaPassword
Specifying the DB as well:
sqlcmd -S 211.11.111.111 -d SomeSpecificDatabase -U NotSA -P NotTheSaPassword
In okhttp v4.* I got it working that way
// import the extensions!
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
// ...
json : String = "..."
val JSON : MediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody: RequestBody = json.toRequestBody(JSON)
// go on with Request.Builder() etc
This issue has been recently fixed (Nov 2010) by Google, see https://code.google.com/p/analytics-issues/issues/detail?id=671. But be aware that as a good fix it brings more bugs :)
You will also have to follow the initialisation method listed here: https://developers.google.com/analytics/devguides/collection/ios/v2.
The latest instructions are going to give you a headache because it references utilities not included in the pod. Below will fail with the cocoapod
// Configure tracker from GoogleService-Info.plist.
NSError *configureError;
[[GGLContext sharedInstance] configureWithError:&configureError];
NSAssert(!configureError, @"Error configuring Google services: %@", configureError);
In addition to all answers, if the clients are using Android 6.0, Android added new permission model for (Marshmallow).
Trick: If you are targeting version 22 or below, your application will request all permissions at install time just as it would on any device running an OS below Marshmallow. If you are trying on the emulator then from android 6.0 onwards you need to explicitly go the settings->apps-> YOURAPP -> permissions and change the permission if you have given any.
I faced this same problem, and I came up with a solution that didn't invole using the ProgressDialog and I get faster results.
What I did was create a layout that has a ProgressBar in it.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ProgressBar
android:id="@+id/progressImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>
</RelativeLayout>
Then in the onCreate method do the following
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.progress);
}
Then do the long task in a thread, and when that's finished have a Runnable set the content view to the real layout you want to use for this activity.
For example:
mHandler.post(new Runnable(){
public void run() {
setContentView(R.layout.my_layout);
}
});
This is what I did, and I've found that it runs faster than showing the ProgressDialog and it's less intrusive and has a better look in my opinion.
However, if you're wanting to use the ProgressDialog, then this answer isn't for you.
variable declares and call like this in a class
class X {
var x: Int = 3
}
var y = X()
print("value of x is: ", y.x)
//value of x is: 3
now you want to program to make the default value of x more than or equal to 3. Now take the hypothetical case if x is less than 3, your program will fail. so, you want people to either put 3 or more than 3. Swift got it easy for you and it is important to understand this bit-advance way of dating the variable value because they will extensively use in iOS development. Now let's see how get and set will be used here.
class X {
var _x: Int = 3
var x: Int {
get {
return _x
}
set(newVal) { //set always take 1 argument
if newVal >= 3 {
_x = newVal //updating _x with the input value by the user
print("new value is: ", _x)
}
else {
print("error must be greater than 3")
}
}
}
}
let y = X()
y.x = 1
print(y.x) //error must be greater than 3
y.x = 8 // //new value is: 8
if you still have doubts, just remember, the use of get and set is to update any variable the way we want it to be updated. get and set will give you better control to rule your logic. Powerful tool hence not easily understandable.
Yes, add it to the php.ini, restart apache and it should work.
You can test it on the fly if you want to with ini_set("max_input_vars",100)
According to eduLINQ:
The best way to get to grips with what GroupJoin does is to think of Join. There, the overall idea was that we looked through the "outer" input sequence, found all the matching items from the "inner" sequence (based on a key projection on each sequence) and then yielded pairs of matching elements. GroupJoin is similar, except that instead of yielding pairs of elements, it yields a single result for each "outer" item based on that item and the sequence of matching "inner" items.
The only difference is in return statement:
Join:
var lookup = inner.ToLookup(innerKeySelector, comparer);
foreach (var outerElement in outer)
{
var key = outerKeySelector(outerElement);
foreach (var innerElement in lookup[key])
{
yield return resultSelector(outerElement, innerElement);
}
}
GroupJoin:
var lookup = inner.ToLookup(innerKeySelector, comparer);
foreach (var outerElement in outer)
{
var key = outerKeySelector(outerElement);
yield return resultSelector(outerElement, lookup[key]);
}
Read more here:
This should help :
https://www.w3schools.com/tags/att_select_required.asp
<form>_x000D_
<select required>_x000D_
<option value="">None</option>_x000D_
<option value="volvo">Volvo</option>_x000D_
<option value="saab">Saab</option>_x000D_
<option value="mercedes">Mercedes</option>_x000D_
<option value="audi">Audi</option>_x000D_
</select>_x000D_
<button type="submit">Submit</button>_x000D_
</form>
_x000D_
For some cases UIWebView is a good solution. Because:
Using NSAttributedString can lead to crashes, if html is complex or contains tables (so example)
For loading text to web view you can use the following snippet (just example):
func loadHTMLText(_ text: String?, font: UIFont) {
let fontSize = font.pointSize * UIScreen.screens[0].scale
let html = """
<html><body><span style=\"font-family: \(font.fontName); font-size: \(fontSize)\; color: #112233">\(text ?? "")</span></body></html>
"""
self.loadHTMLString(html, baseURL: nil)
}
If you have linked the node packages using sudo command
Then go to the folder where node_modules are installed globally.
On Unix systems they are normally placed in /usr/local/lib/node or /usr/local/lib/node_modules when installed globally. If you set the NODE_PATH environment variable to this path, the modules can be found by node.
Windows XP - %USERPROFILE%\Application Data\npm\node_modules Windows 7 - %AppData%\npm\node_modules
and then run the command
ls -l
This will give the list of all global node_modules and you can easily see the linked node modules.
In order to completely remove pip, I believe you have to delete its files from all Python versions on your computer. For me, they are here:
cd /Library/Frameworks/Python.framework/Versions/Current/bin/
cd /Library/Frameworks/Python.framework/Versions/3.3/bin/
You may need to remove the files or the directories located at these file-paths (and more, depending on the number of versions of Python you have installed).
Edit: to find all versions of pip on your machine, use:
find / -name pip 2>/dev/null
, which starts at its highest level (hence the /
) and hides all error messages (that's what 2>/dev/null
does). This is my output:
$ find / -name pip 2>/dev/null
/Library/Frameworks/Python.framework/Versions/2.7/bin/pip
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip
/Library/Frameworks/Python.framework/Versions/3.3/bin/pip
/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pip
/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pip
/Library/Frameworks/Python.framework/Versions/7.1/bin/pip
/Library/Frameworks/Python.framework/Versions/7.1/lib/python2.7/site-packages/pip-1.4.1-py2.7.egg/pip
If you need a CakePHP Docker Container with MySQL, I have created a Docker image for that purpose! No need to worry about setting it up. It just works!
Here's how I installed in Ubuntu-based image:
https://github.com/marcellodesales/php-apache-mysql-4-cakephp-docker/blob/master/Dockerfile#L8
RUN docker-php-ext-install mysql mysqli pdo pdo_mysql
Building and running your application is just a 2 step process (considering you are in the current directory of the app):
$ docker build -t myCakePhpApp .
$ docker run -ti myCakePhpApp
[1,2,3].is_a? Array
evaluates to true.
Check this out:
XAML:
<DataGrid Name="DataGrid1">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Click="ChangeText">Show/Hide</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Method:
private void ChangeText(object sender, RoutedEventArgs e)
{
DemoModel model = (sender as Button).DataContext as DemoModel;
model.DynamicText = (new Random().Next(0, 100).ToString());
}
Class:
class DemoModel : INotifyPropertyChanged
{
protected String _text;
public String Text
{
get { return _text; }
set { _text = value; RaisePropertyChanged("Text"); }
}
protected String _dynamicText;
public String DynamicText
{
get { return _dynamicText; }
set { _dynamicText = value; RaisePropertyChanged("DynamicText"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(String propertyName)
{
PropertyChangedEventHandler temp = PropertyChanged;
if (temp != null)
{
temp(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Initialization Code:
ObservableCollection<DemoModel> models = new ObservableCollection<DemoModel>();
models.Add(new DemoModel() { Text = "Some Text #1." });
models.Add(new DemoModel() { Text = "Some Text #2." });
models.Add(new DemoModel() { Text = "Some Text #3." });
models.Add(new DemoModel() { Text = "Some Text #4." });
models.Add(new DemoModel() { Text = "Some Text #5." });
DataGrid1.ItemsSource = models;
After some googling I found this:
curl -c cookie.txt -d "LoginName=someuser" -d "password=somepass" https://oursite/a
curl -b cookie.txt https://oursite/b
No idea if it works, but it might lead you in the right direction.
remap
is an option that makes mappings work recursively. By default it is on and I'd recommend you leave it that way. The rest are mapping commands, described below:
:map
and :noremap
are recursive and non-recursive versions of the various mapping commands. For example, if we run:
:map j gg (moves cursor to first line)
:map Q j (moves cursor to first line)
:noremap W j (moves cursor down one line)
Then:
j
will be mapped to gg
.Q
will also be mapped to gg
, because j
will be expanded for the recursive mapping.W
will be mapped to j
(and not to gg
) because j
will not be expanded for the non-recursive mapping.Now remember that Vim is a modal editor. It has a normal mode, visual mode and other modes.
For each of these sets of mappings, there is a mapping that works in normal, visual, select and operator modes (:map
and :noremap
), one that works in normal mode (:nmap
and :nnoremap
), one in visual mode (:vmap
and :vnoremap
) and so on.
For more guidance on this, see:
:help :map
:help :noremap
:help recursive_mapping
:help :map-modes
If you want to close it you can either hide it or remove it from the page. To hide it you would do some javascript like:
this.parentNode.style.display = 'none';
To remove it you use removeChild
this.parentNode.parentNode.removeChild(this.parentNode);
If you had a library like jQuery included then hiding or removing the div would be slightly easier:
$(this).parent().hide();
$(this).parent().remove();
One other thing, as your img
is in an anchor the onclick event on the anchor is going to fire as well. As the href
is set to # then the page will scroll back to the top of the page. Generally it is good practice that if you want a link to do something other than go to its href
you should set the onclick event to return false;
Check the VC++ directories, in VS 2010 these can be found in your project properties. Check whether $(WindowsSdkDir)\lib
is included in the directories list, if not, manually add it. If you're building for X64 platform, you should select X64 from the “Platform” ComboBox, and make sure that $(WindowsSdkDir)\lib\x64
is included in the directories list.
This will do it:
#signin input {
background-color:#FFF;
min-height:200px;
}
To make sure your code is portable across Windows, Linux and OSX and for systems with and without displays, I would suggest following snippet:
import matplotlib
import os
# must be before importing matplotlib.pyplot or pylab!
if os.name == 'posix' and "DISPLAY" not in os.environ:
matplotlib.use('Agg')
# now import other things from matplotlib
import matplotlib.pyplot as plt
Actually, as long as the parent element is positioned, you can set the child's height to 100%. Namely, in case you don't want the parent to be absolutely positioned. Let me explain further:
<style>
#outer2 {
padding-left: 23px;
position: relative;
height:auto;
width:200px;
border: 1px solid red;
}
#inner2 {
left:0;
position:absolute;
height:100%;
width:20px;
border: 1px solid black;
}
</style>
<div id='outer2'>
<div id='inner2'>
</div>
</div>
Program to find the longest substring which is palindrome from a given string.
package source;
import java.util.ArrayList;
public class LongestPalindrome
{
//Check the given string is palindrome by
public static boolean isPalindrome (String s)
{
StringBuffer sb = new StringBuffer(s);
if(s.equalsIgnoreCase(sb.reverse().toString()))
return true;
else
return false;
}
public static void main(String[] args)
{
//String / word without space
String str = "MOMABCMOMOM"; // "mom" //abccbabcd
if(str.length() > 2 )
{
StringBuffer sb = new StringBuffer();
ArrayList<String> allPalindromeList = new ArrayList<>();
for(int i=0; i<str.length(); i++)
{
for(int j=i; j<str.length(); j++)
{
sb.append(str.charAt(j));
if( isPalindrome(sb.toString()) ) {
allPalindromeList.add(sb.toString());
}
}
//clear the stringBuffer
sb.delete(0, sb.length());
}
int maxSubStrLength = -1;
int indexMaxSubStr = -1;
int index = -1;
for (String subStr : allPalindromeList) {
++index;
if(maxSubStrLength < subStr.length()) {
maxSubStrLength = subStr.length();
indexMaxSubStr = index;
}
}
if(maxSubStrLength > 2)
System.out.println("Maximum Length Palindrome SubString is : "+allPalindromeList.get(indexMaxSubStr));
else
System.out.println("Not able to find a Palindrome who is three character in length!!");
}
}
}
Did you try to chomp the $str1
and $str2
?
I found a similar issue with using (another) $str1
eq 'Y' and it only went away when I first did:
chomp($str1);
if ($str1 eq 'Y') {
....
}
works after that.
Hope that helps.
Yes, and then some, example from documentation:
public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
MARS (6.421e+23, 3.3972e6),
JUPITER (1.9e+27, 7.1492e7),
SATURN (5.688e+26, 6.0268e7),
URANUS (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7);
// in kilograms
private final double mass;
// in meters
private final double radius;
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
private double mass() { return mass; }
private double radius() { return radius; }
// universal gravitational
// constant (m3 kg-1 s-2)
public static final double G = 6.67300E-11;
double surfaceGravity() {
return G * mass / (radius * radius);
}
double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java Planet <earth_weight>");
System.exit(-1);
}
double earthWeight = Double.parseDouble(args[0]);
double mass = earthWeight/EARTH.surfaceGravity();
for (Planet p : Planet.values())
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}
}
I don't think jQuery itself includes datetimepicker. You must use jQuery UI instead (src="jquery.ui").
If you are using a newer version (over 1.3.x) you should learn more about the function parseJSON! I experienced the same problem. Use an old version or change your code
success=function(data){
//something like this
jQuery.parseJSON(data)
}
This error can also occur if your interface name is different than the file it is contained in. Read about ES6 modules for details. If the SignInComponent
was an interface, as was in my case, then
SignInComponent
should be in a file named SignInComponent.ts
.
Some things to try:
Restart the rails console; changes to your models will only get picked up by a rails console that is already open if you do > reload!
(although I have found this to be unpredictable), or by restarting the console.
Is your model file called "phone_number.rb" and is it in "/app/models"?
You should double-check the "--sandbox" option on your rails console command. AFAIK, this prevents changes. Try it without the switch.
You can do it with reduce:
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [], [1, 2]]
print(reduce(lambda count, l: count + len(l), a, 0))
# result is 11
Not much, really. You need a Makefile
in the current directory.
While you're in Vim, type :make
to invoke a shell and build your program. Don't worry when the output scrolls by; just press Enter when it's finished to return to Vim.
Back within Vim, you have the following commands at your disposal:
:cl
lists the errors, warnings, and other messages.:cc
displays the current error/warning message at the bottom of the screen and jumps to the offending line in your code.:cc n
jumps to the n
th message.:cn
advances to the next message.:cp
jumps to the previous message.There are more; if you're interested, type :help :cc
from within Vim.
Get the path of running Apache
$ ps -ef | grep apache
apache 12846 14590 0 Oct20 ? 00:00:00 /usr/sbin/apache2
Append -V
argument to the path
$ /usr/sbin/apache2 -V | grep SERVER_CONFIG_FILE
-D SERVER_CONFIG_FILE="/etc/apache2/apache2.conf"
Reference:
http://commanigy.com/blog/2011/6/8/finding-apache-configuration-file-httpd-conf-location
This also works like a charm
<form>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio" checked>Option 1_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio">Option 2_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio">Option 3_x000D_
</label>_x000D_
</form>
_x000D_
Declare the parameter in test.ps1:
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$input_dir,
[Parameter(Mandatory=$True)]
[string]$output_dir,
[switch]$force = $false
)
Run the script from Run OR Windows Task Scheduler:
powershell.exe -command "& C:\FTP_DATA\test.ps1 -input_dir C:\FTP_DATA\IN -output_dir C:\FTP_DATA\OUT"
or,
powershell.exe -command "& 'C:\FTP DATA\test.ps1' -input_dir 'C:\FTP DATA\IN' -output_dir 'C:\FTP DATA\OUT'"
if the name of node is for example : abcd then below query will work :
MATCH (n:abcd)
DETACH DELETE n
This will only delete the node with label "abcd" and all its relation-ships.
Try this:
HTML:
<input type="submit" value="submit" name="submit" onclick="myfunction()">
jQuery:
<script type="text/javascript">
function myfunction()
{
var url = $(location).attr('href');
$('#spn_url').html('<strong>' + url + '</strong>');
}
</script>
On Linux, macOS and Unix to display the groups to which you belong, use:
id -Gn
which is equivalent to groups
utility which has been obsoleted on Unix (as per Unix manual).
On macOS and Unix, the command id -p
is suggested for normal interactive.
Explanation of the parameters:
-G
,--groups
- print all group IDs
-n
,--name
- print a name instead of a number, for-ugG
-p
- Make the output human-readable.
I have used below code in my SpringBoot application.
MimeMessage message = sender.createMimeMessage();
message.setContent(message, "text/html");
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setFrom(fromAddress);
helper.setTo(toAddress);
helper.setSubject(mailSubject);
helper.setText(mailText, true);
sender.send(message);
We worked around this limitation by adding a simple IF statement in the stored procedure. Practically we pass an empty string whenever we want to save the default value in the DB.
CREATE DEFINER=`test`@`%` PROCEDURE `myProc`(IN myVarParam VARCHAR(40))
BEGIN
IF myVarParam = '' THEN SET myVarParam = 'default-value'; END IF;
...your code here...
END
I think the best way to do it is by creating a filter, like this:
myModule.filter('ceil', function() {
return function(input) {
return Math.ceil(input);
};
});
then the markup looks like this:
<p>The percentage is {{ (100*count/total) | ceil }}%</p>
Updated fiddle: http://jsfiddle.net/BB4T4/
changed from your code :
private String toDate(long timestamp) {
Date date = new Date (timestamp * 1000 - 24 * 60 * 60 * 1000);
return new SimpleDateFormat("yyyy-MM-dd").format(date).toString();
}
but you do better using calendar.
mentions YAML line continuations.
As an example (tried with ansible 2.0.0.2):
---
- hosts: all
tasks:
- name: multiline shell command
shell: >
ls --color
/home
register: stdout
- name: debug output
debug: msg={{ stdout }}
The shell command is collapsed into a single line, as in ls --color /home
If you understand partial
you're halfway there. The idea of partial
is to preapply arguments to a function and give back a new function that wants only the remaining arguments. When this new function is called it includes the preloaded arguments along with whatever arguments were supplied to it.
In Clojure +
is a function but to make things starkly clear:
(defn add [a b] (+ a b))
You may be aware that the inc
function simply adds 1 to whatever number it's passed.
(inc 7) # => 8
Let's build it ourselves using partial
:
(def inc (partial add 1))
Here we return another function that has 1 loaded into the first argument of add
. As add
takes two arguments the new inc
function wants only the b
argument -- not 2 arguments as before since 1 has already been partially applied. Thus partial
is a tool from which to create new functions with default values presupplied. That is why in a functional language functions often order arguments from general to specific. This makes it easier to reuse such functions from which to construct other functions.
Now imagine if the language were smart enough to understand introspectively that add
wanted two arguments. When we passed it one argument, rather than balking, what if the function partially applied the argument we passed it on our behalf understanding that we probably meant to provide the other argument later? We could then define inc
without explicitly using partial
.
(def inc (add 1)) #partial is implied
This is the way some languages behave. It is exceptionally useful when one wishes to compose functions into larger transformations. This would lead one to transducers.
I would checkout the remote file from the "master" (the remote/origin repository) like this:
git checkout master <FileWithPath>
Example: git checkout master components/indexTest.html
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
First of all, if table2
's idProduct is an identity, you cannot insert it explicitly until you set IDENTITY_INSERT
on that table
SET IDENTITY_INSERT table2 ON;
before the insert.
So one of two, you modify your second stored and call it with only the parameters productName
and productDescription
and then get the new ID
EXEC test2 'productName', 'productDescription'
SET @newID = SCOPE_IDENTIY()
or you already have the ID of the product and you don't need to call SCOPE_IDENTITY()
and can make the insert on table1
with that ID
Use the JQuery Serialize function
http://docs.jquery.com/Ajax/serialize
Serialize is typically used to prepare user input data to be posted to a server. The serialized data is in a standard format that is compatible with almost all server side programming languages and frameworks.
I suggest Validator.nu's parser, based on the HTML5 parsing algorithm. It is the parser used in Mozilla from 2010-05-03
My EAR project had 2 modules *.ear and *.war and I got this dependency error on *.war
project when trying mvn eclipse:eclipse
. Resolved it by fixing utf-8 encoding issue in the *.war
project. mvn
-X
or -e
options weren't of help here.
What about something like:
Alter Table Products
Add LastUpdate varchar(200) null
Do you need something more complex than this?
All of my tasks (which need to be scheduled) for a website are kept within the website and called from a special page. I then wrote a simple Windows service which calls this page every so often. Once the page runs it returns a value. If I know there is more work to be done, I run the page again, right away, otherwise I run it in a little while. This has worked really well for me and keeps all my task logic with the web code. Before writing the simple Windows service, I used Windows scheduler to call the page every x minutes.
Another convenient way to run this is to use a monitoring service like Pingdom. Point their http check to the page which runs your service code. Have the page return results which then can be used to trigger Pingdom to send alert messages when something isn't right.
I had the same problem for a long time now, I often needed to mix Matchers and values and I never managed to do that with Mockito.... until recently ! I put the solution here hoping it will help someone even if this post is quite old.
It is clearly not possible to use Matchers AND values together in Mockito, but what if there was a Matcher accepting to compare a variable ? That would solve the problem... and in fact there is : eq
when(recommendedAccessor.searchRecommendedHolidaysProduct(eq(metas), any(List.class), any(HotelsBoardBasisType.class), any(Config.class)))
.thenReturn(recommendedResults);
In this example 'metas' is an existing list of values
You can overwrite a string, as follows:
String myName = "halftime";
myName = myName.substring(0,4)+'x'+myName.substring(5);
Note that the string myName
occurs on both lines, and on both sides of the second line.
Therefore, even though strings may technically be immutable, in practice, you can treat them as editable by overwriting them.
This is a long-standing "feature" of the list controls in .NET in my experience. Personally, I would just bind to the on change of the SelectedValue property and write whatever additional code is necessary to workaround this "feature" (such as having two properties, binding to one for SelectedValue, and then, on the set of that property, updating the value from SelectedItem in your custom code).
Anyway, I hope that helps =D
Try this, it's working for me.
Sender:
byte[] message = ...
Socket socket = ...
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeInt(message.length); // write length of the message
dOut.write(message); // write the message
Receiver:
Socket socket = ...
DataInputStream dIn = new DataInputStream(socket.getInputStream());
int length = dIn.readInt(); // read length of incoming message
if(length>0) {
byte[] message = new byte[length];
dIn.readFully(message, 0, message.length); // read the message
}
try this
<html>_x000D_
<head>_x000D_
<style type="text/css">_x000D_
body {_x000D_
font-family: sans-serif;_x000D_
font-size: 14px;_x000D_
}_x000D_
</style>_x000D_
_x000D_
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places®ion=in" type="text/javascript"></script>_x000D_
<script type="text/javascript">_x000D_
function initialize() {_x000D_
var input = document.getElementById('searchTextField');_x000D_
var autocomplete = new google.maps.places.Autocomplete(input);_x000D_
}_x000D_
google.maps.event.addDomListener(window, 'load', initialize);_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"
Change this to: "region=in" (in=india)
"http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places®ion=in" type="text/javascript"
PUT and PATCH methods are similar in nature, but there is a key difference.
PUT - in PUT request, the enclosed entity would be considered as the modified version of a resource which residing on server and it would be replaced by this modified entity.
PATCH - in PATCH request, enclosed entity contains the set of instructions that how the entity which residing on server, would be modified to produce a newer version.
Try using rowMeans
:
z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)
w x y mean
1 5 1 1 1
2 6 2 2 2
3 7 3 3 3
4 8 4 NA 4
db.getCollection('orders').aggregate([
{$group: {
_id: {name: "$name"},
uniqueIds: {$addToSet: "$_id"},
count: {$sum: 1}
}
},
{$match: {
count: {"$gt": 1}
}
}
])
First Group Query the group according to the fields.
Then we check the unique Id and count it, If count is greater then 1 then the field is duplicate in the entire collection so that thing is to be handle by $match query.
In order to take advantage of the auto-incrementing capability of the column, do not supply a value for that column when inserting rows. The database will supply a value for you.
INSERT INTO test.authors (
instance_id,host_object_id,check_type,is_raw_check,
current_check_attempt,max_check_attempts,state,state_type,
start_time,start_time_usec,end_time,end_time_usec,command_object_id,
command_args,command_line,timeout,early_timeout,execution_time,
latency,return_code,output,long_output,perfdata
) VALUES (
'1','67','0','0','1','10','0','1','2012-01-03 12:50:49','108929',
'2012-01-03 12:50:59','198963','21','',
'/usr/local/nagios/libexec/check_ping 5','30','0','4.04159',
'0.102','1','PING WARNING -DUPLICATES FOUND! Packet loss = 0%, RTA = 2.86 ms',
'','rta=2.860000m=0%;80;100;0'
);
This code checks if the number is odd or even in PHP. In the example $a
is 2
and you get even number. If you need odd then change the $a
value
$a=2;
if($a %2 == 0){
echo "<h3>This Number is <b>$a</b> Even</h3>";
}else{
echo "<h3>This Number is <b>$a</b> Odd</h3>";
}
I'm using XAMPP with Apache2.4, I had this same issue. I wanted to leave the default xampp/htdocs folder in place, be able to access it from locahost and have a Virtual Host to point to my dev area...
The full contents of my C:\xampp\apache\conf\extra\http-vhosts.conf
file is below...
# Virtual Hosts
#
# Required modules: mod_log_config
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.4/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
##NameVirtualHost *:80
#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ##ServerName or ##ServerAlias in any <VirtualHost> block.
#
##<VirtualHost *:80>
##ServerAdmin [email protected]
##DocumentRoot "C:/xampp/htdocs/dummy-host.example.com"
##ServerName dummy-host.example.com
##ServerAlias www.dummy-host.example.com
##ErrorLog "logs/dummy-host.example.com-error.log"
##CustomLog "logs/dummy-host.example.com-access.log" common
##</VirtualHost>
##<VirtualHost *:80>
##ServerAdmin [email protected]
##DocumentRoot "C:/xampp/htdocs/dummy-host2.example.com"
##ServerName dummy-host2.example.com
##ErrorLog "logs/dummy-host2.example.com-error.log"
##CustomLog "logs/dummy-host2.example.com-access.log" common
##</VirtualHost>
<VirtualHost *:80>
DocumentRoot "C:\xampp\htdocs"
ServerName localhost
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "C:\nick\static"
ServerName dev.middleweek.co.uk
<Directory "C:\nick\static">
Allow from all
Require all granted
</Directory>
</VirtualHost>
I then updated my C:\windows\System32\drivers\etc\hosts
file like this...
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host
# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
127.0.0.1 dev.middleweek.co.uk
127.0.0.1 localhost
Restart your machine for good measure, open the XAMPP Control Panel and start Apache.
Now open your custom domain in your browser, in the above example, it'll be http://dev.middleweek.co.uk
Hope that helps someone!
And if you want to be able to view directory listings under your new Virtual host, then edit your VirtualHost block in C:\xampp\apache\conf\extra\http-vhosts.conf
to include "Options Indexes" like this...
<VirtualHost *:80>
DocumentRoot "C:\nick\static"
ServerName dev.middleweek.co.uk
<Directory "C:\nick\static">
Allow from all
Require all granted
Options Indexes
</Directory>
</VirtualHost>
Cheers, Nick
I can see many good answers to the question, but I still would like to share this method, by using Git parameter as follows:
When building the pipeline you will be asked to choose the branch:
After that through the groovy code you could specify the branch you want to clone:
git branch:BRANCH[7..-1], url: 'https://github.com/YourName/YourRepo.git' , credentialsId: 'github'
Note that I'm using a slice from 7 to the last character to shrink "origin/" and get the branch name.
Also in case you configured a webhooks trigger it still work and it will take the default branch you specified(master
in our case).
I had a similar problem. Data in a worksheet I needed to save as a separate CSV file.
Here's my code behind a command button
Private Sub cmdSave()
Dim sFileName As String
Dim WB As Workbook
Application.DisplayAlerts = False
sFileName = "MyFileName.csv"
'Copy the contents of required sheet ready to paste into the new CSV
Sheets(1).Range("A1:T85").Copy 'Define your own range
'Open a new XLS workbook, save it as the file name
Set WB = Workbooks.Add
With WB
.Title = "MyTitle"
.Subject = "MySubject"
.Sheets(1).Select
ActiveSheet.Paste
.SaveAs "MyDirectory\" & sFileName, xlCSV
.Close
End With
Application.DisplayAlerts = True
End Sub
This works for me :-)
I have a a blank solution BuildRebuildClean
and three class library Models
,Repository
,Notification
.
I use Models
and Repository
in Notification
class library.
Then:
Models
library project, then BUILD solution.
In the below screen shot, refer to the time stamp of DLL, EXE is updated in Models
and Notification
library.BuildRebuildClean
. What it does is deletes all the assemblies,
EXEs and referred files to compile again.$('#slick-slider').slick('refresh'); //Working for slick 1.8.1
I recently just ran into this issue as well. I had a very large table in the dialog div. It was >15,000 rows. When the .empty() was called on the dialog div, I was getting the error above.
I found a round-about solution where before I call cleaning the dialog box, I would remove every other row from the very large table, then call the .empty(). It seemed to have worked though. It seems that my old version of JQuery can't handle such large elements.
I'm pretty sure you can do explicit casting here.
foo f = (foo)value;
So long as you say the enum inherits(?) from int, which you have.
enum foo : int
EDIT Yes it turns out that by default, an enums underlying type is int. You can however use any integral type except char.
You can also cast from a value that's not in the enum, producing an invalid enum. I suspect this works by just changing the type of the reference and not actually changing the value in memory.
enum (C# Reference)
Enumeration Types (C# Programming Guide)
I don't think one is inherently better than another one, but I would suggest sticking with || because it is the default in most languages.
EDIT: As others have pointed out there is indeed a difference between the two.
The much more simple and logical is to do this:
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
return [[UIView alloc] initWithFrame:CGRectZero];
}
In most cases you don't want to see only the last table view cell separator. And this approach removes only the last table view cell separator, and you don't need to think about Auto Layout issues (i.e. rotating device) or hardcode values to set up separator insets.
import org.apache.spark.sql.functions.desc
df.orderBy(desc("columnname1"),desc("columnname2"),asc("columnname3"))
If you just want to change file permissions, you want to be careful about using -R
on chmod
since it will change anything, files or folders. If you are doing a relative change (like adding write permission for everyone), you can do this:
sudo chmod -R a+w /var/www
But if you want to use the literal permissions of read/write, you may want to select files versus folders:
sudo find /var/www -type f -exec chmod 666 {} \;
(Which, by the way, for security reasons, I wouldn't recommend either of these.)
Or for folders:
sudo find /var/www -type d -exec chmod 755 {} \;
select owner, table_name, num_rows, sample_size, last_analyzed from all_tables;
This is the fastest way to retrieve the row counts but there are a few important caveats:
ESTIMATE_PERCENT => DBMS_STATS.AUTO_SAMPLE_SIZE
(the default), or in earlier versions with ESTIMATE_PERCENT => 100
. See this post for an explanation of how
the AUTO_SAMPLE_SIZE algorithm works in 11g.LAST_ANALYZED
, the current results may be different.My Problem was that I was not in the correct git directory that I just cloned.
You need:
$ro = preg_replace('/\s+/', ' ',$row['message']);
You are using \s\s+
which means whitespace(space, tab or newline) followed by one or more whitespace. Which effectively means replace two or more whitespace with a single space.
What you want is replace one or more whitespace with single whitespace, so you can use the pattern \s\s*
or \s+
(recommended)
Your problem is most likely with the video file, not the code. Your video is most likely not "safe for streaming". See where to place videos to stream android for more.
This is a late answer. However, I thought of putting the struggle I had to bear to get a shell script to be executed from a Spring-Boot application for future developers.
I was working in Spring-Boot and I was not able to find the file to be executed from my Java application and it was throwing FileNotFoundFoundException
. I had to keep the file in the resources
directory and had to set the file to be scanned in pom.xml
while the application was being started like the following.
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
<include>**/*.sh</include>
</includes>
</resource>
</resources>
error code = 13, Permission Denied
. Then I had to make the file executable by running this command - chmod u+x myShellScript.sh
Finally, I could execute the file using the following code snippet.
public void runScript() {
ProcessBuilder pb = new ProcessBuilder("src/main/resources/myFile.sh");
try {
Process p;
p = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
}
Hope that solves someone's problem.
Leveraging from the good answers above and assuming you were only using plt as in
import matplotlib.pyplot as plt
then you can get all four plot limits using plt.axis()
as in the following example.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8] # fake data
y = [1, 2, 3, 4, 3, 2, 5, 6]
plt.plot(x, y, 'k')
xmin, xmax, ymin, ymax = plt.axis()
s = 'xmin = ' + str(round(xmin, 2)) + ', ' + \
'xmax = ' + str(xmax) + '\n' + \
'ymin = ' + str(ymin) + ', ' + \
'ymax = ' + str(ymax) + ' '
plt.annotate(s, (1, 5))
plt.show()
Do you want to order it?
Select * From temp where mydate > '2009-06-29 04:00:44' ORDER BY mydate;
git log -p
will generate the a patch (the diff) for every commit selected. For a single file, use git log --follow -p $file
.
If you're looking for a particular change, use git bisect
to find the change in log(n) views by splitting the number of commits in half until you find where what you're looking for changed.
Also consider looking back in history using git blame
to follow changes to the line in question if you know what that is. This command shows the most recent revision to affect a certain line. You may have to go back a few versions to find the first change where something was introduced if somebody has tweaked it over time, but that could give you a good start.
Finally, gitk
as a GUI does show me the patch immediately for any commit I click on.
Example :
Here is a more efficient way of fading out an element:
function fade(element) {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 50);
}
you can do the reverse for fade in
setInterval or setTimeout should not get a string as argument
google the evils of eval to know why
And here is a more efficient way of fading in an element.
function unfade(element) {
var op = 0.1; // initial opacity
element.style.display = 'block';
var timer = setInterval(function () {
if (op >= 1){
clearInterval(timer);
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op += op * 0.1;
}, 10);
}