INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Advanced drawing library for C#
I’m looking for an advanced noncommercial drawing library for C# with WPF. My goal is to create a drawing application. Not vector graphic support is needed, only bitmap.
|
The most advanced non-commercial API's for drawing are going to be DirectX and OpenGL. They are both complex, but you will be able to make them do almost anything you would want. You could also roll your own design that uses an Image and just changes the various pixels manually. You can then draw the image to your window when changes occur. Here is a code example below. <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, graphics, frameworks, drawing"
}
|
<h2> and img in one line
<span><img src='/img/Rosia.gif' /><h2>Россия</h2></span>
how can i set image in one line with h2?
|
add the style display:inline; to the h2.
<span><img src='/img/Rosia.gif' /><h2 style='display:inline;'>Россия</h2></span>
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 6,
"tags": "templates, html"
}
|
How to output numpy array from the animation script node
is there a way to output a numpy array from script node in ? Or do i have to make my own output class types in the socket folder of this addon ?
|
You can use `Generic` type to output ndarrays.
 I am in /root. Needless to say, I cannot do anything in /root and I cannot find my home directory. Any advice??
|
`echo $HOME` should show what the system thinks is your home directory. That requires access to a terminal of course.
|
stackexchange-serverfault
|
{
"answer_score": 2,
"question_score": 2,
"tags": "ssh, permissions, find, home directory"
}
|
Change of coordinates under resampling operation in itk
If i have a large image and i resample it to a smaller size. How can i apply the same transformation to the coordinates in the larger image. Specifically, if I resample an image to a smaller size, what are the new coordinates of the points in the larger image and how can i get them in the new coordinate system. It seems that multiple coordinates in the larger image should get mapped to the same coordinates in the smaller image. But i have no idea how to go about getting the transformed coordinates
|
It depends on the library you are using. ITK and SimpleITK have two sets of coordinates: physical coordinates which are independent of image details, and index coordinates which depend on image's size and buffered region. Physical coordinates will be the same in both the high-resolution ("big") and low-resolution ("small") image. To get index coordinates from a physical coordinate point `p` you use `imageBig->TransformPhysicalPointToIndex(p)` or `imageSmall->TransformPhysicalPointToIndex(p)`.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "python, opencv, image processing, itk, simpleitk"
}
|
Mathematical Induction, show that $n!>n^3$ for all $n \ge 6$
I have a math question where I am to show, using induction, that $n!> n^{3}$, $n\geq 6$
i) I have shown that $LHS > RHS$ for $n=6$
$$720 > 216$$
ii)
Set $n=p$ and assume that
$p!> p^{3}$
iii) set $n=p+1$
$$(p+1)!>(p+1)^{3}$$
by the assumption we know that
$$(p+1)p! > (p+1)p^{3}$$
this is where I am stuck and would appreciate some help.
|
**Hint** :
$(p+1)p^3=p^4+p^3>p^3+3p^2+3p+1\iff p^4>3p^2+3p+1$.
Now observe that, since $p\ge 6$, $\enspace p^4=p^2\cdot p^2\ge 36p^2> 7p^2$.
Can you continue?
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": -1,
"tags": "induction"
}
|
Why then don't aircraft fly even higher, for even greater efficiency?
After reading various superb QA on here I now see that (basically) aircraft are more efficient per passenger-mile, at higher altitudes.
Why don't we go even higher, than current typical airliner cruising altitudes?
What's the deal?
If there's an efficiency transition, have we reached it?
|
Please meet the ceiling altitude.
Above this altitude the aircraft cannot fly fast enough to generate enough lift to stay aloft.
This is affected by:
* weight (more weight needs more lift)
* engine power (more lift means more drag, that is overcome by engine power)
* L/D ratio (if you can have less drag for the same lift, you can fly a bit higher, all the rest being equal)
So, overall, engines are getting better, but you gain more flying a bit lower, at your ideal cruise speed, and thus consuming less.
|
stackexchange-aviation
|
{
"answer_score": 10,
"question_score": 24,
"tags": "aerodynamics, airliner, engine, efficiency"
}
|
android-where to store lots of images and how to move them while installing
I'm writing an android app that contains about 500 images . there are somethings that make me worry, I don't want to use internet.
1-the application size will be very big , is there anyway to moving images to sd card while installing? some devices may don't have this amount of space on the phone .
2-should I make 3 images for hdpi , ldpi and mdpi ?
|
1. Yes, it will be big. No, you can't remove them from your package.
2. No, you can make only `hdpi` images. Android will scale them automatically (which may slow down a bit the app).
Suggestion - use internet. Since the user has internet to download your app, he can wait to download the resources on first start. Also it give you the ability to add/remove files via online configuration. Just imagine if you have to add 1 image and upload new version - this means that the user will have to download the same huge package again.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, image, file, move"
}
|
the argument type 'widget' can't be assegned to the parameter type 'PreferredSizeWidget?'
the argument type 'widget' can't be assegned to the parameter type 'PreferredSizeWidget?'
class home_screen extends StatelessWidget {
const home_screen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: myAppBar(),
);
}
}
Widget myAppBar() {
return AppBar(
backgroundColor: Colors.red,
elevation: 0,
);
}
|
An `AppBar` implements `PreferredSizeWidget` and `Scaffold` expect the `appBar` property to be of type `PreferredSizeWidget`
Simply do:
PreferredSizeWidget myAppBar() {
return AppBar(
backgroundColor: Colors.red,
elevation: 0,
);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "flutter, dart, flutter appbar"
}
|
PHP large number into SQL
I'm trying to use this query:
$cert= 125125161241261241261;
$cert= $cert + 1;
INSERT into table (column) values ($cert);
however, when the insertion is done.
I get something like `12512516124126124+E17` or something like that. I already have put the datatype into `varchar(max)` and `var_dump`'ed my variable
SQL Server 200x.
|
I used a SQL procedure that does the insert and used it in my PHP insertion, Thanks for whoever tried to help.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "php, sql, int, long integer"
}
|
Python __new__ - how can cls be different than class that __new__ is in
[Documentation for `object.__new__(cls[, ...])` says:](
> Called to create a new instance of class `cls`. __ `new` __ is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument.
So if you have `var = MyClass()` and
class MyClass:
def __new__(cls):
...
Won't `cls` ALWAYS be equal to `MyClass` ?
|
Try this:
class MyClass:
def __new__(cls):
print(cls)
class Yac(MyClass):
pass
x = Yac()
print(x)
We get:
<class '__main__.Yac'>
None
By the way, this is fine in Python 3, but will not work in Python 2. In Python 2 `__new__` is only supported in "new-style" classes:
class MyClass(object):
In Python 3 all classes are "new-style".
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python"
}
|
MEF .NET Core how export CompositionHost?
I have next code:
var configuration = new ContainerConfiguration().WithAssemblies(filteredLibraries, conventionBuilder);
CompositionHost container = configuration.CreateContainer();
One of exported classes next:
[Export(typeof(IClass1))]
public class Class1 : IClass1
{
private readonly CompositionHost _host;
public Class1(CompositionHost host)
{
_host = host;
}
}
How export this container to itself?
|
I think the host is not exported as `CompositionHost`, but as `CompositionContext`. You are also missing the `[ImportingConstructor]` attribute.
So the code would look like this:
[Export(typeof(IClass1))]
public class Class1 : IClass1
{
private readonly CompositionContext _compositionContext;
[ImportingConstructor]
public Class1(CompositionContext compositionContext)
{
_compositionContext = compositionContext;
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, .net, .net core, mef, .net standard"
}
|
Delete a table from mongodb database
I'm really new to mongodb. I want to see data in one of my table in mongodb database. I tried using `db.table_name.remove` `db.table_name.drop` but nothing is working. also the response is pretty weird.
function () {
if (arguments.length > 0) {
throw "drop takes no argument";
}
this.resetIndexCache();
var ret = this._db.runCommand({drop:this.getName()});
if (!ret.ok) {
if (ret.errmsg == "ns not found") {
return false;
}
throw "drop failed: " + tojson(ret);
}
return true;
}
So please tell me the commands to remove table completely.
|
Your syntax is wrong, use **()** after drop and remove. The response(result) should be **true** or **false**. For more information see <
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 4,
"tags": "mongodb, command, putty"
}
|
Probability - Airplane row or column
Airplane seats are labeled using 1-30 and A-F. What's the probability of your seat being in column A or row 30 ? Please help with steps to solve this.
|
First of all we need to find the number of seats on the plane. We have 30 rows and each row contains 6 seats (A-F).
$30\times 6=180$
In column A there are 30 seats (1 seat per row), and in row 30 there are 6 seats. But since we already counted seat 30A, we don't count it. So there is a 35 in 180 chance of your seat being in one of column A or row 30.
$\frac{35}{180} = \frac{7}{36} = 19.44 $%
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": -1,
"tags": "probability"
}
|
How to return from JavaScript object with type java.util.Date?
I'm calling in JS some `javaMethod(java.util.Date date)`.
I can't change code on java-side. How can I create java.util.Date object from JS-side (at least empty date)?
|
Solved it in a not very good way, but still..
So now I'm just added to that method with JS just one more `Date` arg. Now it looks like
native void doSomething(Object object, Date date) /*-{
.....
.....::setDate(Ljava/util/Date;)(date);
.....
}-*/;
and calling it like `doSomething(var1, new Date());`
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "java, javascript, date, gwt, jsni"
}
|
C# is there ever a reason to use ArrayList instead of List<T> anymore?
The title pretty much sums it up. Now that we have `List<T>`'s why would anyone want to use an `ArrayList` instead? The only reason I can think of is if you are forced to use an old version of .NET before `List<T>` was implemented?
|
As you said, if for some reason you are stuck with .Net 1.1 then you don't have a choice.
Your question seems to indicate that there is a choice. So then there is no reason to user`ArrayList`. Anything that `ArrayList` can do, `List<T>` can do as well, if not better.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 6,
"tags": "c#, list, arraylist"
}
|
Invoking method issue in Java
public class Tester {
private String text;
public void text() {
text = "abc";
}
public static void main(String[] args) {
Tester test = new Tester();
System.out.println(test.text);
}
}
Why does this print `null`? Also, if I write `test.text()` inside the print command, why there is an error? I thought I needed to invoke the method like that.
|
`null` because `private String text;` is `null` as you have not made call to your `public void text()` which sets the value of `String text`
Make call to your `text()` before printing
Tester test=new Tester();
test.text();
System.out.println(test.text);
_Output:_
abc
_**PS._**
As per comment => _"Can I directly write System.out.println(test.text())? "_
For that set `return` type to `String` and return `String` from it
So Change your code to
public String text() {
return "abc";
}
And
Test test = new Test();
System.out.println(test.text());
_Output:_
abc
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "java"
}
|
Writing a python program takes an int argument and adds 1+1/2+1/3+1/4....1/n
I need to write a function, count(n), that takes a positive integer, n, and returns the value 1 + 1/2 + 1/3 + 1/4 + ⋯ + 1/n.
Ex : Count(4) should yield 1+ 1/2 + 1/3 + 1/4
I'm not sure how to do this? Any help would be great .
def count(n):
for c in range(1, n+1):
print c + 1/c
I cannot get it to start at the number one and I cannot get it to print in array format.
My results of count(4) are count(4)
2.0 (should be 1)
2.5 (should be 1.5)
3.33333333333 (should be 1.833333)
4.25(should be 2.083333)
|
Your problem is that you are adding a preliminary `1` to `1/1` which gives `2`. Try this:
def count(n):
sum = 0 #Intializing the return variable
for i in range(1, n+1):
sum+=1.0/i #Adding to the return variable
return sum
This works as such:
>>> def count(n):
... sum = 0
... for i in range(1, n+1):
... sum+=1.0/i
... return sum
...
>>> count(4)
2.083333333333333
>>> count(1)
1.0
>>> count(2)
1.5
>>> count(3)
1.8333333333333333
>>> count(4)
2.083333333333333
>>>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -5,
"tags": "python 2.7"
}
|
Operator precedence and ternary operator
I have a problem in C.
#include<stdio.h>
int main()
{
int a = 10, b = 0, c = 7;
if (a ? b : c == 0)
printf("1");
else if (c = c || a && b)
printf("2");
return 0;
}
This code prints 2 but I think a?b:c returns b=0 and 0==0 returns 1. Can you explain the code?
|
Your conditions are not properly written.
In the first if-statement:
if (a ? b : c == 0)
if you put the values, then it becomes
if(10 ? 0 : 7 == 0)
means, it will always return 0.
That's why control goes to the else part and there, it becomes
else if (7 = 7 || 10 && 0)
since you used the "=" operator here (c = c), it will be always true, therefore it prints "2".
Now you want that code should return "1", then change your if statement in this way.
if( (a ? b:c) == 0){...}
because "==" operator has higher precedence than ternary operator.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "c, operator precedence, ternary"
}
|
Remove legend title from seaborn plot
I just wanted to remove the title of a scatterplot made with seaborn. The title is given by the hue parameter. In this case the title is "Pluton"

