INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Call ASP from Javascript
I'm trying to figure out, how can i call ASP (NOT asp.net) site/page/etc with javascript. The ASP is external file and JS is inside of HTML code.
ASP function is intended to use delete function, which deletes selected row from database. How can i do it without changing the page in browser?
And PLEASE, tell me, if you know some another way to do this, i'm still learning ASP.
Thank You!
|
There are a few ways to do this, but by _far_ the most common way is to use `XMLHttpRequest`, often called AJAX. For example:
var xhr = new XMLHttpRequest();
xhr.open("POST", "delete.asp", true);
xhr.send("id=" + rowID);
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "javascript, asp classic"
}
|
Should i bring bytearray of image along with entity? - ria services
I have near about 100 entities and each entity has custom property of byteArray which is the actual byte array of the image. My question is should i bring the byte array also along with the entities or should i make 100 requests(each request for each entity) so that the user can atleast see something while the other bytearrays are being downloaded.
Thanks in advance :)
|
Think through the application requirements and make a decision based on that. How big are the byte[]s? What will the receiving app actually do with these? Display them all at once or on-demand? Will they be displayed initially just as thumbnails?
Your decision isn't just whether or not to include the byte[]... depending on the actual requirements, you could put the byte[]s as seperate entities which can be retrieved by making paged requests to that collection as the user scrolls through some list. Or you could decide to create seperate entities to represent thumbnails of the images. Lots of options...
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "silverlight, silverlight 4.0, wcf ria services"
}
|
Why CreateWindowEx will add WS_CAPTION by default?
I'm trying to create an window by CreateWindowEx.aspx), but seams even I give both `dwExStyle` `dwStyle` value 0, the window still have `WS_CAPTION` style.
Code snippet as following:
_hWnd = CreateWindowExW(iExStyle, pszClassName, pszTitle, iStyle | WS_CLIPCHILDREN, dX, dY, dWidth, dHeight,
hWndParent, 0, hInstance, NULL);
ASSERT(GetWindowLong(_hWnd, GWL_STYLE) & WS_CAPTION == 0); //<---- This will failed.
|
`dwStyle = 0x00000000L` means `WS_OVERLAPPED or WS_TILED`, this window has a title bar and a border.
Window Styles.aspx)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c++, winapi"
}
|
iOS and UIKit class checking
How do you programmatically check if `UIKit` has a given class?
For example, on iOS3 there's no `UINib`, but on iOS4 there is. I can build on SDK4, but if I try to run on an iOS3.0 device I'll meet an exception.
|
The iOS 4 release notes state:
> iOS 4 includes a new UINib class to support rapidly unarchiving nib files. While this class is new to iOS SDK 4, it was present but private, in previous releases. Special care needs to be taken when deploying code that uses the UINib class and also runs on iOS releases prior to version 4. Specifically, you cannot determine the availability of the class solely using the NSClassFromString function, because that check returns a private class on iOS 3.x and earlier. Instead, after getting the UINib class using NSClassFromString, you must also use the respondsToSelector: method of the returned class to see if it responds to the nibWithNibName:bundle: method. If it responds to that method, you can use the class.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "ios, class, uikit"
}
|
How to extract part of an aeson value that satisfies a condition?
I have a JSON structure which looks like this:
{
"instances": [
{
"instanceId": "i-1234",
"tags": [
{
"value": "author1useast1",
"key": "hostname"
}
]
},
{
"instanceId": "i-5678",
"tags": [
{
"value": "proxy1useast1",
"key": "hostname"
}
]
}
]
}
I would like to get a list of all `instances/instanceId` where `instances/tags` has a `hostname` of `author1useast1`.
I have thought about getting a list of instances with `key "instances" . _Values` first, then mapping it into a list of (`instanceId`, `tags`) tuples and then doing the filtering. However that looks very inefficient to me.
Is there a more elegant / idiomatic way of doing this?
Thanks a lot!
|
If you want to use lens, you can use `filtered` optic, as instance:
key "instances" . values
. filtered (anyOf (key "tags" . values) $
allOf (key "key") (=="hostname")
<&&> allOf (key "value") (=="author1useast1"))
. key "instanceId"
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "json, haskell, filter, haskell lens, aeson"
}
|
Node.JS extracting class comments
I have a Node.JS project that I'm working on, and a very specific feature of it needs to read all of the JS files in a directory, extract their class comments (possibly class name too), then store this information in an array of objects to later convert into markdown.
My question is _what's the best way to extract these components such as class names and class comments?_
I've thought about reading the file and parsing the syntax, but why reinvent the wheel? If there are good tools for extracting specific comments, or clever algorithms of parsing the JS file, I'd like to hear them. Thanks!
|
You can try one of these libs:
<
<
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, node.js, comments"
}
|
xpath find specific link in page
I'm trying to get the email to a friend link from this page using xpath.
<
The link itself is wrapped up in tags like this
<li><a class="rollover sendlink" href=" title="Opens an email form" name="&lid={pageToolbox}{Email a friend}&lpos={pageToolbox}{2}"><img src=" alt="" class="trail-icon" /><span>Send to a friend</span></a></li>
I'm using this for my query, but it's not quite right.
$links = $xpath->query("//a/span[text()='Send to a friend']/@href");
|
You're trying to get the href of the span there. I think you want
$links = $xpath->query("//a[span/text()='Send to a friend']/@href");
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "html, parsing, xpath"
}
|
Should the "X" be lined up with the Login button or Sign Up Form?
, (27,29), (30,33), (42,46)]
This example is easy, I'd like to know if there is an algorithm that deals with complex data sets as well
thanks
|
You are looking for the quantiles that split up your data equally. This combined with `cut`should work. So, suppose you want `n` groups.
set.seed(1)
x <- rnorm(1000) # Generate some toy data
n <- 10
uniform <- cut(x, c(-Inf, quantile(x, prob = (1:(n-1))/n), Inf)) # Determine the groups
plot(uniform)
!Imgur
Edit: now corrected to yield the correct cuts in the ends.
Edit2: I don't quite understand the downvote. But this also works in your example:
data_set = c(18,21,22,24,27,27,28,29,30,32,33,33,42,42,45,46)
n <- 4
groups <- cut(data_set, breaks = c(-Inf, quantile(data_set, prob = 1:(n-1)/n), Inf))
levels(groups)
With some minor renaming nessesary. For slightly better level names, you could also put in `min(x)` and `max(x)` instead of `-Inf` and `Inf`.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "sql, r, statistics"
}
|
Pre-Tax Plan Election - Employers Benefit Plan
Looking for advice on whether it makes sense to accept participation in the Pre-Tax Plan where your employer is authorized to reduce your income as necessary to pay your share of the cost of the employers benefit plan with pre-tax dollars.
Or if it's generally a better idea to waive the pre-tax plan and deduct my premium contributions for the plan after state / federal taxes have been withheld.
Since unused amounts would be forfeited at the end of the plan year, I'm not sure which route to go. So hopefully someone with more experience can give a better explanation as to which would be the better way to go, and why?
Thanks
|
The pre-tax vs post-tax issue may include more than an FSA. As discussed in What is the difference between pre-tax and post-tax paycheck deductions? it can be the entire cafeteria plan that that can be handled pre-tax or post-tax.
Most people don't want to pay for these benefits post-tax, but in a narrow range of situations such as trying to maximize your social security income it may make some sense to pay for these post tax.
The phrase:
> "reduce your income as necessary to pay your share of the cost of the employers benefit plan with pre-tax dollars"
may point to more than the FSA or HSA.
You will have to review all the documents regarding benefits to understand what your options are regarding pre-tax and post-tax.
|
stackexchange-money
|
{
"answer_score": 2,
"question_score": 2,
"tags": "united states, taxes, income tax, employment, benefits"
}
|
Find First Row and Insert Formula to Last Row
When A1 changes, I want to insert a formula to first row and drag it down to last row.
First row is where string "ABC" in column D offset by 2 columns to the right (how do I use offset function instead of just putting 5?)
My try:
Option Explicit
Private Sub WorkSheet_Change(ByVal Target As Range)
Dim firstrow As Long, lastrow As Long
If Not Intersect(Target, Range("A1")) Is Nothing Then
If Target.Count > 1 Then Exit Sub
firstrow = .Cells(Application.WorksheetFunction.Match("ABC", .Range("D:D"), 0), 6)
lastrow = .Cells(fr).End(xlDown).Row
With Range(firstrow, lastrow)
.Formula = "=$F$1+G1"
End With
End If
End Sub
Obviously this doesn't seems to work...
I know there got to be easier and much clever/simpler ways to do this
Thank you for the help.
|
I'm not sure exactly which column should be used to determine the `lastRow`, but something like this should do the trick:
Private Sub WorkSheet_Change(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
If Not Intersect(Target, Me.Range("A1")) Is Nothing Then
Dim firstRow As Variant
firstRow = Application.Match("ABC", Me.Range("D:D"), 0)
If Not IsError(firstRow) Then
Dim lastRow As Long
lastRow = Me.Cells(Me.Rows.Count, "D").End(xlUp).Row
Me.Range("F" & firstRow & ":F" & lastRow).Formula = "=$F$1+G1"
End If
End If
End Sub
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "excel, vba"
}
|
How to handle views?
How can I handle different views in XCode?
Let's say I want to show a different view when the user press a button.
UIViewController *viewSettings;
[viewSettings initWithNibName:(NSString *)@"SettingsViewController" bundle:(NSBundle *)nil];
This code don't work. The app crashes.
I have updated my XCode to the new version. How can I say my projects that they have to take the new SDK?
Thanks.
|
This is the correct line. Then you need to push it (pushViewController) onto a UINavigationController or add it to an existing view. Do a Google search for iPhone Beginner Tutorial First Application or something like that.
UIViewController *viewSettings = [SettingsViewController initWithNibName:@"SettingsViewController" bundle:nil];
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "iphone, objective c, xcode"
}
|
Rotate and transform connected rigid bodies in unity3d
I want to move connected rigid bodies as in image example, one of them needs to rotate around a point. Then using ground check I want to rotate it back to line I tried using hinge joint 2d, using angle limits, but can not control rotating angle.
How can I achieve this effect? thanks.
![rotate position\]](
Edit: Tagged both rigidbodies as fixed angle and then applied rotation to upper object
void Update () {
if(Input.GetKeyDown(KeyCode.F)){
zRotation += 45;
myGameObject.transform.eulerAngles = new Vector3(myGameObject.transform.rotation.x, myGameObject.transform.rotation.y, zRotation);
}
|
> How can I achieve this effect?
Point to the object then rotate it.
First you want to find the GameObject.
GameObject g = GameObject.Find("Object Name");
Save the original rotation so you can return to it.
Quaternion originalPos = g.transform.rotation;
Then rotate it to your liking.
g.transform.rotation = new Quaternion(x,y,z,w);
In addition you could use iTween to smoothen out the rotation.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "c#, unity3d"
}
|
Randomness of np.random.shuffle
I have two arrays (i and j) that are exactly the same. I shuffle them with a specified random seed.
import numpy as np
np.random.seed(42)
i = np.array([0, 1, 2, 3, 4, 5, 6, 7])
j = np.array([0, 1, 2, 3, 4, 5, 6, 7])
np.random.shuffle(i)
np.random.shuffle(j)
print(i, j)
# [1 5 0 7 2 4 3 6] [3 7 0 4 5 2 1 6]
They were supposed to be the same after shuffling, but it is not the case.
Do you have any ideas about how to get the same results (like the example below) after shuffling?
# [1 5 0 7 2 4 3 6] [1 5 0 7 2 4 3 6]
Many thanks in advance!
|
Calling `seed()` sets the state of a global random number generator. Each call of `shuffle` continues with the same global random number generator, so the results are different, as they should be. If you want them to be the same, reset the seed before each call of `shuffle`.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "numpy, shuffle"
}
|
How to replace substring between two other substrings in python?
I have a corpus of text documents, some of which will have a sequence of substrings. The first and last substrings are consistent, and mark the beginning and the end of the parts I want to replace. But, I would also like to delete/replace all substrings that exist between these first and last positions.
origSent = 'This is the sentence I am intending to edit'
Using the above as an example, how would I go about using 'the' as the start substring, and 'intending' as the end substring, deleting both in addition to the words that exist between them to make the following:
newSent = 'This is to edit'
|
You could use regex replacement here:
origSent = 'This is the sentence I am intending to edit'
newSent = re.sub(r'\bthe((?!\bthe\b).)*\bintending\b', '', origSent)
print(newSent)
This prints:
This is to edit
The "secret sauce" in the regex pattern is the tempered dot:
((?!\bthe\b).)*
This will consume all content which does _not_ cross over another occurrence of the word `the`. This prevents matching on some earlier `the` before `intending`, which we don't want to do.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, string"
}
|
windows 7 / server 2008 remote port query tool
Is there any built-in tool in Win7/Win Server 2008 to query remote host opening ports?
On Win XP/Win Server 2003, we can use `telnet <remote host> <port>` to do so. However, telnet is not available Win7/Win Server 2008.
|
I don't know a built-in tool. But 2003 shipped with `Prtqry.exe` a very handy tool to do just that. Maybe you could include it with the script or put it on a networkshare?
More info on can be found here : KB310099
Or if you have the rights to do it, run a `netstat` remotely.
|
stackexchange-serverfault
|
{
"answer_score": 1,
"question_score": 1,
"tags": "windows server 2008, networking, windows 7"
}
|
How to find the line integral from $(0,0)$ to $(1/8,0)$
I have to find the line integral from $(0,0)$ to $(1/8,0)$. I just want to know if what I did is correct.
$x=x$ and $y=0$ where $x$ is less than or equal to $0$ and greater than or equal to $1/8$.
I took the integral from $0$ to $1/8$ of $1dx$. However, I have to find the jacobian. The jacobian is the square root of the square of $dx/dx$ plus the square of $dy/dx$. Doing this I got square root of $(1)^2 + (0)^2 = 1$
So my integral is now just $1dx$ from $0$ to $1/8$. Solving this I get $1/8$.
Did I do this correctly?
|
Think of a line integral over a path $\gamma$ with velocity $v$ as
$ \int _ \gamma v dt = \int _ \gamma \sqrt { \left ( \frac{ dx}{dt} \right ) ^2 + \left ( \frac{dy}{dt} \right )^2 } dt$
You won't need the jacobian since we're not changing coordinates (that's when it'll show up). That path we're moving along in your case is
$ \gamma(t) = (t , 0 )$
we travel from $t = 0$ to $t=1/8$ so we end up doing exactly what you said.
$ \int_0^{1/8} dt = \frac{1}{8} $
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "multivariable calculus"
}
|
How to bring data to another page in php
As the question, I can do that with `$_SESSION` on the below code, but I would like to do that without using `$_SESSION`, any suggestion ? I am new for using oop in php.
PHP (page 1):
include './class.php';
include './next.php';
if(isset($_POST['submit'])){
$data = new myData();
$data->setTest($_POST['test']);
}
$content = '<form method="post" action="next.php">
<input type="text" name="test" id="test" value="test"/>
<input type="submit" name="submit" value="Submit"/>
</form>';
if(!empty($next)){
$content = $next;
}
echo $content;
class.php:
class myData{
function __construct($test){
***some process***
$_SESSION["test"] = $test;
}
}
next.php
$next = $_SESSION["test"];
|
You could store the variable in the class and then use a getter method to get that data back. file1.php
if(isset($_POST['submit'])){
$data = new MyData($_POST['test']);
}
class MyData{
private $data = '';
function __construct($test){
***some process***
$data = $test;
}
function getData() {
return $this->data;
}
}
file2.php
include file1.php;
echo $data->getData();
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, oop"
}
|
What is the most efficient way to do the String comparison?
Both do the same thing. What is the most efficient way to compare two strings? Equals() or Compare()? Are there any differences?
if (String.Equals(StringA, StringB, StringComparison.OrdinalIgnoreCase))
{
// Your code goes here
}
if (String.Compare(StringA, StringB, true) == 0)
{
// Your code goes here
}
|
Why don't you just try it out with a microbenchmark and find out?
Let each statement run atleast 100000 times.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 3,
"tags": "c#"
}
|
How to reference grandparent in scss?
I have a scss question.
Lets say I have something like this
.footer-logos {
&__link {
&:nth-child(2) a{
}
&:nth-child(3) a {
}
&:nth-child(4) a {
}
}
&__imagelink {
}
}
As you can see, I have &:nth-child(n) a. I want this to be like a has the class .footer-logos__imagelink. I tried to do like below
&:nth-child &__imagelink
Obviously, that did not work. I wonder how I can reference it there?
|
# Goal: `.footer-logos__imagelink`
`&` gives the parent's full selector, to achieve your goal you need to concatenate it with the child, to do so we can use string interpolations!
.footer-logos {
#{&}__imagelink {
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "css, sass"
}
|
Git clone error warning: refname '' is ambiguous. Git normally never creates a ref that ends with 40 hex characters
Got this error during cloning
remote: warning: refname '4e810d87701e09df2949cb33e731052aa05d2c76' is ambiguous.
remote: Git normally never creates a ref that ends with 40 hex characters
remote: because it will be ignored when you just specify 40-hex. These refs
remote: may be created by mistake. For example,
remote:
remote: git checkout -b $br $(git rev-parse ...)
remote:
remote: where "$br" is somehow empty and a 40-hex ref is created. Please
remote: examine these refs and maybe delete them. Turn this message off by
remote: running "git config advice.objectNameWarning false"
|
During cloning I got this error message and found that a tag was created with this name (like a 40-hex ref).
When you get this error, you can look for branch or tag names with the ambiguous value and remove it if the ref is not required
$ git tag | grep 4e810d87701e09df2949cb33e731052aa05d2c76
4e810d87701e09df2949cb33e731052aa05d2c76
$ git tag -d 4e810d87701e09df2949cb33e731052aa05d2c76
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 13,
"tags": "git, git clone"
}
|
Game Theory: Prove $F \geq G$
I'm trying to prove that $F=0.15w+0.5x+0.15y+0.2z$ is greater than or equal to $G=0.25w+0.25x+0.25y+0.25z$. I also know some additional information:
$w\ge x\ge y\ge z$
$x=0.6w+0.4z$
$y=0.2w+0.8z$
So far, using some substitution, I've managed to work the problem down to this: $F=0.48w+0.52z$ and $G=0.45w+0.55z$. This is where I am stuck. I'm not sure how to prove $F\ge G$ from here. Any help would be appreciated, and links to resources where I could learn more about how to solve this particular problem are encouraged. Thanks!
|
Based on what you've already done, $F-G=0.03(w-z)$, which is non-negative because $w \geq z$.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 1,
"tags": "inequality, proof writing, game theory"
}
|
How to access to extend user information from the template in Django?
I am extended user.model to ClientUser I want to have access to ClientUser information using current user from the template side. I want to display the name of the company in my template, something like this {{user.company}}
class ClientUser(models.Model):
client = models.OneToOneField(User)
company = models.ForeignKey(Company)
def __str__(self):
return str(self.company) + ' - ' + str(self.client)
class Company(models.Model):
company_name = models.CharField(max_length=250, null=True)
company_url = models.CharField(max_length=500, null=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.company_name
|
{{ user.clientuser.company.company_name }}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "django, django models, django forms, django templates, django views"
}
|
<script> tag elements are not working on Angular 2 CLI created application
I have create an application using angular cli. My application is the angular 2 application. I would like to run a `<script>` and put an alert box.
I have try to load the `<script>` on hello.component.html but it does not work. And also I try put the `<script></script>` inside the index.html but it also fails.
How do i implement `<script></script>` on angular 2 applications.
<script>
$(document).ready(function() {
alert("Hello from JS");
});
</script>
|
`<script>` tags in Angular2 component templates are just silently stripped.
You can use
class MyComponent {
ngAfterContentInit() {
alert("...");
}
or add JavaScript to your TypeScript by other means like `require`
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "javascript, angular, angular cli"
}
|
Does end user need to have .NET 3.5 or .NET 4.0 to run Silverlight 3 and 4 applications?
Does the end users need to have .NET 3.5 or .NET 4.0 installed on their machines in order to run Silverlight 3 or 4 applications from within IE?
|
Nope but he need to install the runtime of silverlight and it needs to be the same version or higher as where the app is developed in
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": ".net, silverlight, silverlight 3.0"
}
|
get_reader() got multiple values for argument 'mode'
this is my code:
reader = read(uri, format,"i", **kwargs)
with reader:
return reader.get_data(0)
I m getting error in above mentioned lines. I m not able to find error. Can anyone help me?
|
> reader = read(uri, format,"i", **kwargs)
I expect the "i" parameter is the mode argument (though I gues it could also be `format`), but the kwargs dict also contains a value for mode. As a result, Python gets a conflict where the mode argument is provided twice, and reports an error.
Either fix your positional parameters, or fix your kwargs, or update your kwarg with a default mode using `kwargs.setdefault('mode', 'i')` (that way `mode` is set to `'i'` when it was missing, but if it's already present it doesn't get replaced).
edit: opening an issue on their repository because your completely unrelated code is broken or nonsensical is not cool
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "python"
}
|
Rails has_secure_password authentication errors
This is my user:
class User < ActiveRecord::Base
has_secure_password
end
This is how someone can authenticate via API:
module Api
class SessionsController < ApiController
def create
user = User.find_by_email(params[:user][:email])
if user && user.authenticate(params[:user][:password])
# some login logic
else
render json: {messages: user.errors.full_messages}, status: :unauthorized
end
end
end
end
If I pass an incorrect password, I get 401 Unauthorized as expected. However, `user.errors` is blank. How can I access `has_secure_password` authentication errors?
|
only validation errors get populated in active record errors. Incorrect password is not a validation error. Why can't you set the message explicitly since the only possible error is email/password invalid
module Api
class SessionsController < ApiController
def create
user = User.find_by_email(params[:user][:email])
if user && user.authenticate(params[:user][:password])
# some login logic
else
render json: {messages: ["Invalid Email or Password"]}, status: :unauthorized
end
end
end
end
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "ruby on rails"
}
|
How istio do weight-based tcp traffic shifting?
The offical doc show a weight-based tcp traffic routing, I'm curious about how istio done this job due to tcp is streaming data, there is no delimiter in it. istio have no idea about what tcp data it will gets.
So I look into the example code found the destination go server use `byte('\n')` as delimeter. Does this mean istio tcp traffic routing(exclude the port forwarding which don't need inspect the data content) require user tcp data must use '\n' as delimeter?
|
envoy is incapable of routing custom defined L4 traffic. Its L4 traffic routing is only used for http, as the definition of http data format, string end with a `\n` is a legal Simple-Request, that's why the sample works fine.
The custom defined filters do encode and decode in `Envoy::Networks::ReadFilter::onData` and `Envoy::Networks::WriteFilter::onWrite` respectively. However, those 2 functions pass nothing to envoy about the knowledge of packet. That means envoy can not do traffic management on those custom defined tcp stream, for example, redirect to another pod
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "istio"
}
|
I need the updated sum from 1st to the current date
I have extracted the cell address of the current date by using:
=CELL("Address",INDEX($H$4:$AK$4,MATCH(G3,H4:$AK$4,1)))
`G3` contains the day number of the month.
Now I need to use the `Sum` formula in `G6` such that it adds the values from 1st to the current date which is updated by the function `Today()` in cell `G1`.
Is there a way I can use the `Sum` function to use the address inside the cell rather than the address of the cell.
!SS of the sheet
You can download the sheet from here.
|
I think you are making it too difficult. Just use `SUMIF`, and make the criteria that the dates are less than today.
`=SUMIF(date_range, "<"&TODAY(), sum_range)`
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "excel, excel formula"
}
|
c struct question
#include <stdio.h>
struct audiocd {
char title[256];
int trackNo;
char type;
char publisher[256];
};
int main() {
struct audiocd* cdptr;
struct audiocd cdarray[4];
cdptr = cdarray;
printf("%d\n", &(cdarray[2]));
printf("%d\n", cdptr);
}
What is `cdarray[2] & cdptr`?
EDIT: Thanks, but if `printf("%d\n", &cdarray)` is `4291520` , is it possible to trace `printf("%d\n", &(cdarray[2])) & printf("%d\n", cdptr)`?
|
The overall effect of the program is simply undefined behavior. It's passing addresses to printf, but using the `%d` conversion, which expects an int. The mismatch causes undefined behavior.
In a typical case that int and a pointer happen to be the same size, it'll print out the address in `cdptr` and the address of `cdarray[2]`.
If you want to print out those addresses, the obvious way is something like:
printf("%p", (void *)&cdarray[2]); // (void *)cdarray+2
printf("%p", (void *)cdptr);
As for what those expressions "are", they're addresses -- the addresses of the beginning of the array and the third element of the array, respectively.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "c, arrays, pointers, struct"
}
|
Recursive function to reverse an arbitrarily nested list
I'm trying to write a "simple" recursive function to traverse a tree represented by nested lists. I have the correct output when I use `print` but I want the result returned in a `list`.
Code
def trav(t):
while len(t) > 1:
for counter, i in enumerate(t):
if isinstance(i, list):
t2 = t.pop(counter)
trav(t2)
n=t.pop()
print(n)
Run it
tree1 = [1, [2, [4], [5]], [3]]
trav(tree1)
Output via print:
4
5
2
3
1
Desired output via return value:
[4, 5, 2, 3, 1]
|
Declare an accumulator `acc`, aggregate the return value of the recursive call in the loop.
At the end return `acc` \+ the last popped value (this nicely merges into the base case).
def trav(t):
acc = []
while len(t) > 1:
for counter, i in enumerate(t):
if isinstance(i, list):
t2 = t.pop(counter)
acc += trav(t2)
n = t.pop()
return acc + [n]
tree1 = [1, [2, [4], [5]], [3]]
print(trav(tree1))
# [4, 5, 2, 3, 1]
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -3,
"tags": "python, python 3.x, recursion"
}
|
Move files having one or two digits in name at certain point
Let's say I have a folder full of files with a name in the format `foo<number1>.bar.o<number2>`. `<number1>` can consist of `1`, `2` or `3` digits.
Now if I, for some odd reason, would want to move only the files at which `<number1>` consists of `1` or `2` digits, but not `3`, I would write a `python` script:
#!/bin/python
import glob, shutil, re
for f in glob.glob("*.bar.o*"):
print f
numbers = map(int, re.findall('\d+', f))
print numbers
if numbers[0] < 100:
shutil.move(f, "dir/" + f)
The question now: How can, if, this be done in less code, for example in one line (max 80 characters)?
Would prefer a solution usable in a `bash` shell.
|
unless I'm mistaken about what you mean:
mv foo[0-9][0-9].bar* /wherever/you/like
will catch 2 digit numbers
For either you could do:
mv $(ls |egrep "foo[0-9]{1,2}.bar") /wherever/you/like
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, regex, bash, mv"
}
|
Hammerjs panend not working in firefox
I have used hammerjs (version: 2.0.8) pan events to move an element (span). It works fine on Chrome and Firefox. But `panend` event is not working in Firefox. only `panstart` and `panmove` events are firing.
|
That's known issue on project's github. It seems that v. 2.0.1 works fine
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, firefox, hammer.js"
}
|
not being able to query BusinessHours in Case object
I have set up Business Hours in my org. A field called `BusinessHours` appears in the `Case` Standard field List. However as soon as I try to query using workbench, it throws an error
select BusinessHours,Id from case
> **INVALID_FIELD** : select BusinessHours,Id from case
Can anyone tell me where am I going wrong?
|
If you look at the documentation on `Case`, you will see that the actual field API Name is **`BusinessHoursId`** :
SELECT BusinessHoursId FROM Case
|
stackexchange-salesforce
|
{
"answer_score": 3,
"question_score": 1,
"tags": "soql, query, case, workbench, businesshours"
}
|
Barebones JVM environment
Need to setup a barebones environment to benchmark code with as little enviromental external system overhead as possible at runtime to get as stable reports overtime as possible. What is the best way to do this?
|
Your question is not clear because there are many variables which you may or may not be interested in.
One possibility is to install a brand new Windows or Linux system (if either of those OS's is relevant, or at least not detrimental to your goal), install only the JRE and your benchmark software, disconnect from the internet, and run your tests.
If you're looking to use a JVM on other systems, or you feel the official JRE is too cumbersome and will affect your results, you much wish to check out < \-- a JVM which is relatively easy to port to several arbitrary systems. Of course there are other similar portable alternatives.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "architecture, jvm, benchmarking"
}
|
Why isn't oil used for rockets?
Most people know that when you add oil to a fire, it grows rapidly and becomes more powerful. So, why isn't added into the propellant just before it comes out of the engine?
|
Because 'oil' is basically what most rockets already use for fuel.
To be a useful fuel you want a high energy density so your rocket is not lifting 'stuff' that does not burn, ideally both in terms of volume and mass (light fuel weight AND low tank weight). In the middle of this table from the Wikipedia page  chains with Kerosene, pretty close to the canonical rocket fuel as RP1 bang in the middle.
Natural Gas and Hydrogen are 'better' but depend on very good tank design to not end up with big and/or massive tanks eating the performance advantage.
|
stackexchange-space
|
{
"answer_score": 8,
"question_score": -3,
"tags": "rockets, engines, fuel, fire, green propellant"
}
|
create an array via loop
I need to create an array of strings, easy enough... the only problem is that the strings are integers from 1-1000 and I really dont want to type each of them.
Can you create a loop that could create this?
right now it looks like this
private readonly string[] _myArray = { "1", "2", "3", "4", "5" };
and its called by
for (var i = 0; i < _myArray.Length; i++)
{
arFoo[i].SetBar(_myArray[i]);
}
any suggestions on how to add the other 995 without manually typing them?
|
This is simple and clean:
readonly string[] _myArray
= Enumerable.Range(1, 1000)
.Select(i => i.ToString())
.ToArray();
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 2,
"tags": "c#, arrays, loops"
}
|
Netbeans 8.0 wrongly gives "Unknown HTML tag" warning
When using the elements `kbd` or `samp` in JavaDoc comments for Java 7 source code, Netbeans 8.0 flags these elements with a warning such as `Unknown HTML Tag: <kbd>`.
These elements are valid in HTML 4.1 (which is the format produced by the JavaDoc generator) and in the newer HTML5 specification, so Netbeans seems incorrect to declare them unknown.
Is there a way I can edit the list of HTML elements recognised by Netbeans 8.0?
(I am aware that this type of warning can be disabled in Netbeans, but I don't want to do this. I want to receive warnings about genuinely invalid markup, but in this case the markup is valid.)
|
It's a bug of netbeans 8.0. Someone as already filled a bug report for the elements `<s>` and `<strike>`. You can sign in to the netbeans bugzilla database and complete the bug report. Then you just have to wait and hope that it will be fixed in the next release.
The other possibility is to patch NetBeans but it could be a little bit difficult.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "java, html, netbeans, javadoc"
}
|
How to add a column default?
I created a Postgres DB which contains 5 tables. Then I realized that the column `student.student_id` lacks a column default to generate an _UUID_ :
CREATE TABLE student (
student_id UUID PRIMARY KEY,
first_name VARCHAR(100) NOT NULL,
last_name varchar(100) NOT NULL,
date_of_birth Date NOT NULL
)
Knowing that some tables are linked to the `student` table, how can I add to the function as column default for `student_id` so that the result will be:
student_id UUID PRIMARY KEY DEFAULT uuid_generate_v4()
|
Use `ALTER TABLE`:
ALTER TABLE student
ALTER COLUMN student_id SET DEFAULT uuid_generate_v4();
Column defaults do not conflict with `FOREIGN KEY` references.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "sql, postgresql, database design"
}
|
ActiveRecord inside the thread is too slow
I have a problem. I have serveral code blocks that has to work parallel and independent, but can have some connection dots like threadsafe queue. I'm not using rails, that is just a ruby script. But i'm using activerecord. And when I'm calling an activerecord model find in the main ruby thread it is ok and selects are taking about 0.3 ms. But if I call an activerecord model find inside a created thread like:
Thread.new do
3.times {
SomeModel.find(3)
}
end
It now takes 400 ms. Why does it happen and what to do, to low the request execution time?
|
I discivored that this is of ActiveRecord gets connection from a main thread, there it established the connection. Reestablishing connection in each thread does the trick. Another way is to override current_connection method in activerecord to share connection between the threads.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "ruby, multithreading, activerecord"
}
|
WPF Button what is the right Trigger for me?
I've been trying several properties but I can't seem to get the result I want. Currently, this is what's in my resource dictionary:
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="marker" Property="Fill" Value="Black" />
</Trigger>
<Trigger Property="IsFocused" Value="True">
<Setter TargetName="marker" Property="Fill" Value="Black" />
</Trigger>
Now whenever I click one of my buttons (there is 4), the marker object turns black. I move my mouse elsewhere and it's still black - so far so good. Now, however, if I click another control on my application, the button loses focus (naturally) and therefore the marker isn't black anymore!
How can this be prevented? I want the marker to stay black when I click the button and once the button loses focus the marker should still stay black until I click the next button.
|
It sounds more like you're looking for the kind of behaviour you'd get from ToggleButton, where the button is "checked" and "unchecked" by successive clicks.
Try swapping out your Button for a ToggleButton and adding a trigger for the IsChecked property rather than the properties you have now.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, .net, wpf"
}
|
Access SSDT without a database project
Is it possible to access the SQL Server Data Tools menu and features **without** having a database project? I want to compare two databases without creating or opening a database project.
|
The SQL Server menu has been moved under them main Tools menu in recent Visual Studio updates. You can use this to start a Schema Compare or Data Compare without opening a project:
!Schema Compare via the Tools menu
Alternatively go to View -> SQL Server Object Explorer, connect to your server from there, and right-clicking on any database will give you the same options:
!Schema Compare via SQL Server Object Explorer
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "sql, sql server data tools"
}
|
cut a string after a dot in R
All my column names start with
A.ABC.test1
A.ABC.test2
A.ABC.test3
A.ABC.test4
A.ABC.test5
I would like to keep only `test1` , `test2` ...
Any ideas?
|
simply do: (by chance the same as @jogo commented)
colNames <- c("A.ABC.test1","A.ABC.test2","A.ABC.test3","A.ABC.test4","A.ABC.test5")
sub(".*\\.","",colNames)
#[1] "test1" "test2" "test3" "test4" "test5"
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -3,
"tags": "r, character"
}
|
Talents during the time of Achasverous
The Megillah states that Haman gave 10,000 Talents of silver to King Achasverous.
What is the value of a talent of silver in their age and the value now?
|
Jewish Encyclopedia writes a heavy talent was 60 kilograms, a light talent 30 kilograms, and there's an opinion (very bottom) it is 20 kilograms. 10,000 talents would then be between 200-600 tons of silver.
At today's price of 500 USD/kilo of silver this would be between 100 and 300 million dollars.
The first three sources I found on this topic all concur with the range above (here, here and there).
|
stackexchange-judaism
|
{
"answer_score": 8,
"question_score": 6,
"tags": "money, purim, megillat esther"
}
|
Particular current divider
Consider this circuit:
!schematic
simulate this circuit - Schematic created using CircuitLab
(this part is preceeded and followed by other components).
$$I_1 + I_2 = \displaystyle \frac{V_1}{sL_{12}} - \frac{V_3}{sL_{12}} \left( \displaystyle \frac{L_1}{L_1 + L_2} \right)$$
with
$$L_{12} = L_1 || L_2 = \displaystyle \frac{L_1 L_2}{L_1 + L_2}$$
How can this relation be obtained? Any hint?
The ratio \$ \displaystyle \frac{L_1}{L_1 + L_2} \$ seems a voltage divider; but I can't see anything similar. Moreover, \$ L_1 \$ and \$ L_2 \$ are not parallel.
|
Just realize that \$\frac 1 {sL_{12}} (\frac {L_1} {L_1+L_2})=\frac 1 {sL_2}\$
|
stackexchange-electronics
|
{
"answer_score": 2,
"question_score": 1,
"tags": "circuit analysis, voltage divider, kirchhoffs laws"
}
|
Why did Snape claim that Tonks's Patronus looked weak?
Why did Snape claim that Tonks's Patronus looked weak in the 6th book? Did he know how she felt about Lupin? If so, how? Did he read her mind? And why did he say that given what his Patronus was?
|
He clearly recognized Tonks' patronus as Lupin, whom he disliked intensely. It's unclear whether he was merely sneering at the idea of Lupin being anyone's Patronus or was mocking Tonks herself for falling in love with a werewolf.
As for his own Patronus referencing Lily, I'm sure he'd be insulted at your insinuation that this could be even remotely comparable. (Lily == perfect, Lupin == weak. Makes perfect sense from Snape's view.)
Interestingly, when Harry witnesses the scene, he thinks Tonks' Patronus is Padfoot, but Snape's derision is just as believable.
|
stackexchange-scifi
|
{
"answer_score": 28,
"question_score": 13,
"tags": "harry potter, character motivation, severus snape"
}
|
How to do a foreach loop with multiple lists
I am trying to do a `foreach` loop that runs through 3 lists. Here is what I have currently:
foreach (Button btn in appList && sequenceLsit && FunctionList)
{
if (btn.FillColor != Color.White)
{
// Do stuff
}
}
I tried using tuples, but as I understand, they use a separate variable for each list. I need a single variable (btn) for all 3 lists.
|
A `foreach` loop enumerates one list. If you have three separate lists then you need to create one list from them first, which can then be enumerated. The simplest way to do that is the `Enumerable.Concat` extension method:
foreach (Button btn in appList.Concat(sequenceLsit).Concat(FunctionList))
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "c#, winforms"
}
|
Set SQL CLR assembly PERMISSION_SET in Visual Studio
Is it possible for me to have the deployment / scripts within Visual Studio generate my assembly with "PERMISSION_SET" set to "EXTERNAL_ACCESS" instead of "SAFE". I can obviously build the project and then modify the script, but I would like to have that be a setting so I can re-build then deploy to my Development instance.
Probably something I am looking over, but I can't seem to find where I could set that build property for the assembly creation.
Thanks,
S
|
If found the setting in Visual Studio. You can go to Project Properties -> Database here you select the Database to deploy to along with the Permission level of the CLR Assembly.
\--S
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "sql server, visual studio 2010, sql server 2008, sqlclr"
}
|
How to find the return type of a function in sybase?
How to find the return type of a function, for example getdate()? I guess it is a datetime, but how do I know that?
|
Apart from looking at the manual, you could do following:
select getdate() as d into datatype_debug
go
sp_help datatype_debug
go
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sybase, sap ase"
}
|
не работает массив в операторе IN
$ids = implode(',', $productsIds); //получается просто 2,3,4
$products = Product::find()
->where(['id'=>[$ids],'status'=>'1']) //так не работает(выводит только первый товар)
->all();
$products = Product::find()
->where(['id'=>[2,3,4],'status'=>'1']) //если просто подставлю числа , то все работает
->all();
В чем может быть причина?
|
Вы массив вкладываете строчку. Надо так:
->where(['id'=>$productsIds,'status'=>'1'])
Имплод уберите.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, yii2"
}
|
Accessing the settings (app.config) of the calling application
I have a WinForms application ("WF"), and a Library called by that WinForms application ("LIB")
WF has a Settings.settings (Visual Studio Designer) and app.config combo. I gather than the designer is a front end that auto generates the app.config file. To use those settings from within WF, I use the strongly typed properties of the class it autogenerates (i.e. WF.Settings.MyTimeOutSetting).
When WF calls a method in LIB, I want to use one of WF's settings from within lib. How can I retrieve a setting from the caller's (WF's) app.config while in the callee's (LIB's) code?
|
Like John said, this is a bad idea. The caller (exe in this case) should pass the needed information to the DLL. That way you can re-use the DLL later, somewhere else, and not have some 'invisible' dependency on an app.config setting.
Try this:
Dim oConfiguration As System.Configuration.Configuration
oConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
Dim sValue As String = oConfiguration.AppSettings.Settings("setting").Value
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": ".net, visual studio, settings, app config"
}
|
what is the translation for the word "intersection"? when used as an *operation* between volumes or lines. (not a road intersection)
intersection when used as an _operation_ or _volumetric operation_ between volumes or lines.
(not as a road intersection).
|
For the set theory operation, there are a few terms as given in this Wikipedia article), including:
*
*
*
*
*
*
Although the article points out that is also used to refer to the product of two sets, so is probably the preferred term. is also used for "in common" in other mathematical terms, e.g. if two triangles have the same height they might be referred to as .
As you can see in this page, the intersection of two or more 3D solids is referred to as , and you would have similar terms for intersections of areas and other mathematical constructs.
|
stackexchange-japanese
|
{
"answer_score": 0,
"question_score": 0,
"tags": "translation, multiple readings"
}
|
Ubuntu Software Center additional software plug-ins, official or third-party?
When getting software from the Ubuntu Software Center I often see that it says "Optional add-ons", like for instance here for `rkhunter` these are the Optional Add-ons it displays:
!rkhunter Optional Add-ons
Are these optional add-ons made by the developers of the software or at least approved by them? Or are these third-party add-ons? Or does it vary?
I am running Ubuntu 14.10.
|
If I were to make a guess, the "Optional Add-ons" are what would be called _Recommends_ or _Suggests_ dependencies. They are listed by the package maintainer of whichever package you're trying to install, but may or may not be developed by them or be approved by/known to the upstream developers.
And indeed it is so:
$ apt-cache depends rkhunter | grep -Ei 'recommends|suggests'
|Suggests: bsd-mailx
|Suggests: mailutils
|Suggests: heirloom-mailx
Suggests: <mailx>
Suggests: tripwire
Suggests: libdigest-whirlpool-perl
Suggests: liburi-perl
Suggests: libwww-perl
Suggests: powermgmt-base
|Recommends: <default-mta>
Recommends: <mail-transport-agent>
|Recommends: wget
|Recommends: curl
|Recommends: links
|Recommends: elinks
Recommends: lynx
Recommends: iproute
|Recommends: unhide.rb
Recommends: unhide
Recommends: lsof
|
stackexchange-askubuntu
|
{
"answer_score": 3,
"question_score": 1,
"tags": "software center, plugins"
}
|
Refer to a Class in a Style
I have a custom button implemented as an anchor. The button has an image and text.
When the button has focus, I would like to style it differently. Specifically, I would like to draw a dotted rectangle around the image and text. I would also would like to additionally style it based on another class.
Here's the button code:
<a id="searchButton" class="button" href="#">
<span class="icon-search"></span>
Search
</a>
Here's the CSS code with my questions:
button:focus {
/*How do I make a rectangular dotted line around the button text and icon? /*
/* How do I refer to another class that has additional stylings? */
}
|
You have "button" but it should be ".button" instead since your tag is not a button, but rather your class.
.button:focus {
outline: #00FF00 dotted thick;
}
In regards to the question, "How do I refer to another class that has additional stylings?", I believe you would need a library like SASS, LESS or some other dynamic stylesheet language because that type of functionality is not currently supported by CSS natively.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "css, focus"
}
|
Is A∩B has Maximum?
Consider $A=(0,1)∪\\{2\\}$ and $B=(0,1)∪\\{3\\}$. Both sets have maxima, $2$ and $3$ respectively. But $A∩B=(0,1)$ which has no maximum.
How can we say that $A∩B=(0,1)$ does not have any maximum. Wouldn't it be $1$ ?
|
$1$ is not a max, since the interval $(0,1)$ is open, this means, in particular that $1$ is not in the set. This set has no max, but it has an upper bound.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "real analysis, order theory, supremum and infimum"
}
|
Using the "default" login system for a new MVC application
I've just created my first ASP.NET MVC app. Since I didnt choose to create an empty project, visual studio generated some views for me, including a register user page.
But what tables would i need to create to make use of the register/login-functionality?
|
Use the `aspnet_regsql.exe` tool to create your membership database.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "c#, asp.net, asp.net mvc"
}
|
Getting Error 22 for dynamically naming a downloaded files using request from Python
So I'm trying to automate a daily download in jupyter and trying to name it adding the date and time of the download but I get this error 22:
OSError: [Errno 22] Invalid argument: 'C:\\Users\\Emilio\\Downloads\\BonosMX_2021-09-29_01:26:40_PM.xlsx'
This is what I'm trying:
import requests
from openpyxl import load_workbook
from datetime import datetime
from pathlib import Path
url='www.xyz.com/file.xyz'
r = requests.get(url, allow_redirects=True)
print(r.headers.get('content-type'))
fechaDes = datetime.now().strftime("_%Y-%m-%d_%I:%M:%S_%p")
path = r"C:\Users\Emilio\Downloads\BonosMX" + fechaDes + ".xlsx"
open(path, 'wb').write(r.content)
Thanks for the help!
|
Windows is quite fussy about what you can put into paths. Try this:
fechaDes = datetime.now().strftime("_%Y-%m-%d_%I-%M-%S_%p")
In general stick to `_` and `-` as separators... and be aware that windows _also_ has limits on path length which are quite easy to hit.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, request, file management"
}
|
How to properly format body for post request?
I'm using a firefox pluing called restclient to simulate a post request. It doesnt' seem to be picking up any post data, but not sure if I'm formatting it properly.
using header: Content-Type: application/json and body: {"id":1234}
but not go, it's not picking up the id parameter in my php, is there some special formatting I need to set?
|
okay, got it working, here is what is needed
two content types:
Content-Type: application/json
Content-Type: application/x-www-form-urlencoded
and then set your params like so in body:
param1=value1¶m2=value2
Thanks for the help everyone.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "php, jquery, json, rest, post"
}
|
Java to C# - CallableStatement convert
Hi I am trying to understand how to convert java code to C#, I read some tutorials about java but I dont find the way in how to translate this lines of code:
CallableStatement cstmt = con.prepareCall("?=CALL
cstmt.registerOutParameter(1, Types.JAVA_OBJECT);
cstmt.execute();
ResultSet rs = (ResultSet) cstmt.getObject(1);
I try with
CUBRIDConnection con = new CUBRIDConnection(ConnectionString);
CUBRIDCommand com = new CUBRIDCommand();
com.CommandType = CommandType.StoredProcedure;
com.Connection = con;
com.CommandText = "call mySP();";
com.Parameters.Add("?=p", CUBRIDDataType.CCI_U_TYPE_RESULTSET).Direction =
ParameterDirection.Output;
con.Open();
DbDataReader df = com.ExecuteReader(CommandBehavior.SingleResult);
//some stuff
con.Close();
This dont work, how can I translate it?
|
try this
SqlConnection con = new SqlConnection("your connection string");
SqlCommand com = new SqlCommand();
com.CommandType = CommandType.StoredProcedure;
com.Connection = con;
com.CommandText = "yourstoredprocedurename"; //no paranthesis or call key word just procedure name
SqlParameter parameter = new SqlParameter("yourparametername", SqlDbType.Binary); //just parameter name no questionmark
parameter.Direction= ParameterDirection.Output;
com.Parameters.Add(parameter);
con.Open();
var df = com.ExecuteReader(CommandBehavior.SingleResult);
//some stuff
con.Close();
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "c#, java, .net, cubrid"
}
|
pg_dump ignoring table sequence?
I have been playing around with PostgreSQL lately, and am having trouble understanding how to backup and restore a single table.
I used pgadmin3 to backup a single table in my database, in order to copy it to a different server. When I try to do a pg_restore on the file, I get error messages saying that the sequence does not exist:
pg_restore: [archiver (db)] could not execute query: ERROR: relation "businesses_id_seq" does not exist
Command was:
CREATE TABLE businesses (
id integer DEFAULT nextval('businesses_id_seq'::regclass) NOT NULL,
name character varyin...
It looks like the dump file did not include the sequence for my auto incrementing column. How do I get it to include that?
|
dumping by table only - will dump only the table. You need to dump the sequence separately in addition to the table.
If you dont know your sequence you can list it with `\d yourtable` in psql. You will see something in the row your sequence is on that looks like : `nextval('yourtable_id_seq'::regclass')`
Then from the command line, `pgdump -t yourtable_id_seq`
<
|
stackexchange-stackoverflow
|
{
"answer_score": 26,
"question_score": 19,
"tags": "postgresql, pg dump, pg restore"
}
|
After changing branch I lost my code from it
I know this is a bit newbie question. I have my frontend branch and backend branch. I wrote backend code on this one branch and when I switch tu frontend my code from backend is not visible. What sould I do, just merge them together?
Cheers
|
IF you want to view the back end code again switch back to the back end branch. In git, a branch has its own code the whole purpose of creating branches is to keep a separate copy for adding features or doing any change without affecting the master branch normally this is a
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "git, branch"
}
|
トランプのカードをすべて表示する方法
python
rm_card
from random import shuffle
class Card():
suits = ["spades", "hearts", "diamonds", "clubs"]
values = [None, None, "2", "3", "4", "5", "6", "7","8",
"9", "10", "Jack", "Queen", "King", "Ace"]
def __init__(self, value, suit):
self.value = value
self.suit = suit
def __repr__(self):
return self.values[self.value] + " of " + self.suits[self.suit]
class Deck():
def __init__(self):
self.cards = []
for i in range(2, 15):
for j in range(0, 4):
self.cards.append(Card(i, j))
shuffle(self.cards)
def rm_card(self):
if len(self.cards) == 0:
return
return self.cards.pop()
deck = Deck()
for card in deck.cards:
print(card)
|
(War Game) self_taught/python_ex280.py rm_card(deck )
|
stackexchange-ja_stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "python"
}
|
How to prevent size of UIScrollView after device orientation is changed?
!enter image description here
I have `UIScrollView` on xib-file on portrait mode. When I run the application and rotate device to landscape mode I see the new bounds of the `UIScrollView`. Half of the controls inside `UIScrollView` at the bottom are inaccessible. There is no any scroller visible.
How to prevent change of the vertical size of `UIScrollView` after device orientation is changed?
!enter image description here !enter image description here
Thanks a lot for the help!
|
1. Setup **Reference Outlet**.
2. Use the code:
scrollView.contentSize = CGSizeMake(width, height);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "iphone, ios, uiscrollview, orientation"
}
|
WebStorm debug mode for Meteor npm script
In WebStorm if I add run configuration as "Meteor" app then debugging works fine.
Recently we moved to use NPM script `npm start` to start our app. This helped us to reduce sending settings of WebStorm run config to other team members.
When I start NPM script in debug mode in WebStorm, then it doesn't hit the breakpoint. I want to know should I do some kind of change in 'run config' so that WebStorm knows that it should run Meteor debugger.
Here is my run script in package.json
{
"scripts": {
"start": "MONGO_URL=mongodb://localhost/db meteor --settings private/settings.json",
},
}
|
meteor can only be debugged via Meteor run configuration; there is no way to debug it through NPM script. You can specify environment variables and pass settings to Meteor right in your configuration
 to the native app using the emit(target,'data', 'the data') ; emit(target,'end'); as mentioned in the MDN documentation, it seems like the app recieves the message only once. If I try to again do emit(target,'data',..) ; emit(target,'end') , again .. it is not sent to the native app. I debugged it and looks like after we emit('end') , it removes some listeners and next time when emit() is called there is no registered listeners and it does not actually dispatch the event. Would really appreciate if some one could point me to what I am missing.
