_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d11201 | train | Are you using mysql_info and mysql_error outside the Database class? And if so how are you referencing the database connection? If you don't identify the database connection then:
The MySQL connection. If the link identifier is not specified, the last
link opened by mysql_connect() is assumed. If no such link is found,
it will try to create one as if mysql_connect() was called with no
arguments. If no connection is found or established, an E_WARNING
level error is generated.
So internally you should be doing mysql_info($this->db); to get mysql_info. Accessing $db externally requires you to write something to get around it being private.
But if you are going to be doing database stuff in an object-oriented mode you really should investigate PDO.
A: After adding "or die()" statements in several places in my script, I was surprised to see that nothing was actually failing to work, instead it was failing to work the way I expected it to. The problem I was having as it turns out, was that splitting the output of mysql_info (on the space character) resulted in several indices in the array containing nothing, as would be generated by inconsistent whitespace in the output of mysql_info. The index that I thought (based upon counting spaces visually) would contain an integer instead contained a string, and I was attempting to compare that string against the number 0, which won't work. I have updated my executeNonQuery function as follows:
public function executeNonQuery($query){
mysql_query($query, $this->db) or die ("Error in query: $query. ".mysql_error());
$info = mysql_info($this->db);
if($info){
$output = array();
$bits = explode(' ', $info);
$output["rowsMatched"] = $bits[2];
$output["rowsChanged"] = $bits[5];
$output["warnings"] = $bits[8];
return $output;
}
return false;
} | unknown | |
d11202 | train | The output you want is produced if you use the jasmine.TrivialReporter. The one the gem displays is the recommended one, i.e. the jasmine.HtmlReporter. You can use the trivial one as described here: https://github.com/pivotal/jasmine/blob/v1.3.1/lib/jasmine-core/example/SpecRunner.html, but that implies running jasmine stand-alone not through the gem.
(version 1._._ only.) | unknown | |
d11203 | train | As long as the string still has the underline html you should be able to utilize the Html.fromHtml method to style the string.
textview.setText(Html.fromHtml(mrng));
A: Actually, the string getResource().getString(R.string.s_hello_txt) is not be underlined.
The best way to add html source code in strings.xml is to use <![CDATA[html source code]]>. Here is an example:
<string name="s_hello_txt"><![CDATA[<u>Text</u>]]></string>
And then use Html.fromHtml(mrng) to show the underlined string
A: // Try This One This Will Help For Your Acheivement
**String.xml**
<string name="s_hello_txt"><br/>{ <u>hello all</u> }<br/></string>
**activity_main1.xml**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/txtValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/s_hello_txt"/>
<Button
android:id="@+id/btnClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GoTo Second Activity"/>
</LinearLayout>
**MainActivity1 Activity**
public class MainActivity1 extends Activity {
private Button btnClick;
private TextView txtValue;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
txtValue = (TextView)findViewById(R.id.txtValue);
btnClick = (Button)findViewById(R.id.btnClick);
txtValue.setText(Html.fromHtml(getString(R.string.s_hello_txt)));
btnClick.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity1.this, MainActivity2.class);
intent.putExtra("EXTRA",getString(R.string.s_hello_txt));
startActivity(intent);
}
});
}
}
**activity_main2.xml**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/txtValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
**MainActivity2 Activity**
public class MainActivity2 extends Activity {
private TextView txtValue;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
txtValue = (TextView)findViewById(R.id.txtValue);
txtValue.setText(Html.fromHtml(getIntent().getStringExtra("EXTRA")));
}
} | unknown | |
d11204 | train | The 'Variable' object does not support item assignment. You may enforce your requirement as a constraint:
import cvxpy as cp
S = cp.Variable(100) # Define your variables
objective = ... # Define your objective function
constraints = [] # Create an array of constraints
constraints.append(S[0]==320000) # Make your requirement a constraint
# Add more constraints
prob = Problem(objective, constraints) # Define your optimization problem
prob.solve(verbose=True) # Solve the problem
print(S.value) | unknown | |
d11205 | train | Have a look at Twitter Bootstrap. It integrates very well with django-crispy-forms and will let you produce very clean, modern looking forms quite easily, with very little work on the client side.
It won't help you out with Ajax functionality, but will handle look and feel quite nicely. | unknown | |
d11206 | train | LayeredArchitecture considers all dependencies between layers. You cannot forbid inheritance, but allow access – nor vice versa. I recommend to define individual specific rules instead:
@ArchTest
ArchRule adapter_should_not_inherit_from_port = noClasses()
.that().resideInAPackage("….adapter")
.should().beAssignableTo(JavaClass.Predicates.resideInAPackage("….port"));
@ArchTest
ArchRule service_should_not_access_port = noClasses()
.that().resideInAPackage("….service")
.should().accessClassesThat().resideInAPackage("….port"); | unknown | |
d11207 | train | Please add pl-0 and pr-0 class for the remove the padding
<div class="col align-self-start pl-0">
<div class="card card-body justify-content-center" style="height:150px">
<h5 class="card-title">Privacy & Security</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
</div>
<div class="col align-self-end pr-0">
<div class="card card-body justify-content-center" style="height:150px">
<h5 class="card-title">Privacy & Security</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
</div>
A: <div class="col-12 mb-3">
<div class="card card-body justify-content-center" style="height:150px">
<h5 class="card-title">Privacy & Security</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
</div>
<div class="col ml-auto">
<div class="card card-body justify-content-center" style="height:150px">
<h5 class="card-title">Privacy & Security</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
</div>
<div class="col mr-auto">
<div class="card card-body justify-content-center" style="height:150px">
<h5 class="card-title">Privacy & Security</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
</div>
</div>
A: Please use the predefined Bootstrap classes at first and if you have any custom CSS add it in a new classes.
Is this what you search for:
HTML
<div class="container" style="border:1px red dotted">
<div class="row " style="border:1px blue dotted">
<div class="col pl-0">
<div class="card card-body justify-content-center" style="height:150px">
<h5 class="card-title">Privacy & Security</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's
content.</p>
</div>
</div>
<div class="col pr-0">
<div class="card card-body justify-content-center" style="height:150px">
<h5 class="card-title">Privacy & Security</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's
content.</p>
</div>
</div>
</div>
</div>
A: this is a demo for what exactly you want I have just remove padding for the full-width box and for the next two box I remove padding-left for left side box and padding-right for the right side box.
this is the code snippet which helps you to understand what I do.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container p-0">
<div class="row m-0">
<div class="col-12 p-0 mb-4">
<div class="card bg-primary card-body text-center justify-content-center" style="height: 150px; font-size: 50px; color: red;">
Box 1
</div>
</div>
<div class="col-6 pl-0">
<div class="card bg-primary card-body text-center justify-content-center" style="height: 150px; font-size: 50px; color: red;">
Box 2
</div>
</div>
<div class="col-6 pr-0">
<div class="card bg-primary card-body text-center justify-content-center" style="height: 150px; font-size: 50px; color: red;">
Box 3
</div>
</div>
</div>
</div>
</body>
</html>
I hope this answer will help you to solve your problem this time and also help you in future for this type of structure.
Thank you... | unknown | |
d11208 | train | I think that error cannot implicitly convert from uint to int refers to = statement. The field this.ProcessID is int, but GetWindowThreadProcessId returns uint.
Try this
this.ProcessID = unchecked((int)GetWindowThreadProcessId(windowHandle.ToInt32(),0))
A: The SendMessage signature is
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
or this
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, StringBuilder lParam);
Don't exchange int and IntPtr. They are nearly equivalent only at 32 bits (equal in size). At 64 bits an IntPtr is nearly equivalent to a long (equal in size)
The GetWindowThreadProcessId signature is
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
or
static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
In this case, a ref or a out to "something" are managed references to something, so they are internally converted to IntPtr when passed to Native API. So out uint is, from the point of view of the Native API, equivalent to IntPtr.
Explanation: what is important is that the "length" of the parameters is the correct one. int and uint are equal for the called API. And a 32bit IntPtr is the same too.
Note that some types (like bool and char) have special handling by the marshaler.
You shouldn't EVER convert an int to an IntPtr. Keep it as an IntPtr and live happy. If you have to make some math operations not supported by IntPtr, use long (it's 64 bits, so until we will have Windows 128, there won't be any problem :-) ).
IntPtr p = ...
long l = (long)p;
p = (IntPtr)l;
A: I was getting "Arithmetic operation resulted in an overflow", whenever I was:
IntPtr handler = OpenSCManager(null, null, SC_MANAGER_CREATE_SERVICE);
if (handler.ToInt32() == 0) //throws Exception
instead of that:
IntPtr handler = OpenSCManager(null, null, SC_MANAGER_CREATE_SERVICE);
if (handler == IntPtr.Zero) //OK | unknown | |
d11209 | train | There is a tutorial on fine-tuning with MXNet. Did you check this out?
http://mxnet.incubator.apache.org/faq/finetune.html | unknown | |
d11210 | train | Refering to Koh
"UserManager requires API level 17 while AppOpsManager requires API level 19. [...] Otherwise, this could be a multidex issue such as here." | unknown | |
d11211 | train | You can do that manually on change event :
var monthsLabels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var picker = jQuery('#SearchVal').MonthPicker({
ShowIcon: false,
OnAfterChooseMonth: function(){
var elts = picker.val().split('/');
picker.val(monthsLabels[parseInt(elts[0])-1]+', '+elts[1]);
}
});
jsFiddle
A: hello bro try to see this will help you it's about Datepicker | unknown | |
d11212 | train | Have you tried using 0.0.0.0? that will map it to your local IP, and you will be able to access it within your network if you know your IP.
A: Yes I am able to debug it finally using below code after lots of search on google.
we have to define them into args using ipaddress & port.
"args": [
"runserver",
"--noreload",
"192.168.1.195:8005",
], | unknown | |
d11213 | train | You are able to let each parent know about which children was added/removed.
Each parent will get the event and will handle it if it's a matching child (or relevant due to other logic).
Two public objects which are used for communication between parent and master:
public enum ChangeType { Added, Removed }
public delegate void ChildChangeEvent(Parent parent, Child child, ChangeType changeType);
The parent class has two main roles- raising an event if it has a child that was added/removed, and handling this event if raised by other parents and it's relevant for them.
class Parent
{
public event ChildChangeEvent ChildChangeEvent;
private List<Child> _children;
public void Add(Child child)
{
_children.Add(child);
ChildChangeEvent(this, child, ChangeType.Added);
}
public void Remove(Child child)
{
_children.Remove(child);
ChildChangeEvent(this, child, ChangeType.Removed);
}
public void NotifyChange(Parent parent, Child child, ChangeType changeType)
{
//do where you want with this info.. change local id or whatever logic you need
}
}
The Master class should notify all parents about the child added/removed
event that was raised by one of the parents:
class Master
{
private List<Parent> _parents;
public void AddParent(Parent parent)
{
_parents.Add(parent);
parent.ChildChangeEvent += parent_ChildChangeEvent;
}
void parent_ChildChangeEvent(Parent parent, Child child, ChangeType changeType)
{
foreach (var notifyParent in _parents)
{
notifyParent.NotifyChange(parent, child, changeType);
}
}
} | unknown | |
d11214 | train | I've been able to use the 'Test-Port' function from Boe Prox for similar scan/ reporting functions, the code is available on PoshCode:
http://poshcode.org/2514
When I needed to test ports for Directory health, I built a csv with 'port' and 'protocol' columns, then added the port number/ protocol for each port to check. This was used in the following script:
. .\test-port.ps1
$computersToCheck = get-content .\computers.txt
$portList = Import-CSV .\portList.csv
foreach($entry in $portList)
{
$testPortParams = @{
port = $($entry.port)
}
if( $($entry.protocol) -eq "tcp")
{ $testPortParams += @{ TCP = $true } }
else
{ $testPortParams += @{ UDP = $true } }
$outLog = "portTest-$($entry.port)-$($entry.protocol).txt"
$computersToCheck |
Test-Port @testPortParams |
Sort-Object -Property open,name -descending |
format-table -auto -outVariable status
Add-Content -path $outLog -value $status
}
You could certainly build a feeder script to build the range of IP addresses and ports to scan. | unknown | |
d11215 | train | Yes, you can use stack output exports, define export value on one stack and import it in any other: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-exports.html | unknown | |
d11216 | train | You can easily make a shortcut for your function that does same of function code and load the file on start:
display = {}
function display.writeline(str)
display.Display_writeLine(str)
end | unknown | |
d11217 | train | There is no need to use .get() on the static jQuery.map() function, it returns a proper array, while the plugin method .map() returns a jQuery object on which you have to call .get() to get an array.
Also there is no need to use 2 loops,
var objArr = $('input[type=text].editfield').map(function (idx, i) {
//the element selection used here is cruel, if you can share the html used we can help you to clean it
return {
// you can try myDate: $(this).parent().prevAll().eq(5).text() - not testable without the html and what is the expected output
myDate: i.parentElement.previousSibling.previousSibling.previousSibling.previousSibling.previousSibling.previousSibling.childNodes[0].textContent,
myValue: i.value
};
}).get(); | unknown | |
d11218 | train | In psql:
\d+ the_view
--or
select definition from pg_views where viewname = 'the_view'; | unknown | |
d11219 | train | Not enough reputation to comment.
Does the media actually load though? Or does it load but just not play? If it's the latter then this may be your problem.
JQuery jPlayer autoplay not working on ipad how to show controls
Answer from other thread:
You're not going to be able to play video from $(document).ready() or from jPlayer's ready event. IOS specifically prevents it
I can't test this because I don't have an Ipad, but this may be your problem. | unknown | |
d11220 | train | You need to make sure the files calling the functions are Objective-C++ files (basically, give them the extension ".mm"), and you need to add the library to your project so it gets linked in. | unknown | |
d11221 | train | Your code works with strict null checks off, because you can then assign undefined values to a string. We're talking about values here, the keys are indifferent!
Your index type signature for Mapped promises no particular keys, so assigning a type with zero or more keys will work. What isn't allowed is the assignment of non-string values (like undefined and null) and this is what the error is highlighting.
Here is a contrived example of what the error is guarding against:
var undef: undefined;
const partialMapped: Partial<Mapped> = {a: undef, b: undef}; // Works
The partial version can accept undefined values. The "full" version wouldn't allow this.
var undef: undefined;
const mapped: Mapped = {a: undef, b: undef}; // Warnings! | unknown | |
d11222 | train | Normalize Whitespace normalizes the whitespace for the current object - not the object contained within a SyntaxTree.
If you would for instance call normalize whitespace on newVariable with the value
string varTest2 = @"test var hello";
It does not matter that the variable declaration is also within a syntax tree - what matters is the current context. Normalizing the whitespace of the above statement does basically nothing as there are no BlockStatements, Declarations or other elements which would create an indentation.
If you however call normalize whitespace on the containing scope, for instance the method, you would get something along these lines:
static void Main(string[] args)
{
string test5 = @"test symbols \r\n © @ {} [] <> | / \ $£@!\#¤%&/()=?` hello";
string varTest1 = @"test var hello";
string varTest2 = @"test var hello";
string test1 = @"test string hello";
string test2 = @"test String hello";
string test3 = @"test const hello";
string test4 = @"test readonly hello";
int i = 0;
var i2 = 0;
}
As you can see this would provide you with a correctly indented method. So in order to get the correctly formatted document you would have to call NormalizeWhitespace on the SyntaxRoot after everything else is done:
editor.GetChangedRoot().NormalizeWhitespace().ToFullString()
This will of course prevent you from retaining your old formatting if you had some artifact you would like to keep (e.g. the additional line between the DeclarationStatements you have in your sample).
If you want to keep this formatting and the comments you could just try to copy the Trivia(or parts of the Trivia) from the original statement:
foreach (var localDeclarationStatementSyntax in localDeclarations)
{
foreach (VariableDeclaratorSyntax variable in localDeclarationStatementSyntax.Declaration.Variables)
{
var stringKind = variable.Initializer.Value.Kind();
//Replace string variables
if (stringKind == SyntaxKind.StringLiteralExpression)
{
//Remove " from string
var value = variable.Initializer.Value.ToString().Remove(0, 1);
value = value.Remove(value.Length - 1, 1);
var newVariable = SyntaxFactory.ParseStatement($"string {variable.Identifier.ValueText} = @\"{value + " hello"}\";").WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation);
newVariable = newVariable.NormalizeWhitespace();
// This is new, copies the trivia (indentations, comments, etc.)
newVariable = newVariable.WithLeadingTrivia(localDeclarationStatementSyntax.GetLeadingTrivia());
newVariable = newVariable.WithTrailingTrivia(localDeclarationStatementSyntax.GetTrailingTrivia());
editor.ReplaceNode(variable, newVariable);
Console.WriteLine($"Key: {variable.Identifier.Value} Value:{variable.Initializer.Value}");
}
}
} | unknown | |
d11223 | train | Have your complete .htaccess like this:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
## don't touch /forum URIs
RewriteRule ^forums/ - [L,NC]
RewriteCond %{THE_REQUEST} \s/+products(?:\.php)?\?id=([0-9]+) [NC]
RewriteRule ^ products/%1? [R,L]
RewriteRule ^products/([0-9]+)/?$ products.php?id=$1 [L,QSA]
## hide .php extension snippet
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} \s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L]
# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]
A: you need to use it like that
RewriteRule ^products/([0-9]+)$ products.php?id=$1
A: use below htaccess rule
RewriteRule ^products/([0-9]*)$ /product.php?id=$1 [L,QSA] | unknown | |
d11224 | train | Overloading Mock's __setattr__ actually does work okay:
[ins] In [1]: class MyMock(mock.Mock):
...: def __init__(self, *args, **kwargs):
...: super().__init__(*args, **kwargs)
...:
...: def __setattr__(self, attr_name, attr_value):
...: setattr(self._mock_wraps, attr_name, attr_value)
[nav] In [2]: foo = Foo()
[nav] In [3]: mock_foo = MyMock(wraps=foo)
[ins] In [4]: mock_foo.y = 4
[ins] In [5]: foo.y
4 | unknown | |
d11225 | train | I apologize for not seeing this sooner. The code on that page has been restored and you can download it now without issue.
https://developer.linkedin.com/documents/getting-oauth-token-python
If it's still not working, please let us know (I'll check back here, or you can post in our forums). I use essentially that exact code whenever I test our API so it should work. | unknown | |
d11226 | train | You can embed excel documents on a website using one drive or google docs.
Sync your doc to your one drive, then embed the doc on the page. | unknown | |
d11227 | train | SQL Server does not perform short circuit evaluation (i.e. should not be relied upon). It's a fairly well known problem.
Ref:
*
*Don’t depend on expression short circuiting in T-SQL (not even with CASE)
*Short Circuit
*Short-Circuit Evaluation
*Is the SQL WHERE clause short-circuit evaluated?
A: EDIT: I misunderstood the question with my original answer.
I supposed you could add a where clause, as shown below. Side note: this query might benefit from an index on (ID1, ID2).
select
sum(log(convert(float, ID2)))
from #TEMP
where
-- exclude all records with ID1 = 2 if there are any records with ID1 = 2 and ID2 = 0
not exists (
select 1
from #TEMP NoZeros
where
NoZeros.ID1 = #TEMP.ID1
and NoZeros.ID2 = 0
)
Update: Just in case performance is a concern, I got fairly comparable performance from this query after adding the following indexes:
create index ix_TEMP_ID1_ID2 on #TEMP (ID1, ID2)
create index ix_TEMP_ID2 on #TEMP (ID2) include (ID1)
Original Answer
How about modifying your sum function as shown below?
sum(case ID2 when 0 then null else log(convert(float, ID2)) end) | unknown | |
d11228 | train | This is because you use in.hasNextInt() too soon (or too late, depending on how you look at it): the Scanner cannot tell you if it sees an integer or not until after the end user has entered a value.
If you prompt for a number and then check for hasNextInt, your code should not skip the second prompt:
System.out.print("Enter an integer: ");
while (in.hasNextInt()) {
int numb = in.nextInt();
System.out.println(numb);
System.out.print("Enter an integer: ");
}
This would also prevent an exception in situations when the very first entry is not a number. | unknown | |
d11229 | train | git rebase is showing noop since you're not specifying the starting commit of where you want to rebase from. You can do the following from command line.
Checkout to your noetic branch. Run the following command.
git rebase -i HEAD~130
In the interactive window, leave the first commit as pick and change the next 129 commits to squash. I have Vim as my default editor so I can run the following to easily squash the 129 unneeded commits:
:s/pick/squash/ 129
Once you're done, save & exit with: :wq
Do :wq again when the editor asks you to write your commit message (or edit the commit message as you like)
After this your rebase should be complete and you should have only one commit with all your changes. | unknown | |
d11230 | train | CommonTree tree = (CommonTree)parser.javaSource().getTree();
This assumes that the start point for the Java grammar you are using is the javaSource rule.
Check your grammar to see whether that is indeed the case. If not, identify the correct starting rule and use that. The methods of the parser are named the same as the rules in the grammar. | unknown | |
d11231 | train | data[:, -1] returns the value of the last column for every row
but data[:, 50:] will return the values of the all columns starting from column no 50. Since in your case there are only 50 columns it is same as data[:, -1] but with 1 in the second dimension indicating that only 1 column was picked
Assume that the data is of size (1000, 60), then data[:, -1] would still return a array of shape (1000,) but data[:, 50:] would return an array of shape (1000, 10) | unknown | |
d11232 | train | To share access with new guy I had to add him to https://developer.apple.com/account/#/people/ , not only to https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/users_roles | unknown | |
d11233 | train | The formula:
=MAX(INDEX(GOOGLEFINANCE(C7, "high", A7, B7), , 2))
…will return the stock's high price between the dates A7 and B7 in your example.1
How does it work?
Using the formula:
=GOOGLEFINANCE(<symbol>, "high", <StartDate>, <EndDate>) or
=GOOGLEFINANCE(C7, "high", A7, B7) (in your example),
…will return an array which looks something like this:
Using the INDEX() function, you can convert that array to a single column of the high values:
=INDEX(GOOGLEFINANCE(C7, "high", A7, B7), , 2)
Now you can pass that array into the MAX() function to get the highest value in a single cell:
=MAX(INDEX(GOOGLEFINANCE(C7, "high", A7, B7), , 2))
1 Important Note:
If you include a date range in GOOGLEFINANCE's "high" function, it will not include today's price during the current trading day — so if you need to include today's high price in your range, you will need to compare today's high price to the historical data explicitly.
E.g., the function =GOOGLEFINANCE(symbol, "high") gives you today's high price, so:
=MAX(GOOGLEFINANCE(C7, "high"), MAX(INDEX(GOOGLEFINANCE(C7, "high", TODAY()-30, TODAY()), , 2)))
…will give you the high price over the last 30 days, including today.
If there's a possibility that your date range might include today only (i.e. no historical data where A7 and B7 both equal today), unfortunately, the formula above will return #NA. I have the ultimate solution to generate the correct array even if it does not contain historical data.
The Bullet-Proof Solution
The formula below traps the #NA condition and builds the array to include today's high no matter what date range is specified:
=MAX(INDEX({IFNA(GOOGLEFINANCE(E7, "high", A7, TODAY()), {"Date", "High"}); NOW(), GOOGLEFINANCE(E7, "high")}, , 2))
I've been bitten by this quirk a few times and this solution seems to be cover all scenarios. Enjoy!
A: Please try:
=max(INDEX(GoogleFinance(C7,"high",A7,B7,"DAILY"),0,2))
0,2 rather than 2,2 at the end to return the range rather than a cell from it and MAX for the maximum. | unknown | |
d11234 | train | Can you explain more about what you mean? If you are talking about declaring the cursor in a dynamic context as in the following example, then yes you can:
DECLARE @i int -- variable input
DECLARE @valuableData int
SET @i = 1 -- value for that input, this could be set by a query
DECLARE cursorFoo CURSOR FOR
SELECT valuableData
FROM myTable
WHERE someParameter = @i
OPEN cursorFoo
WHILE (1=1)
BEGIN
FETCH NEXT FROM cursorFoo
INTO @valuableData
IF (@@FETCH_STATUS <> 0) BREAK
SELECT @valuableData -- Do something with your data
END
CLOSE cursorFoo
EDIT due to discussion in comments
You should have two separate program loops here
Loop 1:
*
*Webservice adds tasks to permanent
table with information on priority.
Loop 2:
*
*Server script queries permanent
table for most important task
*Server script removes task from
table and processes task (or hands
that information off to a script
that does the work
*Server script goes back to permanent
table and looks for most important
task
SQL is meant to store data, not loop around and process it. The processing should be done with a server script. That script should get the data from the database. You start to have the concurrency issues you have having right now when SQL is writing and reading and looping through the same temporary table concurrently. You can do processing in SQL, but you should only use temp tables for data that is relevant only to that particular process. | unknown | |
d11235 | train | Looks like it's about space. Seems following should work but I'm not sure
contains( DEFINES, SOME_DEF ):DEFINES+=SOME_OTHER_DEF
As I got it it's designed to be used as logical AND operator.
conditionA:conditionB {
...
} | unknown | |
d11236 | train | Use only one column with an IN operator
SELECT *
FROM COMPANY_COUPON
WHERE COMPANY_ID = 1
AND COUPON_ID IN (SELECT COUPON_ID FROM COUPON WHERE TYPE = CAMPING)
A: I think you just want a join:
SELECT cc.COUPON_ID
FROM COMPANY_COUPON cc JOIN
COUPON c
ON cc.COUPON_ID = c.ID
WHERE cc.COMPANY_ID = ? AND c.TYPE = ?;
A: You might want to use WHERE IN here:
SELECT *
FROM COMPANY_COUPON
WHERE COMPANY_ID = 1 AND COUPON_ID IN (SELECT ID FROM COUPON WHERE TYPE = 'CAMPING');
You could also use EXISTS, which is probably the best way to write your logic:
SELECT cc.*
FROM COMPANY_COUPON cc
WHERE
cc.COMPANY_ID = 1 AND
EXISTS (SELECT 1 FROM COUPON c WHERE c.TYPE = 'CAMPING' AND c.ID = cc.COUPON_ID);
Using EXISTS might outperform doing a join between the two tables, because the database can stop as soon as it finds the very first match. | unknown | |
d11237 | train | This issue was caused because linker behavior for IOS application was set to full and that causes issues with Unity IOC Container. | unknown | |
d11238 | train | Replace this code
<form action="{{ route('delLink', Auth()->user()) }}" method="POST">
@csrf
@method('DELETE')
<table class="table-auto w-full">
<tr class="bg-slate-300">
<td class="p-4"><strong>Url</strong></td>
<td class="p-4"><strong>Filter selector</strong></td>
<td class="p-4"><strong>Website</strong></td>
<td class="p-4"><strong>Categorie</strong></td>
<td></td>
<td></td>
</tr>
@foreach ($links as $link)
<tr data-id="{{ $link->id }}" class="">
<td class="p-4 border-r">{{ $link->url }}</td>
<td class="p-4 border-r">{{ $link->main_filter_selector }}</td>
<td class="p-4 border-r">{{ $link->website->title }}</td>
<td class="p-4 border-r">{{ $link->category->title }}</td>
<td class="p-4 border-r"><button class="w-fit bg-green-400 h-fit p-2 rounded hover:bg-green-600 hover:text-white block m-auto" type="submit">Scrape</button></td>
<td class="p-4"><button class="w-fit h-full p-2 bg-red-400 h-fit rounded hover:bg-red-600 hover:text-white block m-auto" type="submit">Verwijderen</button>
</td>
</tr>
@endforeach
</table>
</form>
With this
<table class="table-auto w-full">
<tr class="bg-slate-300">
<td class="p-4"><strong>Url</strong></td>
<td class="p-4"><strong>Filter selector</strong></td>
<td class="p-4"><strong>Website</strong></td>
<td class="p-4"><strong>Categorie</strong></td>
<td></td>
<td></td>
</tr>
@foreach ($links as $link)
<tr data-id="{{ $link->id }}" class="">
<td class="p-4 border-r">{{ $link->url }}</td>
<td class="p-4 border-r">{{ $link->main_filter_selector }}</td>
<td class="p-4 border-r">{{ $link->website->title }}</td>
<td class="p-4 border-r">{{ $link->category->title }}</td>
<td class="p-4 border-r"><button class="w-fit bg-green-400 h-fit p-2 rounded hover:bg-green-600 hover:text-white block m-auto" type="submit">Scrape</button></td>
<td class="p-4">
<form action="{{ route('delLink', $link->id) }}" method="POST">
@csrf
@method('DELETE')
<button class="w-fit h-full p-2 bg-red-400 h-fit rounded hover:bg-red-600 hover:text-white block m-auto" type="submit">Verwijderen</button>
</form>
</td>
</tr>
@endforeach
</table>
Your destroyLink() method should contain this
public function destroyLink(Request $request)
{
$id = $request->id;
$link = Link::find($id);
$link->delete();
return back();
} | unknown | |
d11239 | train | In Magento 2 provide the functionality of auto created a number of associated product base on selected attributes.
Like First, you have created one attribute for mobile model, Then you have wanted, enter 500 Model name only one time. Then after you have want to create one configurable product then select model attributes >> then click on Select All menu for all selected models >> Then create a configurable product.
Note: automatically created 500 simple (associated) product. Please see screenshot. http://prntscr.com/knsqxl
Please check the example demo : http://blankrefer.com/?http://demo-acm2.bird.eu/admin | unknown | |
d11240 | train | evgfilim1:
Hello. You need to use FSM, it's more flexible than register_next_step_handler.
Check the example: https://github.com/aiogram/aiogram/blob/dev-2.x/examples/finite_state_machine_example.py
The linked page won't break as the implementation is not going to change in aiogram 2.x. | unknown | |
d11241 | train | Although there are several potential problems in your code, I'm going to just identifying the problem of the 4th column *'s. In the code below, although you're checking ch!=10 in the for statement, the value of a[i][j] is getting assigned TRUE before terminating the loop. So you might want to do if(ch!=32 && ch!=10) a[i][j]=TRUE;.
flag=TRUE;
for(j=0;ch!=10;j++)
{
ch=getchar();
if(ch==69)
{
return a;
}
if(ch!=32) a[i][j]=TRUE;
}
ch=1; | unknown | |
d11242 | train | I suppose you are using Bootstrap 2? Submenus are removed in Bootstrap 3. An example of working submenus in Bootstrap 3 can be found at http://www.bootply.com/86684 | unknown | |
d11243 | train | UIApplicationOpenSettingsURLString is the only supported way of opening the built-in Settings.app. Any other method is a hack and runs the risk of review rejection because of private API usage.
See e.g. Is it considered a private API to use App-prefs:root? | unknown | |
d11244 | train | You should use ng2-charts which is a ChartJS wrapper for Angular 2/4.
Using this you can create a simple doughnut chart (with click event) as follows :
template
<div id="chart-container">
<canvas baseChart
[chartType]="chartType"
[data]="chartData"
[labels]="chartLabels"
(chartClick)="chartClicked($event)">
</canvas>
</div>
component
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public chartType: string = 'doughnut';
public chartLabels: Array<string> = ['Jan', 'Feb', 'Mar'];
public chartData: Array<number> = [1, 1, 1];
public chartClicked(e: any): void {
if (!e.active.length) return; //return if not clicked on chart/slice
alert('Clicked on Chart!');
}
}
LIVE DEMO
( this shouldn't be too hard to implement in Ionic 2 )
note: this is just a basic example of a doughnut chart and you can customize it further to fit your need, following the official documentation. | unknown | |
d11245 | train | You can use loadeddata or canplaythrough event to check whether the browser has loaded the current frame of the audio/video. See a full list of possible video events here
$("body").prepend(
"<div class='fullscreen-bg'><video loop muted autoplay class='fullscreen-bg__video' ><source src='https://www.iresearchservices.com/wp-content/uploads/2018/03/bgvideo.mp4' type='video/mp4'><source src='https://www.iresearchservices.com/wp-content/uploads/2018/03/bgvideo.mp4' type='video/mp4'><source src='https://www.iresearchservices.com/wp-content/uploads/2018/03/bgvideo.mp4' type='video/mp4'></video></div>"
);
$(".fullscreen-bg__video").on("loadeddata", function () {
alert("Video Loaded")
});
.fullscreen-bg {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow: hidden;
z-index: -100;
}
.fullscreen-bg__video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
@media (min-aspect-ratio: 16/9) {
.fullscreen-bg__video {
width: 100%;
height: auto;
}
}
@media (max-aspect-ratio: 16/9) {
.fullscreen-bg__video {
width: auto;
height: 100%;
}
}
@media (min-aspect-ratio: 16/9) {
.fullscreen-bg__video {
height: 300%;
top: -100%;
}
}
@media (max-aspect-ratio: 16/9) {
.fullscreen-bg__video {
width: 300%;
left: -100%;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> | unknown | |
d11246 | train | It seems to me that all you need to do is maintain a dictionary of locks whose keys are the names given by variable req_name and whose values are the corresponding locks. If the key reg_name is not already in the dictionary, then a new lock for that key will be added:
import asyncio
from collections import defaultdict
# dictionary of locks
locks = defaultdict(asyncio.Lock)
async def handle(req_json_):
req_name = req_json_.get(req_name)
# acquire lock here based on req_name if request comes with different name acquire the lock
# but if the request comes with same name block the request
# untill the req for that name is completed if the request is already completed then acquire
# the lock with that name
# Get lock from locks dictionary with name req_name. If it
# does not exit, then create a new lock and store it with key
# req_name and return it:
lock = locks[req_name]
async with lock:
# do whatever needs to be done:
...
logger.info(f"Request finished with req name {req_name} for action patch stack")
Update
If you need to timeout the attempt to acquire a lock, then create a coroutine that acquires the passed lock argument in conjunctions with a call to asyncio.wait_for with a suitable timeout argument:
import asyncio
from collections import defaultdict
async def acquire_lock(lock):
await lock.acquire()
# dictionary of locks
locks = defaultdict(asyncio.Lock)
async def handle(req_json_):
req_name = req_json_.get(req_name)
lock = locks[req_name]
# Try to acquire the lock but timeout after 1 second:
try:
await asyncio.wait_for(acquire_lock(lock), timeout=1.0)
except asyncio.TimeoutError:
# Here if the lockout could not be acquired:
...
else:
# Do whatever needs to be done
# The lock must now be explicitly released:
try:
...
logger.info(f"Request finished with req name {req_name} for action patch stack")
finally:
lock.release() | unknown | |
d11247 | train | gvTable.AutoGenerateColumns = false
or
<asp:GridView ID="gvTable" runat="server" AutoGenerateColumns="False" AllowSorting="true" ShowHeader="true">
should do the trick.
A: Set the attribute on your gridview:
AutoGenerateColumns="false"
A: You need to set the AutoGenerateColumns property on the grid to false.
A: Have you tried AutoGenerateColumns="false" in the gridview? | unknown | |
d11248 | train | Microsoft has announced that they are working on this exact feature, and it should be coming to Visual Studio Online in Q1 2015, and to on-premise TFS sometime after that.
You can read about it at the bottom of this blog post:
http://blogs.msdn.com/b/bharry/archive/2014/11/12/news-from-connect.aspx
Also the estimated timeline is publicized here:
http://www.visualstudio.com/en-us/news/release-archive-vso.aspx
A: You can use TFS Administrators Toolkit, here is the description of search feature:
http://mskold.blogspot.se/2012/09/find-in-files-new-feature-of-tfs.html | unknown | |
d11249 | train | Okay, first things first, the s and d in rsi and rdi stand for source and destination. It may work the other way (as you have it) but you'll upset a lot of CDO people like myself(a) :-)
But, for your actual problem, look here:
end_count:
mov [message], rsi
I assume that's meant to copy the final byte 0x10 into the destination but there are two problems:
*
*message is the start of the buffer, not the position where the byte should go.
*You're copying the multi-byte rsi variable into there, not the byte you need.
Those two points mean that you're putting some weird value into the first few bytes, as your symptoms suggest.
Perhaps a better way to do it would be as follows:
mov rsi, hello ; as Gordon Moore intended :-)
mov rdi, message
put_str_into_message:
mov al, byte [rsi] ; get byte, increment src ptr.
inc rsi
mov byte [rdi], al ; put byte, increment dst ptr.
inc rdi
cmp al, 10 ; continue until newline.
jne put_str_into_message
ret
For completeness, if you didn't want the newline copied (though this is pretty much what you have now, just with the errant buffer-damaging mov taken away) (b):
put_str_into_message:
mov al, byte [rsi] ; get byte.
cmp al, 10 ; stop before newline.
je stop_str
mov byte [rdi], al ; put byte, increment pointers.
inc rsi
inc rdi
jmp put_str_into_message
stop_str:
ret
(a) CDO is obsessive-compulsive disorder, but with the letters arranged correctly :-)
(b) Or the don't-copy-newline loop can be done more efficiently, while still having a single branch at the bottom.
Looping one byte at a time is still very inefficient (x86-64 has SSE2 which lets you copy and check 16 bytes at a time). Since you have the length as an assemble-time constant hello_len, you could use that to efficiently copy in wide chunks (possibly needing special handling at the end if your buffer size is not a multiple of 16), or with rep movsb.
But this demonstrates an efficient loop structure, avoiding the false dependency of merging a new AL into the bottom of RAX, allowing out-of-order exec to run ahead and "see" the loop exit branch earlier.
strcpy_newline_end:
movzx eax, byte [rsi] ; get byte (without false dependency).
cmp al, 10
je copy_done ; first byte isn't newline, enter loop.
copy_loop: ; do:
mov [rdi], al ; put byte.
inc rsi ; increment both pointers.
inc rdi
movzx eax, byte [rsi] ; get next byte.
cmp al, 10
jne copy_loop ; until you get a newline.
; After falling out of the loop (or jumping here from the top)
; we've loaded but *not* stored the terminating newline
copy_done:
ret
You should also be aware there are other tricks you can use, to save instructions inside the loop, such as addressing one string relative to the other (with an indexed addressing mode for the load, only incrementing one pointer).
However, we won't cover them in detail here as it risks making the answer more complex than it needs to be. | unknown | |
d11250 | train | In .NET Core, X509Certificate2.PublicKey.Key and X509Certificate2.PrivateKey use platform-specific implementation of key. On Windows, there are two implementations, legacy RSACryptoServiceProvider and modern RSACng.
You have to change the way how you access these properties. And do not access them. Instead, use extension methods: X509Certificate2 Extension Methods. They return safe abstract classes you shall use. Do not try to use explicit cast to anything. For RSA keys use RSA class and so on.
X509Certificate2 objCert = new X509Certificate2(path);
// well, it is reasonable to check the algorithm of public key. If it is ECC,
// then call objCert.GetECDsaPublicKey()
RSA rsa = objCert.GetRsaPublicKey();
byte [] EncrRes = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1);
A: Figured it out on my own. Instead of
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)objCert.PublicKey.Key;
do
RSA rsa_helper = (RSA)objCert.PublicKey.Key;
RSAParameters certparams = rsa_helper.ExportParameters(false);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
RSAParameters paramcopy = new RSAParameters();
paramcopy.Exponent = certparams.Exponent;
paramcopy.Modulus = certparams.Modulus;
rsa.ImportParameters(paramcopy);
Works with .NET 2.0+ and .NET Core! | unknown | |
d11251 | train | When they are dragged set a click handler to prevent the default action, like so:
ui.draggable.find('a').click(function(e) { e.preventDefault(); });
As I said, do it when they are dragged in case it's too late when doing it in the dropped event.
UPDATE:
$('.draggable').draggable({
start: function( event, ui ) {
$('#dropdownAddTile').slideDown();
ui.draggable.find('a').click(function(e) {
e.preventDefault();
});
},
stop: function() {
$('#dropdownAddTile').slideUp();
},
containment: '#container',
snap:'.droppable',
snapMode:'inner',
revert:'invalid',
snapTolerance: 32
});
so you can call ui.draggable.find('a').click(function(e) { e.preventDefault();
A: The issue didn't arise in Chrome, Firefox, or IE10 but it did happen in IE9 and lower.
My advice would be to run preventDefault on the event. Using your code,
function handleDropEvent( event, ui ) {
event.preventDefault();
var draggable = ui.draggable;
var droppable = $(this);
var droppableId = $(this).attr("id");
var draggableId = ui.draggable.attr("id");
$('.draggable').draggable({containment: '#container', snap:'.droppable', snapMode:'inner', revert:'invalid',snapTolerance: 32});
$('.droppable').droppable({drop: handleDropEvent, accept: function(e){if(e.hasClass('draggable')) { if (!$(this).hasClass('occupied')) {return true; }}}});
var initPosit = ui.draggable.parent().attr('id');
$.post("tiles/updateTilePosition", { draggableId:draggableId, droppableId: droppableId }).done(function(data) {
})
$(this).addClass('occupied');
ui.draggable.parent().removeClass('occupied');
if($(ui.draggable).parent() !==$(this)){
$(ui.draggable).appendTo($( this ));
}
}
Also, if you view your source code, everything is encoded (apostrophes, quotes, etc.) Not sure how that happened but I'd fix that.
A: If I understood correctly you just want the a link not to be drag able right?
Do this:
<a href="#test" draggable="false">Test</a>
This is basically how you disable the drag function idk why everyone writes such a long code for this....
A: Try setting the onclick to
return false; | unknown | |
d11252 | train | You can add a custom window editor which implements OnHierarchyChange to handle all the changes in the hierarchy window. This script must be inside the Editor folder. To make it work automatically make sure you have this window opened first.
using System.Linq;
using UnityEditor;
using UnityEngine;
public class HierarchyMonitorWindow : EditorWindow
{
[MenuItem("Window/Hierarchy Monitor")]
static void CreateWindow()
{
EditorWindow.GetWindow<HierarchyMonitorWindow>();
}
void OnHierarchyChange()
{
var addedObjects = Resources.FindObjectsOfTypeAll<MyScript>()
.Where(x => x.isAdded < 2);
foreach (var item in addedObjects)
{
//if (item.isAdded == 0) early setup
if (item.isAdded == 1) {
// do setup here,
// will happen just after user releases mouse
// will only happen once
Vector3 p = transform.position;
item.transform.position = new Vector3(p.x, 2f, p.z);
}
// finish with this:
item.isAdded++;
}
}
}
I attached the following script to the box:
public class MyScript : MonoBehaviour {
public int isAdded { get; set; }
}
Note that OnHierarchyChange is called twice (once when you start dragging the box onto the scene, and once when you release the mouse button) so isAdded is defined as an int to enable its comparison with 2. So you can also have initialization logic when x.isAdded < 1
A: You could thy this:
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
[ExecuteInEditMode]
public class PrintAwake : MonoBehaviour
{
#if UNITY_EDITOR
void Awake() .. Start() also works perfectly
{
if(!EditorApplication.isPlaying)
Debug.Log("Editor causes this Awake");
}
#endif
}
See https://docs.unity3d.com/ScriptReference/ExecuteInEditMode.html
Analysis:
*
*This does in fact work!
*One problem! It happens when the object starts to exist, so, when you are dragging it to the scene, but before you let go. So in fact, if you specifically want to adjust the position in some way (snapping to a grid - whatever) it is not possible using this technique!
So, for example, this will work perfectly:
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
[ExecuteInEditMode]
public class PrintAwake : MonoBehaviour
{
#if UNITY_EDITOR
void Start() {
if(!EditorApplication.isPlaying) {
Debug.Log("Editor causes this START!!");
RandomSpinSetup();
}
}
#endif
private void RandomSpinSetup() {
float r = Random.Range(3,8) * 10f;
transform.eulerAngles = new Vector3(0f, r, 0f);
name = "Cube: " + r + "°";
}
}
Note that this works correctly, that is to say it does "not run" when you actually Play the game. If you hit "Play" it won't then again set random spins :)
Great stuff
A: Have a similar issue - wanted to do some stuff after object was dragged into scene (or scene was opened with already existed object). But in my case gameobject was disabled. So I couldn't use neither Awake, nor Start.
Solved via akin of dirty trick - just used constructor for my MonoBehaviour class. Unity blocks any attempts to use most of API inside MonoBehaviour constructors, but we could just wait for some time, for example via EditorApplication.delayedCall. So code looks like this:
public class ExampleClass: MonoBehaviour
{
//...
// some runtime logic
//...
#if UNITY_EDITOR
//Constructor
ExampleClass()
{
EditorApplication.delayCall += DoSomeStuffForDisabledObjectAfterCreation;
}
void DoSomeStuffForDisabledObjectAfterCreation()
{
if (!isActiveAndEnabled)
{
//Some usefull stuff
}
}
#endif
}
A: Monobehaviours have a Reset method, that only gets called in Editor mode, whenever you reset or first instantiate an object.
public class Example : MonoBehaviour
{
void Reset()
{
transform.position =
new Vector3(transform.position.x, 2.22f, transform.position.z);
Debug.Log("Hi ...");
}
} | unknown | |
d11253 | train | Its not possible to write a custom aggregation function for a standard pivot table. But you can probably do what you want using MDX... maybe an MDX expert would like to comment? | unknown | |
d11254 | train | According to this question there is no tui support on mac by default. So you have to compile gdb yourself with TUI enabled. | unknown | |
d11255 | train | Maybe just add the missing dependency
<plugin>
<artifactId>maven-release-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.apache.maven.scm</groupId>
<artifactId>maven-scm-api</artifactId>
<version>1.10.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven.scm</groupId>
<artifactId>maven-scm-provider-gitexe</artifactId>
<version>1.10.0</version>
</dependency>
</dependencies>
</plugin> | unknown | |
d11256 | train | You can simply use matplotlib.pyplot.plot method. For example:
import numpy as np
import matplotlib.pyplot as plt
def plot_PR(precision_bundle, recall_bundle, save_path:Path=None):
line = plt.plot(recall_bundle, precision_bundle, linewidth=2, markersize=6)
line = plt.title('Precision/Recall curve', size =18, weight='bold')
line = plt.ylabel('Precision', size=15)
line = plt.xlabel('Recall', size=15 )
random_classifier_line_x = np.linspace(0, 1, 10)
random_classifier_line_y = np.linspace(1, 0, 10)
_ = plt.plot(random_classifier_line_x, random_classifier_line_y, color='firebrick', linestyle='--')
if save_path:
outname = save_path / 'PR_curve_thresh_opt.png'
_ = plt.savefig(outname, dpi = 100, bbox_inches='tight' )
return line
and then just use it as plot_PR(precision_bundle, recall_bundle).
Note: here I also added a dashed line for a random classifier and the possibility to save the figure in case you want to | unknown | |
d11257 | train | If the only difference is truly the hyphen, try a different type of hyphen (e.g. an 'actual' hyphen, instead of the minus sign: http://unicode-table.com/en/2010/).
I should say I cannot reproduce this exactly.
The images in my example (left vs. right) are about a pixel or so different, not as much as yours:
A: I had this same issue and was only able to solve it with html. You can add html code directly into the markdown file:
<table width="100%">
<thead>
<tr>
<th width="50%">First header</th>
<th width="50%">Second header long</th>
</tr>
</thead>
<tbody>
<tr>
<td width="50%"><img src="https://docs.github.com/assets/cb-194149/images/help/images/view.png"/></td>
<td width="50%"><img src="https://docs.github.com/assets/cb-194149/images/help/images/view.png"/></td>
</tr>
</tbody>
</table> | unknown | |
d11258 | train | Yes, you can use MapStore and MapLoader to persist file to local storage. Read official documentation here.
https://docs.hazelcast.org/docs/latest/manual/html-single/#loading-and-storing-persistent-data
A: Hazelcast has two types of distributed objects in terms of their partitioning strategies:
*
*Data structures where each partition stores a part of the instance, namely partitioned data structures.
*Data structures where a single partition stores the whole instance, namely non-partitioned data structures.
Partitioned Hazelcast data structures persistence data to local file system is not supported,need a centralized system that is accessible from all hazelcast members,like mysql or mongodb.
You can get code from hazelcast-code-samples. | unknown | |
d11259 | train | Or change timestamp's type to Byte[]. More [info]:http://geekswithblogs.net/frankw/archive/2008/08/29/serialization-issue-with-timestamp-in-linq-to-sql.aspx
A: It can be fixed by changing the ReadOnly property on the timestamp column, in the DBML, to true. | unknown | |
d11260 | train | Just use e.preventDefault() in onClick | unknown | |
d11261 | train | Use unstack with to_frame i.e
ndf = df.unstack().to_frame().sort_index(level=1)
0
Year
JAN 2015 96.6
FEB 2015 58.9
MAR 2015 23.5
APR 2015 18.6
MAY 2015 62.9
JUN 2015 26.7
JUL 2015 60.0
AUG 2015 108.6
SEP 2015 67.9
OCT 2015 58.1
NOV 2015 78.0
DEC 2015 80.4
JAN 2016 131.8
FEB 2016 54.2
MAR 2016 80.2
APR 2016 51.2
MAY 2016 64.1
JUN 2016 91.3
JUL 2016 17.4
AUG 2016 38.8
SEP 2016 50.9
OCT 2016 29.8
NOV 2016 100.6
DEC 2016 17.4
If you need index as a string then
ndf.index = ['{} {}'.format(i,j) for i,j in ndf.index.values]
If you need it as a datetime then
ndf.index = pd.to_datetime(['{} {}'.format(i,j) for i,j in ndf.index.values]) | unknown | |
d11262 | train | You'll get this error when mixing the CommonJS module.exports with ES Modules. You'll have to change module.exports to its ES Module counterpart export default:
import Worker from '../workers/sim.js';
class Synapse {
// ...
}
export default Synapse; // ES Module syntax
A: You are doing import and export in the same file which is not allowed by webpack
better to do like this
const {Worker} = require('../workers/sim.js');
class Synapse {
// ...
}
module.exports = {Synapse}; | unknown | |
d11263 | train | A statement level trigger (i.e. without FOR EACH ROW clause) will update always all records in Payments table, I don't think that's needed. For an update of only related products, use this trigger:
create trigger PROD_TOTAL
after insert ON Products
for each row
begin
update Payments
set ProdTotal = :new.ProdPrice * :new.ProdQuantity
WHERE PayProdId = :new.ProdId ;
end; | unknown | |
d11264 | train | I believe the issue was in building the model using optuna. After several errors and fixing a lot of issues, I got it all working. If anyone's interested here's the section relevant to the errors I was getting.
def create_model(trial):
# We optimize the numbers of layers, their units and weight decay parameter.
n_layers = trial.suggest_int("n_layers", 3, 20)
weight_decay = trial.suggest_float("weight_decay", 1e-100, 1e-1, log=True)
lr = trial.suggest_float("lr", 1e-12, 1e-1, log=True)
momentum = trial.suggest_float("momentum", 0.0, 1.0)
model = tf.keras.Sequential()
#model.add(Dropout(0.1))
for i in range(n_layers):
dropout = trial.suggest_float("dropout_l{}".format(i), 0.05, 0.5)
num_hidden = trial.suggest_int("n_units_l{}".format(i), 32, 256, log=True)
model = Sequential()
model.add(LSTM(num_hidden, input_shape=(train_x.shape[1:]), return_sequences=True))
model.add(Dropout(rate=dropout))
model.add(LSTM(num_hidden))
model.add(Dropout(rate=dropout))
model.add(Dense(num_hidden, activation='relu'))
model.add(Dropout(rate=dropout))
model.add(tf.keras.layers.Flatten())
model.add(Dense(
num_hidden,
activation="relu",
kernel_regularizer=tf.keras.regularizers.l2(weight_decay)
)
)
model.add(Dense(2, activation='softmax', kernel_regularizer=tf.keras.regularizers.l2(weight_decay)))
#tf.keras.layers.Dense(2, kernel_regularizer=tf.keras.regularizers.l2(weight_decay)))
# Compile model.
model.compile(
optimizer=tf.keras.optimizers.SGD(lr=lr, momentum=momentum, nesterov=True),
loss="sparse_categorical_crossentropy",
metrics=["accuracy"],
)
return model
and if you want to see all of the code for it here's what I have so far, needs a lot of tidying up but it works. Any advice is greatly appreciated.
https://colab.research.google.com/drive/1cgnz7XUwnhfBvsA9whCXKQ3PrRs_sddh?usp=sharing | unknown | |
d11265 | train | You are using HTTP server directives to "retrieve" something "externally". This is what typically an HTTP client does.
For this sort of things, you can use akka http client api.
For example:
val response = Http().singleRequest(HttpRequest(uri = "http://akka.io"))
response onComplete {
case Success(res) =>
val entity = Unmarshal(res.entity).to[YourDomainObject]
// use entity here
case Failure(ex) => // do something here
}
However, this requires some Unmarshaller (to deserialize the received json). Take also a look at Json Support, as it helps you define marshallers easily:
case class YourDomainObject(id: String, name: String)
implicit val YourDomainObjectFormat = jsonFormat2(YourDomainObject)
A: I think what you are trying to ask is how to get the body i.e in JSOn format to the Case class that you have
Here is a quick example:
path("createBot" / Segment) { tag: String =>
post {
decodeRequest {
entity(as[CaseClassName]) { caseclassInstance: CaseClassName =>
val updatedAnswer = doSomeStuff(caseclassInstance)
complete {
"Done"
}
}
}
You can find more detailed example from here : https://github.com/InternityFoundation/Stackoverflowbots/blob/master/src/main/scala/in/internity/http/RestService.scala#L56
I hope it answers your question. | unknown | |
d11266 | train | A "map" really is the best way. Good news is that you can save a few keystrokes with shorthand property names (ES2015):
import * as People from ./People.json
import * as Education from ./Education.json
import * as Vehicle from ./Vehicle.json
const lookup = {People,Education,Vehicle}; // equivalent to {"People":People, ...}
function transpose(str : string) {
let data = {};
if(validate(str)) //validate function returns true if valid string
data = lookup[str] //data takes in the string value and uses variable name
runFile(data); //runFile expects data to be a JSON type
...
}
A: Useful if you want to pass in JSON as a parameter to the transpose function.
function transpose(jsonObj, str) {
let data = {};
if(validate(str))
{
data = jsonObj[str];
runFile(data); //runFile expects data to be a JSON type
}
...
} | unknown | |
d11267 | train | It sounds like you have a trigger built into a hyperlink or a form... so although your script runs, the browser navigates and refreshes the page.
If you have a click event, you need to stop the event from propagating.
Short example:
HTML
<div id="example">
</div>
<form>
<input type="number" id="num" />
<button id="clicker">
Go
</button>
</form>
JavaScript
document.getElementById('clicker').onclick = function () {
document.getElementById('example').innerHTML = 'Content';
// return false; // <-- without this (or an alternative) the form posts
} | unknown | |
d11268 | train | Your addition operator is using unitinitialized member Inputsec, Inputmint and Inputhours variables. It should look like this:
time operator+(time Inputobj)
{
return time(sec+InputObj.sec, mint+InputObj.mint, hours+InputObj.hours);
}
or
time operator+(time Inputobj)
{
InputObj.sec += sec;
InputObj.mint += mint;
InputObj.hours += hours;
return InputObj;
}
Or, even better, implement time& operator+=(const time& rhs); and use it in a non-member addition operator:
time operator+(time lhs, const time& rhs)
{
return lhs += rhs;
}
You have two sets of member variables representing the same thing. You do not need this duplication.
One final remark: there is something called std::time in header<ctime>. Having a class called time, and using namespace std is asking for trouble. You should avoid both if possible (avoiding the second is definitely possible).
A: You should rewrite your operator+ at least as follows:
time operator+(time Inputobj)
{
time blah time(sec+InputObj.sec, mint+InputObj.mint, hours+InputObj.hours);
return blah;
}
also I think you should use the % operator for getting the correct time results:
time operator+(time Inputobj){
int s = (sec+InputObj.sec) % 60;
int m = (sec+InputObj.sec) / 60 + (mint+InputObj.mint) % 60;
int h = (mint+InputObj.mint) / 60 + (hours+InputObj.hours) % 24;
return time(s,m,h);
}
A: Your operator overloading function is using uninitialized variables. Initialize variables inputsec, inputmint, Inputhours in your constructor.
Moreover, try this:
time operator+ (time Inputobj)
{
time blah (sec+Inputobj.sec, mint+Inputobj.mint, hours+Inputobj.hours);
return blah;
}
A: Your error is your publics members with the same name as the parameter constructor, which are unitialized.
Try this :
#include <iostream>
using namespace std;
class time
{
private:
int sec;
int mint;
int hours;
public:
time(int Inputsec, int Inputmint, int Inputhours):sec(Inputsec), mint(Inputmint), hours(Inputhours)
{
};
time operator+(time Inputobj)
{
time blah (sec+Inputobj.sec, mint+Inputobj.mint, hours+Inputobj.hours);
return blah;
}
void DisplayCurrentTime()
{
cout << "The Current Time Is"<<endl<< hours<<" hours"<<endl<<mint<<"minutes"<<endl<<sec<<"seconds"<<endl;
}
};
int main()
{
time now(11,13,3);
time after(13,31,11);
time then(now+after);
then.DisplayCurrentTime();
} | unknown | |
d11269 | train | These are the answers to your questions:
1. Your url is not working because of there is a $ at the end of users.urls url. $ is a zero width token which means an end in regex. So remove it.
2. You do not need to add <username> at the profile_update url. If you are using UpdateView, then add slug_url_kwarg attribute to UpdateView, like:
class MyUpdateView(UpdateView):
slug_url_kwarg = "username"
If you are using function based view, then simply use:
def myview(request,username):
.... | unknown | |
d11270 | train | I think wine will not find paths like /home/martin/....
One possibility would be to put groundfilter.exe (and possibly dlls it needs) into the directory you want to work with, and set the R working directory to that directory using setwd().
The other possibility I see would be to give a path that wine understands, like Z:/home/martin/....
This is not an authoritative answer, just my thoughts, so please refer to the documentation for the real story. | unknown | |
d11271 | train | I'm pretty late with this, but I was googling "silverlight operationcontext" and found your SO question as well as the blog post that I am linking (one right after the other in the Google results). I don't know if it will help or not (he says, almost two years later).
I haven't worked much with WCF and not at all with WFF, so I don't really have much to add aside from this link. | unknown | |
d11272 | train | draw.io is a drawing tool, not a UML tool.
As such you can simply draw two class shapes, connect them with an association shape, then draw a third class as you association class and then use an association shape to connect you association class to the association.
Then go into the properties of the last association shape and change the line style to dashed.
Now it looks like a valid UML Association class, but I think you should really opt for a real UML tool instead of a drawing tool when you want to do anything with UML. Using this tool is similar to writing Java with MS Word.
A: The accepted answer is far to be perfect. In Draw.io (now called Diagrams.net), you can connect two shapes (here classes) with a connector but you cannot connect two connectors together.
Consequently, with the given solution, it will look like an association class but the dashes will not be really adjusted :
And really worste, if you need to re-arrange your diagram, the association link will not move and you will have to re-adjust it manually :
So, as it is sadly not possible to have a 100% satisfying solution for an association class, another solution is to turn the association class as a regular class. Here in the example, the OrderLine class is associated with both Order and Product classes. It is worth to note the migration of the multiplicities. Refactoring a class association as such an association will ALWAYS lead to have a 1 multiplicity for the non-association classes (here Order and Product), and the original multiplicities will be moved to the association class (here OrderLine). | unknown | |
d11273 | train | That's quoted printable encoding. You need to undo the content-transfer-encoding, which might be quoted printable or base64. | unknown | |
d11274 | train | So first you have a lot of typos / code that doesn't even compile.
You use e.g. once directionOfBirdFromPlanet but later call it directionOfGameObjectFromMiddle ;) Your Start is quite redundant.
As said bird.rigidbody2D is deprecaded and you should rather use GetComponent<Rigidbody2D>() or even better directly make your field of type
public Rigidbody2D bird;
For having multiple objects you could simply assign them to a List and do
public class Planet : MonoBehaviour
{
// Directly use the correct field type
public List<Rigidbody2D> birds;
// Make this field adjustable via the Inspector for fine tuning
[SerializeField] private float gravitationalForce = 5;
// Your start was redundant
private void FixedUpdate()
{
// iterate through all birds
foreach (var bird in birds)
{
// Since transform.position is a Vector3 but bird.position is a Vector2 you now have to cast
var directionOfBirdFromPlanet = ((Vector2) transform.position - bird.position).normalized;
// Adds the force towards the center
bird.AddForce(directionOfBirdFromPlanet * gravitationalForce);
}
}
}
Then on the planet you reference all the bird objects
On the birds' Rigidbody2D component make sure to set
Gravity Scale -> 0
you also can play with the Linear Drag so in simple words how much should the object slow down itself while moving
E.g. this is how it looks like with Linear Drag = 0 so your objects will continue to move away from the center with the same "energy"
this is what happens with Linear Drag = 0.3 so your objects lose "energy" over time | unknown | |
d11275 | train | if you:
include ActionController::PolymorphicRoutes
In your model:
class SomeModel < ActiveRecord::Base
include ActionController::PolymorphicRoutes
end
you get polymorphic_path and polymorphic_url. These can then be used by passing self into the methods if you're generating a route for the current AR object. | unknown | |
d11276 | train | In the design definition you can add a callback node where your facet should appear. This should expose the Editable Area when you add your control to another page.
The format for the callback node would look similar to
<xp:callback id="callbackID" facetName="facetname" />
A: Dan,
Can you get the Editable Area as a javax.faces.component.UIComponent and then do .getFacets()?
BTW, hope you're well! | unknown | |
d11277 | train | The meaning is Information Repository.
A: Although there's no official statement on the matter AFAIK, I tend to think about it as Internal Resource (various resources the system needs to work fine, but not actually meaningful for normal users day-to-day work), just as I think about the res prefix as Resource (which is not internal, it's for normal usage).
As example, res.config is to create visual configuration wizards to be presented to a user that may not be the sysadmin (he could be just the sales responsible for example), but many settings are actually stored as ir.config_parameter records, which are only accessible for the sysadmin and are used extensively by Odoo internal code. | unknown | |
d11278 | train | In web.config add the following:
<system.web>
<globalization culture="en-GB" uiCulture="en-GB" />
</system.web>
It should change the default date parsing. | unknown | |
d11279 | train | in your code, you define the loop which is reading all the objects in response and there is no unique id for each of the appended elements so we are going to assign each appended div with a unique id which we will get from the response in your case we will use comment_id and before append we will check if this element has existed or not
window.setInterval(function() {
$.post('<?php echo base_url(); ?>ClientCont/List_Files/fetchmessage', {
id: folderid
}, function(data) {
console.log(data);
if (data.length > 0) {
var a;
for (a = 0; a < data.length; a++) {
if ($('#dateconvo' + data[a]['comment_id']).length == 0) {
$('#previouscomment').append("<div id = 'dateconvo" + data[a]['comment_id'] + "' style = 'margin-top:20px;text-align:center;color:#D3D3D3'>" + data[a]['date_entry'] + "</div><br>" +
"<input id = 'oldid' type = 'hidden' value = " + data[a]['comment_id'] + ">" +
"<div id = 'usernamemessage' style = 'color:#D3D3D3'>" + atob(data[a]['name_user']) + "</div>" +
"<div id = 'messageme' style = 'margin-left:10px;margin-top:10px;border-radius: .4em;background-color: #4CAF50!important; border-radius: 5px;box-shadow: 0 0 6px #B2B2B2; display: inline-block;padding: 10px 18px;position: relative;vertical-align: top;color:#FFFFFF'>" +
data[a]['message']) + "\n";
}
}
} else {
$('#previouscomment').append("<div align = 'center' style = 'margin-top:30px;color:#D3D3D3'><img src = '<?php echo base_url();?>assets/images/nocommentyet.png' align = 'middle' style = 'height:100px;width:100px;'/>" + "<br>NO COMMENT TO DISPLAY</div>");
}
$("#previouscomment").animate({
scrollTop: "2000000000000px"
}, "fast");
}, 'json');
}, 1000); | unknown | |
d11280 | train | I am not sure if I fully understand the question so please forgive if I miss something.
I desired a similar setup, multiple projects in a workspace, but all managed by Cocoapods. I needed the projects to link to each other. My motive was promoting MVC separation, so I had an App project (view), a Controller project, a Model project. The shell of a project is here: https://github.com/premosystems/iOSMVCTemplate/tree/1.0/MVC-Example/iOS/MVCApp
Here are the basic steps:
*
*Create your projects, and add a podspec to each one. (e.g. controller podspec like this one: https://github.com/premosystems/iOSMVCTemplate/blob/1.0/MVC-Example/iOS/MVCApp/Controller/ProximityController/ProximityController.podspec)
*Add a Podfile that links all of the podspecs together. https://github.com/premosystems/iOSMVCTemplate/blob/1.0/MVC-Example/iOS/MVCApp/Podfile
*And of course pod install :)
Be sure to reference the podspecs you create in the Podfile using the :path=> development directive before they are referenced by any podspecs so cocoapods will know not to look in the public repository.
I have been using this a month or so, and it works pretty well. Only drawback is that indexing and compile time take longer than I would like, and pod update is really slow. Before adding and new files, .h, .m to any podspecs you must run pod update.
Best of luck! | unknown | |
d11281 | train | Passing objects from one component to a child component is the purpose of props.
You can pass many items through props. VueJS has the following types built-in:
*
*String
*Number
*Boolean
*Array
*Object
*Function
*Promise
In the V3 VueJS guide it gives the following example of a prop being passed into a component and then being logged to the console inside the setup() method.
export default {
props: {
title: String
},
setup(props) {
console.log(props.title)
}
}
However, when using props, you should always mark whether the is required, what its type is and what the default is if it is not required.
For example:
export default {
props: {
title: String, // This is the type
required: false, // If the prop is required
default: () => 'defaultText' // Default needed if required false
},
setup(props) {
console.log(props.title)
}
}
It's important to note that when using default, the value must be returned from a function. You cannot pass a default value directly. | unknown | |
d11282 | train | You are not calling super.ready() in your ready callback.
This is required because the Polymer.Element declares a ready function to initialise the elements template and data system. As you are overriding this function, you need to call the super class function to initialise your element.
See the info on initialisation.
Without super.ready()
With call to super.ready()
I also noticed that in your handleClick function, you have mis-typed the function you wish to call. | unknown | |
d11283 | train | The node.js driver findOne has a different call signature than the findOne in the MongoDB shell. You pass the field selection object as the projection element of the options parameter:
dbo.collection("users")
.findOne({"friends.email": email},
{projection: { friends: { $elemMatch: { email: email } } } },
function(errT, resultT) {...});
A: If you want to find for any values which is stored in some variable, you use regex for that. Your query should look like
dbo.collection("users").findOne({
email: new RegExp(emailGiven, 'i'),
"friends.email": new RegExp(element.email, 'i')
}, {
friends: {
$elemMatch: {
email: new RegExp(element.email, 'i')
}
}
}, function(errT, resultT) {})
i is for case insensitive comparison here | unknown | |
d11284 | train | try float.Parse, but you need to convert the datarow to dynamic/string type for it to be compatible:
var test = (dynamic)fb[fb.Table.Columns.Count - 1];
float boat = float.Parse(test);
Or something similar using float.Parse
A: You can try after converting it to String like this,
float akun = float.Parse(fb[fb.Table.Columns.Count - 1].ToString()) /
float.Parse(fb[u].ToString());
A: As noted in my comment, try casting the relevant columns to Decimal first. It is one of the explicitly supported DataTypes when accessing data from columns of DataRow instances; the valid types are listed in the MSDN DataColumn Reference page | unknown | |
d11285 | train | Pros: you can end up with code which is simpler to read. Few people would argue that:
BigDecimal a = x.add(y).divide(z).plus(m.times(n));
is as easy to read as
BigDecimal a = ((x + y) / z) + (m * n); // Brackets added for clarity
Cons: it's harder to tell what's being called. I seem to remember that in C++, a statement of the form
a = b[i];
can end up performing 7 custom operations, although I can't remember what they all are. I may be slightly "off" on the example, but the principle is right - operator overloading and custom conversions can "hide" code.
A: EDIT: it has been mentioned that std::complex is a much better example than std::string for "good use" of operator overloading, so I am including an example of that as well:
std::complex<double> c;
c = 10.0;
c += 2.0;
c = std::complex<double>(10.0, 1.0);
c = c + 10.0;
Aside from the constructor syntax, it looks and acts just like any other built in type.
The primary pro is that you can create new types which act like the built in types. A good example of this is std::string (see above for a better example) in c++. Which is implemented in the library and is not a basic type. Yet you can write things like:
std::string s = "hello"
s += " world";
if(s == "hello world") {
//....
}
The downside is that it is easy to abuse. Poor choices in operator overloading can lead to accidentally inefficient or unclear code. Imagine if std::list had an operator[]. You may be tempted to write:
for(int i = 0; i < l.size(); ++i) {
l[i] += 10;
}
that's an O(n^2) algorithm! Ouch. Fortunately, std::list does not have operator[] since it is assumed to be an efficient operation.
A: The initial driver is usually maths. Programmers want to add vectors and quaternions by writing a + b and multiply matrices by vectors with M * v.
It has much broader scope than that. For instance, smart pointers look syntactically like normal pointers, streams can look a bit like Unix pipes and various custom data structures can be used as if they were arrays (with strings as indexes, even!).
The general principle behind overloading is to allow library implementors to enhance the language in a seamless way. This is both a strength and a curse. It provides a very powerful way to make the language seem richer than it is out of the box, but it is also highly vulnerable to abuse (more so than many other C++ features).
A: You can do some interesting tricks with syntax (i.e. streams in C++) and you can make some code very concise. However, you can have the effect of making code very difficult to debug and understand. You sort of have to constantly be on your guard about the effects of various operators of different kinds of objects.
A: You might deem operator overloading as a kind of method/function overloading. It is part of polymorphism in object oriented language.
With overloading, each class of objects work like primitive types, which make classes more natural to use, just as easy as 1 + 2.
Say a complex number class, Complex.
Complex(1,2i) + Complex(2,3i) yields Complex(3,5i).
5 + Complex(3, 2i) yields Complex(8, 2i).
Complex(2, 4i) + -1.8 yields Complex(0.2, 4i).
It is much easier to use class this way. If there is no operator overloading, you have to use a bunch of class methods to denote 'add' and make the notation clumsy.
The operator overloading ought to be defined carefully; otherwise, comes confusion. For example, '+' operator is natural to adding numbers, time, date, or concatenation of array or text. Adding '+' operator to a class of Mouse or Car might not make any sense. Sometimes some overloading might not be seem natural to some people. For example, Array(1,2,3) + Array(3,4,5). Some might expect Array(4,6,8) but some expect Array(1,2,3,3,4,5). | unknown | |
d11286 | train | Is it possible to put dir1...3 in git repo1, as a submodule, then all
project codes in project folder in git repo2, which is the main git
repo that hosts git repo1 as the submodule?
That's totally feasible. But the .git of the master project have to be in the root directory (it's up to you to say if it's good for you or not), since submodules have to be located inside the repo's path (which is defined by the location of the .git folder).
From root :
git init
git submodule add <remote_url> dir1
git submodule add <remote_url> dir2
git submodule add <remote_url> dir3
mkdir project<n>
git submodule update --init --recursive
git commit -m "Added the submodule to the project." | unknown | |
d11287 | train | To do this, you would need to increment a counter on each iteration (like you are trying to avoid).
count=0
while read -r line; do
printf '%d %s\n' "$count" "${line*//}"
(( count++ ))
done < test.txt
EDIT: After some more thought, you can do it without a counter if you have bash version 4 or higher:
mapfile -t arr < test.txt
for i in "${!arr[@]}"; do
printf '%d %s' "$i" "${arr[i]}"
done
The mapfile builtin reads the entire contents of the file into the array. You can then iterate over the indices of the array, which will be the line numbers and access that element.
A: You can use a range to go through, it can be an array, a string, a input line or a list.
In this example, i use a list of numbers [0..10] is used with an increment of 2, as well.
#!/bin/bash
for i in {0..10..2}; do
echo " $i times"
done
The output is:
0 times
2 times
4 times
6 times
8 times
10 times
To print the index regardless of the loop range, you have to use a variable "COUNTER=0" and increase it in each iteration "COUNTER+1".
my solution prints each iteration, the FOR traverses an inputline and increments by one each iteration, also shows each of words in the inputline:
#!/bin/bash
COUNTER=0
line="this is a sample input line"
for word in $line; do
echo "This i a word number $COUNTER: $word"
COUNTER=$((COUNTER+1))
done
The output is:
This i a word number 0: this
This i a word number 1: is
This i a word number 2: a
This i a word number 3: sample
This i a word number 4: input
This i a word number 5: line
to see more about loops: enter link description here
to test your scripts: enter link description here
A: n=0
cat test.txt | while read line; do
printf "%7s %s\n" "$n" "${line#*//}"
n=$((n+1))
done
This will work in Bourne shell as well, of course.
If you really want to avoid incrementing a variable, you can pipe the output through grep or awk:
cat test.txt | while read line; do
printf " %s\n" "${line#*//}"
done | grep -n .
or
awk '{sub(/.*\/\//, ""); print NR,$0}' test.txt
A: You don't often see it, but you can have multiple commands in the condition clause of a while loop. The following still requires an explicit counter variable, but the arrangement may be more suitable or appealing for some uses.
while ((i++)); read -r line
do
echo "$i $line"
done < inputfile
The while condition is satisfied by whatever the last command returns (read in this case).
Some people prefer to include the do on the same line. This is what that would look like:
while ((i++)); read -r line; do
echo "$i $line"
done < inputfile
A: Update: Other answers posted here are better, especially those of @Graham and @DennisWilliamson.
Something very like this should suit:
tr -s ' ' '\n' <test.txt | nl -ba
You can add a -v0 flag to the nl command if you want indexing from 0. | unknown | |
d11288 | train | In the end, I have a workaround for this problem. I split my zip file into two files, with each containing about 20k entries. Voila, it works like a charm again.
I've heard of Java's problem with reading entries in zip files of more than 64k entries. What I have no idea why is my file has only about 40k entries but it faces the problem as well. | unknown | |
d11289 | train | useEffect with an empty dependency array will fire once when the component mounts. This is a good place to get that value from local storage and set it to the state. Then your close function can just set the local storage to true.
I made a sandbox for you here: https://codesandbox.io/s/crazy-davinci-io03f?file=/src/App.js
You should probably initialise your state to false too. This will avoid that flicker that you see. | unknown | |
d11290 | train | Good day.
1. Reset Function
Create a 'reset' method to contain all the code to revert your game as you might have other attributes to change as well.
2. Callback Method
Create a callback function for your 'back' button. This callback might check for a condition before it calls the 'reset' method. i,e
if game_won: reset() | unknown | |
d11291 | train | " It sounds as if rebasing "replays" commits, one after another (so sequentially) from the source branch over the changes in my working branch, is this the case? "
Yes.
" Furthermore, it does so, one develop commit at a time, until all the changes have been "replayed" into my feature branch, yes? "
No, it's the contrary. If you rebase your branch on origin/develop, all your branch's commits are to be replayed on top of origin/develop, not the other way around.
Finally, the difference between merge and rebase scenarios has been described in details everywhere, including on this site, but very broadly the merge workflow will add a merge commit to history. For that last part, take a look here for a start.
A: RomainValeri's answer covers a lot of this, but let me add a few more items:
*
*"Replaying" a commit is a matter of running git cherry-pick or doing something equivalent. Some versions of git rebase literally do run git cherry-pick and if you want to think about how rebase works, that's the concrete piece to consider. (If you want to get into all the side details, the other principal way to "copy" a commit is to use git format-patch and git am: this goes faster because it doesn't handle renames properly. So the cherry-pick method is normally better. It was not the default until relatively recently, though, except for interactive rebases and any rebases that used the interactive machinery.)
*Merge commits literally cannot be cherry-picked, so when using git rebase --rebase-merges, Git can't do that. Instead, Git will re-perform the merges. That is, Git figures out, at the start of the rebase operation, which commits are ordinary (single-parent) commits that can be cherry-picked, and which ones are merges with two or more parents. It then lays out, in the interactive rebase script—this particular kind of rebase always uses the interactive machinery—the special extra commands that interactive rebase needs in order to run git merge again. You can see these commands by adding --interactive to your rebase command. Be careful if you edit them: they have to be run in the right order for everything to work.
*If you have merge commits that git rebase would need to "replay", and you don't use --rebase-merges, git rebase simply drops these merge commits entirely. The result is ... often not good. But if you did a merge that you did not mean to do, and want to do a rebase instead, it actually is good: this strips out the final merge.
The TL;DR version of this is: both are complicated. Using git merge often makes one (1) new merge commit, that combines work. Using git rebase copies, as if by cherry-pick, many commits, and abandons the old (and lousy?) commits for the new-and-improved copies.
When using either git cherry-pick or git merge, merge conflicts can occur. Git 2.33 is likely to have git rerere enabled by default, so that any previous resolution for some particular merge conflict will be picked up automatically and re-used. Currently you must enable this manually. The way rerere works is a bit complicated; it's worth reading through this blog entry. | unknown | |
d11292 | train | This is your problem:
Cache-Control: no-cache
from the spec:
This allows an origin server to prevent caching even by caches that
have been configured to return stale responses to client requests.
A: If this content can change, try to use ifModified: true in the jQuery.ajax
A: In your .ajax call, set the cache: attribute to true, like this:
$.ajax({
url: postUrl,
type: 'POST',
cache: true, /* this should be true by default, but in your case I would check this*/
data: stuff
}); | unknown | |
d11293 | train | *
*Open Firefox
*In the address bar type: about:config
*Firefox3.x and later requires you to agree that you will proceed with caution.
*After the config page loads, in the filter box type: network.automatic
*Modify network.automatic-ntlm-auth.trusted-uris by double clicking the row and enter http://www.replacewithyoursite.com
*Multiple sites can be added by comma delimiting them such as http://www.replacewithyoursite.com, http://www.replacewithyourintranetsite.com
I also use IEtab add-on for the intranet sites
A: IIS needs to pass a Kerberos ticket to SQL Server for this scenario to work. MSIE is picking up the workstation session ticket, whereas Firefox is negotiating its own authentication (and not Kerberos).
Check out e.g. this dense blog post as a starting point for understanding what is needed. I'm not sure if FF support MS-Kerberos.
Be aware that even getting MSIE->IIS->SQL Server authentication can be tricky if you have the wrong versions or trust configuration...
A: AS noted by Pontus Gagge, IIS needs to pass a Kerberos ticket to SQL Server. That was enough to tip my Google-fu in the right direction.
Firefox supports Kerberos, but, you have to tell it which domains it trusts to send the Kerberos tokens too.
*
*Open Firefox
*In the address bar type: about:config
*Firefox3.x and later requires you to agree that you will proceed with caution.
*After the config page loads, in the filter box type: network.negotiate-auth
*Modify network.negotiate-auth.trusted-uris by double clicking the row and enter yourdomain.com
*Multiple domains can be added by comma delimiting them such as yourdomain.com, yourotherdomain.com
Note: This is not the same as gbn's solution which just configures firefox to not prompt you to enter domain account details on login.
Also, if you have already tried to authenticate through the stack in your current Firefox session, you will need to restart Firefox for this to work. | unknown | |
d11294 | train | As mentionned in the documentation you have to enable the new authenticator system to use login links.
Login links are only supported by Symfony when using the authenticator system. Before using this authenticator, make sure you have enabled it with enable_authenticator_manager: true in your security.yaml file.
So modify your security.yaml to add:
enable_authenticator_manager: true
If you do not use it, for example if you use guards, you will have to replace it with the new system. | unknown | |
d11295 | train | The short and sweet answer is that you can't do this, the way you've set this up.
The std::string object from which you retrieve your c_str() is in the function's local scope. When the function returns that std::string object gets destroyed.
That
std::string s;
is a local function object. When the function returns it ceases to exist. It joins the choir invisible. It is no more. It's an ex-object.
And when a std::string object gets destroyed, any of its c_str()s are no longer valid. This is why you're getting garbage: undefined behavior.
There is no way to do this without changing the overall design of it, in some way. There are many ways to go forward. Some of the possibilities:
Return a std::string in the first place
Just return the std::string from getName(). Whoever calls it can store this std::string, for a while, and grab it's c_str() if it needs it.
Use a std::string with a different scope
If this getName() is a class method, you could have a private std::string class member, have getName() store the string there, and return its c_str().
Because the original std::string continues to exist, the returned c_str() remains valid. Note that there are some pitfalls here. If the caller calls getName() again, the previously-returned c_str() will no longer be valid.
Conclusion
Just get in the habit of using and working with std::strings in your C++ code. That's what they're for.
The name "c_str()" should be a clue. It gives you a string to be used with C code, if there's any C code lying around, in the near vicinity. It's a C string. Are you writing C code here? No, you're writing C++ code.
Unless you're writing C code, or are talking to a C library, there's no need to use c_str() in the first place. If you're writing C++ code, you should be using std::strings. If you need to call a C library function, call c_str() to pass the appropriate C library function parameter, and speak of this C string no more.
A: You are creating a local variable 's' and then returning a pointer to the strig withing the string memory.
When the function returns the string goes out of scope (and so does the pointer)
Best bet is probally change getname to return a std::string, and then if you need to use the c_str, use it where it is returned.
std::string name = object.getName();
printf("name = %s", name.c_str()); | unknown | |
d11296 | train | Use unique ID's, or classes if generating elements where the same identifier will be used.
To target an element outside the current parent of the clicked element you can find the closest parent that matches a selector, and then the next element etc.
$(document).ready(function () {
$('[class*="btnToggleDiv"]').on('click', function () {
$(this).closest('li').next('div').slideToggle(100);
return false;
});
});
A: Use something like this to select the toggleThisDiv
$('#<%= toggleThisDiv.ClientID %>')
When the website is generated from your asp code, your IDs will be different than what you have given them. This is because they are run at server. Anytime that you are using runat server, use the format above to find the generated ID.
You should use a class inside to repeater though. | unknown | |
d11297 | train | Most likely, it means that you have rules that contains incorrect syntax or rules file have more the 50 000 rules.
Also the error can happened when you fill returningItems with nil context.completeRequest(returningItems: nil, completionHandler: nil) in your NSExtensionRequestHandling where context is NSExtensionContext | unknown | |
d11298 | train | So here is the answer; You can use detail route for such situations;
http://www.django-rest-framework.org/api-guide/routers/ go through DRF routing documentation;
class CourseViewSet(ModelViewSet):
@detail_route(methods=['get'])
def lectures(self, request, pk=None):
# code to get all lectures of your current course
# pk will be course id(ex: id of Maths course)
data = {} # serialize the data
return Response(data)
so your url will be like;
/courses/id/lectures | unknown | |
d11299 | train | In your config/environments/production.rb add this line to precompile the external assets
config.assets.precompile += ["third-part.js"]
and don't forget to mention env=production while precompiling assets on production. | unknown | |
d11300 | train | Enter "The Cupertino Tongue Twister" by James Dempsey
Peter put a PICT upon the pasteboard.
Deprecated PICT's a poor pasteboard type to pick.
For reference see: http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/PasteboardGuide106/Articles/pbUpdating105.html
In short: it's deprecated to put PICT on the pasteboard.
A: Ok, I'm answering my own question here, but here's what I've found:
Apple wants you to use PDF for pasteboards. So if you swap out Pict with PDF, it pretty muc just works. However, MS Word (what I was testing with) only started to allow pasting of PDF in the newest version (Which I don't have).
So, that's the solution, use PDF, and require Word 2008. | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.