sns.set_style("ticks")
plt.legend(ncol=3, loc='upper center',
bbox_to_anchor=[0.5, 1.25],
columnspacing=1.3, labelspacing=0.0,
handletextpad=0.0, handlelength=1.5,
fancybox=True, shadow=True)
plt.ylim(0.2 ,1.1)
Thanks!
|
When you create a `scatterplot()` with a `hue=`, or `style=`, etc., seaborn automatically adds an entry in the legend list to act as a "section header".
Since you are recreating the legend to put it in your desired format, it is pretty trivial to ask matplotlib to exclude the first entry in the legend list to get rid of that "header"
tips = sns.load_dataset('tips')
ax = sns.scatterplot(x="total_bill", y="tip", hue="day",
data=tips)
h,l = ax.get_legend_handles_labels()
plt.legend(h[1:],l[1:],ncol=3, loc='upper center',
bbox_to_anchor=[0.5, 1.25],
columnspacing=1.3, labelspacing=0.0,
handletextpad=0.0, handlelength=1.5,
fancybox=True, shadow=True)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, matplotlib, seaborn"
}
|
O-sumai-wa dochira-desu ka? vs Doko-ni sunde i-masu ka?
Can someone help me to understand the difference between these two. From what I understand they both mean "Where do you live?"
|
Just that the first one is the polite version, used when you're talking to complete strangers or people in positions higher than you, or who are older than you.
"Doko ni sunde imasu ka" can be used with respect to the sets of people as mentioned above but it is simply lesser in its formality compared to the first one, but is respectful and polite nonetheless.
Any standard Japanese learner would be using the second version, and I think that the first one would be used by those who've been using Japanese for quite a good while now and who know some business-Japanese as well <\-- This, I mean in the case of foreigners who are Japanese students.
|
stackexchange-japanese
|
{
"answer_score": 3,
"question_score": 1,
"tags": "word choice, words"
}
|
Logjam definition question
As I understand it, the Logjam TLS attack is an attack that downgrades the DHE cipher suite used by the server to DHE_EXPORT. Where the client thinks it is talking DHE 512 and the server things it's talking DHE_EXPORT (which is 512 but with a different name?).
**It is not** possible to downgrade to a lower (weaker) bit DHE ciphers: it is just a cipher downgrade.
|
In Logjam attack, the client presents a list of cipher suites (includes some strong cipher and EXPORT cipher as well). A Man-in-the-Middle attack will change this request such that highest grade cipher in the request becomes the EXPORT grade cipher.
The server doesn't want to reject this request (it could be an eCommerce website and server don't want to lose business), so the shared secret is derived using export grade cipher suite which can be broken if that prime group is sieved using GNFS.
Check out this video, it's a long one but from the authors of Logjam <
|
stackexchange-security
|
{
"answer_score": 1,
"question_score": 0,
"tags": "tls, diffie hellman, logjam"
}
|
Push-pull amplifier
The question is concerned the output current of push-pull amplifier once the over-current protection is activated. The resistor Rs(one between base and emitter of the over-current protection transistor T) has it's resistance so that Vbe=Rs*Ipmax. So when the current reaches Ipmax, it turns on the transistor T, and transistor T pulls some of the current from the regular transistor. My question is: does the current on the load stay Ipmax, after the protection turns on, and if yes, can it be calculated analytically?
 + ' ' + b.time_ago());
