INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Possible to execute ForEach-Object commands in Parallel
I have been attempting to execute parallel commands on data (such as a list of Server Names) that is imported via CSV and called by `ForEach-Object`. I have found that foreach has a parallel method but it appears that `ForEach-Object` does not. I am concerned about good performance as I hit multiple servers to read log data, and have the following options:
1) PowerShell Workflow
2) PowerShell Background Job
3) Invoke-Command
When I tried option 3, it failed as I tried to send arguments via -ArgumentList, but it didn't seem to like the variables I was pushing from the CSV in the form of:
$($_.'CSVColumnValue')
Is it possible to execute commands in parallel using `ForEach-Object`, and if so, what is the recommended method to achieve this? | There is no such thing as 'ForEach-Object -Parallel' since it is performed in the pipeline. Check Erik Meijer and Jeffrey Snover at MSDN Channel 9; those folks are gettin' nitty-gritty on the pipeline of PowerShell. It's a vid from 2008, lasts over an hour, but still... excellent on how the pipeline works.
The 'ForEach -Parallel' is a construct and not a pipeline cmdlet. It is part of the Workflow.aspx) module and introduced in Windows PowerShell 3.0.
Compare:
$Items = 1..42
ForEach -Parallel ($Item in $Items) {
$Item
}
With:
1..42 | ForEach-Object -Process { $_ } | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "powershell"
} |
How to Call Client-Side Code Before Server-Side Event?
<asp:RadioButtonList ID="rbEmployeeGroup" runat="server" RepeatDirection="Horizontal"
AutoPostBack="true" OnSelectedIndexChanged=" [Call java script to check first] then rbEmployeeGroup_SelectedIndexChanged">
<asp:ListItem Selected="True" Text="Employees" Value="employees"></asp:ListItem>
<asp:ListItem Text="Groups" Value="groups"></asp:ListItem>
</asp:RadioButtonList>
How to call the javascript function before call rbEmployeeGroup_SelectedIndexChanged this code behind function? | I figured out. Just add the onClientClick = "..." | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "c#, asp.net, javascript"
} |
Log doesn't save to file in docker environment
In my production environment `production.rb`. I have configured my log will be saved to file:
config.logger = Logger.new('log/production.log')
When I run locally (start server by using command line `rails s -e production`). everything works fine. But when I run on docker environment, I don't see `production.log` printed out.
Please help me about this problem. | > I don't see production.log printed out.
Where are you looking? On your host or in the docker container that you are running?
By default, the file will be created in your container filesystem.
If you want it directly visible from your host (which runs the docker daemon), you would need to mount an host directory as a data volume first.
docker run -d -P --name myapp -v /a/local/host/path:/path/to/log/in/container myimage
Then you would see `production.log` in `/a/local/host/path`. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "ruby on rails, logging, docker"
} |
Gloomhaven - movement dance to gain momentum
The Brute in our party has an attack that is based on movement. Using 4 movement, does using 4 Move to back out of their hex and back into it 2x count as moving 4 spaces? | If they moved 4 spaces then it counts as four. Where they end is irrelevent.
From the rules on moving :-
> A “Move X” ability allows a character to move up to X number of hexes on the map. Figures (characters and monsters) can move through allies, but cannot move through enemies or obstacles. Traps and other terrain effects of hexes must be resolved when a figure enters them with normal movement. A figure cannot end its movement in the same hex as another figure. Figures can never move through walls.
Note what it doesn't say. There is nothing to prohibit finishing in the same space. There is nothing to prohibit moving back and forth between two spaces. For some attacks and items where number of spaces moved is taken into account then this is a valid tactic.
There is also This question asked on BGG. The designer gave a thumb up to answer confirming a player can finish a move where they started. | stackexchange-boardgames | {
"answer_score": 8,
"question_score": 4,
"tags": "gloomhaven"
} |
How to find out if variable value in database json column Codeigniter?
Im using Codeigniter. Im trying to get some value in database like;
$this->db->where('json_value','test1');
the problem is 'json_value' column is like = `[{"name":"test1","value":"test1"},{"name":"test2","value":"test2"}]`
how can I get 'test1' if 'json_value' has? | You can use LIKE in your query
$this->db->like('json_value', 'test1', 'both');
For more information read the CI3 documentation. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, mysql, sql, json, codeigniter"
} |
localhost infinitely loading nodejs
I am starting to learn Node.js and as the first step I am deploying my server using `node.js`
This is my code:
const express = require("express");
const { readFile } = require("fs/promises");
const app = express();
app.get('/', (request, response) => {
readFile('./home.html', 'utf8', (err, html) => {
if(err){
response.status(500).send("Sorry, we are out of order");
}
response.send(html);
})
})
app.listen(3000, () => console.log(`App available on
But the when i click that link, the localhost seems to be loading infintely.I have tried with different ports.I am using powershell for this and not a WSL.What seems to be the problem here? | Try to use `node` `path` `module`, and put your `html` file into **root directory**. It works like a charm.
const express = require("express");
const path = require("path");
// const { readFile } = require("fs/promises");
const app = express();
// app.get("/", (request, response) => {
// readFile("./home.html", "utf8", (err, html) => {
// if (!err) {
// response.status(500).send("Sorry, we are out of order");
// }
// response.send(html);
// });
// });
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname, "/home.html"));
});
app.listen(3000, () => console.log(`App available on | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "node.js, express"
} |
PowerBI dataset and Excel on Mac OS
I want to provide access to data from a DataWareHouse to several users of my company. I need to create a dataset with filtered data and then I want to provide to granted users access to those data inside Excel on Mac Os. I don't know if this is possible as the feature "Analyze on Excel" is not available for download on Mac Os. Any ideas? | Connection to the Power BI datasets via Power Query, can't be done on Excel for MacOS as it is not supported. Power Query for MacOS Excel is limited to csv, json and d few others. Power Pivot for MacOS isn't available.
You can connect to OLAP sources like SQL Server Tabular using this paid for option, but only for On-premise SSAS, or Azure Analysis Service. If you have Power BI Premium, the CDATA plugin might be able to connect to the xmla endpoint of the dataset.
The other option is create the filtered data model with PBI Desktop on Windows and deploy it to the service, then to give them access to the Power BI Service. The user can then create their own reports, or export the data via csv, but the export size it limited to 100,000 rows.
For Mac users Power BI is mostly limited to viewing/creating the reports in the service. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "excel, macos, powerbi"
} |
String-split to keep comma in string
I have following code to split a string to a list:
(define ss "1, 2, 3, \"Hi, John\", 5, 6")
(string-split ss ",")
However, it splits the string `"Hi, John"` also since that contains the delimiter:
'("1" " 2" " 3" " \"Hi" " John\"" " 5" " 6")
How can I make it keep `"Hi, John"` together? Do I need to use regex for this? | Use the package `csv-reading` by Neil van Dyke. It's great!
< | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "scheme, racket"
} |
Use paste command with dplyr
I am trying to use paste command in order to paste some part of string into command group_by from dyplyr. This how is look like code normally without paste.
library(dplyr)
DATA1<-DATA%>%
dplyr::group_by(id_n,gross_income)%>%
dplyr::summarize(gross_i=sum(gross_i)
So now I want to use paste command, and I try with this line of code.
query_type1<-"id_n,gross_income"
Next step is to implement this line of code in code above.
DATA1<-DATA%>%
dplyr::group_by(query_type1)%>%
dplyr::summarize(gross_i=sum(gross_i)
But unfortunately this don't give me good result. So can anybody help me how to fix this line of code? | As others have already suggested have column names as vector instead of one comma-separated string.
query_type1<- c("id_n","gross_income")
You can then use `across` in `group_by` :
library(dplyr)
DATA%>%
group_by(across(query_type1)) %>%
summarize(gross_i=sum(gross_i) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "r, dplyr"
} |
updating prior rows of dataframe conditionally upon current
I have a dataframe (`ev`), and I would like to read it and whenever the value of the 'trig' column is 64, I need to update the value of the `critical` column that is 4 rows above, and change it to 999. I tried the code below but it does not change anything, though seems it should work.
for i in range(0,len(ev)):
if ev['trig'][i] == 64:
ev['critical'][i-4] == 999 | Try this, you were close: Learn about single `"="` vs double `"=="`
for i in range(0,len(ev)):
if ev['trig'][i] == 64:
ev['critical'][i-4] = 999 | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "python, pandas, dataframe"
} |
What is a term for a genre that is not sci-fi or fantasy?
I need a term to distinguish movies such as _Die Hard_ or _Taken_ from the likes of _The Lord of the Rings_ or _Minority Report_. Broadly speaking, they are all action movies. But what do I say when I want to exclude genres like sci-fi, fantasy and superhero? What would I call a movie set in the real world with human characters, one which doesn’t include mythical or superhuman characters or settings? | Head on over to your local video store, and you'll see the typical groupings for movie genres. Generally, though, these types of movies belong in the Action genre.
Many movies cross over the boundaries of genre. Taken, for example, is classed as Action/Crime/Thriller. Die Hard is classed as Action/Thriller. Minority Report is classed as Action/Mystery/Sci-Fi. LOTR is Action/Adventure/Fantasy. Given the broad sweep of genres covering Action, I would suggest non-Sci-Fi Action.
For some great definitions of movie genres and sub-genres, you should check out filmsite.org. They have a great listing of genres, sub-genres and hybrids. | stackexchange-english | {
"answer_score": 4,
"question_score": 2,
"tags": "word choice"
} |
Cannot get ffmpeg to work after installing from homebrew
I installed ffmpeg through homebrew but when I try to run it, even just typing in `ffmpeg` I get the following error message:
dyld: Library not loaded: /usr/local/lib/liblzma.5.dylib
Referenced from: /usr/local/bin/ffmpeg
Reason: Incompatible library version: ffmpeg requires version 8.0.0 or later, but liblzma.5.dylib provides version 6.0.0
Trace/BPT trap: 5
I've tried running `brew update` and `brew upgrade` but that didn't change anything. Running `brew doctor` the only error I get is:
Warning: You have a curlrc file
If you have trouble downloading packages with Homebrew, then maybe this
is the problem? If the following command doesn't work, then try removing
your curlrc:
curl
New at doing things in the terminal, what to do next? | I got it to work by running `brew search liblzma` which told me `lzma is now part of the xz formula.`
So then I ran `brew install xz` and tried running `ffmpeg` again and it works now! | stackexchange-stackoverflow | {
"answer_score": 37,
"question_score": 15,
"tags": "shell, ffmpeg, homebrew"
} |
Can i execute a single query on 2 database?
I am using php and mysql.
i have a question, lets say, I have a userid column in users table under database A, and userid column in purchases table under database B.
Can I execute a single query, using innerjoin, to get value from 2 databases? Or I must use multiple queries?
Oh ya, if let say, i have this variable:
$conn // connect to database A
Can i create another variable to connect database B before mysql_close()??
Sorry for multiple questions here ;p | SELECT * FROM database1.table1 t1, database2.table2 t2 WHERE t1.id = t2.id
from MySQL documentation
> You can refer to a table within the default database as tbl_name, or as db_name.tbl_name to specify a database explicitly. You can refer to a column as col_name, tbl_name.col_name, or db_name.tbl_name.col_name. You need not specify a tbl_name or db_name.tbl_name prefix for a column reference unless the reference would be ambiguous. See Section 8.2.1, “Identifier Qualifiers”, for examples of ambiguity that require the more explicit column reference forms. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql, database"
} |
Joint Distribution of n Poisson Random Variables
Let $x_1,x_2,\dots,x_n$ be a set of independent and identically distributed random variables with distribution Poisson with parameter λ. Write the joint distribution of all those random variables. Simplify as much as possible your final answer and show work.
So I think that the joint probability of independent random variables is the product of all individual probability distribution function, but I don't actually understand how to implement that in this case, since it's for $n$ variables. | The pdf of the Poisson distribution is
$$p(k) = \frac{\lambda ^k}{k!} \exp(-\lambda)$$
The joint pdf is the product of the pdfs of all $n$ independent variables $x_i$. Which is given by
$$p_n = p(x_1,x_2,...,x_n) =\prod _{i=1}^n p(x_i) $$
which can be siplified to
$$p_n = \lambda^{\sum _{i=1}^n x_i}\exp(- n \lambda)\; \prod_{i=1}^n \frac{1}{x_i !}$$ | stackexchange-math | {
"answer_score": 4,
"question_score": 4,
"tags": "probability, statistics, poisson distribution"
} |
Is there an API or a simple way to check if a volume is deduped on Windows server 2012?
Here's the MSDN page about Data deduplication API, and it seems there's no API to check if a volume is deduped.
One way to do it is to check if there's a folder named "Dedup" under "System Volume Information", but I don't think it is reliable for every case. | The list of deduped volumes can be obtained in powershell. See the following link about a third of the way down the page
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "c++, windows, windows server 2012"
} |
Sending multiple mails from a single method in ActionMailer
I have a simple mailer
class ApplyMailer < ActionMailer::Base
def inform_teacher
end
def inform_division
end
def inform_everyone
inform_teacher.deliver
inform_division.deliver
end
end
Calling `inform_teacher` and `inform_division` everything works well. But when I try to call `inform_everyone` just one blank email arrives.
Is it possible to combine multiple email method though one method? | Found solution to this:
class ApplyMailer < ActionMailer::Base
def inform_teacher
end
def inform_division
end
def self.inform_everyone
ApplyMailer.inform_teacher.deliver
ApplyMailer.inform_division.deliver
end
end | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ruby on rails, email, actionmailer"
} |
When inheriting from a base class, what happens with nested classes?
Say I have these classes:
class Base
{
public:
class Foo { ... };
...
};
Then another class derives from the base:
class Derived : public Base
{
// no mention or redefinition of nested class "Foo" anywhere in "Derived"
};
Does this mean we now have a distinct `Derived::Foo`, or is `Derived::Foo` the exact same as `Base::Foo`?
Here is a twist on this scenario: what if someone throws an instance of `Derived::Foo`? Would it be caught in this scenario:
catch ( const Base::Foo &ex )
{
// would this also catch an instance of Derived::Foo?
} | `Derived::Foo` is just accessing `Base::Foo`, therefore these are just two ways to refer to the same type. You can easily check it with `std::is_same`:
#include <type_traits>
struct Base
{
class Foo {};
};
struct Derived : Base {};
static_assert( std::is_same< Base::Foo, Derived::Foo >::value, "Oops" );
int main()
{
try {
throw Derived::Foo();
}
catch( const Base::Foo& ) {}
}
As you can see, this also means throwing it by one name and catching it by the other works as well.
**Live example** | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 14,
"tags": "c++, inheritance, try catch, nested class"
} |
Assembly.Load() or Not?
we have a very old windows program which developed with c# and with every new publishment the customers need to reinstall the program's new version. I wonder that if it's possible.
1. I will store all classes into txt files
2. When program starts to run, my dispatcher class will search for related txt file and it will create the form/class with Assembly.Load on the fly.
3. Let's assume if I change something in X form, I will only revise the text file related to X form and overwrite it.
Is this possible? | Why txt files, you mean in source code form? Assembly.Load() is not a compiler.
This is not Java. You do not compile classes into *.class files (binary files). An aggregate of C# classes are compiled into dll (a binary file). Assembly.Load() only loads .NET dll.
So not possible to use Assembly.Load() directly with text files. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c#, reflection, .net assembly"
} |
Evaluating a limit algebraically
$$\lim _{ x\rightarrow 4 }{ \frac { (\sqrt { 5-x } )-1 }{ 2-\sqrt { x } } } $$
Steps I took:
$$\lim _{ x\rightarrow 4 }{ \frac { (\sqrt { 5-x } )-1 }{ 2-\sqrt { x } } } \cdot \frac { (\sqrt { 5-x } )+1 }{ (\sqrt { 5-x } )+1 } $$
$$\lim _{ x\rightarrow 4 }{ \frac { 5-x-1 }{ (2-\sqrt { x } )(\sqrt { 5-x } +1) } } =\frac { -x+4 }{ 2\sqrt { 5-x } +2-\sqrt { x } \sqrt { 5-x } -\sqrt { x } } $$
At this point I don't know how else to manipulate it in order to get it to a form in which I could evaluate the limit. I would like hints rather than a direct answer. | From the step $$\lim _{ x\rightarrow 4 }{ \frac { 5-x-1 }{ (2-\sqrt { x } )(\sqrt { 5-x } +1) } } = \lim _{ x\rightarrow 4 }{ \frac { 4-x }{ (2-\sqrt { x } )(\sqrt { 5-x } +1) } }$$ Factor $$4-x=(2-\sqrt{x})(2+\sqrt{x})$$ then, $$\lim _{ x\rightarrow 4 }{ \frac { 4-x }{ (2-\sqrt { x } )(\sqrt { 5-x } +1) } }=\lim _{ x\rightarrow 4 }{ \frac { 2+\sqrt{x} }{ (\sqrt { 5-x } +1) } }=\frac{4}{2}=2.$$ | stackexchange-math | {
"answer_score": 3,
"question_score": 0,
"tags": "calculus"
} |
Force excel to refresh command ribbon (for office add-in) after updating manifest XML
I'm sideloading an office add-in using office.js and an XML manifest located on a share drive. This adds a new ribbon to excel with a few custom command icons once the add-in is loaded.
However, **after editing the manifest.XML file, say I comment out a command icon from the ribbon, I have not figured out how to force a refresh of the excel ribbon to reflect my changes.**
**I've tried** reloading the add-in, re-adding it, restarting excel, updating the manifest version when saving, changing the manifest Id/GUID when saving, etc, but still have not been able to find a way to consistently update the ribbon immediately after making changes. It seems to just be loading a cached version of my manifest file. Any ideas?
**I'm on** Windows 10 using Excel 2016. | I figured out that it wasn't the ribbon that was caching old icons, it was actually the Office Add-ins window that was caching the old manifest files.
If you go to Insert -> My Add-ins -> Shared Folder there is a refresh button in the top right corner which will refresh the manifest files to their latest changes.
 a good sign, although the presence of low levels of duplicates may not always be cause for alarm.
