_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d18401 | test | 1- Most trivial query, get all FileSystem Documents:
const fileSystems = await FileSystem.find({
// Empty Object means no condition thus give me all your data
});
2- Using the $eq operator to match documents with a certain value
const fileSystems = await FileSystem.find({
isDir: true,
folderName: { $eq: 'root' }
});
3- Using the $in operator to match a specific field with an array of possible values.
const fileSystems = await FileSystem.find({
isDir: true,
folderName: { $in: ['root', 'nestedFolder1', 'nestedFolder2'] }
});
4- Using the $and operator to specify multiple conditions
const fileSystems = await FileSystem.find({
$and: [
{ isDir: true },
{ folderName: { $in: ['root', 'nestedFolder1', 'nestedFolder2'] } }
]
});
5- Retrieve all documents that are directories and are not empty.
const fileSystems = await FileSystem.find({
isDir: true,
$or: [
{ files: { $exists: true, $ne: [] } },
{ folders: { $exists: true, $ne: [] } }
]
});
6- All directories that have a folder name that starts with the letter 'n'
const fileSystems = await FileSystem.find({
isDir: true,
folderName: { $regex: '^n' }
});
Now the tougher queries:
1- count the total number of documents
const count = await FileSystem.aggregate([
{ $count: 'total' }
]);
2- count the total number of documents that are directories
const count = await FileSystem.aggregate([
{ $match: { isDir: true } },
{ $count: 'total' }
]);
3- Get 'foldername' and 'filename; of all documents that are files.
const fileSystems = await FileSystem.aggregate([
{ $match: { isDir: false } },
{ $project: { folderName: 1, fileName: 1 } }
]);
4- Retrieve the total number of files (isDir: false) in each directory (isDir: true)
const fileCounts = await FileSystem.aggregate([
{ $match: { isDir: true } },
{
$project: {
folderName: 1,
fileCount: {
$size: {
$filter: {
input: '$files',
as: 'file',
cond: { $eq: ['$$file.isDir', false] }
}
}
}
}
}
]);
5- Recursive structure querying:
The FileSystem interface is recursive, because it has both an array of files and an array of folders, which are both of type File[] and FileSystem[].
To query this recursive schema, you can use the $lookup operator in an aggregate pipeline, to make a left join between FileSystem and itself, based on some criteria.
//Retrieve All Documents from FileSystem and their child documents
const fileSystems = await FileSystem.aggregate([
{
$lookup: {
from: 'FileSystem',
localField: '_id',
foreignField: 'parentId',
as: 'children'
}
}
]);
//Use the match operator in the pipeline to filter the results:
const fileSystems = await FileSystem.aggregate([
{
$lookup: {
from: 'FileSystem',
localField: '_id',
foreignField: 'parentId',
as: 'children'
}
},
{ $match: { isDir: true } }
]); | unknown | |
d18402 | test | You can simply use
$window.open('/controller-Name/action-method-Name');};
Which will find the action method and return the view.
If problem still persist, debug your action method once. | unknown | |
d18403 | test | The problem is that you can't combine a SELECT which sets a variable with a SELECT which returns data on the screen.
You set @OutputName to (case when (a.M_TRN_TYPE='XSW' .. ) but in the same SELECT you're also trying to display the results of:
case
when @OutputName='XSW' and
(case
when c.M_DATESKIP='+1OD'
then b.M_DTE_SKIP_1
else b.M_DTE_SKIP_2
end)=a.M_TP_DTEFST
then 0
else a.M_NB
end as 'NBI'
You can't have these two in the same SELECT, in the format you're using. My recommendation is to split them, one for assigning the variable:
DECLARE @OutputName CHAR(50)
SELECT @OutputName=
(case when (a.M_TRN_TYPE='XSW' or a.M_TRN_TYPE='SWLEG') then 'FXSW'
when (a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS='C') then 'DCS'
when a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS<>'C' and SUBSTRING(c.M_SP_SCHED0,1,2)='+1' then
(case when b.M_DTE_SKIP_1>=a.M_TP_DTEEXP then 'SPOT' else 'OUTR' end)
when a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS<>'C' and SUBSTRING(c.M_SP_SCHED0,1,2)<>'+1' then
(case when b.M_DTE_SKIP_2>=a.M_TP_DTEEXP then 'SPOT' else 'OUTR' end)
end)
from TP_COMPL_PL_REP b
join TP_ALL_REP a on (a.M_NB=b.M_NB and a.M_REF_DATA=b.M_REF_DATA)
left join DM_SPOT_CONTRACT_REP c on (a.M_NB=c.M_NB and a.M_REF_DATA=c.M_REF_DATA)
and one for returning the data:
SELECT case when @OutputName='XSW' and
(case when c.M_DATESKIP='+1OD' then b.M_DTE_SKIP_1 else b.M_DTE_SKIP_2 end)=a.M_TP_DTEFST
then 0
else a.M_NB
end as 'NBI'
from TP_COMPL_PL_REP b
join TP_ALL_REP a on (a.M_NB=b.M_NB and a.M_REF_DATA=b.M_REF_DATA)
left join DM_SPOT_CONTRACT_REP c on (a.M_NB=c.M_NB and a.M_REF_DATA=c.M_REF_DATA) | unknown | |
d18404 | test | To make sure I'm understanding your question completely...
You're looking for a way to limit a User's ability to manage Groups based on the locations of the Company that User belongs to?
Assuming I've got that correct, I would recommend using #pluck:
can :manage, Group, location_id: user.company.locations.pluck(:id)
This collects all the :id's on a User's Company's Locations, and ensures a User can only manage Groups that have a :location_id contained within that collection.
Functionally, this is identical to what you've done, but is more efficient in two ways:
*
*It doesn't involve any unnecessary Ruby logic
*Using #pluck only queries the :id on a location, as opposed to the entire location and all its attributes
Generally speaking, whenever you're accessing your database in Rails, you're better off doing so entirely with ActiveRecord methods. This will help prevent you from wasting time querying for extra information you don't need, and eliminate the extra overhead of using Ruby to re-structure your data.
Hope that helps! | unknown | |
d18405 | test | Use the default argument to set the default date. This should handle all the cases except the third one, which is somewhat ambiguous and probably needs some parser tweaking or a mindreader:
In [15]: from datetime import datetime
In [16]: from dateutil import parser
In [17]: DEFAULT_DATE = datetime(2013,1,1)
In [18]: dates=["Today is August 2012. Tomorrow isn't",
...: "Another day 12 August, another time",
...: "12/08 is another format",
...: "have another ? 08/12/12 could be",
...: "finally august 12 would be"]
In [19]: for date in dates:
...: print parser.parse(date,fuzzy=True, default=DEFAULT_DATE)
...:
2012-08-01 00:00:00
2013-08-12 00:00:00
2013-12-08 00:00:00 # wrong
2012-08-12 00:00:00
2013-08-12 00:00:00 | unknown | |
d18406 | test | Seems like you are trying to create two arrays of int, holding different set of images. But you are using the same variable name pirates. I would suggest you define two different variables int[] pirates and int[] piratesNatural and then switch between those two arrays when you need one and the other.
Bitmap icon;
if(natural)
icon = BitmapFactory.decodeResource(getResources(),piratesNatural[i]);
else
icon = BitmapFactory.decodeResource(getResources(),pirates[i]);
A: you doing animation?
int frame=0;
int frametime=24;
Bitmap icon1 BitmapFactory.decodeResource(getResources(), R.drawable.image_1,);
Bitmap icon2 BitmapFactory.decodeResource(getResources(), R.drawable.image_2,);
Bitmap icon3 BitmapFactory.decodeResource(getResources(), R.drawable.image_3,);
Bitmap icon4 BitmapFactory.decodeResource(getResources(), R.drawable.image_4,);
//in update
frametime--;
if(frametime<=0){
frame++;
frametime=24;
}
if(frame>3){
frame=0;
}
//in onDraw
switch(frame){
case 0:
canvas.drawBitmap(icon1,x,y,null);
break;
case 1:
canvas.drawBitmap(icon2,x,y,null);
break;
case 2:
canvas.drawBitmap(icon3,x,y,null);
break;
case 3:
canvas.drawBitmap(icon4,x,y,null);
break;
default:
canvas.drawBitmap(icon1,x,y,null);
break;} | unknown | |
d18407 | test | As far as I can tell the program has undefined behavior.
The member declaration std::initializer_list<wrapped> lst; requires the type to be complete and hence will implicitly instantiate std::initializer_list<wrapped>.
At this point wrapped is an incomplete type. According to [res.on.functions]/2.5, if no specific exception is stated, instantiating a standard library template with an incomplete type as template argument is undefined.
I don't see any such exception in [support.initlist].
See also active LWG issue 2493.
A: What you're doing should be safe. Section 6.7.7 of the ISO Standard, paragraph 6, describes the third and last context in which temporaries are destroyed at a different point than the end of the full expression. Footnote (35) explicitly says that this applies to the initialization of an intializer_list with its underlying temporary array:
The temporary object to which the reference is bound or the temporary object that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference if the glvalue to which the reference is bound was obtained through one of the following: ...
...(where a glvalue is, per 7.2.1, an expression whose evaluation determines the identity of an object, bit-field, or function) and then enumerates the conditions. In (6.9), it specifically mentions that:
A temporary object bound to a reference parameter in a function call (7.6.1.2) persists until the completion of the full-expression containing the call.
As I read it, this protects everything needed to build up the final argument to the top call to call_it, which is what you intend. | unknown | |
d18408 | test | In Linux,
InetAddress.getLocalHost() will look for the hostname and then return the first IP address assigned to that hostname by DNS. If you have that hostname in the file /etc/hosts, it will get the first IP address in that file for that hostname.
If you pay attention this method returns only one InetAddress.
If you haven't assigned a hostname, most probably it will be localhost.localdomain. You can set the hostname with command line:
hostname [name]
or by setting it in file /etc/sysconfig/network
If you want to get all ip addresses, including IPv6, assigned to a hostname you can use:
InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
If you want to get all ip addresses, including IPv6, assigned to a host's network interfaces, you must use class NetworkInterface.
Here I'm pasting some example code:
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.SocketException;
import java.net.NetworkInterface;
import java.util.*;
public class Test
{
public static void main(String[] args)
{
try
{
System.out.println("getLocalHost: " + InetAddress.getLocalHost().toString());
System.out.println("All addresses for local host:");
InetAddress[] addr = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
for(InetAddress a : addr)
{
System.out.println(a.toString());
}
}
catch(UnknownHostException _e)
{
_e.printStackTrace();
}
try
{
Enumeration nicEnum = NetworkInterface.getNetworkInterfaces();
while(nicEnum.hasMoreElements())
{
NetworkInterface ni=(NetworkInterface) nicEnum.nextElement();
System.out.println("Name: " + ni.getDisplayName());
System.out.println("Name: " + ni.getName());
Enumeration addrEnum = ni.getInetAddresses();
while(addrEnum.hasMoreElements())
{
InetAddress ia= (InetAddress) addrEnum.nextElement();
System.out.println(ia.getHostAddress());
}
}
}
catch(SocketException _e)
{
_e.printStackTrace();
}
}
}
For this example, I got code from one of the responses in InetAddress.getLocalHost().getHostAddress() is returning 127.0.1.1 | unknown | |
d18409 | test | You can try with the following package of npm:
Infinite Scrolling package | unknown | |
d18410 | test | Train part looks good. Validation part has a lot of 'jumps' though. Does it overfit?
the answer is yes. The so-called 'jumps' in the validation part may indicate that the model is not generalizing well to the validation data and therefore your model might be overfitting.
Is there any way to fix this and make validation part more stable?
To fix this you can use the following:
*
*Increasing the size of your training set
*Regularization techniques
*Early stopping
*Reduce the complexity of your model
*Use different hyperparameters like learning rate
A:
I've applied data augmentation (on the train data).
What does this mean? What kind of data did you add and how much? You might think I'm nitpicking, but if the distribution of the augmented data is different enough from the original data, then this will indeed cause your model to generalize poorly to the validation set.
Increasing your epochs isn't going to help here, your training loss is already decreasing reasonably. Training your model for longer is a good step if the validation loss is also decreasing nicely, but that's obviously not the case.
Some things I would personally try:
*
*Try decreasing the learning rate.
*Try training the model without the augmented data and see how the validation loss behaves.
*Try splitting the augmented data so that it's also contained in the validation set and see how the model behaves. | unknown | |
d18411 | test | you can use the below code snippet. If you are writing logic within the step definition method then the below code would be handy as method nesting is not advisable.
Boolean elementnotpresent;
Try
{
IWebElement element = Driver.FindElement(By.XPath("Element XPath"));
}
catch (NoSuchElementException)
{
elementnotpresent=true;
}
if (elementnotpresent == true)
{
Console.WriteLine("Element not present");
}
else
{
throw new Exception("Element is present");
}
A: Here's a straightforward approach to the problem:
if (Driver.Instance.FindElements(By.XPath(baseXPathSendKeys + "div[2]/textarea")).Count != 0)
{
// exists
}
else
{
// doesn't exist
}
You could create a method Exists(By) to test elements:
public bool Exists(By by)
{
if (Driver.Instance.FindElements(by).Count != 0)
{
return true;
}
else
{
return false;
}
}
Then call it when you want to test something:
By by = By.XPath(baseXPathSendKeys + "div[2]/textarea")
if (Exists(by))
{
// success
}
A: I had a strange case, when selenium was not throwing a NoSuchElementException exception, but MakeHttpRequest timed out.
So i had come up with idea, that i got the attribute innerHTML of parent HTML element, and assert that it doesnot contain not wanted element.
Assert.IsTrue(!parent.GetAttribute("innerHTML").Contains("notWantedElement"));
A: I know this was asked a while ago but you can try something like this
var wait = new WebDriverWait(driver, Timespan.FromSeconds(10));
wait.Until(driver => driver.FindElements(By.WhateverYourLocatorIs("")).Count == 0); | unknown | |
d18412 | test | Objects in chrome console get evaluated only when they are first opened.
This means that when you console.log an object like the return value of Auth.getCurrentUser(), the console displays a reference to it - this at the time of the log call contains a promise object, but it's most likely resolved by the time you open it on the console, so you see the property you're looking for.
On the other hand, when you're logging $scope.getCurrentUser._id, that's the result of a property lookup on the promise object - and it prints the current value of the property, which is undefined.
A note about clean code: your scope variable is called getCurrentUser, which makes one think it's a getter function, but it is infact the return value of a getter function. This is confusing. | unknown | |
d18413 | test | If you use windows authentication you just need to make sure that the user(s) under which your application runs also have access to the database(s) on the sql server. Using Management Studio you can add the windows logins or groups and grant them access. | unknown | |
d18414 | test | From cppreference.com Constraint_normalization
The normal form of any other expression E is the atomic constraint whose expression is E and whose parameter mapping is the identity mapping. This includes all fold expressions, even those folding over the && or || operators.
So
template <typename... Types>
concept are_same = (... && same_with_others<Types, Types...>);
is "atomic".
So indeed are_same<U, T> and are_same<T, U> are not equivalent.
I don't see how to implement it :-(
A: The problem is, with this concept:
template <typename T, typename... Others>
concept are_same = (... && std::same_as<T, Others>);
Is that the normalized form of this concept is... exactly that. We can't "unfold" this (there's nothing to do), and the current rules don't normalize through "parts" of a concept.
In other words, what you need for this to work is for your concept to normalize into:
... && (same-as-impl<T, U> && same-as-impl<U, T>)
into:
... && (is_same_v<T, U> && is_same_v<U, T>)
And consider one fold-expression && constraint to subsume another fold-expression constraint && if its underlying constraint subsumes the other's underlying constraint. If we had that rule, that would make your example work.
It may be possible to add this in the future - but the concern around the subsumption rules is that we do not want to require compilers to go all out and implement a full SAT solver to check constraint subsumption. This one doesn't seem like it makes it that much more complicated (we'd really just add the && and || rules through fold-expressions), but I really have no idea.
Note however that even if we had this kind of fold-expression subsumption, are_same<T, U> would still not subsume std::same_as<T, U>. It would only subsume are_same<U, T>. I am not sure if this would even be possible.
A: churill is right .Using std::conjunction_v might be helpful.
template <typename T,typename... Types>
concept are_same = std::conjunction_v<std::same_as<T,Types>...>; | unknown | |
d18415 | test | Why would you write a stored procedure? MySQL now supports check constraints:
alter table employee add constraint chk_employee_eid
check (eid regexp '^E[0-9]{2}')
Note that this allows anything after the first 3 characters. If you don't want anything, then add $ to the pattern:
alter table employee add constraint chk_employee_eid
check (eid regexp '^E[0-9]{2}$') | unknown | |
d18416 | test | So, if I understand your question correctly you want to know how far along the chart a number is. The answer could be pixels or inches or whatever...we'll call that multiplier m.
*
*10 should appear at 1*m (log (10) == 1)
*100 should appear at 2*m (log (100) == 2)
To find where any arbitrary value will appear (I'm using 150 from your example):
Math.Log10(150) * m
Which equals 2.18 * m.
All that's left is for you to figure out what your m is. I don't have enough info to help you with that.
It may help to use values from the chart to understand why they are there:
*
*Math.Log10(126) = 2.1
*Math.Log10(158) = 2.2
*Math.Log10(200) = 2.3
*Math.Log10(251) = 2.4
You'll note that they increment along the chart by 1/10 each time. | unknown | |
d18417 | test | Is your NAS running SAMBA? If so will the Samba log files or smbstatus command solve your need? See https://askubuntu.com/questions/89288/how-can-i-monitor-my-samba-traffic | unknown | |
d18418 | test | I agree with @@Douglas Gandini. You should define your business objects in a separate assembly that you can reference from both your ASP.NET and WPF applications. These classes should not implement any client-specific interfaces such as INotifyPropertyChanged but be pure POCO classes that contains business logic only.
In your WPF application, you could then create a view model class that implements the INotifyPropertyChanged interface and wraps any properties of the business object that it makes sense to expose to and bind to from the view.
The view model then has a reference to the model, i.e. your business object that is defined in a separate assembly that may be shared between several different client applications, and the view binds to the view model. This is typically how the MVVM design pattern is (or should be) implemented in a WPF application. The view model class contains your application logic, for example how to notify the view when a data bound property value is changed, and the model contains the business logic that is the same across all platforms and applications.
Of course this means that you will end up with a larger number of classes in total but this is not necessarily a bad thing as each class has its own responsibility. The responsibility of a view model is to act as a model for the application specific XAML view whereas the responsibility of the model class is to implement the business logic.
A: Create a shared assembly. Call it Contracts or Models and share it between your WPF and MVC | unknown | |
d18419 | test | It looks like you're trying to use the ContentType header to determine which type of response to return. That's not what it's for. You should be using the Accepts header instead, which tells the server which content types you accept.
A: Try using
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/Vendor/Details/" + newid,
beforeSend: function(xhr) {
xhr.setRequestHeader("Content-type",
"application/json; charset=utf-8");
},
data: "{}",
dataType: "json",
success: function(data) { alert(data); },
error: function(req, status, err) { ShowError("Sorry, an error occured (Vendor callback failed). Please try agian later."); }
});
a la -
http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/
A: The "content-type" header doesn't do anything when your method is "GET". | unknown | |
d18420 | test | A short answer is write a loop and customise output.
Here is a token example which you can run.
sysuse auto, clear
foreach v of var mpg price weight length displacement {
quietly ranksum `v', by(foreign) porder
scalar pval = 2*normprob(-abs(r(z)))
di "`v'{col 14}" %05.3f pval " " %6.4e pval " " %05.3f r(porder)
}
Output is
mpg 0.002 1.9e-03 0.271
price 0.298 3.0e-01 0.423
weight 0.000 3.8e-07 0.875
length 0.000 9.4e-07 0.862
displacement 0.000 1.1e-08 0.921
Notes:
*
*If your variable names are longer, they will need more space.
*Displaying P-values with fixed numbers of decimal places won't prepare you for the circumstance in which all displayed digits are zero. The code exemplifies two forms of output.
*The probability that values for the first group exceed those for the second group is very helpful in interpretation. Further summary statistics could be added.
*Naturally a presentable table needs more header lines, best given with display. | unknown | |
d18421 | test | You cannot display images on text/plain emails as shown above. You must send it as text/html.
So you first have to extend your headers like this:
$header = "From: [email protected]\nMIME-Version: 1.0\nContent-Type: text/html; charset=utf-8\n";
Then you must update your mailcontent replacing \n or linebreaks with html tags <br> or even <p>
Then you also can include image tags having the image you want to show in the email
<img src="http://www.yourserver.com/myimages/image1.jpg">
This will be downloaded from your webserver when recipient opens it.
.
BUT the much better way will be to use phpMailer Class
Using this, you will be able to include any images IN your email, without need to download it from any website. It is easy to learn and absolutely customizable.
By the way: You should use quotation marks for your $body and $body2 values...
$body= "<<<EOD
Contact Form Details of $nameFeild
Name: $nameFeild \n
City: $cityFeild \n
Country: $countryFeild \n"
A: $headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message = "<html><head>
<title>Your email at the time</title>
</head>
<body>
<img src=\"http://www.myserver.com/images_folder/my_image.jpg\">
</body>"
mail($email_to, $email_subject , $message,$headers); | unknown | |
d18422 | test | Have you looked at $where clauses in MongoDB? Seems like those would pretty much give you exactly what you're looking for. In PyMongo it would look something like:
db.foo.find().where("some javascript function that will get applied to each document matched by the find") | unknown | |
d18423 | test | I reckon this'll solve it:
char* ptr = (char*)&t;
*(int*)(ptr+sizeof(string)) = 10;
sizeof will return the size in bytes. Pointer increments will go for the size of the object its pointing at. char is a byte in size.
If you want to read up on it: C pointer arithmetic article
Just to reiterate what I think you've said: you're just hacking around as a point of learning, and you know there's no way you should ever do this in real life... !!
A: Why it doesn't work
Really just never write code like this. There is a way to set private data and that is via public members on the class. Otherwise, it's private for a reason. This being C++, there are actually non-UB ways of doing this but I'm not going to link them here because don't.
Why it doesn't work, specifically
Hint: What does ptr + sizeof(string) actually mean, for ptr being an int*? What is ptr pointing to after this line?
A: The pointer arithmetic should be done with byte pointers, not integer pointers.
#include <iostream>
#include <string>
using namespace std;
class Test
{
private:
string s;
int data;
public:
Test() { s = "New", data = 0; }
int getData() { return data; }
};
int main()
{
Test t;
char* ptr = (char*)&t;
*(int*)(ptr+sizeof(string)) = 10;
cout << t.getData();
return 0;
} | unknown | |
d18424 | test | It is not an entity framework limitation but SQL server limitation. You cannot have more then 2100 parameters for IN statement.
SELECT * FROM YourTable WHERE YourColumn IN (1,2,....,2101)
So I see 2 workarounds for it:
*
*Split the query in several queries sending each time less then <2100 parameters for the IN statement.
*Insert all the parameters in a special DB Table and then perform your query against that table.
For example, you can create a temporary table, insert there more then 2100 parameters and then JOIN your table with this temporary table.
CREATE TABLE #temptable (id int);
INSERT INTO #temptable (id) VALUES (1), (2), (3)
SELECT * FROM YourTable yt INNER JOIN #temptable tt ON yt.id = tt.id
A: I had the same issue, what I did is, removed all the entities from the model and then added them back to model and it's worked. | unknown | |
d18425 | test | In the first example, since the function uses self (which is set to a reference to the new instance) rather than this, no matter how the function is called/bound, it would always correctly set its own message observable.
In the second example, when binding normally to the function like data-bind="click: eatSomething", you would get the same result. Knockout calls the function with the value of this equal to the current data.
If you had a scenario where you needed to call the function from a different context (maybe your view model has a child object that you are using with or a template against). then you might use a binding like data-bind="click: $parent.eatSomething". KO would still call the function with this equal to the current data (which would not be $parent), so you would have an issue.
One advantage of putting the function on the prototype though, is that if you created many instances of HomeViewModel they would all share the same eatSomething function through their prototype, rather than each instance getting its own copy of the eatSomething function. That may not be a concern in your scenario, as you may only have one HomeViewModel.
You can ensure that the context is correct by calling it like: data-bind="click: $parent.eatSomething.bind($parent). Using this call, would create a new wrapper function that calls the original with the appropriate context (value of this). Alternatively, you could bind it in the view model as well to keep the binding cleaner. Either way, you do lose some of the value of putting it on the prototype, as you are creating wrapper functions for each instance anyways. The "guts" of the function would only exist once on the prototype though at least.
I tend to use prototypes in my code, but there is no doubt that using the self technique (or something like the revealing module pattern) can reduce your concern with the value of this. | unknown | |
d18426 | test | Looks like you have the basic idea, but your code is all over the place.
Try something like:
search_name = raw_input('Please enter the actor to search for: ')
actors = ['Idris Elba', 'Dwayne Johnson', 'Mel Brooks']
if search_name in actors:
print search_name + 'is in the movie!'
else:
print search_name + 'is NOT in the movie!'
If you want to continue asking until the input is a name in the list, use a loop:
search_name = raw_input('Please enter the actor to search for: ')
actors = ['Idris Elba', 'Dwayne Johnson', 'Mel Brooks']
while search_name not in actors:
print search_name + 'is NOT in the movie!'
search_name = raw_input('Please enter a different actor's name:')
print search_name + 'is in the movie!' | unknown | |
d18427 | test | Giving this answer for completeness - even though your case was different.
I've once named my django project test. Well, django was importing python module test - which is a module for regression testing and has nothing to do with my project.
This error will occur if python finds another module with the same name as your django project. Name your project in a distinct way, or prepend the path of the parent directory of your application to sys.path.
A: I think mod_python is looking for settings in the MKSearch module which doesn't exist in side the /home/user/django/MyDjangoApp directory. Try adding the parent dir to the PythonPath directive as below:
<Location "/MyDjangoApp/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE MKSearch.settings
PythonOption django.root /MyDjangoApp
PythonPath "['/home/user/django/', '/home/user/django/MyDjangoApp,'/var/www'] + sys.path"
PythonDebug On
</Location>
Or remove the module name from the DJANGO_SETTINGS_MODULE env var as below:
<Location "/MyDjangoApp/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE settings
PythonOption django.root /MyDjangoApp
PythonPath "['/home/user/django/MyDjangoApp,'/var/www'] + sys.path"
PythonDebug On
</Location>
A: The following example, located in my Apache configuration file, works. I found it very hard to get mod_python to work despite good answers from folks. For the most part, the comments I received all said to use mod_wsgi, instead of mod_python.
Comments I've seen including from the Boston Python Meetup all concur mod_wsgi is easier to use. In my case on Red Hat EL 5 WS, changing from mod_python is not practical.
<Location />
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE settings
PythonOption django.root /home/amr/django/amr
PythonPath "['/home/amr/django', '/home/amr/django/amr', '/usr/local/lib
/site-packages/django'] + sys.path"
PythonDebug On
</Location> | unknown | |
d18428 | test | <?php
$fruits = array("d" => 4, "a" => 3, "b" => 2, "c" => 1);
asort($fruits, SORT_NUMERIC);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?> | unknown | |
d18429 | test | It's actually unclear what your problem is. If you want the form submit to be idempotent/bookmarkable, then just remove method="post" from the HTML <form> element if you want the request to be bookmarkable. Don't forget to remove doPost() method from the servlet as well.
Or if you actually want to let the form submit to a different servlet, then just create another servlet, register/map it the same way but on a bit different URL pattern and finally change the action URL of the HTML <form> element. | unknown | |
d18430 | test | I faced with the same problem before and when I add my ip adress to proxy then try again to do Get latest in TFS. Its worked!!!. Have a nice coding :) | unknown | |
d18431 | test | this.name represents the instance variable while the name variable is a parameter that is in the scope of the function (constructor in this case).
With this assignment, the value of the local variable is assigned to the instance variable.
A: This is not a javascript thing, it's an OOP thing. You want to leave the properties of an object isolated from other scopes.
var Animal = function(name) {
this.name = name;
};
var name = "foo";
var dog = new Animal("bar");
// shows "foo"
console.log(name);
// shows "bar"
console.log(dog.name);
A: As use of the pronoun “he.” We could have written this: “John is running fast because John is trying to catch the train.” We don’t reuse “John” in this manner, . In a similar graceful manner, in JavaScript, we use the this keyword as a shortcut, a referent; it refers to an object; that is, the subject in context, or the subject of the executing code. Consider this example:
var person = {
firstName: "Penelope",
lastName: "Barrymore",
fullName: function ()
// Notice we use "this" just as we used "he" in the example sentence earlier?:
console.log(this.firstName + " " + this.lastName);
// We could have also written this:
console.log(person.firstName + " " + person.lastName);
}
}
A: Well... you are working with an object constructor and prototype not just a function with two parameters where example:
function Animals(pet1, pet2) {
var pets = "first pet " + pet1 + " second pet " + pet2;
console.log(pets);
}
Animals("Tiger", "Lion");
so referencing to your parameter as 'this.name' is a prototype of the sayName() if you know what i mean.
FOR MORE. | unknown | |
d18432 | test | Overriding the OnPaint() method of a control is normally recommended for custom drawing of THAT control, not of drawing another control. What you are trying to do in your code is to attach the Paint event of the hosting form to the OnPaint() method of your control. That's probably not working.
As you can read in the MSDN documentation, the Paint event of a control is raised by the OnPaint() method. You can attach a custom event handler:
hostControl.FindForm().Paint += new PaintEventHandler(Form_Paint);
private void Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
...
}
In the PaintEventArgs argument you will get the required parameters for drawing. | unknown | |
d18433 | test | We found the same problem. There is one more report here:
https://mail-archives.apache.org/mod_mbox/subversion-users/201201.mbox/%[email protected]%3E
Basically, if you have different ways to refer to the subversion server, for example, server and server.domain.com, you checkout a working copy from "server", but in the Maven root POM the SVN configuration points to server.domain.com, you will find this error.
You have to enter the same name in the elemento in the root POM, and in the svn command used to check-out a project from the Subversion sever. | unknown | |
d18434 | test | I used 'event-stream' for processing of ~200kB files contain JSONs inside and got the issue when 'end' Event was never called when using 'event-stream', if I put .on('end') after event-stream pipes. But when I put it Before pipes - everything works just ok!
stream.on('end',function () {
console.log("This is the End, my friend");
}).on('error',function (err) {
console.error(err);
}).pipe(es.split())
.pipe(es.map(function (line, cb) {
//Do anything you want here with JSON of line
return cb();
}));
nodejs, event-stream
A: Sorted. Save the read stream in a variable and pipe an on('end', function) on that read stream. | unknown | |
d18435 | test | Here's the solution that you looking for:
protected void lnk_Click(object sender, EventArgs e)
{
LinkButton lnk = sender as LinkButton;
Label Label1 = lnk.NamingContainer.FindControl("Label1") as Label;
if (Label1.Text == "Alert1")
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert1.aspx','_blank');", true);
}
else if (Label1.Text == "Alert2")
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert2.aspx','_blank');", true);
}
}
Also, Give unique names to controls inside GridView.
A: Replace '_newtab' to '_blank'
Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert1.aspx','_blank');", true);
A: You need to set target attribute to _blank
Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert1.aspx','_blank');", true);
The second argument in window.open is to specify whether you want to open page in new tab or in existing tab. So you need to set it to _blank to open page in new tab
A: set CommandName to alert type and access it in click event
<asp:LinkButton ID="lnk" runat="server" Text="Click" OnClick="lnk_Click" CommandArgument='<%# Bind("Alert_Type") %>'>
</asp:LinkButton>
Click event
protected void lnk_Click(object sender, EventArgs e)
{
string alerttype=e.CommandArgument.ToString();
Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open("+alerttype+"'.aspx','_newtab');", true);
} | unknown | |
d18436 | test | C99, 7.1.2/4:
[...] If
used, a header shall be included outside of any external declaration or definition, and it
shall first be included before the first reference to any of the functions or objects it
declares, or to any of the types or macros it defines.
4/2:
If a ‘‘shall’’ or ‘‘shall not’’ requirement that appears outside of a constraint is violated, the
behavior is undefined.
6.9/4:
As discussed in 5.1.1.1, the unit of program text after preprocessing is a translation unit,
which consists of a sequence of external declarations. These are described as ‘‘external’’
because they appear outside any function (and hence have file scope).
So I think this is undefined behavior.
A: In C++11: 17.6.2.2/3:
A translation unit shall include a header only outside of any external declaration or definition, and shall
include the header lexically before the first reference in that translation unit to any of the entities declared
in that header.
main() is extern, so is not a proper context for include.
A: Try including the header file outside of the main method. Like this.
#include <stdio.h>
int main()
{
printf("hello , world \n");
return 0;
} | unknown | |
d18437 | test | jQuery allows you to work with fragments of a page (as well as XML).
Once you've used the .html method to assign the HTML of an element to a variable, you can operate on the HTML like so:
var html, withoutTitle;
html = $('#someDiv').html();
withoutTitle = $(html).remove('#title').html();
$('#someOtherDiv').html(withoutTitle);
I haven't tested this code, so you may need to tweak it a bit to suit your purposes. | unknown | |
d18438 | test | You seem to have run cache:clear as root user without the --no-warmup flag.
Now symfony has warmed the cache after clearing it using the root account which would result in the newly created cache files being owned by your root user. Depending on your umask the webserver-user now might not have r+w access to these files.
Make sure your webserver-user / cgi-user has read and write access to your cache folder or give the ownership back to this user.
sudo chown webserver_user:webserver_group -R app/cache
sudo chmod 770 -R app/cache # or use acl to permit read/write to your webserver-user
A: Make sure the permissions for the app/cache and app/logs are set correctly for both the web server user and the CLI user.
The Symfony Book has instructions on how to do it.
If your OS supportschmod +a (OSX) you can do the following:
$ rm -rf app/cache/*
$ rm -rf app/logs/*
$ sudo chmod +a "www-data allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
$ sudo chmod +a "`whoami` allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
If your OS supports setfacl (Ubuntu, for example) and ACL support is enabled, you can do the following:
$ sudo setfacl -R -m u:www-data:rwX -m u:`whoami`:rwX app/cache app/logs
$ sudo setfacl -dR -m u:www-data:rwx -m u:`whoami`:rwx app/cache app/logs
Note: both examples assume that the username for the web server user is www-data | unknown | |
d18439 | test | DISCLAIMER: Following answer is purely speculative
*
*I think key_file param of SSHHook is meant for this purpose
*And the idiomatic way to supply it is to pass it's name via extra args in Airflow Connection entry (web UI)
*
*Of course when neither key_file nor credentials are provided, then SSHHook falls back to identityfile to initialize paramiko client.
*Also have a look how SFTPHook is handling this | unknown | |
d18440 | test | When you have a generic class in C#, you have to provide the type parameter. You could write another class that would not be generic. If there is any logic, that should be shared between generic and non-generic classes, you can move that logic to one more new class.
A: Inherit from a non-generic base class:
internal abstract class AutoRegisterThreadBase { }
internal class AutoRegisterThread<T> : AutoRegisterThreadBase
where T: AutoRegisterAbstract
{
field1....
method1...
}
Your main form field can now be of type AutoRegisterThreadBase
Note, if desired, the non-generic parent class can have the same name as the generic class; in your case, AutoRegisterThread.
EDIT: Extended example, with usage:
internal abstract class AutoRegisterThreadBase { /* Leave empty, or put methods that don't depend on typeof(T) */ }
internal abstract class AutoRegisterAbstract { /* Can have whatever code you need */ }
internal class AutoRegisterThread<T> : AutoRegisterThreadBase
where T : AutoRegisterAbstract
{
private int someField;
public void SomeMethod() { }
}
internal class AutoRegisterWidget : AutoRegisterAbstract { /* An implementation of AutoRegisterAbstract; put any relevant code here */ }
// A type that stores an AutoRegisterThread<T> (as an AutoRegisterThreadBase)
class SomeType
{
public AutoRegisterThreadBase MyAutoRegisterThread { get; set; }
}
// Your code that uses/calls the above types
class Program
{
static void Main(string[] args)
{
var someType = new SomeType();
// Any sub-class of AutoRegisterThreadBase, including generic classes, is valid
someType.MyAutoRegisterThread = new AutoRegisterThread<AutoRegisterWidget>();
// You can then get a local reference to that type
// in the code that's created it - since you know the type here
var localRefToMyAutoRegisterThread = someType.MyAutoRegisterThread as AutoRegisterThread<AutoRegisterWidget>;
localRefToMyAutoRegisterThread.SomeMethod();
}
} | unknown | |
d18441 | test | I would create a g element for entry in myData:
groups = d3.select('body').append('svg')
.selectAll('g').data(myData).enter()
.append('g');
and append shapes to those group elements individually:
groups.append('rect')
groups.append('circle')
A: Perhaps, what you want here is the .datum() function in d3. One of it's specific use-cases is to bind the same datum to multiple DOM elments (i.e. bind one datum to an entire d3 selection).
For example, d3.selectAll('div').datum({foo: 'bar'}) would bind the same object {foo: 'bar'} to all of the <div>...</div> elements currently existing on the document.
Quoting directly from https://github.com/mbostock/d3/wiki/Selections#datum
selection.datum([value])...If value is specified, sets the element's
bound data to the specified value on all selected elements. If value
is a constant, all elements are given the same data [sic]
(Somewhat ironically, he refers to the constant datum as "data" in the explanation of the .datum() function!)
However, this is a literal answer to your question; there may be a more design-oriented answer to your question which might explain the "conventional" d3-way of handling your overall objective... In which case, you should probably consult some tutorials like
http://mbostock.github.io/d3/tutorial/circle.html
A: TLDR;
Use Selection.data "key" argument function.
A key function may be specified to control which datum is assigned to which element
«This function is evaluated for each selected element, in order, […] The key function is then also evaluated for each new datum in data, […] the returned string is the datum’s key.
(Search «If a key function is not specified…» paragraph)
More details …
D3 binds data to elements. By default is uses the «join-by-index» method (first found element maps to datum at index 0 and so forth…). If join-by-index is not enough to appropriately identify elements, Selection.data "key" should be used in order for D3 to appropriately synchronise input dataset during rendering phases: "update" (result of data() method call), "creation" enter selection, "removal" (exit selection).
Let's say we need to draw some legend, given the following dataset …
const dataSet = [
[ 15, "#440154" ]
[ 238.58, "#414487" ]
// ...
]
we first decide to draw the coloured square using <rect> element.
const updateSelection = d3.select('rect').data(dataSet);
// join-by-index strategy is enough here so there is no need to supply the key fn arg
// Key function could be `d => d[0]` (given data source cannot produce two entries
// with value at index 0 being the same, uniqness is garanteed)
updateSelection.enter()
.append('rect')
.attr('width', 15).attr('height', 15)
.merge(updateSelection)
.style('fill', d => d[1])
;
// Dispose outdated elements
updateSelection.exit().remove();
We now need a <text> element to be drawn for each given datum to visually expose numeric values. Keeping join-by-index (default) strategy would cause D3 to first draw both rect and text elements but since there can only be a single element bound to a specific datum key, only the first found element will be considered upon update phase and any other element having same datum key will end up in the exit selection and removed from the DOM as soon as the Selection remove method is called.
… If multiple elements have the same key, the duplicate elements are put into the exit selection …
A solution is to concatenate the numeric value with the element nodeName.
// Notice how the selector has changed
const updateSelection = d3.select('rect, text').data(dataSet, function(d) {
// Concatenate the numeric value with the element nodeName
return `${d[0]}:${this.nodeName}`;
})
, enterSelection = updateSelection.enter()
;
// Add rect element
enterSelection
.append('rect').attr('width', 15).attr('height', 15)
.merge(updateSelection)
.style('fill', d => d[1])
;
// Add text label
enterSelection
.append('text')
.merge(updateSelection)
.text(d => d[0])
;
// Dispose outdated elements
updateSelection.exit().remove(); | unknown | |
d18442 | test | A couple of things here.
*
*Zip and GZip are different.. If you are doing a gzip test, your file should have the extension .gz, not .zip
*To properly append "test" to the end of the gzip data, you should first use a GZIPInputStream to read in from the file, then tack "test" onto the uncompressed text, and then send it back out through GZipOutputStream | unknown | |
d18443 | test | The problem is that your class is called Math, so the compiler is looking for a method round() on your class, which doesn't exist.
Rename your class to MyJavaLesson or somesuch, and then the compiler will know you want methods from java.lang.Math.
You should never name your own classes with the same name as a class from anything under the java package, because it usually leads to confusion (as it has here).
A: See if replacing double doubleValue to float doubleValue helps you.The Math.round() functions takes float as its arguements.
Dont forget to add f after the float number assignment i.e float doubleValue = -3.999f.
A: The main problem here is that this class is named Math (at the very top: public class Math {). Which overwrites the Math toolkit provided by java. If you name your class and file to something else it should be fine.
p.s. generally by convention, we don't use capital letters in class and file names; to avoid these from happening.
A: Thanks everyone for the help on this. Also, not sure if asking this question is allowed on this forum but was just curious how others learned Java? I am considering take a class at a community college but wondering if I am just better off learning from Lynda.com, Udemy, and Coursera. | unknown | |
d18444 | test | You cannot directly write the object and expect it to store everything properly when you have members that don't have a fixed size.
If it were char array you could use this way.
Given this situation, I would manually write the details, like length of username first, then write characters in username so that while reading I can read the length of username and read that number of characters from file. | unknown | |
d18445 | test | You're looking for the function minimumBy in the Data.List module. It's type is
minimumBy :: (a -> a -> Ordering) -> [a] -> a
In your case, it would also be useful to import comparing from the Data.Ord module, which has the type
comparing :: Ord a => (b -> a) -> b -> b -> Ordering
And this lets you give it an "accessor" function to create an ordering. So in this case you can do
minimumSnd :: [(String, Int)] -> (String, Int)
minimumSnd = minimumBy (comparing ???)
I'll let you fill in the ???, it should be quite easy at this point. What would your accessor function passed to comparing be for your type?
If you wanted to write a custom function for this instead, I would suggest using the fold pattern. We can also take this opportunity to make it safer by returning a Maybe type, and more general by not requiring it to be a list of (String, Int):
minimumSnd :: (Ord b) => [(a, b)] -> Maybe (a, b)
minimumSnd = go Nothing
where
-- If the list is empty, just return our accumulator
go acc [] = acc
-- If we haven't found a minimum yet, grab the first element and use that
go Nothing (x:xs) = go (Just x) xs
-- If we have a minimum already, compare it to the next element
go (Just currentMin) (x:xs)
-- If it's <= our current min, use it
| snd x <= snd currentMin = go (Just x) xs
-- otherwise keep our current min and check the rest of the list
| otherwise = go (Just currentMin) xs
A: Try this:
foldl1 (\acc x -> if snd x < snd acc then x else acc) <your list>
You fold your list by comparing the current element of the list to the next one. If the second value of the next element if smaller than the value of the current element, it is the new value for the accumulator. Else the accumulator stays the same. This process is repeated until the entire list has been traversed.
A: I am Haskell beginner but I wanted to find a working solution anyway and came up with:
minTup' :: [(String, Int)] -> Maybe (String, Int) -> (String, Int)
minTup' [] (Just x)= x
minTup' (x:xs) Nothing = minTup' xs (Just x)
minTup' ((s,n):xs) (Just (s',n'))
| n < n' = minTup' xs (Just (s,n))
| otherwise = minTup' xs (Just (s',n'))
minTup :: [(String, Int)] -> (String, Int)
minTup [] = error "Need a list of (String,Int)"
minTup x = minTup' x Nothing
main = do
print $ minTup [("CHURCH",262),("PENCIL",311),("FLOUR",175),("FOREST",405),("CLASS",105)]
print $ minTup [("CHURCH",262)]
print $ minTup [] | unknown | |
d18446 | test | You can use following command for extract all tar.gz files in directory in unix
find . -name 'alcatelS*.tar.gz' -exec tar -xvf {} \;
A: -xfv is wrong since v is being referred as the file instead. Also, tar can't accept multiple files to extract at once. Perhaps -M can be used but it's a little stubborn when I tried it. Also, it would be difficult to pass multiple arguments that were extracted from pathname expansion i.e. you have to do tar -xvM -f file1.tar -f file2.tar.
Do this instead:
for F in alcatelS*.tar; do
tar -xvf "$F"
done
Or one-line: (EDIT: Sorry that -is- a "one"-liner but I find that not technically a real one-liner, just a condensed one so I should haven't referred to that as a one-liner. Avoid the wrong convention.)
for F in alcatelS*.tar; do tar -xvf "$F"; done
A: Following is my favorite way to untar multiple tar files:
ls *tar.gz | xargs -n1 tar xvf
A: Can be done in one line:
cat *.tar | tar -xvf - -i | unknown | |
d18447 | test | Problem was with JDK/JRE. They were installed separately. Deleted them and installed from a bundle. Although they were the same version, project building kept on crashing. | unknown | |
d18448 | test | d.find_element("xpath",'//*[@id="firstName"]').send_keys("amine")
d.find_element("id","lastName").send_keys("wannes")
A: To send a character sequence to the <input> field you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:
*
*Using CSS_SELECTOR:
driver.get('https://demoqa.com/automation-practice-form')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#firstName"))).send_keys("hamdi")
*Using XPATH:
driver.get('https://demoqa.com/automation-practice-form')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='firstName']"))).send_keys("hamdi")
*Note: You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
*Browser Snapshot: | unknown | |
d18449 | test | As you can see in the stack trace, exception thrown during the migration step.
This happens because you adding not null column to your table, which generally impossible. SQLite don't know what value should be set to role_id for records that already in the table, so it prevents you from this operation.
You can either add default value to role_id, or move it to initial migration. | unknown | |
d18450 | test | If I may suggest a different approach: derive from your thread class and make a virtual Run() function.
The reason is that although it is possible to call a function pointer from the static thread entry function, you face problem after problem. For example, you can solve the problem of having the right function signature with templates and variadic parameters, but it is not of much avail, because the entry function won't know what to send to your function.
On the other hand, deriving from Thread is easy and straightforward. You put into the contructor whatever the thread needs to know. Or, optionally, you can call any number of other functions and set any number of members before you create the thread. Once you do create the thread, the static thread entry function will simply call the virtual Run function. Now... the Run function is part of the thread object, so it knows anything the class knows -- no problem.
The extra overhead of a single virtual function call and of one pointer in the vtable is also ridiculously small compared to how easy it is.
A: I suggest you look at the treatment of this topic in the C++ FAQ Lite. In short, pointers to member functions are problematic, but there are several work-arounds, as well as a number of reasons why they should be avoided for certain purposes.
A: Finally I decided to use a stub function as suggested in this thread:
Create thread is not accepting the member function
thanks everbody :) | unknown | |
d18451 | test | When using file functions to access remote files (paths starting with http:// and similar protocols) it only works if the php.ini setting allow_url_fopen is enabled.
Additionally, you have no influence on the request sent. Using CURL is suggested when dealing with remote files.
If it's a local file, ensure that you have access to the file - you can check that with is_readable($filename) - and that it's within your open_basedir restriction if one is set (usually to your document root in shared hosting environments).
Additionally, enable errors when debugging problems:
ini_set('display_errors', 'on');
error_reporting(E_ALL); | unknown | |
d18452 | test | "on-link" doesn't equal 10.0.0.138. It means that the destination network is directly attached to the interface - meaning traffic that matches this route entry will trigger an ARP request that should be sent from this link to resolve the destination IP directly (not the gateway 10.0.0.138).
This is also called "glean adjacency".
The 10.0.0.9 route instructs packets with destination IP 10.0.0.9 to be sent to the CPU (AKA punt adjacency).
127.0.0.0/24 network is for internal communication within the machine.
224.0.0.0/4 is for multicast traffic. | unknown | |
d18453 | test | Your input is very strange. Usually, I see matched square brackets.
That aside, what you want is something like this:
# This assumes you have Perl 5.10 or autodie installed: failures in open, readline,
# or close will die automatically
use autodie;
# chunks of your input to ignore, see below...
my %ignorables = map { $_ => 1 } qw(
[notice mpmstats: rdy bsy rd wr ka log dns cls bsy: in
);
# 3-arg open is safer than 2, lexical my $fh better than a global FH glob
open my $error_fh, '<', 'error_log';
# Iterates over the lines in the file, putting each into $_
while (<$error_fh>) {
# Only worry about the lines containing [notice
if (/\[notice/) {
# Split the line into fields, separated by spaces, skip the %ignorables
my @line = grep { not defined $ignorables{$_} } split /\s+/;
# More cleanup
s/^\[//g for @line; # remove [ from [foo
# Output the line
print join(",", @line);
# Assuming the second line always has "in" in it,
# but this could be whatever condition that fits your data...
if (/\bin\b/) { # \b matches word edges, e.g., avoids matching "glint"
print "\n";
}
else {
print ",";
}
}
}
close $error_fh;
I did not compile this, so I can't guarantee that I didn't typo somewhere.
The key here is that you do the first print without a newline, but end with comma. Then, add the newline when you detect that this is the second line.
You could instead declare @line outside the loop and use it to accumulate the fields until you need to output them with the newline on the end.
A: One way using perl. It omits lines that don't contain [notice. For each line matching it increments a variable and saves different fields in an array depending if it is odd or even (first ocurrence of [notice or the second one).
perl -ane '
next unless $F[5] eq q|[notice|;
++$notice;
if ( $notice % 2 != 0 ) {
push @data, @F[0..4, 8, 10, 12, 14, 16, 18, 20, 22];
next unless eof;
}
push @data, (eof) ? 0 : $F[8];
$data[0] =~ s/\A\[//;
printf qq|%s\n|, join q|,|, @data;
@data = ();
' infile
Assuming infile has content of your question, output would be:
Wed,Jun,13,01:41:34,2012,786,14,0,11,3,0,0,0,11 | unknown | |
d18454 | test | You can't initialize a member object using that syntax. If your compiler supports C++11's uniform initialization syntax or in-class initialization of member variables you can do this:
class QtGlass : public QFrame {
Q_OBJECT
...
protected:
Figure the_figure{'L'};
// or
Figure the_figure = 'L'; // works because Figure(char) is not explicit
...
};
Otherwise you need to initialize the object within QtGlass' constructor initializer list
class QtGlass : public QFrame {
Q_OBJECT
...
protected:
Figure the_figure;
...
};
// in QtGlass.cpp
QtGlass::QtGlass(QWidget *parent)
: QFrame(parent)
, the_figure('L')
{}
A: You are trying to create an instance of Figure in the definition of QtGlass which is not allowed. You have to instantiate the_figure in the constructor of QtGlass:
class QtGlass : public QFrame {
Q_OBJECT
QtGlass() {
the_figure = Figure('L');
};
...
protected:
Figure the_figure;
...
}; | unknown | |
d18455 | test | On most 32-bit CPUs, 64-bit division must be implemented with a slow library function.
To prevent the compiler from generating unobviously slow code, Linux does not implement these functions.
If you want to do 64-bit divisions, you have to do them explicitly.
Use do_div() from <asm/div64.h>. | unknown | |
d18456 | test | I think this is using BackdropFilter
class GlassMorphism extends StatelessWidget {
GlassMorphism({
Key? key,
required this.blur,
required this.opacity,
required this.child,
required this.color,
BorderRadius? borderRadius,
}) : _borderRadius = borderRadius ?? BorderRadius.circular(12),
super(key: key);
final Color color;
final double blur;
final double opacity;
final Widget child;
final BorderRadius _borderRadius;
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: _borderRadius,
child: BackdropFilter(
filter: ImageFilter.blur(
sigmaX: blur,
sigmaY: blur,
),
child: Container(
decoration: BoxDecoration(
color: color.withOpacity(opacity),
borderRadius: _borderRadius,
border: Border.all(
color: color,
),
),
child: child,
),
),
);
}
}
And using it
class GSX extends StatelessWidget {
const GSX({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: LayoutBuilder(
builder: (context, constraints) => Container(
width: constraints.maxWidth,
height: constraints.maxHeight,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.amber.shade100,
Colors.blue.shade100,
],
),
),
child: Column(
children: [
GlassMorphism(
color: Colors.white,
blur: 1,
opacity: .4,
child: Container(height: 200, width: 100, child: Text("AA")),
),
],
),
),
),
);
}
}
A: return Container(
decoration: const BoxDecoration(
gradient: LinearGradient(colors:[Color(0xFFd9a7c7),Color(0xFF30E8BF),]),
),
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(title: const Text("TEST")),
body: SafeArea(
child: Container(
margin:
const EdgeInsets.symmetric(horizontal: 20.0, vertical: 30.0),
alignment: Alignment.center,
width: double.infinity,
height: 200,
decoration: BoxDecoration(
color: const Color(0xFFFFFFFF).withOpacity(0.5),
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
border: Border.all(
color: const Color(0xFFFFFFFF),
width: 1.0,
style: BorderStyle.solid),
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.black12.withOpacity(0.1),
offset: Offset(2.0, 4.0),
blurRadius: 6.0,
//blurStyle: BlurStyle.outer
),
],
),
),
),
),
);
A: You can create a custom box shadow like this:
class CustomBoxShadow extends BoxShadow {
final BlurStyle blurStyle;
const CustomBoxShadow({
super.color,
super.offset,
super.blurRadius,
this.blurStyle = BlurStyle.normal,
});
@override
Paint toPaint() {
final Paint result = Paint()
..color = color
..maskFilter = MaskFilter.blur(blurStyle, blurSigma);
assert(() {
if (debugDisableShadows) {
result.maskFilter = null;
}
return true;
}());
return result;
}
}
and then use it like this:
CustomBoxShadow(
blurRadius: 10,
color: Colors.white.withOpacity(.3),
offset: const Offset(0, 5),
blurStyle: BlurStyle.outer, //<--- this will give shadow outwards
), | unknown | |
d18457 | test | input is willing to prompt your
"Enter your choice from ===> Rock , Paper or Scissor"
on its own but you also put a print there. So first print prints what you give it, and then its return value (print returns None) is passed to input and input then prompts this None (if you notice, it's on a newline actually because your print gave a newline).
So you dont need print there:
user_action = str(input("Enter your choice from ===> Rock , Paper or Scissor")).lower()
More, you don't need to cast str the input's result because it's always a string (if succeeds), so
user_action = input("Enter your choice from ===> Rock, Paper or Scissors: ").lower()
A: I copied this myself and got the NONE to go away by moving the input().lower() out of the print statement
print("Enter your choice from ===> Rock , Paper or Scissor")
user_action = str(input()).lower()
comp_actions = str(random.choice(comp_choices)).lower()
A: Simply remove the print() from your input:
str(input("Enter your choice from ===> Rock , Paper or Scissor\n")).lower()
A: whenever you see none its because your using print twice
change this:
user_action = str(input(print("Enter your choice from ===> Rock , Paper or Scissor"))).lower()
to this:
user_action = str(input("Enter your choice from ===> Rock , Paper or Scissor")).lower()
you are saying to print the function and then print the string that will take and input, which is in your function so your saying print twice, when you only need to say print the function and since the string that will take and input is in your function it will print it out. | unknown | |
d18458 | test | Another approach:
merge into
tester
using (
select 1 id,'0123456785' employee_phone_number from dual union all
select 2 id,'0123456786' employee_phone_number from dual) new_values
on (
tester.id = new_values.id)
when matched then update
set employee_phone_number = new_values.employee_phone_number;
More words, but allows the values to be specified in only one place and extends to allow inserts where the id does not already exist.
http://sqlfiddle.com/#!4/8fc86/3
A: Try this instead:
update Tester
set employee_phone_number = CASE WHEN employee_id = 1 THEN 0789456123
WHEN employee_id = 2 THEN 0789456321
END
where employee_id in (1,2); | unknown | |
d18459 | test | You're using different CRT settings (static vs DLL) for your project and the library. Make sure to (re)build both of them using the same option, either /MD[d] or /MT[d].
A: There are many possible causes for this linker error. First adress to check is MSDN: https://msdn.microsoft.com/en-us/library/ts7eyw4s.aspx
What is $(WXWIN) and how does it differ from $(WXDIR284)? It seems, you include wxWidgets path twice... | unknown | |
d18460 | test | This is similar to the flyweight pattern detailed in the GoF patterns book (see edit below). Object pools have gone out of favour in a "normal" virtual machine due to the advances made in reducing the object creation, synchronization and GC overhead. However, these have certainly been around for a long time and it's certainly fine to try them to see if they help!
Certainly Object Pools are still in use for objects which have a very expensive creation overhead when compared with the pooling overheads mentioned above (database connections being one obvious example).
Only a test will tell you whether the pooling approach works for you on your target platforms!
EDIT - I took the OP "re-used wherever possible" to mean that the objects were immutable. Of course this might not be the case and the flyweight pattern is really about immutable objects being shared (Enums being one example of a flyweight). A mutable (read: unshareable) object is not a candidate for the flyweight pattern but is (of course) for an object pool.
A: Normally, I'd say this was a job for tuning the GC parameters of the VM, the reduce the spiky-ness, but for mobile apps that isn't really an option. So if the JVms you are using cannot have their GC behavioure modified, then old-fashioned object pooling may be the best solution.
The Apache Commons Pool library is good for that, although if this is a mobile app, then you may not want the library dependency overhead.
A: Actually, that graph looks pretty healthy to me. The GC is reclaiming lots of objects and the memory is then returning to the same base level. Empirically, this means that the GC is working efficiently.
The problem with object pooling is that it makes your app slower, more complicated and potentially more buggy. What is more, it can actually make each GC run take longer. (All of the "idle" objects in the pool are non-garbage and need to be marked, etc by the GC.)
A: Does J2ME have a generational garbage collector? If so it does many small, fast, collections and thus the pauses are reduced. You could try reducing the eden memory space (the small memory space) to increase the frequency and reduce the latency for collections and thus reduce the pauses.
Although, come to think of it, my guess is that you can't adjust gc behaviour because everything probably runs in the same VM (just a guess here).
A: You could check out this link describing enhancements to the Concurrent Mark Sweep collector, although I'm not sure it's available for J2ME. In particular note:
"The concurrent mark sweep collector, also known as the concurrent collector or CMS, is targeted at applications that are sensitive to garbage collection pauses."
... "In JDK 6, the CMS collector can optionally perform these collections concurrently, to avoid a lengthy pause in response to a System.gc() or Runtime.getRuntime().gc() call. To enable this feature, add the option"
-XX:+ExplicitGCInvokesConcurrent
A: Check out this link. In particular:
Just to list a few of the problems
object pools create: first, an unused
object takes up memory space for no
reason; the GC must process the unused
objects as well, detaining it on
useless objects for no reason; and in
order to fetch an object from the
object pool a synchronization is
usually required which is much slower
than the asynchronous allocation
available natively.
A: You're talking about a pool of reusable object instances.
class MyObjectPool {
List<MyObject> free= new LinkedList<MyObject>();
List<MyObject> inuse= new LinkedList<MyObject>();
public MyObjectPool(int poolsize) {
for( int i= 0; i != poolsize; ++i ) {
MyObject obj= new MyObject();
free.add( obj );
}
}
pubic makeNewObject( ) {
if( free.size() == 0 ) {
MyObject obj= new MyObject();
free.add( obj );
}
MyObject next= free.remove(0);
inuse.add( next );
return next;
}
public freeObject( MyObject obj ) {
inuse.remove( obj );
free.add( obj );
}
}
return in
A: Given that this answer suggests that there is not much scope for tweaking garbage collection itself in J2ME then if GC is an issue the only other option is to look at how you can change your application to improve performance/memory usage. Maybe some of the suggestions in the answer referenced would apply to your application.
As oxbow_lakes says, what you suggest is a standard design pattern. However, as with any optimisation the only way to really know how much it will improve your particular application is by implementing and profiling. | unknown | |
d18461 | test | If you are asking if the Google .net client Library is thread safe. I am pretty sure that it is. It is noted in at least one place in the documentation that it is thread safe.
Google APIs Client Library for .NET
UserCredential is a thread-safe helper class for using an access token
to access protected resources. An access token typically expires after
1 hour, after which you will get an error if you try to use it.
A: It isn't. I've tried writing some code assuming it was, and my code would sometimes randomly crash at the "request.Execute()"s...
I tried using a mutex and so only one thread was using a singleton service at a time: that reduced the crashes but it didn't eliminate them.
Leaving the mutex in, I changed it to a singleton UserCredential and use a new service for each thread and it hasn't crashed since. (I don't know if I need the mutex anymore or not, but the google api calls aren't critical path for my application, I just needed to get the calls out of the main thread.) | unknown | |
d18462 | test | Yes, you are right. It is indeed an anti-pattern within RxJS to chain multiple subscribes.
A more elegant way of chaining these observable calls would be to make use of pipeable operators. In this scenario, the switchMap() operator would suffice.
As stated on the documentation, switchMap() will
Map to observable, complete previous inner observable, emit values.
this.service1.info
.pipe(
switchMap((a) => this.service2.getDetails(a.id)),
switchMap((a) => this.service3.getDetails(a.id)),
// switchMap((a) => this.service4.getDetails(a.id)),
// subsequent chained methods
).subscribe(z => {
// handle the rest when observables are returned
this.doStuff(z);
});
As you can see from the above pipe statement, we only call subscribe() once, and that will return the observable values. That is when we call the doStuff method. | unknown | |
d18463 | test | When you do this:
leaderboard = open("leaderboard.txt", "r+")
leaderboard.write(username + '-' + '{}'.format(score))
you open the leaderboard in read-and-write mode, but it will start writing at the beginning of the file, overwriting whatever is there. If you just want to add new scores to the leaderboard, the simplest would be to open the file in "append" mode "a":
with open("leaderboard.txt", "a") as leaderboard:
leaderboard.write(username + '-' + '{}'.format(score))
Alternatively, you could open the file in "r" mode, then first read all the lines (scores) in a list or dictionary, merge / update them with the current player's new score (e.g. adding to the last score, replacing the last score, or getting the max of the new and last score of that player), and then open the file again in "w" mode and write the updated scores. (Left as an exercise to the reader.)
A: The problem lies within the final few lines of code, where you are writing to the leaderboard.txt file.
Using "r+" indicates that you are updating (reading and writing) the file. Opening a file this way, moves the cursor at the beginning of the file. Therefore any attempt to write to the file will override whatever is already there.
The proper way to do it, is to open the file using "a" (or "a+" if you are planning to read as well). This is append mode and will move the cursor to the end of the file.
Some other general notes:
*
*Use the with-as statement to handle closing the file automatically after you are done.
*Use f-strings as opposed to string concatenation to increase readability
With that in mind, here's the code:
with open("leaderboards.txt", "a") as f:
f.write(f"{username}-{score}")
For more on files, check this question.
For more on f-strings, check this quite extensive overview of them. | unknown | |
d18464 | test | Make your items focusable. It will let you navigate it via dpad. Then you'll need to add your logic to "select" focused item on press. (whatever your select key is) | unknown | |
d18465 | test | This is a little late, but I just googled this exact problem (and ended here).
I found the above solution did fix it, but then it could also be fixed by just adding "using System.Linq;" to the top resolved the issue.
A: If you are certain UsersSet is some kind of a collection of User instances then you can try
var t = from User e in entity.UsersSet
where e.Id == 1
select e; | unknown | |
d18466 | test | If we stay within Ext 3.4.0 boundaries, not reaching back to the plain javascript then you haven't done inheritance correctly. Inheritance is already implemented in Ext, so you do not need to go down to prototypes, creating constructors as instances of parent classes, and so on.
Let's suppose you want to define MyWindow class inheriting from Ext.Window:
Ext.define('MyWindow',{
extend:'Ext.Window'
,method:function(){/* some stuff */}
,closable:false // don't create close box
,closeAction:'hide'
// etc
});
To create an instance:
var win = Ext.create('MyWindow', {
width:800
,height:600
});
win.show();
For more info see Ext.define docs.
A: After days, I've found an answered from Inheritance using prototype / “new”.
The code around my first code block at the bottom part is where I got it wrong.
Cls_MyWindow.prototype = new Ext.Window;
Cls_MyWindow.prototype.constructor = Ext.Window;
The "new" at "new Ext.Window" operator there is my mistake.
*
*Why this.buttons are not the same objects when it is destroy via different way?
Answer:
Because of the new operator, when I created a new instance of Cls_MyWindow total of 2 constructors get called: one of the Cls_MyWindow, another of Ext.Window. Which then cause them to have "their own prototype of buttons" where SaveButton and CancelButton available in Cls_MyWindow as Ext.Button objects and in Ext.Window as a plain Object
Closing Cls_MyWindow with CancelButton -> The buttons can be destroyed in Ext.Window.destroy's way. Closing it with "x" -> The buttons cannot be destroyed.
Solution:
I change my code to
//Cls_MyWindow.prototype = new Ext.Window; the old one
Cls_MyWindow.prototype = Ext.Window.prototype;
Cls_MyWindow.prototype.constructor = Ext.Window;
and everything works perfectly | unknown | |
d18467 | test | logInViewController and signUpViewController are both undefined.
You need to define them with:
let logInViewController = PFLogInViewController()
let signUpViewController = PFSignUpViewController() | unknown | |
d18468 | test | This should work
$IncomeTo = $fetchSubFormDetailData['IncomeTo']; | unknown | |
d18469 | test | Typically you would not store this data in a table, you have all the data needed to generate the report.
SQL Server does not have an easy way to generate a comma-separated list so you will have to use FOR XML PATH to create the list:
;with cte as
(
select id,
studentid,
date,
'#'+subject+';'+grade+';'+convert(varchar(10), date, 101) report
from student
)
-- insert into studentreport
select distinct
studentid,
STUFF(
(SELECT cast(t2.report as varchar(50))
FROM cte t2
where c.StudentId = t2.StudentId
order by t2.date desc
FOR XML PATH (''))
, 1, 0, '') AS report
from cte c;
See SQL Fiddle with Demo (includes an insert into the new table). Give a result:
| ID | STUDENTID | REPORT |
------------------------------------------------------------------------------------
| 10 | 1 | #Biology;B;05/01/2013#Literature;B;03/02/2013#Math;A;02/20/2013 |
| 11 | 2 | #Math;C;03/10/2013#Biology;A;01/01/2013 |
| 12 | 3 | #Biology;A;04/08/2013 |
A: If you are looking to insert the data from 'Students' into 'Student Report', try:
INSERT INTO StudentReport (ID, StudentID, Report)
SELECT ID, StudentID, '#' + subject + ';' + grade + ';' + date AS report
FROM Students
A: Without using CTE.Improve performance.
FOR XML
(select
min(ID) as ID,
StudentId,
STUFF((select ', '+'#'+s2.Subject+';'+s2.Grade+';'+convert(varchar(25),s2.Date)
from student s2
where s2.StudentId=s1.StudentId
FOR XML PATH (''))
,1,2,'') as report
into t
from student s1
group by StudentId)
;
select * from t
Where t would be new Table Name which doesn't exists in DataBase.
SQL Fiddle | unknown | |
d18470 | test | Some good info here:
Careful reading of the MSDN page also shows that duplicate rowversion values are possible if SELECT INTO statements are used improperly. Something to watch out for there.
I would stick with an Identity field in the original data, carried over into the change tracking table that has its own Identity field. | unknown | |
d18471 | test | As @assylias mentioned in the comments the documentation for binarySearch I can quote from it
Returns:
index of the search key, if it is contained in the array within the specified range; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element in the range greater than the key, or toIndex if all elements in the range are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
So basically this is what happens in your attempt to search unsorted array:
{6, 12, 3, 9, 8, 25, 10}
*
*it takes middle element 9 and compares it to your searched element 8, since 8 is lower it takes lower half {6, 12, 3}
*in second step it compares 12 to 8 and since 8 is again lower it takes lower half {6}
*6 doesn't equal 8 and since it's the last element it didn't find what you wanted
*it returns (-(insertion point) - 1) where insertion point is
the index of the first element in the range greater than the key
*in your case that index is 1 since first element greater then 8 is 12 and it's index is 1
*when you put that into equation it returns (-1 - 1) which equals -2
Hope I have answered your question. | unknown | |
d18472 | test | @Azam - There's nothing wrong with the code you posted above. There's no reason why it shouldn't work. I copied the code in the post directly and tested in this jsbin page. See it for yourself.
To keep it as simple as possible this is all I used for the HTML body.
<input type="button" value="Show Comment" onclick="showCommentBox()" />
<div id="commentBox" style="display:none"><br/>
This is the text from the CommentBox Div<br/>
<input type="button" value="Cancel" onclick="cancelComment()" />
</div>
EDIT: After reading some of your other posts, I realized that real reason for the problem is that your are adding the "commentBox" div inside a GridView's ItemTemplate. This causes the creation of the same div with the same ID multiplied by the number of rows in your gridview. Normally, having the same id in multiple HTML elements is bad, but this is what the gridview does.
Here's a workaround that I tested and it works. Change your two functions to this:
function showCommentBox() {
$.currentBox = $("#commentBox");
$.currentBox.addClass("modalPopup");
alert($.currentBox.hasClass("modalPopup"));
$.blockUI( { message: $.currentBox } );
}
function cancelComment() {
alert($.currentBox.hasClass("modalPopup"));
$.unblockUI();
}
Here I'm using a jQuery variable to store a reference to the commentBox DIV and passing that to $.blockUI, in that way the call to $.unblockUI() will work correctly. | unknown | |
d18473 | test | As Set-LocalGroup fails on that, the only other way I can think of is using ADSI:
$group = [ADSI]"WinNT://$env:COMPUTERNAME/Group1,group"
$group.Description.Value = [string]::Empty
$group.CommitChanges()
It's a workaround of course and I agree with iRon you should do a bug report on this.
A: Although there are some AD attributes that requires the Putex method, that doesn't count for the Description attribute. Meaning my assumption in the initial comment to the question is wrong, and it is possible to clear the Description attribute with just the Put method`:
$Name = 'Group1'
New-LocalGroup -Name $Name -Description 'xxx'
$Group = [ADSI]"WinNT://./$Name,group"
$Group.Put('Description', '')
$Group.SetInfo()
Get-LocalGroup -Name $Name
Name Description
---- -----------
Group1
The issue lays purely in the cmdlet parameter definitions. Without going into the C# programming, you might just pull this from the proxy command:
$Command = Get-Command Set-LocalGroup
$MetaData = [System.Management.Automation.CommandMetadata]$Command
$ProxyCommand = [System.Management.Automation.ProxyCommand]::Create($MetaData)
$ProxyCommand
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium', HelpUri='https://go.microsoft.com/fwlink/?LinkId=717979')]
param(
[Parameter(Mandatory=$true)]
[ValidateNotNull()] # <-- Here is the issue
[ValidateLength(0, 48)]
[string]
${Description},
...
In other words, to quick and dirty workaround this with a proxy command:
function SetLocalGroup {
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium', HelpUri='https://go.microsoft.com/fwlink/?LinkId=717979')]
param(
[Parameter(Mandatory=$true)]
[AllowEmptyString()] # <-- Modified
[ValidateLength(0, 48)]
[string]
${Description},
[Parameter(ParameterSetName='InputObject', Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[ValidateNotNull()]
[Microsoft.PowerShell.Commands.LocalGroup]
${InputObject},
[Parameter(ParameterSetName='Default', Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[ValidateNotNull()]
${Name},
[Parameter(ParameterSetName='SecurityIdentifier', Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[ValidateNotNull()]
[System.Security.Principal.SecurityIdentifier]
${SID})
end {
if ($Description) { Set-LocalGroup @PSBoundParameters }
elseif ($Name) {
$Group = [ADSI]"WinNT://./$Name,group"
$Group.Put('Description', '')
$Group.SetInfo()
}
}
}
SetLocalGroup -Name 'Group1' -Description ''
Related bug report: #16049 AllowEmptyString()] for -Description in Set-LocalGroup/SetLocalUser | unknown | |
d18474 | test | If you want to scan in the background, you need to add the ACCESS_BACKGROUND_LOCATION to your permissions (both in the manifest file and at runtime). There are a few other restrictions when it comes to scanning in the background; the articles below do a good job covering them and how to temporarily overcome them:-
*
*Restrictions when scanning background in Android 10
*ACCESS_BACKGROUND_LOCATION permission
*Beacond detection with Android 8
*Background BLE scan in DOZE mode
*Android BLE scan stops after a couple of minutes in the background | unknown | |
d18475 | test | OK, after upgrading to 5.2 the problem's gone. | unknown | |
d18476 | test | You could use setTimeout() which will wait a specified amount of time (ms) then execute the declared function.
Example:
setTimeout(openUrl, 5000); // Wait 5 seconds
function openUrl(){
window.open('http://google.com');
}
To repeat an action on a timer you can use setInterval()
setInterval(openUrl, 5000);
A: check out the setTimeout and setInterval methods for JS
http://www.w3schools.com/js/js_timing.asp
http://www.w3schools.com/jsref/met_win_setinterval.asp
A: You need to call settimeout inside openUrl again to repeat it endlessly | unknown | |
d18477 | test | Android doesn't have any "native" iBeacon capability at all, but you can see iBeacons using my company's open source Android iBeacon Library, which has APIs similar to those native to iOS 7.
In the case of iOS, the CLLocationManagerDelegate gives you access to the didEnterRegion and didExitRegion callbacks that you describe. In the Android iBeacon Library, the equivalent is the MonitorNotifier interface that gives you the same callback methods.
Making these callbacks successfully fire for apps that aren't in the foreground is a little tricky on both iOS and Android. On Android, you need to start a service of your own that runs when the Android device starts up, and bind to the IBeaconManager in that service.
Setting this up isn't super easy, so we developed a Pro Android iBeacon Library that does all this automatically. Examples are here.
EDIT: Both libraries above have been discontinued in favor of the free and open source Android Beacon Library which has all the feature of the pro library described above. | unknown | |
d18478 | test | Looks like you have some mismatched quotes on your problem line:
$html_table .= "<td>' .$row\['$title'\]. '</td>";
You begin with a double quote. Inside double quotes, single quotes cannot be used to terminate the string. Instead, double quotes can only be terminated by double quotes. And the same goes for the single quotes. Meaning, this can be fixed in one of two ways:
$html_table .= "<td>" . $row[$title] . "</td>";
Or:
$html_table .= '<td>' . $row[$title] . '</td>';
Also notice how I removed the quotes from around $title. They are unnecessary and will make PHP do a little more processing than necessary.
Notice how the quotes match now. Be sure, when writing code in your editor, to look at how the syntax is highlighted. You should see that with your original code, the variable and index were inside the string, because it would all be the same color.
If you are relying on variable expansion in double-quoted strings (like echo "Hello $name";), know that accessing string keys of arrays will not work unless they are surrounded with brackets like so:
echo "Hello {$person['FirstName']}";
You can however, use numeric indices like so:
echo "Hello $people[0]";
So with your code, you'd need to do this if you didn't want to end the string and concatenate the value and then begin the string again:
$html_table .= "<td>{$row[$title]}</td>";
However, I find this syntax ugly and it makes PHP do extra processing to find the places where it needs to expand variables. IMHO, use concatenation to avoid all of these problems.
A: Your are not looping correctly. $result is a PDOStatement which you must fetch. Try
foreach( $result->fetchAll() as $row ) {
$html_table .= '<tr>' . "\n";
foreach( $row as $col ) {
$html_table .= '<td>' .$col. '</td>';
}
$html_table .= '</tr>' . "\n";
}
A: this solution seems to be working in my project and allows me to get the column from the query and the records into an html table, hopefully it might help someone else too:
$conn = (...)
$sqlselect = "SELECT name, last, othercol FROM persontable";
// I prepare and execute my query
$stmt = $conn->prepare($sqlselect);
$stmt->execute();
//get full recordset: header and records
$fullrs = $stmt->fetchAll(PDO::FETCH_ASSOC);
//get the first row (column headers) but do not go to next record
$colheaders = current($fullrs)
out = ""; //variable that will hold my table
out .= <table>;
//get my columns headers in the table
foreach($colheaders as $key=>$val)
{
$out .= '<th>'.$key.'</th>';
}
//get my records in the table
foreach($fullrs as $row)
{
$out .= "<tr>";
$out .= '<td>'.$row['name'].'</td>';
$out .= '<td>'.$row['last'].'</td>';
$out .= '<td>'.$row['othercol'].'</td>';
$out .= "</tr>";
}
out .= </table>;
//spit my table out
echo $out; | unknown | |
d18479 | test | Here is a Java project that does image normalization, includes code:
http://www.developer.com/java/other/article.php/3441391/Processing-Image-Pixels-Using-Java-Controlling-Contrast-and-Brightness.htm
When working with images, terms that are used are (root mean square) contrast and brightness instead of variance and average.
(Be sure to specify what kind of contrast definition you use.)
Information in this page seems to hint that it is about histogram equalization.
http://answers.opencv.org/question/6364/fingerprint-matching-in-mobile-devices-android/
Information on wikipedia: http://en.wikipedia.org/wiki/Histogram_equalization#Implementationhint
A: I can help you implementing Image Normalization used in this article Fingerprint Recognition Using Zernike Moments
Try to use Catalano Framework, in next version (1.2), I'll code Image Normalization in the framework.
Zernike Moments is ready like Hu Moments too, if you want to do like this article.
A: So, you dont need to use Histogram to perform this filter.
// Parameters to ImageNormalization
float mean = 160;
float variance = 150;
int width = fastBitmap.getWidth();
int height = fastBitmap.getHeight();
float globalMean = Mean(fastBitmap);
float globalVariance = Variance(fastBitmap, globalMean);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int g = fastBitmap.getGray(i, j);
float common = (float)Math.sqrt((variance * (float)Math.pow(g - globalMean, 2)) / globalVariance);
int n = 0;
if (g > globalMean){
n = (int)(mean + common);
}
else{
n = (int)(mean - common);
}
n = n > 255 ? 255 : n;
n = n < 0 ? 0 : n;
fastBitmap.setGray(i, j, n);
}
}
private float Mean(FastBitmap fb){
int height = fb.getHeight();
int width = fb.getWidth();
float mean = 0;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
mean += fastBitmap.getGray(i, j);
}
}
return mean / (width * height);
}
private float Variance(FastBitmap fb, float mean){
int height = fb.getHeight();
int width = fb.getWidth();
float sum = 0;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
sum += Math.pow(fastBitmap.getGray(i, j) - mean, 2);
}
}
return sum / (float)((width * height) - 1);
} | unknown | |
d18480 | test | you can use this code
List<EmailParam> param = new List<EmailParam>()
{
new EmailParam(){Code ="A01",UserName="Tony"},
new EmailParam(){Code ="B01",UserName="William"},
};
string body = "My name is @UserName and my code is @Code";
var findItem = param.Where(a => a.UserName.Equals("Tony") && a.Code.Equals("A01")).FirstOrDefault();
body = body.Replace("@UserName", findItem.UserName).Replace("@Code", findItem.Code);
A: You can use something similar to following
string body = "My name is {0} and my code is {1}"; //use placeholders instead of @UserName, @Code.
param.UserName = "Tony";
param.Code = "A01";
var convertedBody = String.Format(body, aram.UserName, param.Code); | unknown | |
d18481 | test | I don't think you need the else after the the first if statement.
Something like the following might work,
if left!=null:
inorder(left)
print(current_node.val)
if (right!=null):
inorder(right) | unknown | |
d18482 | test | Instead of using :
<a href="{% url "social:begin" "**google**" %}">
Login with Google
</a>
Use:
< a href="{% url 'social:begin' '**google-oauth2**' %}?next={{ request.path }}">
Login with Google
</a>
Source : official documentation | unknown | |
d18483 | test | If we are using strings, then convert to symbol and evaluate (!!) while we do the assignment with (:=)
library(dplyr)
library(stringr)
col_names <- names(my_data)
for (i in seq_along(col_names)) {
my_data <- my_data %>%
mutate(!! col_names[i] :=
str_extract(!!rlang::sym(col_names[i]), '.+?(?=[a-z])'))
}
In tidyverse, we could do this with across instead of looping with a for loop (dplyr version >= 1.0)
my_data <- my_data %>%
mutate(across(everything(), ~ str_extract(., '.+?(?=[a-z])')))
If the dplyr version is old, use mutate_all
my_data <- my_data %>%
mutate_all(~ str_extract(., '.+?(?=[a-z])')) | unknown | |
d18484 | test | Yes this is correct. In VB style languages, including VBScript, the colon is an end of statement token. It allows you to place several statements on the same line.
A: What you have stated is correct. The purpose of the colon is to combine 2 otherwise separate lines into a single line. It works on most statements, but not all.
A: Yes, the code would work exactly the same on two lines; the colon's just a statement separator.
A: You can put two (or more) lines of code in one line. It's most often used, as in your example, to declare and set a variable on one line.
Think of it like a semicolon in every other language, except optional. | unknown | |
d18485 | test | Just test if the object already exists in ready() :
# django/myapp/apps.py
from django.apps import AppConfig
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
class BlogConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'blog'
def __init__(self, app_name, app_module):
super(BlogConfig, self).__init__(app_name, app_module)
self.planer_zad = None
def ready(self):
if os.environ.get('RUN_MAIN', None) != 'true':
return
if self.planer_zad is None:
background_scheduler = BackgroundScheduler()
background_scheduler.add_job(task1, CronTrigger.from_crontab('* * * * *')) # Every minutes (debug).
background_scheduler.start()
return background_scheduler
def task1(self):
print("cron task is working")
You can then call it later :
# api.py
from django.apps import apps
@router.get("/background-task")
def background_task(request):
"""
Run a background task.
"""
user = request.user
blog_config= apps.get_app_config('blog')
background_scheduler = blog_config.background_scheduler
return {"status": "Success", "True": str(background_scheduler)} | unknown | |
d18486 | test | The extra members are still there. No data is lost. You just can not access them from a variable of the base type. This behavior is a property of polymorphism.
When you implicitly (or explicitly) cast Derived to Base, you are not creating a new instance of Base, or altering the existing instance of Derived, you are simply creating a different view to Derived, treating it as if it were a Base.
To access the derived members again, you will need to explicitly cast back to a derived type to access them.
Assuming Derived has field Foo while Base does not:
Derived d = new Derived();
Console.WriteLine(d.Foo);
Base b = d;
Console.WriteLine(b.Foo); //compile error
Derived d2 = (Derived)b; //or Derived d2 = b as Derived;
Console.WriteLine(d2.Foo); //valid | unknown | |
d18487 | test | You can use value_counts with df.stack():
df[['name1','name2']].stack().value_counts()
#df.stack().value_counts() for all cols
A 7
B 4
C 1
Specifically:
(df[['name1','name2']].stack().value_counts().
to_frame('new').rename_axis('name').reset_index())
name new
0 A 7
1 B 4
2 C 1
A: Let us try melt
df.melt().value.value_counts()
Out[17]:
A 7
B 4
C 1
Name: value, dtype: int64
A: Alternatively,
df.name1.value_counts().add(df.name2.value_counts(), fill_value=0).astype(int)
gives you
A 7
B 4
C 1
dtype: int64
A: Using Series.append with Series.value_counts:
df['name1'].append(df['name2']).value_counts()
A 7
B 4
C 1
dtype: int64
value_counts converts the aggregated column to index. To get your desired output, use rename_axis with reset_index:
df['name1'].append(df['name2']).value_counts().rename_axis('name').reset_index(name='new')
name new
0 A 7
1 B 4
2 C 1
A: python Counter is another solution
from collections import Counter
s = pd.Series(Counter(df.to_numpy().flatten()))
In [1325]: s
Out[1325]:
A 7
B 4
C 1
dtype: int64 | unknown | |
d18488 | test | @Injectable()
class MyGlobalService {
properties$:Subject = new BehaviorSubject();
constructor() {
this.properties.next(window.properties);
}
}
@NgModule({
providers: [MyGlobalService],
...
})
class AppModule()
class MyComponent {
constructor(private myGlobals:MyGlobalService) {
myGlobals.properties$.subscribe(val => console.log(val));
}
} | unknown | |
d18489 | test | You have to adjust your getmyip.sh to the following code:
#!/bin/sh
python getmyexternalip.py
Then create the python file called getmyexternalip.py and add following code:
import subprocess
import xbmcgui
output = subprocess.check_output("curl -s http://whatismijnip.nl |cut -d ' ' -f 5", shell=True)
output = output.rstrip('\n')
xbmcgui.Window(10000).getControl(32000).setLabel("IP: " + str(output))
Also you have to adjust the XML to have an id on this control:
<control type="label" id="32000">
Please consider that the id has to be the same as in the parameter in the xbmcgui.Window(10000).getControl function.
The ID 10000 in the python script for the window is the default Window ID for the Home.xml | unknown | |
d18490 | test | Using margin-left instead of padding:
&__space {
padding: 10px 0 10px 10px;
margin-left: 140px;
}
A: I think you are missing the big picture here.
Making up a block box in CSS we have the:
Content box: The area where your content is displayed, which can be
sized using properties like width and height. Padding box: The padding
sits around the content as white space; its size can be controlled
using padding and related properties.
Border box: The border box wraps
the content and any padding. Its size and style can be controlled
using border and related properties.
Margin box: The margin is the
outermost layer, wrapping the content, padding, and border as
whitespace between this box and other elements. Its size can be
controlled using margin and related properties.
So in short the border includes the padding (it wraps the content as well as the padding), while the margin lays outside of it (pushing the content with border and padding included). I would recomand to check the box model docs. | unknown | |
d18491 | test | The problem is you are attempting to destructure a property (namely the 'show' property) which doesnt exist in your json object when you make your map call.
Heres an example of destructuring (in case you arent familiar):
const example= {
show: 'Seinfeld',
};
const { show } = example;
In the last line the show property is being taken from the example object and assigned to a variable named show (so the variable show would hold the value 'Seinfeld').
In your code below you are also destructuring a property named show from each json object in the map function call:
props.shows.map(({show}) => (
<ShowLink key={show} value={show} />
));
In the working json each object has a show: property which itself is an object containing data you want.
In the not working json there is no show: property so you are attempting to access a property that doesnt exist which would return null.
So to solve the issue in the case of the not working url, you simply need to remove the destructuring:
props.shows.map((show) => (
<ShowLink key={show} value={show} />
)); | unknown | |
d18492 | test | You can decide one to use like this:
<script>window.JSON || document.write('<script src="js/json2.js"><\/script>')</script>
This checks for window.JSON (supported by browser) first if it exists, use that else imports json2.js of Crockford.
update
var whichJSON = null;
if (! window.JSON) {
document.write('<script src="js/json2.js"><\/script>');
whichJSON = 'Crockford Version';
}
else {
whichJSON = 'Browser Native Version';
}
alert(whichJSON);
A: Before you load Crockford's script, you can check for the global JSON object exactly like he does:
<script>
var JSON,
nativeJSON = true;
if (!JSON) {
var nativeJSON = false;
document.write('<script src="js/json2.js"><\/script>');
}
if (!nativeJSON) {
// All JSON objects are using Crockford's implementation
} else {
// All JSON objects from here on out are NOT using Crockford's implementation
}
</script> | unknown | |
d18493 | test | The problem was in this->backURL because it has / so the server feel like go to /another resource so you need to encode it using urlencode(this->backURL) | unknown | |
d18494 | test | Not sure if I understood your question correctly (some sample data will help) but I think you mean that you need all the combinations of Quarter and Review and then any related Sale and Potential data for each combination of Quarter and Review. If that is what you need, then try the below query:
SELECT [Quarter].ID AS QID, Review.ID AS RID, Sales.ID AS SID, Potentials.ID AS PID FROM [Quarter]
CROSS JOIN [Review]
LEFT JOIN (SELECT * FROM Sale WHERE IsArchived = 0) Sales ON [Quarter].ID = Sales.QuarterID AND [Review].ID = Sales.ReviewID
LEFT JOIN (SELECT * FROM Potential WHERE IsArchived = 0) Potentials ON [Quarter].ID = Potentials.QuarterID AND [Review].ID = Potentials.ReviewID | unknown | |
d18495 | test | Do not use post, use ajax
sample:
var paperData = 'name=' + sourceFileName + '&' + 'file=' + uploadFileName;
var url = encodeURI('/Paper/Create?' + paperData);
ajax
({
block: false,
url: url,
success: function (r) {
if (r.success) {
var html='<tr><td class="tac">';
html = html + r.displayName;
html = html + '</td>';
html = html + '<td class="tac">';
html = html + r.type;
html = html + '</td>';
html = html + '<td>';
html = html + '<a class="showPaperEditor" href="/Paper/Edit/';
html = html + r.paperID;
html = html + '" w="570" h="340" >修改</a>';
html = html + '<span class="cd">┊</span>' ;
html = html + '<a class="a-ajax-delPaper" href="/Paper/Delete/';
html = html + r.paperID;
html = html + '">删除</a>';
html = html + '</td></tr>';
$('#tbPaperList').append(html);
}
else {
alert(r.message);
//$.unblockUI();
}
}
}); | unknown | |
d18496 | test | Sounds like AspectJ pointcut "after catching" (not exising). Existing is "after throwing"
https://coderanch.com/t/498256/frameworks/AOP-pointcut-CATCH-block
https://www.eclipse.org/aspectj/doc/next/progguide/printable.html#the-handler-join-point
How to intercept method which handles its own exceptions using AspectJ
Spring AOP - Invoking advice from catch block
Maybe java agents/bytecode manipulation can be helpful
Using Instrumentation to record unhandled exception
You can consider to instrument catch blocks throughout the codebase with Scalameta (or Scalafix)
import scala.meta._
val transformer = new Transformer {
override def apply(tree: Tree): Tree = tree match {
case q"try $expr catch { ..case $cases } finally $expropt" =>
val cases1 = cases.map {
case p"case $pat if $expropt => $expr" =>
pat match {
case p"${pat: Pat.Var}: $tpe" =>
p"""case $pat: $tpe if $expropt =>
println("Exception " + ${pat.name} + " is caught")
$expr
"""
case p"$pat" =>
p"""case $pat if $expropt =>
println("Exception " + ${pat.toString} + " is caught")
$expr
"""
}
}
q"try $expr catch { ..case $cases1 } finally $expropt"
case _ => super.apply(tree)
}
}
transformer(q"""
try {
1 / 0
} catch {
case e: RuntimeException =>
println(e)
throw e
}
""")
//try {
// 1 / 0
//} catch {
// case e: RuntimeException =>
// println("Exception " + e + " is caught")
// {
// println(e)
// throw e
// }
//}
transformer(q"""
try {
1 / 0
} catch {
case _ =>
println("swallowed")
}
""")
//try {
// 1 / 0
//} catch {
// case _ =>
// println("Exception " + "_" + " is caught")
// println("swallowed")
//}
transformer(q"""
try {
1 / 0
} finally {
case _ =>
println("not catching")
}
""")
//try {
// 1 / 0
//} finally {
// case _ =>
// println("not catching")
//}
https://scalameta.org/
https://www.scala-sbt.org/1.x/docs/Howto-Generating-Files.html
Scala conditional compilation
Macro annotation to override toString of Scala function
How to merge multiple imports in scala?
https://scalacenter.github.io/scalafix
For Java sources Spoon (https://spoon.gforge.inria.fr) can be a replacement for Scalameta.
A: Solution 1 can work. If you are only worried about different semantics then it is sufficient to search in client code for occurrences of the exceptions defined by lib1. If client code catches a more generic exception (e.g. Exception or Throwable) then the precise semantics don't matter and you can leave that code alone.
Assumptions:
*
*Lib1's exceptions are specific and are not thrown by other code (e.g. not RuntimeException but Lib1Exception is okay).
*Lib1 and lib2 throw different exceptions but for the same reasons: if lib1 would throw an exception, lib2 would as well (and vice versa).
A: "Approach 3" is a "nogo". I would go with "approach 4": write a wrapper client library (L3?) that throws the exceptions you want.
It may look like somewhat more work initially, but will definitely pay for itself when you change your mind and want to go back to L1, or when there are L4, L5 and L6 you want to try. It is also probably going to be a lot easier to unit-test. | unknown | |
d18497 | test | You have to add your drawings to your model and make sure your model is rendered, as appropriate, when the view is invalidated. You do not want to be drawing on the view directly without a model around to re-render it when necessary.
Jacob | unknown | |
d18498 | test | https://github.com/DigiSkyOps/knife
this is a obs stream server
nginx/config
rtmp {
server {
listen 1935;
chunk_size 4000;
application live {
live on;
}
application hls {
live on;
hls on;
hls_path /data/hls;
hls_fragment 5s;
hls_playlist_length 10s;
hls_continuous on;
hls_cleanup on;
hls_nested on;
}
}
} | unknown | |
d18499 | test | On function based views you would use decorators, in your particular case
permission_required decorator
@permission_required('abc.change_shiftchange', raise_exception=True)
delete_viewgen(request,id) | unknown | |
d18500 | test | To push notification to users, you need a your backend environment with your certificates.
You also have to receive the user device token needed to send the push notification.
Here there is a complete tutorial to make all the necessary for push notifications: http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1
NSNotification is another thing and is local..in your app. You can use that to generate notification in your app at certain time or when a certain event happen. | unknown |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.