This is breaking in FireFox 3, meaning when FF hits that line in the JS, it goes no further. Strangely if I have Firebug open it doesn't break and continues as normal. Some how firebug prevents this issue?
I'm puzzled on this one. Any thoughts as to why console.log would break firefox 3, but not if firebug is open?
Thanks
|
This is not just Firefox. Your code will stop working in every browser (except Chrome and safari (in some instances) because they have console.log() built in along with their developer tools.)
It is because when you don't have firebug open, the object "console" is not defined. You should take care never too leave console.log() functions in your code, or it will break in _every browser_.
* * *
I'd like to add that I have sometimes used this function:
function log () {
if (typeof console == 'undefined') {
return;
}
console.log.apply(console, arguments);
}
Then you can simply call:
log(somevar, anothervar);
and it will work the same way as console.log, but will not fail if firebug is not loaded (and is shorter to type :P)
Cheers
|
stackexchange-stackoverflow
|
{
"answer_score": 30,
"question_score": 11,
"tags": "javascript, firefox, firebug, firefox 3"
}
|
Does the orthogonal projection of a vector onto a subspace equal the original vector?
I've come to the conclusion that a vector equals its orthogonal projection onto a subspace by the following:
Since by orthogonal decomposition a vector "y" can be written uniquely as the sum of its projection "p" onto a subspace, and a vector (y - p) orthogonal to the subspace. I have y = p + (y - p). So then I can say the inner product of p and (y - p) is the inner product of p & y minus the inner product of p & p, which is equal to zero. So inner product of p & y equals inner product of p & p, and y = p. I'm a student and I cannot be sure that this is correct with my knowledge of linear algebra, and I was interested in finding out if what I just proved is true.
|
$\langle p, y\rangle = \langle p, p \rangle$ does **not** imply $y=p$. For example, $p=(1,0)$ and $y=(1,1)$.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": -1,
"tags": "linear algebra, orthogonality, projection"
}
|
$location is not working in Angular
I have an rest api, in which the api is sending instruction to redirect (`301` is being sent).
And I have my angular js code like this:
var request = $http.post(LOGIN_URL,{username:'tes',password:'test'})
request.success(function(html)
{
if(html.failure) {
console.log("failure")
$scope.errorMessage = html.failure.message
}
else {
console.log("Success here....")
$location.path("route")
}
})
I can see in the browser log that it is coming in the else part ( `Success here.....` is being printed). But the url is not changed. `$location.path` doesnt do anything; I have also tried `$location.url` which also results the same thing.
And also I'm injecting the `$location` to my controller.
Where I'm making mistake?
Thanks in advance.
|
Try something like this
$location.path("/myroute")
You have to have a ng-view on the page as well.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, angularjs, rest"
}
|
How to prove that $\frac{1}{\sqrt{1-x^2}}=\sum _{n=0}^{\infty }\frac{(2n)!}{4^n(n!)^2}x^{2n}$?
how can I prove that $\frac{1}{\sqrt{1-x^2}}=\sum _{n=0}^{\infty }\frac{(2n)!}{4^n(n!)^2}x^{2n}$?
I tried using Newton's generalized binomial theorem to get:$$\frac{1}{\sqrt{1-x^2}}=(1-x^2)^{-1/2}=\sum_{k=0}^{\infty}{\begin{pmatrix} -1/2\\\ k \end{pmatrix}}(-x^2)^k=\sum_{k=0}^{\infty}{(-1)^k\begin{pmatrix} -1/2\\\ k \end{pmatrix}}x^{2k}$$ How is that equal to to $\sum _{n=0}^{\infty }\frac{(2n)!}{4^n(n!)^2}x^{2n}$?
|
Well, you just need to go one step further. Detailed steps are
$$ (-1)^k\binom{-1/2}{k} x^{2k} = (-1)^k\frac{\prod_{i=1}^k(-1/2-i+1)}{\prod_{i=1}^k i}x^{2k} $$ $$ = \frac{\prod_{i=1}^k(1/2+i-1)}{\prod_{i=1}^k i }x^{2k} = \frac{\prod_{i=1}^k(2i-1)}{2^k\prod_{i=1}^k i }x^{2k} $$ $$ = \frac{\prod_{i=1}^k(2i-1)\prod_{j=1}^k j}{2^k\prod_{i=1}^k i \prod_{j=1}^k j }x^{2k} = \frac{\prod_{i=1}^k(2i-1)\prod_{j=1}^k (2j)}{4^k{\left(\prod_{i=1}^k i\right)}^2 }x^{2k} $$ $$ = \frac{\prod_{i=1}^{2k}i}{4^k{\left(\prod_{i=1}^k i\right)}^2 }x^{2k} = \frac{(2k)!}{4^k{\left(k!\right)}^2 }x^{2k} $$
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 0,
"tags": "real analysis, sequences and series, taylor expansion"
}
|
Pandas: How to return the list of values which are not in another dataframe?
import pandas as pd
df1 = pd.DataFrame({'name': ['CAD123', 'MXN789', 'EUR567','JPY224', 'EUR673', 'PLN254'],
'currency': ['CAD', 'MXN', 'EUR', 'JPY', 'EUR','PLN']})
df2 = pd.DataFrame({'currency':['EUR','PLN']})
Above are my two dataframes. I am doing some data analysis and want the list of values in 'name' column whose 'currency' is not there in another dataframe. My expected output as below. Please suggest.
Expected_list = ['CAD123','MXN789','JPY224']
|
We do `isin` with `loc`
l = df1.loc[~df1.currency.isin(df2.currency), 'name'].tolist()
['CAD123', 'MXN789', 'JPY224']
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "python, pandas"
}
|
Randomize Transform is not available
I wanted to use the "Randomize Transform" tool as described here
Or in the first half of that video.
Following the video, after seperation of each individual cube into single objects, when I want to use the tool, everything is greyed out, like in the attached screenshot.
!Randomized Transform greyed out
What am I doing wrong here?
|
Make sure _**Global Undo**_ is enabled.
For 2.8x and 2.9.
_Edit > User preferences > System > Memory & Limits: Global Undo_
.
So this panel is disabled when undo is not available.
|
stackexchange-blender
|
{
"answer_score": 5,
"question_score": 4,
"tags": "objects, transforms"
}
|
In a multithreaded app, can 2+ threads access the same function if the function does not modify/read data or modifies/reads temporary data?
I can't seem to find an answer anywhere on Google. I basically want to know if 2 threads can access normal/member functions like these at the same time and not result in undefined behavior or do I have to use a mutex?
void foo(void)
{
float x(133.7);
float y(10);
std::cout << std::endl << (x * y);
}
void foobar(void)
{
std::cout << std::endl << 1/1;
}
|
I am pretty sure your code doesn't have undefined behaviour.
That said, you **are** using shared data, namely `std::cout`.
So if you expect `std::cout << std::endl << (x * y)` to be executed as a single operation (e.g. to prevent bits of output from different threads getting interleaved on stdout), you are going to have to use locks.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "c++, multithreading, function, c++11, mutex"
}
|
What does "+=" (plus equals) mean in Ruby?
I'm going through a Ruby tutorial and I can't grasp the += statement. Google isn't helping, "Ruby +=" only searches for "Ruby".
Help is appreciated.
Sample:
num = -10
num += -1 if num < 0
puts num
#=> -11
|
num += -1
is an equivalent of
num = num + -1
or, for this example
num = num - 1
which, in turn, can be written as
num -= 1
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "ruby"
}
|
Hard or soft link is more useful in Linux?
In small scale Linux infrastructure environment which link to the file is more helpful, hard or soft link?
As a beginner in Linux administration, I have found that most Linux admins tend to use soft links over hard link. Even though the link may be dangling if the file name gets manipulated. Is there any special or a specific reason towards that?
|
More useful is a matter of opinion, both hard and soft links have very valid use cases but I usually create softlinks:
# Directories
You can only create hard links to files and not to directories.
And then since creating hard links frequently fails creating softlinks has become a habit.
# Back-ups
I have had issues with back-up software that does not recognise a hard link as such and then your backup might:
* store a full copy of the linked file for each hardlink rather than the hardlink.
and even when the hardlink was recognised as such restoring it can be a challenge as:
* the target of the hardlink must be still/already be present or the restore fails1
or when it wasn't archived as a hardlink:
* your restore will result in files that are no longer linked.
|
stackexchange-serverfault
|
{
"answer_score": 1,
"question_score": 2,
"tags": "linux, symlink, hardlink"
}
|
Is there an API for making a Google Chrome extension that reads the network resource request activity?
In the Google Chrome developer window, there is a Network tab that shows you all the resources that a web page loads over time. Is there a way to access this data in a Google Chrome extension?
CLARIFICATION: I want to make a Chrome extension that needs to read this data and do something based on what it reads. So I should have asked, "is there a Chrome Extension API that allows this?"
|
There is experimental API for accessing network resources. Being experimental means that to use it users need to enable experimental API flag in their settings, plus you won't be able to submit such extension to the gallery.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 6,
"tags": "google chrome extension"
}
|
Format text file using shell
I want to format text file using shell commands.
File content is like:
first_name:last_name:some_random_characters
Jack:Brown:!@#xyz
Mike:Spencer:234QWE
Robert:Junior:^#2dsa
...
and I want the output to be like:
JBrown:!@#xyz
MSpencer:234QWE
RJunior:^#2dsa
...
I tried using `cat -d ':' -f 1 file.txt` and `cat -d ':' -f 2-3 file.txt`, but I don't know how to combine this commands.
|
$ sed -E 's/(.)[^:]+:/\1/' file
JBrown:!@#xyz
MSpencer:234QWE
RJunior:^#2dsa
I think this is what you tried to do, but it's not efficient
$ paste -d'\0' <(cut -c1 file) <(cut -d: -f2- file)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "linux, shell, concatenation"
}
|
You flip a coin until you get a total of n heads. What is the expected number of flips this will take? Expectation and Variance
You flip a coin until you get a total of _n_ heads. What is the expected number of flips this will take? In terms of Expectation, `E[x]` and Variance `Var(x)`.
Edit: The heads don't have to be consecutive.
|
Let $X_1$ be the number of coin tosses until the first head, $X_2$ be the number of coin tosses _after_ that until the second head, and so on. We want $E[X]$ where $X = X_1 + X_2 + \dots + X_k$. By linearity of expectation, we have $E[X] = E[X_1] + E[X_2] + \dots + E[X_k]$.
For any $i$, $E[X_i]$ is the expected number of coin tosses until a head appears which is equal to $\dfrac{1}{p}$.
Therefore, we have $E[X] = \dfrac1p + \dfrac1p + \dots + \dfrac1p = \dfrac{k}p$. Put $k=n$ to get your answer.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 2,
"tags": "probability, expectation"
}
|
How to generage .xml or .html with jacoco and spoon
I can setup spoon with:
spoon {
//...
codeCoverage = true
}
to generage `coverage.ec` files.
How can I generate the reports in `.xml` or `.html`?
|
You can do this creating your own task using the built-in Jacoco Gradle plugin:
apply plugin: 'jacoco'
task jacocoTestReport(type: JacocoReport, dependsOn: ['<taskThatProducesEcFile>']) {
reports {
xml.enabled = true
html.enabled = true
}
def fileFilter = ['**/R.class', <another filters...>]
def debugTree = fileTree(dir: "${buildDir}/intermediates/classes/debug", excludes: fileFilter)
def mainSrc = "${project.projectDir}/src/main/java"
sourceDirectories = files([mainSrc])
classDirectories = files([debugTree])
executionData = files([<your_path_to_ec_file>])
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "android, android testing, spoon"
}
|
How to align more than 2 sequences with Needleman-Wunsch?
I have a DNA sequence of a protein and around 1200 zinc finger target sequences. These zinc finger target sequences are 9 bp long, resulting in BLASTn not finding them in the sequence. Needleman-Wunsch does find them, however, I can only search/align the DNA protein sequence with 1 zinc finger at a time. Is there a way to do this simultaneous (serial or parallel, computational time is not a big problem) for all 1200 zinc fingers and have the result in a table as with BLAST?
|
(I assume that by "DNA protein" you mean "coding DNA".)
"I can only search/align the sequence with 1 zinc finger at a time" \- does this mean that you have not found out a way to do so, or that you desire to proceed in this fashion? I think that it is the first, based on the title of your question, but it is not at all clear what you are looking to do.
If you want to _locate specific 9bp motifs in your sequence_ , then I can suggest this small piece of code that I wrote that looks for exact matches of specific sequences, that outputs a BLAST-like table. It is slow relative to BLASTN but it does not use the short-match-ignoring heuristics that BLASTN relies upon so it may be helpful.
The code was written in response to this bioinformatics SE question, which seems somewhat similar to your question here.
Note that you will have to input each expected 9bp query against the reference sequence in the form of a FASTA file.
|
stackexchange-biology
|
{
"answer_score": 0,
"question_score": -1,
"tags": "bioinformatics, sequence alignment, blast"
}
|
Problem based on area projection in 3-D geometry
Considering a Quadrilateral $ABCD$ where $A(0,0,0), B(2,0,2), C(2,2\sqrt 2,2), D(0,2\sqrt2,0)$. Basically I have to find the **Area** of **projection** of quadrilateral $ABCD$ on the plane $x+y-z=3$.
I have tried to first find the projection of the points $A,B,C,D$ _**individually**_ on the plane and then using the **projected points** find the vectors $\vec{AB}$ and $\vec{BC}$ and then using $|\vec{AB}\cdot \vec{BC}|$ , but I was unable to find the projected points.
Is it the correct approach? If it is not I would highly appreciate a correct approach for the problem.
|
As indicated by Intelligenti pauca in the above comments, the best way to go is to find the area of the quadrilateral, then multiply the area found by the cosine of the angle between the two planes which is the same angle between the normals to the planes (or its supplement).
$\begin{equation} \begin{split} \text{Area} &= \frac{1}{2} ( | AB \times AC | + | AC \times AD | ) \\\ &= \frac{1}{2} ( | (2,0,2) \times (2, 2\sqrt{2}, 2) | + | (2, 2 \sqrt{2}, 2) \times (0, 2 \sqrt{2}, 0) | ) \\\ &= 2 ( | (- \sqrt{2}, 0, \sqrt{2} ) | + | (-\sqrt{2}, 0, \sqrt{2} ) | )\\\ & = 2 ( 2 + 2 ) = 8 \end{split} \end{equation}$
The normal to the plane of the quadrilateral is along $(-1, 0, 1)$ and the normal to the projection plane is along $(1, 1, -1)$, therefore, if $\theta$ is the angle between these two normals, then,
$\cos \theta = \dfrac{ (-1, 0, 1) \cdot (1, 1, -1) }{\sqrt{2}\sqrt{3} } = -\sqrt{\dfrac{2}{3}} $
Hence, the projected area is equal to $8\sqrt{\dfrac{2}{3}}$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "geometry, vectors, 3d"
}
|
Can someone give an example of how edit function for clojure.zip works?
I am a newbie to clojure and i was working with clojure.zip, and was not able to figure out how to use the edit function in it. If someone can give me a working example of how it works it would be really helpful.
say for example i have a binary tree
45
10 57
how would i edit the value 57 and change it to say 75
|
Presuming a structure of nested vectors in which the first element is the value, the second is the left child and the third is the right child, this would work:
(let [btree [45 [10] [57]]
root-loc (zip/zipper vector? rest
(fn [[x _ _] children]
(vec (cons x children)))
btree)]
(-> root-loc
zip/down
zip/right
(zip/edit (fn [node]
(assoc-in node [0] 75)))
zip/root))
;=> [45 [10] [75]]
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "clojure, binary tree, zipper"
}
|
Updated Model for Entity Framework and got complicated error message
I get this message when I'm trying to run my application:
> An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
>
> Additional information: The model backing the 'MVC2_1Context' context has changed since the database was created...
The application has worked before, the only thing I have done, is to add some Data Annotations in the model and reference a property to an Enum in a new class.
To solve this I thought it should be enough to use `Tools -> NuGet Package Manager -> Package Manager Console and type in Enable-Migration -EnableAutomaticMigrations` and then hit enter! But I still get this error message and hope to get som help here to be able to continue!
|
> Additional information: The model backing the 'MVC2_1Context' context has changed since the database was created.
It means one of your classes use in the _MVC2_1Context_ has changed, but the database hasn't been updated so is now out of date.
for more info:<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "asp.net, asp.net mvc, visual studio 2015"
}
|
SET WithCredentials globally with axios on VueJS
In main.js, I put
axios.defaults.withCredentials = true;
It should work, but by this way the cookies are not sent to the back end.
Here the request header
 {
request.credentials = true
return function(response) {
};
});
|
stackexchange-stackoverflow
|
{
"answer_score": -2,
"question_score": 2,
"tags": "vue.js, cookies, axios"
}
|
Save UI and data in android
, and displaying a listView with an adapter on this data. then, when adding data, you only need to notify your adapter to refresh the view.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android"
}
|
plugin generated unexpected output during activation, but it is empty
I am getting this error what is already answered in several threads here with same problem. Here the error message:
> The plugin generated 3 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
_Plugin that causes this error is written by me._ To find out I deleted the complete code and only left the documentation block at the top.
Still get the error when activating my plugin even when it is empty! There is no cache running.
Find this very weird. How can an empty plugin generated the same error as when it is filled with code?
Someone of you any idea how to solve this? Would be very nice. I do not understand this.
|
You may have empty characters at the beginning before the `<?php` block.
You may also try to `var_dump($result->get_error_data())` this error message -- this would be the dirty way.
File: wp-admin/plugins.php
42: $result = activate_plugin($plugin, self_admin_url('plugins.php?error=true&plugin=' . $plugin), is_network_admin() );
43: if ( is_wp_error( $result ) ) {
44: if ( 'unexpected_output' == $result->get_error_code() ) {
45: $redirect = self_admin_url('plugins.php?error=true&charsout=' . strlen($result->get_error_data()) . '&plugin=' . $plugin . "&plugin_status=$status&paged=$page&s=$s");
46: wp_redirect(add_query_arg('_error_nonce', wp_create_nonce('plugin-activation-error_' . $plugin), $redirect));
47: exit;
48: } else {
49: wp_die($result);
50: }
51: }
|
stackexchange-wordpress
|
{
"answer_score": 1,
"question_score": 0,
"tags": "plugins, wp error"
}
|
Monitoring Clustered MSMQ
According to Microsoft, Systems Center Operations Manager cannot monitor clustered MSMQ's on Server 2003. The Microsoft rep referenced this article. and said it applied to our problem. So, my question is: what does the serverfault community recommend to monitor msmq's in a Server 2003 cluster?
What I am looking for is something to monitor the number of messages on the queues and send an alert if messages appear on the fault queue or if the messages back-up on the main queue.
Thanks!
|
If you just want to monitor queue depth, I would break out your powershell handbook or buy your favorite developer a beer or two and look into the .NET System.Messaging namespace. You can run a scheduled task every few minutes and get near-realtime alerting that way.
|
stackexchange-serverfault
|
{
"answer_score": 1,
"question_score": 0,
"tags": "windows server 2003, cluster"
}
|
Bing Map Aerial Question
I am aware of Microsoft Bing Maps Aerial licensing changes with ArcGIS for Desktop at the end of this year.
My question here is why I have two different ArcMap I saved had them in it.
One was able to show it and the other would not allowed me to show me?
What is the reason for that?
ArcGIS 10.1 SP 1
Here is screenshot:
!Here is the Sample of the screenshot
|
I think @Paul is on the right track regarding the differences between your two Map Documents.
Since you have Service Pack 1 installed, you can download the newly available Set Bing Key Patch so that you can have access to Bing basemaps in all your Map Documents (10.1). You will need to get a temporary key from ESRI which expires Dec 31st, 2013.
|
stackexchange-gis
|
{
"answer_score": 1,
"question_score": 2,
"tags": "arcgis 10.1, arcgis desktop, bing maps"
}
|
Disable Javascript in Playwright
Is it possible to define a browser with Javascript disabled to simulate how a crawler would view a page? There should be an option that can be passed.
|
You can pass `javaScriptEnabled` in the BrowserContext options:
const playwright = require("playwright");
(async () => {
const browser = await playwright.chromium.launch();
const context = await browser.newContext({
javaScriptEnabled: false
});
const page = await context.newPage();
// ...
await browser.close();
})();
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 11,
"tags": "playwright"
}
|
The closure of a singleton is path-connected
Let $x$ be in an element of topological space $X$. Prove that the closure of $\\{x\\}$ is path connected.
I am having issues creating a path, and I have a bit of difficulty understanding "the closure of $\\{x\\}$".
|
Take any point $y\in \overline{\\{x\\}}$ and consider the curve $\gamma\colon[0,1] \to X$ defined by $$ \gamma(t) = \begin{cases}y &\text{when $t=0$}\\\x &\text{when $t>0$}\end{cases} $$ it is enough to prove that $\gamma$ is continuous.
For $t>0$ the function is constant hence continuous. For $t=0$ take any neighbourhood $U$ of $y$. Since $y\in \overline{\\{x\\}}$ then $U\cap\\{x\\}\neq \emptyset$ hence $x\in U$. So $\gamma([0,1]) = \\{x,y\\} \subset $U$.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 3,
"tags": "general topology"
}
|
Select specefic rows from a 2d Numpy array using a sparse binary 1-d array
I am having a issues figuring out to do this operation
So I have and the variable `index` 1xM sparse binary array and I have a 2-d array (NxM) `samples`. I want to use `index` to select specific rows of `samples` adnd get a 2-d array.
I have tried stuff like:
idx = index.todense() == 1
samples[idx.T,:]
but nothing.
So far I have made it work doing this:
idx = test_x.todense() == 1
selected_samples = samples[np.array(idx.flat)]
But there should be a cleaner way.
To give an idea using a fraction of the data:
print(idx.shape) # (1, 22360)
print(samples.shape) (22360, 200)
|
The short answer:
selected_samples = samples[index.nonzero()[1]]
The long answer:
The first problem is that your index matrix is 1xN while your sample ndarray is NxM. (See the mismatch?) This is why you needed to call `.flat`.
That's not a big deal, though, because we just need the nonzero entries in the sparse vector. Get those with `index.nonzero()`, which returns a tuple of (row indices, column indices). We only care about the column indices, so we use `index.nonzero()[1]` to get those by themselves.
Then, simply index with the array of nonzero column indices and you're done.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "python, arrays, numpy"
}
|
<list-index ...> --Hibernate mappings
Two questions about `<list-index...>` :
1. Is it necessary that values of column given in `<list-index ...>` element of `<list>` tag in mappings lists must be unique???
<list-index column="index_col"/>
2. Does hibernate generate values for column in `<list-index>` or we provide them through code?
|
1. Yes. I don't see why one would use several columns to store a single integer value. The index column stores the index of the element in the list.
2. Hibernate populates this column automatically, from the index of the element in the list.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "hibernate, mapping"
}
|
How can i make the buttons on my sideabar switch tabs?
I have a UI with 4 buttons on a sidebar I made and I have no clue how I can set it so when you press it, it shows a different screen.
I do not need it to open a new window just so it can change between 4-5 "modes"
I am using `Bunifu UI`
|
I just took a quick look at the Buniforms reference docs for their WinForms product (I assume you are using their WinForms product) and it look like you want to use the "Transitions" component
<
"Bunifu Transition is a special component, that allows us to have transitions in our Windows Forms apps. This is an amazing feature of Bunifu Framework, because it makes our User Interfaces more interactive and improves massively the User Experience. Let’s see how!"
"Bunifu Transition allows us to apply transitions to other controls."
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "bunifu"
}
|
Display All post on one page in wordpress
i am using below code to display all post through `wordpress` page-- Its displaying the same code as it is-- Any help==
<?php
$wp_query = new WP_Query(array('post_type'=>'post', 'post_status'=>'publish',
'posts_per_page'=>10, 'paged'=>get_query_var('paged')));
?>
Or below one is also not working
<?php
$args = array( 'numberposts' => '8' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<li class="latesttrends"><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
|
$wp_query = query_posts( '&posts_per_page=-1' );
In $wp_query Array you will get all post.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "wordpress"
}
|
"Could not load file or assembly" when configuring XSLT Mediator
I am trying to configure XSLT mediator. After adding a configuration entry, when I try to run, I get following error.
> Could not load file or assembly 'file:///C:\Docs\Tridion.Extensions.Mediators.dll' or one of its dependencies. Operation is not supported.
>
> (Exception from HRESULT: 0x80131515). An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See < for more information.
DLL is located at right path and I am not sure why the prefix "file:///" is added to my path in exception trace.
|
Have you tried to unblock the dll file. Right click on file, under General tab you can control/unblock this. Usually Windows Server locks the dlls in case they are sent over e-mail.
|
stackexchange-tridion
|
{
"answer_score": 5,
"question_score": 2,
"tags": "2011, xslt mediator"
}
|
php file to delete all images with a specfic string
i need a php script that can delete all files in a folder and subfolders than contain a "-" in them. The file are images- specifically duplicate thumbnails of images in wordpress media library
Thanks!
|
let the structure is
/images
- /list1
image-11.jpeg
image-12.jpeg
- /list2
image-21.jpeg
image-22.jpeg
using RecursiveDirectoryIterator we can delete all the images.
$parentDirPath = "images";//pathtofolder
if (is_dir($parentDirPath)) {
$directory = new RecursiveDirectoryIterator($parentDirPath);
foreach (new RecursiveIteratorIterator($directory) as $fileNetPath => $file) {
if ($file->isFile()) {
$fileName = $file->getFilename();
if (preg_match("/-/", $fileName)) {//checking for matching names
echo "<br/> Deleting file : ".$fileNetPath;
@unlink($fileNetPath);
}
}
}
}
Hope this will help you
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -5,
"tags": "php, wordpress"
}
|
How do I perform 'shiny swapping'?
In Pokémon Sun and Moon it's possible to 'shiny swap' Pokémon as a method to gain shinies. How does this method work? I'd love to get some legal shiny Pokémon, but I don't get how the shiny swapping method works. I'd be very interested in knowing how to do this and if there are any caveats to it.
|