>
> Damaged packets are obviously serious cause for alarm and often indicate broken hardware somewhere in the ping packet's path (in the network or in the hosts).
There are different reasons for this, did you capture your network traffic with an interface in promiscous mode? Sometimes this is the reason for dupplicated packets. | stackexchange-unix | {
"answer_score": 62,
"question_score": 77,
"tags": "ping"
} |
Showing a variable converges in probability
I have a random variable
$Y_n$ with probability density function $f_{Y_n}(y) = \frac{n}{\theta}\left(1- \frac{y}{\theta}\right)^{n-1}$ for $0 < y < \theta$ and $n$ is a positive integer.
To show $Y$ converges to $0$ in probability, I consider
$\mathbb{P}(|Y_n - 0| > \varepsilon)$ and show for large $n$, this equals to zero.
The thing is, how would I get rid of the absolute value sign?
For context, $Y_n$ is the minimum of $(X_k)$ for $k= 1,2,3,\cdots,n$ and $X_i$ follows the distribution $U(0,\theta)$.
The solution just simply took away the absolute value signs, but why? | Note that $\theta\ge Y_n\ge 0$ so the absolute value sign can be removed.
**EDITED**
For any $\varepsilon>0$, the probability that $Y_n>\varepsilon$ can be calculated based on the pdf belonging to $Y_n$: $$P(Y_n>\varepsilon)=\frac n{\theta}\int_{\varepsilon}^{\theta}\left(1-\frac{y}{\theta}\right)^{n-1}\ dy=-\left[\left(1-\frac{y}{\theta}\right)^{n}\right]_{\varepsilon}^{\theta}=\left(1-\frac{\varepsilon}{\theta}\right)^n.$$
For any $\theta$ ($\theta>\varepsilon$): $0<1-\frac {\varepsilon}{\theta}<1$. That is $\left(1-\frac{\varepsilon}{\theta}\right)^{n}$ tends to zero if $n$ tends to infinity. So does the probability on the left. This is convergence to zero in probability. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "probability distributions, convergence divergence"
} |
Submitting form to new window
On websites, links can be opened in new windows/tabs using the middle-click button, CTRL+left click or Context Menu->'Open in new tab' option. However, this behaviour seems to be not implemented for submit buttons on forms, such as search forms.
For example, when watching music videos on YouTube, I often wish to search for my next video while the current one continues playing. I typically type in my query, but am stuck at how to search without interrupting the video. Middle-click and the other actions don't work, which seems quite strange.
So it got me thinking. **Is there a nice, intuitive way to allow a user to submit a form, loading in a new window at their request?** The shortcuts for links seem to be learned behaviours, and I suspect that many people would see a button and a link as distinct. The only intuitive way I can think of is having an alternative button with label 'Search (New Window)', but this seems quite convoluted and bulky. | There is no known UI/UX patterns to address this as it depends mostly on the user's settings. You can always implement this programmatically by having a "Send button" with multiple actions aka a "Button Dropdown", such as the control below taken from the Bootstrap framework.
!enter image description here
What really matters is to have a consistent UX, regardless of the device, the browser and the settings. Note that using such a control let users choose what they want, you're not enforcing a certain behaviour. | stackexchange-ux | {
"answer_score": 0,
"question_score": 0,
"tags": "forms, keyboard shortcuts"
} |
How to detect stuff that has not been released properly
Writing a program for the iphone. Realized that I forgot to release an object, but there was really no indication that the object was not released everything just worked.
What is the best way to track something like this down? Is there a way to see what objects still exist in memory when the program exits out? | Take a look at the Leaks tool in Instruments. | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 4,
"tags": "ios, objective c, memory management, memory leaks"
} |
Finding degrees of mutual friends between non-friends
Let us assume: Users A and B use my application but they themselves are not Facebook friends and are both huge fans of the band, Cold Play.
User A searches for people who like Cold Play. The application then displays people who also like Cold Play and breaks them up according to the degrees they are separated from User A. User B shows up as a result, being separated from User A by four people. So basically, User A knows someone, who knows someone, who knows someone that knows User B.
Will the Facebook API allow me to find those common links? Or is that all data that I will have to collect on my end and constantly crawl for changes to friends lists of all my users and write my own algorithm to find the shortest distance between two people? | The Facebook API won't tell you who likes a page, so you would be limited to prompting the user for user_likes extended permission and recording which pages they like, and do this for any future users of your app.
The only thing close to this that Facebook provides is the mutual friends API. This would only get immediate results between 2 users. Thus, you will need to log all the users friends and write your own algorithm for this. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "facebook, facebook friends"
} |
Consistency with external/3rd-party calls
I am faced with the following problem. We are required to call the Twitter API to send a status update then we must write a record to a local database, recording that this Twitter update happened.
My question is how can we ensure data consistency if either Twitter or the database calls fail? If we update Twitter and the database call fails we will have no local record of the Twitter call and if the Twitter call fails but the database call succeeds we will have an erroneous local record.
I understand the obvious first steps such as only updating the DB if Twitter call is successful or vice-versa but this only addresses half the problem.
I imagine that this is a common problem but I have tried searching for relevant information without much luck. | Stephen,
You will have a SPOF (single point of failure) in any case - it will be your application. However, for reducing the risk of failure, you can dump your data into a queue (of any sort; even a /tmpfs on the web-server will suffice), and repeat the attempts to write it to DB until it's available.
If the call to Twitter API fails, you obvoiusly can just put a record of failed attempt to the DB. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "database, rest, twitter, architecture"
} |
Angular httpClient: Reformat date in json
I have an object with a property of kind date. If I post it with httpClient.post(...) the date property has it's natural string representation. How can I adopt it to a format that the server understands? | you can make use of this to convert it into the format you need and send it over to the server.
### Angular Date Pipes
Try this,
1. Import the {DatePipe} from '@angular/common' and include this in your main module.
2. Use DatePipe in your ts code where you wish to convert the date into a format that you want to change and use transform method and change it in the form you want.
3. Also do not forget to initialize the DatePipe in your constructor,
Try this code
let myDate = new Date();
console.log(this.datepipe.transform(myDate, 'yyyy-mm-dd')); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "angular, typescript"
} |
topological groups basic facts
How to show that the usual metric with the usual addition is a topological group?
Can anybody please explain me briefly about topological groups and the way that I need to approach to this question? | Let $n:\Bbb R\to\Bbb R:x\mapsto -x$ and $a:\Bbb R\times\Bbb R\to\Bbb R:\langle x,y\rangle\mapsto x+y$; $a$ is the operation of addition on $\Bbb R$, and $n$ is the operation of taking the additive inverse. To show that $\langle\Bbb R,+\rangle$ is a topological group when $\Bbb R$ is given the usual topology, you just have to show that the functions $n$ and $a$ are continuous. You don’t need to know anything more about topological groups; this is really just a beginning real analysis or metric topology problem stated in fancier language. | stackexchange-math | {
"answer_score": 3,
"question_score": 2,
"tags": "general topology, topological groups"
} |
Clusters centers for Distance-based clustering
I implement Distance-based clustering based on android-maps-utils implementation, but I want to use more friendly clusters centers (not the first marker in the cluster like proposed). Any ideas without big performance losing? Thanks. | Density based clusters can be of arbitrary shape.
For non-convex clusters, **the center can be outside of the cluster**.
For such clustering, clusters are not well represented with any single sample. Instead, you would better characterize them by their _cover_ or _shape_. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "android, google maps, google maps markers, cluster analysis"
} |
Воспроизведение звука в input при фокусе
У меня есть 3 текстовых поля, есть в корне звук. Не получается реализовать следующее: если поле в фокусе, должен однократно воспроизвестись звук. Делал так, но не работает:
JS:
function click() {
new Audio('click.mp3').play();
}
HTML:
<form>
<input name="86" type="text" id="pole1" onfocus="click();">
<input name="95" type="text" id="pole2" >
<input name="71" type="text" id="pole3" onfocus="click();">
</form> | Достаточно сменить название функции на другое. Например:
JS:
function onFocus() {
new Audio('click.mp3').play();
}
HTML:
<input name="86" type="text" id="pole1" onfocus="onFocus();">
Fiddle.
Почему не работает именно с названием функции `click` \- не очень понятно. | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "javascript, html, аудио"
} |
S&W Treasure Hoard
Looking for a little clarification on Treasure Hoards.
In the _Swords & Wizardry Complete_ section "Generating a Random Treasure Hoard" (p120) you determine total XP value of the monsters in the adventure, and multiply by (1d3)+1 for gold value. For argument sake let us say this total is 5050gp. I would then roll:
* 50 times for 100gp trade-outs
* 5 times for 1000gp trade-outs
* 1 time for 5000gp trade-out
If I hit five 100gp and one 1000gp trade-outs, (1500gp total), then the party gets 3550gp plus whatever they received in the trade-out rolls.
If, however, I hit one of each (6100gp total) then I have a defecit of 1050gp. Does the party then get the entire 5050gp originally rolled, plus the result of each trade-out?
Either I am a bit thick, or it is wonderfully simple. Possibly both. | That's correct! The second case you describe (in which the value of the trade-outs exceeds the total GP value of the hoard) is how a “Major” treasure hoard is randomly determined. In that case, yes, the hoard consists of all the trade-outs you randomly determined _plus_ all the original gold piece value, as per the note under the main trade-outs table (p. 120):
> Note: if there are several trade-outs, it is possible to end up without enough gold pieces to trade for them, in which case it is a MAJOR treasure – add all the traded-out gold pieces back into the treasure along with the items rolled on the trade-out tables! | stackexchange-rpg | {
"answer_score": 3,
"question_score": 4,
"tags": "treasure, swords and wizardry"
} |
What's the difference between contain and include in English?
What's the difference between: 'his question didn't include a link on Yahoo answers? ' and 'his question didn't contain a link on Yahoo answers? ' (I want to say there wasn't a link in his question on Yahoo answers).
Someone mentioned there are subtle differences, but just can't tell what they are, so I am wondering that you guys here might have the answer. please help me out. thanks folks!
By the way, I am a freshman here. any opinion that regarding the DIFFERENCE between them are appreciated, please feel free to express your opinion, thank you very much your answers! | There's indeed a subtle but important difference between these two terms in the context of the scenario you describe.
**Include** expresses a greater degree of ownership over the object in question (the link) and seems to suggest the user actively worked to incorporate it in their answer. This connotation arises from the fact that _including_ is something a user does, but the answer is what _contains_ (something). In other words, the two terms emphasize two different aspects (the user or the answer) of the same scenario. **Contain** merely refers to the link appearing somewhere in the answer.
In all honesty, though, one term isn't more appropriate than the other. You could say:
> Your answer should contain a link.
Or you could also say:
> You should include a link in your answer.
But it doesn't matter which you choose. | stackexchange-english | {
"answer_score": 3,
"question_score": 0,
"tags": "grammar, differences, synonyms, usage, comparisons"
} |
Is the division property of equality just a special case of the multiplication property?
My textbook clearly states after the lesson on Transforming Equations: Addition and Subtraction
"Notice that the subtraction property of equality is just a special case of the addition property, since subtracting the number c is the same as adding -c."
But, following the next lesson which is on Transforming Equations: Multiplication and Division there is no equivalent statement such as
The division property of equality is just a special case of the multiplication property, since dividing by the number c is the same as multiplying by the reciprocal of c.
Is division just a special case of multiplication, with the restriction of not having 0 in the denominator?
If so, why would they not include such a natural parallel statement? | I cannot speak for the authors, but my guess is that the relation between addition and subtraction is sometimes subtly different from that between multiplication and division, while sometimes the difference is more pronounced. For example, when dealing with real equations, division is simply multiplication by the inverse, except when dividing by $0$. However, in the case of $\mathbb{Z}$ and $\mathbb{R}[x]$, there are multiplicative inverses of only a few elements, whereas there are additive inverses of all of the elements. | stackexchange-math | {
"answer_score": 5,
"question_score": 4,
"tags": "algebra precalculus"
} |
Swift - Where does the point comes from?
I'm having hard time understanding the simple function below. Where does the mysterious 'point' comes from ?
typealias Position = CGPoint
typealias Distance = CGFloat
typealias Region = Position -> Bool
func circle(radius: Distance) -> Region {
return { point in
sqrt(point.x * point.x + point.y * point.y) <= radius
}
} | The `circle` function returns a closure having this declaration:
(Position) -> Bool
`point` is the name of the parameter passed to the closure, of `Position` type - maybe rewriting the function as follows it's more clear:
func circle(radius: Distance) -> Region {
let closure: Region = { (point: Position) -> Bool in
return sqrt(point.x * point.x + point.y * point.y) <= radius
}
return closure
}
You can assign the return value of the `circle` function to a variable:
let closure = circle(1.0)
and then invoke it:
let p = CGPoint(x: 1.0, y: 1.0)
closure(p)
The `p` parameter is what is called (and referenced as) `point` in the closure declaration | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "ios, swift"
} |
Close Div overlay by clicking anywhere on the body
This is what I've done:
$('#keks-overlay').hide();
$('#click').click(function(){
$('#keks-overlay').toggle(450);
});
$('#close-overlay').click(function(){
$('#keks-overlay').toggle(250);
});
jsFiddle: <
This works fine, but it shows/hides (toggles) only by clicking the "X" (#close-overlay).
I'd like do something like the fancybox-effect: fade out on clicking anywhere on the whole body.
Thanks for your help. | You can add an event handler to a `div` that contains the whole page (or the document itself), and `hide()` the overlay in that handler.
$("#somebody").click(function() {
$('#keks-overlay').hide(250);
});
However, if you want to prevent clicks on the overlay itself from triggering the `hide()`, you could either add an event handler to the overlay that returns false (to prevent the event from bubbling up), or place the overlay outside the `div` that holds the rest of your content (which works because the overlay has `absolute` positioning).
I updated your fiddle to show the second method. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "html, overlay, fade, jquery"
} |
How to change instance method's visibility
I want to change an instance method's visibility from public to private.
ooo = Object.new
def ooo.some_public; 'woot' end
ooo.some_public # => "woot"
ooo.respond_to?(:some_public) # => true
I want `ooo.some_public` to be private. How can I do that? | ooo = Object.new
def ooo.some_public; 'woot' end
ooo.respond_to?(:some_public) # => true
ooo.singleton_class.class_eval{private :some_public}
ooo.respond_to?(:some_public) # => false | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "ruby, visibility"
} |
Where is "showing the output of the 'ls' command vertically" documented?
I found out it's possible to show the output of the `ls` command vertically using the `-1` switch:
> $ ls -1
But couldn't find it in the manual of `ls`. Is it a secret option? | The manual is out of date with the program. Try `ls --help | grep -- ' -1'`:
-1 list one file per line
It is one of the last options described if you just do `ls --help`. | stackexchange-unix | {
"answer_score": 52,
"question_score": 42,
"tags": "ls, man, documentation"
} |
Funções de parametros para evento click não funcionam
Estou tentando grifar um texto com o evento **click** e depois "desgrifar" no segundo click, tirei a sugestão de um código que já tinha visto no codepen , estou passando duas funções para o evento click, porém só a segunda funciona, código:
$('.texto').click(function() {
alert(1);
}, function() {
alert(2);
}
);
Só aparece o **alert(2)** , por que isso acontece? | Pelo o que você descreveu, basta utilizar a função `toggleClass` do jQuery para adicionar/remover uma classe CSS do elemento pressionado. Quando um elemento é pressionado, o jQuery irá verificar se ele possui a classe CSS; se não possuir, a adiciona; se possuir, a remove.
$(() => {
// Evento `click` dos elementos desejados:
$("li").on("click", function (event) {
// Adiciona/remove a classe CSS:
$(this).toggleClass("selected");
});
});
.selected {
font-weight: bold;
background: cyan;
}
<ul>
<li>Abacaxi</li>
<li>Banana</li>
<li>Caqui</li>
<li>Damasco</li>
</ul> | stackexchange-pt_stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "javascript, jquery"
} |
Make a web link open App Store on iOS devices
The question of how to link to a specific app or a list of a specific developers apps from a web link has been answered many times. My issue is that I cannot find a format that works to open the appstore front page, I do not want to link to a specific app I just want the link to open the app store on iOS devices. I have tried < and that works on iPad but on the iPhone I am getting a blank page. Is there a way to open the front page of the app store app from a web link on both iPad and iPhones? | Thy this:
`[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"
It opens the featured page at iphone (main page). | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ios, iphone, ipad, hyperlink, app store"
} |
Unable to install VirtualBox Guest Additions on Tails OS
I mounted Tails OS (booted through ISO file) on Virtual Box. The default OS display looks ugly and I couldn't mount Guest Additions through Optical drive as I mounted OS through the same. So, I uploaded Guest Additions.iso file in Google drive and downloaded in VM. When I try to install it, I got following error
 %>'>Employee ID</a>
On the back-end code:
string sortBy = Request.QueryString["s"];
IEnumerable<Employee> items = null;
if (String.IsNullOrEmpty(sortBy))
items = Employee.GetPaged(pageNumber, pageSize);
else
items = Employee.GetPaged(sortBy, pageNumber, pageSize);
return View(items); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "subsonic3"
} |
– encoding of em dash when inserted using CSS :after
I'm getting the old `–` on my page when I try to render an em dash ( `—` ). This can be cleared up by adding `<meta charset="utf-8">` to the document head, I believe. But in this case I'm inserting the em dash via css.
.el:after{
content: "— content to be after";
}
Somehow it is not being encoded properly. `content: "—";` does not work either; it only renders the amersand code. How can I solve this? | While setting the correct encoding is always a good thing to do, I try to avoid this situation entirely and use only ASCII characters in HTML, JavaScript and CSS:
content:"\2014"
Unicode characters are represented by `\hexValue` in CSS.
Beware that if the following character is `0-9` or `a-f` (or `A-F`), it will be considered part of the unicode character. You can put a space after it: `"\2014 stuff"`, and the space won't be displayed (it just marks the end of the character). To actually put a space after it, use two spaces. | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 5,
"tags": "css, encoding, character encoding"
} |
RDS 2012R2 not reconnecting to disconnected session from RDWeb
When a user connects via RDWeb and closes all the applications, the session is disconnected. If that same user, then connects via RDP to the full desktop, a new session is created instead of reconnecting the disconnected session from RDWeb.
Aside from bringing a continuity issue, it also breaks mapped drives.
Any idea what might cause this? | This is by design, RDWeb and full RDP session are using different services. | stackexchange-serverfault | {
"answer_score": 0,
"question_score": 0,
"tags": "windows server 2012 r2, rds, rdweb"
} |
Row Address After Filtering
I have a sheet with around 300k rows. I apply filtering based on dates. After filtering the sheet looks like as follows;
A1 - Header
A2 - Header
A243349 - First data
In order to copy&paste I would like to get A243349 as the address. I tried the code below, it founds correct row, however it gives "First Data" not "A243349"
Dim DataRange As Range
Dim FirstFilteredRow As Range
With Sheets("MySheet")
Set DataRange = Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With
Set FirstFilteredRow = DataRange.Offset(2, 0).SpecialCells(xlCellTypeVisible).Areas(1).Rows(1)
Many thanks in advance for your help.
Best regards, | You need to call the Range.Address property to retrieve the address of the cell
Debug.Print FirstFilteredRow.Address | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "excel, vba, autofilter"
} |
how to correct word rotate - ly?
I want to say a group of people can be host rotate. Means if there's four of us, me can be host today and guest 'A' can be host tomorrow and then 'B' can be host at day 3 ... I will be host again at day 5.
I sense it may be **rotate - ly** or something similar? how do I say that. | The word "rotate" is a verb. You have to use it as a verb
> The host will rotate with each meeting.
There is a little ambiguity, because this could also mean "The host will pirouette". The context makes it clear.
You can use the phrase "in rotation", which can function like a -ly word.
> The host will be chosen in rotation. | stackexchange-ell | {
"answer_score": 0,
"question_score": 1,
"tags": "word request"
} |
Perform function if string exists on page
I simply want to have an alert that says "Page contains string" if a specific string exists on a page.
Shouldn't it be as simple as this:
if ('*:contains("This String")') {
alert('Page Contains String');
} | Try this way :
if($("body").text().indexOf("This String") > -1) {
alert("page contains string");
}
Or pure JS :
if (~document.body.textContent.indexOf('This String')) {
alert("page contains string");
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, jquery"
} |
Safari mobile browser doesn't have selectedOptions for <select>
I am working on a web app and was testing it on my ipad when I realized that something was not working.
I decided to further look into it and discovered that this won't work on the ipad but will on desktop browser:
$(function() {
$('select').change(function(e) {
console.log(e.srcElement.selectedOptions);
});
});
Ipad console shows `undefined`
Here is a jsfiddle to test it out with.
Is my approach wrong? Or is this a bug in mobile safari? | Do you mean to be using e.srcElement.selectedIndex or e.srcElement.value?
e.srcElement.options[e.srcElement.selectedIndex].getAttribute("data-sort"); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "javascript, ios, mobile safari"
} |
python selenium how to get hover element information
I need to get information from this site from the description using selenium python. The description appears when you hover your mouse over the nickname. I can't seem to find a way to get the description, any help would be greatly appreciated | Just grab all the values in the element div with id tip after you hover using ActionChains.
values=[x.text for x in driver.find_elements(By.CSS_SELECTOR,"div#tip a")]
print(values) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, selenium, hover"
} |
Can I cross develop an app for IIS and Azure?
We are starting to build out some new tech and I want to know if it is possible to cross develop a web app to run natively in Azure (ie, use Azure specific stuff like storage) but also run locally on our test servers and accommodate internal deployments natively on IIS?
I know I can host them from a dev box in a simulated Azure environment and I know that I can interface the Azure parts out and write in non-azure counterparts. It just seems like this should be a solved problem. | If you want to run Azure applications on-premises ( _and using non-development Azure storage_ ), you must run a Microsoft Private Cloud. It requires special hardware and licensing costs, so don't expect it to run on what you have today. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 4,
"tags": "iis, azure"
} |
How to get px height of the element with CSS height auto MooTools?
Is there any way to get actual element height ? getSize().y
returns 0 since element has property height auto? even if you declare image inline property to auto you get 0 back?
Thank you! | It sounds like you had a different issue, but to make this future-relevant, the mechanisms in MooTools for this are (for an element with the id `x`:
$('x').getSize().y
or
$('x').getCoordinates().height
Either of which will return an integer (no units) of the pixel height. So a 100 pixel tall element would return `100` for either of these.
You could also use the non-MooTools specific `getComputedStyle` method:
$('x').getComputedStyle('height')
Which returns the element height with the unit. So a 100 pixel tall element would return `100px`. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "mootools"
} |
Using Google API 3 with Openlayers Brings POPUP
> **Possible Duplicate:**
> Google Maps layer copyright popup every time map updated / user input
I recently upgraded from google map api v2 to v3. It was working quite fine previously but now it does work but each time I zoom,pan I get a popup. I had look at many thred and < one especially that explains that openlayes 2.11 has no problem (2.10 has problem and 2.11 being the latest I assume this). I am using openlayers 2.11 with geoext. How can I solve this problem?
!POPUP | Adding version works for me too:
<script type="text/javascript" src="
Adding this to CSS hides popup and 2nd copyright:
div.olLayerGoogleCopyright,
div.olLayerGooglePoweredBy
{
display: none !important;
}
but Google links are still not clickable. | stackexchange-gis | {
"answer_score": 0,
"question_score": 0,
"tags": "openlayers 2, geoext, google maps api"
} |
display my json list of customers in asp.net mvc with jquery
i have a customer list object back from server and i want to display in my view. What's the best way to do this? for instance, showing the customers in a div on the page | It depends on your business and how you want to display it. There is no generic solution for this. In case you want to display the json "as is" (don't know why you'd like to to this, maybe for debugging), you could put it inside a pre:
<div>
<pre id="pre"></pre>
</div>
...
$("#pre").html(JSON.stringify(jsonObject));
JSON.stringify will work on modern browsers. But, (I insist), there is no "correct" answer for your question, it depends specifically on your "business" needs. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, asp.net, asp.net mvc"
} |
Countdown timer to start of HTML5 video
I am trying to get a 3 second timer to display and then start the HTML5 video. What I have so far is a hover to start the video and it works great. I need to have a timer display when you hover over the video and when that timer hits 0 it will start the video. Any suggestions. This is the code I have for the video hover to start.
$('#player2').hover(function(){
var that = $(this);
if(!$('#'+that.data('video')).is(':visible')){
$('video:visible')[0].play();
$('video:visible').fadeIn('normal', function(){
$('video')[0].play();
$('#'+that.data('video')).fadeOut('normal', function(){
$('#'+that.data('video'))[0].play();
});
});
}else{
$('#'+that.data('video'))[0].play();
}
}, function(){
$('video:visible')[0].play();
}); | Granted this is not the most elegant way to do things. But to give you an idea.
var running = false;
$('#counter').hide();
$('#player2').hover(function(){
if(!running){
running = true;
var that = $(this); // get your that variable here
$('#counter').html('3'); //counter animation 3
$('#counter').show();
setTimeout(function() {
$('#counter').html('2'); //counter animation 2
},1000);
setTimeout(function() {
$('#counter').html('1'); //counter animation 1
},2000);
setTimeout(function() {
if(!$('#'+that.data('video')).is(':visible')){ // the rest of your video code
....
});
},3000);
}
});
Fiddle example
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "jquery, html"
} |
Creating a raster mosaic from multiple un-referenced jpegs
I have multiple historical aerial photographs that I would like to use to compare coastal change over time in relation to urban development. The aerials I have obtained come in tiles that are not georeferenced but they are also not big enough to get a good RMSE when georeferencing them individually. So to fix this I would like to turn each of the individual tiles into one large mosaic to use for georeferencing. However, when adding them into Arcmap they each just layer on top of each other which does not help me at all. Is there anyway that I can manually (or otherwise) arrange them into their correct order so that I can then combine them into a single mosaic and subsequently accurately georeference? | You can use Photomerge if you have overlap in your rasters.
> Images should overlap by approximately 40%. If the overlap is less, Photomerge may not be able to automatically assemble the panorama. However, keep in mind that the images shouldn’t overlap too much. If images overlap by 70% or more, Photomerge may not be able to blend the images.
If Photomerge does not work for you, try a manual overlap/blend/stitch.
After this you can simply georeference the raster. Use an online service, find good points for the corners and add extra points for the coastal area for an increase in precision in that area. | stackexchange-gis | {
"answer_score": 0,
"question_score": 0,
"tags": "arcgis desktop, georeferencing, mosaic, image mosaic, aerial photography"
} |
C++ Initialization query
Can someone please tell me if there is anything incorrect with this initialization:
static unsigned char* var[1]
var[0] = new unsigned char[ 800 * 600 ]
Is this creating a 2D array at var[0] ? Is this even valid ? | It is creating a 1-d array of length (800*600) at var[0]. You'll be able to access its elements with:
var[0][0]
var[0][1]
...
var[0][800*600-1] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c++, initialization"
} |
Laravel Eager Loading, multiple same hasOne relations
I have 2 simple models. First, one is called Builds and the second one is called SlotOptions. Each build can have like 5 assigned slots.
class BuildDB extends Model
And has 5 such relations `slot1-5 and id changes to slot1-5_id`
public function slot1()
{
return $this->hasOne('\App\SlotOptions', 'id', 'slot1_id');
}
In the controller I call it such way;
BuildDB::with([ 'slot1', 'slot2', 'slot3', 'slot4', 'slot5'])->find(5);
`\App\SlotOptions` model doesn't contain any extra coding.
This generates 5 "same" queries. - atm the eager loading would work if I get a list of builds and each slot would have whereIn clause, is it possible to have it a one big `wherein` the clause, or does it require to change the DB schema. | It's not possible to optimize eager loading in this case.
I recommend that you change your database schema to a many-to-many relationship).
This design is more flexible, it allows you to easily add more slots in the future.
Create a pivot table named `build_slot_option` with these columns: `build_id`, `slot_option_id`
Add an additional column if you want to number/order the slots.
Then define a `BelongsToMany` relationship:
class BuildDB extends Model
{
public function slots()
{
return $this->belongsToMany(
SlotOptions::class, 'build_slot_option', 'build_id', 'slot_option_id'
);
}
}
BuildDB::with('slots')->find(5); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php, laravel 5, eloquent"
} |
Difference between rows.add and importRow
When adding a row to a datatable in vb.net, what is the difference between rows.add and importRow?
Dim dt As DataTable
Dim dr As DataRow
'Add row this way...
dt.rows.add(dr)
'or this way.
dt.importRow(dr) | both do same functionality adding row to datatable but the main difference is
DataTable dt1=new DataTable();
DataRow dr1=dt1.NewRow();
DataTable dt2=new DataTable();
dt2.Rows.Add(dr1); // will give you error already dr1 belongs to another datatable in that //case you can do like this
dt2.ImportRow(dr1); // safe
dt1.Rows.Add(dr1); // safe as dr1 Row belongs to DataTable1 so no exception raise
hope that will give you an idea.. | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 10,
"tags": "vb.net, datatable"
} |
SQL Server - transfer Excel file with T sql
Can I transfer an Excel file from one folder to another after reading it?
let's say I have the Excel file first in "incoming" folder and after reading it I want to transfer the file to "reads" folder
this is possible with T sql? | I would recommend using SSIS to accomplish this task. It has an inbuilt File System task which you can use to rename the file into another folder. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "sql server, excel, tsql"
} |
Is the largest number of molecules in 36 g of water or 54 g of dinitrogen pentaoxide?
Recently my teacher asked us which of the following has the largest number of molecules? He gave us two options:
1. $\pu{36 g}$ of $\ce{H2O}$
2. $\pu{54 g}$ of $\ce{N2O5}$
I'm stuck, because both of them are having two moles of each of the respective molecules. And technically, the number of molecules equals the amount of substance multiplied by Avogadro's number.
So shouldn't $\pu{2 mol} \times N_\mathrm{A} = N(\text{molecules})$ be the same number of molecules for both of them?
But yet, the teacher said that water is the correct answer.
And I'm still not able to figure out why? | > I'm stuck, because both of them are having two moles of each of the respective molecules.
Are you sure?
\begin{align} M(\ce{H2O}) &= \pu{18 g mol^-1} & \implies \pu{36 g} &\mathop{\hat{=}} \pu{2 mol} \\\ M(\ce{N2O5}) &= \pu{108 g mol^-1} & \implies \pu{54 g} &\mathop{\hat{=}} \pu{0.5 mol} \\\ \end{align} | stackexchange-chemistry | {
"answer_score": 7,
"question_score": 4,
"tags": "stoichiometry, mole"
} |
How to remove padding of 0 while using NSdateFormatter?
Like if I am using the code.
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setDateFormat:@"dd.MM.yyyy"];
NSDate *today = [NSDate date];
NSString *log_date = [df stringFromDate:today];
//Generate Log Current Time.
[df setDateFormat:@"hh:mma"];
NSString *log_currenttime = [[df stringFromDate:today] lowercaseString];
NSLog(@"Log Date %@",log_date);
NSLog(@"Log Current Time %@",log_currenttime);
My log shows me :
> Log Date 19.12.2011
> Log Current Time 03:18pm
At least I can remove the Time Padding. | Change your format from `hh:mma` to `h:mma`
//Generate Log Current Time.
[df setDateFormat:@"h:mma"]; // Changed from hh:mma to h:mma
NSString *log_currenttime=[[df stringFromDate:today] lowercaseString];
NSLog(@"Log Current Time %@",log_currenttime);
This will output
> Log Current Time 3:18pm | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 2,
"tags": "iphone, objective c, xcode, cocoa touch"
} |
GCM push notification issue in android P (28)
we're using GCM for push notification for our app with target release to 26. Using `class GCMJobIntentService extends JobIntentService` for push notification services because of target release 26.
It's now android P released and push notification stopped working. When debugged found below exceptions
> ActivityManager: Unable to start service Intent { act=com.google.android.c2dm.intent.REGISTER pkg=com.google.android.gsf (has extras) } U=0: not found
Due to exception above, it's returning blank gcm token and nothing working for push. Is there someone facing same issue, and if there is any solution to go with GCM without updating to FCM for now? | You may refer with this post: GCM unable to start service intent. You need to upgrade to GCM 11 or higher.
> You are likely be using an older version of GCM.
>
> You may upgrade to GCM 11 or higher, or even better, migrate to FCM. (GCM is now deprecated)
>
> (The latest GCM version is 15.0.1: com.google.android.gms:play-services-gcm:15.0.1)
Since GCM is going to be taken out soon, it is recommended for you to use FCM instead. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "android, push notification, google cloud messaging"
} |
Looking for a database solution for mostly read application, querying 300 million records
Looking for right database technology to query efficiently 300 mil record tables. Tables may contain 5-30 columns mostly tinyint + zip, state. Users can issue arbitrary queries with where conditions on many columns and group with count either by state or zip. Datasets are static in a sense data is reloaded regularly and there is no inserts, just reads.
I already tried Mysql (RDS) with InnoDB. Because of big number of records and nature of queries I could not get satisfactory performance.
Tried MonetDB (columnar store) with very good results but it doesn't seem it is being used by many which raises some concerns.
Requirement is response time quick enough for responsive web UIs for analytics.
What other technologies I should explore? | I would encourage you to try MonetDB, it depends on your queries, but generally - it being a column-store you should get good performance (even over 300 mil record). Plus you don't need to manually create indices and such - it is mostly self-optimizing. MonetDB also has a Node.js driver/connector, which may be used for writing quick analytical web apps. There are also connectors for popular languages/frameworks: Ruby, Python, Perl, PHP, Java (via JDBC).
And don't worry, MonetDB is being actively developed (disclaimer: I am actually a developer) and you can get answers relatively quickly on the users mailing list. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "mysql, bigdata, monetdb"
} |
Why can't I get JavaScript yield to work?
I'm trying to run the code from here
MDN: Generators and Iterators
function fib() {
var i = 0, j = 1;
while (true) {
yield i;
var t = i;
i = j;
j += t;
}
}
var g = fib();
for (var i = 0; i < 10; i++) {
console.log(g.next());
}
I cannot get it working in Node.js, Chrome or Firefox | It's an EcmaScript.next feature that is being tested in newer versions of JavaScript interpreters.
Mozilla's "Iterators and Generators" explains how to use them.
To see which browsers support which ES.next features, see kangax's compatibility chart and browser specific reports. Although Chrome as a whole does not yet, jmar777 reports that V8 supports it (as of Aug 2013). | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "javascript"
} |
Unrecognized VM option 'CMSClassUnloadingEnabledn-J-Xmx2Gn'
I have installed scala, sbt on Mac. When I try to run sbt it gives an error Unrecognized VM option 'CMSClassUnloadingEnabledn-J-Xmx2Gn'. I think there is an issue with JVM but could not find any help for this error.
More error info: Did you mean '(+/-)CMSClassUnloadingEnabled'? Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit. | My guess is that the sbt configuration is confused with regards to line breaks and mangles something like
-J-XX:+CMSClassUnloadingEnabled
-J-Xmx2G
into one line | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 6,
"tags": "scala, sbt"
} |
Play WEBM music on Debian headless
I'm able to play .mp3, .ogg, .m4a, etc., but .webm does not work. The error I get is:
Playing La Caution-Thé à la Menthe Instrumentale.webm.
[mkv] Unknown/unsupported audio codec ID 'A_OPUS' for track 1 or missing/faulty
[mkv] private codec data.
[mkv] Track ID 1: audio (A_OPUS), -aid 0, -alang eng
[mkv] No video track found/wanted.
Detected file format: Matroska
No stream found.
Exiting... (End of file)
I'm running it on a Raspberry PI (2, I think):
Linux host 4.9.35-v7+ #1014 SMP Fri Jun 30 14:47:43 BST 2017 armv7l GNU/Linux
Am I missing some library? When running it through `mplayer.exe` under Windows it works just fine and `avconv` is able to convert in the Raspberry PI too. | Switch to `mpv` instead of `mplayer`. Problem instantly solved! | stackexchange-superuser | {
"answer_score": 1,
"question_score": 1,
"tags": "linux, debian, raspberry pi, arm, mplayer"
} |
SMP, NUMA, local memory - limits on numer of processors
I consider what are limits on number of processor in following models of shared memory:
a. each processor has only own local memory.
b. SMP
c. NUMA
I can't see any limits. Am I wrong ? | When each processor has its own memory, you end up with separate computers in a network. This is limited by the network speed, because you still need to distribute work packages and collect results.
SMP is limited by memory bandwidth. WHen your processor cores compete for memory access, they end up waiting for more and more time, so even if you can add more cores, the total amount of work that can be performed will not rise after some point. In addition, the length of the connection between the cores limits the bus clock.
NUMA is just a specialized network that emulates access to non-local memory, so it still has the same limitations as a regular networked approach, and IIRC the protocol requires direct pairwise connections between cores, so this becomes a signal routing problem as well. | stackexchange-electronics | {
"answer_score": 1,
"question_score": 1,
"tags": "memory, computer architecture"
} |
Activiti BPM get Variables within Task
is it possible to get all process or task variables using TaskService:
`processEngine.getTaskService.createTaskQuery().list();`
I know there is an opportunity to get variables via `processEngine.getTaskService().getVariable()`
or
`processEngine.getRuntimeService().getVariable()`
but every of operation above goes to database. If I have list of 100 tasks I'll make 100 queries to DB. I don't want to use this approach. Is there any other way to get task or process related variables? | Unfortunately, there is no way to do that via the "official" query API! However, what you could do is writing a custom MyBatis query as described here:
< (Note: Everything described in the article also works for bare Activiti, you do not need the fox engine for that!)
This way you could write a query which selects tasks along with the variables in one step. At my company we used this solution as we had the exact same performance problem.
A drawback of this solution is that custom queries need to be maintained. For instance, if you upgrade your Activiti version, you will need to ensure that your custom query still fits the database schema (e.g., via integration tests). | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 4,
"tags": "java, business process management, activiti"
} |
Is there a way to use the over function in r to retrieve all polygons that do NOT have points in them?
I have used the over function to retrieve the polygons of a map that contain points. I'am wondering, for my own learning purposes, if there is a way to use the over function to retrieve the polygons that don't have points in them. Is this possible?
Here is some code to return polygons of a map WITH points in them:
coordinates(data) <- ~ long_xcord + lat_ycord
# Set the projection of the SpatialPointsDataFrame using the projection of the shapefile.
proj4string(data) <- proj4string(shapeData)
p <- over(data, shapeData, returnList = TRUE)
p <- do.call(rbind.data.frame, p)
can the above be modified to return the polygons that DO NOT have points in them? | You can use the results of your over query to select from the original polygon layer, and its easier if you just set returnList to False to get a dataframe e.g.
p <- over(points, polys)
polys_notint <- polys[!(polys$id_field %in% unlist(p$id_field)), ] | stackexchange-gis | {
"answer_score": 1,
"question_score": 1,
"tags": "r, overlay"
} |
Python passing variable tuples between functions
Im having an issue with returning multiple values in a fuction and using them in a different function. For simplicity:
def menu1():
system=system1
choice=1
return system,choice
def menu2():
option = menu1() #this assigns the option a tuple based on the first function.
if option==system1:
print"yes"
if option==1:
print"yes"
menu2()
How can i correctly give option a value of either "system1" or "1" based on getting the values from a previous function? | You can index the tuple just as you would any other kind of sequence:
def menu2():
option = menu1()
if option[0]==system1:
print"yes"
if option[1]==1:
print"yes"
Sequences are 0-indexed in Python so the first element is at index 0, and the second is at index 1, and so on.
However, in my opinion, it's clearer to do the following:
def menu2():
system, choice = menu1()
if system==system1:
print"yes"
if choice==1:
print"yes"
This is called tuple-unpacking and it can be used to split the value of a tuple up into multiple names to be assigned to. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "python, function, variables"
} |
How to parse a string in Java? Is there anything similar to Python's re.finditer()?
I have an input string with a very simple pattern - capital letter, integer, capital letter, integer, ... and I would like to separate each capital letter and each integer. I can't figure out the best way to do this in Java.
I have tried regexp using Pattern and Matcher, then StringTokenizer, but still without success.
This is what I want to do, shown in Python:
for token in re.finditer( "([A-Z])(\d*)", inputString):
print token.group(1)
print token.group(2)
For input "A12R5F28" the result would be:
A
12
R
5
F
28 | You could use regex API in Java and achieve the same functionality:
Pattern myPattern = Pattern.compile("([A-Z])(\d+)")
Matcher myMatcher = myPattern.matcher("A12R5F28");
while (myMatcher.find()) {
// Do your stuff here
} | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 5,
"tags": "java, python, regex, parsing"
} |
Explain Objective C retain cycle with real world example?
I am reading about retain cycle that, "A retain cycle can take a few forms, but it typically means that object A retains object B, and object B retains object A, but nothing else retains object A or B". But I'm not clear about that concepts. Please can anyone explain retain cycle with real world example.
Thanks. | A simple example,a person lives in a department,a department have one person(Suppose have one)
@class Department;
@interface Person:NSObject
@property (strong,nonatomic)Department * department;
@end
@implementation Person
-(void)dealloc{
NSLog(@"dealloc person");
}
@end
@interface Department: NSObject
@property (strong,nonatomic)Person * person;
@end
@implementation Department
-(void)dealloc{
NSLog(@"dealloc Department");
}
@end
Then call it like this
- (void)viewDidLoad {
[super viewDidLoad];
Person * person = [[Person alloc] init];
Department * department = [[Department alloc] init];
person.department = department;
department.person = person;
}
> You will not see dealloc log,this is the retain circle | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": -1,
"tags": "ios, objective c, retain cycle"
} |
How do I transition to the last slide using fadeIn()
I made a script in order to create this "slideshow": <
yet I can not go back to the last slide if I hit "previous" when it is on the first slide
I tried using the last-child selector but had no success
I also tried resetting the count directly like so:
if(count==1){
count=2;
$(".slideshow :nth-child("+count+")").fadeIn();
}
I've been stuck with this for two days, I'm trying to understand what I'm doing wrong!
**all I what's left to do is to go to the last slide if I hit "previous" while I'm "standing" on the first slide** | First you need to hide all the other `.slideshow img` elements not being shown when your page first loads. You can do that multiple ways, but here's an example:
$(".slideshow img:not(:nth-child(" + count + "))").hide();
Next, you need to hide the current showing slide when going to the previous one:
$(".slideshow :nth-child(" + count + ")").fadeOut();
Finally, you need to set the count to the number of elements in `.slideshow img` when going to the last image:
count = $(".slideshow img").length;
Here's a working example: < | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "javascript, jquery, html, css"
} |
Connect a computer to the same printer via a direct USB connection and a network connection simultaneously?
Can I connect a computer to the same printer via a direct USB connection and a network connection simultaneously?
The idea behind is that while I work from home and am connected to my work via VPN, I cannot access the printer via home network. However, I still want to be able to connect to the printer via network when I am not connected to the VPN (and in this case I prefer using the printer as a network printer and not as a USB printer). | Easy, plug it in!
Assuming it's already hooked up via network, wait until Windows detects the new printer port, and installs the new queue. Go to the **Start Menu** , and open up **Devices and Printers**. Then right-click on the printer, select **Printer Properties** (not just _Properties_ ).
Click on the **Ports** tab, and tick the box for **printer pooling**. This allows you to select both ports, the TCP/IP port and the USB001 port (or whatever one is currently used). Save your settings. Windows will print to whatever port is available.
Failing this, you can also _pause_ printing until you disconnect from the VPN. Advantages include not seeing error messages about finding the printer, and the queuing happens almost instantaneously. Disadvantages include not seeing error messages right away (i.e. paper out, but that's easy enough to fix), and remembering to Resume printing. | stackexchange-superuser | {
"answer_score": 1,
"question_score": 2,
"tags": "usb, printer, network printer"
} |
Inject dynamically generated data into JSON
I have developed a tool that can test some requests to a server, the requests themselves are no more than some simple JSON files that are stored on the disc and can be added continuously, but ... there is one more thing, the JSON files contains an e-mail address that needs to be changed upon running the project each time, this is because each of users have a personal e-mail, I made that because server can't accept more than one request from an user. So I am looking for a solution to inject this e-mail address dynamically into JSON.
I'm using Java for this, and also jayway for REST API and Gson for JSONs. So far I looked into google, but can't find anything at all. | You could do this by these solutions:
* Use json file as template string with markup like "{email: ${e-mail}}", then just use `jsonTemplate.replace("${e-mail}", email[i])`
* parse json to Map or Object that model request, then change email field and build again json out of it | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "java, json"
} |
Shuffling cards causes uneven mana distribution - ways to fix that?
I am a newbie Magic player who is suffering from frequent bad luck with mana distribution in the deck.
I am shuffling cards regularly between rounds and matches, and I use mixture of overhand and pile shuffle (4x2). After game, I drop 1-2 cards from graveyard or play on each land in play, and I put the block in the library. I do few overhand shuffles, and before match I do pile shuffle. However, having multiple lands at the bottom of my library after a mana-screw game has happened twice in two weeks.
What am I doing wrong, and is there a better way to ensure land randomization in the deck? | > I am shuffling cards regularly between rounds and matches, and I use mixture of overhand and pile shuffle (4x2). After game, I drop 1-2 cards from graveyard or play on each land in play, and I put the block in the library. I do few overhand shuffles, and before match I do pile shuffle.
Quite frankly, you are not shuffling your deck. Only riffle and mash shuffles can effectively randomize a deck, and you need to do it at least 8 times. An overhand shuffle is about 100 times less effective. A pile "shuffle" should only be used to count your deck (which you should do at the start of each game); it does not randomize the deck.
You should not do any organization of lands or spells in the deck before shuffling. If your deck is randomized, it does not matter what order it began in. | stackexchange-boardgames | {
"answer_score": 7,
"question_score": 3,
"tags": "magic the gathering"
} |
Sites API should include a site branding color, or if it shouldn't, why not?
I'm making a Stack Exchange app, and one thing I found pretty cool in the sites API is that it sends us the colors for links and tags, so my apps color is kind of consistent with the sites.
But the site branding color, like orange in Stack Overflow, or red in Server Fault, is not included. I consider that color to be the most important one, so I could use as an "accent color" in my app.
I'm thinking that maybe somebody already thought that, and maybe there is a reason to not to provide this color, but I can't think of one. If that's the case, I really want to know the reason.
P.S.: my app is a personal project to learn Jetpack Compose - < | It looks like this color is used in the side menu:
,
static readonly string apiKey = ConfigurationManager.AppSettings["apiKey"];
**The name 'ConfigurationManager' does not exist in the current context.**
Why would this be? `System.Configuration` is used all over the place in this application, but isn't being recognized in this particular file.
If I go to the Manage NuGet packages panel and search 'configuration manager', the top choice is 'System.Configuration.ConfigurationManager'. Even the oldest available version has a .NETFramework dependency of 4.6.1, whereas this application uses 4.5.1 so downloading it is not possible.
Is there something I am overlooking here?
Any and all input appreciated. | if you are getting error in the Add References window, try editing the .csproj to add the reference (along with other references) in the Reference ItemGroup like:
<ItemGroup>
<Reference Include="System.Configuration" />
</ItemGroup> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, .net, configurationmanager"
} |
Using embedded resource icon as app icon in C#
I'm trying to figure a way to specify my C# application to use an embedded resource (icon) as my application icon (the one displayed for taskbar, task switch, etc). Yet, as I already embedded my icon in a resource, I can manage to use it in my forms but not with my application yet.
In fact, if someone could first tell me where I'll be able to set this (which file) by hand instead of using the VS2010 GUI to specify it, that'd be a great start!
Yet, my icon is available in these 2 ways : `{{Namespace}}.Properties.Resources.c_name.ico` and in `{{Namespace}}.Refs.c_name.ico` (as a property of a `public static class` inside a class library). | Windows is an unmanaged operating system that doesn't know beans about managed resources. The only icon it can display is one that's embedded as an _unmanaged_ resource. You can see what unmanaged resources look like in Visual Studio. Use File + Open + File and pick a .NET exe file (won't work in Express). A .NET program should have three of them, an icon, a manifest that declares the program compatible with UAC and a Version resource. This is all done automatically by the compiler, note for example how the Version resource properties match the attributes you set in AssemblyInfo.cs
The IDE makes it simple to set the icon for a program, you use Project + Properties, Application tab, Icon setting. Just pick the same .ico file as you embedded as a managed resource. Forget about trying to share, it cannot work by design. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 1,
"tags": "c#, visual studio 2010, resources, icons"
} |
Failed package upload: permission set references Payment that has M-D relationship with Account
I am trying to upload a managed package, it is failing validation and complaining that my permission set references the blng__Payment__c object that has a M-D relationship with Account.
<Permission Set Name> references Payment that has M-D relationship with Account.
Searching online it is said that M-D relationship are not supported for managed packages, which is fine.
The problem is I don't have control over blng__Payment__c, that's not part of my package, I only reference it in some component I uses. So I am not sure how I can fix it? | The relevant documentation from the ISVforce Guide is About Permission Sets and Profile Settings:
> Do they [Permission Sets] include standard object permissions?
> No. Also, _you can’t include object permissions for a custom object in a master-detail relationship where the master is a standard object_
Emphasis mine. You can ship master-detail objects, but you cannot permission them in a packaged permission set. The fact that this object is owned by a different managed package doesn't change how these manageability rules are enforced.
You'll have to remove these object permissions from your Permission Set. | stackexchange-salesforce | {
"answer_score": 2,
"question_score": 0,
"tags": "managed package"
} |
How to save MATLAB figure in full screen
I would like to save the figure plot in in FULL SCREEN.
My code save the figure in tiff file but not in full screen; with overlapping txt titles. please, any one does know how to solve this issue ?
scrsz = get(0,'ScreenSize');
set(figure,'position',scrsz);
subplot(2,2,1)
surf(peaks(30))
title(' ********************** test ************************** ');
subplot(2,2,2)
surf(peaks(30))
title(' ********************** test ************************** ');
subplot(2,2,3)
surf(peaks(30))
title(' ********************** test ************************** ');
subplot(2,2,4)
surf(peaks(30))
title(' ********************** test ************************** ');
saveas(gcf,'test.tiff')
answer:
set(gcf,'PaperPositionMode','auto','PaperPosition',[0 0 20 10])
print -dtiff -r96 itest.tiff | You should change the dimensions in paper space and use _"Print"_ instead of _"Save as"_. For example:
set (gcf, 'PaperPositionMode', 'manual','PaperPosition',[0 0 30 20])
print -dtif -r 150 test.tiff
This will create a `tiff` 30x20 cm with a resolution of 150dpi. Playing with the dimensions you can easily obtain figures with the size you need.
The attribute "position" is related to `.fig` files and define the position of that files on the screen space. After printing (saving Matlab figures as pictures `jpeg`, `png`, `tiff` or `pdf`) the dimensions should be defined in the paper space.
I hope this can help. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "matlab, save, figure"
} |
Search curl output for string with Bash
Trying to fetch a webpage as a lowercase string, then search the string output for a substring
My attempt:
1 #!/usr/bin/env bash
2
3 URL="
4 MOVIES_SOURCE="movies.txt"
5 PAGE=`curl "$URL"` | tr '[:upper:]' '[:lower:]'
6
7 while IFS= read -r movie
8 do
9 FOUND="$($PAGE =~ "$movie")"
10 echo $FOUND
11 if [[ $FOUND ]]; then
12 echo "$movie found"
13 fi
14 done < $MOVIES_SOURCE
15
When I run this, I'm receiving `line 9: =~: command not found`
The `$movie` variable is valid and contains each line from `movies.txt`, but I'm struggling to figure out this one! | If you want to use regex matching in bash:
if [[ $PAGE =~ $movie ]]; then
echo "$movie found"
fi
example:
PAGE="text blah Avengers more text"
movie="Avengers"
if [[ $PAGE =~ $movie ]]; then
echo "$movie found"
fi
gives:
Avengers found
**Also:** to capture the output of the whole curl command:
PAGE=$(curl "$URL" | tr '[:upper:]' '[:lower:]')
* always prefer `$()` over backticks
* you had to wrap your whole command in order for `$PAGE` to contain the output where you converted to lowercase. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "regex, bash"
} |
How to get img src that changed by JavaScript in code behind C#.NET
this is my client code:
<form id="form1" runat="server">
<div>
<img id="mm" runat="server" />
</div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<script>
document.onclick = function () {
mm.src = "photo1.jpg";
}
</script>
</form>
and I try to get img src in code behind, but it returns null :
protected void Button1_Click(object sender, EventArgs e)
{
string s1= Request.Form["mm"];
string s2= mm.Attributes["src"];
string s3 = mm.Src;
}
How can I do this? | **You simple can not**. You can not get on code behind the `src`of an image after have been change by javascript.
This is because this information is not travel back to server even by post back.
The work around is to save at the same time with the `src` to a hidden input control on the value... the same data.
So after the post back you read the value from that input control, because only that type of controls send back their values.
Here is an example base on your code
<asp:HiddenField runat="server" ID="ImgExSrc" />
<script>
document.onclick = function () {
mm.src = "photo1.jpg";
document.getElementById("<%=ImgExSrc.ClientID%>").value = mm.src;
}
</script>
and on code behind you just read the `ImgExSrc.Value` after the post back. Only with post back you can send your values to the server side. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "asp.net"
} |
Can diffusion produce energy?
A friend and I recently got into a silly argument where I stated
> pure diffusion can't produce energy since **diffusion are a part of passive transport**.
He stated if we
> If we have tinny turbine which allow to transfer only one molecule at a time due to the different concentration the molecule will make turbine rotate and produce energy (which I thought this assembly will be a non-permeable since direct contact is must in diffusion )
On the other hand we encounter some research trying to produce energy by differentiating level of water separated by a semi-permeable. And they accomplish producing energy how that happen (I think they give an energy in another way by differentiating concentration and they collect this energy. It is only an engineering) | It depends what you mean by diffusion.
If you're considering a system at equilibrium, e.g. a sodium chloride solution, and you're trying to extract energy from the diffusional motion of the sodium and chlorine atoms then you can't extract any energy. Your friends idea of a tiny turbine is effectively the same as the Maxwell's demon idea for extracting energy from the thermal motion of gas molecules.
On the other hand, if you're considering a non-equilibrium system, e.g. where there is a concentration gradient, of a solute then yes you can extract energy from this. The easiest way would be to use a semipermeable membrane as you describe.
!SPM
If your semipermeable membrane allows solvent through but not the solute, then there will be a net flow of solvent from the low concentration to high concentration side. This creates an osmotic pressure so there is a force on the membrane, $F$. Allow the membrane to move a distance $x$ and you can extract some work $W = Fx$. | stackexchange-physics | {
"answer_score": 4,
"question_score": 1,
"tags": "energy, diffusion"
} |
module 'django.forms' has no attribute 'PhoneNumberField'
I get this error module 'django.forms' has no attribute 'PhoneNumberField'
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
mobile = forms.PhoneNumberField() | First of all, you are missing a ":" behind your class, then you have a typo in the "mobile" and there is no phoneNumber field, you could import one like this but only if you first install the `phonenumber_field` library
from phonenumber_field.modelfields import PhoneNumberField | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "django, forms"
} |
How to select only specific columns when querying using ActiveRecord?
I know if we want to select only some specific columns by using find or where is like this.
Post.find(10).select("column1")
But, when I write code like this `post.user.username` (rely on ActiveRecord associations), if I want to select only a few columns from the `user` table, I can't find a way to do so. | In your post model you can define the association as follows:
belongs_to :user, :select => [:username]
Then referring to the user via a post would select only the stated columns. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, ruby, ruby on rails 3"
} |
Python: distance from index to 1s in binary mask
I have a binary mask like this:
X = [[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 1, 1],
[0, 0, 0, 1, 1, 1],
[0, 0, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 1]]
I have a certain index in this array and want to compute the distance from that index to the closest `1` in the mask. If there's already a `1` at that index, the distance should be zero. Examples (assuming Manhattan distance):
distance(X, idx=(0, 5)) == 0 # already is a 1 -> distance is zero
distance(X, idx=(1, 2)) == 2 # second row, third column
distance(X, idx=(0, 0)) == 5 # upper left corner
Is there already existing functionality like this in Python/NumPy/SciPy? Both Euclidian and Manhattan distance would be fine. I'd prefer to avoid computing distances for the entire matrix (as that is pretty big in my case), and only get the distance for my one index. | Here's one for `manhattan` distance metric for one entry -
def bwdist_manhattan_single_entry(X, idx):
nz = np.argwhere(X==1)
return np.abs((idx-nz).sum(1)).min()
Sample run -
In [143]: bwdist_manhattan_single_entry(X, idx=(0,5))
Out[143]: 0
In [144]: bwdist_manhattan_single_entry(X, idx=(1,2))
Out[144]: 2
In [145]: bwdist_manhattan_single_entry(X, idx=(0,0))
Out[145]: 5
Optimize further on performance by extracting the boudary elements only off the blobs of `1s` -
from scipy.ndimage.morphology import binary_erosion
def bwdist_manhattan_single_entry_v2(X, idx):
k = np.ones((3,3),dtype=int)
nz = np.argwhere((X==1) & (~binary_erosion(X,k,border_value=1)))
return np.abs((idx-nz).sum(1)).min()
Number of elements in `nz` with this method would be smaller number than the earlier one, hence it improves. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 5,
"tags": "python, numpy, scipy"
} |
Expected Identifier with NSTimer
I have a block of code that calls an NSTimer from a singleton class. this is Viewcontroller.m
-(IBAction) start
{
[[[ApplicationManager instance].ticker [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showActivity) userInfo:nil repeats:YES]];
I have an error that says: Expected identifier Can anyone see why? or where i can add something to fix it? Thanks | You're going to want to get a book on Objective-C because this is all kinds of messed up. The code should look something like this. (at least if you're trying to do what I think you are)
- (IBAction) start
{
[ApplicationManager instance].ticker = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];
}
You had extraneous brackets at the beginning of the line, the beginning of the timer instance and at the end of the line, you were missing the statement's closing brace, and there was no equal sign between ticker and [NSTimer.. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -3,
"tags": "objective c"
} |
How to disable HMAC Authentication in C# Web API Rest Webservice
I am working on a C# Web API REST webservice that should be used for webhooks calls.
My problem is that when I try to connect to my webservice and call my controller, I always get an error message about ms-signature parameter. The only way to call my controller is to use HMAC authentication in the client side (ie SHA calculations on a secret key and the JSON data to be send to the webservice). It seems thata HMAC authentication is set by default, even if I don't want it.
I added a BasicAuthenticationFilter class for login and password check, and it works, but I still have the error message about ms-signature parameter before I can call my controller.
What should I do to disable HMAC authentication in my REST webservice? Basic Authentication by login and password is enough security for me. | Apparently, the answer was that if I do not want SHA authentication, I need to use Nu-Get to install AspNet.Webhooks.Receiver.Generic package rather than AspNet.WebHooks.Receiver.Custom package. Some changes must be applied to the code, but I finally get ride of SHA authetification which seems to be set by default in Custom WebHooks receivers. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "rest, authentication, asp.net web api, hmac"
} |
How to create a password field for a user model in Django?
I am completely new to Django. In my models.py, I want a User model to represent users that sign into the application.
I see how I could have fields like fname, lname, email, and username, (simply add "first_name = models.CharField(max_length=50)", for example) but how would I have a password field so that users can be authenticated? Obviously it's a bad practice to store passwords in clear text. | There is built in django.contrib.auth user models which has following fields (username, firstname, lastname, password, email, groups, user_permissions, is_active, is_staff, is_superuser, last_login, last_joined)
you can use this built in user model by creating user object and setting password for it.
from django.contrib.auth.models import User
user = User.objects.create(username="username", password = "password", email="email")
user.save()
some fields in django user models are optional except username, password and email and by default it sets some fields like is_superuser='f' if you don't specify.
it will automatically store password in hash function and In future If you want to update any user's password you can get and update
user = User.objects.get(username="username")
user.set_password("password")
user.save()
You can get an current online user instance by request.user | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "django, django models"
} |
Remove percent-escaped characters from string
How do I _remove_ , not decode, percent-escaped characters from a string using Swift. For instance:
`"hello%20there"` should become `"hellothere"`
EDIT:
I would like to replace multiple percent-escaped characters in a string. So: `"hello%20there%0Dperson"` should become `"hellothereperson"` | let string = originalString.replacingOccurrences(of: "%[0-9a-fA-F]{2}",
with: "",
options: .regularExpression,
range: nil) | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 0,
"tags": "ios, swift"
} |
I'm trying to use QTabBar::pane stylesheet from official Qt 4.8 docs
I read topic about qstylesheet and tried to implement it in my app.
tabsMain->setStyleSheet(
"QTabWidget::pane {"
" background-color: red; background-image: url(:/prefix1/images/patern.png); "
" background-position: top left;"
" background-repeat: repeat-xy;"
"}"
"QTabBar::tab:selected, QTabBar::tab:hover {"
" background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"
" stop: 0 #fafafa, stop: 0.4 #f4f4f4,"
" stop: 0.5 #e7e7e7, stop: 1.0 #fafafa);"
"}"
);
But nothing was changed. I tried to locate this item in the sources of Qt 4.8.1 (processing of style "QTabBar::pane") and that was all what I found:
QtSDK\QtSources\4.8.1\src\gui\styles\qstylesheetstyle.cpp
276: QStyle::SC_None, "pane"
It's not implemented in this version of Qt or maybe in my OS only? | The effect of stylesheets on Qt widgets depends on the selected QStyle.
When using your example stylesheet on a QTabWidget in Qt designer, the widget's pane is colored correctly in all QStyles except the GTK+-style and the Cleanlooks-style. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c++, css, qt"
} |
Why is the English phoneme /θ/ pronounced like /t/ in Indian accents but /s/ in Chinese accents?
The dental fricatives (/θ/ and /ð/; spelled with _th_ ) often present a challenge to non-native learners of English. Depending on the speaker's native language, different phonemes may be substituted. In Indian accented English, the dental fricatives are replaced with some variation of /t/ or /tʰ/; native Mandarin speakers substitute /s/ or /z/. (source)
This is surprising because both Hindi and Mandarin have consonants close to /s/, /z/, /t/, and /tʰ/. What causes Hindi and Mandarin speakers to replace /θ/ with different sounds then? | Here's a paper that's addressed a similar phenomenon of the different realizations of /θ/ between Cantonese and Sichuanese speakers, both of which are dialects of Chinese and share similar phonetic inventories.
The paper conducted production and perception comparisons between Cantonese and Sichuanese native speakers as to explore the reason for different choices of realization for /θ/ in English as L2.
The production tests came out somewhat insignificant. However, in perception tests, Cantonese speakers showed a significantly lower accuracy rates of discrimination between /θ/ and /f/ than Sichuanese speakers, and Sichuanese speakers between /θ/ and /s/, which aligned with their respective choice of realizations as discovered in a pilot test.
And the author argued with comparisons of the **function load** of different phonemes in two dialects that different outputs for one L2 from different L1 speakers are rather frequency-motivated than markedness-motivated. | stackexchange-linguistics | {
"answer_score": 12,
"question_score": 8,
"tags": "language acquisition, accent, mandarin, hindustani"
} |
Python Version issue
I am very new to Python. But **I install Python 3.5.0** from pkg file downloaded from python.org on my MAC (OS X El Capitan).
Issue is that when I go to Terminal and issue command
`python -V`
It shows me **Python 2.7.10** why it is so and how can I remove that version | Every Linux(Most of them Actually) comes bundled with python 2.7.x. So that's why it is showing you version 2.7.10.
Try running in terminal:
python3
You will get something like:
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
where 3.4.3 is the python version.
same goes for python2. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "python, macos, osx elcapitan"
} |
Haskell Warp/Wai and HTTPS -- how to make them work?
I have a basic hello-world application in Haskell Servant and Warp. This is not real code but for the sake of simplicity let's say I'm using it:
import Network.Wai
import Network.Wai.Handler.Warp
import Servant
personAPI :: Proxy PersonAPI
personAPI = Proxy
server :: Server PersonAPI
server = return people
app :: Application
app = serve personAPI server
serveApp :: IO ()
serveApp = run 80 app
It works fine on a server. With http.
I'm not using nginx or apache, I run it as-is and at this point it's fine for me.
But with https it won't load the page. I've installed https certificate but I gathered that I should somehow setup warp/wai to use it, because by default it won't use it. There's shortage of information about this - warp/wai and SSL, I haven't found anything. Could anyone help me? | I guess the easiest way is using the warp-tls library - settup your certificate files in the `TLSSettings` (I would try `tlsSettings` first) and use `runTLS` instead of `run`:
serveApp :: IO ()
serveApp = do
let tls = tlsSettings "pathToCert" "pathToKey"
runTLS tls (setPort 443 defaultSettings) app | stackexchange-stackoverflow | {
"answer_score": 12,
"question_score": 12,
"tags": "haskell, ssl, https, haskell warp"
} |
Why HTML tags are replaced by '+AD-'?
I have an HTML file that looks proper, but when I run a find and replace on it, I get the file changes to the following. I tried resaving the file through windows notepad and setting the Encoding, but i still get these weird characters.
Before:
<TABLE width='100%' border='0' bgcolor='#6699cc' cellspacing='0' cellpadding='0' ...
After:
+ADw-TABLE width+AD0-'100+ACU-' border+AD0-'0' bgcolor+AD0-'+ACM-6699cc' cellspacing+AD0-'0' cellpadding+AD0-'0' ... | You need to set the Encoding correctly.
That appears to be UTF-7.
> UTF-7 is used by less than 0.003% of websites.[1] UTF-8 has since 2009 been the dominant encoding (of any kind, not just of Unicode encodings) for the World Wide Web (and declared mandatory "for all things" by WHATWG[2]). | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "notepad++"
} |
Is the format be+on+trial grammatically correct?
See, for example, the following example;
> He **is on trial** for selling illicit goods in his store.
Is that sentence grammatically sound or should it better be like;
> He **is _put_ on trial** for selling illicit goods in his store.
? According to Google N-grams, the original is more frequent. See is on trial,is put on trial. | "Is on trial" is the common phrase and perfectly correct. The passive "is put" is odd in the example you give, using the present tense. The verb "put" indicates a single act, but you want to talk about an ongoing state. You could "put" in the past tense:
> John is on trial for murder
>
> John was put on trial for murder three weeks ago. | stackexchange-ell | {
"answer_score": 3,
"question_score": 0,
"tags": "sentence construction, verbs, sentence structure"
} |
Disable scrollbar
If you go to < you will notice that there is a disabled scrollbar.
On my site, to avoid annoying the user with page shifting, I want a scrollbar on every page. But, if the page truly does not need to scroll have the scrollbar disabled.
This seems like a trivial task, but I can't seem to find the solution. Perhaps I'm just missing something.
Anyway, can anyone help with this issue? Thanks. | `overflow: auto` makes the scrollbar appear when needed and disappear when not. For the scrollbar to always appear, use "scroll"
body {
overflow-y: scroll;
} | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 2,
"tags": "javascript, html, layout, scrollbar"
} |
String object to ArrayList object
the user enters 2 sting, which are stored in variable a and b. Now there are many ArrayList present in the program, we have to check if there is an ArrayList present with the name stored in variable a. So how can I do that?
public static void root(String a,String b)
{
ArrayList chicago=new ArrayList();
chicago.add("newyork");
chicago.add("new jersy");
chicago.add("dallas");
ArrayList buffalo=new ArrayList();
buffalo.add("arlington");
buffalo.add("california");
buffalo.add("dallas");
ArrayList newyork=new ArrayList();
newyork.add("chicago");
newyork.add("paris");
newyork.add("nigara");
ArrayList stations=new ArrayList();
stations.add(chicago);
stations.add(buffalo);
stations.add(newyork);
if(stations.contains(a))
{
}
} | Use something like a `HashMap<String, List<String>>`. The keys in the `HashMap` could be the strings that you are using as names here.
Map<String,List<String>> map = new HashMap<>();
ArrayList<String> chicago=new ArrayList<>();
chicago.add("newyork");
chicago.add("new jersy");
chicago.add("dallas");
map.put("chicago", chicago);
and so on.
Then the condition that you want to check will be
if (map.containsKey(a) && map.get(a).contains(b)) {
...
} | stackexchange-stackoverflow | {
"answer_score": -1,
"question_score": 0,
"tags": "java, arrays, collections"
} |
How does one place the tag R on the ignore list?
I observe that entering R in the box, yields other tags, containing R, but R itself does not show. | The dropdown is unnecessary to use when adding an ignored tag. Just enter "R" in the field, and hit the "Add" button, and it'll be complete. | stackexchange-meta | {
"answer_score": 3,
"question_score": 1,
"tags": "support, ignored tags"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.