|
Emitting `end` likely closes the output stream or something to that effect, so simply don't emit `end` until you're actually done sending data for good.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "firefox addon, firefox addon sdk"
}
|
Shorten path name with initial letters for prompt
Can we have `~/a/very/long/path/name` shorten to `~/a/v/l/p/name` for zsh promt?
I saw my vim buffer display the path `~/.vim/plugged/YouCompleteMe/plugin/youcompleteme.vim` as `~/.v/p/Y/p/youcompleteme.vim` and wonder if we can do similarly for bash/zsh prompt. This will save some space for a small monitor like laptop.
|
I've found a solution using regex:
$ echo "~/a/very/long/path/name" | perl -pe 's/(\w)[^\/]+\//\1\//g'
~/a/v/l/p/name
$ export PS1='$(echo $PWD | perl -pe "s/(\w)[^\/]+\//\1\//g") '
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 2,
"tags": "path, zsh"
}
|
Divide by 2 and 9 php
Can you help me with this problem:
> Write a Boolean expression that checks for given integer if it can be divided (without remainder) by 9 and 2 in the same time. Example: Divided by 9 and 2: 17-false ; 0 - false; 10 -false; 7-false; 18 -true; 72-true
Is it correct logic of my code ?
<html>
<head></head>
<body>
<?php
if (72 % 9 == 0) {
if (72 % 2 == 0) {
}
echo 'True.';
}
else {
echo'False';
}
?>
</body>
|
Maybe you thought in the right way, but that code won't work I think. Use this:
if (72 % 2 == 0 && 72 % 9 == 0) {
echo "Correct";
} else {
echo "Incorrect";
}
You can also check if the number is divisible by 2 * 9.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -4,
"tags": "php"
}
|
Broken motherboard, bios failure
After some tests I have found that the BIOS is broken.
I have tried to make sure it is the BIOS that's broken. And after unplugging everything unnecessary the same result remains.
And now I would like to replace the broken motherboard with a new one without a direct reinstallation of the operative system. Is this possible?
On the hard drive windows 8.1 is installed and on the motherboard a AMD chip is found.
Is the installation on the hard drive possible to use again? Can the motherboard be upgraded without a reinstallation beeing necessarily?
|
Until now I have transferred HDDs with installed Windows 8.1 between different hardware platforms many time and without a single problem. Especially it is very smooth when you are exchanging the platform for the same one (Intel for Intel, AMD for AMD), but actually I have not experienced any issues until now whatsoever.
It was the era of Windows XP where changing the platform was a matter of luck, but with Windows 8.1 (even with Windows 7) I didn't have any issues... and I'm running my own computer service, meaning that things like this happens daily
Until now, I didn't have any issue with Windows 10 as well
And I am very grateful to Microsoft for this, as this saved my life (time and money)
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 1,
"tags": "windows 8.1, motherboard, hardware failure, chipset"
}
|
How do I quickly open or close a jammed zipper?
On occasion a zipper gets stuck in quite inconvenient situations. This may be when wearing a warm coat on entering an even warmer room, or most embarrasing while in a public restroom.
In both occasions I want the zipper to open or close as fast as possible but the more I pull the worse it appears to become. Also with trousers or coats visible control on what happened is limited if any.
Is there a way to safely and quickly resolve this?
|
I find this a common problem on metal teethed zips, not so much on plastic ones. Pulling the two sides of the zipper tight at the open end and keeping as much as the zipper as you can in a straight line usually solves any sticking issues, you might need to wobble the zip a little from side to size to release it, but don't directly pull it hard as you risk damaging the teeth can causing more problems.
For the really difficult ones, I find a graphite, a crayon the same colour as the material or a candle a good lubricant to loosen them up.
|
stackexchange-lifehacks
|
{
"answer_score": 5,
"question_score": 12,
"tags": "clothing"
}
|
Loading from string instead of document/url
I just found out about html agility pack and I tried it, but stumbled upon a problem. I couldn't find anything on the web so I am trying here.
Do you know how I can load the HTML from a string instead of document/URL?
Thanks.
|
Have you tried using **LoadHtml**?
string htmlString = 'Your html string here...';
HtmlAgilityPack.HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument();
htmlDocument.LoadHtml(htmlString);
// Do whatever with htmlDocument here
|
stackexchange-stackoverflow
|
{
"answer_score": 59,
"question_score": 25,
"tags": "c#, html agility pack"
}
|
Conditionally styling @font-face
I'm using @font-face for some headers.
The replaced typeface is different in dimension and overall character. When the switch happens, the old typeface's rules don't look so good.
Other than writing a conditional Javascript script, is there a way to have a set of CSS rules for @font-face fonts (if the browsers supports it) and CSS rules for the unreplaced default fonts?
|
There are no events that fire when this switch happens. So if you wanted to change line-height for instance, browsers don't give you any way to know when to do it.
However,
The new Google WebFont Loader provides CSS and javascript hooks so that you can change anything whenever that new @font-face font applies.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "css, font face"
}
|
Split string on spaces
I have a textarea where you can type in a message. After typing a '@', the messages should be splitted on spaces. After putting all the words into an array, I would like to search the array for words like this: `@person1`, `@person2`.
But the first part is already going wrong.
I tried it with the following code, but the array always seems to be empty.
$("textarea.autocomplete-pt").keypress(function(e) {
if (e.which == 64) {
var string = $(".autocomplete-pt").text(),
array = string.split(/ +/);
console.log(array);
}
});
What am I doing wrong?
Here is the jsfiddle
|
To read content of `input` and `textarea` you have to use `val()` instead of `text()`. Refer to jQuery documentation for further details but your code should be like this:
$("textarea.autocomplete-pt").keypress(function(e) {
if (e.which == 64) {
var string = $(".autocomplete-pt").val().trim();
var array = string.split(/\s+/);
console.log(array);
}
});
As Tushar already suggested in comments it's also better to use `\s+` instead of ` ` to match spaces because it also handles multiple spaces and _other kind of spaces_ (tabs, short and long spaces and so on, it's especially useful if users will paste text copied from another page or they have double/single width characters in Japanese).
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "javascript, jquery, ajax"
}
|
AWS postgres copying data from one database to the other daily?
I want to create an automated job that can copy the entire database to a different one, both are in AWS RDS Postgres, how can I do that?
Thanks.
|
I have had success in the past running a script that dumps data from one Postgres server and pipes it into another server. It was basically like this **pseudo-code** :
psql target-database -c "truncate foo"
pg_dump source-database --data-only --table=foo | psql target-database
The `pg_dump` command outputs normal SQL commands that can be piped into a receiving `psql` command, which then inserts the data.
To understand how this works, run `pg_dump` on one table and then take a look at the output. You'll need to tweak the command to get exactly what you want (eg using `--no-owner` to avoid sending access configurations).
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "postgresql, amazon web services, amazon rds"
}
|
How to switch between different datatemplates in listbox
I want to have different datatemplates within a single listbox. For example I need 3 listbox items with editbox, ckeckbox and textbox.
If I have only one template everything is ok, because I can declare ListBox.ItemTemplate with DataTemplate but I can't understand how to make different templates and how switch between them?
Thanks!
|
Look at Implementing Windows Phone 7 DataTemplateSelector and CustomDataTemplateSelector
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "windows phone 7, listbox, datatemplate"
}
|
Using bash's "source" command return error though it successfully read config file
I want my bash script to read parameters from config file. Here is what inside the script:
#!/bin/bash
source /home/myscript/conf/config.conf
echo "$username"
and below is my config.conf:
username="jonas"
The output when I run the script:
[user@machinename bin]$ . thescript
: No such file or directoryonfig.conf
: command not found
jonas
Here I am confused, though it successfully print "jonas", why is there error "No such file or directory" and "command not found"?
Am I doing something wrong?
|
As @Mat pointed out, `thescript` probably has Windows newlines (carriage return/CR followed by line feed aka. LF). Compare:
$ echo : No such file or directoryonfig.conf
: No such file or directoryonfig.conf
$ printf '/[.................]/conf/config.conf\r: No such file or directory\n'
: No such file or directoryonfig.conf
Use `dos2unix thescript` to fix it.
|
stackexchange-unix
|
{
"answer_score": 3,
"question_score": 1,
"tags": "bash, shell script"
}
|
Приложение React Native 0.63 не запускается на android 4.4
Ребят, привет! Делаю приложение для wonlex kt24. Там android 4.4, который kit kat , для этого поставил старую версию (0.63), где ещё была поддержка старого SDK. На эмуляторе самый стартовый проект запускается, а на часах даже не запускается, хотя apk ставится. Куда копать?
Изменение `targetSdkVersion` до 19 тоже ничего не дало.
|
Все было странно просто, не ставилась именно дебаг-версия, а релизная заработала без проблем:
npx react-native run-android --variant=release
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "react native"
}
|
How to handle Table row selected changed?
How to handle row selected changed event for a table using Blazor? I tried handling @onchange as well as @onselectionchange. The syntax for the table looks like this:
`<table class="table" @onchange="@this.SelectionChanged">`
|
Your event binding doesn't work because the `table` element does not emit `change` events.
Instead, you could add an input element (for example a checkbox) inside your table rows. You can then handle row selection changes by adding your event binding to the input elements.
Read more on the HTMLElement change event in this article.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "asp.net core, blazor"
}
|
How to download Unicode CLDR JSON data with cldr-data-downloader behind proxy server?
I would like to use cldr-data-downloader(< behind proxy server. The document says exec the command below.
enter code here$ npm install cldr-data-downloader
Using the CLI:
$ ./node_modules/cldr-data-downloader/bin/download.sh \
-i \
-o ./cldr
GET `
[========================================] 100% 0.0s
Received 3425K total.
Unpacking it into ./cldr
I can exec this command without error when I try it without proxy, but it cause error when I execute it from behind proxy server. I suspicious that I need to the proxy address to this application but I don't know how should I do it.
Does someone know how to do this?
|
I could solve the issue by myself. Solution is to set HTTP_PROXY value
on windows
set HTTP_PROXY =
on Linux
export HTTP_PROXY =
CLDR downloader check this value, but npm and bower checks different config files. in short, You have to set proxy value separately for npm, bower and CLDR downloader.(and gradle if you are using it)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "node.js, cldr"
}
|
Center ul but keep left-aligned
I created a simple page with Bootstrap and would like my ul to be center aligned on mobile but with the text left aligned. I tried setting text-align to left and the right and left margins to auto in my CSS file, but it isn't centered:

{
}
|
You can use `Buffer.BlockCopy` to do this very efficiently:
using System;
class Test
{
static double[,] ConvertMatrix(double[] flat, int m, int n)
{
if (flat.Length != m * n)
{
throw new ArgumentException("Invalid length");
}
double[,] ret = new double[m, n];
// BlockCopy uses byte lengths: a double is 8 bytes
Buffer.BlockCopy(flat, 0, ret, 0, flat.Length * sizeof(double));
return ret;
}
static void Main()
{
double[] d = { 2, 5, 3, 5, 1, 6 };
double[,] matrix = ConvertMatrix(d, 3, 2);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
Console.WriteLine("matrix[{0},{1}] = {2}", i, j, matrix[i, j]);
}
}
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 14,
"question_score": 8,
"tags": "c#"
}
|
How to add seconds to an string with ffmpeg timestamp format?
If the part in bold of this string are the seconds. 00:00:00: **00**.000
How could I add 10 seconds to all this string formats ?
00:00:00:00.000
00:00.000
00.000
The result should be:
00:00:00:10.000
00:10.000
10.000
|
Using `re.sub` with replacement function:
>>> import re
>>> strings = [
... '00:00:00:00.000',
... '00:00.000',
... '00.000',
... ]
>>> for s in strings:
... re.sub(r'\d+(?=\.\d+$)', lambda match: str(int(match.group()) + 10), s)
...
'00:00:00:10.000'
'00:10.000'
'10.000'
* `re.sub` accept not only the replacement string as the second parameter, but can also accept replacement function as the second parameter.
* The function receive matched object as the parameter. The return value of the function is used as a replacemnt string.
* `\d+(?=\.\d+$)` pattern is used to match last second part (which is followed by `.nnn` decimal part)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "python, regex, string"
}
|
Smtp Server default timeout
In case the destination mail server is temporarily down, how much time would my own mail server keep retrying sending the mail before giving up? I would love to know the default timeout value if it is mentioned in the RFC (which I could not figure out).
|
Sendmail documentation in `Message timeouts` sections references RFC1123
RFC1123
> **Requirements for Internet Hosts -- Application and Support**
> ...
> 5.3.1 SMTP Queueing Strategies
> ...
> 5.3.1.1 Sending Strategy
> ... Retries continue until the message is transmitted or the sender gives up; the give-up time generally needs to be at least 4-5 days. ...
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "email, smtp, sendmail"
}
|
How to make new virtual field In data class in Entity Framework
I have the following columns in my table
public partial class Address
{
public int AddressID { get; set; }
public string street { get; set; }
public string Town { get; set; }
public string PostCode { get; set; }
public string City { get; set; }
}
I want to make a new field by combining all other fields but I don't want the new field in the database.
public partial class Address
{
public int AddressID { get; set; }
public string street { get; set; }
public string Town { get; set; }
public string PostCode { get; set; }
public string City { get; set; }
Public String FullAddress =street+Town+PostCode+City; // the required new field
}
My question is how to properly code it?
Thanks
|
Just create a property without a `setter`:
public string FullAddress
{
get
{
return this.street + " " +
this.Town + " " +
this.PostCode + " " +
this.City;
}
}
Entity Framework will automatically detect that it's a getter-only property and will ignore it (as if it really was a `GetFullAddress()` method).
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#, entity framework"
}
|
color of first conour was changed after plotting second contour
My first contour is:
figure
x = -2:0.2:2;
y = -2:0.2:3;
[X,Y] = meshgrid(x,y);
Z = X.*exp(-X.^2-Y.^2);
contour(X,Y,Z,'LineWidth', 2)
;
Z = exp(-X.^2-Y.^2);
contour(X,Y,Z,'LineWidth', 2)
 I traversed till got to the Nth non-deleted element.
How can I do it? i thought to use side effect:
int i;
collectiom.Skip(Convert.ToInt32(startIndex))
.TakeWhile( x=>
{
++i != 0;
return (!x.IsDeleted)
})
.Take(N);
But the compiler refuses. And now I see it's not answering my need anyway
TIA
|
How about this:
var selected = collection.Select((x, i) => new {Item = x, Index = i})
.Skip(Convert.ToInt32(startIndex))
.Where(x => !x.Item.IsDeleted)
.Take(N);
The result is a sequence of `N` anonymous objects where `x.Item` is the original object, and `x.Index` is its index in the original collection. If you want to start counting the original collection from `startIndex` just swap the `Select` and `Skip` calls.
You can then get the number you want like so:
var numberProcessed = selected.Last().Index + 1;
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "c#, .net, linq"
}
|
Does the free shipping normally method remove all others?
If free shipping is available, all other methods disappear in my shop.
Is this standard functionality (otherwise I might have to search for a custom modification)?
If it is standard, where in the code does that happen? The goal is to have some shipping methods still appear, even if free shipping is available.
|
This is not a standard functionality.
Free shipping should appear along with other methods.
Maybe you have a minimum order value (0.01 or something like that) set for your other shipping methods in order to be available.
Or maybe there is indeed some custom code, that removes all the other methods when free shipping is available.
|
stackexchange-magento
|
{
"answer_score": 5,
"question_score": 3,
"tags": "shipping, ee 1.13"
}
|
Push into Firebase with unique ID
I'm building my first iOS app and I'm using Firebase as my backend.
I'm trying to store an array into my Firebase backend like so:
Firebase* f = [[Firebase alloc] initWithUrl:@"
[f setValue:@{@"UNIQUE OBJECT ID HERE": @{@"meh": @"lol", @"hum": @"kek"}}];
It works as expected, but I need to have an unique id for each "object". Right now, every time that method runs Firebase just replaces the old data with the new one.
Coming from a web dev background, I know that in JavaScript I would do this:
var ref = new Firebase("
ref.push({meh: "lol", hum: "kek")};
Which yields the expected result, since it gives the object above a name of "-IuxeSuSiNy6xiahCXa0".
How do I accomplish this in ObjC?
|
Firebase has build in system in Objective-C as well, but the syntax is a touch different.
Firebase * ref;
Firebase * autoId = [ref childByAutoId];
This:
Firebase* f = [[Firebase alloc] initWithUrl:@"
[f setValue:@{@"UNIQUE OBJECT ID HERE": @{@"meh": @"lol", @"hum": @"kek"}}];
Should be:
Firebase* f = [[Firebase alloc] initWithUrl:@"
[[f childByAutoId] setValue:@{@"meh": @"lol", @"hum": @"kek"}}];
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "ios, objective c, firebase"
}
|
Matlab figures lagging
Last week, Matlab crashed on my computer and gave a message regarding the figure driver or engine being changed (unfortunately, I do not remember exactly what it said). Ever since then, all of my figures have been extremely laggy and have appeared to have a lower resolution.
Has anyone run into this or have any troubleshooting advice?
|
I was able to solve this by creating a startup.m file in my MATLAB directory (located in Documents in my case). This file is called every time MATLAB is initialized. In this file I typed: `opengl('save','hardware')`. After staring MATLAB once with this startup.m file, I was able to delete this line of code from that file (this command changes opengl permanently, unless it is manually changed back).
Alternatively, I could have typed `opengl hardware` into the startup.m file. In this case this line of code would need to be left in the startup file.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "matlab, matlab figure"
}
|
Unresolved Proxy error when installing Xtext Plugin
When exporting my Xtext-Plugin as a deployable feature, I can install it in another Eclipse IDE, but whenever I open a file `test.mydsl` I get this error-message:
java.lang.IllegalStateException: Unresolved proxy Make sure the EPackage has been registered.
I read somewhere that a possible cause could be the `plugin.xml` and `plugin.xml_gen` files being out-of-sync, but this is not the case here...
Btw I am using `Xtext 2.11`
|
Make sure that you don't have any warnings or errors in your projects build.properties so that everything can get packaged properly
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "xtext"
}
|
how to know the number of feeds in an url in android
in my app in have an edit box when the user types a web address it goes on and i want to calculate the number of feeds and data of the feeds in that url.
how to do this. Please help me friends
|
You would have to parse the XML and count for how many elements where returned.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, url, feed"
}
|
windows service for data insertion
I have created windows service for data-insertion.Time interval is one min.After one min, data insert into table.Data get inserted into table at multiple time.I don't want to that,only one time.How to do that?May I need to check in database wether entry is there or nor if not add.
|
You can use this query before inserting the data.
IF EXISTS(SELECT * FROM dbo.YourTable WHERE Name = @Name)
RETURN
\-- here, after the check, do the INSERT You might also want to create a UNIQUE INDEX on your Name column to make sure no two rows with the same value exist:
CREATE UNIQUE NONCLUSTERED INDEX UIX_Name
ON dbo.YourTable(Name)
Hope this help you.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "asp.net"
}
|
UIImageView+AFNetworking get UIImage for URL
I am using `UIImageView+AFNetworking` and am wondering if there is a way to get the `UIImage` from the cache? It seems like there should be a method to return the `UIImage` based on the URL.
Possible?
|
AFNetworking already caches images automatically (and doesn't expose the cache publicly). You should just be able to request from a URL and it'll either come from the cache or it will get cached when it's downloaded from the remote website.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ios, objective c, afnetworking, nscache"
}
|
Delphi global variable setter
I got problem with setting global variable in Delphi unit:
unit SomeUnit;
...
interface
...
var
variable1: String;
...
implementation
procedure TSomeForm.SetNewVersion(variable1: String);
begin
variable1 := variable1; //here is problem
end;
How to assign value to global variable if it have same name like local argument value from procedure? If that is some form value, that can be done like this:
TSomeForm.variable1 = variable1;
But problem is when variable is global variable in unit?
SomeUnit.variable1 = variable1; // this dont work
|
FWIW: The following works as one might expect:
var
SomeForm: TSomeForm;
variable1: string;
implementation
{$R *.dfm}
{ TSomeForm }
procedure TSomeForm.FormCreate(Sender: TObject);
begin
Assert(SomeUnit.variable1 = '');
SetNewVersion('1');
Assert(SomeUnit.variable1 = '1');
end;
procedure TSomeForm.SetNewVersion(variable1: string);
begin
SomeUnit.variable1 := variable1;
end;
To avoid such problems you might consider prefixing arguments with 'A' which is kind of semi-standard in Delphi. And while you're at it, make string parameters `const`:
procedure TSomeForm.SetNewVersion(const AVariable1: string);
begin
variable1 := AVariable1;
end;
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": -2,
"tags": "delphi, variables, global"
}
|
Word for a lucky object?
What is the word for a lucky object, a thing you hold in your hand for good luck? Perhaps a stone. A small object that represents good fortune. I think it begins with _tal-_
Like a necklaces of a Hawaiian God (like in that Partridge Family TV episode.) You might even rub it or keep it in your pocket when you go to Vegas.
|
You're thinking of a talisman
> A talisman is an object which is believed to contain certain magical or sacramental properties which would provide good luck for the possessor or possibly offer protection from evil or harm
|
stackexchange-english
|
{
"answer_score": 3,
"question_score": 1,
"tags": "single word requests"
}
|
Build own "SDK" to put in other 3rd application
I have to create "`library`" that allow other developers use it in their applications. My library will be simple -
Developers will call our lib's api f.e. create button (pre-defined in our lib) and add to his subview.
**What is the best way to create this kind of lib? Should it be "static" library or something else?**
Thanks
|
A static library is probably the best way to go. You _can't_ use dynamic library loading on iOS (unless you're Apple).
Static libraries are pretty easy to create these days. There's a target you can use in Xcode and, basically, you just put the right files in it. It used to be much harder.
If you're not willing to share your code it might be the only option. If you _are_ willing to share your code, you can just distribute the files and instructions of which need adding to other projects. It still might be nicer to make a library available.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "iphone, ios, static libraries"
}
|
Add two density curves (from separate tables) into same plot (using ggplot in R)
I have two tables mresm, mresf with a numeric column Total in both tables (different values). Plotting a density plot for either of the two in R can be done in the following way:
> mresm %>% ggplot(aes(x = mresm$Total)) + geom_density()
> mresf %>% ggplot(aes(x = mresf$Total)) + geom_density()
However, I want to add both the resulting curves on the same plot to be able to compare them. Have tried a lot of alternatives with no success. Please help!
|
You could specify inside `geom_density` the `data` and `aes` arguments:
ggplot() +
geom_density(data = mresm , aes(x = Total))+
geom_density(data = mres , aes(x = Total))
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "r, ggplot2"
}
|
Python imports
Добрый день!
Используя конструкцию вида:
from a import *
Но не используя все классы/функции и т.п. из `a`, можно ли сказать, что это влияет на скорость работы программы, на количество требующейся памяти? Или для python это не страшно?
|
Используя конструкцию `from smth import *`, если у вас там действительно очень много объектов и суб-объектов, повлияет на время выполнения - интерпретатор будет бегать по файлам выискивая все "зависимости" и создавая ссылки на объекты.
Для того, чтобы точно определить список импортируемых объектов и не допустить "каскадного импорта до упора", существует директива `__all__`
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 3,
"question_score": 17,
"tags": "python"
}
|
Using Javascript, How to get number of items of radio button with the same id in html
Using Javascript, How to get number of items of radio button with the same id in html;
I am aware if I can wrap a form on top of the radio button I can get the length like
document.formname.radiobtnobj.length;
Wondering if is there a way I can get the number of items if I do not have a parent form to that control.
|
All IDs must be unique. Duplicating IDs is BAD HTML.
That being said, one way to do what you intend is to give all of the radio buttons a class name, and get all of the items that share that class name.
In forms we usually group radio buttons by giving them the same NAME, not ID. In this case, the elements are an array.
var myRadioButtons = document.forms[0].yourRadioButtonName // this gives you back your array.
alert(myRadioButtons[0].value)
alert(myRadioButtons[0].checked)
alert(myRadioButtons.length)
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 1,
"tags": "javascript"
}
|
SaxonJS - xslt3 - ObjectNotFound: (xslt3:String) [], CommandNotFoundException
I would like to transform XML File with Stylesheet XSLT with Saxon JS.
I did: npm install saxon-js npm install xslt3
Next Step is: xslt3 -xsl:xslt_filepath.xslt -export:books.sef.json -nogo
I am getting error
xslt3 : Die Benennung "xslt3" wurde nicht als Name eines Cmdlet, einer Funktion, einer Skriptdatei oder eines ausführbaren Programms erkannt. Überprüfen Sie die Schreibweise
des Namens, oder ob der Pfad korrekt ist (sofern enthalten), und wiederholen Sie den Vorgang.
In Zeile:1 Zeichen:1
+ xslt3
+
+ CategoryInfo : ObjectNotFound: (xslt3:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
packet.json has
"xslt3": "^2.0.2",
"saxon-js": "^2.0.2",
what could be a problem?
i have same error on my Windows 10 PC, and on windows 10 Laptop
|
Try installing with the `-g` (global) option on the `npm` command.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "saxon, saxon js"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.