|
stackexchange-gaming
|
{
"answer_score": 3,
"question_score": 2,
"tags": "pokemon sun moon"
}
|
Update DATE in tables stored as VARCHAR after conversion
I imported data from Excel and brought dates over in VARCHAR format as 03/24/2017 because the dates were not saving. So I used VARCHAR for expediency. Now I am paying the price.
I am trying to use the STR_TO_DATE function to convert so that I can UPDATE a new column (defined as DATE) in the row.
When I use the following it looks promising, but only the month/day convert properly, the year becomes 2020 as shown below:
date_order $conv_date_order
3/24/2017 2020-03-24
SELECT date_order, STR_TO_DATE(date_order, '%m/%d/%y') AS $conv_date_order,
date_shipped, STR_TO_DATE(date_shipped, '%m/%d/%y') AS $conv_date_shipped,
date_need, STR_TO_DATE(date_need, '%m/%d/%y') AS $conv_date_need
FROM Orders
WHERE Orders.id = $id;
|
You need to use a capital Y in your `'%m/%d/%Y'` format string to indicate a four digit year. The lowercase y indicates a two digit year.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "mysql, date, str to date"
}
|
How can i fix this error? c# asp linq
A few minutes ago this part of my code was functional with success, few minutes after i see this when i compile the project
!Error image result
And the code is:
string Cat = ddlCategoria.SelectedValue;
int? MaxIdCat = (from p in db.tblProducto
where p.IdCategoria == Cat
select p.IdProducto).Max() + 1;
txtIdEmp.Text = Convert.ToString(MaxIdCat ?? +1);
|
Please make sure Cat is having value in variable and as well as in table. If that value is not existing in table you have to handle is null on the entire linq query.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "c#, asp.net, linq"
}
|
Android: one time only variable storing
I have an appliaction which will show a welcome window only the first time the user starts the app. What would be the best way to store this boolean variable (i.e. "isFirstTime") to phone storage? Should I use Shared Preferences or Internal Storage?
The docs say that if I use Internal Storage my "preference" file will automatically get removed upon uninstallation which is quite handy.
I want a clean, simple and fast solution.
|
Yes, I'd recommend using Shared Preferences. Basically you could put a shared preference with a key of "isFirstTime" and a type of boolean set to false. Then in your main activity do something like:
getBoolean (isFirstTime, true);
This, if it can't find isFirstTime will give you true, allowing you to do an if-statement based on the result.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "android, storage, sharedpreferences"
}
|
can't close uploaded file (suddenly)
Suddenly these three lines throw the following error message. A few hours ago it just worked, I changed nothing within the file, I can read the file just fine and work with it.
if ( isset( $_FILES['xlsxFile'] ) ) {
$tmp_file = 'tmp.xlsx';
move_uploaded_file( $_FILES['xlsxFile']['tmp_name'], $tmp_file );
fclose($tmp_file);
}
> Warning: fclose() expects parameter 1 to be resource, string given in /var/www/vhosts/foo.bar/httpdocs/foo.php on line 5
It feels so weird for me, is there something, that might have changed on the hoster side or something?
|
There is no need to `fclose($tmp_file)` in that code example. `fclose` is used to free resources held by a call to `fopen`.
`move_uploaded_file` just takes two strings that are the names of the files, and manages all the resources itself - you don't need to free the resources for that.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, file upload"
}
|
Seeking a seemingly missing reference of Casson
Floer's paper, _An Instanton-Invariant for 3-Manifolds_ , makes reference to Casson's construction of a topological invariant for homology 3-spheres. He literally references it by placing the bibliographic-tag [C] in one of his sentences... but he doesn't actually list it in the bibliography!
I subsequently search around, and cannot find where Casson originally defines his invariant; only locate papers that talk about his invariant. Does this "paper" not exist? I would think that such an important construction has a foundational paper in existence.
|
According to the following paper, this invariant's introduction is sourced as: A. Casson, Lecture notes, MSRI Lectures, Berkeley, 1985.
The first published discussion appears to be found in: S. Akbulut & J. McCarthy, Casson's invariant for oriented homology 3-spheres, an exposition, Math. Notes, No. 36, Princeton Univ. Press, Princeton, 1990.
* * *
"I don't know if he [Casson] has ever written his notes. I attended his lectures at MSRI then I went back to MSU and tried to fill in the details together with McCarthy, those notes are the result." S. Akbulut
* * *
"Here is a pdf of hand-written notes of T. Cochran's. Page two includes annotated notes by Boyer, and I got the notes from my friend and colleague, A. Nicas." H. Boden
|
stackexchange-mathoverflow_net_7z
|
{
"answer_score": 9,
"question_score": 6,
"tags": "reference request, at.algebraic topology"
}
|
Why can't select my Ionic app on Play Console to make an AdWords Campaign?
I have upload an app to Google Play and I want to make an AdWords campaign. The problem is that I can't select the app to promote it. I don't know if the problem is related whith the code (maybe I need to include code for Google detect my app) or if I have to make something on AdWords.
|
Link your AdWords account to your developer account as described here.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ionic framework, google play, google ads api"
}
|
hibernate query returns only first character of string
When I run a query like this in oracle 10g using sqldeveloper, it runs fine.
select 'Canada' as "country", emp.name as "name" from emp.
Gives me the name and country. When I run it in hibernate as a named query, I get only 'C' instead of 'Canada' for "country".
Why is this so?
|
select cast('Canada' as varchar2(100)) as "country", emp.name as "name" from emp
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 5,
"tags": "hibernate, named query"
}
|
Map List<List<string>> into List<Dictionary<string, int>>
I'm trying the following code to map a list of lists into list of dictionaries but I'm getting error
> index out of range
Updated the question
List<List<string>> _terms = new List<List<string>>();
for (int i = 0; i < _numcats; ++i)
{
_terms.Add( GenerateTerms(_docs[i]));
}
// where _docs[i] is an array element
// and the procedure GenerateTerms returns list
int j = 0;
foreach (List <string> catterms in _terms)
{
for (int i = 0; i < catterms.Count; i++)
{
_wordsIndex[j].Add(catterms[i], i);
}
j ++;
}
Could any help please?
|
Assumptions:
* `_terms` is type `List<List<string>>`
* `_wordsIndex` is type `List<Dictionary<string,int>>`
Try this:
var _wordsIndex =
_terms.Select(listOfWords =>
// for each list of words
listOfWords
// each word => pair of (word, index)
.Select((word, wordIndex) =>
new KeyValuePair<string,int>(word, wordIndex))
// to dictionary these
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value))
// Finally, ToList the resulting dictionaries
.ToList();
A note of caution, however - and this bug exists in your example code as well: Calling `Add` on a dictionary where that key already exists is a no-no. To ensure safety here, you'd probably want to get a `Distinct()` on the key value pairs.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#, c# 4.0"
}
|
How to enable gzip for yii2?
I need to add new rules to .htaccess or to add the code to index.php of YII2?
My site is on shared hosting.
I want to compress only .css and .js files. I don't want to compress all responses.
|
You can make it work by attaching event handler on yii\web\Response in index.php.
$application = new yii\web\Application($config);
$application->on(yii\web\Application::EVENT_BEFORE_REQUEST, function(yii\base\Event $event){
$event->sender->response->on(yii\web\Response::EVENT_BEFORE_SEND, function($e){
ob_start("ob_gzhandler");
});
$event->sender->response->on(yii\web\Response::EVENT_AFTER_SEND, function($e){
ob_end_flush();
});
});
$application->run();
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": ".htaccess, yii, yii2"
}
|
Examples of 2D wave equations with analytic solutions
I need to numerically solve the following wave equation$$\nabla^2\psi(\vec{r},t) - \frac{1}{c(\vec{r})^2}\frac{\partial^2}{\partial t^2}\psi(\vec{r},t) = -s(\vec{r},t)$$ subject to zero initial conditions $$\psi(\vec{r},0)=0, \quad \left.\frac{\partial}{\partial t}\psi(\vec{r},t)\right|_{t=0}=0$$ where $\vec{r} \in \mathbb{R}^2$ and $t \in \mathbb{R}$.
The problem is that I don't know if my numerical solution is right or not, so I wonder if there are some simple cases where the analytic solution can be calculated ( _besides the green's function, i.e. the solution when $c(\vec{r}) \equiv $ const and $s(\vec{r},t) = \delta(\vec{r},t)$_ ), so I can compare it with my numerical solution.
Thanks!
|
One easy trick is to take $\psi(r,t)$ as your favorite function as long as it satisfies the initial conditions, and then compute the inhomogeneous term $s(r,t)$ from the equation itself.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 3,
"tags": "partial differential equations, numerical methods"
}
|
How to use IN statement in partiqL DynamodB
I want to convert this query select lKey from KeyMapping where gKey in ['A#1','A#2','A#3'];
I have a List that contain A#1, A#2 and A#3
into Java code to extract records from DynamoDB using PartiQL
|
@Autowired
private AmazonDynamoDB client;
List<String> paramList = new ArrayList<>(); //List of Parameters
paramList.add("A#1");
paramList.add("A#2");
paramList.add("A#3");
ExecuteStatementRequest request = new ExecuteStatementRequest();
String[] placeholders = new String[paramList.size()];
Arrays.fill(placeholders, "?");
String commalist = Arrays.stream(placeholders).collect(Collectors.joining(","));
request.setStatement("select * from "+appConfigs.getBoclipsTableName()+" where id in ("+commalist+")");
List<AttributeValue> parameters = new ArrayList<>();
for(String videoId: videoIds){
parameters.add(new AttributeValue(videoId));
}
System.out.println(client.executeStatement(request).toString());
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "amazon dynamodb, partiql"
}
|
Creating a Lisp alias with defalias or new function?
I want `mylist` to have the same functionality as `list`. In most Lisps (I'm on Emacs Lisp) I can simply write
(defalias 'mylist 'list)
But if I want to write my own I can write
(defun mylist (&rest x)
(car (list x)))
which has the same functionality. But then I got this by experimenting. First, I had this code
(defun mylist (&rest x)
(list x))
which produced a list in a list. I wasn't sure why, but the simple solution was to just put `(list x)` inside a `car` and call it good. But I'd like to know why I get a list inside a list when I don't use the `car` trick. What am I missing?
|
> `(defun my-list (&rest x) …`
The `&rest` parameter means that all remaining arguments are put into a list that is bound to this parameter. `X` then holds the list that you want. You're done.
(defun my-list (&rest x)
x)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "function, lisp, elisp, alias"
}
|
jquery css change outline of input to none
Ok. I know some of you are reading this and already asking why I'm so stupid and why I dont do this with simple CSS.
input:focus { outline:none; }
Simple... for some reason wordpress is not allowing this change to happen - so I am reverting to jquery to do the dirty work.
Problem is for me.. I can't get it to work either....
< is the link to the following code on jsfiddle:
<form action="" method="post">
<input id="optin" name="optin"><br />
<input type="submit" id="submit" name="submit" value="go">
</form>
$('input[name=optin]').click(function() {
$(this).css('outline', none');
});
|
Just a typo (a missing quote) :
$('#optin').click(function() {
$(this).css('outline', 'none');
});
Note that I also replaced `'input[name=optin]'` by `'#optin'` because this is cleaner and faster to use the id when you have one.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 2,
"tags": "jquery, html, forms, input, jquery selectors"
}
|
survplot() in "rms" : number of risk is shown by the whole group, not for each curve
I was plotting survival curves using `survplot{rms}`. However, when I used `n.risk = TRUE` to plot the number of risk table, R gave me a number of the whole data set, not for each curve, and I cannot figure out why.
# initialize survival commands in R
survive <- Surv(dat$dx_lastcontact_death_months, dat$event)
library(rms)
ff <- cph(survive ~ radiation, data = dat,x = T, y = T)
survplot(ff,radiation,conf.int = 0.95,
lty = c(1,1,1), col = c("red","blue","yellow"), xlab = "", ylab = "",
xlim = c(0,60), time.inc = 12, label.curves = F, n.risk = T)
` function around a categorical variable results in the expected output format. I did also add `surv=T`.
n <- 1000
set.seed(731)
age <- 50 + 12*rnorm(n)
label(age) <- "Age"
sex <- factor(sample(c('male','female'), n, TRUE))
cens <- 15*runif(n)
h <- .02*exp(.04*(age-50)+.8*(sex=='female'))
dt <- -log(runif(n))/h
label(dt) <- 'Follow-up Time'
e <- ifelse(dt <= cens,1,0)
dt <- pmin(dt, cens)
units(dt) <- "Year"
dd <- datadist(age, sex)
options(datadist='dd')
f <- cph(Surv(dt,e) ~ strat(sex), x=T,y=T, surv=T)
survplot(f, sex, label.curves = F, n.risk = T)
 then stop removing any numbers after?
$title = "0002.22 Greatest Voices In The Business (Current Female Singers Only)";
$words = preg_replace('/[0-9]+./', '', $title );
output:
Greatest Voices In The Business (Current Female Singers Only)
expected output:
22 Greatest Voices In The Business (Current Female Singers Only)
|
So, you need to remove all numbers from start of the string till the dot ? Use `^` for "start of string"
$title = "0002.22 Greatest Voices In The Business (Current Female Singers Only)";
$words = preg_replace('/^[0-9]+\./', '', $title );
If u need to remove any number followed by dot, your code is correct, except that **dot** is special character and need to be escaped .
$title = "0002.22 Greatest Voices In The Business (Current Female Singers Only)";
$words = preg_replace('/[0-9]+\./', '', $title );
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, regex"
}
|
Aggregate rows to create new columns based off row content in MySQL
I currently have a query that returns this result:
|product|status|
|-------|------|
|string1|A |
|string1|C |
|string2|B |
|string2|A |
|string3|B |
|string3|B |
----------------
And I would like to be able to convert it into a descriptive table like this.
|product|total |A |B |C |
|-------|------|-----|-----|------|
|string1|2 |1 |0 |1 |
|string2|2 |1 |1 |0 |
|string3|2 |0 |2 |0 |
-----------------------------------
Is there some kind of rollup or handy function that lets me aggregate rows like this?
|
You want to pivot the data. I would recommend conditional aggregation:
select product, count(*) as total,
sum( status = 'A' ) as A,
sum( status = 'B' ) as B,
sum( status = 'C' ) as C
from (<your query here>) q
group by product;
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "mysql, sql, pivot table"
}
|
Make enter select existing or top match
We've implemented algolia for our search, but now we're trying to figure out how I can trigger "enter" to select the existing match (say you're done typing and it's a match), or the #1 selected choice that comes from the dropdown.
I haven't been able to find any good documentation on this. Does anybody know how to do this?
Example (here I want 0934 to be chosen when you click enter): .
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "algolia"
}
|
Create network from points in QGIS using grouping variables
There seem to be some answers for this problem for ArcMap, but not for QGIS.
I have a set of points representing the power grid and I want to produce a network from them. Here's my data:
ID lat_from lat_to lon_from lon_to voltage
1 51.1 51.2 0.2 0.97 400
1 51.2 51.9 0.96 0.84 400
1 51.4 51.8 0.5 0.37 275
1 51.6 51.7 0.7 0.57 400
1 51.7 51.6 0.6 0.67 275
1 51.8 51.4 0.9 0.97 400
Many of the tools don't seem to accept directional connections (from point x to point y) or grouping variables (e.g. voltage)
I'm looking for something like this:

This can be done in many ways, for example using CONCATENATE in Excel or LibreOffice.
Then the file can be saved as csv, keeping any needed attributes as additional columns, and opened in QGIS using "Add delimited text layer" and choosing the WKT linestring column as geometry.
Then the attributes can be used to create an adequate symbology.
|
stackexchange-gis
|
{
"answer_score": 2,
"question_score": 1,
"tags": "qgis, network"
}
|
AngularJS: Is there a better way to sync two promises?
$http.get('/services/menu').success(function (dataMenu) {
$http.get('/services/language').success(function (dataLanguage) {
console.log('dataLanguage', dataLanguage);
$scope.menuRoot = dataMenu.result.items;
$scope.menuItems = dataMenu.result.items;
$scope.languageRoot = dataLanguage.result;
$scope.currentMenuItem = null;
$scope.refreshExperiments();
$scope.mergeLanguage();
});
});
|
Yes, you can run them in parallel by using `$q.all`:
$q.all([$http.get('/services/menu'), $http.get('/services/language')])
.then(function (res) {
var dataMenu = res[0].data.result.items;
console.log('dataLanguage', res[1].data);
$scope.menuRoot = dataMenu;
$scope.menuItems = dataMenu;
$scope.languageRoot = res[1].data.result;
$scope.currentMenuItem = null;
$scope.refreshExperiments();
$scope.mergeLanguage();
});
|
stackexchange-stackoverflow
|
{
"answer_score": 25,
"question_score": 10,
"tags": "javascript, angularjs"
}
|
is OAuth2 a good choice to allow external Enterprise clients SAML Authentication?
We have build a stand alone SaaS product and we are attracting Enterprise clients who want their users to log straight in. We are not looking for authorization, just simpler authentication; where the user gets an account without having to enter their name or email address.
We want to give our enterprise customers the ability to connect to our login system. Once we implement Oauth2, do we need to supply the end customers with an authentication server or is this something they sort themselves?
I have been looking at services, would < be good?
|
It sounds like your clients want to use their own Identity Provider to issue SAML assertions that your SaaS product can use to authenticate them. Hence you would be looking at an Identity Provider initiated logon architecture.
You would need to setup your SaaS product as a Service Provider, exchange metadata and certificates to enable signing, then you can accept SAML assertions and grant the users access. You can use a number of libraries to implement this.
We recently used the open source library OIOSAML to build both an Identity Provider and a Service Provider, both which proved straightforward and reliable. They have .Net and Java versions. Even if you decide to use a different product, both include sample applications and documentation that are very valuble to see SAML in action.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "oauth 2.0, saas, saml 2.0"
}
|
Can feedback be used on buildings?
Can you feedback buildings: Nexus, Orbital center?
|
According to this* (and the fact that I just tried it), it can't.
> * Feedback is an offensive spell cast by the Protoss High Templar. It is cast on an enemy spell caster ( **cannot be used on buildings** ), depleting the target's energy pool and dealing one point of damage for each energy lost. Feedback can only be cast on units with energy.
|
stackexchange-gaming
|
{
"answer_score": 11,
"question_score": 11,
"tags": "starcraft 2"
}
|
Dataset in Foundry has a marking that appeared from nowhere
I have a dataset in Foundry that has a marking, but none of its input datasets have a marking. How did the marking appear on my dataset?

2. If the dataset is up to date, the marking was directly applied to the dataset or its parent folder/project.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "palantir foundry, palantir foundry security"
}
|
Populate QCombobox with SQL Values
I'm trying to populate a `qcombobox` with values from an SQL table, but I get
> TypeError: addItems(self, Iterable[str]): argument 1 has unexpected type 'function'
My code is
self.building = QComboBox()
self.building.addItems(lambda: self.Buildingcombobox())
and
def Buildingcombobox(self):
conn = pyodbc.connect(<connection>)
cursor = conn.cursor()
cursor.execute("SELECT building, building_id FROM buildings")
rows = cursor.fetchall()
for row in rows:
self.building.addItem(str(row[0]), row[1])
print(row)
conn.commit()
conn.close()
I'm selecting building and building_id because I want only building_id stored in the table employees.
|
The `QComboBox()` object's `addItems()` method wants an _Iterable[Str]_ parameter, not a function which adds items to the widget.
(For the SQL that you've quoted, you do not need to `commit` because you're not `INSERT`ing, `DELETE`ing or `UPDATE`ing).
I would remove the call to `addItems()` entirely, and use your `Buildcombobox` function (without the `commit`) because the `addItem()` call is doing what you need.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, sql server, pyqt, pyqt5, pyodbc"
}
|
How to set the status message in [Code] Section of Inno install script?
I know that `StatusMsg`can only be used in the [Run] selection. I want to use the same in the `[Code]` Selection, Please Help me to solve this,
Thanks in advance, Regards Samuel J
|
You can change the status label contents at runtime using:
WizardForm.StatusLabel.Caption := 'Intalling WibbleTech Widget'
See the Support classes reference for the full list of controls and properties you can change.
|
stackexchange-stackoverflow
|
{
"answer_score": 15,
"question_score": 9,
"tags": "installation, inno setup, uninstallation"
}
|
how can we include favourite functionality in android?? please provide any example
how can we include favourite functionality in android?? please provide any example i mean to say there is a one phase in my app "favourite". when you click on particular item from the list that particular item will be add into the favourite and you can view that selected item in that favourite list.
|
If I understood well you want to store favourites item somewhere. An easy way to do that could be create a key in SharedPreferences that stores you favourites.
// Read the favourites
SharedPreferences settings = context.getSharedPreferences("FavouritesApp", 0);
Set<String> favourites = setting.getStringSet("myFavourites");
// Write the favourites
SharedPreferences settings = getSharedPreferences("FavouritesApp", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putStringSet("myFavourites",myStringSet);
editor.commit();
All that you have to do is to keep a set of strings that identify your favourites.
This is a very small example and probably not the best way to do that.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "android"
}
|
How to close programs running in the background
when I do `ps` I see `vi Dockerfile` running how do I close it?
I tried `q!` in the vi editor but doesn't seem to work.
|
Before killing the process like suggested in the comments, you could try to get it from the background to the foreground with the command `fg`.
After bringing it to the foreground you can close the program like you would normally do. In case of vi with:
* `:q` if you have no changes made to the file
* `:qw` if you have made changes and want to keep them
* `:q!` if you have made changes but don't want to keep them.
If `fg` doesn't work you can use `kill` or `killall` like suggested in the comments.
I prefer `kill`, because it only kills the process you choose. Find process:
$ ps -ef | grep <e.g. program_name>
Example output:
user 15256 31598 0 14:41 pts/0 00:00:01 program_name
Kill process:
$ kill 15256
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sh, vi, ps"
}
|
How can I find out which user groups my domain user belongs to?
Running Windows 7 on my work PC, how can I check which groups I am a part of on the domain from my PC? I know how to check the local groups using MMC (Microsoft Management Console), just not the groups managed on the domain. I do not have remote access to our domain controller to check this, as we use a proprietary admin tool to access the server and licensing prevents additional installation.
|
Open a command prompt.
Type: `net user <userName> /domain`
It will list both Local and Global groups that user belongs to.
If you want it to only list the groups, you can use Find to filter it:
`net user <userName> /domain | find "Group"`
This has worked in all (NT) version of Windows since at least NT 4.
On Vista/2008 and above, you can also use `WhoAmI /Groups` to get a verbose list of group memberships (including their UIDs, etc.) for the current user.
|
stackexchange-superuser
|
{
"answer_score": 122,
"question_score": 68,
"tags": "windows 7, windows, domain, active directory, user groups"
}
|
Intersection - Difference - Union of sets
1) $A \setminus B = A \cap \overline B$
2) $(A\cup B)\setminus(A\cap B)=(A \setminus B)\cup(B\setminus A)$
3) $A\cup B=(A \setminus B)\cup (B \setminus A)\cup (A\cap B)$
I need to prove the following equalities of sets. I only have an idea for the first and did the following.
1) My Answer : By definition $A \setminus B = \\{x \in U \mid x \in A \text{ and } x\notin B\\}$.
For set B we have the following : $$x \in U\text{ and }\space x\in B$$ but, $$\overline B=\\{x\in U\mid x\notin B\\}$$
Hence from the following facts I got,
$$A\cap \overline B=\\{x\in U\mid x\in A \text{ and }\notin B.$$
I assume that this is logically true but I'm not sure whether it is true as a proof.
I'll be waiting for your comments about "1"(to my solution) and also help for "2 and 3"
|
The usual thing to do in this kind of proof is to show that each set (on each side of the equation) is contained in the other.
As for example in 1) you need to verify that $A\setminus B\subseteq A\cap \overline{B}$ and $A\cap \overline{B}\subseteq A\setminus B$. And this you can do taking an $x$ in $A\setminus B$ and proving that $x\in A\cap \overline{B}$ and vice-versa. But the idea to prove this is pretty similar to what you've done.
That being said, the statement 2) is false, maybe you got it written wrong because if you change the second part for $(A\setminus B)\cap(B\setminus A)$ it works.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "elementary set theory, proof verification"
}
|
R: Data frame names with escape characters
In R, how can I do this
mdf1 <- data.frame(a=c(1:5),b=c(11:15),c=c(21:25),d=c(101:105))
names(mdf1)[2] <- 'A-11:01'
in one operation? Something like:
mdf1 <- data.frame(a=c(1:5),'A-11:01'=c(11:15),c=c(21:25),d=c(101:105))
which produces A.11.01 instead... Thanks!
|
Use `check.names = FALSE` in `data.frame()`.
data.frame(a = 1:5, "A-11:01" = 11:15, c = 21:25, check.names = FALSE)
# a A-11:01 c
# 1 1 11 21
# 2 2 12 22
# 3 3 13 23
# 4 4 14 24
# 5 5 15 25
**Note:** You don't need all those `c()` calls around the sequence generation operator `:`
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "r, escaping, dataframe, names"
}
|
convert scientific data into generic
I have a file containing only numerical values in scientific format. I want to convert them into generic notation and multiply them by 1000. e.g.
_input.txt_
1.1234e-01
2.123e+01
3.12345e-02
...
...
_output.txt_
112.34
21230
31.2345
...
...
I have many such files to perform the task (one file at a time) so command line single liner solution is preferable.
|
You could try this little awk script:
#!/bin/awk
{ printf "%f\n", 1000*$0 }
That's reasonably concise, but may produce unnecessary trailing zeroes.
|
stackexchange-unix
|
{
"answer_score": 4,
"question_score": -1,
"tags": "text processing, text formatting"
}
|
When deriving Bernoulli's equation why do we assume that the forces are inward?
Consider the following diagram. All textbooks I read don't explain why the forces are assumed to be inward. Could you tell me the reason?
. Someone has already configured another server, so I am referring that too while configuring.
After setting the default gateway, I cant ping to that gateway ip though I can ping to the loopback address and to the local server ip. I have referred the already configured server and found that both server uses same gateway..The already configured server can ping this gateway, but not mine.
What will be the issue?? Can someone please help me on this,since my work is on hold now??
|
Found out the root cause.. This might be a basic issue... But posting if in case helps this anyone..
My hostname (or FQDN) and IP was not added in **/etc/hosts** file. And it worked!!!
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": 0,
"tags": "linux, ping, trace"
}
|
Передача параметра даты при вызове хранимой процедуры MS SQL Server
Вызываю хранимую процедуру с параметром типа datetime из проекта ADP Access 2003, выдаёт ошибку
> Неправильный синтаксис около конструкции '-'
Пробовал разные форматы дат, но ошибка однотипная повторяется, только конструкции другие.
Вызов из кода
Me.items.Form.RecordSource = "exec usp_pct_ItemForTree " & cur & "," & usl & ",-1,1,'" & Nz(fltr, "") & "'" & "," & Abs(Nz(inet, 0)) & "," & idb & "," & DueDate
Хранимая процедура
alter procedure [dbo].[usp_pct_ItemForTree]
@group_id int=21
,@instoreonly int=1
,@idbrand int=-1
,@hotim bit=1
,@fltr varchar(150)=''
,@inet bit = 0
,@idbill int=null
,@dueDate datetime = null
Пример даты
2015-09-22
Строка, после конкатенации
"exec usp_pct_ItemForTree 0,6,-1,1,'',0,5425157,2015-09-22"
|
Проблема в настройках locale. На клиенте и сервере установлены разные locale. Клиент передает дату в одних региональных настройках, в то время когда сервер ожидает принять в других.
Отсюда и возникает ошибка преобразования строки `varchar` к `datetime`. Нужно смотреть настройки сервера. В каком формате от принимает параметры типа `datetime`. Или использовать инструкцию set dateformat перед выполнением обновления в хранимой процедуре.
Ну и обязательно использование одинарных кавычек, как правильно заметил Aries. Без этого никуда. Дату следует передавать в хп так же как и строковые параметры.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql server, ms access"
}
|
Как скопировать значение кнопки?
Такой вопрос: как мне скопировать само значение кнопки? Т.е.:
<input id="knop" name="nomer_vagona" type="submit" value="<?=$item->num ?>" />
Значение `value` нужно копировать.
Заранее спасибо!
|
Javascript:
document.getElementById('knop').value
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "html, css"
}
|
what is the fasest method to communicate between pthreads on linux
I have a pthreads app that I currently use regular linux pipes to communicate and send messages to the various threads. Its works fine and is not really broken but I have a nagging feeling that it can be improved.
If I want to design for the least latency, what is the **fastest** method to communicate between pthreads? Would using condition variables be faster than pipes?
I need to pass small amounts of data, as a single int optcode with a few parameters. Will pthreads condition variables let me pass data between threads?
Thanks,
-Andres
|
Since it's between threads then either shared memory or a lock free queue would be quite a bit faster.
The choice between which to choose will depend on the data you're passing around. A static buffer shared between two threads guarded by a lock is fine. Where you are generating data and passing it to another thread perhaps a queue is a better choice.
Some implementations of bounded lockfree MPMC queues are available here: <
By the way, be careful writing your own lock free data structures. They are not as trivial as you might expect to get right. A locking version will be a good start and will still out-perform pipes.
Between processes linux pipes as you call them (or unix domain sockets are a good option).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "linux, multithreading, pthreads"
}
|
Upvote increases rating with +2
Mates,
I'm wondering why was my rating increased by `+2` after I had received a downvote. Or it's something that is supposed to happen (by rules) when a downvote is received ?
!enter image description here
|
To explain, let's give number to each upvote:
> (data da insercao)(hora insercao).txt
1234567894120150501142024.txt
Preciso selecionar o `txt` correspondente ao CPF do cliente informado, porém não estou conseguindo procurar o arquivo.
|
Utiliza a função glob() para isso.
foreach (glob("00000000000*") as $file) {
$user = $file;
}
Note que na definição do padrão existe um `*` que serve para definir que tudo o que vier após o `$cpf` é irrelevante para a busca, sendo assim você receberá como retorno todos os arquivos que possuam no início um valor que seja igual ao CPF igual ao buscado.
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 5,
"question_score": 4,
"tags": "php, diretório"
}
|
Using ArcPy to get length of Polyline created?
I am trying to get the length of Polylines I am creating immediately after I create them.
The code I am using:
arcpy.Polyline(arcpy.Array([arcpy.Point(firstx, firsty), arcpy.Point(secondx, secondy)])).getLength('GEODESIC', 'METERS')
Error I am receiving:
Traceback (most recent call last):
File "C:\Josh\Scripts\Projects\carriageways_unplit_ptSplit.py", line 53, in <module>
road_specs['{0}_{1}_{2}'.format(round(road[0], 5), round(road[1], 5), arcpy.Polyline(arcpy.Array([arcpy.Point(firstx, firsty), arcpy.Point(secondx, secondy)])).getLength('GEODESIC', 'METERS'))] = road[2]
File "C:\Program Files (x86)\ArcGIS\Desktop10.2\arcpy\arcpy\arcobjects\arcobjects.py", line 781, in getLength
return convertArcObjectToPythonObject(self._arc_object.GetLength(*gp_fixargs((method, units))))
TypeError: Invalid geometry type for method
Am I creating the polyline incorrectly?
|
Spatial reference of newly created Polyline is undefined, this is why ArcGis struggles with next request, that is a calculation of geodetic length.
So, define spatial reference in arcpy. Polyline () method. I also suggest to split single line of code into three a) create array of points b) create Polyline c) calculate it's length. This is easier to read and debug
|
stackexchange-gis
|
{
"answer_score": 5,
"question_score": 1,
"tags": "arcpy, arcgis 10.2, line, length, typeerror"
}
|
push array into multidimensional array?
I have json_encoded array that i would like to add to using php
[{"id":"a","value":"2"},{"id":"b","value":"2"}]
I want to add the following to the array above:
array("id" => c, "value" => "3")
I tried `json_decode` then trying to push the array into that but im confused on how to do that
|
Make sure you use json_decode in array mode rather than object mode:
// Default: JSON is decoded as object
$json_object = json_decode($json_string);
// Pass true in the second argument to get an array instead
$json_array = json_decode($json_string, true);
// Push a new entry onto the end
$json_array[] = array("id" => c, "value" => "3");
// Re-encode JSON string, if needed
$json_final_string = json_encode($json_array);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, json, multidimensional array"
}
|
SQL ADSI Active Directory Create New Accounts
I have an ADSI connection in my SQL Server (2005) and I'm able to query it using openquery. Is there any way to create new accounts (and/or) edit existing ones?
Also, I'd like to have to use openquery to get to the data, but it looks like it's the only solution.
Here's a sample query that I'm using:
SELECT
samaccountname,
department,
mail,
displayName,
employeeid
FROM OPENQUERY( ADSI,
'
SELECT samaccountname, department, mail, displayName, employeeid
FROM ''LDAP://DC=MyDomainName,DC=MyDomainExtension''
WHERE objectCategory = ''Person'' and objectClass= ''user''
'
)
Thanks
|
You can't (at least not using ADSI SQL).
ADSI SQL only defines a search interface, supporting nothing more than the `SELECT` statement (See MSDN: "SQL Dialect.aspx)"). Also, `OPENQUERY()` is the only way to get the data in SQL Server.
To create objects, you will have to use another method (you can script against the ADSI interface quite well).
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "sql server, active directory, adsi"
}
|
using free bound generic type as type parameter
Do you see a way to specify that my result type have to be **MonadType < arg type >** within this interface ?
interface IMonad<MonadType> // where MonadType : GenricType<>
{
MonadType<T1> unit<T1>(T1 t)
Func<MonadType<T1>, MonadType<T2>> map<T1, T2>(Func<T1, T2> f);
}
I get as an error : The type parameter 'MonadType' cannot be used with type arguments
|
No, you can't do this with .NET generics. What you want to do is to specify that the `MonadType` type parameter must itself have one generic parameter; the .NET type system can't represent that constraint.
Here's one approach to faking generic monads in C#: <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, .net, generics"
}
|
Expected End of Statement Error When Inserting Formula into Excel with VBA
I'm getting Expected End of Statement Error with the code below. The debugger is highlighting the full stop/period but that is part of the formula.
Can anyone see the issue?
Sub ParseSurnames()
Dim lastRow As Long
'Where is last row of data?
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
'Apply formula
Range("C1:C" & lastRow).Formula = "=IF(A1="","",LEFT(A1,FIND(".",A1)-3))"
End Sub
|
Try changing the code line applying the formula in:
Range("C1:C" & lastRow).Formula = "=IF(A1="""","""",LEFT(A1,FIND(""."",A1)-3))"
In a string containing ", the double quote must be escaped, using another one. I mean """" for "" and "" for "...
In order to check such strings, please try the next code line:
Debug.Print "=IF(A1="""","""",LEFT(A1,FIND(""."",A1)-3))"
Does it return in Immediate Window (Ctrl + G, being in VBE) the formula as you need? If yes, this is the way...
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "excel, vba"
}
|
How to add where not null condition to cron job in Laravel
In my Laravel-5.8, I have a cron job running.
public function handle()
{
$client = new Client();
$res = $client->request('GET',' [
'query' => ['key' => 'kkdfhfn7755222']
])->getBody();
$clientdatas = json_decode($res->getContents(), true);
foreach($clientdatas as $clientdata)
{
$testing = HrTesting::updateOrCreate([
'testing_name' => $clientdata['testing_location']
],
[
'company_id' => 1,
]);
}
}
I found that where $clientdata['testing_location'] is null, it still creates/updates it in the table.
How do I put it that where null, it should not perform any action?
Thanks
|
Just simply add it to your foreach loop.
foreach($clientdatas as $clientdata)
{
if (isset($clientdata['testing_location']) && $clientdata['testing_location'] !== null) {
$testing = HrTesting::updateOrCreate([
'testing_name' => $clientdata['testing_location']
],[
'company_id' => 1,
]);
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "laravel, cron"
}
|
Azure - Web to SQL with local (Azure) IP
In a typical web app environment, the SQL server and Web App server are on the same network and the web app connects to the SQL server using a local IP. This, of course, helps performance as requests dont need to go out to the internet and come back, all the communication can be done in the local network. An added benefit is being able to completely restrict the SQL server to internal traffic only.
How can the same be accomplished with an Azure Web and SQL server? Im assuming that being in the same geographical area is an obvious requirement (or not?). Is it as simple as finding out the SQL servers local IP and opening the firewall to the web server? Are all azure resources in a geographical location part of the same network? Do I need to create a VLAN of some sort? Sorry....probably trivial questions, but not knowing the physical architecture of Azure creates confusion for me..
|
There is no such thing as a direct local connection for Azure SQL DB. You cannot place either in a virtual network (though a Web App can be _connected_ to a VNET).
The firewall option in Azure SQL that allows traffic from your Web App allows traffic from _any_ Azure subscription by the way. Azure can surely detect malicious attempts to break into Azure SQL and block them if they occur, but your main line of defense is your password. And auditing helps too of course.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "sql server, azure, networking, azure sql database, azure web app service"
}
|
Support on Windows for Sony noise-canceling in-ear earphones
I have these Sony noise-canceling in-ear earphones (model number: mdr-nc31e):
!enter image description here
They came with my Sony Xperia Z2 phone. On the Z2 they kind of work. I can't hear my colleges talking if I plug them in (without even playing music and that's great).
But however if I use them with other devices the noise-canceling does not work. Are there any drivers for example for Windows? Or is this hardware specific?
|
It's a non-solvable hardware issue. Sony agrees.
From what i've seen it's a 5-pin jack. One of the pins is dedicated for noise feedback. Your PC probably has only 3 pins.
Noise cancellation requires a digital circuit to measure, process and invert the noise signal.
According to this article: " _sound processing and battery power are provided by the device they are plugged into_ ". Your PC hasn't got one of those either.
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": 0,
"tags": "windows 7, noise cancelling"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.