I prefer to use \c
at the end of the search string:
/copyright\c
Basically, you need to include the Wordpress loop in your search.php template to loop through the search results and show them as part of the template.
Below is a very basic example from The WordPress Theme Search Template and Page Template over at ThemeShaper.
<?php
/**
* The template for displaying Search Results pages.
*
* @package Shape
* @since Shape 1.0
*/
get_header(); ?>
<section id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php if ( have_posts() ) : ?>
<header class="page-header">
<h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'shape' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
</header><!-- .page-header -->
<?php shape_content_nav( 'nav-above' ); ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'search' ); ?>
<?php endwhile; ?>
<?php shape_content_nav( 'nav-below' ); ?>
<?php else : ?>
<?php get_template_part( 'no-results', 'search' ); ?>
<?php endif; ?>
</div><!-- #content .site-content -->
</section><!-- #primary .content-area -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
While all of the above links have merit, and have benefited me greatly in the past, as a linguist "exposed" to various Lucene search engines for the last 15 years, I have to say that elastic-search development is very fast in Python. That being said, some of the code felt non-intuitive to me. So, I reached out to one component of the ELK stack, Kibana, from an open source perspective, and found that I could generate the somewhat cryptic code of elasticsearch very easily in Kibana. Also, I could pull Chrome Sense es queries into Kibana as well. If you use Kibana to evaluate es, it will further speed up your evaluation. What took hours to run on other platforms was up and running in JSON in Sense on top of elasticsearch (RESTful interface) in a few minutes at worst (largest data sets); in seconds at best. The documentation for elasticsearch, while 700+ pages, didn't answer questions I had that normally would be resolved in SOLR or other Lucene documentation, which obviously took more time to analyze. Also, you may want to take a look at Aggregates in elastic-search, which have taken Faceting to a new level.
Bigger picture: if you're doing data science, text analytics, or computational linguistics, elasticsearch has some ranking algorithms that seem to innovate well in the information retrieval area. If you're using any TF/IDF algorithms, Text Frequency/Inverse Document Frequency, elasticsearch extends this 1960's algorithm to a new level, even using BM25, Best Match 25, and other Relevancy Ranking algorithms. So, if you are scoring or ranking words, phrases or sentences, elasticsearch does this scoring on the fly, without the large overhead of other data analytics approaches that take hours--another elasticsearch time savings. With es, combining some of the strengths of bucketing from aggregations with the real-time JSON data relevancy scoring and ranking, you could find a winning combination, depending on either your agile (stories) or architectural(use cases) approach.
Note: did see a similar discussion on aggregations above, but not on aggregations and relevancy scoring--my apology for any overlap. Disclosure: I don't work for elastic and won't be able to benefit in the near future from their excellent work due to a different architecural path, unless I do some charity work with elasticsearch, which wouldn't be a bad idea
Simpler approach? A little more Pythonic?
>>> ok = "0123456789abcdef"
>>> all(c in ok for c in "123456abc")
True
>>> all(c in ok for c in "hello world")
False
It certainly isn't the most efficient, but it's sure readable.
Below is the example of searching for a keyword in the whole list and remove that item:
public class Book
{
public int BookId { get; set; }
public DateTime CreatedDate { get; set; }
public string Text { get; set; }
public string Autor { get; set; }
public string Source { get; set; }
}
If you want to remove a book that contains some keyword in the Text property, you can create a list of keywords and remove it from list of books:
List<Book> listToSearch = new List<Book>()
{
new Book(){
BookId = 1,
CreatedDate = new DateTime(2014, 5, 27),
Text = " test voprivreda...",
Autor = "abc",
Source = "SSSS"
},
new Book(){
BookId = 2,
CreatedDate = new DateTime(2014, 5, 27),
Text = "here you go...",
Autor = "bcd",
Source = "SSSS"
}
};
var blackList = new List<string>()
{
"test", "b"
};
foreach (var itemtoremove in blackList)
{
listToSearch.RemoveAll(p => p.Source.ToLower().Contains(itemtoremove.ToLower()) || p.Source.ToLower().Contains(itemtoremove.ToLower()));
}
return listToSearch.ToList();
(You're not searching through "JSON", you're searching through an array -- the JSON string has already been deserialized into an object graph, in this case an array.)
Some options:
If you're in control of the generation of this thing, does it have to be an array? Because if not, there's a much simpler way.
Say this is your original data:
[
{"id": "one", "pId": "foo1", "cId": "bar1"},
{"id": "two", "pId": "foo2", "cId": "bar2"},
{"id": "three", "pId": "foo3", "cId": "bar3"}
]
Could you do the following instead?
{
"one": {"pId": "foo1", "cId": "bar1"},
"two": {"pId": "foo2", "cId": "bar2"},
"three": {"pId": "foo3", "cId": "bar3"}
}
Then finding the relevant entry by ID is trivial:
id = "one"; // Or whatever
var entry = objJsonResp[id];
...as is updating it:
objJsonResp[id] = /* New value */;
...and removing it:
delete objJsonResp[id];
This takes advantage of the fact that in JavaScript, you can index into an object using a property name as a string -- and that string can be a literal, or it can come from a variable as with id
above.
(Dumb idea, predates the above. Kept for historical reasons.)
It looks like you need this to be an array, in which case there isn't really a better way than searching through the array unless you want to put a map on it, which you could do if you have control of the generation of the object. E.g., say you have this originally:
[
{"id": "one", "pId": "foo1", "cId": "bar1"},
{"id": "two", "pId": "foo2", "cId": "bar2"},
{"id": "three", "pId": "foo3", "cId": "bar3"}
]
The generating code could provide an id-to-index map:
{
"index": {
"one": 0, "two": 1, "three": 2
},
"data": [
{"id": "one", "pId": "foo1", "cId": "bar1"},
{"id": "two", "pId": "foo2", "cId": "bar2"},
{"id": "three", "pId": "foo3", "cId": "bar3"}
]
}
Then getting an entry for the id in the variable id
is trivial:
var index = objJsonResp.index[id];
var obj = objJsonResp.data[index];
This takes advantage of the fact you can index into objects using property names.
Of course, if you do that, you have to update the map when you modify the array, which could become a maintenance problem.
But if you're not in control of the generation of the object, or updating the map of ids-to-indexes is too much code and/ora maintenance issue, then you'll have to do a brute force search.
Somewhat OT (although you did ask if there was a better way :-) ), but your code for looping through an array is incorrect. Details here, but you can't use for..in
to loop through array indexes (or rather, if you do, you have to take special pains to do so); for..in
loops through the properties of an object, not the indexes of an array. Your best bet with a non-sparse array (and yours is non-sparse) is a standard old-fashioned loop:
var k;
for (k = 0; k < someArray.length; ++k) { /* ... */ }
or
var k;
for (k = someArray.length - 1; k >= 0; --k) { /* ... */ }
Whichever you prefer (the latter is not always faster in all implementations, which is counter-intuitive to me, but there we are). (With a sparse array, you might use for..in
but again taking special pains to avoid pitfalls; more in the article linked above.)
Using for..in
on an array seems to work in simple cases because arrays have properties for each of their indexes, and their only other default properties (length
and their methods) are marked as non-enumerable. But it breaks as soon as you set (or a framework sets) any other properties on the array object (which is perfectly valid; arrays are just objects with a bit of special handling around the length
property).
You can use Array.prototype.find function in javascript. Array find MDN.
So to find string in array of string, the code becomes very simple. Plus as browser implementation, it will provide good performance.
Ex.
var strs = ['abc', 'def', 'ghi', 'jkl', 'mno'];
var value = 'abc';
strs.find(
function(str) {
return str == value;
}
);
or using lambda expression it will become much shorter
var strs = ['abc', 'def', 'ghi', 'jkl', 'mno'];
var value = 'abc';
strs.find((str) => str === value);
mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given
This means that the first parameter you passed is a boolean (true or false).
The first parameter is $result
, and it is false
because there is a syntax error in the query.
" ... WHERE PartNumber = $partid';"
You should never directly include a request variable in a SQL query, else the users are able to inject SQL in your queries. (See SQL injection.)
You should escape the variable:
" ... WHERE PartNumber = '" . mysqli_escape_string($conn,$partid) . "';"
Or better, use Prepared Statements
.
Adding this answer for people like me for whom a TRUE/FALSE answer is perfectly acceptable
OR(IF(ISNUMBER(SEARCH($G$1:$G$7,A1)),TRUE,FALSE))
or case-sensitive
OR(IF(ISNUMBER(FIND($G$1:$G$7,A1)),TRUE,FALSE))
Where the range for the search terms is G1:G7
Remember to press CTRL+SHIFT+ENTER
At my company they didn't configure the server to provide a list of repositories, so svn list
worked for a specific repository but not at a higher level to list all repositories.
However they installed FishEye which gives you a GUI listing the repositories https://www.atlassian.com/software/fisheye
It's a paid option, so it's not for everyone, but the functionality is nice.
I don't know why that doesn't work, but this one is logically equivalent and it does work:
-(myField:superneat AND -myOtherField:somethingElse)
Maybe it has something to do with defining the same field twice in the query...
Try asking in the solr-user group, then post back here the final answer!
Visual Studio's search in folders is by far the fastest I've found.
I believe it intelligently searches only text (non-binary) files, and subsequent searches in the same folder are extremely fast, unlike with the other tools (likely the text files fit in the windows disk cache).
VS2010 on a regular hard drive, no SSD, takes 1 minute to search a 20GB folder with 26k files, source code and binaries mixed up. 15k files are searched - the rest are likely skipped due to being binary files. Subsequent searches in the same folder are on the order of seconds (until stuff gets evicted form the cache).
The next closest I've found for the same folder was grepWin. Around 3 minutes. I excluded files larger than 2000KB (default). The "Include binary files" setting seems to do nothing in terms of speeding up the search, it looks like binary files are still touched (bug?), but they don't show up in the search results. Subsequent searches all take the same 3 minutes - can't take advantage of hard drive cache. If I restrict to files smaller than 200k, the initial search is 2.5min and subsequent searches are on the order of seconds, about as fast as VS - in the cache.
Agent Ransack and FileSeek are both very slow on that folder, around 20min, due to searching through everything, including giant multi-gigabyte binary files. They search at about 10-20MB per second according to Resource Monitor.
UPDATE: Agent Ransack can be set to search files of certain sizes, and using the <200KB cutoff it's 1:15min for a fresh search and 5s for subsequent searches. Faster than grepWin and as fast as VS overall. It's actually pretty nice if you want to keep several searches in tabs and you don't want to pollute the VS recently searched folders list, and you want to keep the ability to search binaries, which VS doesn't seem to wanna do. Agent Ransack also creates an explorer context menu entry, so it's easy to launch from a folder. Same as grepWin but nicer UI and faster.
My new search setup is Agent Ransack for contents and Everything for file names (awesome tool, instant results!).
I am adding this for completeness as this post hits high in Google search results.
You can actually copy all from a regex search, just not in one step.
This might be what you are looking for:
<?php
$text = 'This is a Simple text.';
// this echoes "is is a Simple text." because 'i' is matched first
echo strpbrk($text, 'mi');
// this echoes "Simple text." because chars are case sensitive
echo strpbrk($text, 'S');
?>
Is it?
Or maybe this:
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>
Or even this
<?php
$email = '[email protected]';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>
You can read all about them in the documentation here:
Pipe the content of your
Get-ChildItem -recurse | Get-Content | Select-String -pattern "dummy"
to fl *
You will see that the path is already being returned as a property of the objects.
IF you want just the path, use select path
or select -unique path
to remove duplicates:
Get-ChildItem -recurse | Get-Content | Select-String -pattern "dummy" | select -unique path
You should also read about python packages here: http://docs.python.org/tutorial/modules.html.
From your example, I would guess that you really have a package at ~/codez/project
. The file __init__.py
in a python directory maps a directory into a namespace. If your subdirectories all have an __init__.py
file, then you only need to add the base directory to your PYTHONPATH
. For example:
PYTHONPATH=$PYTHONPATH:$HOME/adaifotis/project
In addition to testing your PYTHONPATH environment variable, as David explains, you can test it in python like this:
$ python
>>> import project # should work if PYTHONPATH set
>>> import sys
>>> for line in sys.path: print line # print current python path
...
It seems that OpenQA, guys behind Selenium, have already addressed this problem. They defined some variables to explicitely match whitespaces. In my case, I need to use an XPATH similar to //td[text()="${nbsp}"]
.
I reproduced here the text from OpenQA concerning this issue (found here):
HTML automatically normalizes whitespace within elements, ignoring leading/trailing spaces and converting extra spaces, tabs and newlines into a single space. When Selenium reads text out of the page, it attempts to duplicate this behavior, so you can ignore all the tabs and newlines in your HTML and do assertions based on how the text looks in the browser when rendered. We do this by replacing all non-visible whitespace (including the non-breaking space "
") with a single space. All visible newlines (<br>
,<p>
, and<pre>
formatted new lines) should be preserved.We use the same normalization logic on the text of HTML Selenese test case tables. This has a number of advantages. First, you don't need to look at the HTML source of the page to figure out what your assertions should be; "
" symbols are invisible to the end user, and so you shouldn't have to worry about them when writing Selenese tests. (You don't need to put "
" markers in your test case to assertText on a field that contains "
".) You may also put extra newlines and spaces in your Selenese<td>
tags; since we use the same normalization logic on the test case as we do on the text, we can ensure that assertions and the extracted text will match exactly.This creates a bit of a problem on those rare occasions when you really want/need to insert extra whitespace in your test case. For example, you may need to type text in a field like this: "
foo
". But if you simply write<td>foo </td>
in your Selenese test case, we'll replace your extra spaces with just one space.This problem has a simple workaround. We've defined a variable in Selenese,
${space}
, whose value is a single space. You can use${space}
to insert a space that won't be automatically trimmed, like this:<td>foo${space}${space}${space}</td>
. We've also included a variable${nbsp}
, that you can use to insert a non-breaking space.Note that XPaths do not normalize whitespace the way we do. If you need to write an XPath like
//div[text()="hello world"]
but the HTML of the link is really "hello world
", you'll need to insert a real "
" into your Selenese test case to get it to match, like this://div[text()="hello${nbsp}world"]
.
:g/xxxx/d
This will delete all the lines with pattern, and report how many deleted. Undo to get them back after.
Have a look at java.io.File.list()
and FilenameFilter
.
T(n)=T(n/2)+1
T(n/2)= T(n/4)+1+1
Put the value of The(n/2) in above so T(n)=T(n/4)+1+1 . . . . T(n/2^k)+1+1+1.....+1
=T(2^k/2^k)+1+1....+1 up to k
=T(1)+k
As we taken 2^k=n
K = log n
So Time complexity is O(log n)
To use quotes just for completeness.
"/Users/my/work/a project with space"/**
If not recursive, remove the /**
First of all, do you really need to store indices like this? Have you looked into std::map, enabling you to store key => value pairs?
Secondly, if you used iterators instead, you would be able to return std::vector.end() to indicate an invalid result. To convert an iterator to an index you simply use
size_t i = it - myvector.begin();
What you want to reach is that, I believe:
Besides shift + cmd + f for find in path && double shift to search anywhere. Play with those and you will know what satisfy your need.
Just put this in your .vimrc
" <Ctrl-l> redraws the screen and removes any search highlighting.
nnoremap <silent> <C-l> :nohl<CR><C-l>
I'm taking some guesses here, because I don't quite understand what you're asking.
I think that what you want is a count of the number of lines on which the pattern 'echo' appears in the given file.
I've pasted your sample text into a file called 6741967
.
First, grep
finds the matches:
james@Brindle:tmp$grep echo 6741967
echo "Preparing to add a new user..."
echo "1. Add user"
echo "2. Exit"
echo "Enter your choice: "
Second, use wc -l
to count the lines
james@Brindle:tmp$grep echo 6741967 | wc -l
4
As of mid-2019
Screenshot:
Another poossible solution is based on the array_search()
function. You need to use PHP 5.5.0 or higher.
$userdb=Array
(
(0) => Array
(
(uid) => '100',
(name) => 'Sandra Shush',
(url) => 'urlof100'
),
(1) => Array
(
(uid) => '5465',
(name) => 'Stefanie Mcmohn',
(pic_square) => 'urlof100'
),
(2) => Array
(
(uid) => '40489',
(name) => 'Michael',
(pic_square) => 'urlof40489'
)
);
$key = array_search(40489, array_column($userdb, 'uid'));
echo ("The key is: ".$key);
//This will output- The key is: 2
The function array_search()
has two arguments. The first one is the value that you want to search. The second is where the function should search. The function array_column()
gets the values of the elements which key is 'uid'
.
So you could use it as:
array_search('breville-one-touch-tea-maker-BTM800XL', array_column($products, 'slug'));
or, if you prefer:
// define function
function array_search_multidim($array, $column, $key){
return (array_search($key, array_column($array, $column)));
}
// use it
array_search_multidim($products, 'slug', 'breville-one-touch-tea-maker-BTM800XL');
The original example(by xfoxawy) can be found on the DOCS.
The array_column()
page.
Update
Due to Vael comment I was curious, so I made a simple test to meassure the performance of the method that uses array_search
and the method proposed on the accepted answer.
I created an array which contained 1000 arrays, the structure was like this (all data was randomized):
[
{
"_id": "57fe684fb22a07039b3f196c",
"index": 0,
"guid": "98dd3515-3f1e-4b89-8bb9-103b0d67e613",
"isActive": true,
"balance": "$2,372.04",
"picture": "http://placehold.it/32x32",
"age": 21,
"eyeColor": "blue",
"name": "Green",
"company": "MIXERS"
},...
]
I ran the search test 100 times searching for different values for the name field, and then I calculated the mean time in milliseconds. Here you can see an example.
Results were that the method proposed on this answer needed about 2E-7 to find the value, while the accepted answer method needed about 8E-7.
Like I said before both times are pretty aceptable for an application using an array with this size. If the size grows a lot, let's say 1M elements, then this little difference will be increased too.
Update II
I've added a test for the method based in array_walk_recursive
which was mentionend on some of the answers here. The result got is the correct one. And if we focus on the performance, its a bit worse than the others examined on the test. In the test, you can see that is about 10 times slower than the method based on array_search
. Again, this isn't a very relevant difference for the most of the applications.
Update III
Thanks to @mickmackusa for spotting several limitations on this method:
I understood the question as "How do I match a word but exclude another", for which one solution is two greps in series: First grep finding the wanted "word1", second grep excluding "word2":
grep "word1" | grep -v "word2"
In my case: I need to differentiate between "plot" and "#plot" which grep's "word" option won't do ("#" not being a alphanumerical).
Hope this helps.
You could probably use the LIKE
clause to do some simple string matching:
SELECT * FROM items WHERE items.xml LIKE '%123456%'
If you need more advanced functionality, take a look at MySQL's fulltext-search functions here: http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html
It depends on what you want the search to do:
if you want to find all matches, use the built-in grep:
my @matches = grep { /pattern/ } @list_of_strings;
if you want to find the first match, use first
in List::Util:
use List::Util 'first';
my $match = first { /pattern/ } @list_of_strings;
if you want to find the count of all matches, use true
in List::MoreUtils:
use List::MoreUtils 'true';
my $count = true { /pattern/ } @list_of_strings;
if you want to know the index of the first match, use first_index
in List::MoreUtils:
use List::MoreUtils 'first_index';
my $index = first_index { /pattern/ } @list_of_strings;
if you want to simply know if there was a match, but you don't care which element it was or its value, use any
in List::Util:
use List::Util 1.33 'any';
my $match_found = any { /pattern/ } @list_of_strings;
All these examples do similar things at their core, but their implementations have been heavily optimized to be fast, and will be faster than any pure-perl implementation that you might write yourself with grep, map or a for loop.
Note that the algorithm for doing the looping is a separate issue than performing the individual matches. To match a string case-insensitively, you can simply use the i
flag in the pattern: /pattern/i
. You should definitely read through perldoc perlre if you have not previously done so.
In the main method using for loops: -the third for loop in my example is the answer to this question. -in my example I made an array of 20 random integers, assigned a variable the smallest number, and stopped the loop when the location of the array reached the smallest value while counting the number of loops.
import java.util.Random;
public class scratch {
public static void main(String[] args){
Random rnd = new Random();
int randomIntegers[] = new int[20];
double smallest = randomIntegers[0];
int location = 0;
for(int i = 0; i < randomIntegers.length; i++){ // fills array with random integers
randomIntegers[i] = rnd.nextInt(99) + 1;
System.out.println(" --" + i + "-- " + randomIntegers[i]);
}
for (int i = 0; i < randomIntegers.length; i++){ // get the location of smallest number in the array
if(randomIntegers[i] < smallest){
smallest = randomIntegers[i];
}
}
for (int i = 0; i < randomIntegers.length; i++){
if(randomIntegers[i] == smallest){ //break the loop when array location value == <smallest>
break;
}
location ++;
}
System.out.println("location: " + location + "\nsmallest: " + smallest);
}
}
Code outputs all the numbers and their locations, and the location of the smallest number followed by the smallest number.
When you have opened a folder in a workspace you can do Ctrl+P (Cmd+P on Mac) and start typing the filename, or extension to filter the list of filenames
if you have:
You can type css
and press enter and it will open the page.css
. If you type .ts
the list is filtered and contains two items.
Yes you can and your DBA will hate you and will find you to nail your shoes to the floor because that will cause lots of I/O and bring the database performance really down as the cache purges.
select column_name from all_tab_columns c, user_all_tables u where c.table_name = u.table_name;
for a start.
I would start with the running queries, using the v$session
and the v$sqlarea
. This changes based on oracle version. This will narrow down the space and not hit everything.
Despite JAVA 8 SDK there is a lot of collection tools libraries can help you to work with, for instance: http://commons.apache.org/proper/commons-collections/
Predicate condition = new Predicate() {
boolean evaluate(Object obj) {
return ((Sample)obj).myField.equals("myVal");
}
};
List result = CollectionUtils.select( list, condition );
The Best Order I've seen :
// SearchList is your List
// TEXT is your Search Text
// SubList is your result
ArrayList<String> TempList = new ArrayList<String>(
(SearchList));
int temp = 0;
int num = 0;
ArrayList<String> SubList = new ArrayList<String>();
while (temp > -1) {
temp = TempList.indexOf(new Object() {
@Override
public boolean equals(Object obj) {
return obj.toString().startsWith(TEXT);
}
});
if (temp > -1) {
SubList.add(SearchList.get(temp + num++));
TempList.remove(temp);
}
}
If you are searching for the index of the last occurrence of myvalue
in mylist
:
len(mylist) - mylist[::-1].index(myvalue) - 1
I came upon this post looking to do the same and came up with my own solution I wanted to offer for future visitors of this page (and to see if doing this way presents any problems I had not forseen).
If you want to get a simple true
or false
output and want to do this with one line of code without a function or a loop you could serialize the array and then use stripos
to search for the value:
stripos(serialize($my_array),$needle)
It seems to work for me.
A linear search works by looking at each element in a list of data until it either finds the target or reaches the end. This results in O(n) performance on a given list. A binary search comes with the prerequisite that the data must be sorted. We can leverage this information to decrease the number of items we need to look at to find our target. We know that if we look at a random item in the data (let's say the middle item) and that item is greater than our target, then all items to the right of that item will also be greater than our target. This means that we only need to look at the left part of the data. Basically, each time we search for the target and miss, we can eliminate half of the remaining items. This gives us a nice O(log n) time complexity.
Just remember that sorting data, even with the most efficient algorithm, will always be slower than a linear search (the fastest sorting algorithms are O(n * log n)). So you should never sort data just to perform a single binary search later on. But if you will be performing many searches (say at least O(log n) searches), it may be worthwhile to sort the data so that you can perform binary searches. You might also consider other data structures such as a hash table in such situations.
match is much faster than search, so instead of doing regex.search("word") you can do regex.match((.*?)word(.*?)) and gain tons of performance if you are working with millions of samples.
This comment from @ivan_bilan under the accepted answer above got me thinking if such hack is actually speeding anything up, so let's find out how many tons of performance you will really gain.
I prepared the following test suite:
import random
import re
import string
import time
LENGTH = 10
LIST_SIZE = 1000000
def generate_word():
word = [random.choice(string.ascii_lowercase) for _ in range(LENGTH)]
word = ''.join(word)
return word
wordlist = [generate_word() for _ in range(LIST_SIZE)]
start = time.time()
[re.search('python', word) for word in wordlist]
print('search:', time.time() - start)
start = time.time()
[re.match('(.*?)python(.*?)', word) for word in wordlist]
print('match:', time.time() - start)
I made 10 measurements (1M, 2M, ..., 10M words) which gave me the following plot:
The resulting lines are surprisingly (actually not that surprisingly) straight. And the search
function is (slightly) faster given this specific pattern combination. The moral of this test: Avoid overoptimizing your code.
You would expect that this is easily possible but that seems not be the case. The only way I see at the moment is to create a user defined JQL function. I never tried this but here is a plug-in:
http://confluence.atlassian.com/display/DEVNET/Plugin+Tutorial+-+Adding+a+JQL+Function+to+JIRA
If you just want to skip binary files, I suggest you look at the -I
(upper case i) option. It ignores binary files. I regularly use the following command:
grep -rI --exclude-dir="\.svn" "pattern" *
It searches recursively, ignores binary files, and doesn't look inside Subversion hidden folders, for whatever pattern I want. I have it aliased as "grepsvn" on my box at work.
It seems that resource filtering/searching can be implemented in a RESTful way. The idea is to introduce a new endpoint called /filters/
or /api/filters/
.
Using this endpoint filter can be considered as a resource and hence created via POST
method. This way - of course - body can be used to carry all the parameters as well as complex search/filter structures can be created.
After creating such filter there are two possibilities to get the search/filter result.
A new resource with unique ID will be returned along with 201 Created
status code. Then using this ID a GET
request can be made to /api/users/
like:
GET /api/users/?filterId=1234-abcd
After new filter is created via POST
it won't reply with 201 Created
but at once with 303 SeeOther
along with Location
header pointing to /api/users/?filterId=1234-abcd
. This redirect will be automatically handled via underlying library.
In both scenarios two requests need to be made to get the filtered results - this may be considered as a drawback, especially for mobile applications. For mobile applications I'd use single POST
call to /api/users/filter/
.
How to keep created filters?
They can be stored in DB and used later on. They can also be stored in some temporary storage e.g. redis and have some TTL after which they will expire and will be removed.
What are the advantages of this idea?
Filters, filtered results are cacheable and can be even bookmarked.
<shameless-plug>
Search+ is a notepad++ plugin that does exactly this. You can download it from here and install it following the steps mentioned here
Feel free to post any issues/suggestions here.
</shameless-plug>
--reverse is also helpful since you want the first commit that made the change:
git log --all -p --reverse --source -S 'needle'
This way older commits will appear first.
Just search for the string in plain old indexOf
arr.forEach(function(a){
if (typeof(a) == 'string' && a.indexOf('curl')>-1) {
console.log(a);
}
});
public class searchingFile
{
static String path;//defining(not initializing) these variables outside main
static String filename;//so that recursive function can access them
static int counter=0;//adding static so that can be accessed by static methods
public static void main(String[] args) //main methods begins
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the path : ");
path=sc.nextLine(); //storing path in path variable
System.out.println("Enter file name : ");
filename=sc.nextLine(); //storing filename in filename variable
searchfile(path);//calling our recursive function and passing path as argument
System.out.println("Number of locations file found at : "+counter);//Printing occurences
}
public static String searchfile(String path)//declaring recursive function having return
//type and argument both strings
{
File file=new File(path);//denoting the path
File[] filelist=file.listFiles();//storing all the files and directories in array
for (int i = 0; i < filelist.length; i++) //for loop for accessing all resources
{
if(filelist[i].getName().equals(filename))//if loop is true if resource name=filename
{
System.out.println("File is present at : "+filelist[i].getAbsolutePath());
//if loop is true,this will print it's location
counter++;//counter increments if file found
}
if(filelist[i].isDirectory())// if resource is a directory,we want to inside that folder
{
path=filelist[i].getAbsolutePath();//this is the path of the subfolder
searchfile(path);//this path is again passed into the searchfile function
//and this countinues untill we reach a file which has
//no sub directories
}
}
return path;// returning path variable as it is the return type and also
// because function needs path as argument.
}
}
I did something close to that, the compiler is seeing that your return statement is in an If() statement. If you wish to resolve this error, simply create a new local variable called customerId before the If statement, then assign a value inside of the if statement. After the if statement, call your return statement, and return cstomerId. Like this:
Customer findCustomerByid(int id)
{
boolean exist=false;
if(this.customers.isEmpty()) {
return null;
}
for(int i=0;i<this.customers.size();i++) {
if(this.customers.get(i).getId() == id) {
exist=true;
break;
}
int customerId;
if(exist) {
customerId = this.customers.get(id);
} else {
customerId = this.customers.get(id);
}
}
return customerId;
}
Concatenating the querysets into a list is the simplest approach. If the database will be hit for all querysets anyway (e.g. because the result needs to be sorted), this won't add further cost.
from itertools import chain
result_list = list(chain(page_list, article_list, post_list))
Using itertools.chain
is faster than looping each list and appending elements one by one, since itertools
is implemented in C. It also consumes less memory than converting each queryset into a list before concatenating.
Now it's possible to sort the resulting list e.g. by date (as requested in hasen j's comment to another answer). The sorted()
function conveniently accepts a generator and returns a list:
result_list = sorted(
chain(page_list, article_list, post_list),
key=lambda instance: instance.date_created)
If you're using Python 2.4 or later, you can use attrgetter
instead of a lambda. I remember reading about it being faster, but I didn't see a noticeable speed difference for a million item list.
from operator import attrgetter
result_list = sorted(
chain(page_list, article_list, post_list),
key=attrgetter('date_created'))
I'm not sure I quite understand the question but if you want to search objects on the database for a particular search string try:
SELECT owner, name, type, line, text
FROM dba_source
WHERE instr(UPPER(text), UPPER(:srch_str)) > 0;
From there if you need any more info you can just look up the object / line number.
Assuming you have Notepad++, an often-missed feature is 'Find in files', which is extremely fast and comes with filters, regular expressions, replace and all the N++ goodies.
This was very helpful. I wanted to import this function to a Postgre SQL database. Thought i would share it with anyone who is interested. Will have them a few hours. Note: this function creates a list of SQL statements that can be copied and executed on the Postgre database. Maybe someone smarter then me can get Postgre to create and execute the statements all in one function.
CREATE OR REPLACE FUNCTION SearchAllTables(_search text) RETURNS TABLE( txt text ) as $funct$
DECLARE __COUNT int;
__SQL text;
BEGIN
EXECUTE 'SELECT COUNT(0) FROM INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE = ''text''
AND table_schema = ''public'' ' INTO __COUNT;
RETURN QUERY
SELECT CASE WHEN ROW_NUMBER() OVER (ORDER BY table_name) < __COUNT THEN
'SELECT ''' || table_name ||'.'|| column_name || ''' AS tbl, "' || column_name || '" AS col FROM "public"."' || "table_name" || '" WHERE "'|| "column_name" || '" ILIKE ''%' || _search || '%'' UNION ALL'
ELSE
'SELECT ''' || table_name ||'.'|| column_name || ''' AS tbl, "' || column_name || '" AS col FROM "public"."' || "table_name" || '" WHERE "'|| "column_name" || '" ILIKE ''%' || _search || '%'''
END AS txt
FROM INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE = 'text'
AND table_schema = 'public';
END
$funct$ LANGUAGE plpgsql;
A PHP Based Solution for search entire table ! Search string is $string . This is generic and will work with all the tables with any number of fields
$sql="SELECT * from client_wireless";
$sql_query=mysql_query($sql);
$logicStr="WHERE ";
$count=mysql_num_fields($sql_query);
for($i=0 ; $i < mysql_num_fields($sql_query) ; $i++){
if($i == ($count-1) )
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$string."%' ";
else
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$string."%' OR ";
}
// start the search in all the fields and when a match is found, go on printing it .
$sql="SELECT * from client_wireless ".$logicStr;
//echo $sql;
$query=mysql_query($sql);
Here is a fast vectorized version of @Dimitri's solution if you have many values
to search for (values
can be multi-dimensional array):
#`values` should be sorted
def get_closest(array, values):
#make sure array is a numpy array
array = np.array(array)
# get insert positions
idxs = np.searchsorted(array, values, side="left")
# find indexes where previous index is closer
prev_idx_is_less = ((idxs == len(array))|(np.fabs(values - array[np.maximum(idxs-1, 0)]) < np.fabs(values - array[np.minimum(idxs, len(array)-1)])))
idxs[prev_idx_is_less] -= 1
return array[idxs]
Benchmarks
> 100 times faster than using a for
loop with @Demitri's solution`
>>> %timeit ar=get_closest(np.linspace(1, 1000, 100), np.random.randint(0, 1050, (1000, 1000)))
139 ms ± 4.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
>>> %timeit ar=[find_nearest(np.linspace(1, 1000, 100), value) for value in np.random.randint(0, 1050, 1000*1000)]
took 21.4 seconds
I used a similar method to the IndexOf by Maitrey684 and the foreach loop of Theomax to create this. (Note: the first 3 "string" lines are just an example of how you could create an array and get it into the proper format).
If you want to compare 2 arrays, they will be semi-colon delimited, but the last value won't have one after it. If you append a semi-colon to the string form of the array (i.e. a;b;c becomes a;b;c;), you can match using "x;" no matter what position it is in:
bool found = false;
string someString = "a-b-c";
string[] arrString = someString.Split('-');
string myStringArray = arrString.ToString() + ";";
foreach (string s in otherArray)
{
if (myStringArray.IndexOf(s + ";") != -1) {
found = true;
break;
}
}
if (found == true) {
// ....
}
You can use option -A (after) and -B (before) in your grep command try grep -nri -A 5 -B 5 .
You can press ctrl+t to get a editor Get to all , in which you can type the file name to navigate to that specific file.
Just a note, FishEye (and a lot of other Atlassian products) have a $10 Starter Editions, which in the case of FishEye gives you 5 repositories and access for up to 10 committers. The money goes to charity in this case.
One more way/syntax to do it is: git log -S "word"
Like this you can search for example git log -S "with whitespaces and stuff @/#ü !"
If any cell in a row contains the searched phrase or word, this function shows that row otherwise hides it.
<input type="text" class="search-table"/>
$(document).on("keyup",".search-table", function () {
var value = $(this).val();
$("table tr").each(function (index) {
$row = $(this);
$row.show();
if (index !== 0 && value) {
var found = false;
$row.find("td").each(function () {
var cell = $(this).text();
if (cell.indexOf(value.toLowerCase()) >= 0) {
found = true;
return;
}
});
if (found === true) {
$row.show();
}
else {
$row.hide();
}
}
});
});
Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
@Override
public void afterTextChanged(Editable arg0) {}
});
The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.
EDIT
To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.
class CustomAdapter extends BaseAdapter implements Filterable {
public View getView(){
...
}
public Integer getCount()
{
...
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayListNames = (List<String>) results.values;
notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<String> FilteredArrayNames = new ArrayList<String>();
// perform your search here using the searchConstraint String.
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mDatabaseOfNames.size(); i++) {
String dataNames = mDatabaseOfNames.get(i);
if (dataNames.toLowerCase().startsWith(constraint.toString())) {
FilteredArrayNames.add(dataNames);
}
}
results.count = FilteredArrayNames.size();
results.values = FilteredArrayNames;
Log.e("VALUES", results.values.toString());
return results;
}
};
return filter;
}
}
Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.
An extension to Joachim Isaksson's answer: Quite often I need something from the middle of a long file, e.g. lines 5001 to 5020, in which case you can combine head
with tail
:
head -5020 file.txt | tail -20 | grep x
This gets the first 5020 lines, then shows only the last 20 of those, then pipes everything to grep.
(Edited: fencepost error in my example numbers, added pipe to grep)
In addition to what other have said, you may also be interested to know that what in
does is to call the list.__contains__
method, that you can define on any class you write and can get extremely handy to use python at his full extent.
A dumb use may be:
>>> class ContainsEverything:
def __init__(self):
return None
def __contains__(self, *elem, **k):
return True
>>> a = ContainsEverything()
>>> 3 in a
True
>>> a in a
True
>>> False in a
True
>>> False not in a
False
>>>
this will return first match
@fathers.detect {|f| f["age"] > 35 }
one way...
$needle = "blah";
$content = file_get_contents('file.txt');
preg_match('~^(.*'.$needle.'.*)$~',$content,$line);
echo $line[1];
though it would probably be better to read it line by line with fopen() and fread() and use strpos()
You can find the object in array with Alasql library:
var data = [ { name : "bob" , dinner : "pizza" }, { name : "john" , dinner : "sushi" },
{ name : "larry", dinner : "hummus" } ];
var res = alasql('SELECT * FROM ? WHERE dinner="sushi"',[data]);
Try this example in jsFiddle.
Perl version (of the leading answer):
use strict;
sub subset_sum {
my ($numbers, $target, $result, $sum) = @_;
print 'sum('.join(',', @$result).") = $target\n" if $sum == $target;
return if $sum >= $target;
subset_sum([@$numbers[$_ + 1 .. $#$numbers]], $target,
[@{$result||[]}, $numbers->[$_]], $sum + $numbers->[$_])
for (0 .. $#$numbers);
}
subset_sum([3,9,8,4,5,7,10,6], 15);
Result:
sum(3,8,4) = 15
sum(3,5,7) = 15
sum(9,6) = 15
sum(8,7) = 15
sum(4,5,6) = 15
sum(5,10) = 15
Javascript version:
const subsetSum = (numbers, target, partial = [], sum = 0) => {_x000D_
if (sum < target)_x000D_
numbers.forEach((num, i) =>_x000D_
subsetSum(numbers.slice(i + 1), target, partial.concat([num]), sum + num));_x000D_
else if (sum == target)_x000D_
console.log('sum(%s) = %s', partial.join(), target);_x000D_
}_x000D_
_x000D_
subsetSum([3,9,8,4,5,7,10,6], 15);
_x000D_
Javascript one-liner that actually returns results (instead of printing it):
const subsetSum=(n,t,p=[],s=0,r=[])=>(s<t?n.forEach((l,i)=>subsetSum(n.slice(i+1),t,[...p,l],s+l,r)):s==t?r.push(p):0,r);_x000D_
_x000D_
console.log(subsetSum([3,9,8,4,5,7,10,6], 15));
_x000D_
And my favorite, one-liner with callback:
const subsetSum=(n,t,cb,p=[],s=0)=>s<t?n.forEach((l,i)=>subsetSum(n.slice(i+1),t,cb,[...p,l],s+l)):s==t?cb(p):0;_x000D_
_x000D_
subsetSum([3,9,8,4,5,7,10,6], 15, console.log);
_x000D_
Thanks to both of you. This worked perfectly for me.
$("input[type='text'][id*=" + strID + "]:visible").each(function() {
this.value=strVal;
});
The Replace string function will do that.
boolean found;
for(CustomObject obj : ArrayOfCustObj) {
if(obj.getName.equals("Android")) {
found = true;
}
}
Update January 2013: a brand new search has arrived!, based on elasticsearch.org:
A search for stat within the ruby repo will be expressed as stat repo:ruby/ruby
, and will now just workTM.
(the repo name is not case sensitive: test repo:wordpress/wordpress
returns the same as test repo:Wordpress/Wordpress
)
Will give:
And you have many other examples of search, based on followers, or on forks, or...
Update July 2012 (old days of Lucene search and poor code indexing, combined with broken GUI, kept here for archive):
The search (based on SolrQuerySyntax) is now more permissive and the dreaded "Invalid search query. Try quoting it.
" is gone when using the default search selector "Everything":)
(I suppose we can all than Tim Pease, which had in one of his objectives "hacking on improved search experiences for all GitHub properties", and I did mention this Stack Overflow question at the time ;) )
Here is an illustration of a grep within the ruby code: it will looks for repos and users, but also for what I wanted to search in the first place: the code!
Initial answer and illustration of the former issue (Sept. 2012 => March 2012)
You can use the advanced search GitHub form:
Code
, Repositories
or Users
from the drop-down and For instance, Use the repo:username/repo-name
directive to limit the search to a code repository.
The initial "Advanced Search
" page includes the section:
Code Search:
The Code search will look through all of the code publicly hosted on GitHub. You can also filter by :
- the language
language:
- the repository name (including the username)
repo:
- the file path
path:
So if you select the "Code
" search selector, then your query grepping for a text within a repo will work:
What is incredibly unhelpful from GitHub is that:
Code
"), you will get an error message:Invalid search query. Try quoting it.
" the error message doesn't help you at all.
No amount of "quoting it
" will get you out of this error.
once you get that error message, you don't get the sections reminding you of the right association between the search selectors ("Repositories
", "Users
" or "Language
") and the (right) search filters (here "repo:
").
Any further attempt you do won't display those associations (selectors-filters) back. Only the error message you see above...
The only way to get back those arrays is by clicking the "Advance Search
" icon:
the "Everything
" search selector, which is the default, is actually the wrong one for all of the search filters! Except "language:
"...
(You could imagine/assume that "Everything
" would help you to pick whatever search selector actually works with the search filter "repo:
", but nope. That would be too easy)
you cannot specify the search selector you want through the "Advance Search
" field alone!
(but you can for "language:
", even though "Search Language
" is another combo box just below the "Search for
" 'type' one...)
So, the user's experience usually is as follows:
Advanced Search
", glance over those sections of filters, and notice one you want to use: "repo:
"repo:jruby/jruby stat
", but with the default Search selector "Everything
"FAIL
! (and the arrays displaying the association "Selectors-Filters" is gone)Repositories
" ("Dah! I want to search within repositories...")FAIL
!Users
"), without even looking at said selector, just to give it one more try...FAIL
!So, to recap, if you want to "grep for something inside a Github project's code", as the OP Ben Humphreys, don't forget to select the "Code
" search selector...
As per @lvkz comment :
if you are using datatable with uppercase d .DataTable()
( this will return a Datatable API object ) use this :
oTable.search($(this).val()).draw() ;
which is @netbrain answer.
if you are using datatable with lowercase d .dataTable()
( this will return a jquery object ) use this :
oTable.fnFilter($(this).val());
Here's another way that might be faster, in terms of compute time, than iterating. Not sure. The idea is to convert the array to a string, truncate it, and get the size of the new array.
For example, to find the index of 'd':
arr=(a b c d)
temp=`echo ${arr[@]}`
temp=( ${temp%%d*} )
index=${#temp[@]}
You could turn this into a function like:
get-index() {
Item=$1
Array="$2[@]"
ArgArray=( ${!Array} )
NewArray=( ${!Array%%${Item}*} )
Index=${#NewArray[@]}
[[ ${#ArgArray[@]} == ${#NewArray[@]} ]] && echo -1 || echo $Index
}
You could then call:
get-index d arr
and it would echo back 3, which would be assignable with:
index=`get-index d arr`
Suppose provided array is inPutArray = [1,2,5,8,7,3] expected O/P -> 7 (second largest)
take temp array
temp = [0,0], int dummmy=0;
for (no in inPutArray) {
if(temp[1]<no)
temp[1] = no
if(temp[0]<temp[1]){
dummmy = temp[0]
temp[0] = temp[1]
temp[1] = temp
}
}
print("Second largest no is %d",temp[1])
You can give a try to Apache Commons Collections.
There is a class CollectionUtils that allows you to select or filter items by custom Predicate.
Your code would be like this:
Predicate condition = new Predicate() {
boolean evaluate(Object sample) {
return ((Sample)sample).value3.equals("three");
}
};
List result = CollectionUtils.select( list, condition );
Update:
In java8, using Lambdas and StreamAPI this should be:
List<Sample> result = list.stream()
.filter(item -> item.value3.equals("three"))
.collect(Collectors.toList());
much nicer!
And another version that returns the key value from the array element in which the value is found (no recursion, optimized for speed):
// if the array is
$arr['apples'] = array('id' => 1);
$arr['oranges'] = array('id' => 2);
//then
print_r(search_array($arr, 'id', 2);
// returns Array ( [oranges] => Array ( [id] => 2 ) )
// instead of Array ( [0] => Array ( [id] => 2 ) )
// search array for specific key = value
function search_array($array, $key, $value) {
$return = array();
foreach ($array as $k=>$subarray){
if (isset($subarray[$key]) && $subarray[$key] == $value) {
$return[$k] = $subarray;
return $return;
}
}
}
Thanks to all who posted here.
if you want to search tuple for any number which is present in tuple then you can use
a= [(1,2),(1,4),(3,5),(5,7)]
i=1
result=[]
for j in a:
if i in j:
result.append(j)
print(result)
You can also use if i==j[0] or i==j[index]
if you want to search a number in particular index
The explicit way of saying "search until X
but not including X
" is:
(?:(?!X).)*
where X
can be any regular expression.
In your case, though, this might be overkill - here the easiest way would be
[^z]*
This will match anything except z
and therefore stop right before the next z
.
So .*?quick[^z]*
will match The quick fox jumps over the la
.
However, as soon as you have more than one simple letter to look out for, (?:(?!X).)*
comes into play, for example
(?:(?!lazy).)*
- match anything until the start of the word lazy
.
This is using a lookahead assertion, more specifically a negative lookahead.
.*?quick(?:(?!lazy).)*
will match The quick fox jumps over the
.
Explanation:
(?: # Match the following but do not capture it:
(?!lazy) # (first assert that it's not possible to match "lazy" here
. # then match any character
)* # end of group, zero or more repetitions.
Furthermore, when searching for keywords, you might want to surround them with word boundary anchors: \bfox\b
will only match the complete word fox
but not the fox in foxy
.
Note
If the text to be matched can also include linebreaks, you will need to set the "dot matches all" option of your regex engine. Usually, you can achieve that by prepending (?s)
to the regex, but that doesn't work in all regex engines (notably JavaScript).
Alternative solution:
In many cases, you can also use a simpler, more readable solution that uses a lazy quantifier. By adding a ?
to the *
quantifier, it will try to match as few characters as possible from the current position:
.*?(?=(?:X)|$)
will match any number of characters, stopping right before X
(which can be any regex) or the end of the string (if X
doesn't match). You may also need to set the "dot matches all" option for this to work. (Note: I added a non-capturing group around X
in order to reliably isolate it from the alternation)
Although a bit late, but a more compact version may be the following:
/**
* @param {string} quickCriteria Any string value to search for in the object properties.
* @param {any[]} objectArray The array of objects as the search domain
* @return {any[]} the search result
*/
onQuickSearchChangeHandler(quickCriteria, objectArray){
let quickResult = objectArray.filter(obj => Object.values(obj).some(val => val?val.toString().toLowerCase().includes(quickCriteria):false));
return quickResult;
}
It can handle falsy values like false, undefined, null and all the data types that define .toString()
method like number, boolean
etc.
you mentioned "entire line" , so i assumed mystring is the entire line.
if "token" in mystring:
print(mystring)
however if you want to just get "token qwerty",
>>> mystring="""
... qwertyuiop
... asdfghjkl
...
... zxcvbnm
... token qwerty
...
... asdfghjklñ
... """
>>> for item in mystring.split("\n"):
... if "token" in item:
... print (item.strip())
...
token qwerty
Build lists of matched lines - several flavors:
def lines_that_equal(line_to_match, fp):
return [line for line in fp if line == line_to_match]
def lines_that_contain(string, fp):
return [line for line in fp if string in line]
def lines_that_start_with(string, fp):
return [line for line in fp if line.startswith(string)]
def lines_that_end_with(string, fp):
return [line for line in fp if line.endswith(string)]
Build generator of matched lines (memory efficient):
def generate_lines_that_equal(string, fp):
for line in fp:
if line == string:
yield line
Print all matching lines (find all matches first, then print them):
with open("file.txt", "r") as fp:
for line in lines_that_equal("my_string", fp):
print line
Print all matching lines (print them lazily, as we find them)
with open("file.txt", "r") as fp:
for line in generate_lines_that_equal("my_string", fp):
print line
Generators (produced by yield) are your friends, especially with large files that don't fit into memory.
It depends on how efficient you need things to be. Simply iterating over the list looking for the element which satisfies a certain condition is O(n), but so is ArrayList.Contains if you could implement the Equals method. If you're not doing this in loops or inner loops this approach is probably just fine.
If you really need very efficient look-up speeds at all cost, you'll need to do two things:
Of course, building this HashSet still has a O(n) cost. You are only going to gain anything if the cost of building the HashSet is negligible compared to the total cost of all the contains() checks that you need to do. Trying to build a list without duplicates is such a case.
Try vi with the -b option, this will show special end of line characters (I typically use it to see windows line endings in a txt file on a unix OS)
But if you want a scripted solution obviously vi wont work so you can try the -f or -e options with grep and pipe the result into sed or awk. From grep man page:
Matcher Selection -E, --extended-regexp Interpret PATTERN as an extended regular expression (ERE, see below). (-E is specified by POSIX.)
-F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched. (-F is specified
by POSIX.)
I will answer the 1 GB version:
There is not enough information in the question, so I will state some assumptions first:
The integer is 32 bits with range -2,147,483,648 to 2,147,483,647.
Pseudo-code:
var bitArray = new bit[4294967296]; // 0.5 GB, initialized to all 0s.
foreach (var number in file) {
bitArray[number + 2147483648] = 1; // Shift all numbers so they start at 0.
}
for (var i = 0; i < 4294967296; i++) {
if (bitArray[i] == 0) {
return i - 2147483648;
}
}
//when a Department selecting
$('#department_id').on('select2-selecting', function (e) {
console.log("Action Before Selected");
var deptid=e.choice.id;
var depttext=e.choice.text;
console.log("Department ID "+deptid);
console.log("Department Text "+depttext);
});
//when a Department removing
$('#department_id').on('select2-removing', function (e) {
console.log("Action Before Deleted");
var deptid=e.choice.id;
var depttext=e.choice.text;
console.log("Department ID "+deptid);
console.log("Department Text "+depttext);
});
I simplified your code to isolate the test for "%" being in the cell. Once you get that to work, you can add in the rest of your code.
Try this:
Option Explicit
Sub DoIHavePercentSymbol()
Dim rng As Range
Set rng = ActiveCell
Do While rng.Value <> Empty
If InStr(rng.Value, "%") = 0 Then
MsgBox "I know nothing about percentages!"
Set rng = rng.Offset(1)
rng.Select
Else
MsgBox "I contain a % symbol!"
Set rng = rng.Offset(1)
rng.Select
End If
Loop
End Sub
InStr
will return the number of times your search text appears in the string. I changed your if
test to check for no matches first.
The message boxes and the .Selects
are there simply for you to see what is happening while you are stepping through the code. Take them out once you get it working.
The definitive answer to this is from Facebook themselves. In post today at https://developers.facebook.com/bugs/335452696581712 a Facebook dev says
The ability to pass in an e-mail address into the "user" search type was
removed on July 10, 2013. This search type only returns results that match
a user's name (including alternate name).
So, alas, the simple answer is you can no longer search for users by their email address. This sucks, but that's Facebook's new rules.
Yes, you can use SQL IN
operator to search multiple absolute values:
SELECT name FROM products WHERE name IN ( 'Value1', 'Value2', ... );
If you want to use LIKE
you will need to use OR
instead:
SELECT name FROM products WHERE name LIKE '%Value1' OR name LIKE '%Value2';
Using AND
(as you tried) requires ALL conditions to be true, using OR
requires at least one to be true.
(See answer below for a Angular 1.3 solution.)
The issue here is that the search will execute every time the model changes, which is every keyup action on an input.
There would be cleaner ways to do this, but probably the easiest way would be to switch the binding so that you have a $scope property defined inside your Controller on which your filter operates. That way you can control how frequently that $scope variable is updated. Something like this:
JS:
var App = angular.module('App', []);
App.controller('DisplayController', function($scope, $http, $timeout) {
$http.get('data.json').then(function(result){
$scope.entries = result.data;
});
// This is what you will bind the filter to
$scope.filterText = '';
// Instantiate these variables outside the watch
var tempFilterText = '',
filterTextTimeout;
$scope.$watch('searchText', function (val) {
if (filterTextTimeout) $timeout.cancel(filterTextTimeout);
tempFilterText = val;
filterTextTimeout = $timeout(function() {
$scope.filterText = tempFilterText;
}, 250); // delay 250 ms
})
});
HTML:
<input id="searchText" type="search" placeholder="live search..." ng-model="searchText" />
<div class="entry" ng-repeat="entry in entries | filter:filterText">
<span>{{entry.content}}</span>
</div>
Use re.findall
or re.finditer
instead.
re.findall(pattern, string)
returns a list of matching strings.
re.finditer(pattern, string)
returns an iterator over MatchObject
objects.
Example:
re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']
[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']
A generator expression is probably the most performant and simple solution to your problem:
l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
result = next((i for i, v in enumerate(l) if v[0] == 53), None)
# 2
There are several answers that provide a simple solution to this question with list comprehensions. While these answers are perfectly correct, they are not optimal. Depending on your use case, there may be significant benefits to making a few simple modifications.
The main problem I see with using a list comprehension for this use case is that the entire list will be processed, although you only want to find 1 element.
Python provides a simple construct which is ideal here. It is called the generator expression. Here is an example:
# Our input list, same as before
l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
# Call next on our generator expression.
next((i for i, v in enumerate(l) if v[0] == 53), None)
We can expect this method to perform basically the same as list comprehensions in our trivial example, but what if we're working with a larger data set?
That's where the advantage of using the generator method comes into play.
Rather than constructing a new list, we'll use your existing list as our iterable, and use next()
to get the first item from our generator.
Lets look at how these methods perform differently on some larger data sets. These are large lists, made of 10000000 + 1 elements, with our target at the beginning (best) or end (worst). We can verify that both of these lists will perform equally using the following list comprehension:
worst_case = ([(False, 'F')] * 10000000) + [(True, 'T')]
print [i for i, v in enumerate(worst_case) if v[0] is True]
# [10000000]
# 2 function calls in 3.885 seconds
#
# Ordered by: standard name
#
# ncalls tottime percall cumtime percall filename:lineno(function)
# 1 3.885 3.885 3.885 3.885 so_lc.py:1(<module>)
# 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
best_case = [(True, 'T')] + ([(False, 'F')] * 10000000)
print [i for i, v in enumerate(best_case) if v[0] is True]
# [0]
# 2 function calls in 3.864 seconds
#
# Ordered by: standard name
#
# ncalls tottime percall cumtime percall filename:lineno(function)
# 1 3.864 3.864 3.864 3.864 so_lc.py:1(<module>)
# 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Here's my hypothesis for generators: we'll see that generators will significantly perform better in the best case, but similarly in the worst case. This performance gain is mostly due to the fact that the generator is evaluated lazily, meaning it will only compute what is required to yield a value.
# 10000000
# 5 function calls in 1.733 seconds
#
# Ordered by: standard name
#
# ncalls tottime percall cumtime percall filename:lineno(function)
# 2 1.455 0.727 1.455 0.727 so_lc.py:10(<genexpr>)
# 1 0.278 0.278 1.733 1.733 so_lc.py:9(<module>)
# 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
# 1 0.000 0.000 1.455 1.455 {next}
best_case = [(True, 'T')] + ([(False, 'F')] * 10000000)
print next((i for i, v in enumerate(best_case) if v[0] == True), None)
# 0
# 5 function calls in 0.316 seconds
#
# Ordered by: standard name
#
# ncalls tottime percall cumtime percall filename:lineno(function)
# 1 0.316 0.316 0.316 0.316 so_lc.py:6(<module>)
# 2 0.000 0.000 0.000 0.000 so_lc.py:7(<genexpr>)
# 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
# 1 0.000 0.000 0.000 0.000 {next}
WHAT?! The best case blows away the list comprehensions, but I wasn't expecting the our worst case to outperform the list comprehensions to such an extent. How is that? Frankly, I could only speculate without further research.
Take all of this with a grain of salt, I have not run any robust profiling here, just some very basic testing. This should be sufficient to appreciate that a generator expression is more performant for this type of list searching.
Note that this is all basic, built-in python. We don't need to import anything or use any libraries.
I first saw this technique for searching in the Udacity cs212 course with Peter Norvig.
From within less (in Linux):
g and the line number to go forward
G and the line number to go backwards
Used alone, g and G will take you to the first and last line in a file respectively; used with a number they are both equivalent.
An example; you want to go to line 320123 of a file,
press 'g' and after the colon type in the number 320123
Additionally you can type '-N' inside less to activate / deactivate the line numbers. You can as a matter of fact pass any command line switches from inside the program, such as -j or -N.
NOTE: You can provide the line number in the command line to start less (less +number -N) which will be much faster than doing it from inside the program:
less +12345 -N /var/log/hugelogfile
This will open a file displaying the line numbers and starting at line 12345
Source: man 1 less and built-in help in less (less 418)
Besides grep
, you can also use other utilities such as awk
or sed
Here is a few examples. Let say you want to search for a string is
in the file named GPL
.
Your sample file
user@linux:~$ cat -n GPL
1 The GNU General Public License is a free, copyleft license for
2 The licenses for most software and other practical works are designed
3 the GNU General Public License is intended to guarantee your freedom to
4 GNU General Public License for most of our software;
user@linux:~$
1. grep
user@linux:~$ grep is GPL
The GNU General Public License is a free, copyleft license for
the GNU General Public License is intended to guarantee your freedom to
user@linux:~$
2. awk
user@linux:~$ awk /is/ GPL
The GNU General Public License is a free, copyleft license for
the GNU General Public License is intended to guarantee your freedom to
user@linux:~$
3. sed
user@linux:~$ sed -n '/is/p' GPL
The GNU General Public License is a free, copyleft license for
the GNU General Public License is intended to guarantee your freedom to
user@linux:~$
Hope this helps
Most (if not all) implementations proposed here have two flaws:
An updated proposition:
def find_first_in_list(objects, **kwargs):
return next((obj for obj in objects if
len(set(obj.keys()).intersection(kwargs.keys())) > 0 and
all([obj[k] == v for k, v in kwargs.items() if k in obj.keys()])),
None)
Maybe not the most pythonic, but at least a bit more failsafe.
Usage:
>>> obj1 = find_first_in_list(list_of_dict, name='Pam', age=7)
>>> obj2 = find_first_in_list(list_of_dict, name='Pam', age=27)
>>> obj3 = find_first_in_list(list_of_dict, name='Pam', address='nowhere')
>>>
>>> print(obj1, obj2, obj3)
{"name": "Pam", "age": 7}, None, {"name": "Pam", "age": 7}
The gist.
You can find another simpler option in a thread here: Match Against.. with a more detail help in 11.9.2. Boolean Full-Text Searches
This is just in case someone need a more compact option. This will require to create an Index FULLTEXT in the table, which can be accomplish easily.
Information on how to create Indexes (MySQL): MySQL FULLTEXT Indexing and Searching
In the FULLTEXT
Index you can have more than one column listed, the result would be an SQL Statement with an index named search
:
SELECT *,MATCH (`column`) AGAINST('+keyword1* +keyword2* +keyword3*') as relevance FROM `documents`USE INDEX(search) WHERE MATCH (`column`) AGAINST('+keyword1* +keyword2* +keyword3*' IN BOOLEAN MODE) ORDER BY relevance;
I tried with multiple columns, with no luck. Even though multiple columns are allowed in indexes, you still need an index for each column to use with Match/Against Statement.
Depending in your criterias you can use either options.
handles lookinng for something > 1 char long. feel free to increase the parm sizes if you like.
couldnt resist posting
drop function if exists lastIndexOf
go
create function lastIndexOf(@searchFor varchar(100),@searchIn varchar(500))
returns int
as
begin
if LEN(@searchfor) > LEN(@searchin) return 0
declare @r varchar(500), @rsp varchar(100)
select @r = REVERSE(@searchin)
select @rsp = REVERSE(@searchfor)
return len(@searchin) - charindex(@rsp, @r) - len(@searchfor)+1
end
and tests
select dbo.lastIndexof('greg','greg greg asdflk; greg sadf' ) -- 18
select dbo.lastIndexof('greg','greg greg asdflk; grewg sadf' ) --5
select dbo.lastIndexof(' ','greg greg asdflk; grewg sadf' ) --24
Yes, this is possible.
<form id="formName" action="<?php echo $_SERVER['PHP_SELF'];?>" method="get">
<input type ="checkbox" name="cBox[]" value = "3" onchange="document.getElementById('formName').submit()">3</input>
<input type ="checkbox" name="cBox[]" value = "4" onchange="document.getElementById('formName').submit()">4</input>
<input type ="checkbox" name="cBox[]" value = "5" onchange="document.getElementById('formName').submit()">5</input>
<input type="submit" name="submit" value="Search" />
</form>
By adding onchange="document.getElementById('formName').submit()"
to each checkbox, you'll submit any time a checkbox is changed.
If you're OK with jQuery, it's even easier (and unobtrusive):
$(document).ready(function(){
$("#formname").on("change", "input:checkbox", function(){
$("#formname").submit();
});
});
For any number of checkboxes in your form, when the "change" event happens, the form is submitted. This will even work if you dynamically create more checkboxes thanks to the .on()
method.
with open('file.txt', 'r') as searchfile:
for line in searchfile:
if 'searchphrase' in line:
print line
With apologies to senderle who I blatantly copied.
grep eth0 $(find /etc/ -type f -exec file {} \; | egrep -i "text|ascii" | cut -d ':' -f1)
Keep both lists x and y in sorted order.
If x = y, do your action, if x < y, advance x, if y < x, advance y until either list is empty.
The run time of this intersection is proportional to min (size (x), size (y))
Don't run a .Contains () loop, this is proportional to x * y which is much worse.
There is possible to space with different widths:
<string name="space_demo">| | | ||</string>
| SPACE | THIN SPACE | HAIR SPACE | no space |
Visualisation:
As Jage's answer removes the element completely, including event handlers and data, I'm adding a simple solution that doesn't do that, thanks to the detach
function.
var element = $('#childNode').detach();
$('#parentNode').append(element);
Edit:
Igor Mukhin suggested an even shorter version in the comments below:
$("#childNode").detach().appendTo("#parentNode");
For ng9 upgraders:
npm i -g core-js@^3
..then:
npm cache clean -f
..followed by:
npm i
If for some reason you're intent on using Date
objects for your solution, you'll need to do something like this:
// Convert user input into year, month, and day integers
Date toDate = new Date(year - 1900, month - 1, day + 1);
Date currentDate = new Date();
boolean runThatReport = toDate.after(currentDate);
Shifting the toDate
ahead to midnight of the next day will take care of the bug I've whined about in the comments to other answers. But, note that this approach uses a deprecated constructor; any approach relying on Date
will use one deprecated method or another, and depending on how you do it may lead to race conditions as well (if you base toDate
off of new Date()
and then fiddle around with the year, month, and day, for instance). Use Calendar
, as described elsewhere.
I've found a post here on Stackoverflow and implemented your design:
Here's the original post: https://stackoverflow.com/a/5768262/1368423
Is that what you're looking for?
HTML:
<div class="container-fluid wrapper">
<div class="row-fluid columns content">
<div class="span2 article-tree">
navigation column
</div>
<div class="span10 content-area">
content column
</div>
</div>
<div class="footer">
footer content
</div>
</div>
CSS:
html, body {
height: 100%;
}
.container-fluid {
margin: 0 auto;
height: 100%;
padding: 20px 0;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.columns {
background-color: #C9E6FF;
height: 100%;
}
.content-area, .article-tree{
background: #bada55;
overflow:auto;
height: 100%;
}
.footer {
background: red;
height: 20px;
}
if you use docker-compose.yml
file:
services:
varnish:
ports:
- 80
- 6081
You can also specify the host/network port as HOST/NETWORK_PORT:CONTAINER_PORT
varnish:
ports:
- 81:80
- 6081:6081
new URL("file:///your/file/here")
below answer support api level below and above 10
if (Build.VERSION.SDK_INT >= 11) {
Point size = new Point();
try {
this.getWindowManager().getDefaultDisplay().getRealSize(size);
screenWidth = size.x;
screenHeight = size.y;
} catch (NoSuchMethodError e) {
screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
screenWidth=this.getWindowManager().getDefaultDisplay().getWidth();
}
} else {
DisplayMetrics metrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
screenWidth = metrics.widthPixels;
screenHeight = metrics.heightPixels;
}
There are indeed global variables in javascript. You can learn more about scopes, which are helpful in this situation.
Your code could look like this:
<script>
var count = 1;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
property.style.backgroundColor = "#7FFF00"
count = 0;
}
}
</script>
Hope this helps.
You must set your query base to the DN of the user in question, then set your filter to the DN of the group you're wondering if they're a member of. To see if jdoe is a member of the office group then your query will look something like this:
ldapsearch -x -D "ldap_user" -w "user_passwd" -b "cn=jdoe,dc=example,dc=local" -h ldap_host '(memberof=cn=officegroup,dc=example,dc=local)'
If you want to see ALL the groups he's a member of, just request only the 'memberof' attribute in your search, like this:
ldapsearch -x -D "ldap_user" -w "user_passwd" -b "cn=jdoe,dc=example,dc=local" -h ldap_host **memberof**
It is possible to tell Intellij to ignore this error.
File > Settings > Editor > Inspections, then search for "Wrong package statement" (Under Java, Probable Bugs) on the right and uncheck it.
With JDBC 4.2 or later and java 8 or later:
myPreparedStatement.setObject( … , myLocalDate )
…and…
myResultSet.getObject( … , LocalDate.class )
The Answer by Vargas is good about mentioning java.time types but refers only to converting to java.sql.Date. No need to convert if your driver is updated.
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
. The Joda-Time team also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
LocalDate
In java.time, the java.time.LocalDate
class represents a date-only value without time-of-day and without time zone.
If using a JDBC driver compliant with JDBC 4.2 or later spec, no need to use the old java.sql.Date
class. You can pass/fetch LocalDate
objects directly to/from your database via PreparedStatement::setObject
and ResultSet::getObject
.
LocalDate localDate = LocalDate.now( ZoneId.of( "America/Montreal" ) );
myPreparedStatement.setObject( 1 , localDate );
…and…
LocalDate localDate = myResultSet.getObject( 1 , LocalDate.class );
If your driver cannot handle the java.time types directly, fall back to converting to java.sql types. But minimize their use, with your business logic using only java.time types.
New methods have been added to the old classes for conversion to/from java.time types. For java.sql.Date
see the valueOf
and toLocalDate
methods.
java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );
…and…
LocalDate localDate = sqlDate.toLocalDate();
Be wary of using 0000-00-00
as a placeholder value as shown in your Question’s code. Not all databases and other software can handle going back that far in time. I suggest using something like the commonly-used Unix/Posix epoch reference date of 1970, 1970-01-01
.
LocalDate EPOCH_DATE = LocalDate.ofEpochDay( 0 ); // 1970-01-01 is day 0 in Epoch counting.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
YES You can create abstract class with out any abstract method the best example of abstract class without abstract method is HttpServlet
Abstract Method is a method which have no body, If you declared at least one method into the class, the class must be declared as an abstract its mandatory BUT if you declared the abstract class its not mandatory to declared the abstract method inside the class.
You cannot create objects of abstract class, which means that it cannot be instantiated.
The best way to remember if rows or columns come first would be writing a comment and mentioning it.
Java does not store a 2D Array as a table with specified rows and columns, it stores it as an array of arrays, like many other answers explain. So you can decide, if the first or second dimension is your row. You just have to read the array depending on that.
So, since I get confused by this all the time myself, I always write a comment that tells me, which dimension of the 2d Array is my row, and which is my column.
In your case, expand columns of that database in the object explorer. Drag the columns in to the query area.
And then just delete one or two columns which you don't want and then run it. I'm open to any suggestions easier than this.
All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)
Based on this related answer, you are looking at a list that looks like: A-Z
, a-z
, 0-9
, -
, .
, _
, ~
, :
, /
, ?
, #
, [
, ]
, @
, !
, $
, &
, '
, (
, )
, *
, +
, ,
, ;
, %
, and =
. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. %
can only be used in conjunction with url encoding as in %20
), the RFC has all of these specifics.
Yeah there's no built in classes to do this that I'm aware of.
But that shouldn't really be an issue should it? It looks easy enough to parse just by storing the result of Stream.ReadToEnd()
in a string, splitting based on new lines and then splitting each record on the =
character. What you'd be left with is a bunch of key value pairs which you can easily toss into a dictionary.
Here's an example that might work for you:
public static Dictionary<string, string> GetProperties(string path)
{
string fileData = "";
using (StreamReader sr = new StreamReader(path))
{
fileData = sr.ReadToEnd().Replace("\r", "");
}
Dictionary<string, string> Properties = new Dictionary<string, string>();
string[] kvp;
string[] records = fileData.Split("\n".ToCharArray());
foreach (string record in records)
{
kvp = record.Split("=".ToCharArray());
Properties.Add(kvp[0], kvp[1]);
}
return Properties;
}
Here's an example of how to use it:
Dictionary<string,string> Properties = GetProperties("data.txt");
Console.WriteLine("Hello: " + Properties["Hello"]);
Console.ReadKey();
As chmullig wrote, use Jenkins. Some additional points:
In fact, arguably it was Oracle who did the forking! And technically, too, that's kinda what happened.
It's interesting to see what comes out of "Hudson" though. While the "Winston summarizes the state and rosy future of the Hudson project" stuff they posted on the (new) Hudson website originally seemed like odd humour to me, perhaps this was a purposeful takeover, and the Sonatype guys actually have some big ideas up their sleeve. This analysis, suggesting a deliberate strategy by Oracle/Sonatype to oust Kohsuke and crew to create a more "enterprisy" Hudson is a very interesting read!
In any case, this brief comparison a fortnight after the split—while not exactly scientific—shows Jenkins to be by far more active of the two projects.
...and a little background info:
The creator of Hudson, Kohsuke Kawaguchi, started the project on his free time, even if he was working for Sun Microsystems and later paid by them to develop it further. As @erickson noted at another SO question,
[Hudson/Jenkins] is the product of a single genius intellect—Kohsuke Kawaguchi. Because of that, it's consistent, coherent, and rock solid.
After the acquisition by Oracle, Kohsuke didn't hang around for long (due to lack of monitors...? ;-]), and went to work for CloudBees. What started in late 2010 as conflict over tools between the dev community and Oracle and ended in the rename/fork/split is well documented in the links chmullig provided. To me, that whole conundrum speaks, perhaps more than anything else, to Oracle's utter inability or unwillingness to sponsor an open-source project in a way that keeps all parties (Oracle, developers, users) happy. It's not in their DNA or something, as we've seen in other cases too.
Given all of the above, I would personally follow Kohsuke and other core developers in this matter, and go with Jenkins.
I also experienced this issue after installing Telerik Reporting. I was not able to launch any solution in Visual Studio 2013, nor could I close Visual Studio 2013.
After uninstalling the reporting package and deleting Local / Roaming AppData for Visual Studio 2012, the problem was fixed.
What about @Primary
?
Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the
<bean>
element'sprimary
attribute in Spring XML.
@Primary
public class HibernateDeviceDao implements DeviceDao
Or if you want your Jdbc version to be used by default:
<bean id="jdbcDeviceDao" primary="true" class="com.initech.service.dao.jdbc.JdbcDeviceDao">
@Primary
is also great for integration testing when you can easily replace production bean with stubbed version by annotating it.
By combining Sanjeevakumar Hiremath's and Jeff Mercado's answers you can actually in a way get around the problem when retrieving the icon from a 64-bit process in a 32-bit process.
using System;
using System.Management;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int processID = 6680; // Change for the process you would like to use
Process process = Process.GetProcessById(processID);
string path = ProcessExecutablePath(process);
}
static private string ProcessExecutablePath(Process process)
{
try
{
return process.MainModule.FileName;
}
catch
{
string query = "SELECT ExecutablePath, ProcessID FROM Win32_Process";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject item in searcher.Get())
{
object id = item["ProcessID"];
object path = item["ExecutablePath"];
if (path != null && id.ToString() == process.Id.ToString())
{
return path.ToString();
}
}
}
return "";
}
}
}
This may be a bit slow and doesn't work on every process which lacks a "valid" icon.
If you need the value before insert a row:
CREATE FUNCTION `getAutoincrementalNextVal`(`TableName` VARCHAR(50))
RETURNS BIGINT
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE Value BIGINT;
SELECT
AUTO_INCREMENT INTO Value
FROM
information_schema.tables
WHERE
table_name = TableName AND
table_schema = DATABASE();
RETURN Value;
END
You can use this in a insert:
INSERT INTO
document (Code, Title, Body)
VALUES (
sha1( concat (convert ( now() , char), ' ', getAutoincrementalNextval ('document') ) ),
'Title',
'Body'
);
If you are getting this same error after adding dynamic module then don't worry follow this:
Add productFlavors in your build.gradle(dynamic- module)
productFlavors {
flavorDimensions "default"
stage {
// to do
}
prod {
// to do
}
}
1. In my opinion, the most convenient way is to search for one
occurrence first, and then invoke the following :substitute
command:
:%s///gc
Since the pattern is empty, this :substitute
command will look for
the occurrences of the last-used search pattern, and will then replace
them with the empty string, each time asking for user confirmation,
realizing exactly the desired behavior.
2. If it is a common pattern in one’s editing habits, one can further define a couple of text-object selection mappings to operate specifically on the match of the last search pattern under the cursor. The following two mappings can be used in both Visual and Operator-pending modes to select the text of the preceding match of the last search pattern.
vnoremap <silent> i/ :<c-u>call SelectMatch()<cr>
onoremap <silent> i/ :call SelectMatch()<cr>
function! SelectMatch()
if search(@/, 'bcW')
norm! v
call search(@/, 'ceW')
else
norm! gv
endif
endfunction
Using these mappings one can delete the match under the cursor with
di/
, or apply any other operator or visually select it with vi/
.
No, it doesn't save you memory.
Also note that you don't have to import Math
at all. Everything in java.lang
is imported automatically.
A better example would be something like an ArrayList
import java.util.ArrayList;
....
ArrayList<String> i = new ArrayList<String>();
Note I'm importing the ArrayList
specifically. I could have done
import java.util.*;
But you generally want to avoid large wildcard imports to avoid the problem of collisions between packages.
Have a look at the official issue 33930. There is pointed out, that it may have to do with the start up of OpenGL during the start of the emulator. Others wrote it only crashes when they use WXGA800-skin and suggest to manually set the resolution to 800x1280.
Further there are ZIP-files provided to manually downgrade your android SDK to version 19 and plattform-tools to version 11. This may help as well to temporally fix the issue.
I use this. It is just about the same thing as the others, but it is just another way to write it.
@ECHO off
set count=0
:Loop
if %count%==[how many times to loop] goto end
::[Commands to execute here]
set count=%count%+1
goto Loop
:end
update-alternatives
is problematic in this case as it forces you to update all the elements depending on the JDK.
For this specific purpose, the package java-common
contains a tool called update-java-alternatives
.
It's straightforward to use it. First list the JDK installs available on your machine:
root@mylaptop:~# update-java-alternatives -l
java-1.7.0-openjdk-amd64 1071 /usr/lib/jvm/java-1.7.0-openjdk-amd64
java-1.8.0-openjdk-amd64 1069 /usr/lib/jvm/java-1.8.0-openjdk-amd64
And then pick one up:
root@mylaptop:~# update-java-alternatives -s java-1.7.0-openjdk-amd64
The following worked for me... Just use
app.use(bodyParser({limit: '50mb'}));
that's it.
Tried all above and none worked. Found that even though we use like the following,
app.use(bodyParser());
app.use(bodyParser({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb'}));
only the 1st app.use(bodyParser());
one gets defined and the latter two lines were ignored.
Refer: https://github.com/expressjs/body-parser/issues/176 >> see 'dougwilson commented on Jun 17, 2016'
You could encode your string using Base64 encoding on the JavaScript side and then decoding it on the server side with PHP (?).
JavaScript (Docu)
var wysiwyg_clean = window.btoa( wysiwyg );
PHP (Docu):
var wysiwyg = base64_decode( $_POST['wysiwyg'] );
Putting a <br clear="all" />
after the last floated div worked the best for me. Thanks to Brent Fiare & Paul Waite for the info that floated divs will not expand the height of the parent div! This has been driving me nuts! ;-}
I kind of like this method which I think covers all the bases:
const matches = str.match(/aeiou/gi];
return matches ? matches.length : 0;
You can Close your super view window
self.view.superview?.window?.close()
Structs "really" pure aren't supported in Java. E.g., C# supports struct
definitions that represent values and can be allocated anytime.
In Java, the unique way to get an approximation of C++ structs
struct Token
{
TokenType type;
Stringp stringValue;
double mathValue;
}
// Instantiation
{
Token t = new Token;
}
without using a (static buffer or list) is doing something like
var type = /* TokenType */ ;
var stringValue = /* String */ ;
var mathValue = /* double */ ;
So, simply allocate variables or statically define them into a class.
(For anybody looking how to do it in Visual Studio!)
I had a similar problem with 2D arrays and ended here. I was copying the main array and changing the inner arrays' values and was surprised when the values changed in both copies. Basically both copies were independent but contained references to the same inner arrays and I had to make an array of copies of the inner arrays to get what I wanted.
This is sometimes called a deep copy. The same term "deep copy" can also have a completely different and arguably more complex meaning, which can be confusing, especially to someone not figuring out why their copied arrays don't behave as they should. It probably isn't the OP's problem, but I hope it can still be helpful.
I know its too late to answer this question but for others who are searching for some thing similar to this here is a simple code of an alertbox with an edittext
AlertDialog.Builder alert = new AlertDialog.Builder(this);
or
new AlertDialog.Builder(mContext, R.style.MyCustomDialogTheme);
if you want to change the theme of the dialog.
final EditText edittext = new EditText(ActivityContext);
alert.setMessage("Enter Your Message");
alert.setTitle("Enter Your Title");
alert.setView(edittext);
alert.setPositiveButton("Yes Option", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//What ever you want to do with the value
Editable YouEditTextValue = edittext.getText();
//OR
String YouEditTextValue = edittext.getText().toString();
}
});
alert.setNegativeButton("No Option", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// what ever you want to do with No option.
}
});
alert.show();
itertools.combinations is your friend if you have Python 2.6 or greater. Otherwise, check the link for an implementation of an equivalent function.
import itertools
def findsubsets(S,m):
return set(itertools.combinations(S, m))
S: The set for which you want to find subsets
m: The number of elements in the subset
System Preferences => Keyboard => Key Repeat Rate
Which version of Bootstrap are you using? I was perplexed that I could get @Chad's solution to work in jsfiddle, but not locally. So, I checked the version of Bootstrap used by jsfiddle, and it's using a 3.0.0-rc1 release, while the default download on getbootstrap.com is version 2.3.2.
In 2.3.2 the collapse
class wasn't getting replaced by the in
class. The in
class was simply getting appended when the button was clicked. In version 3.0.0-rc1, the collapse
class correctly is removed, and the <tr>
collapses.
Use @Chad's solution for the html, and try using these links for referencing Bootstrap:
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css" rel="stylesheet">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
There is nothing you can do on your end (client side). You can not enable crossDomain calls yourself, the source (dailymotion.com) needs to have CORS enabled for this to work.
The only thing you can really do is to create a server side proxy script which does this for you. Are you using any server side scripts in your project? PHP, Python, ASP.NET etc? If so, you could create a server side "proxy" script which makes the HTTP call to dailymotion and returns the response. Then you call that script from your Javascript code, since that server side script is on the same domain as your script code, CORS will not be a problem.
Thanks to Waseem05 for his Swift 3 translation but his method only worked for me when I wrapped it inside an extension to UIImage and placed it outside/below the parent class like so:
extension UIImage {
func fixOrientation() -> UIImage
{
if self.imageOrientation == UIImageOrientation.up {
return self
}
var transform = CGAffineTransform.identity
switch self.imageOrientation {
case .down, .downMirrored:
transform = transform.translatedBy(x: self.size.width, y: self.size.height)
transform = transform.rotated(by: CGFloat(M_PI));
case .left, .leftMirrored:
transform = transform.translatedBy(x: self.size.width, y: 0);
transform = transform.rotated(by: CGFloat(M_PI_2));
case .right, .rightMirrored:
transform = transform.translatedBy(x: 0, y: self.size.height);
transform = transform.rotated(by: CGFloat(-M_PI_2));
case .up, .upMirrored:
break
}
switch self.imageOrientation {
case .upMirrored, .downMirrored:
transform = transform.translatedBy(x: self.size.width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
case .leftMirrored, .rightMirrored:
transform = transform.translatedBy(x: self.size.height, y: 0)
transform = transform.scaledBy(x: -1, y: 1);
default:
break;
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
let ctx = CGContext(
data: nil,
width: Int(self.size.width),
height: Int(self.size.height),
bitsPerComponent: self.cgImage!.bitsPerComponent,
bytesPerRow: 0,
space: self.cgImage!.colorSpace!,
bitmapInfo: UInt32(self.cgImage!.bitmapInfo.rawValue)
)
ctx!.concatenate(transform);
switch self.imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
// Grr...
ctx?.draw(self.cgImage!, in: CGRect(x:0 ,y: 0 ,width: self.size.height ,height:self.size.width))
default:
ctx?.draw(self.cgImage!, in: CGRect(x:0 ,y: 0 ,width: self.size.width ,height:self.size.height))
break;
}
// And now we just create a new UIImage from the drawing context
let cgimg = ctx!.makeImage()
let img = UIImage(cgImage: cgimg!)
return img;
}
}
Then called it with:
let correctedImage:UIImage = wonkyImage.fixOrientation()
And all was then well! Apple should make it easier to discard orientation when we don't need front/back camera and up/down/left/right device orientation metadata.
Yet another crooked solution for a ternary helper:
'?:' ( condition, first, second ) {
return condition ? first : second;
}
<span>{{?: fooExists 'found it' 'nope, sorry'}}</span>
Or a simple coalesce helper:
'??' ( first, second ) {
return first ? first : second;
}
<span>{{?? foo bar}}</span>
Since these characters don't have a special meaning in handlebars markup, you're free to use them for helper names.
I get same issue but I was getting error below error when run regsvr32 MSCOMCTL.OCX
The module "MSCOMCTL.OCX" was loaded but the call to DllRegisterServer failed with error code 0x8002801c.
When I run CMD.EXE as Administrator, then it solved my issue.
Some Times VB6.EXE also need o run as administrator to access some registry issue.
Good Luck.
Key insights for me were: - ensure that label content comes after the input-radio field - I tweaked my css to make everything a little closer
.radio-inline+.radio-inline {
margin-left: 5px;
}
Go to bin directory of Zookeeper and type
./zkServer.sh status
For More info go through below link:
http://www.ibm.com/developerworks/library/bd-zookeeper/
Hope this could help you.
I had a different cause for this error. I tried to insert a date without using quotes and received a strange error telling me I had tried to insert a date from 2003.
Although I was already using the YYYY-MM-DD format, I forgot to add quotes around the date. Even though it is a date and not a string, quotes are still required.
src
folder which is immediately inside the project's folder.
Note the hollow 'J' in the image. That indicates that the file is not part of a project.
When you use Context.SECURITY_AUTHENTICATION as "simple", you need to supply the userPrincipalName attribute value (user@domain_base).
I found a solution for Windows users. All the other solutions i tried didn't work for Windows.
I have been searching about the same problem for a few days. iTunes make obligation to update itself to iTunes newer version for ios 11 phones and iTunes 12.7 version doesn't have apps section so i couldn't download anymore my ad hoc app ipa file and provision files to iPhone.
I just found out that there is an iTunes version (12.6.3) Apple published which won’t be prompted to download new versions of iTunes and you can use this version to download your app. You can dowload it from this link: https://support.apple.com/en-us/HT208079
Apple say if you have a newer version of iTunes you can just download this one over it but I couldn't do it like this. First, I removed iTunes from my computer, then I removed the iTunes folder from my musics folder (you probably don't need to do that) and I downloaded iTunes for 64 bit PC from the link I wrote above. And with this iTunes i can use Apps section again and it doesn't force me to update it. So it works like the good old times.
It is possible to develop iOS (and Android at the same time) application using React Native + Expo without owning a mac. You will also be able to run your iOS application within iOS Expo app while developing it. (You can even publish it for other people to access, but it will only run within Expo app). Here is page from Expo on how to generate standalone app.
One: Install exp
by running npm install -g exp
Two: Configure app.json (somewhere along these lines):
{
"expo": {
"name": "Your App Name",
"icon": "./path/to/your/app-icon.png",
"version": "1.0.0",
"slug": "your-app-slug",
"sdkVersion": "17.0.0",
"ios": {
"bundleIdentifier": "com.yourcompany.yourappname"
},
"android": {
"package": "com.yourcompany.yourappname"
}
}
}
Three: Start exp
packeger with exp start
Four: run exp build:android
or exp build:ios
.
You will be prompted for some input. For android you can choose 1) Let Expo handle the process!
if you don't have keystore (or if you don't know what it is). For iOS you will have to enter your Apple developer credentials. Then you can provide distribution certificate or let expo handle it.
Five: Once in a while you will have to come back and run exp build:status
command to check whether your build was complete. If complete you will be provided a direct link to .apk
or .ipa
file.
The only drawback to this approach is that it won't be as native as writing iOS app in Swift, and you will have to put up with parade of issues you may run into while developing with weakly typed js, npm, and it's dependency-on-particular-version-of-some-other-library issues, and other stuff.
Here is the code to check whether value is present or not.
If Trim(textbox1.text) <> "" Then
'Your code goes here
Else
'Nothing
End If
I think this will help.
As claustrofob said, oninput is supported for IE9+.
However, "The oninput event is buggy in Internet Explorer 9. It is not fired when characters are deleted from a text field through the user interface only when characters are inserted. Although the onpropertychange event is supported in Internet Explorer 9, but similarly to the oninput event, it is also buggy, it is not fired on deletion.
Since characters can be deleted in several ways (Backspace and Delete keys, CTRL + X, Cut and Delete command in context menu), there is no good solution to detect all changes. If characters are deleted by the Delete command of the context menu, the modification cannot be detected in JavaScript in Internet Explorer 9."
I have good results binding to both input and keyup (and keydown, if you want it to fire in IE while holding down the Backspace key).
Create your shell script as login.sh
in your $HOME folder.
Paste the following one-line script into Script Editor:
do shell script "$HOME/login.sh"
Then save it as an application.
Finally add the application to your login items.
If you want to make the script output visual, you can swap step 2 for this:
tell application "Terminal"
activate
do script "$HOME/login.sh"
end tell
If multiple commands are needed something like this can be used:
tell application "Terminal"
activate
do script "cd $HOME"
do script "./login.sh" in window 1
end tell
I'm going to go against the general wisdom here that std::copy
will have a slight, almost imperceptible performance loss. I just did a test and found that to be untrue: I did notice a performance difference. However, the winner was std::copy
.
I wrote a C++ SHA-2 implementation. In my test, I hash 5 strings using all four SHA-2 versions (224, 256, 384, 512), and I loop 300 times. I measure times using Boost.timer. That 300 loop counter is enough to completely stabilize my results. I ran the test 5 times each, alternating between the memcpy
version and the std::copy
version. My code takes advantage of grabbing data in as large of chunks as possible (many other implementations operate with char
/ char *
, whereas I operate with T
/ T *
(where T
is the largest type in the user's implementation that has correct overflow behavior), so fast memory access on the largest types I can is central to the performance of my algorithm. These are my results:
Time (in seconds) to complete run of SHA-2 tests
std::copy memcpy % increase
6.11 6.29 2.86%
6.09 6.28 3.03%
6.10 6.29 3.02%
6.08 6.27 3.03%
6.08 6.27 3.03%
Total average increase in speed of std::copy over memcpy: 2.99%
My compiler is gcc 4.6.3 on Fedora 16 x86_64. My optimization flags are -Ofast -march=native -funsafe-loop-optimizations
.
Code for my SHA-2 implementations.
I decided to run a test on my MD5 implementation as well. The results were much less stable, so I decided to do 10 runs. However, after my first few attempts, I got results that varied wildly from one run to the next, so I'm guessing there was some sort of OS activity going on. I decided to start over.
Same compiler settings and flags. There is only one version of MD5, and it's faster than SHA-2, so I did 3000 loops on a similar set of 5 test strings.
These are my final 10 results:
Time (in seconds) to complete run of MD5 tests
std::copy memcpy % difference
5.52 5.56 +0.72%
5.56 5.55 -0.18%
5.57 5.53 -0.72%
5.57 5.52 -0.91%
5.56 5.57 +0.18%
5.56 5.57 +0.18%
5.56 5.53 -0.54%
5.53 5.57 +0.72%
5.59 5.57 -0.36%
5.57 5.56 -0.18%
Total average decrease in speed of std::copy over memcpy: 0.11%
Code for my MD5 implementation
These results suggest that there is some optimization that std::copy used in my SHA-2 tests that std::copy
could not use in my MD5 tests. In the SHA-2 tests, both arrays were created in the same function that called std::copy
/ memcpy
. In my MD5 tests, one of the arrays was passed in to the function as a function parameter.
I did a little bit more testing to see what I could do to make std::copy
faster again. The answer turned out to be simple: turn on link time optimization. These are my results with LTO turned on (option -flto in gcc):
Time (in seconds) to complete run of MD5 tests with -flto
std::copy memcpy % difference
5.54 5.57 +0.54%
5.50 5.53 +0.54%
5.54 5.58 +0.72%
5.50 5.57 +1.26%
5.54 5.58 +0.72%
5.54 5.57 +0.54%
5.54 5.56 +0.36%
5.54 5.58 +0.72%
5.51 5.58 +1.25%
5.54 5.57 +0.54%
Total average increase in speed of std::copy over memcpy: 0.72%
In summary, there does not appear to be a performance penalty for using std::copy
. In fact, there appears to be a performance gain.
Explanation of results
So why might std::copy
give a performance boost?
First, I would not expect it to be slower for any implementation, as long as the optimization of inlining is turned on. All compilers inline aggressively; it is possibly the most important optimization because it enables so many other optimizations. std::copy
can (and I suspect all real world implementations do) detect that the arguments are trivially copyable and that memory is laid out sequentially. This means that in the worst case, when memcpy
is legal, std::copy
should perform no worse. The trivial implementation of std::copy
that defers to memcpy
should meet your compiler's criteria of "always inline this when optimizing for speed or size".
However, std::copy
also keeps more of its information. When you call std::copy
, the function keeps the types intact. memcpy
operates on void *
, which discards almost all useful information. For instance, if I pass in an array of std::uint64_t
, the compiler or library implementer may be able to take advantage of 64-bit alignment with std::copy
, but it may be more difficult to do so with memcpy
. Many implementations of algorithms like this work by first working on the unaligned portion at the start of the range, then the aligned portion, then the unaligned portion at the end. If it is all guaranteed to be aligned, then the code becomes simpler and faster, and easier for the branch predictor in your processor to get correct.
Premature optimization?
std::copy
is in an interesting position. I expect it to never be slower than memcpy
and sometimes faster with any modern optimizing compiler. Moreover, anything that you can memcpy
, you can std::copy
. memcpy
does not allow any overlap in the buffers, whereas std::copy
supports overlap in one direction (with std::copy_backward
for the other direction of overlap). memcpy
only works on pointers, std::copy
works on any iterators (std::map
, std::vector
, std::deque
, or my own custom type). In other words, you should just use std::copy
when you need to copy chunks of data around.
Using mysqli i've created following function. Asuming you have an mysqli instance called $con.
function table_exist($table){
global $con;
$table = $con->real_escape_string($table);
$sql = "show tables like '".$table."'";
$res = $con->query($sql);
return ($res->num_rows > 0);
}
Hope it helps.
Warning: as sugested by @jcaron this function could be vulnerable to sqlinjection attacs, so make sure your $table
var is clean or even better use parameterised queries.
If you're having an issue where the Resources added are images and are not getting copied to your build folder on compiling. You need to change the "Build Action" to None from Resource ( which is the default) and change the Copy to "If Newer" or "Always" as shown below :
if ( values > 0 ) {
//you got a positive value
}else{
//you got a negative or zero value
}
Voilà...
Do the following thing if you want to use json as a http request and response. So we need to make changes in [context].xml
<!-- Configure to plugin JSON as request and response in method handler -->
<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<beans:property name="messageConverters">
<beans:list>
<beans:ref bean="jsonMessageConverter"/>
</beans:list>
</beans:property>
</beans:bean>
<!-- Configure bean to convert JSON to POJO and vice versa -->
<beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>
MappingJackson2HttpMessageConverter to the RequestMappingHandlerAdapter messageConverters so that Jackson API kicks in and converts JSON to Java Beans and vice versa. By having this configuration, we will be using JSON in request body and we will receive JSON data in the response.
I am also providing small code snippet for controller part:
@RequestMapping(value = EmpRestURIConstants.DUMMY_EMP, method = RequestMethod.GET)
public @ResponseBody Employee getDummyEmployee() {
logger.info("Start getDummyEmployee");
Employee emp = new Employee();
emp.setId(9999);
emp.setName("Dummy");
emp.setCreatedDate(new Date());
empData.put(9999, emp);
return emp;
}
So in above code emp object will directly convert into json as a response. same will happen for post also.
The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes()
call directly or create a vector for that instead.
This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.
level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses
ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()
or
level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))
ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()
or
directly in the aes()
call without a pre-created vector:
ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()
The answer comes from the javadoc of ZoneId
(emphasis mine) ...
A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:
- Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
- Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply
Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.
... and from the javadoc of ZoneId#of
(emphasis mine):
This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.
The argument id is specified as "UTC"
, therefore it will return a ZoneId
with an offset, which also presented in the string form:
System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));
Outputs:
2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]
As you use the equals
method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false
.
When the normalized()
method is used as proposed in the documentation, the comparison using equals
will return true
, as normalized()
will return the corresponding ZoneOffset
:
Normalizes the time-zone ID, returning a ZoneOffset where possible.
now.withZoneSameInstant(ZoneOffset.UTC)
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true
As the documentation states, if you use "Z"
or "+0"
as input id, of
will return the ZoneOffset
directly and there is no need to call normalized()
:
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true
To check if they store the same date time, you can use the isEqual
method instead:
now.withZoneSameInstant(ZoneOffset.UTC)
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true
Sample
System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));
Output:
equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true
When defining an array, you are setting aside a block of memory to hold all the items you want to have in the array.
This will have a default value, depending on the type of the array member types.
What you can't do is find out the number of items that you have populated, except for tracking it in your own code.
List does not implement IBindingList
so the grid does not know about your new items.
Bind your DataGridView to a BindingList<T>
instead.
var list = new BindingList<Person>(persons);
myGrid.DataSource = list;
But I would even go further and bind your grid to a BindingSource
var list = new List<Person>()
{
new Person { Name = "Joe", },
new Person { Name = "Misha", },
};
var bindingList = new BindingList<Person>(list);
var source = new BindingSource(bindingList, null);
grid.DataSource = source;
You don't need to compile header files. It doesn't actually do anything, so there's no point in trying to run it. However, it is a great way to check for typos and mistakes and bugs, so it'll be easier later.
First malloc allocates memory for struct, including memory for x (pointer to double). Second malloc allocates memory for double value wtich x points to.
Here is your answer. use
jquery.json-2.2.min.js
and
jquery-1.8.3.min.js
Javascript :
function CallAddToCart(eitemId, equantity) {
var itemId = Number(eitemId);
var quantity = equantity;
var dataValue = "{itemId:'" + itemId+ "', quantity :'"+ quantity "'}" ;
$.ajax({
url: "AddToCart.aspx/AddTo_Cart",
type: "POST",
dataType: "json",
data: dataValue,
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert("Success");
},
error: function () { alert(arguments[2]); }
});
}
and your C# web method should be
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddTo_Cart(int itemId, string quantity)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Item Added Successfully";
}
From any of the button click
or any other html control event
you can call to the javascript
method with the parameter which in turn calls to the webmethod
to get the value in json
format.
Here's an example of a transaction that will rollback on error and return the error code.
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `SP_CREATE_SERVER_USER`(
IN P_server_id VARCHAR(100),
IN P_db_user_pw_creds VARCHAR(32),
IN p_premium_status_name VARCHAR(100),
IN P_premium_status_limit INT,
IN P_user_tag VARCHAR(255),
IN P_first_name VARCHAR(50),
IN P_last_name VARCHAR(50)
)
BEGIN
DECLARE errno INT;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET CURRENT DIAGNOSTICS CONDITION 1 errno = MYSQL_ERRNO;
SELECT errno AS MYSQL_ERROR;
ROLLBACK;
END;
START TRANSACTION;
INSERT INTO server_users(server_id, db_user_pw_creds, premium_status_name, premium_status_limit)
VALUES(P_server_id, P_db_user_pw_creds, P_premium_status_name, P_premium_status_limit);
INSERT INTO client_users(user_id, server_id, user_tag, first_name, last_name, lat, lng)
VALUES(P_server_id, P_server_id, P_user_tag, P_first_name, P_last_name, 0, 0);
COMMIT WORK;
END$$
DELIMITER ;
This is assuming that autocommit is set to 0. Hope this helps.
I like to use this. There is nothing wrong with using the for loop, I just like using the build-in functions. You could even pass in a boolean argument for typecast or non typecast matching, which in that case you would use a for loop (the filter()
method/function does typecast matching (===))
Array.prototype.unique =
function()
{
return this.filter(
function(val, i, arr)
{
return (i <= arr.indexOf(val));
}
);
}
ToolTip in C# is very easy to add to almost all UI controls. You don't need to add any MouseHover event for this.
This is how to do it-
Add a ToolTip object to your form. One object is enough for the entire form.
ToolTip toolTip = new ToolTip();
Add the control to the tooltip with the desired text.
toolTip.SetToolTip(Button1,"Click here");
Ctrl++
or
Ctrl+=
Ctrl+-
This feature is described here:
In text editors, you can now use Zoom In (Ctrl++ or Ctrl+=) and Zoom Out (Ctrl+-) commands to increase and decrease the font size. Like a change in the General > Appearance > Colors and Fonts preference page, the commands persistently change the font size in all editors of the same type. If the editor type's font is configured to use a default font, then that default font will be zoomed.
So, the font size change is not limited to the current file and the new value of the font size is available here Window > Preferences > General > Appearance > Colors and Fonts.
For a start I would recommend wxglade. It is a rather easy to use tool that helps you build wxPython applications. wx is already cross platform and can be packaged with tools like py2exe or py2app.
You could do something like this:
<body>
<textarea id="txtArea" onkeypress="onTestChange();"></textarea>
<script>
function onTestChange() {
var key = window.event.keyCode;
// If the user has pressed enter
if (key === 13) {
document.getElementById("txtArea").value = document.getElementById("txtArea").value + "\n*";
return false;
}
else {
return true;
}
}
</script>
</body>
Although the new line character feed from pressing enter will still be there, but its a start to getting what you want.
I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.
SELECT wpoi.order_id As No_Commande
FROM wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id
AND wpp.meta_key = '_shipping_first_name'
WHERE wpoi.order_id =2198
This question is already answered and most of the answers here are correct but they don't solve one major issue with config changes. Have a look at this article https://androidresearch.wordpress.com/2013/05/10/dealing-with-asynctask-and-screen-orientation/ if you would like to write a async task in a better way.
You can use the following:
float asd = (float) Convert.ToDouble("41.00027357629127");
You are likely to use in the code a variable named model
.
Don't write Objective-C as if it were Java/C#/C++/etc.
I once saw a team used to writing Java EE web applications try to write a Cocoa desktop application. As if it was a Java EE web application. There was a lot of AbstractFooFactory and FooFactory and IFoo and Foo flying around when all they really needed was a Foo class and possibly a Fooable protocol.
Part of ensuring you don't do this is truly understanding the differences in the language. For example, you don't need the abstract factory and factory classes above because Objective-C class methods are dispatched just as dynamically as instance methods, and can be overridden in subclasses.
The del statement is what you're looking for. If you have a dictionary named foo with a key called 'bar', you can delete 'bar' from foo like this:
del foo['bar']
Note that this permanently modifies the dictionary being operated on. If you want to keep the original dictionary, you'll have to create a copy beforehand:
>>> foo = {'bar': 'baz'}
>>> fu = dict(foo)
>>> del foo['bar']
>>> print foo
{}
>>> print fu
{'bar': 'baz'}
The dict
call makes a shallow copy. If you want a deep copy, use copy.deepcopy
.
Here's a method you can copy & paste, for your convenience:
def minus_key(key, dictionary):
shallow_copy = dict(dictionary)
del shallow_copy[key]
return shallow_copy
Just a recommendation:
I'd recommend using the DOM table implementation, it's very straight forward and easy to use, you really don't need jQuery for this task.
var table = document.getElementById('tblOne');
var rowLength = table.rows.length;
for(var i=0; i<rowLength; i+=1){
var row = table.rows[i];
//your code goes here, looping over every row.
//cells are accessed as easy
var cellLength = row.cells.length;
for(var y=0; y<cellLength; y+=1){
var cell = row.cells[y];
//do something with every cell here
}
}
I had this error with Firebase Admin, the solution was configure the Firebase Admin correctly following this link
The issue is with the Version of JSCH jar you are using.
Update it to latest jar.
I was also getting the same error and this solution worked.
You can download latest jar from
It is not possible yet to search for content using multiple tags, for now only single tags are supported.
Firstly, the Instagram API endpoint "tags" required OAuth authentication.
This is not quite true, you only need an API-Key. Just register an application and add it to your requests. Example:
https://api.instagram.com/v1/users/userIdYouWantToGetMediaFrom/media/recent?client_id=yourAPIKey
Also note that the username is not the user-id. You can look up user-Id`s here.
A workaround for searching multiple keywords would be if you start one request for each tag and compare the results on your server. Of course this could slow down your site depending on how much keywords you want to compare.
As stated in this answer not all browsers support the standard way. It is not a good idea to use for robust user experience. And if you use it, you cannot ask too much.
Instead use time-picker libraries. For example: TimePicker.js is a zero dependency and lightweight library. Use it like:
var timepicker = new TimePicker('time', {_x000D_
lang: 'en',_x000D_
theme: 'dark'_x000D_
});_x000D_
timepicker.on('change', function(evt) {_x000D_
_x000D_
var value = (evt.hour || '00') + ':' + (evt.minute || '00');_x000D_
evt.element.value = value;_x000D_
_x000D_
});
_x000D_
<script src="https://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.js"></script>_x000D_
<link href="https://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div>_x000D_
<input type="text" id="time" placeholder="Time">_x000D_
</div>
_x000D_
$(window).on('load', function () {
alert('Alert after page load');
}
});
I have found one related behaviour that may help (sounds like your specific problem runs deeper though):
Flash checks whether a source file needs recompiling by looking at timestamps. If its compiled version is older than the source file, it will recompile. But it doesn't check whether the compiled version was generated from the same source file or not.
Specifically, if you have your actionscript files under version control, and you Revert a change, the reverted file will usually have an older timestamp, and Flash will ignore it.
This line:
char b = "blah";
Is no good - your lvalue needs to be a pointer.
Your code is also in danger of a stack overflow, since your recursion check isn't bounding the decreasing value of x.
Anyway, the actual error message you are getting is because char a
is an automatic variable; the moment you return
it will cease to exist. You need something other than an automatic variable.
As so often with SQL-related question, it depends on the DBMS. Some DBMS allow you to combine ALTER table operations separated by commas. For example...
Informix syntax:
ALTER TABLE one
ADD two_id INTEGER,
ADD CONSTRAINT FOREIGN KEY(two_id) REFERENCES two(id);
The syntax for IBM DB2 LUW is similar, repeating the keyword ADD but (if I read the diagram correctly) not requiring a comma to separate the added items.
Microsoft SQL Server syntax:
ALTER TABLE one
ADD two_id INTEGER,
FOREIGN KEY(two_id) REFERENCES two(id);
Some others do not allow you to combine ALTER TABLE operations like that. Standard SQL only allows a single operation in the ALTER TABLE statement, so in Standard SQL, it has to be done in two steps.
My fix for this issue was to separate the primary key with the foreign key. If you are using eclipse and made the above changes please remember to refresh the database explorer. Then recreate the entities from the tables.
# coding: utf-8
from __future__ import unicode_literals
import base64
import os
import six
from Crypto import Random
from Crypto.PublicKey import RSA
class PublicKeyFileExists(Exception): pass
class RSAEncryption(object):
PRIVATE_KEY_FILE_PATH = None
PUBLIC_KEY_FILE_PATH = None
def encrypt(self, message):
public_key = self._get_public_key()
public_key_object = RSA.importKey(public_key)
random_phrase = 'M'
encrypted_message = public_key_object.encrypt(self._to_format_for_encrypt(message), random_phrase)[0]
# use base64 for save encrypted_message in database without problems with encoding
return base64.b64encode(encrypted_message)
def decrypt(self, encoded_encrypted_message):
encrypted_message = base64.b64decode(encoded_encrypted_message)
private_key = self._get_private_key()
private_key_object = RSA.importKey(private_key)
decrypted_message = private_key_object.decrypt(encrypted_message)
return six.text_type(decrypted_message, encoding='utf8')
def generate_keys(self):
"""Be careful rewrite your keys"""
random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
private, public = key.exportKey(), key.publickey().exportKey()
if os.path.isfile(self.PUBLIC_KEY_FILE_PATH):
raise PublicKeyFileExists('???? ? ????????? ?????? ??????????. ??????? ????')
self.create_directories()
with open(self.PRIVATE_KEY_FILE_PATH, 'w') as private_file:
private_file.write(private)
with open(self.PUBLIC_KEY_FILE_PATH, 'w') as public_file:
public_file.write(public)
return private, public
def create_directories(self, for_private_key=True):
public_key_path = self.PUBLIC_KEY_FILE_PATH.rsplit('/', 1)
if not os.path.exists(public_key_path):
os.makedirs(public_key_path)
if for_private_key:
private_key_path = self.PRIVATE_KEY_FILE_PATH.rsplit('/', 1)
if not os.path.exists(private_key_path):
os.makedirs(private_key_path)
def _get_public_key(self):
"""run generate_keys() before get keys """
with open(self.PUBLIC_KEY_FILE_PATH, 'r') as _file:
return _file.read()
def _get_private_key(self):
"""run generate_keys() before get keys """
with open(self.PRIVATE_KEY_FILE_PATH, 'r') as _file:
return _file.read()
def _to_format_for_encrypt(value):
if isinstance(value, int):
return six.binary_type(value)
for str_type in six.string_types:
if isinstance(value, str_type):
return value.encode('utf8')
if isinstance(value, six.binary_type):
return value
And use
KEYS_DIRECTORY = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS
class TestingEncryption(RSAEncryption):
PRIVATE_KEY_FILE_PATH = KEYS_DIRECTORY + 'private.key'
PUBLIC_KEY_FILE_PATH = KEYS_DIRECTORY + 'public.key'
# django/flask
from django.core.files import File
class ProductionEncryption(RSAEncryption):
PUBLIC_KEY_FILE_PATH = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS + 'public.key'
def _get_private_key(self):
"""run generate_keys() before get keys """
from corportal.utils import global_elements
private_key = global_elements.request.FILES.get('private_key')
if private_key:
private_key_file = File(private_key)
return private_key_file.read()
message = 'Hello ??? friend'
encrypted_mes = ProductionEncryption().encrypt(message)
decrypted_mes = ProductionEncryption().decrypt(message)
here is working code.
i use appBarLayout to anchor my floatingActionButton. hope this might helpful.
XML CODE.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_height="192dp"
android:layout_width="match_parent">
<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:toolbarId="@+id/toolbar"
app:titleEnabled="true"
app:layout_scrollFlags="scroll|enterAlways|exitUntilCollapsed"
android:id="@+id/collapsingbar"
app:contentScrim="?attr/colorPrimary">
<android.support.v7.widget.Toolbar
app:layout_collapseMode="pin"
android:id="@+id/toolbarItemDetailsView"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"></android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.rktech.myshoplist.Item_details_views">
<RelativeLayout
android:orientation="vertical"
android:focusableInTouchMode="true"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--Put Image here -->
<ImageView
android:visibility="gone"
android:layout_marginTop="56dp"
android:layout_width="match_parent"
android:layout_height="230dp"
android:scaleType="centerCrop"
android:src="@drawable/third" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:cardCornerRadius="4dp"
app:cardElevation="4dp"
app:cardMaxElevation="6dp"
app:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:padding="3dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/txtDetailItemTitle"
style="@style/TextAppearance.AppCompat.Title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:text="Title" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="8dp"
android:orientation="horizontal">
<TextView
android:id="@+id/txtDetailItemSeller"
style="@style/TextAppearance.AppCompat.Subhead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:layout_weight="1"
android:text="Shope Name" />
<TextView
android:id="@+id/txtDetailItemDate"
style="@style/TextAppearance.AppCompat.Subhead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="4dp"
android:gravity="right"
android:text="Date" />
</LinearLayout>
<TextView
android:id="@+id/txtDetailItemDescription"
style="@style/TextAppearance.AppCompat.Medium"
android:layout_width="match_parent"
android:minLines="5"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:layout_marginTop="16dp"
android:text="description" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:orientation="horizontal">
<TextView
android:id="@+id/txtDetailItemQty"
style="@style/TextAppearance.AppCompat.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:layout_weight="1"
android:text="Qunatity" />
<TextView
android:id="@+id/txtDetailItemMessure"
style="@style/TextAppearance.AppCompat.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="4dp"
android:layout_weight="1"
android:gravity="right"
android:text="Messure in Gram" />
</LinearLayout>
<TextView
android:id="@+id/txtDetailItemPrice"
style="@style/TextAppearance.AppCompat.Headline"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="4dp"
android:layout_weight="1"
android:gravity="right"
android:text="Price" />
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
</android.support.v4.widget.NestedScrollView>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
app:layout_anchor="@id/appbar"
app:fabSize="normal"
app:layout_anchorGravity="bottom|right|end"
android:layout_marginEnd="@dimen/_6sdp"
android:src="@drawable/ic_done_black_24dp"
android:layout_height="wrap_content" />
</android.support.design.widget.CoordinatorLayout>
Now if you paste above code. you will see following result on your device.
You can use .is(':visible')
to test if something is visible and .is(':hidden')
to test for the opposite:
$('#offers').toggle(!$('#column-left form').is(':visible')); // or:
$('#offers').toggle($('#column-left form').is(':hidden'));
Reference:
Create a Java Model using Axis wsdl2java (which can take in .xsd files).
Use a database generation tool for Java that takes in a Java Model. Surely something like Hibernate can do this? I wrote my own tool (takes a couple of days, also generates CRUD code in Java too) to save myself time at work, maybe this would be a nice personal project?
Or just do it manually so that you can check everything is correct and good! Database tools are good enough now that you can zip through creating tables for a model without too many problems.
if ( defined $x && $x !~ m/\D/ ) {} or $x = 0 if ! $x; if ( $x !~ m/\D/) {}
This is a slight variation on Veekay's answer but let me explain my reasoning for the change.
Performing a regex on an undefined value will cause error spew and will cause the code to exit in many if not most environments. Testing if the value is defined or setting a default case like i did in the alternative example before running the expression will, at a minimum, save your error log.
On the one hand as @Mark-Rajcok said you can just get away with private inner function:
// at the bottom of your controller
var init = function () {
// check if there is query in url
// and fire search in case its value is not empty
};
// and fire it after definition
init();
Also you can take a look at ng-init directive. Implementation will be much like:
// register controller in html
<div data-ng-controller="myCtrl" data-ng-init="init()"></div>
// in controller
$scope.init = function () {
// check if there is query in url
// and fire search in case its value is not empty
};
But take care about it as angular documentation implies (since v1.2) to NOT use ng-init
for that. However imo it depends on architecture of your app.
I used ng-init
when I wanted to pass a value from back-end into angular app:
<div data-ng-controller="myCtrl" data-ng-init="init('%some_backend_value%')"></div>
Model.pluck("DISTINCT column_name")
Pulling in things from all the answers above, here's what I came up with.
There are essentially two ways to do this:
;WITH TMP AS (
SELECT CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("bin")))', 'VARCHAR(MAX)') as Base64Encoding
FROM
(
SELECT TOP 10000 CAST(Words AS VARBINARY(MAX)) AS bin FROM TestData
) SRC
)
SELECT *, CAST(CAST(N'' AS XML).value('xs:base64Binary(sql:column("Base64Encoding"))', 'VARBINARY(MAX)') AS NVARCHAR(MAX)) as ASCIIEncoding
FROM
(
SELECT * FROM TMP
) SRC
And the second way
;WITH TMP AS
(
SELECT TOP 10000 CONVERT(VARCHAR(MAX), (SELECT CAST(Wordsas varbinary(max)) FOR XML PATH(''))) as BX
FROM TestData
)
SELECT *, CONVERT(NVARCHAR(MAX), CONVERT(XML, BX).value('.','varbinary(max)'))
FROM TMP
When comparing performance, the first one has a subtree cost of 2.4414 and the second one has a subtree cost of 4.1538. Which means the first one is about twice as fast as the second one (which is expected, since it uses XML, which is notoriously slow).
IsEmpty()
would be the quickest way to check for that.
IsNull()
would seem like a similar solution, but keep in mind Null has to be assigned to the cell; it's not inherently created in the cell.
Also, you can check the cell by:
count()
counta()
Len(range("BCell").Value) = 0
Use ampersand to specify the parent selector.
SCSS syntax:
p {
margin: 2em auto;
> a {
color: red;
}
&:before {
content: "";
}
&:after {
content: "* * *";
}
}
If you want to export all JAR-files of a Java web-project, open the latest generated WAR-file with a ZIP-tool (e.g. 7-Zip), navigate to the /WEB-INF/lib/ folder. Here you will find all JAR-files you need for this project (as listed in "Referenced Libraries").
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
Updated:
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Output:
So, is that a behavior to expect, a bug
Truth be told I am not sure. It looks like parser is interpreting count
not as a column name but a function and expects following parentheses. Looks like a bug or at least a serious limitation of the parser.
is there a canonical way to go around?
Some options have been already mentioned by Herman and mattinbits so here more SQLish approach from me:
import org.apache.spark.sql.functions.count
df.groupBy("x").agg(count("*").alias("cnt")).where($"cnt" > 2)
If you're running Linux I would suggest two tools:
align_image_stack from package hugin-tools - is a commandline program that can automatically correct rotation, scaling, and other distortions (it's mostly intended for compositing HDR photography, but works for video frames and other documents too). More information: http://hugin.sourceforge.net/docs/manual/Align_image_stack.html
compare from package imagemagick - a program that can find and count the amount of different pixels in two images. Here's a neat tutorial: http://www.imagemagick.org/Usage/compare/ uising the -fuzz N% you can increase the error tolerance. The higher the N the higher the error tolerance to still count two pixels as the same.
align_image_stack should correct any offset so the compare command will actually have a chance of detecting same pixels.
A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection
, instead.
Below is the code to do that,
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty ("Authorization", encodedCredentials);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(data);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
Change URLConnection
to HttpURLConnection
, to make it POST request.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
Suggestion (...in comments):
You might need to set these properties too,
conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );
When create React components from functions
and useState
.
const [drawerState, setDrawerState] = useState(false);
const toggleDrawer = () => {
// attempting to trigger re-render
setDrawerState(!drawerState);
};
This does not work
<Drawer
drawerState={drawerState}
toggleDrawer={toggleDrawer}
/>
This does work (adding key)
<Drawer
drawerState={drawerState}
key={drawerState}
toggleDrawer={toggleDrawer}
/>
My answer is similar to this one on ServerFault.com.
If you want to be more conservative than granting "all privileges", you might want to try something more like these.
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO some_user_;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO some_user_;
The use of public
there refers to the name of the default schema created for every new database/catalog. Replace with your own name if you created a schema.
To access a schema at all, for any action, the user must be granted "usage" rights. Before a user can select, insert, update, or delete, a user must first be granted "usage" to a schema.
You will not notice this requirement when first using Postgres. By default every database has a first schema named public
. And every user by default has been automatically been granted "usage" rights to that particular schema. When adding additional schema, then you must explicitly grant usage rights.
GRANT USAGE ON SCHEMA some_schema_ TO some_user_ ;
Excerpt from the Postgres doc:
For schemas, allows access to objects contained in the specified schema (assuming that the objects' own privilege requirements are also met). Essentially this allows the grantee to "look up" objects within the schema. Without this permission, it is still possible to see the object names, e.g. by querying the system tables. Also, after revoking this permission, existing backends might have statements that have previously performed this lookup, so this is not a completely secure way to prevent object access.
For more discussion see the Question, What GRANT USAGE ON SCHEMA exactly do?. Pay special attention to the Answer by Postgres expert Craig Ringer.
These commands only affect existing objects. Tables and such you create in the future get default privileges until you re-execute those lines above. See the other answer by Erwin Brandstetter to change the defaults thereby affecting future objects.
Join on the prices table, and then select the entry for the last day:
select pa.partid, pa.Partnumber, max(pr.price)
from myparts pa
inner join myprices pr on pr.partid = pa.partid
where pr.PriceDate = (
select max(PriceDate)
from myprices
where partid = pa.partid
)
The max() is in case there are multiple prices per day; I'm assuming you'd like to display the highest one. If your price table has an id column, you can avoid the max() and simplify like:
select pa.partid, pa.Partnumber, pr.price
from myparts pa
inner join myprices pr on pr.partid = pa.partid
where pr.priceid = (
select max(priceid)
from myprices
where partid = pa.partid
)
P.S. Use wcm's solution instead!
I shall try the solution with jQuery, for sure it should give a nice result. Of course you have to load jQuery ... What about a pop-up with something like this? Of course this is dependant on the user authorizing pop-ups.
<html>
<head>
<script language="javascript">
var ret;
function returnfunction()
{
alert(ret);
}
</script>
</head>
<body>
<form>
<label id="QuestionToAsk" name="QuestionToAsk">Here is talked.</label><br />
<input type="button" value="Yes" name="yes" onClick="ret=true;returnfunction()" />
<input type="button" value="No" onClick="ret=false;returnfunction()" />
</form>
</body>
</html>
The proposed solutions are perfect to download the images and if it is enough for you to save all the files in the directory you are using. But if you want to save all the images in a specified directory without reproducing the entire hierarchical tree of the site, try to add "cut-dirs" to the line proposed by Jon.
wget -r -P /save/location -A jpeg,jpg,bmp,gif,png http://www.boia.de --cut-dirs=1 --cut-dirs=2 --cut-dirs=3
in this case cut-dirs will prevent wget from creating sub-directories until the 3th level of depth in the website hierarchical tree, saving all the files in the directory you specified.You can add more 'cut-dirs' with higher numbers if you are dealing with sites with a deep structure.
What are iml files in Android Studio project?
A Google search on iml file
turns up:
IML is a module file created by IntelliJ IDEA, an IDE used to develop Java applications. It stores information about a development module, which may be a Java, Plugin, Android, or Maven component; saves the module paths, dependencies, and other settings.
(from this page)
why not to use gradle scripts to integrate with external modules that you add to your project.
You do "use gradle scripts to integrate with external modules", or your own modules.
However, Gradle is not IntelliJ IDEA's native project model — that is separate, held in .iml
files and the metadata in .idea/
directories. In Android Studio, that stuff is largely generated out of the Gradle build scripts, which is why you are sometimes prompted to "sync project with Gradle files" when you change files like build.gradle
. This is also why you don't bother putting .iml
files or .idea/
in version control, as their contents will be regenerated.
If I have a team that work in different IDE's like Eclipse and AS how to make project IDE agnostic?
To a large extent, you can't.
You are welcome to have an Android project that uses the Eclipse-style directory structure (e.g., resources and manifest in the project root directory). You can teach Gradle, via build.gradle
, how to find files in that structure. However, other metadata (compileSdkVersion
, dependencies, etc.) will not be nearly as easily replicated.
Other alternatives include:
Move everybody over to another build system, like Maven, that is equally integrated (or not, depending upon your perspective) to both Eclipse and Android Studio
Hope that Andmore takes off soon, so that perhaps you can have an Eclipse IDE that can build Android projects from Gradle build scripts
Have everyone use one IDE
Wanted to comment on the last answer, but without login it’s only possible to make an answer:
To get rid of the "read only error" just stop the device immediately after it’s ready. My script looks as follows:
#!/bin/bash
~/bin/AndroidSdk/tools/emulator @Nexus_6P_API_23 -no-boot-anim &
adb wait-for-device
adb shell stop
adb remount
adb push GmsCore.apk /system/priv-app
adb push GoogleServicesFramework.apk /system/priv-app
adb push GoogleLoginService.apk /system/priv-app
adb push Phonesky.apk /system/priv-app
adb shell start
In my case, my server was configured to work only in https mode, and error occured when I try to access http mode. So changing http://my-service
to https://my-service
helped.
if os.path.exists(filePath):
#the file is there
elif os.access(os.path.dirname(filePath), os.W_OK):
#the file does not exists but write privileges are given
else:
#can not write there
Note that path.exists
can fail for more reasons than just the file is not there
so you might have to do finer tests like testing if the containing directory exists and so on.
After my discussion with the OP it turned out, that the main problem seems to be, that the file name might contain characters that are not allowed by the filesystem. Of course they need to be removed but the OP wants to maintain as much human readablitiy as the filesystem allows.
Sadly I do not know of any good solution for this. However Cecil Curry's answer takes a closer look at detecting the problem.
As the above people stated, select PostGIS_full_version(); will answer your question. On my machine, where I'm running PostGIS 2.0 from trunk, I get the following output:
postgres=# select PostGIS_full_version();
postgis_full_version
-------------------------------------------------------------------------------------------------------------------------------------------------------
POSTGIS="2.0.0alpha4SVN" GEOS="3.3.2-CAPI-1.7.2" PROJ="Rel. 4.7.1, 23 September 2009" GDAL="GDAL 1.8.1, released 2011/07/09" LIBXML="2.7.3" USE_STATS
(1 row)
You do need to care about the versions of PROJ and GEOS that are included if you didn't install an all-inclusive package - in particular, there's some brokenness in GEOS prior to 3.3.2 (as noted in the postgis 2.0 manual) in dealing with geometry validity.
For kotlin, it's not possible for now but they've considered to add it: Source
But for now, just a little trick:
try {
// code
} catch(ex:Exception) {
when(ex) {
is SomeException,
is AnotherException -> {
// handle
}
else -> throw ex
}
}
Since none of the answers here solved my particular issue, I should probably add my own solution to to the list.
I had to hard reset my computer while MAMP was still running. This sometimes leads to a problem where, after restarting the machine MAMP can start the Apache Server
, but can not start the MySQL server
for some reason.
My solution for this issue was to:
Applications/MAMP/tmp/mysql
mysql.sock.lock
Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.
Let me explain using step-by-step guidance.
First, download the source code from https://github.com/rmtheis/tess-two.
Import all three projects. After importing you will get an error.
To solve the error you have to create a res
folder in the tess-two project
First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"
After doing this in all three project the error should be gone.
Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.
Now you just need to import it into your workspace, but first you have to download android-ndk from this site:
http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file
Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable
Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture
done it
Now open cmd and go to on D:\Android Workspace\tess-two like below
If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:
Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest
Import test-two in this and run OCRTest and run it; you will get the best example of OCR.
Just created python script for that:
import sys
from shutil import which
import logging
from subprocess import check_output, call
logger = logging.getLogger(__name__)
if __name__ == '__main__':
if which("git") is None:
logger.error("git is not found!")
sys.exit(-1)
branches = check_output("git branch -r --merged".split()).strip().decode("utf8").splitlines()
current = check_output("git branch --show-current".split()).strip().decode("utf8")
blacklist = ["master", current]
for b in branches:
b = b.split("/")[-1]
if b in blacklist:
continue
else:
if input(f"Do you want to delete branch: '{b}' [y/n]\n").lower() == "y":
call(f"git branch -D {b}".split())
call(f"git push --delete origin {b}".split())
Concatenate strings just like in the DOS days. This is a big deal for logging so here you go:
$strDate = Get-Date
$strday = "$($strDate.Year)$($strDate.Month)$($strDate.Day)"
Write-Output "$($strDate.Year)$($strDate.Month)$($strDate.Day)"
Write-Output $strday
For me, the jobs were running under DOMAIN\Administrator and failing with the error message "The job failed. Unable to determine if the owner (DOMAIN\administrator) of job Agent history clean up: distribution has server access (reason: Could not obtain information about Windows NT group/user 'DOMAIN\administrator', error code 0x5. [SQLSTATE 42000] (Error 15404)).
To fix this, I changed the owner of each failing job to sa
. Worked flawlessly after that. The jobs were related to replication cleanup, but I'm unsure if they were manually added or were added as a part of the replication set-up - I wasn't involved with it, so I am not sure.
Add ID current
for active/current page:
<div class="menuBar">
<ul>
<li id="current"><a href="index.php">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
<li><a href="three.php">ABOUT</a></li>
<li><a href="four.php">CONTACT</a></li>
<li><a href="five.php">SHOP</a></li>
</ul>
#current a { color: #ff0000; }
Or, as an alternative to @Chase's code, being a recent plyr fan with a background in databases:
require(plyr)
zz<-join(df1, df2, type="left")
zz[is.na(zz)] <- 0
Just to make one point clear about
Main-Class: <packagename>.<classname>
If you don't have package you have to ignore that part, like this:
Main-Class: <classname>
The command-line program for 7-Zip is 7z or 7za. Here's a helpful post on the options available. The -r (recurse) option stores paths.
Below code shows the two sub-controllers from where the events are dispatched upwards to parent controller (rootScope)
<body ng-app="App">
<div ng-controller="parentCtrl">
<p>City : {{city}} </p>
<p> Address : {{address}} </p>
<div ng-controller="subCtrlOne">
<input type="text" ng-model="city" />
<button ng-click="getCity(city)">City !!!</button>
</div>
<div ng-controller="subCtrlTwo">
<input type="text" ng-model="address" />
<button ng-click="getAddrress(address)">Address !!!</button>
</div>
</div>
</body>
var App = angular.module('App', []);
// parent controller
App.controller('parentCtrl', parentCtrl);
parentCtrl.$inject = ["$scope"];
function parentCtrl($scope) {
$scope.$on('cityBoom', function(events, data) {
$scope.city = data;
});
$scope.$on('addrBoom', function(events, data) {
$scope.address = data;
});
}
// sub controller one
App.controller('subCtrlOne', subCtrlOne);
subCtrlOne.$inject = ['$scope'];
function subCtrlOne($scope) {
$scope.getCity = function(city) {
$scope.$emit('cityBoom', city);
}
}
// sub controller two
App.controller('subCtrlTwo', subCtrlTwo);
subCtrlTwo.$inject = ["$scope"];
function subCtrlTwo($scope) {
$scope.getAddrress = function(addr) {
$scope.$emit('addrBoom', addr);
}
}
It depends on how you tested it, and possibly on differences in the TCP stack implementation of the personal computer and the server.
For example, if your sendall
always completes immediately (or very quickly) on the personal computer, the connection may simply never have broken during sending. This is very likely if your browser is running on the same machine (since there is no real network latency).
In general, you just need to handle the case where a client disconnects before you're finished, by handling the exception.
Remember that TCP communications are asynchronous, but this is much more obvious on physically remote connections than on local ones, so conditions like this can be hard to reproduce on a local workstation. Specifically, loopback connections on a single machine are often almost synchronous.
Fall through approach is the best one i feel.
case text1:
case text4: {
//Yada yada
break;
}
AFAIK, no such way. And there is also an ambiguity: what would you like to get as the answer if the same executable has multiple hard-links "pointing" to it? (Hard-links don't actually "point", they are the same file, just at another place in the file system hierarchy.)
Once execve()
successfully executes a new binary, all information about the arguments to the original program is lost.
I doubt very much a telnet library will ever be part of the .Net BCL, although you do have almost full socket support so it wouldnt be too hard to emulate a telnet client, Telnet in its general implementation is a legacy and dying technology that where exists generally sits behind a nice new modern facade. In terms of Unix/Linux variants you'll find that out the box its SSH and enabling telnet is generally considered poor practice.
You could check out: http://granados.sourceforge.net/ - SSH Library for .Net http://www.tamirgal.com/home/dev.aspx?Item=SharpSsh
You'll still need to put in place your own wrapper to handle events for feeding in input in a scripted manner.
What might be easier, is to have two buttons and show/hide them in your functions. (ie. display:none|block;
) Each button could then have it's own onclick with whatever code you need.
So, at first button1
would be display:block
and button2
would be display:none
. Then when you click button1
it would switch button2
to be display:block
and button1
to be display:none
.
you can also use append function
b = [ ]
for x in range(0, 5):
b.append(["O"] * 5)
def print_b(b):
for row in b:
print " ".join(row)
Here's an extremely simple CSV parser that handles quoted fields with commas, new lines, and escaped double quotation marks. There's no splitting or regular expression. It scans the input string 1-2 characters at a time and builds an array.
Test it at http://jsfiddle.net/vHKYH/.
function parseCSV(str) {
var arr = [];
var quote = false; // 'true' means we're inside a quoted field
// Iterate over each character, keep track of current row and column (of the returned array)
for (var row = 0, col = 0, c = 0; c < str.length; c++) {
var cc = str[c], nc = str[c+1]; // Current character, next character
arr[row] = arr[row] || []; // Create a new row if necessary
arr[row][col] = arr[row][col] || ''; // Create a new column (start with empty string) if necessary
// If the current character is a quotation mark, and we're inside a
// quoted field, and the next character is also a quotation mark,
// add a quotation mark to the current column and skip the next character
if (cc == '"' && quote && nc == '"') { arr[row][col] += cc; ++c; continue; }
// If it's just one quotation mark, begin/end quoted field
if (cc == '"') { quote = !quote; continue; }
// If it's a comma and we're not in a quoted field, move on to the next column
if (cc == ',' && !quote) { ++col; continue; }
// If it's a newline (CRLF) and we're not in a quoted field, skip the next character
// and move on to the next row and move to column 0 of that new row
if (cc == '\r' && nc == '\n' && !quote) { ++row; col = 0; ++c; continue; }
// If it's a newline (LF or CR) and we're not in a quoted field,
// move on to the next row and move to column 0 of that new row
if (cc == '\n' && !quote) { ++row; col = 0; continue; }
if (cc == '\r' && !quote) { ++row; col = 0; continue; }
// Otherwise, append the current character to the current column
arr[row][col] += cc;
}
return arr;
}
In addition to all the comments, I thought I might add some code on how to use java.util.Date, java.util.Calendar and java.util.GregorianCalendar according to the javadoc.
//Initialize your Date however you like it.
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
//Add one to month {0 - 11}
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
If you don't want to wrap it in another div as other answers have suggested, you can also wrap it in an array and it will work.
// Wrong!
return (
<Comp1 />
<Comp2 />
)
It can be written as:
// Correct!
return (
[<Comp1 />,
<Comp2 />]
)
Please note that the above will generate a warning: Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of 'YourComponent'.
This can be fixed by adding a key
attribute to the components, if manually adding these add it like:
return (
[<Comp1 key="0" />,
<Comp2 key="1" />]
)
Here is some more information on keys:Composition vs Inheritance
if the zipcode field is not a required field then add null=True and blank=True, then run makemigrations and migrate command to successfully reflect the changes in the database.
All of the below is copied directly from @TomOnTime's serverfault answer here:
Show lines that only exist in file a: (i.e. what was deleted from a)
comm -23 a b
Show lines that only exist in file b: (i.e. what was added to b)
comm -13 a b
Show lines that only exist in one file or the other: (but not both)
comm -3 a b | sed 's/^\t//'
(Warning: If file a
has lines that start with TAB, it (the first TAB) will be removed from the output.)
NOTE: Both files need to be sorted for "comm" to work properly. If they aren't already sorted, you should sort them:
sort <a >a.sorted
sort <b >b.sorted
comm -12 a.sorted b.sorted
If the files are extremely long, this may be quite a burden as it requires an extra copy and therefore twice as much disk space.
Edit: note that the command can be written more concisely using process substitution (thanks to @phk for the comment):
comm -12 <(sort < a) <(sort < b)
git archive --format=zip --remote=ssh://<user>@<host>/repos/<repo name> <tag or HEAD> <filename> > <output file name>.zip
As ghills had already mentioned
inp = int(input("Enter a number:"))
n = 0
for i in str(inp):
n = n + int(i);
print n
When you are looping through something, keyword is "IN", just always think of it as a list of something. You cannot loop through a plain integer. Therefore, it is not iterable.
As far as I understand, it is going to drop your database and re-create it based on your db/schema.rb
file. That is why you need to make sure that your schema.rb
file is always up to date and under version control.
As you state JPA is just a specification, meaning there is no implementation. You can annotate your classes as much as you would like with JPA annotations, however without an implementation nothing will happen. Think of JPA as the guidelines that must be followed or an interface, while Hibernate's JPA implementation is code that meets the API as defined by the JPA specification and provides the under the hood functionality.
When you use Hibernate with JPA you are actually using the Hibernate JPA implementation. The benefit of this is that you can swap out Hibernate's implementation of JPA for another implementation of the JPA specification. When you use straight Hibernate you are locking into the implementation because other ORMs may use different methods/configurations and annotations, therefore you cannot just switch over to another ORM.
For a more detailed description read my blog entry.
If you need to include non-ASCII alphabetic characters, and if your regex flavor supports Unicode, then
\A\pL+\z
would be the correct regex.
Some regex engines don't support this Unicode syntax but allow the \w
alphanumeric shorthand to also match non-ASCII characters. In that case, you can get all alphabetics by subtracting digits and underscores from \w
like this:
\A[^\W\d_]+\z
\A
matches at the start of the string, \z
at the end of the string (^
and $
also match at the start/end of lines in some languages like Ruby, or if certain regex options are set).
http://incubator.apache.org/hama/ is a distributed scientific package on Hadoop for massive matrix and graph data.
A scrolling comes from a box with class pre-scrollable
<div class="pre-scrollable"></div>
There's more examples: http://getbootstrap.com/css/#code-block
Wish it helps.
If you append ..\..
to your existing path, the operating system will correctly browse the grand-parent folder.
That should do the job:
System.IO.Path.Combine("C:\\Users\\Masoud\\Documents\\Visual Studio 2008\\Projects\\MyProj\\MyProj\\bin\\Debug", @"..\..");
If you browse that path, you will browse the grand-parent directory.
Sample here:
<Style TargetType="Window" x:Key="DialogWindow">
<Setter Property="AllowsTransparency" Value="True"/>
<Setter Property="WindowStyle" Value="None"/>
<Setter Property="ResizeMode" Value="CanResizeWithGrip"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<Border BorderBrush="Black" BorderThickness="3" CornerRadius="10" Height="{TemplateBinding Height}"
Width="{TemplateBinding Width}" Background="Gray">
<DockPanel>
<Grid DockPanel.Dock="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition Width="50"/>
</Grid.ColumnDefinitions>
<Label Height="35" Grid.ColumnSpan="2"
x:Name="PART_WindowHeader"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"/>
<Button Width="15" Height="15" Content="x" Grid.Column="1" x:Name="PART_CloseButton"/>
</Grid>
<Border HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Background="LightBlue" CornerRadius="0,0,10,10"
Grid.ColumnSpan="2"
Grid.RowSpan="2">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="20"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="20"></RowDefinition>
</Grid.RowDefinitions>
<ResizeGrip Width="10" Height="10" Grid.Column="1" VerticalAlignment="Bottom" Grid.Row="1"/>
</Grid>
</Border>
</DockPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
One reason for this error is very silly mistake in code. If proper value is not passed to a property of ActiveX, then also this error is thrown.
Like empty value is passed to Font.Name property or text value is passed to Height property.
I am reading some data from a file using read. Here I am reading data in a 2d char pointer but the method is the same for the 1d also. Just read character by character and do not worry about the exceptions because the condition in the while loop is handling the exceptions :D
while ( (n = read(fd, buffer,1)) > 0 )
{
if(buffer[0] == '\n')
{
r++;
char**tempData=(char**)malloc(sizeof(char*)*r);
for(int a=0;a<r;a++)
{
tempData[a]=(char*)malloc(sizeof(char)*BUF_SIZE);
memset(tempData[a],0,BUF_SIZE);
}
for(int a=0;a<r-1;a++)
{
strcpy(tempData[a],data[a]);
}
data=tempData;
c=0;
}
else
{
data[r-1][c]=buffer[0];
c++;
buffer[1]='\0';
}
}
As one of the possible codes
echo off
for /f "usebackq tokens=* delims= " %%x in (`chdir`) do set var=%var% %%x
echo The current directory is: "%var:~1%"
Are you certain that the software (and not yourself, since your test actually only shows the shell used as default for your user) uses /bin/bash ?
<html>
<head>
<title>allwon only alphabets in textbox using JavaScript</title>
<script language="Javascript" type="text/javascript">
function onlyAlphabets(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
return true;
else
return false;
}
catch (err) {
alert(err.Description);
}
}
</script>
</head>
<body>
<table align="center">
<tr>
<td>
<input type="text" onkeypress="return onlyAlphabets(event,this);" />
</td>
</tr>
</table>
</body>
</html>
That chart is not showing percents. "#90" is not "90%". That chart shows the hexadecimal to decimal conversion. The hex number 90 (typically represented as 0x90) is equivalent to the decimal number 144.
Hexadecimal numbers are base-16, so each digit is a value between 0 and F. The maximum value for a two byte hex value (such as the transparency of a color) is 0xFF, or 255 in decimal. Thus 100% is 0xFF.
You may have configured AWS credentials correctly, but using these credentials, you may be connecting to some specific S3 endpoint (as was the case with me).
Instead of using:
aws s3 ls
try using:
aws --endpoint-url=https://<your_s3_endpoint_url> s3 ls
Hope this helps those facing the similar problem.
I recommend using this HttpURLConnection
instead HttpGet
. As HttpGet
is already deprecated in Android API level 22.
HttpURLConnection httpcon;
String url = null;
String data = null;
String result = null;
try {
//Connect
httpcon = (HttpURLConnection) ((new URL (url).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();
//Write
OutputStream os = httpcon.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(data);
writer.close();
os.close();
//Read
BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Well, this works for me:
std::cout << std::hex << (0xFF & a) << std::endl;
If you just cast (int)
as suggested it might add 1s to the left of a
if its most significant bit is 1. So making this binary AND operation guarantees the output will have the left bits filled by 0s and also converts it to unsigned int forcing cout to print it as hex.
I hope this helps.
\w
matches a word character. \b
is a zero-width match that matches a position character that has a word character on one side, and something that's not a word character on the other. (Examples of things that aren't word characters include whitespace, beginning and end of the string, etc.)
\w
matches a
, b
, c
, d
, e
, and f
in "abc def"
\b
matches the (zero-width) position before a
, after c
, before d
, and after f
in "abc def"
Once you've created the frame the part of the code with your conditional isn't going to get entered. To put it another way, at the time you execute the test if (btn1Clicked == true)
, the button has not only not been clicked yet, it hasn't even been displayed to the user.
Lose the booleans and move the line with the btnConvertDocuments.setEnabled(false)
into your actionListener. Make the buttons instance variables, do not make them static variables. (Alternatively you could keep the buttons as local variables and assign each of them their own anonymous inner class listener.)
What would happen, if you want to create many such records ones (to register 10 users, not just one)? I find the following solution (just 5 queryes):
Step I: Create temporary table to store new data.
CREATE TEMPORARY TABLE tmp (id bigint(20) NOT NULL, ...)...;
Next, fill this table with values.
INSERT INTO tmp (username, password, bio, homepage) VALUES $ALL_VAL
Here, instead of $ALL_VAL
you place list of values: ('test1','test1','bio1','home1'),...,('testn','testn','bion','homen')
Step II: Send data to 'user' table.
INSERT IGNORE INTO users (username, password)
SELECT username, password FROM tmp;
Here, "IGNORE" can be used, if you allow some users already to be inside. Optionaly you can use UPDATE similar to step III, before this step, to find whom users are already inside (and mark them in tmp table). Here we suppouse, that username is declared as PRIMARY
in users table.
Step III: Apply update to read all users id from users to tmp table. THIS IS ESSENTIAL STEP.
UPDATE tmp JOIN users ON tmp.username=users.username SET tmp.id=users.id
Step IV: Create another table, useing read id for users
INSERT INTO profiles (userid, bio, homepage)
SELECT id, bio, homepage FROM tmp
User can use this
Dim todaysdate As String = String.Format("{0:dd/MM/yyyy}", DateTime.Now)
this will format the date as required whereas user can change the string type dd/MM/yyyy or MM/dd/yyyy or yyyy/MM/dd or even can have this format to get the time from date
yyyy/MM/dd HH:mm:ss
CSS is called Cascading Style Sheets because the rules are inherited. Using the following selector, will select just the direct child of the parent, but its rules will be inherited by that div
's children divs
:
div.section > div { color: red }
Now, both that div
and its children will be red
. You need to cancel out whatever you set on the parent if you don't want it to inherit:
div.section > div { color: red }
div.section > div div { color: black }
Now only that single div
that is a direct child of div.section
will be red, but its children divs
will still be black.
I hope this help. Haven't tried it out yet, will post again once I tested it.
http://blog.appideas.net/using-iphone-video-output-to-demo-your-apps-o
There could be many reasons for Index not being used. Even after you specify hints, there are chances Oracle optimizer thinks otherwise and decide not to use Index. You need to go through the EXPLAIN PLAN part and see what is the cost of the statement with INDEX and without INDEX.
Assuming the Oracle uses CBO. Most often, if the optimizer thinks the cost is high with INDEX, even though you specify it in hints, the optimizer will ignore and continue for full table scan. Your first action should be checking DBA_INDEXES to know when the statistics are LAST_ANALYZED. If not analyzed, you can set table, index for analyze.
begin
DBMS_STATS.GATHER_INDEX_STATS ( OWNNAME=>user
, INDNAME=>IndexName);
end;
For table.
begin
DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME=>user
, TABNAME=>TableName);
end;
In extreme cases, you can try setting up the statistics on your own.
At the present time, there is a simple way to fix this problem:
Tools
? MarketPlace
and search for "PDI MySQL Plugin"data-integration\plugins\databases\pdi-mysql-plugin\lib
)process.hrtime() not give current ts.
This should work.
const loadNs = process.hrtime(),
loadMs = new Date().getTime(),
diffNs = process.hrtime(loadNs),
microSeconds = (loadMs * 1e6) + (diffNs[0] * 1e9) + diffNs[1]
console.log(microSeconds / 1e3)
I assume you called a function with an argument which was defined without taking any.
def f()
puts "hello world"
end
f(1) # <= wrong number of arguments (1 for 0)
Compiler knows by type cast. Given a void *x
:
x+1
adds one byte to x
, pointer goes to byte x+1
(int*)x+1
adds sizeof(int)
bytes, pointer goes to byte x + sizeof(int)
(float*)x+1
addres sizeof(float)
bytes,
etc.Althought the first item is not portable and is against the Galateo of C/C++, it is nevertheless C-language-correct, meaning it will compile to something on most compilers possibly necessitating an appropriate flag (like -Wpointer-arith)
As pointed out in Mohsen's answer, in ES6 it's possible to extend errors using classes. It's a lot easier and their behavior is more consistent with native errors...but unfortunately it's not a simple matter to use this in the browser if you need to support pre-ES6 browsers. See below for some notes on how that might be implemented, but in the meantime I suggest a relatively simple approach that incorporates some of the best suggestions from other answers:
function CustomError(message) {
//This is for future compatibility with the ES6 version, which
//would display a similar message if invoked without the
//`new` operator.
if (!(this instanceof CustomError)) {
throw new TypeError("Constructor 'CustomError' cannot be invoked without 'new'");
}
this.message = message;
//Stack trace in V8
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError);
}
else this.stack = (new Error).stack;
}
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.name = 'CustomError';
In ES6 it's as simple as:
class CustomError extends Error {}
...and you can detect support for ES6 classes with try {eval('class X{}')
, but you'll get a syntax error if you attempt to include the ES6 version in a script that's loaded by older browsers. So the only way to support all browsers would be to load a separate script dynamically (e.g. via AJAX or eval()
) for browsers that support ES6. A further complication is that eval()
isn't supported in all environments (due to Content Security Policies), which may or may not be a consideration for your project.
So for now, either the first approach above or simply using Error
directly without trying to extend it seems to be the best that can practically be done for code that needs to support non-ES6 browsers.
There is one other approach that some people might want to consider, which is to use Object.setPrototypeOf()
where available to create an error object that's an instance of your custom error type but which looks and behaves more like a native error in the console (thanks to Ben's answer for the recommendation). Here's my take on that approach: https://gist.github.com/mbrowne/fe45db61cea7858d11be933a998926a8. But given that one day we'll be able to just use ES6, personally I'm not sure the complexity of that approach is worth it.
I have used in this way.. Working fine!
$inputs = request()->validate([
'name' => 'required | min:6 | max: 20',
'email' => 'required',
'password' => 'required| min:4| max:7 |confirmed',
'password_confirmation' => 'required| min:4'
]);
I dont know why you havent marked on of these gr8 answers... here is another option which would enable you and anyone else visiting to control transition speed and pause time
JAVASCRIPT
$(function () {
/* SET PARAMETERS */
var change_img_time = 5000;
var transition_speed = 100;
var simple_slideshow = $("#exampleSlider"),
listItems = simple_slideshow.children('li'),
listLen = listItems.length,
i = 0,
changeList = function () {
listItems.eq(i).fadeOut(transition_speed, function () {
i += 1;
if (i === listLen) {
i = 0;
}
listItems.eq(i).fadeIn(transition_speed);
});
};
listItems.not(':first').hide();
setInterval(changeList, change_img_time);
});
.
HTML
<ul id="exampleSlider">
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
</ul>
.
If your keeping this simple its easy to keep it resposive
best to visit the: DEMO
.
If you want something with special transition FX (Still responsive) - check this out
DEMO WITH SPECIAL FX
If you want to get a constraint by the column or table names, or you want to get all the constraints in the database, look to other answers. However, if you're just looking for exactly what the question asks, namely, to "test if a given default constraint exists ... by the name of the constraint", then there's a much easier way.
Here's a future-proof answer that doesn't use the sysobjects
or other sys
tables at all:
IF object_id('DF_CONSTRAINT_NAME', 'D') IS NOT NULL BEGIN
-- constraint exists, work with it.
END
No, there is no difference. But I prefer using int[] array
as it is more readable.
The following should work:
$now = date('Y-m-d');
$reservations = Reservation::where('reservation_from', '>=', $now)
->where('reservation_from', '<=', $to)
->get();
Original: @Rob, TFS has something called "Shelving" that addresses your concern about commiting work-in-progress without it affecting the official build. I realize you see central version control as a hindrance, but with respect to TFS, checking your code into the shelf can be viewed as a strength b/c then the central server has a copy of your work-in-progress in the rare event your local machine crashes or is lost/stolen or you need to switch gears quickly. My point is that TFS should be given proper praise in this area. Also, branching and merging in TFS2010 has been improved from prior versions, and it isn't clear what version you are referring to when you say "... from experience that branching and merging in TFS is not good." Disclaimer: I'm a moderate user of TFS2010.
Edit Dec-5-2011: To the OP, one thing that bothers me about TFS is that it insists on setting all your local files to "read-only" when you're not working on them. If you want to make a change, the flow is that you must "check-out" the file, which just clears the readonly attribute on the file so that TFS knows to keep an eye on it. That's an inconvenient workflow. The way I would prefer it to work is that is just automatically detects if I've made a change and doesn't worry/bother with the file attributes at all. That way, I can modify the file either in Visual Studio, or Notepad, or with whatever tool I please. The version control system should be as transparent as possible in this regard. There is a Windows Explorer Extension (TFS PowerTools) that allows you to work with your files in Windows Explorer, but that doesn't simplify the workflow very much.
Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.
public ActionResult ClientIdSearch(int cid)
{
var action = String.Format("Details/{0}", cid);
return RedirectToAction(action, "Accounts");
}
I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.
Old question, but apparently Google likes it so I thought I put an answer down here after some research about this problem.
If you create a figure from scratch you can give it a size option while creation:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(3, 6))
plt.plot(range(10)) #plot example
plt.show() #for control
fig.savefig('temp.png', dpi=fig.dpi)
figsize(width,height) adjusts the absolute dimension of your plot and helps to make sure both plots look the same.
As stated in another answer the dpi option affects the relative size of the text and width of the stroke on lines, etc. Using the option dpi=fig.dpi makes sure the relative size of those are the same both for show() and savefig().
Alternatively the figure size can be changed after creation with:
fig.set_size_inches(3, 6, forward=True)
forward allows to change the size on the fly.
If you have trouble with too large borders in the created image you can adjust those either with:
plt.tight_layout()
#or:
plt.tight_layout(pad=2)
or:
fig.savefig('temp.png', dpi=fig.dpi, bbox_inches='tight')
#or:
fig.savefig('temp.png', dpi=fig.dpi, bbox_inches='tight', pad_inches=0.5)
The first option just minimizes the layout and borders and the second option allows to manually adjust the borders a bit. These tips helped at least me to solve my problem of different savefig() and show() images.
SQLite is database engine, .sqlite
or .db
should be a database. If you don't need to program anything, you can use a GUI like sqlitebrowser or anything like that to view the database contents.
There is also spatialite, https://www.gaia-gis.it/fossil/spatialite_gui/index
I was able to resolve this by using my calling my high order component before exporting the class component. My problem was specifically using react-i18next
and its withTranslation method, but here was the solution:
export default withTranslation()(Header);
And then I was able to call the class Component as originally I had hoped:
<Header someProp={someValue} />
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
For adding item in Spinner, you can do one thing, try to create an adapter and then add/remove items into the adapter, then you can easily bind that adapter to spinner by using setAdapter()
method.
Here is an example:
spinner.setAdapter(adapter);
adapter.add(item1);
adapter.add(item2);
adapter.add(item3);
adapter.add(item4);
adapter.add(item5);
adapter.notifyDataSetChanged();
spinner.setAdapter(adapter);
you can try following
int index = 0;
WebElement baseTable = driver.findElement(By.className("table gradient myPage"));
List<WebElement> tableRows = baseTable.findElements(By.tagName("tr"));
tableRows.get(index).getText();
You can also iterate over tablerows to perform any function you want.
A way to solve this without needing to use a FileSystemResource that requires a file on disk, is to use a ByteArrayResource, that way you can send a byte array in your post (this code works with Spring 3.2.3):
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
final String filename="somefile.txt";
map.add("name", filename);
map.add("filename", filename);
ByteArrayResource contentsAsResource = new ByteArrayResource(content.getBytes("UTF-8")){
@Override
public String getFilename(){
return filename;
}
};
map.add("file", contentsAsResource);
String result = restTemplate.postForObject(urlForFacade, map, String.class);
I override the getFilename of the ByteArrayResource because if I don't I get a null pointer exception (apparently it depends on whether the java activation .jar is on the classpath, if it is, it will use the file name to try to determine the content type)
you can use the following from the device console: pm disable com.my.app.package
which will kill it. Then use pm enable com.my.app.package
so that you can launch it again.
You can use a simple "null function" for this, for example:
func Use(vals ...interface{}) {
for _, val := range vals {
_ = val
}
}
Which you can use like so:
package main
func main() {
a := "declared and not used"
b := "another declared and not used"
c := 123
Use(a, b, c)
}
There's also a package for this so you don't have to define the Use
function every time:
import (
"github.com/lunux2008/xulu"
)
func main() {
// [..]
xulu.Use(a, b, c)
}
This worked for me.
<select ng-model="somethingHere" ng-init="somethingHere='Cool'">
<option value="Cool">Something Cool</option>
<option value="Else">Something Else</option>
</select>
Use the .Clear
method.
Sheets("Test").Range("A1:C3").Clear
Modify the_script.php like this.
<script>
the_function() {
alert("You win");
}
</script>
Either use SciPy whl, download the appropriate one and run pip install <whl_file>
OR
Read through SciPy Windows issue and run one of the methods.
OR
Use Miniconda.
Additionally, install Visual C++ compiler for python2.7 in-case it asks for it.
best way I do this
db.execute(query) where db=db_class() #database class
mydata=[x for x in db.fetchall()]
df=pd.DataFrame(data=mydata)
Use mysql.createPool() with connection.destroy()
This way, new invocations use the established pool, but don't keep the function running. Even though you don't get the full benefit of pooling (each new connection uses a new connection instead of an existing one), it makes it so that a second invocation can establish a new connection without the previous one having to be closed first.
Regarding connection.end()
This can cause a subsequent invocation to throw an error. The invocation will still retry later and work, but with a delay.
Regarding mysql.createPool()
with connection.release()
The Lambda function will keep running until the scheduled timeout, as there is still an open connection.
const mysql = require('mysql');
const pool = mysql.createPool({
connectionLimit: 100,
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
});
exports.handler = (event) => {
pool.getConnection((error, connection) => {
if (error) throw error;
connection.query(`
INSERT INTO table_name (event) VALUES ('${event}')
`, function(error, results, fields) {
if (error) throw error;
connection.destroy();
});
});
};
De esta forma Jquery obtiene solo el elemento checked
$('input[name="radioInline"]:checked').val()
I think your javascript code should be placed between tag,there is need of document load
I know this thread is really old but the solution from @Ivan Bondarenko helped me in my situation.
I had the following in my pom.xml
.
<build>
...
<plugins>
<plugin>
<groupId>com.consol.citrus</groupId>
<artifactId>citrus-remote-maven-plugin</artifactId>
<version>${citrus.version}</version>
<executions>
<execution>
<id>generate-citrus-war</id>
<goals>
<goal>test-war</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
What I wanted, was to disable the execution of generate-citrus-war
for a specific profile and this was the solution:
<profile>
<id>it</id>
<build>
<plugins>
<plugin>
<groupId>com.consol.citrus</groupId>
<artifactId>citrus-remote-maven-plugin</artifactId>
<version>${citrus.version}</version>
<executions>
<!-- disable generating the war for this profile -->
<execution>
<id>generate-citrus-war</id>
<phase/>
</execution>
<!-- do something else -->
<execution>
...
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
The accepted answer provided a good starting point, but if you resize the frame, change the column widths, or even change the table data, the headers will get messed up in various ways. Every other example I've seen has similar issues, or imposes some serious restrictions on the table's layout.
I think I've finally got all these problems solved, though. It took a lot of CSS, but the final product is about as reliable and easy to use as a normal table.
Here's an example that has all the required features to replicate the table referenced by the OP: jsFiddle
The colors and borders would have to be changed to make it identical to the reference. Information on how to make those kinds of changes is provided in the CSS comments.
Here's the code:
/*the following html and body rule sets are required only if using a % width or height*/_x000D_
/*html {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}*/_x000D_
body {_x000D_
box-sizing: border-box;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0 20px 0 20px;_x000D_
text-align: center;_x000D_
background: white;_x000D_
}_x000D_
.scrollingtable {_x000D_
box-sizing: border-box;_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
overflow: hidden;_x000D_
width: auto; /*if you want a fixed width, set it here, else set to auto*/_x000D_
min-width: 0/*100%*/; /*if you want a % width, set it here, else set to 0*/_x000D_
height: 188px/*100%*/; /*set table height here; can be fixed value or %*/_x000D_
min-height: 0/*104px*/; /*if using % height, make this large enough to fit scrollbar arrows + caption + thead*/_x000D_
font-family: Verdana, Tahoma, sans-serif;_x000D_
font-size: 15px;_x000D_
line-height: 20px;_x000D_
padding: 20px 0 20px 0; /*need enough padding to make room for caption*/_x000D_
text-align: left;_x000D_
}_x000D_
.scrollingtable * {box-sizing: border-box;}_x000D_
.scrollingtable > div {_x000D_
position: relative;_x000D_
border-top: 1px solid black;_x000D_
height: 100%;_x000D_
padding-top: 20px; /*this determines column header height*/_x000D_
}_x000D_
.scrollingtable > div:before {_x000D_
top: 0;_x000D_
background: cornflowerblue; /*header row background color*/_x000D_
}_x000D_
.scrollingtable > div:before,_x000D_
.scrollingtable > div > div:after {_x000D_
content: "";_x000D_
position: absolute;_x000D_
z-index: -1;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
left: 0;_x000D_
}_x000D_
.scrollingtable > div > div {_x000D_
min-height: 0/*43px*/; /*if using % height, make this large enough to fit scrollbar arrows*/_x000D_
max-height: 100%;_x000D_
overflow: scroll/*auto*/; /*set to auto if using fixed or % width; else scroll*/_x000D_
overflow-x: hidden;_x000D_
border: 1px solid black; /*border around table body*/_x000D_
}_x000D_
.scrollingtable > div > div:after {background: white;} /*match page background color*/_x000D_
.scrollingtable > div > div > table {_x000D_
width: 100%;_x000D_
border-spacing: 0;_x000D_
margin-top: -20px; /*inverse of column header height*/_x000D_
/*margin-right: 17px;*/ /*uncomment if using % width*/_x000D_
}_x000D_
.scrollingtable > div > div > table > caption {_x000D_
position: absolute;_x000D_
top: -20px; /*inverse of caption height*/_x000D_
margin-top: -1px; /*inverse of border-width*/_x000D_
width: 100%;_x000D_
font-weight: bold;_x000D_
text-align: center;_x000D_
}_x000D_
.scrollingtable > div > div > table > * > tr > * {padding: 0;}_x000D_
.scrollingtable > div > div > table > thead {_x000D_
vertical-align: bottom;_x000D_
white-space: nowrap;_x000D_
text-align: center;_x000D_
}_x000D_
.scrollingtable > div > div > table > thead > tr > * > div {_x000D_
display: inline-block;_x000D_
padding: 0 6px 0 6px; /*header cell padding*/_x000D_
}_x000D_
.scrollingtable > div > div > table > thead > tr > :first-child:before {_x000D_
content: "";_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 20px; /*match column header height*/_x000D_
border-left: 1px solid black; /*leftmost header border*/_x000D_
}_x000D_
.scrollingtable > div > div > table > thead > tr > * > div[label]:before,_x000D_
.scrollingtable > div > div > table > thead > tr > * > div > div:first-child,_x000D_
.scrollingtable > div > div > table > thead > tr > * + :before {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
white-space: pre-wrap;_x000D_
color: white; /*header row font color*/_x000D_
}_x000D_
.scrollingtable > div > div > table > thead > tr > * > div[label]:before,_x000D_
.scrollingtable > div > div > table > thead > tr > * > div[label]:after {content: attr(label);}_x000D_
.scrollingtable > div > div > table > thead > tr > * + :before {_x000D_
content: "";_x000D_
display: block;_x000D_
min-height: 20px; /*match column header height*/_x000D_
padding-top: 1px;_x000D_
border-left: 1px solid black; /*borders between header cells*/_x000D_
}_x000D_
.scrollingtable .scrollbarhead {float: right;}_x000D_
.scrollingtable .scrollbarhead:before {_x000D_
position: absolute;_x000D_
width: 100px;_x000D_
top: -1px; /*inverse border-width*/_x000D_
background: white; /*match page background color*/_x000D_
}_x000D_
.scrollingtable > div > div > table > tbody > tr:after {_x000D_
content: "";_x000D_
display: table-cell;_x000D_
position: relative;_x000D_
padding: 0;_x000D_
border-top: 1px solid black;_x000D_
top: -1px; /*inverse of border width*/_x000D_
}_x000D_
.scrollingtable > div > div > table > tbody {vertical-align: top;}_x000D_
.scrollingtable > div > div > table > tbody > tr {background: white;}_x000D_
.scrollingtable > div > div > table > tbody > tr > * {_x000D_
border-bottom: 1px solid black;_x000D_
padding: 0 6px 0 6px;_x000D_
height: 20px; /*match column header height*/_x000D_
}_x000D_
.scrollingtable > div > div > table > tbody:last-of-type > tr:last-child > * {border-bottom: none;}_x000D_
.scrollingtable > div > div > table > tbody > tr:nth-child(even) {background: gainsboro;} /*alternate row color*/_x000D_
.scrollingtable > div > div > table > tbody > tr > * + * {border-left: 1px solid black;} /*borders between body cells*/
_x000D_
<div class="scrollingtable">_x000D_
<div>_x000D_
<div>_x000D_
<table>_x000D_
<caption>Top Caption</caption>_x000D_
<thead>_x000D_
<tr>_x000D_
<th><div label="Column 1"></div></th>_x000D_
<th><div label="Column 2"></div></th>_x000D_
<th><div label="Column 3"></div></th>_x000D_
<th>_x000D_
<!--more versatile way of doing column label; requires 2 identical copies of label-->_x000D_
<div><div>Column 4</div><div>Column 4</div></div>_x000D_
</th>_x000D_
<th class="scrollbarhead"/> <!--ALWAYS ADD THIS EXTRA CELL AT END OF HEADER ROW-->_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
<tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
Faux bottom caption_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<!--[if lte IE 9]><style>.scrollingtable > div > div > table {margin-right: 17px;}</style><![endif]-->
_x000D_
At some point I read a reasonably convincing argument on Perlmonks that testing the type of a scalar with ref
or reftype
is a bad idea. I don't recall who put the idea forward, or the link. Sorry.
The point was that in Perl there are many mechanisms that make it possible to make a given scalar act like just about anything you want. If you tie
a filehandle so that it acts like a hash, the testing with reftype
will tell you that you have a filehanle. It won't tell you that you need to use it like a hash.
So, the argument went, it is better to use duck typing to find out what a variable is.
Instead of:
sub foo {
my $var = shift;
my $type = reftype $var;
my $result;
if( $type eq 'HASH' ) {
$result = $var->{foo};
}
elsif( $type eq 'ARRAY' ) {
$result = $var->[3];
}
else {
$result = 'foo';
}
return $result;
}
You should do something like this:
sub foo {
my $var = shift;
my $type = reftype $var;
my $result;
eval {
$result = $var->{foo};
1; # guarantee a true result if code works.
}
or eval {
$result = $var->[3];
1;
}
or do {
$result = 'foo';
}
return $result;
}
For the most part I don't actually do this, but in some cases I have. I'm still making my mind up as to when this approach is appropriate. I thought I'd throw the concept out for further discussion. I'd love to see comments.
Update
I realized I should put forward my thoughts on this approach.
This method has the advantage of handling anything you throw at it.
It has the disadvantage of being cumbersome, and somewhat strange. Stumbling upon this in some code would make me issue a big fat 'WTF'.
I like the idea of testing whether a scalar acts like a hash-ref, rather that whether it is a hash ref.
I don't like this implementation.
for the sake of completeness, you could use:
(DT_STR,8, 1252) (YEAR(GetDate()) * 10000 + MONTH(GetDate()) * 100 + DAY(GetDate()))
for YYYYMMDD or
RIGHT("000000" + (DT_STR,8, 1252) (DAY(GetDate()) * 1000000 + MONTH(GetDate()) * 10000 + YEAR(GetDate())), 8)
for DDMMYYYY (without hyphens). If you want / need the date as integer (e.g. for _key-columns in DWHs), just remove the DT_STR / RIGTH function and do just the math.
use value
instead of query
(must specify index of node to return in the XQuery as well as passing the sql data type to return as the second parameter):
select
xt.Id
, x.m.value( '@id[1]', 'varchar(max)' ) MetricId
from
XmlTest xt
cross apply xt.XmlData.nodes( '/Sqm/Metrics/Metric' ) x(m)