The problem is
listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());
you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.
Try
private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {
DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
DefaultListModel lm1 = (DefaultListModel) listaRosa.getModel();
if(lm2 == null)
{
lm2 = new DefaultListModel();
listaTitolari.setModel(lm2);
}
lm2.addElement(listaTitolari.getSelectedValue());
lm1.removeElement(listaTitolari.getSelectedValue());
}
$users = Get-ADGroupMember -Identity 'Client Services' -Recursive ; $users.count
The above one-liner gives a clean count of recursive members found. Simple, easy, and one line.
To me, Fresco is the best among the other libraries.
Just setup Fresco and then simply set the imageURI like this:
draweeView.setImageURI(uri);
Check out this answer explaining some of Fresco benefits.
Only use Popen
kill method
process = subprocess.Popen(
task.getExecutable(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True
)
process.kill()
Floating will result in wrapping if space is not available.
You can use display:inline
and white-space:nowrap
to achieve this. Fiddle
<div id="container" style="white-space:nowrap">
<div id="image" style="display:inline;">
<img src="tree.png"/>
</div>
<div id="texts" style="display:inline; white-space:nowrap;">
A very long text(about 300 words)
</div>
</div>?
I've set up a JSFiddle to test several different solutions to this problem. Based on the [vague] criteria of
1) Maximum flexibility
2) No weird behavior
The accepted answer here of
img { display: block; }
which is recommended by a lot of people (such as in this excellent article), actually ranks fourth.
1st, 2nd, and 3rd place are all a toss-up between these three solutions:
1) The solution given by @Dave Kok and @Hasan Gursoy:
img { vertical-align: top; } /* or bottom */
pros:
cons:
2) Setting font-size: 0;
on the parent element:
.parent {
font-size: 0;
vertical-align: top;
}
.parent > * {
font-size: 16px;
vertical-align: top;
}
Since this one [kind of] requires vertical-align: top
on the img
, this is basically an extension of the 1st solution.
pros:
cons:
3) Setting line-height: 0
on the parent element:
.parent {
line-height: 0;
vertical-align: top;
}
.parent > * {
line-height: 1.15;
vertical-align: top;
}
Similar to the 2nd solution in that, to make it fully flexible, it basically becomes an extension of the 1st.
pros:
cons:
So there you have it. I hope this helps some poor soul.
Yes, it is deprecated. http://docs.jboss.org/hibernate/core/4.0/javadocs/org/hibernate/cfg/Configuration.html#buildSessionFactory() specifically tells you to use the other method you found instead (buildSessionFactory(ServiceRegistry serviceRegistry)
) - so use it.
The documentation is copied over from release to release, and likely just hasn't been updated yet (they don't rewrite the manual with every release) - so trust the Javadocs.
The specifics of this change can be viewed at:
Some additional references:
The var
keyword in C#'s main benefit is to enhance readability, not functionality. Technically, the var
keywords allows for some other unlocks (e.g. use of anonymous objects), but that seems to be outside the scope of this question. Every variable declared with the var
keyword has a type. For instance, you'll find that the following code outputs "String".
var myString = "";
Console.Write(myString.GetType().Name);
Furthermore, the code above is equivalent to:
String myString = "";
Console.Write(myString.GetType().Name);
The var
keyword is simply C#'s way of saying "I can figure out the type for myString
from the context, so don't worry about specifying the type."
var myVariable = (MyType)null
or MyType myVariable = null
should work because you are giving the C# compiler context to figure out what type myVariable
should will be.
For more information:
If you are using the FSFS repository format (the default), then you can copy the repository itself to make a backup. With the older BerkleyDB system, the repository is not platform independent and you would generally want to use svnadmin dump.
The svnbook documentation topic for backup recommends the svnadmin hotcopy
command, as it will take care of issues like files in use and such.
I just set this property and now Android OS is taking care of every thing.
android:adjustViewBounds="true"
Use this in your layout.xml where you have planted your ImageView :D
Depending on your .NET version you could also use HttpClientExtensions.PostAsJsonAsync
method.
https://msdn.microsoft.com/en-us/library/system.net.http.httpclientextensions.postasjsonasync.aspx
I just had to deal with it myself. After all I found this method most easy and useful. Just add
overflow-x: hidden;
To your outer parent. In my case it looks like this:
<body style="overflow-x: hidden;">
You have to use overflow-x
because if you use simply use overflow
you disable the vertical scrolling too, namely overflow-y
If the vertical scrolling is still disabled you can enable it explicitly with:
overflow-y: scroll;
I know its somewhat not a proper way because if everything was setup well one would not have to use this quick and dirty method.
window.location.href = "/";
This worked for me. If you have multiple folders/directories, you can use this:
window.location.href = "/folder_name/";
Try the below:
[[UITabBar appearance] setTintColor:[UIColor redColor]];
[[UITabBar appearance] setBarTintColor:[UIColor yellowColor]];
To tint the non active buttons, put the below code in your VC's viewDidLoad
:
UITabBarItem *tabBarItem = [yourTabBarController.tabBar.items objectAtIndex:0];
UIImage *unselectedImage = [UIImage imageNamed:@"icon-unselected"];
UIImage *selectedImage = [UIImage imageNamed:@"icon-selected"];
[tabBarItem setImage: [unselectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[tabBarItem setSelectedImage: selectedImage];
You need to do this for all the tabBarItems, and yes I know it is ugly and hope there will be cleaner way to do this.
Swift:
UITabBar.appearance().tintColor = UIColor.red
tabBarItem.image = UIImage(named: "unselected")?.withRenderingMode(.alwaysOriginal)
tabBarItem.selectedImage = UIImage(named: "selected")?.withRenderingMode(.alwaysOriginal)
This code will work. The answer from samplebias is almost correct, but you need a third change:
int addNodeBottom(int val, node *head){
//create new node
node *newNode = (node*)malloc(sizeof(node));
if(newNode == NULL){
fprintf(stderr, "Unable to allocate memory for new node\n");
exit(-1);
}
newNode->value = val;
newNode->next = NULL; // Change 1
//check for first insertion
if(head->next == NULL){
head->next = newNode;
printf("added at beginning\n");
}
else
{
//else loop through the list and find the last
//node, insert next to it
node *current = head;
while (true) { // Change 2
if(current->next == NULL)
{
current->next = newNode;
printf("added later\n");
break; // Change 3
}
current = current->next;
};
}
return 0;
}
Change 1: newNode->next
must be set to NULL
so we don't insert invalid pointers at the end of the list.
Change 2/3: The loop is changed to an endless loop that will be jumped out with break;
when we found the last element. Note how while(current->next != NULL)
contradicted if(current->next == NULL)
before.
EDIT: Regarding the while loop, this way it is much better:
node *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
printf("added later\n");
The solution from PSL will not work in Firefox. FF accepts event only as a formal parameter. So you have to find another way to identify the selected row. My solution is something like this:
...
$('#mySelector')
.on('show.bs.modal', function(e) {
var mid;
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
mid = $(e.relatedTarget).data('id');
else
mid = $(event.target).closest('tr').data('id');
...
As an additional note, you may also add markup language for pausing or waiting, I learned this from the iPhone iOS which allows numbers to be stored with extension numbers in the same line. A semi-colon establishes a wait, which will show as a next step upon calling the number. This helps to simplify the workflow of calling numbers with extensions in their board. You press the button shown on the bottom left of the iPhone screen when prompted, and the iPhone will dial it automatically.
<a href="tel:+50225079227;1">Call Now</a>
The pause is entered with a comma ",", allowing a short pause of time for each comma. Once the time has passed, the number after the comma will be dialed automatically
<a href="tel:+50225079227,1">Call Now, you will be automaticlaly transferred</a>
Pandas DataFrame columns are Pandas Series when you pull them out, which you can then call x.tolist()
on to turn them into a Python list. Alternatively you cast it with list(x)
.
import pandas as pd
data_dict = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(data_dict)
print(f"DataFrame:\n{df}\n")
print(f"column types:\n{df.dtypes}")
col_one_list = df['one'].tolist()
col_one_arr = df['one'].to_numpy()
print(f"\ncol_one_list:\n{col_one_list}\ntype:{type(col_one_list)}")
print(f"\ncol_one_arr:\n{col_one_arr}\ntype:{type(col_one_arr)}")
Output:
DataFrame:
one two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4
column types:
one float64
two int64
dtype: object
col_one_list:
[1.0, 2.0, 3.0, nan]
type:<class 'list'>
col_one_arr:
[ 1. 2. 3. nan]
type:<class 'numpy.ndarray'>
You can revert only one file to a specified revision.
First you can check on which commits the file was changed.
git log path/to/file.txt
Then you can checkout the file with the revision number.
git checkout 3cdc61015724f9965575ba954c8cd4232c8b42e4 /path/to/file.txt
After that you can commit and push it again.
For those not using arrow functions but something simpler ... I encountered this when adding parentheses after my signOut function ...
replace this <a onClick={props.signOut()}>Log Out</a>
with this <a onClick={props.signOut}>Log Out</a>
... !
.a
files are created with the ar
utility, and they are libraries. To use it with gcc
, collect all .a files
in a lib/
folder and then link with -L lib/
and -l<name of specific library>
.
Collection of all .a files into lib/
is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.
In your project folder, the vendor folder is missing so you got this error:
Warning: require(vendor/autoload.php): failed to open stream: No such file or directory in
When you download the project through git, the project is downloaded without the vendor folder
You need /vendor
because all your packages are there, including all the classes Laravel uses. The vendor directory contains your Composer dependencies.
The solution is simple, Just run this command:
composer update --no-scripts
composer update
composer update --no-scripts
It will Skips execution of scripts defined in composer.json
file.composer update
It will update your depencencies as they are specified in composer.json
file.With this command, you will re-create the vendor folder in your project and after that your project will start working normally.
I too had that same problem.. If we think logically little bit we can get the answer.. It worked for me very well.. I hope u will get it..
listviewdemo.xml
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="30dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
listviewcontent.xml
- note that TextView
- android:id="@+id/txtLstItem"
<LinearLayout
android:id="@+id/listviewcontentlayout"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="horizontal">
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="6dp" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/txtLstItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:shadowColor="@android:color/black"
android:shadowRadius="5"
android:textColor="@android:color/white" />
</LinearLayout>
<ImageView
android:id="@+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="6dp" />
</LinearLayout>
ListViewActivity.java
- Note that view.findViewById(R.id.txtLstItem)
-
as we setting the value to TextView
by setText()
method we getting text from TextView
by View
object returned by onItemClick
method. OnItemClick()
returns the current view.
TextView v=(TextView) view.findViewById(R.id.txtLstItem);
Toast.makeText(getApplicationContext(), "selected Item Name is "+v.getText(), Toast.LENGTH_LONG).show();**
Using this simple logic we can get other values like CheckBox
, RadioButton
, ImageView
etc.
ListView List = (ListView) findViewById(R.id.listview);
cursor = cr.query(CONTENT_URI,projection,null,null,null);
adapter = new ListViewCursorAdapter(ListViewActivity.this, R.layout.listviewcontent, cursor, from, to);
cursor.moveToFirst();
// Let activity manage the cursor
startManagingCursor(cursor);
List.setAdapter(adapter);
List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick (AdapterView < ? > adapter, View view,int position, long arg){
// TODO Auto-generated method stub
TextView v = (TextView) view.findViewById(R.id.txtLstItem);
Toast.makeText(getApplicationContext(), "selected Item Name is " + v.getText(), Toast.LENGTH_LONG).show();
}
}
);
You need to use background-image instead of backgroundImage. For example:
$(function() {
$('.home').click(function() {
$(this).css('background-image', 'url(images/tabs3.png)');
});
}):
You can use CSS's pseudo-class
to do that. A pseudo-class is used to define a special state of an element.
there is a ::focus
pseudo-class that is used to select the element that has focus.
So you can hook it in your CSS like this
Using class
.my-input::focus {
outline-color: green;
}
_x000D_
Using Id
#my-input::focus {
outline-color: red;
}
_x000D_
Directly selecting element
input::focus {
outline-color: blue;
}
_x000D_
Using attribute selector
input[type="text"]::focus {
outline-color: orange;
}
_x000D_
String s = "ABC[This is to extract]";
System.out.println(s);
int startIndex = s.indexOf('[');
System.out.println("indexOf([) = " + startIndex);
int endIndex = s.indexOf(']');
System.out.println("indexOf(]) = " + endIndex);
System.out.println(s.substring(startIndex + 1, endIndex));
Although this is strictly undefined behaviour, in practice it will work with pretty much any compiler. It is such a widely used paradigm that any self-respecting compiler will need to do "the right thing" in cases such as this. It's certainly to be preferred over type-punning, which may well generate broken code with some compilers.
An approach using extension methods:
class Program
{
static void Main(string[] args)
{
DateTime t = DateTime.Now;
DateTime p = t.PreviousMonthFirstDay();
Console.WriteLine( p.ToShortDateString() );
p = t.PreviousMonthLastDay();
Console.WriteLine( p.ToShortDateString() );
Console.ReadKey();
}
}
public static class Helpers
{
public static DateTime PreviousMonthFirstDay( this DateTime currentDate )
{
DateTime d = currentDate.PreviousMonthLastDay();
return new DateTime( d.Year, d.Month, 1 );
}
public static DateTime PreviousMonthLastDay( this DateTime currentDate )
{
return new DateTime( currentDate.Year, currentDate.Month, 1 ).AddDays( -1 );
}
}
See this link http://www.codeplex.com/fluentdatetime for some inspired DateTime extensions.
A general solution would be to use a linux box (could be in a virtual machine) configured as a transparent proxy to intercept the traffic, and then analyse it using wireshark or tcpdump or whatever you like. Perhaps MacOS can do this also, I haven't tried.
Or if you can run the app in the simulator, you can probably monitor the traffic on your own machine.
This works fine with me
List<string> myList = new List<string>();
myList.Add(string.Format("{0}|{1}","hello","1") ;
label:myList[0].split('|')[0]
val: myList[0].split('|')[1]
In Notepad++ v7.8.9 you can use the Tab
key to increase the indention level, and use Shift + Tab
to decrease the indentation level.
The difference is, re.match()
misleads anyone accustomed to Perl, grep, or sed regular expression matching, and re.search()
does not. :-)
More soberly, As John D. Cook remarks, re.match()
"behaves as if every pattern has ^ prepended." In other words, re.match('pattern')
equals re.search('^pattern')
. So it anchors a pattern's left side. But it also doesn't anchor a pattern's right side: that still requires a terminating $
.
Frankly given the above, I think re.match()
should be deprecated. I would be interested to know reasons it should be retained.
$python 2.7.8
from timeit import timeit
import numpy
timeit("list(0 for i in xrange(0, 100000))", number=1000)
> 8.173301935195923
timeit("[0 for i in xrange(0, 100000)]", number=1000)
> 4.881675958633423
timeit("[0] * 100000", number=1000)
> 0.6624710559844971
timeit('list(itertools.repeat(0, 100000))', 'import itertools', number=1000)
> 1.0820629596710205
You should use [0] * n
to generate a list with n
zeros.
See why [] is faster than list()
There is a gotcha though, both itertools.repeat
and [0] * n
will create lists whose elements refer to same id
. This is not a problem with immutable objects like integers or strings but if you try to create list of mutable objects like a list of lists ([[]] * n
) then all the elements will refer to the same object.
a = [[]] * 10
a[0].append(1)
a
> [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
[0] * n
will create the list immediately while repeat
can be used to create the list lazily when it is first accessed.
If you're dealing with really large amount of data and your problem doesn't need variable length of list or multiple data types within the list it is better to use numpy
arrays.
timeit('numpy.zeros(100000, numpy.int)', 'import numpy', number=1000)
> 0.057849884033203125
numpy
arrays will also consume less memory.
Cinn's answer is great, but there's one thing wrong with it.
The PreferredSize
widget will start immediately at the top of the screen, without accounting for the status bar, so some of its height will be shadowed by the status bar's height. This also accounts for the side notches.
The solution: Wrap the preferredSize
's child with a SafeArea
appBar: PreferredSize(
//Here is the preferred height.
preferredSize: Size.fromHeight(50.0),
child: SafeArea(
child: AppBar(
flexibleSpace: ...
),
),
),
If you don't wanna use the flexibleSpace property, then there's no need for all that, because the other properties of the AppBar
will account for the status bar automatically.
The solutions here just increase editor font size. You can run netbeans with parameter netbeans --fontsize 20
You can edit windows link like this for example. "C:\Program Files\NetBeans 8.0.2\bin\netbeans64.exe" --fontsize 20
I used the answer given by Carcione and modified it to use JSON.
function getUrlJsonSync(url){
var jqxhr = $.ajax({
type: "GET",
url: url,
dataType: 'json',
cache: false,
async: false
});
// 'async' has to be 'false' for this to work
var response = {valid: jqxhr.statusText, data: jqxhr.responseJSON};
return response;
}
function testGetUrlJsonSync()
{
var reply = getUrlJsonSync("myurl");
if (reply.valid == 'OK')
{
console.dir(reply.data);
}
else
{
alert('not valid');
}
}
I added the dataType of 'JSON' and changed the .responseText to responseJSON.
I also retrieved the status using the statusText property of the returned object. Note, that this is the status of the Ajax response, not whether the JSON is valid.
The back-end has to return the response in correct (well-formed) JSON, otherwise the returned object will be undefined.
There are two aspects to consider when answering the original question. One is telling Ajax to perform synchronously (by setting async: false) and the other is returning the response via the calling function's return statement, rather than into a callback function.
I also tried it with POST and it worked.
I changed the GET to POST and added data: postdata
function postUrlJsonSync(url, postdata){
var jqxhr = $.ajax({
type: "POST",
url: url,
data: postdata,
dataType: 'json',
cache: false,
async: false
});
// 'async' has to be 'false' for this to work
var response = {valid: jqxhr.statusText, data: jqxhr.responseJSON};
return response;
}
Note that the above code only works in the case where async is false. If you were to set async: true the returned object jqxhr would not be valid at the time the AJAX call returns, only later when the asynchronous call has finished, but that is much too late to set the response variable.
If you want to extract a single file use:
gunzip file.gz
It will extract the file and remove .gz file.
import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)
I found this answer quite simple and did the trick for what I needed: https://stackoverflow.com/a/12956348/652519
A summary from the link, use this query:
EXEC sp_fkeys 'TableName'
Quick and simple. I was able to locate all the foreign key tables, respective columns and foreign key names of 15 tables pretty quickly.
As @mdisibio noted below, here's a link to the documentation that details the different parameters that can be used: https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-fkeys-transact-sql
C array:
NSInteger array[6] = {1, 2, 3, 4, 5, 6};
Objective-C Array:
NSArray *array = @[@1, @2, @3, @4, @5, @6];
// numeric values must in that case be wrapped into NSNumbers
Swift Array:
var array = [1, 2, 3, 4, 5, 6]
This is correct too:
var array = Array(1...10)
NB: arrays are strongly typed in Swift; in that case, the compiler infers from the content that the array is an array of integers. You could use this explicit-type syntax, too:
var array: [Int] = [1, 2, 3, 4, 5, 6]
If you wanted an array of Doubles, you would use :
var array = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] // implicit type-inference
or:
var array: [Double] = [1, 2, 3, 4, 5, 6] // explicit type
grep -c ^processor /proc/cpuinfo
will count the number of lines starting with "processor" in /proc/cpuinfo
For systems with hyper-threading, you can use
grep ^cpu\\scores /proc/cpuinfo | uniq | awk '{print $4}'
which should return (for example) 8
(whereas the command above would return 16
)
All radio buttons have to have the same name:
<input type='radio' name='foo'>
Only 1 radio button of each group of buttons with the same name can be checked.
or
function isNumber(n){
return (parseFloat(n) == n);
}
i think it should be
select convert(varchar(10),StandardCost) +'S' from DimProduct where ProductKey = 212
or
select cast(StandardCost as varchar(10)) + 'S' from DimProduct where ProductKey = 212
I came by the same error on an old 2010 Exchange Server. A service(Exchange mailbox replication service) was giving out the above error and the migration process could not be continued. Searching through the internet, i came by this link which stated the below:
The Exchange GRE fails to open when installed for the first time or if any changes are made to the IIS server. It fails with snap-in error and when you try to open the snap-in page, the following content is displayed:
This collection already contains an address with scheme http. There can be at most one address per scheme in this collection. If your service is being hosted in IIS you can fix the problem by setting 'system.serviceModel/serviceHostingEnvironment/multipleSiteBindingsEnabled' to true or specifying 'system.serviceModel/serviceHostingEnvironment/baseAddressPrefixFilters'."
Cause: This error occurs because http port number 443 is already in use by another application and the IIS server is not configured to handle multiple binding to the same port.
Solution: Configure IIS server to handle multiple port bindings. Contact the vendor (Microsoft) to configure it.
Since these services were offered from an IIS Web Server, checking the Bindings on the Root Site fixed the problem. Someone had messed up the Site Bindings, defining rules that were overlapping themselves and messed up the services.
Fixing the correct Bindings resolved the problem, in my case, and i did not have to configure the Web.Config.
If you are not giving any modifier to your method then as default it will be Default modifier which has scope within package.
for more info you can refer http://wiki.answers.com/Q/What_is_default_access_specifier_in_Java
Just replace -H
with -h
. Check man grep
for more details on options
find . -name '*.bar' -exec grep -hn FOO {} \;
You will have to access db through the ip of host machine, or if you want to access it via localhost:1521, then run webserver like -
docker run --net=host --name oracle-wls wls-image:latest
I think you are casting in the wrong direction though... if the method returns a list of TestA
objects, then it really isn't safe to cast them to TestB
.
Basically you are asking the compiler to let you perform TestB
operations on a type TestA
that does not support them.
You would have to tune it according to your environment.
Sometimes it's more useful to increase the size of the backlog (acceptCount) instead of the maximum number of threads.
Say, instead of
<Connector ... maxThreads="500" acceptCount="50"
you use
<Connector ... maxThreads="300" acceptCount="150"
you can get much better performance in some cases, cause there would be less threads disputing the resources and the backlog queue would be consumed faster.
In any case, though, you have to do some benchmarks to really know what is best.
I just did a very quick and dirty test on repl.it using Node v7.4. For a single character, the standard for loop is quickest:
Some code:
// winner!
function charCount1(s, c) {
let count = 0;
c = c.charAt(0); // we save some time here
for(let i = 0; i < s.length; ++i) {
if(c === s.charAt(i)) {
++count;
}
}
return count;
}
function charCount2(s, c) {
return (s.match(new RegExp(c[0], 'g')) || []).length;
}
function charCount3(s, c) {
let count = 0;
for(ch of s) {
if(c === ch) {
++count;
}
}
return count;
}
function perfIt() {
const s = 'Hello, World!';
const c = 'o';
console.time('charCount1');
for(let i = 0; i < 10000; i++) {
charCount1(s, c);
}
console.timeEnd('charCount1');
console.time('charCount2');
for(let i = 0; i < 10000; i++) {
charCount2(s, c);
}
console.timeEnd('charCount2');
console.time('charCount3');
for(let i = 0; i < 10000; i++) {
charCount2(s, c);
}
console.timeEnd('charCount3');
}
Results from a few runs:
perfIt()
charCount1: 3.301ms
charCount2: 11.652ms
charCount3: 174.043ms
undefined
perfIt()
charCount1: 2.110ms
charCount2: 11.931ms
charCount3: 177.743ms
undefined
perfIt()
charCount1: 2.074ms
charCount2: 11.738ms
charCount3: 152.611ms
undefined
perfIt()
charCount1: 2.076ms
charCount2: 11.685ms
charCount3: 154.757ms
undefined
Update 2021-Feb-10: Fixed typo in repl.it demo
Update 2020-Oct-24: Still the case with Node.js 12 (play with it yourself here)
Installing the Chrome extension IE Tab did the job for me.
It has the ability to auto-detect URLs so whenever I browse to our SharePoint it emulates Internet Explorer. Finally I can open Office documents directly from Chrome.
You can install IETab for FireFox too.
If you want to return a boolean value, then you can use something like this (much faster than filter):
players.stream().anyMatch(player -> player.getName().contains(name));
If we have scripts in the same project but in different directory means, we can solve this problem by the following method.
In this situation utils.py
is in src/main/util/
import sys
sys.path.append('./')
import src.main.util.utils
#or
from src.main.util.utils import json_converter # json_converter is example method
Yes, you can run commands on the Ansible host. You can specify that all tasks in a play run on the Ansible host, or you can mark individual tasks to run on the Ansible host.
If you want to run an entire play on the Ansible host, then specify hosts: 127.0.0.1
and connection:local
in the play, for example:
- name: a play that runs entirely on the ansible host
hosts: 127.0.0.1
connection: local
tasks:
- name: check out a git repository
git: repo=git://foosball.example.org/path/to/repo.git dest=/local/path
See Local Playbooks in the Ansible documentation for more details.
If you just want to run a single task on your Ansible host, you can use local_action
to specify that a task should be run locally. For example:
- name: an example playbook
hosts: webservers
tasks:
- ...
- name: check out a git repository
local_action: git repo=git://foosball.example.org/path/to/repo.git dest=/local/path
See Delegation in the Ansible documentation for more details.
Edit: You can avoid having to type connection: local
in your play by adding this to your inventory:
localhost ansible_connection=local
(Here you'd use "localhost" instead of "127.0.0.1" to refer to the play).
Edit: In newer versions of ansible, you no longer need to add the above line to your inventory, ansible assumes it's already there.
$( this ).find( 'li.target' ).css("border", "3px double red");
or
$( this ).children( 'li.target' ).css("border", "3px double red");
Use children
for immediate descendants, or find
for deeper elements.
If you've exported the environment variable:
export demoPath=/usr/local/demo
you can simply refer to it by name in the makefile
(make
imports all the environment variables you have set):
DEMOPATH = ${demoPath} # Or $(demoPath) if you prefer.
If you've not exported the environment variable, it is not accessible until you do export it, or unless you pass it explicitly on the command line:
make DEMOPATH="${demoPath}" …
If you are using a C shell derivative, substitute setenv demoPath /usr/local/demo
for the export
command.
Select constraint_name,constraint_type from user_constraints where table_name** **= ‘TABLE_NAME’ ;
(This will list the primary key and then)
Select column_name,position from user_cons_cloumns where constraint_name=’PK_XYZ’;
(This will give you the column, here PK_XYZ is the primay key name)
1800 INFORMATION is more or less correct, but there are a few issues I wanted to correct.
boost::shared_mutex _access;
void reader()
{
boost::shared_lock< boost::shared_mutex > lock(_access);
// do work here, without anyone having exclusive access
}
void conditional_writer()
{
boost::upgrade_lock< boost::shared_mutex > lock(_access);
// do work here, without anyone having exclusive access
if (something) {
boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock);
// do work here, but now you have exclusive access
}
// do more work here, without anyone having exclusive access
}
void unconditional_writer()
{
boost::unique_lock< boost::shared_mutex > lock(_access);
// do work here, with exclusive access
}
Also Note, unlike a shared_lock, only a single thread can acquire an upgrade_lock at one time, even when it isn't upgraded (which I thought was awkward when I ran into it). So, if all your readers are conditional writers, you need to find another solution.
Yes we can use. CSS reset as a {outline:none}
and also
a:focus, a:active {outline:none}
for the Best Practice in Resetting CSS, The Best Solution is using common :focus{outline:none}
If you still have Best Option please Share
If you are really about to work on multi-gigabyte text files then do not use PowerShell. Even if you find a way to read it faster processing of huge amount of lines will be slow in PowerShell anyway and you cannot avoid this. Even simple loops are expensive, say for 10 million iterations (quite real in your case) we have:
# "empty" loop: takes 10 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) {} }
# "simple" job, just output: takes 20 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i } }
# "more real job": 107 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i.ToString() -match '1' } }
UPDATE: If you are still not scared then try to use the .NET reader:
$reader = [System.IO.File]::OpenText("my.log")
try {
for() {
$line = $reader.ReadLine()
if ($line -eq $null) { break }
# process the line
$line
}
}
finally {
$reader.Close()
}
UPDATE 2
There are comments about possibly better / shorter code. There is nothing wrong with the original code with for
and it is not pseudo-code. But the shorter (shortest?) variant of the reading loop is
$reader = [System.IO.File]::OpenText("my.log")
while($null -ne ($line = $reader.ReadLine())) {
$line
}
I've just discovered one more subtle difference between these two methods.
If module foo
uses a following import:
from itertools import count
Then module bar
can by mistake use count
as though it was defined in foo
, not in itertools
:
import foo
foo.count()
If foo
uses:
import itertools
the mistake is still possible, but less likely to be made. bar
needs to:
import foo
foo.itertools.count()
This caused some troubles to me. I had a module that by mistake imported an exception from a module that did not define it, only imported it from other module (using from module import SomeException
). When the import was no longer needed and removed, the offending module was broken.
Works ok for me:
$('a.popup-ajax').popover({
"html": true,
"content": function(){
var div_id = "tmp-id-" + $.now();
return details_in_popup($(this).attr('href'), div_id);
}
});
function details_in_popup(link, div_id){
$.ajax({
url: link,
success: function(response){
$('#'+div_id).html(response);
}
});
return '<div id="'+ div_id +'">Loading...</div>';
}
Just use
unicode_to_list = list(EmployeeList)
The appref-ms file does not point to the exe. When you hit that shortcut, it invokes the deployment manifest at the deployment provider url and checks for updates. It checks the application manifest (yourapp.exe.manifest) to see what files to download, and this file contains the definition of the entry point (i.e. the exe).
In python:
>>> 1.0 / 10
0.10000000000000001
Explain how some fractions cannot be represented precisely in binary. Just like some fractions (like 1/3) cannot be represented precisely in base 10.
You may try this (using jQuery
)
$(function(){_x000D_
$('#MainPopupIframe').load(function(){_x000D_
$(this).show();_x000D_
console.log('iframe loaded successfully')_x000D_
});_x000D_
_x000D_
$('#click').on('click', function(){_x000D_
$('#MainPopupIframe').attr('src', 'https://heera.it'); _x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
Update: Using plain javascript
window.onload=function(){_x000D_
var ifr=document.getElementById('MainPopupIframe');_x000D_
ifr.onload=function(){_x000D_
this.style.display='block';_x000D_
console.log('laod the iframe')_x000D_
};_x000D_
var btn=document.getElementById('click'); _x000D_
btn.onclick=function(){_x000D_
ifr.src='https://heera.it'; _x000D_
};_x000D_
};
_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
Update: Also you can try this (dynamic iframe)
$(function(){_x000D_
$('#click').on('click', function(){_x000D_
var ifr=$('<iframe/>', {_x000D_
id:'MainPopupIframe',_x000D_
src:'https://heera.it',_x000D_
style:'display:none;width:320px;height:400px',_x000D_
load:function(){_x000D_
$(this).show();_x000D_
alert('iframe loaded !');_x000D_
}_x000D_
});_x000D_
$('body').append(ifr); _x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button><br />
_x000D_
Know your host ip address on your lan Open cmd and type ipconfig and the if xampp the default listen port would be 80 Then for instance if 10.0.0.5 is your host ip address Type 10.0.0.5:80 from your mobile's web browser Make sure that both are connected to the same LAN However the default port that webaddress tries is 80.
Typically you model the enum itself as a class with the enum
stereotype
I've never had a problem with doing it like this:
<form>
<div>
<input type="checkbox" id="cb" /> <label for="cb">Label text</label>
</div>
</form>
JObject.ContainsKey(string propertyName)
has been made as public method in 11.0.1 release
Documentation - https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_ContainsKey.htm
There isn't any graph api for this, you need to use facebook xmpp chat api to send the message, good news is: I have made a php class which is too easy to use,call a function and message will be sent, its open source, check it out: facebook message api php the description says its a closed source but the it was made open source later, see the first comment, you can clone from github. It's a open source now.
Try this
var s = {name: "raul", age: "22", gender: "Male"}
var keys = [];
for(var k in s) keys.push(k);
Here keys array will return your keys ["name", "age", "gender"]
API stands for Application Programming Interface, i.e. API is the way for an application to interact with certain system/application/library/etc.
For example, there are API's for OS (WinAPI), API's for other applications (like databases) and for specific libraries (for example, image processing), etc.
APIs are usually developed in a form consumable by a client application. For C/C++ applications, it a set header files and dynamic/static libraries. For Java - set of jars. And so on.
Yes, it is. You can write :
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
or you can get values from another join of the select ...
String.Format("{0:n}", 1234); // Output: 1,234.00
String.Format("{0:n0}", 9876); // No digits after the decimal point. Output: 9,876
If you are using bash 4 you can use the following approach:
x="HELLO"
echo $x # HELLO
y=${x,,}
echo $y # hello
z=${y^^}
echo $z # HELLO
Use only one ,
or ^
to make the first letter lowercase
or uppercase
.
For me rollbackFor was not enough, so I had to put this and it works as expected:
@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
I hope it helps :-)
Some of the benefits of PreparedStatement over Statement are:
Read more about SQL injection issue at http://www.journaldev.com/2489/jdbc-statement-vs-preparedstatement-sql-injection-example
If you program in Lua, you are out of luck here. Lua is THE one programming language that just happens to be notoriously infamous because its authors never implemented "the" split function in the standard library, and instead wrote 16 screenfulls of explanations and lame excuses as to why they didn't and wouldn't, interspersed with numerous half-working examples that are virtually guaranteed to work for almost everyone but break in your corner case. This is just Lua state of the art, and everyone who programs in Lua simply ends up clenching their teeth and iterating over characters. There are lots of solutions in existence that are sometimes better, but exactly zero solutions that are reliably better.
Best solution for this problem is use enumerate in-build python function.
enumerate return tuple
first value is index
second value is element of array at that index
In [1]: ints = [8, 23, 45, 12, 78]
In [2]: for idx, val in enumerate(ints):
...: print(idx, val)
...:
(0, 8)
(1, 23)
(2, 45)
(3, 12)
(4, 78)
The split function separates each part of text with the separator you provide, and you provided "|". So the result would be an array containing "Shimla", "1" and "http://vinspro.org/travel/ind/". You could manipulate that to get the third one, "http://vinspro.org/travel/ind/", and here's an example:
var str="Shimla|1|http://vinspro.org/travel/ind/";
var n = str.split('|');
alert(n[2]);
As mentioned in other answers, this code would differ depending on if it was a string ($(str).split('|');), a textbox input ($(str).val().split('|');), or a DOM element ($(str).text().split('|');).
You could also just use plain JavaScript to get all the stuff after 9 characters, which would be "http://vinspro.org/travel/ind/". Here's an example:
var str="Shimla|1|http://vinspro.org/travel/ind/";
var n=str.substr(9);
alert(n);
In Bootstrap 4:
class="font-weight-bold"
Or:
<strong>text</strong>
You could use iterator to do that:
For keys:
for (Iterator <tab> itr= hash.keySet().iterator(); itr.hasNext();) {
// use itr.next() to get the key value
}
You can use iterator similarly with values.
The character is a backslash \
From the bash manual:
The backslash character ‘\’ may be used to remove any special meaning for the next character read and for line continuation.
When I'm working with csv
files, I often use the pandas library. It makes things like this very easy. For example:
import pandas as pd
a = pd.read_csv("filea.csv")
b = pd.read_csv("fileb.csv")
b = b.dropna(axis=1)
merged = a.merge(b, on='title')
merged.to_csv("output.csv", index=False)
Some explanation follows. First, we read in the csv files:
>>> a = pd.read_csv("filea.csv")
>>> b = pd.read_csv("fileb.csv")
>>> a
title stage jan feb
0 darn 3.001 0.421 0.532
1 ok 2.829 1.036 0.751
2 three 1.115 1.146 2.921
>>> b
title mar apr may jun Unnamed: 5
0 darn 0.631 1.321 0.951 1.7510 NaN
1 ok 1.001 0.247 2.456 0.3216 NaN
2 three 0.285 1.283 0.924 956.0000 NaN
and we see there's an extra column of data (note that the first line of fileb.csv
-- title,mar,apr,may,jun,
-- has an extra comma at the end). We can get rid of that easily enough:
>>> b = b.dropna(axis=1)
>>> b
title mar apr may jun
0 darn 0.631 1.321 0.951 1.7510
1 ok 1.001 0.247 2.456 0.3216
2 three 0.285 1.283 0.924 956.0000
Now we can merge a
and b
on the title column:
>>> merged = a.merge(b, on='title')
>>> merged
title stage jan feb mar apr may jun
0 darn 3.001 0.421 0.532 0.631 1.321 0.951 1.7510
1 ok 2.829 1.036 0.751 1.001 0.247 2.456 0.3216
2 three 1.115 1.146 2.921 0.285 1.283 0.924 956.0000
and finally write this out:
>>> merged.to_csv("output.csv", index=False)
producing:
title,stage,jan,feb,mar,apr,may,jun
darn,3.001,0.421,0.532,0.631,1.321,0.951,1.751
ok,2.829,1.036,0.751,1.001,0.247,2.456,0.3216
three,1.115,1.146,2.921,0.285,1.283,0.924,956.0
TO get pretty timing differences, then
// d1, d2 are dates
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
You can use /* tslint:disable-next-line */
to locally disable tslint. However, as this is a compiler error disabling tslint might not help.
You can always temporarily cast $
to any
:
delete ($ as any).summernote.options.keyMap.pc.TAB
which will allow you to access whatever properties you want.
Edit: As of Typescript 2.6, you can now bypass a compiler error/warning for a specific line:
if (false) {
// @ts-ignore: Unreachable code error
console.log("hello");
}
Note that the official docs "recommend you use [this] very sparingly". It is almost always preferable to cast to any
instead as that better expresses intent.
System.Net.HttpWebRequest adds the header 'HTTP header "Expect: 100-Continue"' to every request unless you explicitly ask it not to by setting this static property to false:
System.Net.ServicePointManager.Expect100Continue = false;
Some servers choke on that header and send back the 417 error you're seeing.
Give that a shot.
Very annoying, no cookie file exmpale on the official website https://ec.haxx.se/http/http-cookies.
Finnaly, I find it does not work, if your file content is just copyied like this
foo1=bar;foo2=bar2
I gusess the format must looks the style said by @Agustí Sánchez . You can test it by -c to create a cookie file on a website.
So try this way, it works
curl -H "Cookie:`cat ./my.cookie`" http://xxxx.com
You can just copy the cookie from chrome console network tab.
For celery 3.0+:
$ celery purge
To purge a specific queue:
$ celery -Q queue_name purge
You just need to wrap object in ()
var arr = [{_x000D_
id: 1,_x000D_
name: 'bill'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
Like this?
[bool]($myObject.PSobject.Properties.name -match "myPropertyNameToTest")
Since I don't find a simple answer just adding more this will be JSP page. save this content to a jsp file once you run you can see the values of the selected displayed.
Update: save the file as test.jsp and run it on any web/app server
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<%@ page import="java.lang.*" %>
<%@ page import="java.io.*" %>
<% String[] a = request.getParameterValues("multiple");
if(a!=null)
{
for(int i=0;i<a.length;i++){
//out.println(Integer.parseInt(a[i])); //If integer
out.println(a[i]);
}}
%>
<html>
<body>
<form action="test.jsp" method="get">
<select name="multiple" multiple="multiple"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>
<input type="submit">
</form>
</body>
</html>
Just like normal background-color: #f0f
You just need a way to target it, eg: <option id="myPinkOption">blah</option>
Note: I know this is a hack, but it was useful for Angular 1.2 and earlier that didn't provide a simple mechanism.
The validation kicks in on the change event, so some things like changing the values programmatically won't trigger it. But triggering the change event will trigger the validation. For example, with jQuery:
$('#formField1, #formField2').trigger('change');
This question is a few years old, and there are some good suggestions for workarounds, but I didn't really notice any answers that address the core of the original question head-on. So:
Providing a "universal" method for viewing source in a feature phone browser (or even arbitrary third-party smartphone browser) is impossible because "view source" — via any method — is a feature implemented in the browser. So how it's accessed, or even if it can be accessed, is up to the developers of the browser. I'm sure there are plenty of browsers that intentionally prevent the user from viewing page source, and if so then you're out of luck, except maybe for workarounds like the ones offered here.
Workarounds such as "view source" apps external to the browser, while useful in some cases, are at best an imperfect partial solution to the original request. It's never certain that any such app will display the source of the page in the same form as it's loaded by the phone's browser.
Modern web content changes itself in all manner of ways through browser detection, session management, etc. so that the source loaded by any external app can never be relied on to represent the source as loaded by a different app. If you're going to use an external app to load a page because you want to see the source, you might as well just use Chrome (or, on an iOS device, Safari) instead.
Rather than editing batch files (which you may have to do for other Ruby gems, e.g. Bundler), it's probably better to do this once, and do it properly.
On Windows, behind my corporate proxy, all I had to do was add the HTTP_PROXY
environment variable to my system.
HTTP_PROXY
", and set the Value to your proxy serverDepending on your authentication requirements, the HTTP_PROXY
value can be as simple as:
http://proxy-server-name
Or more complex as others have pointed out
http://username:password@proxy-server-name:port-number
window.location.replace('http://sidanmor.com');
It's better than using window.location.href = 'http://sidanmor.com';
Using replace()
is better because it does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.
If you want to simulate someone clicking on a link, use
window.location.href
If you want to simulate an HTTP redirect, use
window.location.replace
For example:
// similar behavior as an HTTP redirect
window.location.replace("http://sidanmor.com");
// similar behavior as clicking on a link
window.location.href = "http://sidanmor.com";
Taken from here: How to redirect to another page in jQuery?
Presuming you're talking about dynamic runtime loading of DLLs, you're looking for LoadLibrary and GetProAddress. There's an example on MSDN.
You can float your column divs using float: left; and give them widths.
And to make sure none of your other content gets messed up, you can wrap the floated divs within a parent div and give it some clear float styling.
Hope this helps.
Another possible cause of this error is that you have forgotten to add the libraries that are already in the /WEBINF/lib
folder to the build path (e.g. when importing a .war
-file and not checking the libraries when asked in the wizard). Just happened to me.
VSCode is a code editor, not a full IDE. Think of VSCode as a notepad on steroids with IntelliSense code completion, richer semantic code understanding of multiple languages, code refactoring, including navigation, keyboard support with customizable bindings, syntax highlighting, bracket matching, auto indentation, and snippets.
It's not meant to replace Visual Studio, but making "Visual Studio" part of the name in VSCode will of course confuse some people at first.
for phpMyAdmin-4.8.5-all-languages copy content from config.sample.inc.php into new file config.inc.php and instead of
/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'cookie';
/* Server parameters */
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['AllowNoPassword'] = false;
put the folowing content:
/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'config';
/* Server parameters */
$cfg['Servers'][$i]['host'] = 'localhost}';
$cfg['Servers'][$i]['user'] = '{your root mysql username';
$cfg['Servers'][$i]['password'] = '{your pasword for root user to login into mysql}';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['AllowNoPassword'] = true;
the rest remain commented an un-changed...
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
You should be setting the src using this:
document["pic1"].src = searchPic.src;
or
$("#pic1").attr("src", searchPic.src);
The problem with didMoveToParentViewController
it's that it gets called once the parent view is fully visible again so if you need to perform some tasks before that, it won't work.
And it doesn't work with the driven animation gesture.
Using willMoveToParentViewController
works better.
Objective-c
- (void)willMoveToParentViewController:(UIViewController *)parent{
if (parent == NULL) {
// ...
}
}
Swift
override func willMoveToParentViewController(parent: UIViewController?) {
if parent == nil {
// ...
}
}
I am assuming that we are dealing with a JFrame? The visible portion in the content pane - you have to use jframe.getContentPane().setBackground(...);
Based on John's answer, I changed the GET request to a POST request. It works, without having to change the server configuration. So I went looking how to implement this. The following pages were helpful:
jQuery Ajax POST example with PHP (Note the sanitize posted data remark) and
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
Basically, the difference is that the GET request has the url and parameters in one string and then sends null:
http.open("GET", url+"?"+params, true);
http.send(null);
whereas the POST request sends the url and the parameters in separate commands:
http.open("POST", url, true);
http.send(params);
Here is a working example:
ajaxPOST.html:
<html>
<head>
<script type="text/javascript">
function ajaxPOSTTest() {
try {
// Opera 8.0+, Firefox, Safari
ajaxPOSTTestRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxPOSTTestRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxPOSTTestRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxPOSTTestRequest.onreadystatechange = ajaxCalled_POSTTest;
var url = "ajaxPOST.php";
var params = "lorem=ipsum&name=binny";
ajaxPOSTTestRequest.open("POST", url, true);
ajaxPOSTTestRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxPOSTTestRequest.send(params);
}
//Create a function that will receive data sent from the server
function ajaxCalled_POSTTest() {
if (ajaxPOSTTestRequest.readyState == 4) {
document.getElementById("output").innerHTML = ajaxPOSTTestRequest.responseText;
}
}
</script>
</head>
<body>
<button onclick="ajaxPOSTTest()">ajax POST Test</button>
<div id="output"></div>
</body>
</html>
ajaxPOST.php:
<?php
$lorem=$_POST['lorem'];
print $lorem.'<br>';
?>
I just sent over 12,000 characters without any problems.
Due to PermGen removal some options were removed (like -XX:MaxPermSize
), but options -Xms
and -Xmx
work in Java 8. It's possible that under Java 8 your application simply needs somewhat more memory. Try to increase -Xmx
value. Alternatively you can try to switch to G1 garbage collector using -XX:+UseG1GC
.
Note that if you use any option which was removed in Java 8, you will see a warning upon application start:
$ java -XX:MaxPermSize=128M -version
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=128M; support was removed in 8.0
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b18)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)
To just print 1 or 0 based on the boolean value I just used:
printf("%d\n", !!(42));
Especially useful with Flags:
#define MY_FLAG (1 << 4)
int flags = MY_FLAG;
printf("%d\n", !!(flags & MY_FLAG));
As Jakob S suggested in his answer, Kernel#Float can be used to validate numericality of the string, only thing that I can add is one-liner version of that, without using rescue
block to control flow (which is considered as a bad practice sometimes)
Float(my_string, exception: false).present?
The Database that we are using should be mentioned under search_path in Postgres SQL Configuration file. This can be done by editing Postgressql configuration file by setting search_path along with database name for example: TESTDB.
It worked for me after making the above change.
Try this test:
any(substring in string for substring in substring_list)
It will return True
if any of the substrings in substring_list
is contained in string
.
Note that there is a Python analogue of Marc Gravell's answer in the linked question:
from itertools import imap
any(imap(string.__contains__, substring_list))
In Python 3, you can use map
directly instead:
any(map(string.__contains__, substring_list))
Probably the above version using a generator expression is more clear though.
I'm dealing with a similar problem currently.
There are two main options that occur to me immediately: (1) user-string checking, or (2) maintaining separate mobile pages using a different URL and having users choose what's better for them.
<link rel="mobile.css" />
instead of the normal style.User strings have identifying information about browser, renderer, operating system, etc. It would be up to you to decide what devices are "touch" versus non-touch. You may be able to find this information available somewhere and map it into your system.
A. If you're allowed to ignore old browsers, you just have to add a single rule to the normal, non-mobile css, namely: EDIT: Erk. After doing some experimentation, I discovered the below rule also disables the ability to follow links in webkit-browsers in addition to just causing aesthetic effects to be disabled - see http://jsfiddle.net/3nkcdeao/
As such, you'll have to be a bit more selective as to how you modify rules for the mobile case than what I show here, but it may be a helpful starting point:
* {
pointer-events: none !important; /* only use !important if you have to */
}
As a sidenote, disabling pointer-events on a parent and then explicitly enabling them on a child currently causes any hover-effects on the parent to become active again if a child-element enters :hover
.
See http://jsfiddle.net/38Lookhp/5/
B. If you're supporting legacy web-renderers, you'll have to do a bit more work along the lines of removing any rules which set special styles during :hover
. To save everyone time, you might just want to build an automated copying + seding command which you run on your standard style sheets to create the mobile versions. That would allow you to just write/update the standard code and scrub away any style-rules which use :hover
for the mobile version of your pages.
Again here, you may be able to just add an extra rule or two to the stylesheets or be forced to do something slightly more complicated using sed or a similar utility. It would probably be easiest to apply :not to your styling rules like div:not(.disruptive):hover {...
wherein you would add class="disruptive"
to elements doing annoying things for mobile users using js or the server language, instead of munging the CSS.
(II) You can actually combine the first two and (if you suspect a user has wandered to the wrong version of a page) you can suggest that they switch into/out of the mobile-type display, or simply have a link somewhere which allows users to flop back and forth. As already-stated, @media queries might also be something to look use in determining what's being used to visit.
(III) If you're up for a jQuery solution once you know what devices are "touch" and which aren't, you might find CSS hover not being ignored on touch-screen devices helpful.
The following should suffice:
[^ ]
If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):
[^\s]
or
\S # Note this is a CAPITAL 'S'!
I had wrong package names:
main.java.hello
and main.test.hello
rather than com.blabla.hello
.
src/main/java
and created another src-folder src/test/java
.src/main/java
to com.blabla.hello
src/test/java
.Typical scenario,
scp -r -P port username@ip:/path-to-folder .
explained with an sample,
scp -r -P 27000 [email protected]:/tmp/hotel_dump .
where,
port = 27000
username = "abc" , remote server username
path-to-folder = tmp/hotel_dump
. = current local directory
as mentioned in the responses above, it could be related to AWS security groups, and other things. but if you created a user and gave it remote access '%' and still getting this error, check your mysql config file, on debian, you can find it here: /etc/mysql/my.cnf and find the line:
bind-address = 127.0.0.1
and change it to:
bind-address = 0.0.0.0
and restart mysql.
on debian/ubuntu:
/etc/init.d/mysql restart
I hope this works for you.
Suppose there's a file test.txt
in Root Folder, and want to move it to \TxtFolder
,
You can try
move %~dp0\test.txt %~dp0\TxtFolder
.
reference answer: relative path in BAT script
Storing a list of object instances is very simple
class MyClass(object):
def __init__(self, number):
self.number = number
my_objects = []
for i in range(100):
my_objects.append(MyClass(i))
# later
for obj in my_objects:
print obj.number
To directly save the file in HDFS, use the below command:
hive> insert overwrite directory '/user/cloudera/Sample' row format delimited fields terminated by '\t' stored as textfile select * from table where id >100;
This will put the contents in the folder /user/cloudera/Sample in HDFS.
Dirk Eddelbuettel's answer is the best; here I just note that you can get away with not pre-specifying the dataframe dimensions or data types, which is sometimes useful if you have multiple data types and lots of columns:
row1<-list("a",1,FALSE) #use 'list', not 'c' or 'cbind'!
row2<-list("b",2,TRUE)
df<-data.frame(row1,stringsAsFactors = F) #first row
df<-rbind(df,row2) #now this works as you'd expect.
Postgres hasn't implemented an equivalent to INSERT OR REPLACE
. From the ON CONFLICT
docs (emphasis mine):
It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.
Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE
applies more generally, since it lets you set new values based on preexisting data. For example:
INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;
How to reproduce this error in PHP:
Create an empty array and ask for the value given a key like this:
php> $foobar = array();
php> echo gettype($foobar);
array
php> echo $foobar[0];
PHP Notice: Undefined offset: 0 in
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) :
eval()'d code on line 1
What happened?
You asked an array to give you the value given a key that it does not contain. It will give you the value NULL then put the above error in the errorlog.
It looked for your key in the array, and found undefined
.
How to make the error not happen?
Ask if the key exists first before you go asking for its value.
php> echo array_key_exists(0, $foobar) == false;
1
If the key exists, then get the value, if it doesn't exist, no need to query for its value.
In my case, the others answers was not enough...
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
<application
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
</application>
Tested on Android 4.0.3 API 15.
class Program
{
public static EventHandler AsyncHandler;
static void Main(string[] args)
{
AsyncHandler+= async (sender, eventArgs) => { await AsyncMain(); };
AsyncHandler?.Invoke(null, null);
}
private async Task AsyncMain()
{
//Your Async Code
}
}
apt list [packagename]
seems to be the simplest way to do it outside of dpkg and older apt-* tools
Try This:)
before:-
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>TestServlet</servlet-class>
</servlet>
After:-
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>operation.TestServlet</servlet-class>
</servlet>
How do I have to do in Python for calling an static method from another static method of the same class?
class Test() :
@staticmethod
def static_method_to_call()
pass
@staticmethod
def another_static_method() :
Test.static_method_to_call()
@classmethod
def another_class_method(cls) :
cls.static_method_to_call()
I found this post very useful so here is the solution in PHP. I've been using this successfully and just wanted to save another dev some time.
/**
* Get a center latitude,longitude from an array of like geopoints
*
* @param array data 2 dimensional array of latitudes and longitudes
* For Example:
* $data = array
* (
* 0 = > array(45.849382, 76.322333),
* 1 = > array(45.843543, 75.324143),
* 2 = > array(45.765744, 76.543223),
* 3 = > array(45.784234, 74.542335)
* );
*/
function GetCenterFromDegrees($data)
{
if (!is_array($data)) return FALSE;
$num_coords = count($data);
$X = 0.0;
$Y = 0.0;
$Z = 0.0;
foreach ($data as $coord)
{
$lat = $coord[0] * pi() / 180;
$lon = $coord[1] * pi() / 180;
$a = cos($lat) * cos($lon);
$b = cos($lat) * sin($lon);
$c = sin($lat);
$X += $a;
$Y += $b;
$Z += $c;
}
$X /= $num_coords;
$Y /= $num_coords;
$Z /= $num_coords;
$lon = atan2($Y, $X);
$hyp = sqrt($X * $X + $Y * $Y);
$lat = atan2($Z, $hyp);
return array($lat * 180 / pi(), $lon * 180 / pi());
}
(2>/dev/null crontab -l ; echo "0 3 * * * /usr/local/bin/certbot-auto renew") | crontab -
cat <(crontab -l 2>/dev/null) <(echo "0 3 * * * /usr/local/bin/certbot-auto renew") | crontab -
#write out current crontab
crontab -l > mycron 2>/dev/null
#echo new cron into cron file
echo "0 3 * * * /usr/local/bin/certbot-auto renew" >> mycron
#install new cron file
crontab mycron
rm mycron
If you want to disappear keyboard when writing on alert box textfileds
[[alertController.textFields objectAtIndex:1] resignFirstResponder];
I've come up with a solution which is similar with RacZo's in the fact that I've also created a subclass of TextView
which handles making the text upper-case.
The difference is that instead of overriding one of the setText()
methods, I've used a similar approach to what the TextView
actually does on API 14+ (which is in my point of view a cleaner solution).
If you look into the source, you'll see the implementation of setAllCaps()
:
public void setAllCaps(boolean allCaps) {
if (allCaps) {
setTransformationMethod(new AllCapsTransformationMethod(getContext()));
} else {
setTransformationMethod(null);
}
}
The AllCapsTransformationMethod
class is not (currently) public, but still, the source is also available. I've simplified that class a bit (removed the setLengthChangesAllowed()
method), so the complete solution is this:
public class UpperCaseTextView extends TextView {
public UpperCaseTextView(Context context) {
super(context);
setTransformationMethod(upperCaseTransformation);
}
public UpperCaseTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setTransformationMethod(upperCaseTransformation);
}
public UpperCaseTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setTransformationMethod(upperCaseTransformation);
}
private final TransformationMethod upperCaseTransformation =
new TransformationMethod() {
private final Locale locale = getResources().getConfiguration().locale;
@Override
public CharSequence getTransformation(CharSequence source, View view) {
return source != null ? source.toString().toUpperCase(locale) : null;
}
@Override
public void onFocusChanged(View view, CharSequence sourceText,
boolean focused, int direction, Rect previouslyFocusedRect) {}
};
}
You cannot create a table with a name that is identical to an existing table or view in the cluster. To modify an existing table, use ALTER TABLE
(link), or to drop all data currently in the table and create an empty table with the desired schema, issue DROP TABLE
before CREATE TABLE
.
It could be that the sequence you are creating is the culprit. In PostgreSQL, sequences are implemented as a table with a particular set of columns. If you already have the sequence defined, you should probably skip creating it. Unfortunately, there's no equivalent in CREATE SEQUENCE
to the IF NOT EXISTS
construct available in CREATE TABLE
. By the looks of it, you might be creating your schema unconditionally, anyways, so it's reasonable to use
DROP TABLE IF EXISTS csd_relationship;
DROP SEQUENCE IF EXISTS csd_relationship_csd_relationship_id_seq;
before the rest of your schema update; In case it isn't obvious, This will delete all of the data in the csd_relationship
table, if there is any
The ZIP algorithm is a combination of LZW and Huffman Trees. You can use one of theses algorithms separately.
The compression is based on 2 factors :
In your case, you should try the LZW algorithm only. Used basically, the chain can be compressed without adding meta-informations: it is probably better for short strings compression.
For the Huffman algorithm, the coding tree has to be sent with the compressed text. So, for a small text, the result can be larger than the original text, because of the tree.
Last revision merged from trunk to branch can be found by running this command inside the working copy directory:
svn log -v --stop-on-copy
There are mutiple applications for Java's annotations. First of all, they may used by the compiler (or compiler extensions). Consider for example the Override annotation:
class Foo {
@Override public boolean equals(Object other) {
return ...;
}
}
This one is actually built into the Java JDK. The compiler will signal an error, if some method is tagged with it, which does not override a method inherited from a base class. This annotation may be helpful in order to avoid the common mistake, where you actually intend to override a method, but fail to do so, because the signature given in your method does not match the signature of the method being overridden:
class Foo {
@Override public boolean equals(Foo other) { // Compiler signals an error for this one
return ...;
}
}
As of JDK7, annotations are allowed on any type. This feature can now be used for compiler annotations such as NotNull, like in:
public void processSomething(@NotNull String text) {
...
}
which allows the compiler to warn you about improper/unchecked uses of variables and null values.
Another more advanced application for annotations involves reflection and annotation processing at run-time. This is (I think) what you had in mind when you speak of annotations as "replacement for XML based configuration". This is the kind of annotation processing used, for example, by various frameworks and JCP standards (persistence, dependency injection, you name it) in order to provide the necessary meta-data and configuration information.
You haven't got your SUMIF
in the correct order - it needs to be range, criteria, sum range. Try:
=SUMIF(A:A,">="&DATE(2012,1,1),B:B)
SQL Server Express does not come with profiler, but you can use SQL Server 2005/2008 Express Profiler instead.
Its a function that calls itself. Its useful for walking certain data structures that repeat themselves, such as trees. An HTML DOM is a classic example.
An example of a tree structure in javascript and a recursive function to 'walk' the tree.
1
/ \
2 3
/ \
4 5
--
var tree = {
id: 1,
left: {
id: 2,
left: null,
right: null
},
right: {
id: 3,
left: {
id: 4,
left: null,
right: null
},
right: {
id: 5,
left: null,
right: null
}
}
};
To walk the tree, we call the same function repeatedly, passing the child nodes of the current node to the same function. We then call the function again, first on the left node, and then on the right.
In this example, we'll get the maximum depth of the tree
var depth = 0;
function walkTree(node, i) {
//Increment our depth counter and check
i++;
if (i > depth) depth = i;
//call this function again for each of the branch nodes (recursion!)
if (node.left != null) walkTree(node.left, i);
if (node.right != null) walkTree(node.right, i);
//Decrement our depth counter before going back up the call stack
i--;
}
Finally we call the function
alert('Tree depth:' + walkTree(tree, 0));
A great way of understanding recursion is to step through the code at runtime.
The only benefit in using the newInstance()
that I see are the following:
You will have a single place where all the arguments used by the fragment could be bundled up and you don't have to write the code below everytime you instantiate a fragment.
Bundle args = new Bundle();
args.putInt("someInt", someInt);
args.putString("someString", someString);
// Put any other arguments
myFragment.setArguments(args);
Its a good way to tell other classes what arguments it expects to work faithfully(though you should be able to handle cases if no arguments are bundled in the fragment instance).
So, my take is that using a static newInstance()
to instantiate a fragment is a good practice.
/
means the root of the current drive;
./
means the current directory;
../
means the parent of the current directory.
In java all elements(primitive integer types byte
short
, int
, long
) are initialised to 0 by default. You can save the loop.
You have two choices to do this.
The Quick and Dirty is selecting your files (using ctrl) in Project Explorer view, right-click them, choose Replace with...
and then you choose the best option for you, from Latest from Repository
, or some Branch
version. After getting those files you modify them (with a space, or fix something, your call and commit them to create a newer revision.
A more clean way is choosing Merge
at team menu and navigate through the wizard that will help you to recovery the old version in the actual revision.
Both commands have their command-line equivalents: svn revert
and svn merge
.
additionally, you need to dissmis dialog before calling activity.super.onBackPressed()
, otherwise you'll get "Activity has leaked.." error.
Example in my case with sweetalerdialog library:
@Override
public void onBackPressed() {
//super.onBackPressed();
SweetAlertDialog progressDialog = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE);
progressDialog.setCancelable(false);
progressDialog.setTitleText("Are you sure you want to exit?");
progressDialog.setCancelText("No");
progressDialog.setConfirmText("Yes");
progressDialog.setCanceledOnTouchOutside(true);
progressDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.dismiss();
MainActivity.super.onBackPressed();
}
});
progressDialog.show();
}
you can simply bind @Hostlistener with the component, and rest will take care by it. It won't need binding of any method from its HTML template.
@HostListener('keydown',['$event'])
onkeydown(event:keyboardEvent){
if(event.key == 'Enter'){
// TODO do something here
// form.submit() OR API hit for any http method
}
}
The above code should work with Angular 1+ version
What I suggest you do is add a META-INF
directory with a MANIFEST.MF
file in .war file.
Please note that according to servlet spec, it must be a .war file and not .war directory for the META-INF/MANIFEST.MF
to be read by container.
Edit the MANIFEST.MF
Class-Path property to C:\app_config\java_app
:
See Using JAR Files: The Basics (Understanding the Manifest)
Enjoy.
Docker inspect use to print all container ips and its respective names
docker ps -q | xargs -n 1 docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}} {{ .Name }}' | sed 's/ \// /'
Take selected value:
worksheet name = ordls
form control list box name = DEPDB1
selectvalue = ordls.Shapes("DEPDB1").ControlFormat.List(ordls.Shapes("DEPDB1").ControlFormat.Value)
The problem is not that you can't forward-declare a template class. Yes, you do need to know all of the template parameters and their defaults to be able to forward-declare it correctly:
namespace std {
template<class T, class Allocator = std::allocator<T>>
class list;
}
But to make even such a forward declaration in namespace std
is explicitly prohibited by the standard: the only thing you're allowed to put in std
is a template specialisation, commonly std::less
on a user-defined type. Someone else can cite the relevant text if necessary.
Just #include <list>
and don't worry about it.
Oh, incidentally, any name containing double-underscores is reserved for use by the implementation, so you should use something like TEST_H
instead of __TEST__
. It's not going to generate a warning or an error, but if your program has a clash with an implementation-defined identifier, then it's not guaranteed to compile or run correctly: it's ill-formed. Also prohibited are names beginning with an underscore followed by a capital letter, among others. In general, don't start things with underscores unless you know what magic you're dealing with.
Use this code for find the which key pressed
from pynput import keyboard
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
If you want to pass a JavaScript object/hash (ie. an associative array in PHP) then you would do:
$.post('/url/to/page', {'key1': 'value', 'key2': 'value'});
If you wanna pass an actual array (ie. an indexed array in PHP) then you can do:
$.post('/url/to/page', {'someKeyName': ['value','value']});
If you want to pass a JavaScript array then you can do:
$.post('/url/to/page', {'someKeyName': variableName});
contentType
is the type of data you're sending, so application/json; charset=utf-8
is a common one, as is application/x-www-form-urlencoded; charset=UTF-8
, which is the default.
dataType
is what you're expecting back from the server: json
, html
, text
, etc. jQuery will use this to figure out how to populate the success function's parameter.
If you're posting something like:
{"name":"John Doe"}
and expecting back:
{"success":true}
Then you should have:
var data = {"name":"John Doe"}
$.ajax({
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
alert(result.success); // result is an object which is created from the returned JSON
},
});
If you're expecting the following:
<div>SUCCESS!!!</div>
Then you should do:
var data = {"name":"John Doe"}
$.ajax({
dataType : "html",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
jQuery("#someContainer").html(result); // result is the HTML text
},
});
One more - if you want to post:
name=John&age=34
Then don't stringify
the data, and do:
var data = {"name":"John", "age": 34}
$.ajax({
dataType : "html",
contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
data : data,
success : function(result) {
jQuery("#someContainer").html(result); // result is the HTML text
},
});
Here is the solution for Rest API
class Program
{
static void Main(string[] args)
{
BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
BaseResponse response = new BaseResponse();
BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
}
public async Task<BaseResponse> GetCallAsync(string endpoint)
{
try
{
HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
baseresponse.StatusCode = (int)response.StatusCode;
}
else
{
baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
baseresponse.StatusCode = (int)response.StatusCode;
}
return baseresponse;
}
catch (Exception ex)
{
baseresponse.StatusCode = 0;
baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
}
return baseresponse;
}
}
public class BaseResponse
{
public int StatusCode { get; set; }
public string ResponseMessage { get; set; }
}
public class BaseClient
{
readonly HttpClient client;
readonly BaseResponse baseresponse;
public BaseClient(string baseAddress, string username, string password)
{
HttpClientHandler handler = new HttpClientHandler()
{
Proxy = new WebProxy("http://127.0.0.1:8888"),
UseProxy = false,
};
client = new HttpClient(handler);
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
baseresponse = new BaseResponse();
}
}
+=
in JavaScript (as well as in many other languages) adds the right hand side to the variable on the left hand side, storing the result in that variable. Your example of 1 +=2
therefore does not make sense. Here is an example:
var x = 5;
x += 4; // x now equals 9, same as writing x = x + 4;
x -= 3; // x now equals 6, same as writing x = x - 3;
x *= 2; // x now equals 12, same as writing x = x * 2;
x /= 3; // x now equals 4, same as writing x = x / 3;
In your specific example the loop is summing the numbers in the array data
.
Im putting this in an answer because it's too long for a comment:
If you need the VM to be aware when the CheckBox
is changed, you should really bind the CheckBox
to the VM, and not a static value:
public class ViewModel
{
private bool _caseSensitive;
public bool CaseSensitive
{
get { return _caseSensitive; }
set
{
_caseSensitive = value;
NotifyPropertyChange(() => CaseSensitive);
Settings.Default.bSearchCaseSensitive = value;
}
}
}
XAML:
<CheckBox Content="Case Sensitive" IsChecked="{Binding CaseSensitive}"/>
Press Ctrl, Shift, P at the same time, a menu will appear, search for Editor Zoom in
.
After selecting that, the font will get larger by some degree.
Repeat this until you achieve your desired font size.
That's not possible.
The alternative is using reflection:
Class.forName("SomeClass").getMethod("someMethod").invoke(null);
As part of trying to answer one of my own questions here, I came across this trick.
In the API Gateway mapping template, use the following to give you the complete query string as sent by the HTTP client:
{
"querystring": "$input.params().querystring"
}
The advantage is that you don't have to limit yourself to a set of predefined mapped keys in your query string. Now you can accept any key-value pairs in the query string, if this is how you want to handle.
Note: According to this, only $input.params(x)
is listed as a variable made available for the VTL template. It is possible that the internals might change and querystring
may no longer be available.
Implementing a "Keep Me Logged In" feature means you need to define exactly what that will mean to the user. In the simplest case, I would use that to mean the session has a much longer timeout: 2 days (say) instead of 2 hours. To do that, you will need your own session storage, probably in a database, so you can set custom expiry times for the session data. Then you need to make sure you set a cookie that will stick around for a few days (or longer), rather than expire when they close the browser.
I can hear you asking "why 2 days? why not 2 weeks?". This is because using a session in PHP will automatically push the expiry back. This is because a session's expiry in PHP is actually an idle timeout.
Now, having said that, I'd probably implement a harder timeout value that I store in the session itself, and out at 2 weeks or so, and add code to see that and to forcibly invalidate the session. Or at least to log them out. This will mean that the user will be asked to login periodically. Yahoo! does this.
In case you use a different database schemas than ".dbo" or your db is containing Pk´s, which are composed by several fields, please don´t use the the solution of Carter Medlin, otherwise you will damage your db!!!
When you are working with different schemas try this (don´t forget to make a backup of your database before!):
DECLARE @sql AS NVARCHAR(max)=''
select @sql = @sql +
'ALTER INDEX ALL ON ' + SCHEMA_NAME( t.schema_id) +'.'+ '['+ t.[name] + '] DISABLE;'+CHAR(13)
from
sys.tables t
where type='u'
select @sql = @sql +
'ALTER INDEX ' + i.[name] + ' ON ' + SCHEMA_NAME( t.schema_id) +'.'+'[' + t.[name] + '] REBUILD;'+CHAR(13)
from
sys.key_constraints i
join
sys.tables t on i.parent_object_id=t.object_id
where i.type='PK'
exec dbo.sp_executesql @sql;
go
After doing some Fk-free actions, you can switch back with
DECLARE @sql AS NVARCHAR(max)=''
select @sql = @sql +
'ALTER INDEX ALL ON ' + SCHEMA_NAME( t.schema_id) +'.'+'[' + t.[name] + '] REBUILD;'+CHAR(13)
from
sys.tables t
where type='u'
print @sql
exec dbo.sp_executesql @sql;
exec sp_msforeachtable "ALTER TABLE ? WITH NOCHECK CHECK CONSTRAINT ALL";
Only one thing more: when you´re using the "crasis variable assignment" you need to use double cotes too AND you do not need to use the "input" word!:
valInput = $(`[name="${inputNameHere}"]`).val();
This will Helpfull.Easy to implement,100% tested.
for(int i=1;i<linecount;i++)
{
progressBar1.Value = i * progressBar1.Maximum / linecount; //show process bar counts
LabelTotal.Text = i.ToString() + " of " + linecount; //show number of count in lable
int presentage = (i * 100) / linecount;
LabelPresentage.Text = presentage.ToString() + " %"; //show precentage in lable
Application.DoEvents(); keep form active in every loop
}
Use the filename
property like this:
uriContent = "data:application/octet-stream;filename=filename.txt," +
encodeURIComponent(codeMirror.getValue());
newWindow=window.open(uriContent, 'filename.txt');
EDIT:
Apparently, there is no reliable way to do this. See: Is there any way to specify a suggested filename when using data: URI?
Since android doesnt support <ol>, <ul> or <li>
html elements, I had to do it like this
<string name="names"><![CDATA[<p><h2>List of Names:</h2></p><p>•name1<br />•name2<br /></p>]]></string>
if you want to maintain custom space then use </pre> tag
For J2E code, I've used SilkPerformer, LoadRunner and JMeter for concurrency testing of threads. They all do the same thing. Basically, they give you a relatively simple interface for administrating their version of the proxy server, required, in order to analyze the TCP/IP data stream, and simulate multiple users making simultaneous requests to your app server. The proxy server can give you the ability to do things like analyze the requests made, by presenting the whole page and URL sent to the server, as well as the response from the server, after processing the request.
You can find some bugs in insecure http mode, where you can at least analyze the form data that is being sent, and systematically alter that for each user. But the true tests are when you run in https (Secured Socket Layers). Then, you also have to contend with systematically altering the session and cookie data, which can be a little more convoluted.
The best bug I ever found, while testing concurrency, was when I discovered that the developer had relied upon Java garbage collection to close the connection request that was established at login, to the LDAP server, when logging in. This resulted in users being exposed to other users' sessions and very confusing results, when trying to analyze what happened when the server was brought to it's knees, barely able to complete one transaction, every few seconds.
In the end, you or someone will probably have to buckle down and analyze the code for blunders like the one I just mentioned. And an open discussion across departments, like the one that occurred, when we unfolded the problem described above, are most useful. But these tools are the best solution to testing multi-threaded code. JMeter is open source. SilkPerformer and LoadRunner are proprietary. If you really want to know whether your app is thread safe, that's how the big boys do it. I've done this for very large companies professionally, so I'm not guessing. I'm speaking from personal experience.
A word of caution: it does take some time to understand these tools. It will not be a matter of simply installing the software and firing up the GUI, unless you've already had some exposure to multi-threaded programming. I've tried to identify the 3 critical categories of areas to understand (forms, session and cookie data), with the hope that at least starting with understanding these topics will help you focus on quick results, as opposed to having to read through the entire documentation.
NA is a special value in R, do not mix up the NA value with the "NA" string. Depending on the way the data was imported, your "NA" and "NULL" cells may be of various type (the default behavior is to convert "NA" strings to NA values, and let "NULL" strings as is).
If using read.table() or read.csv(), you should consider the "na.strings" argument to do clean data import, and always work with real R NA values.
An example, working in both cases "NULL" and "NA" cells :
DF <- read.csv("file.csv", na.strings=c("NA", "NULL"))
new_DF <- subset(DF, is.na(DF$Var2))
You need to search the World from the top right search bar and delete the expired certificate. Make sure you selected Login and All items.
Purpose: Android library at single place - Share across multiple projects http://raevilman.blogspot.com/2016/02/android-library-project-using-android.html
It looks funny but it works.
<?php
$file = 'newpage.html';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "<!doctype html><html>
<head><meta charset='utf-8'>
<title>new file</title>
</head><body><h3>New HTML file</h3>
</body></html>
";
// Write the contents back to the file
file_put_contents($file, $current);
?>
That particular phrasing is by James Iry, from his highly entertaining Brief, Incomplete and Mostly Wrong History of Programming Languages, in which he fictionally attributes it to Philip Wadler.
The original quote is from Saunders Mac Lane in Categories for the Working Mathematician, one of the foundational texts of Category Theory. Here it is in context, which is probably the best place to learn exactly what it means.
But, I'll take a stab. The original sentence is this:
All told, a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor.
X here is a category. Endofunctors are functors from a category to itself (which is usually all Functor
s as far as functional programmers are concerned, since they're mostly dealing with just one category; the category of types - but I digress). But you could imagine another category which is the category of "endofunctors on X". This is a category in which the objects are endofunctors and the morphisms are natural transformations.
And of those endofunctors, some of them might be monads. Which ones are monads? Exactly the ones which are monoidal in a particular sense. Instead of spelling out the exact mapping from monads to monoids (since Mac Lane does that far better than I could hope to), I'll just put their respective definitions side by side and let you compare:
* -> *
with a Functor
instance)join
in Haskell)return
in Haskell)With a bit of squinting you might be able to see that both of these definitions are instances of the same abstract concept.
This is what git filter-branch
was designed for.
The answer you're looking for in 2020 and beyond:
setColorFilter(color, mode)
is deprecated since API 29 (as discussed here)button.setBackgroundColor(color)
messes with the button styleNow the proper way to set a buttons color is using BlendModeColorFilter()
(see documentation).
Usage:
btn.background.colorFilter = BlendModeColorFilter(color, BlendMode.MULTIPLY)
If you work with older APIs too:
fun setButtonColor(btn: Button, color: Int) {
if (Build.VERSION.SDK_INT >= 29)
btn.background.colorFilter = BlendModeColorFilter(color, BlendMode.MULTIPLY)
else
btn.background.setColorFilter(color, PorterDuff.Mode.MULTIPLY)
}
Please vote to help others finding this answer - it took me quite a while figuring this out ^^
If you want to concatenate the input, then replace printf("%s\n", buffer);
with strcat(big_buffer, buffer);
. Also create and initialize the big buffer at the beginning: char *big_buffer = new char[BIG_BUFFERSIZE];
big_buffer[0] = '\0';
. You should also prevent a buffer overrun by verifying the current buffer length plus the new buffer length does not exceed the limit: if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE)
. The modified program would look like this:
#include <stdio.h>
#include <string.h>
#define BUFFERSIZE 10
#define BIG_BUFFERSIZE 1024
int main (int argc, char *argv[])
{
char buffer[BUFFERSIZE];
char *big_buffer = new char[BIG_BUFFERSIZE];
big_buffer[0] = '\0';
printf("Enter a message: \n");
while(fgets(buffer, BUFFERSIZE , stdin) != NULL)
{
if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE)
{
strcat(big_buffer, buffer);
}
}
return 0;
}
This is improved @Vicky solution - it has clearInterval() added so it prevents a loop of reloading if the redirect takes too long:
$(document).ready(function () {
var myTimer = window.setInterval(function () {
var timeLeft = $("#countdown").html();
if (eval(timeLeft) == 0) {
console.log('Now redirecting');
clearInterval(myTimer);
window.location = ("@Html.Raw(HttpUtility.HtmlDecode(redirectUrl))");
} else {
$("#countdown").html(eval(timeLeft) - eval(1));
}
}, 1000);
});
A "ContractFilter mismatch at the EndpointDispatcher" means the receiver could not process the message because it did not match any of the contracts the receiver has configured for the endpoint which received the message.
This can be because:
Have at look at the EndpointDispatcher
class for more information on the subject.
So:
Make certain that your client and server contracts match.
Check the bindings are the same between client and server.
Check the security settings are the same between client and server.
function isMobile(){
if(defined(isMobile))return isMobile;
@define(isMobile,(!($HUA=@trim(@$_SERVER['HTTP_USER_AGENT']))?0:
(
preg_match('/(android|bb\d+|meego).+mobile|silk|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i'
,$HUA)
||
preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i'
,$HUA)
)
));
}
echo isMobile()?1:0;
// OR
echo isMobile?1:0;
SELECT tab.*,
row_number() OVER () as rnum
FROM tab;
Here's the relevant section in the docs.
P.S. This, in fact, fully matches the answer in the referenced question.
I hope this will help to understand the relationship between .NET Standard API surface and other .NET platforms. Each interface represents a target framework and methods represents groups of APIs available on that target framework.
namespace Analogy
{
// .NET Standard
interface INetStandard10
{
void Primitives();
void Reflection();
void Tasks();
void Xml();
void Collections();
void Linq();
}
interface INetStandard11 : INetStandard10
{
void ConcurrentCollections();
void LinqParallel();
void Compression();
void HttpClient();
}
interface INetStandard12 : INetStandard11
{
void ThreadingTimer();
}
interface INetStandard13 : INetStandard12
{
//.NET Standard 1.3 specific APIs
}
// And so on ...
// .NET Framework
interface INetFramework45 : INetStandard11
{
void FileSystem();
void Console();
void ThreadPool();
void Crypto();
void WebSockets();
void Process();
void Drawing();
void SystemWeb();
void WPF();
void WindowsForms();
void WCF();
}
interface INetFramework451 : INetFramework45, INetStandard12
{
// .NET Framework 4.5.1 specific APIs
}
interface INetFramework452 : INetFramework451, INetStandard12
{
// .NET Framework 4.5.2 specific APIs
}
interface INetFramework46 : INetFramework452, INetStandard13
{
// .NET Framework 4.6 specific APIs
}
interface INetFramework461 : INetFramework46, INetStandard14
{
// .NET Framework 4.6.1 specific APIs
}
interface INetFramework462 : INetFramework461, INetStandard15
{
// .NET Framework 4.6.2 specific APIs
}
// .NET Core
interface INetCoreApp10 : INetStandard15
{
// TODO: .NET Core 1.0 specific APIs
}
// Windows Universal Platform
interface IWindowsUniversalPlatform : INetStandard13
{
void GPS();
void Xaml();
}
// Xamarin
interface IXamarinIOS : INetStandard15
{
void AppleAPIs();
}
interface IXamarinAndroid : INetStandard15
{
void GoogleAPIs();
}
// Future platform
interface ISomeFuturePlatform : INetStandard13
{
// A future platform chooses to implement a specific .NET Standard version.
// All libraries that target that version are instantly compatible with this new
// platform
}
}
Try to click on the icon on the very right part of the "Android" view, you should see Logcat tab on the Android view (you can bring Android view up by pressing Alt+6)
In WPF
apps This code working perfectly
private void txt1_KeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.IsKeyDown(Key.Enter) )
{
Button_Click(this, new RoutedEventArgs());
}
}
Check against any long running queries in your database.
Increasing your pool size will only make your webapp live a little longer (and probably get a lot slower)
You can use sql server profiler and filter on duration / reads to see which querys need optimization.
I also see you're probably keeping a global connection?
blnMainConnectionIsCreatedLocal
Let .net do the pooling for you and open / close your connection with a using statement.
Suggestions:
Always open and close a connection like this, so .net can manage your connections and you won't run out of connections:
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// do some stuff
} //conn disposed
As I mentioned, check your query with sql server profiler and see if you can optimize it. Having a slow query with many requests in a web app can give these timeouts too.
Biginteger
is an immutable class.
You need to explicitly assign value of your output to sum like this:
sum = sum.add(BigInteger.valueof(i));
I just did the following (in V 3.5) and it worked like a charm:
<p:column headerText="name" width="20px"/>
You have strange expectations. If you gave the chain of arguments that led you to them, we might spot the flaw in them. As it is, I can only give a short primer on generics, hoping to touch on the points you might have misunderstood.
ArrayList<? extends Object>
is an ArrayList whose type parameter is known to be Object
or a subtype thereof. (Yes, extends in type bounds has a meaning other than direct subclass). Since only reference types can be type parameters, this is actually equivalent to ArrayList<?>
.
That is, you can put an ArrayList<String>
into a variable declared with ArrayList<?>
. That's why a1.add(3)
is a compile time error. a1
's declared type permits a1
to be an ArrayList<String>
, to which no Integer
can be added.
Clearly, an ArrayList<?>
is not very useful, as you can only insert null into it. That might be why the Java Spec forbids it:
It is a compile-time error if any of the type arguments used in a class instance creation expression are wildcard type arguments
ArrayList<ArrayList<?>>
in contrast is a functional data type. You can add all kinds of ArrayLists into it, and retrieve them. And since ArrayList<?>
only contains but is not a wildcard type, the above rule does not apply.
Try this configuration. It worked for me:
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>mywebRoot</warSourceDirectory>
<warSourceExcludes>source\**,build\**,dist\**,WEB-INF\lib\*,
WEB-INF\classes\**,build.*
</warSourceExcludes>
<webXml>myproject/source/deploiement/web.xml</webXml>
<webResources>
<resource>
<directory>mywebRoot/WEB-INF/lib</directory>
<targetPath>WEB-INF/lib</targetPath>
<includes>
<include>mySystemJar1.jar.jar</include>
<include>mySystemJar2.jar</include>
</includes>
</resource>
</webResources>
</configuration>
</plugin>
That should work:
>>> df = pd.DataFrame()
>>> data = pd.DataFrame({"A": range(3)})
>>> df.append(data)
A
0 0
1 1
2 2
But the append
doesn't happen in-place, so you'll have to store the output if you want it:
>>> df
Empty DataFrame
Columns: []
Index: []
>>> df = df.append(data)
>>> df
A
0 0
1 1
2 2
$.browser
was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.
I'm on macOS Catalina 10.15.3, and I had a similar error: ExecutableNotFound: failed to execute ['dot', '-Tsvg'], make sure the Graphviz executables are on your systems' PATH
Fixed it with:
pip3 install graphviz
AND brew install graphviz
Note the pip3 install
will only return the success message Successfully installed graphviz-0.13.2
so we still need to run brew install
to get graphviz 2.42.3 (as of 10 Mar 2020, 6PM).
Scripts are raw java embedded in the page code, and if you declare variables in your scripts, then they become local variables embedded in the page.
In contrast, JSTL works entirely with scoped attributes, either at page
, request
or session
scope. You need to rework your scriptlet to fish test
out as an attribute:
<c:set var="test" value="test1"/>
<%
String resp = "abc";
String test = pageContext.getAttribute("test");
resp = resp + test;
pageContext.setAttribute("resp", resp);
%>
<c:out value="${resp}"/>
If you look at the docs for <c:set>
, you'll see you can specify scope
as page
, request
or session
, and it defaults to page
.
Better yet, don't use scriptlets at all: they make the baby jesus cry.
Just put:
import { Observable} from 'rxjs';
Just like that. Nothing more or less.
You can have a view with Background color as black and set alpha for the view as 0.7 or whatever as per your requirement.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/onboardingimg1">
<View
android:id="@+id/opacityFilter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
android:layout_alignParentBottom="true"
android:alpha="0.7">
</View>
</RelativeLayout>
for single line comment add # at starting of a line
for multiple line comments add ' (single quote) from where you want to start & add ' (again single quote) at the point where you want to end the comment line.
If you want to prevent all caching (e.g. force a reload when using the back button) you need:
no-cache for IE
no-store for Firefox
There's my information about this here:
http://blog.httpwatch.com/2008/10/15/two-important-differences-between-firefox-and-ie-caching/
Go to your Target or Project settings, click the Gear icon at the bottom left, and select "Add User-Defined Setting". The new setting name should be GCC_PREPROCESSOR_DEFINITIONS
, and you can type your definitions in the right-hand field.
Per Steph's comments, the full syntax is:
constant_1=VALUE constant_2=VALUE
Note that you don't need the '='s if you just want to #define a symbol, rather than giving it a value (for #ifdef
statements)
You could use a nested Any()
for this check which is available on any Enumerable
:
bool hasMatch = myStrings.Any(x => parameters.Any(y => y.source == x));
Faster performing on larger collections would be to project parameters
to source
and then use Intersect
which internally uses a HashSet<T>
so instead of O(n^2) for the first approach (the equivalent of two nested loops) you can do the check in O(n) :
bool hasMatch = parameters.Select(x => x.source)
.Intersect(myStrings)
.Any();
Also as a side comment you should capitalize your class names and property names to conform with the C# style guidelines.