qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
46,804,566 | I wrote this code to print all prime numbers between 3 and 'n' inputted by the user, but upon running, it produces nothing.
Can you please help?
```
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
for (int candidate = 3; candidate < n; ++candidate)
{
bool isPrime = true;
for (int x = 2; x < n; x++)
{
if (candidate % x == 0)
{
isPrime = false;
}
}
if (isPrime)
{
cout << n << "";
}
}
}
``` | 2017/10/18 | [
"https://Stackoverflow.com/questions/46804566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8794095/"
] | One thing you should know. For checking whether n is prime if we start checking by division operation then you shouldn't check more than `sqrt(n)`.
```
for (int candidate = 3; candidate < n; ++candidate)
{
bool isPrime = true;
for (int x = 2; x*x < candidate; x++)
{
if (candidate % x == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
cout << candidate << "";
}
}
```
### Better way is to use [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) for this:
```
isPrime: initialize with all true
for(int i=2;i*i<=n;i++)
for(int j =i*i;j<=n;j+=i)
isPrime[j]=false; // the if was not needed.
```
Now you know which are primes between 3 and `n`. | 1. It's not recommended to use using namespace std; — because this imports all of the identifiers from std. See this question on [Stack Overflow](https://stackoverflow.com/q/1452721).
2. Should the end condition of the second loop be `candidate` instead of `n`, i.e.
```
for (int x = 2; x < candidate; x++)//not before N prime numbers divine up to them
{
if (candidate % x == 0)
isPrime = false;
}
```
3. Shouldn't you put out `candidate` instead of `n` |
201,357 | For which $a\in {\bf R}$ is $|x|^a$ differentiable at $x=0$ and what is the derivative there? | 2012/09/23 | [
"https://math.stackexchange.com/questions/201357",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/32940/"
] | **Hint:** Let $a\gt 1$. Calculate $\displaystyle\lim\_{x\to 0} \frac{|x|^a-0}{x-0}$. It is useful to work separately with the limit from the right and the limit from the left.
If $x\gt 0$, then $\dfrac{|x|^a-0}{x-0}=\dfrac{x^a}{x}=x^{a-1}$.
If $x\lt 0$, then $\dfrac{|x|^a-0}{x-0}=\dfrac{|x|^a}{-|x|}=-|x|^{a-1}$.
Now we need to show that the limit does not exist when $a\le 1$. For $a=1$, we are working with the familiar absolute value function, and the limit of the differential quotient from the right is $1$, while the limit from the left is $-1$.
If $a\lt 1$, the differential quotient blows up as $x$ approaches $0$ from the right. | By definition, $f$ is called differentiable at the point $x\_0$, if its increment $Δf=f(x\_0+h)−f(x\_0)$ may be represented as $$f(x\_0+h)−f(x\_0)=f'(x\_0)h+α(x\_0,h),$$
where $\alpha$ satisfies
$|\alpha(x\_0,h)|=o(|h|),\quad h\rightarrow 0$. Thus is sufficient to write increment for $f(x)=|x|^\alpha$ at point $x\_0=0$ for $h>0$ and $h<0$ |
8,075,248 | I want to write a macro to write a string, using the compile-time optimisation of knowing the length of a string literal. But I need to detect misuse, using pointers.
Here's what I mean:
```
void transmit(const char *data, int length);
#define tx_string(x) transmit((x), sizeof(x) -1)
void func(char *badmsg) {
tx_string("GO"); // ok
tx_string(badmsg); // not OK
}
```
With the second call, the size will be nonsense (sizeof a pointer).
I want to produce a compile-time error if I attempt to use tx\_string on anything other than a string literal. This is using gcc; is there some gcc thing I can use to do this?
Edit: I work with data buffers that may contain nulls or not be terminated by nulls. I REALLY want to prevent pointers being used for this, and prevent run-time `strlen()` use.
Edit 2:
Here's an example which would cause a problem.
I'll invent an imaginary protocol where I have to tell a 16-bit microcontroller an address using the command GO followed by an address as 16-bit raw (two 8-bit characters), and I want to go from address 0.
```
#define GOSEQ "GO\000\000"
void func(void) {
char *bad = GOSEQ;
tx_string(GOSEQ); // ok, sends 4 bytes: GO and two zero bytes
tx_string(bad); // bad, using runtime strlen sends two characters "GO"
}
```
I feel sure there must be some kind of gcc builtin check for this. I see the Linux kernel sources using compile-time distinction tricks like this a lot.. but can't lay my hands on a specific one quickly.
So far "Windows programmer"'s idea looks good, but a more meaningful compile-time error would be a bonus. | 2011/11/10 | [
"https://Stackoverflow.com/questions/8075248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14200/"
] | You can do this:
```
#define tx_string(x) transmit(x, strlen(x)) // No need for extra parentheses
```
GCC will optimize out the `strlen` call, and I'm sure other compilers will too. Don't waste your time on this stuff.
**Test file:**
```
#include <string.h>
void transmit(const char *, size_t);
#define tx_string(x) transmit(x, strlen(x))
void func(void)
{
tx_string("abcdef");
}
```
**Resulting assembly:**
I trimmed noise out of the assembly, this is the important stuff. Notice that it never calls `strlen`, instead it just uses the number 6:
```
.LC0:
.string "abcdef"
func:
movl $6, %esi
movl $.LC0, %edi
jmp transmit
``` | ```
#define tx_string(x) ("i came, i concatenated, i discarded " x, transmit((x), sizeof(x) - 1))
```
Not quite perfect because some joker could call tx\_string(+1) |
84,125 | All of a sudden, the power supply of a server started to smell real bad. One of the hot swappable power supply units died. We replaced it, booted up Windows Server 2003 to find out that 2 out of 4 drives in a RAID 5 configuration had died.
We're also getting MACHINE\_CHECK\_EXCEPTION BSOD's everyone once in a while.
How realistic is it that the power supply did this to the RAID? The RAID was confirmed to be working minutes before this happened (we were using the RAID right before we noticed the awful smell).
Thanks for any advice given! :) | 2009/11/12 | [
"https://serverfault.com/questions/84125",
"https://serverfault.com",
"https://serverfault.com/users/24088/"
] | Although it shouldn't happen with a well designed power supply the reality is that this does happen all too often. As the unit is dying it may lose voltage regulation capability, resulting in over-voltage power being supplied to the machine. If you've good cooked drives as a result you need to be prepared for other components to fail as well. Ideally the server should be taken off line and stress tested but who has the tools to do that these days?
Assuming you have redundant power supplies, rather than just a single hot swap unit, you would be well advised to get hold of another power cable as well. After all, there's no point in having such gear if you're not going to be able to use it properly. | While it's possible that a bad power supply could potentially damage components I think this is unlikely. If the two drives were the only two drives on a particular power line then I would suspect that the power supply may have sent more than 12v down that line. Otherwise it's probably more likely that you had a few bad drives in your array that you weren't aware of. Powering them down just manifested the problem. Anytime you stop a drive that's been spinning non-stop for years you run the risk that it may not restart properly. |
22,207,256 | I began making changes to my codebase, not realizing I was on an old topic branch. To transfer them, I wanted to stash them and then apply them to a new branch off of master. I used `git stash pop` to transfer work-in-progress changes to this new branch, forgetting that I hadn't pulled new changes into master before creating the new branch. This resulted in a bunch of merge conflicts and loss of a clean stash of my changes (since I used pop).
Once I recreate the new branch correctly, how I can I recover my stashed changes to apply them properly? | 2014/03/05 | [
"https://Stackoverflow.com/questions/22207256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/807674/"
] | ```
git checkout -f
```
must work, if your previous state is clean.
CAUTION: Beware–you'll lose all untracked changes to your files. | If you're like me and had **unstaged changes that you want to preserve**, you can avoid losing that work by checking out a known stable version of each individual file from the `stash`. Hopefully those files are different than the ones you were working on. Also, this is why we use small commits as we go, dumb dumb.
```bash
git checkout main -- <file_with_conflicts>
``` |
58,601,833 | I'm fresh to GCP and i'm using my company's billing. But i'm not sure if I do those tutorial, it will cost money or not.
[enter image description here](https://i.stack.imgur.com/j6e8Q.png)
So this is one of the tutorial about App Engine Quickstart. It will need to deploy an python app balabalabala.
My question is, all those quickstart tutorial, will they cost money?
Thanks for all your help!~
[enter image description here](https://i.stack.imgur.com/ODDLQ.png) | 2019/10/29 | [
"https://Stackoverflow.com/questions/58601833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10779399/"
] | Google Cloud Platform (GCP) provides a free tier for [12-months with $300 credits](https://cloud.google.com/free/docs/gcp-free-tier) to spend, also in this documentation you can check the limits. Furthermore, you can spend this credits in any GCP product. | >
>
> >
> > GCP Free Tier
> > The Google Cloud Platform Free Tier gives you free resources to learn about Google Cloud Platform (GCP) services by trying them on your own. Whether you're completely new to the platform and need to learn the basics, or you're an established customer and want to experiment with new solutions, the GCP Free Tier has you covered.
> >
> >
> >
>
>
>
The GCP Free Tier has two parts:
* List item
A 12-month free trial with $300 credit to use with any GCP services.
**Always Free, which provides limited access to many common GCP resources, free of charge.** |
24,800,843 | Is there any difference between two `SELECTs` from database or single `SELECT with LEFT Join`?
I am limited by number of queries per hour and I am developing my own application.
`"SELECT * FROM table"` represents one query?
`"SELECT * FROM table LEFT JOIN another_table ON table.column=another_table.column2'"` represents one query too?
Are `UPDATE`, `INSERT` and `DELETE` considered query?
Thanks a lot. If my post is not ok, I can delete. | 2014/07/17 | [
"https://Stackoverflow.com/questions/24800843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2571001/"
] | If you have limited number of queries, than `LEFT JOIN` is better, since it's only one query (one connection to database). And yes, `UPDATE`, `INSERT`, `DELETE` is queries too. But You can insert multiple entries with single query. | Yes, joining tables is one query. Splitting that query and executing separately will take more time. |
54,215,582 | I am solving a challenge on hackerrank. It's printing a number in spiral pattern decreasing it's value at each circle completion.
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
```
//Printing Pattern using Loops
/* for eg. for n = 4
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
*/
//Author: Arvind Bakshi
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int n,row,col,size;
scanf("%d", &n);
// Complete the code to print the pattern.
size=2*n-1;
int arr[size][size];
//n=n+1;
while(n>0){
row=0;
col=0;
while(col<size){
arr[row][col] = n;
col++;
}
col=size-1;
row=0;
while(row<size){
arr[row][col]=n;
row++;
}
row = size-1;
col = size-1;
while (col >=0) {
arr[row][col] = n;
col--;
}
col = 0;
row = size-1;
while (row >=0) {
arr[row][col] = n;
row--;
}
n--;
}
for(row=0;row<size;row++){
for(col=0;col<size;col++){
printf("%d",arr[row][col]);
}
printf("\n");
}
return 0;
}
```
Expected output is
```
2 2 2
2 1 2
2 2 2
```
I am getting
```
111
101
111
```
There is numerous code available for it online, I just want to know my mistake, where I am doing wrong. Please don't mark it as a repeat. | 2019/01/16 | [
"https://Stackoverflow.com/questions/54215582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6475857/"
] | ```
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int n;
scanf("%d", &n);
for(int i = n; i >= 1; i--){
for(int j = n; j > i; j--)
printf("%d ", j);
for(int j = 1; j <= 2 * i - 1; j++)
printf("%d ", i);
for(int j = i + 1; j <= n; j++)
printf("%d ", j);
printf("\n");
}
for(int i = 1; i < n; i++){
for(int j = n; j > i; j--)
printf("%d ", j);
for(int j = 1; j <= 2 * i - 1; j++)
printf("%d ", i + 1);
for(int j = i + 1; j <= n; j++)
printf("%d ", j);
printf("\n");
}
return 0;
}
``` | ```
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
for(int i = 1; i<n*2; i++)
{
for(int j = 1; j<n*2; j++)
{
int a = i, b = j;
if(a>n) a = n*2-a;
if(b>n) b = n*2-b;
a = (a<b)? a:b;
printf("%d ",n-a+1);
}
printf("\n");
}
return 0;
}
``` |
36,700,907 | i have a cell (A1) linked to real-time data (=Tickers!Z12). i want to capture all of the price range in a five minute period. my issue is i'm trying to use the Worksheet\_Change method but it wont update when the values change if the cell (A1) is formulated. it works fine if i manually change the values. but i need to capture values that are being generated by the formula and then copy & paste the values in column B everytime the values change. here's what i have so far.
```
Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False
Application.EnableEvents = False
If Range("A1").value <> Range("B2").value Then
Range("A1").Select
Selection.Copy
With ActiveSheet
LastRow = .Cells(.rows.Count, "B").End(xlUp).row + 1
.Cells(LastRow, 2).Select
Selection.PasteSpecial Paste:=xlPasteValues
End With
End If
Application.CutCopyMode = False
Application.EnableEvents = True
End Sub
``` | 2016/04/18 | [
"https://Stackoverflow.com/questions/36700907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5403867/"
] | **Note**: I changed this answer to reflect an edit of the question. Specifically, I added a `split()` to separate the strings in the nested lists into two strings (`issueId` and `status`).
---
I would use list and dictionary comprehensions to turn your list of lists into a list of dictionaries with the keys `issueId` and `status`:
```
resultList = [['TWP-883 PASS'], ['TWP-1080 PASS'], ['TWP-1081 PASS']]
result_dicts = [{("issueId","status")[x[0]]:x[1] for x in enumerate(lst[0].split())} for lst in resultList]
```
Lookups can now be done in this way:
```
>>> result_dicts[0]["status"]
'PASS'
>>> result_dicts[0]["issueId"]
'TWP-883'
>>> result_dicts[1]
{'status': 'PASS', 'issueId': 'TWP-1080'}
>>>
```
To declare variables for each value in each dictionary in the list and print them, use the code below:
```
for entry in result_dicts:
issueId = entry["issueId"]
status = entry["status"]
print("The status of {0: <10} is {1}".format(issueId, status))
```
Output:
```
The status of TWP-883 is PASS
The status of TWP-1080 is PASS
The status of TWP-1081 is PASS
``` | You can get the list of the strings by
```
issueId = [y for x in resultList for (i,y) in enumerate(x.split()) if(i%2==0)]
status = [y for x in resultList for (i,y) in enumerate(x.split()) if(i%2==1)]
```
to go through every issueID and corrosponding status you can use
```
for id,st in zip(issueId,status):
print(id, " : ", st)
``` |
2,690 | I have to download a file from this [link](http://www.vim.org/scripts/download_script.phpsrc_id=11834). The file download is a zip file which I will have to unzip in the current folder.
Normally, I would download it first, then run the unzip command.
```
wget http://www.vim.org/scripts/download_script.php?src_id=11834 -O temp.zip
unzip temp.zip
```
But in this way, I need to execute two commands, wait for the completion of first one to execute the next one, also, I must know the name of the file `temp.zip` to give it to `unzip`.
Is it possible to redirect output of `wget` to `unzip`? Something like
```
unzip < `wget http://www.vim.org/scripts/download_script.php?src_id=11834`
```
But it didn't work.
```
bash: `wget http://www.vim.org/scripts/download_script.php?src_id=11834 -O temp.zip`: ambiguous redirect
```
Also, `wget` got executed twice, and downloaded the file twice. | 2010/10/04 | [
"https://unix.stackexchange.com/questions/2690",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/2045/"
] | You have to download your files to a temp file, because (quoting the unzip man page):
>
> Archives read from standard input
> are not yet supported, except with
> funzip (and then only the first
> member of the archive can be
> extracted).
>
>
>
Just bring the commands together:
```
wget "http://www.vim.org/scripts/download_script.php?src_id=11834" -O temp.zip
unzip temp.zip
rm temp.zip
```
But in order to make it more flexible you should probably put it into a script so you save some typing and in order to make sure you don't accidentally overwrite something you could use the `mktemp` command to create a safe filename for your temp file:
```
#!/bin/bash
TMPFILE=`mktemp`
PWD=`pwd`
wget "$1" -O $TMPFILE
unzip -d $PWD $TMPFILE
rm $TMPFILE
``` | I don't think you even want to bother piping wget's output into unzip.
From the wikipedia ["ZIP (file format)"](http://en.wikipedia.org/wiki/ZIP_%28file_format%29) article:
>
> A ZIP file is identified by the presence of a central directory located at the end of the file.
>
>
>
wget has to completely finish the download before unzip can do any work, so they run sequentially, not interwoven as one might think. |
158,821 | I need a world that is hard, but not impossible, to live on but also to be found on. How can I best accomplish this?
I am working on a world sort of like the planet in the movie Predators. In the world I'm working on, a race uses it for military special-ops training. They take a death-row prisoner and drop them on this world with minimal gear/supplies and leave them there. Trainees are then tasked with hunting them down.
I want this world to be as difficult to live on, traverse, or track someone down on as possible without downright killing them immediately.
I want interesting or unconventional ideas, not just "A jungle world". I want ideas that will make a jungle look easy to traverse. Aspects about this world that, at first, seem irrelevant but render entire strategies useless. Details that turn this planet (or moon) into a living hell. | 2019/10/20 | [
"https://worldbuilding.stackexchange.com/questions/158821",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/69083/"
] | How about some planet with massive amounts of caves or old mines. Little different than jungle. And the underground nature would make things more 3-D. Also would interfere with a lot of radar, IR, lowlevel light surveillance. Also, perhaps interesting physical challenges for pursuers/pursued in terms of the mine/cave setting (sinkhole rivers, etc.). One interesting aspect could be occasional forays to the surface for food or just to change things up, and then returns into the caves. Call the planet "Warren" to give it some color. | I would go with an area (not planet since a single biome world is impossible to sustain a biosphere) of plains. A similar environment to the one we (and possibly the hunters) evolved in would be an ideal hunting/training ground. It is not that easy to survive there for an untrained human, although it would be possible, and it would also be good for hiding. lots of tall grass and human-sized creatures to confuse any heat scanners. There can be some other challenges for the warrior, such as some sort of plains predator similar to a lion or something. |
306,650 | I want to get product details from url key.
Is there a way to get product details from url\_key, I am new to Magento and could not find any such way, please help I tried below code but it is not working properly.
```
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->create('\Magento\Store\Model\StoreManagerInterface');
$storeIds = array_keys($storeManager->getStores());
$action = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\Action');
while($row = mysqli_fetch_assoc($result)) {
$updateAttributes = array();
echo $row["slug"];
echo "--->";
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('url_key',"URL_KEY_HERE");
$collection->addAttributeToSelect('*');
foreach ($collection as $product)
{
echo "id is ->".$product->getId();
echo "<br>";
}
}
``` | 2020/03/10 | [
"https://magento.stackexchange.com/questions/306650",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/29706/"
] | ```
$urlKey = "strive-shoulder-pack"; // add your url key which you want
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\Collection');
$productCollectionFactory->addAttributeToFilter('url_key',$urlKey);
$productCollectionFactory->addAttributeToSelect('*');
foreach ($productCollectionFactory as $product)
{
echo "id is ->".$product->getId();
echo "<br>";
print_r($product->getData());
echo "<br>";
}
```
[](https://i.stack.imgur.com/4Mkxb.jpg)
>
> **Note: Only Enable Product url can check so please enter proper enable product url key**
>
>
> | firstly don't use objectManager you can inject the used class in the construct:
```
public function __construct(\Magento\Catalog\Model\ProductFactory $productFactory)
{
$this->productFactory = $productFactory;
}
```
And after that in your class use loadByAttribute function
```
$product = $this->productFactory->create();
$product->loadByAttribute('url_key', $urlKey);
```
I want my answer to help you
With ObjectManager:
```
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productFactory = $objectManager->get('\Magento\Catalog\Model\ProductFactory');
$product = $productFactory->create();
$product->loadByAttribute('url_key', $urlKey);
``` |
15,605 | We are setting up a new (money) Gemach. To register as a charity, a bank account is now needed. We were told of this on Thursday around noon. We were unable (too busy getting ready for Yom Tov) to get to the bank on Thursday. Friday is a bank holiday. Are we allowed to open the account on Chol HaMoed?
On the one hand it seems that the answer to this question (already posed to the Rav but no answer yet) should be No because we are arranging to do the work on Chol HaMoed. On the other hand it is a need for the community and a need for a mitzva. | 2012/04/06 | [
"https://judaism.stackexchange.com/questions/15605",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/730/"
] | The usual rubric for answering this question is whether there's a financial loss involved.
If you can postpone the trip to the bank until after Hol HaMoed without losing money, then you should. If not, then it's mutar to do it on Hol HaMoed. | The Shulchan Aruch in Orach Chaim in [סימן תקמד - דין צרכי רבים בחל המועד](http://www.toratemetfreeware.com/online/f_01975_part_31.html#HtmpReportNum0014_L2) says:
>
> **א** צָרְכֵי רַבִּים מֻתָּר לַעֲשׂוֹתָהּ בְּחֹל הַמּוֹעֵד, כְּגוֹן לְתַקֵּן הַדְּרָכִים וּלְהָסִיר מֵהֶם הַמִּכְשׁוֹלוֹת; וּלְצַיֵּן הַקְּבָרוֹת כְּדֵי שֶׁיִּזָּהֲרוּ מֵהֶם הַכֹּהֲנִים; וּלְתַקֵּן הַמִּקְוָאוֹת.
>
>
> **הגה**: וְדַוְקָא צָרְכֵי רַבִּים כָּאֵלּוּ, שֶׁהֵם צְרִיכִים לְגוּף הָאָדָם, אֲבָל שְׁאָר צָרְכֵי רַבִּים כְּגוֹן בִּנְיַן בה''כ (בֵּית יוֹסֵף בְּשֵׁם תְּשׁוּבַת הָרַשְׁבָּ''א), אָסוּר לַעֲשׂוֹת בַּמּוֹעֵד; וְהוּא הַדִּין דְּלִשְׁאָר צָרְכֵי מִצְוָה אָסוּר לַעֲשׂוֹת מְלֶאכֶת אֻמָּן בַּמּוֹעֵד (ריב''ש סִימָן רכ''ו).
>
>
>
From what it says - and the Remo clarifies - it seems that the only *community work* allowed on Chol HaMoed is those activities that directly benefit the person's body; fixing the roads, preventing Cohanim from getting impure and fixing bathing houses / Mikvaot.
Proving a supply of money - or other goods - does not seem to be included.
That said, I'm not sure what *work* is involved in opening a bank account. It's a procedure that may involve a few signatures and possibly an initial deposit.
Signing documents seems to be allowed, as we see in the next Siman סימן תקמה - דיני כתיבה בחל המועד there's a long list of permissible documents, including:
>
> **ה** מֻתָּר לִכְתֹּב שְׁטַר קִדּוּשִׁין וְשִׁטְרֵי פְּסִיקְתָא, גִּטִּין וְשׁוֹבָרִים, דַּיְיתִיקֵי, מַתָּנוֹת, פְּרוֹזְבּוֹלִין, אִגְּרוֹת שׁוּם וְאִגְּרוֹת מָזוֹן
>
>
>
Depositing money doesn't seem worse than paying for something which is permissible.
So opening a bank account doesn't seem worse than going to the zoo and paying by credit card; both have nothing to do with the Chag and both involve some money-related signatures.
Reminder: [Mi Yodea](https://judaism.stackexchange.com/) is not for practical Halachic rulings; just for discussions. |
46,639,068 | I am trying to display a message once the user logs in.
In the case where number of characters exceed 8, how can I display only the first 8 characters of a name followed by ".." ? (Eg: Monalisa..)
```
new Vue({
el: '#app',
data: {
username: 'AVERYLONGGGNAMMEEE'
}
});
```
Here is my [jsfiddle demo](https://jsfiddle.net/inchrvndr/t2wm7qbh/) | 2017/10/09 | [
"https://Stackoverflow.com/questions/46639068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7409294/"
] | you want a computed property that check if the string is > 8 chars and make modifications and use that computed property in your template.
```
new Vue({
el: '#app',
data: {
username: 'AVERYLONGGGNAMMEEE'
},
computed: {
usernameLimited(){
if ( this.username.length > 8 ) {
return this.username.substring(0,8) + '...'
} else {
return this.username
}
}
}
})
``` | Think this way it can take care of one line. And checking for null values to avoid **'[Vue warn]: Error in render: “TypeError: Cannot read property 'length' of null” with .substring()'**
```
{{ username && username.length < 8 ? username : username.substring(0,8)+".." }}
``` |
64,490,249 | I have this code which it needs to throw and exception inside a Lambda:
```java
public static <T, E extends Exception> Consumer<T> consumerWrapper(
Consumer<T> consumer,
Class<E> clazz) {
return i -> {
try {
consumer.accept(i);
} catch (Exception ex) {
try {
E exCast = clazz.cast(ex);
System.err.println(
"Exception occured : " + exCast.getMessage());
} catch (ClassCastException ccEx) {
throw ex;
}
}
};
}
```
```java
public static void processConditions(@NotNull List<EntityCondition> conditions)
throws UnsatisfiedConditionException {
conditions.forEach(
consumerWrapper(
entityCondition -> {
throw new UnsatisfiedConditionException(entityCondition);
}, UnsatisfiedConditionException.class));
}
```
Even with this approach, compiling this would throw an error:
`UnsatisfiedConditionException; must be caught or declared to be thrown`
What could be wrong or missing here? | 2020/10/22 | [
"https://Stackoverflow.com/questions/64490249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13429959/"
] | In addition to what the other commenters already suggested, you should avoid using "magic" numbers like 97 and 32. Here is a more Pythonic solution:
```
def all_uppercase(s):
shift = ord('A') - ord('a')
return ''.join(chr(ord(c) + shift) if 'a' <= c <= 'z' else c
for c in s)
all_uppercase('Hello, world!')
#'HELLO, WORLD!'
``` | You have included the len(s) in the while loop if the index starts from 0
So, change the while loop like this:
```
while x<len(s):
``` |
54,161,034 | I have two tables as below
radcheck
```
+----+-------------------+--------------------+----+--------+
| id | username | attribute | op | value |
+----+-------------------+--------------------+----+--------+
| 1 | userA | Cleartext-Password | := | Apass |
| 2 | userB | Cleartext-Password | := | Bpass |
| 3 | DC:9F:DB:xx:xx:xx | Auth-Type | := | Accept |
| 4 | userC | Cleartext-Password | := | Cpass |
+----+-------------------+--------------------+----+--------+
```
radusergroup
```
+----------+------------+----------+
| username | groupname | priority |
+----------+------------+----------+
| userA | daily-plan | 1 |
| userA | disabled | 0 |
| userB | quota-plan | 1 |
| userC | disabled | 0 |
| userC | try | 1 |
+----------+------------+----------+
```
I use the below query to return results which lists usernames that are not part of disabled group but i would like to return another column in results called disabled with value as 1 if part of disabled group and 0 if not:
```
SELECT c.id, c.username, c.value, g.groupname
FROM radcheck c LEFT JOIN
radusergroup g
USING (username)
WHERE attribute = 'Cleartext-Password' AND
groupname <> 'disabled';
```
I tried multiple ways using triple left joins using below query but they dont seem to work, the groupname column in result is always of the first groupname found in radusergroup table:
```
SELECT c.id, c.username, c.value, g.groupname, (disabled.username IS NOT NULL) AS disabled
FROM radcheck c LEFT JOIN
radusergroup g
ON c.username = g.username LEFT JOIN
radusergroup disabled
ON disabled.username = c.username AND
disabled.groupname = 'disabled'
WHERE (c.username = g.username) AND
attribute = 'Cleartext-Password'
GROUP BY c.username;
```
the above outputs:
```
+----+----------+-------+------------+----------+
| id | username | value | groupname | disabled |
+----+----------+-------+------------+----------+
| 1 | userA | Apass | daily-plan | 1 |
| 2 | userB | Bpass | quota-plan | 0 |
| 4 | userC | Cpass | disabled | 1 |
+----+----------+-------+------------+----------+
``` | 2019/01/12 | [
"https://Stackoverflow.com/questions/54161034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10904992/"
] | Unfortunately it seems that Keras dataset lacks information about topics. You could use nltk version of the same dataset. You can get topic names there too.
Refer to <https://martin-thoma.com/nlp-reuters/> for details. | ```
['cocoa','grain','veg-oil','earn','acq','wheat','copper','housing','money-supply',
'coffee','sugar','trade','reserves','ship','cotton','carcass','crude','nat-gas',
'cpi','money-fx','interest','gnp','meal-feed','alum','oilseed','gold','tin',
'strategic-metal','livestock','retail','ipi','iron-steel','rubber','heat','jobs',
'lei','bop','zinc','orange','pet-chem','dlr','gas','silver','wpi','hog','lead']
```
Seem to be the labels as seen [here](https://github.com/keras-team/keras/issues/12072) |
1,475,580 | I am stuck solving the following limit. I know the answer is 5/4, I just can't get it. This is the steps I have done so far.
$\lim \_ \limits{x\to -\infty \:}\left(\sqrt{4\cdot \:x^2-5\cdot \:x}+2\cdot \:x\right)$
Multiply by Conjugate
$\lim \_ \limits{x\to -\infty \:}\left(\sqrt{4\cdot \:x^2-5\cdot \:x}+2\cdot \:x\right)\cdot \frac{\left(\sqrt{4\cdot \:\:x^2-5\cdot \:\:x}-2\cdot \:\:x\right)}{\left(\sqrt{4\cdot \:\:x^2-5\cdot \:\:x}-2\cdot \:\:x\right)}$
Multiply Out
$\lim\limits\_{x\to -\infty \:}\cdot \frac{\left(4\cdot \:\:\:x^2-5\cdot \:\:\:x-4\cdot \:\:x\right)}{\left(\sqrt{4\cdot \:\:x^2-5\cdot \:\:x}-2\cdot \:\:x\right)}$
Combine Like Terms
$\lim\limits\_{x\to -\infty \:}\cdot \frac{\left(4\cdot \:\:\:x^2-9\cdot \:\:x\right)}{\left(\sqrt{4\cdot \:\:x^2-5\cdot \:\:x}-2\cdot \:\:x\right)}$
Factor out x
$\lim\limits\_{x\to -\infty \:}\cdot \frac{x\left(4\cdot \:x-9\right)}{\left(\sqrt{x^2\left(4-\frac{5}{x}\right)}-2\cdot \:\:x\right)}$
Pull out x of sqrt and factor again
$\lim \limits\_{x\to -\infty \:}\cdot \frac{x\left(4\cdot \:x-9\right)}{x\left(\sqrt{\left(4-\frac{5}{x}\right)}-2\right)}$
Now cancel x terms
$\lim \limits\_{x\to -\infty \:}\frac{4\cdot \:\:x-9}{\sqrt{\left(4-\frac{5}{x}\right)}-2}$
Now I don't know what to do next.
If I plug in I get
$\frac{4\cdot \:\:\:-\infty \:-9}{\sqrt{\left(4-0\right)}-2}=\:\frac{-\infty \:}{0}$ Which doesn't equal $\frac{5}{4}$? | 2015/10/11 | [
"https://math.stackexchange.com/questions/1475580",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/279249/"
] | \begin{align\*}
\lim\_{x\to-\infty}\sqrt{4x^2-5x}+2x&=\lim\_{x\to-\infty}-2x\sqrt{1-\frac{5}{4x}}+2x\\
&=\lim\_{x\to-\infty}2x\left(1-\sqrt{1-\frac{5}{4x}}\right)\\
&=\lim\_{x\to-\infty}2x\cdot \frac{\frac5{4x}}{1+\sqrt{1-\frac{5}{4x}}}\\
&=5/4.
\end{align\*} | Somehow, you missed a square.
$$
(\sqrt{4x^2-5x})^2-(2x)^2=4x^2-5x-4x^2=-5x
$$
which radically simplifies the ensuing limit calculation,
$$
\lim\_{x\to-\infty}\frac{5|x|}{\sqrt{4x^2+5|x|}+2|x|}
=\lim\_{x\to-\infty}\frac{5}{\sqrt{4+5/|x|}+2}=\frac54
$$ |
31,291,249 | ```
<div class="modal-dialog" role="document">
<div class="modal-content login conatct_main" id="mdlcont">
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<button id="registrsubmit" name="registrsubmit" value="true" class="friends_log pull-right">Register</button>
</div>
</div>
</div>
</div>
</div>
```
The modal is not scrolling to top after a click. I tried scrolltop() method. It is not working . Can anyone help me on this?
![enter image description here][1] | 2015/07/08 | [
"https://Stackoverflow.com/questions/31291249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Judging by your image I'm guessing you're wanting to reposition the modal itself to move it off of the screen, as opposed to moving the viewport (which is what scrollTop would do). Check out [jQuery's offset function](http://api.jquery.com/offset/#offset-coordinates). For example, you could do
```
$('#foo').offset({
top:-$('#foo').outerHeight()
});
```
Or if you want a smooth scrolling action, use the [animate function](http://api.jquery.com/animate/):
```
$('#foo').animate({
top:-$('#foo').outerHeight()
});
``` | On bootstrap v5.1.2,
if you have already allowed scrolling by adding the tag `modal-dialog-scrollable`, simply target the modal body as shown below:
```
$('#myModal .modal-body').scrollTop(0);
```
This worked for me |
27,256,062 | Is there ever a situation where it makes more sense to create a functor than to use a lambda?
I know my question is effectively the reverse of [when to use a lambda over a functor](https://stackoverflow.com/questions/4686507/lambda-expression-vs-functor-in-c), but I can't think of a situation in practice where a functor would be *preferred* over a lambda. Any thoughts on this? | 2014/12/02 | [
"https://Stackoverflow.com/questions/27256062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2043536/"
] | I would consider using a functor over a lambda when I
* want more than one instance.
* have to do advanced resource handling.
* need to refer to the functor as a type. For example, to pass it as a template parameter.
* (related) can give a meaningful and generally useful name to the *type* (as opposed to the *instance*).
* find that the logic can be written cleaner when split up into sub-functions. In a lambda, we have to write everything into a single function. | I could think of two cases:
1. When functor carries internal state, thus there is a non-trivial life time issue with the functor. It keeps "something" between the uses
2. When you have to use same code all over the place, writing and keeping it as a functor in its own header might be a good idea from maintenance point-of-view |
36,854,676 | All, I have a jar file. and I know it is built from a swing project. Becuase I already view some source code of class files of the jar. I want to know if there exists any tools help to convert the jar back to the source project in the eclipse? Thanks.
[](https://i.stack.imgur.com/oFscC.png) | 2016/04/26 | [
"https://Stackoverflow.com/questions/36854676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1553519/"
] | <http://jd.benow.ca>
1. Drag and drop jar file into JD GUI decompiler
2. select File-> Save all sources | 7zip will allow you to view the contents of the jar, including source files if they are there. Lots of decompilers exist to decompile the class files. My favorite is jd-gui (<http://jd.benow.ca/>).
You can also add a jar in Eclipse by right-clicking on the Project → Build Path → Configure Build Path. Uthen under tje Libraries tab, click Add Jars or Add External JARs and select the jar file. Alternatively you can add a lib directory to your project and put a copy of the jar there.
But as far as converting a jar file into an eclipse project, you could extract the files with 7zip or other tool, then import them into a new eclipse project. |
2,902 | I've had my furnace serviced in time for winter, but what other things should I consider doing before the snow and the ice come? | 2010/11/17 | [
"https://diy.stackexchange.com/questions/2902",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/733/"
] | Drain all your garden hoses and insulate external faucets with [these](http://rads.stackoverflow.com/amzn/click/B002GKC2VW).
 | Blow out your sprinkler (irrigation) lines so the water does not freeze and break the line or sprinkler heads. |
18,716,675 | I want to filter the auto complete results from my suggester
Lets say I have a book table
```
Table (Id Guid, BookName String, BookOwner id)
```
I want each user to get a list to autocomplete from its own books.
I want to add something like the
```
http://.../solr/vault/suggest?q=c&fq=BookOwner:3
```
This doesnt work.
What other ways do I have to implement it? | 2013/09/10 | [
"https://Stackoverflow.com/questions/18716675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/450602/"
] | You need to implement Facebook's client side APIs according to their documentation and the environment you are deploying your client app to (Browser vs iOS vs Android). This includes registering your app with them. Your registered app will direct the user to go through an authentication flow and at the end of it your client app will have access to a short-lived access token. Facebook has multiple types of access tokens, but the one it sounds like you're interested in is called a User Access Token since it identifies an authorized user.
Pass the access token to your Cloud Endpoints API via a field or header. Inside of your API code receive the access token and implement Facebook's API that checks the validity of the access token. The first answer on [this SO question](https://stackoverflow.com/questions/5406859/facebook-access-token-server-side-validation-for-iphone-app) makes it look rather easy, but you probably want to reference their documentation again. If that check passes then you would run your API code, otherwise throw an exception.
You will typically also want to implement a caching mechanism to prevent calling the Facebook server side validation API for each Cloud Endpoints request.
Finally, I mentioned that your client app has a short lived token. If you have a client app that is browser-based then you will probably want to upgrade that to a long lived token. Facebook has a flow for that as well which involves your API code requesting a long lived token with the short lived one. You would then need to transfer that long lived token back to the client app to use for future Cloud Endpoints API calls.
If your client app is iOS or Android based then your tokens are managed by Facebook code and you simply request access tokens from the respective APIs when you need them. | So I actually tried to implement that custom authentication flow. It seems working fine although there might be further consideration on security side.
First, user go to my application and authenticate with facebook, the application got his user\_id and access\_token. Then the application call auth API to the server with these info.
```py
class AuthAPI(remote.Service):
@classmethod
def validate_facebook_user(cls, user_id, user_token):
try:
graph = facebook.GraphAPI(user_token)
profile = graph.get_object("me", fields='email, first_name, last_name, username')
except facebook.GraphAPIError, e:
return (None, None, str(e))
if (profile is not None):
# Check if match user_id
if (profile.get('id', '') == user_id):
# Check if user exists in our own datastore
(user, token) = User.get_by_facebook_id(user_id, 'auth', user_token)
# Create new user if not
if user is None:
#print 'Create new user'
username = profile.get('username', '')
password = security.generate_random_string(length=20)
unique_properties = ['email_address']
if (username != ''):
(is_created, user) = User.create_user(
username,
unique_properties,
email_address = profile.get('email', ''),
name = profile.get('first_name', ''),
last_name = profile.get('last_name', ''),
password_raw = password,
facebook_id = user_id,
facebook_token = user_token,
verified=False,
)
if is_created==False:
return (None, None, 'Cannot create user')
token_str = User.create_auth_token(user.get_id())
#print (user, token_str)
# Return if user exists
if token is not None:
return (user, token.token, 'Successfully logged in')
else:
return (None, None, 'Invalid token')
return (None, None, 'Invalid facebook id and token')
# Return a user_id and token if authenticated successfully
LOGIN_REQ = endpoints.ResourceContainer(MessageCommon,
type=messages.StringField(2, required=True),
user_id=messages.StringField(3, required=False),
token=messages.StringField(4, required=False))
@endpoints.method(LOGIN_REQ, MessageCommon,
path='login', http_method='POST', name='login')
def login(self, request):
type = request.type
result = MessageCommon()
# TODO: Change to enum type if we have multiple auth ways
if (type == "facebook"):
# Facebook user validation
user_id = request.user_id
access_token = request.token
(user_obj, auth_token, msg) = self.validate_facebook_user(user_id, access_token)
# If we can get user data
if (user_obj is not None and auth_token is not None):
print (user_obj, auth_token)
result.success = True
result.message = msg
result.data = json.dumps({
'user_id': user_obj.get_id(),
'user_token': auth_token
})
# If we cannot
else:
result.success = False
result.message = msg
return result
```
In addition to this, you might want to implement the normal user authentication flow following instruction here: <http://blog.abahgat.com/2013/01/07/user-authentication-with-webapp2-on-google-app-engine/> .
This is because the user\_id and user\_token that I obtain was provided by **webapp2\_extras.appengine.auth**.
Implementation of User.get\_by\_facebook\_id:
```py
class User(webapp2_extras.appengine.auth.models.User):
@classmethod
def get_by_facebook_id(cls, fb_id, subj='auth', fb_token=""):
u = cls.query(cls.facebook_id==fb_id).get()
if u is not None:
user_id = u.key.id()
# TODO: something better here, now just append the facebook_token to a prefix
token_str = "fbtk" + str(fb_token)
# get this token if it exists
token_key = cls.token_model.get(user_id, subj, token_str)
print token_key, fb_token
if token_key is None:
# return a token that created from access_token string
if (fb_token == ""):
return (None, None)
else:
token = cls.token_model.create(user_id, subj, token_str)
else:
token = token_key
return (u, token)
return (None, None)
```
Server verify if the user is authenticated with facebook once more time. If it passes, user is considered logged in. In this case, server pass back a user\_token (generated based on facebook\_token) and user\_id from our datastore.
Any further API calls should use this user\_id and user\_token
```py
def get_request_class(messageCls):
return endpoints.ResourceContainer(messageCls,
user_id=messages.IntegerField(2, required=False),
user_token=messages.StringField(3, required=False))
def authenticated_required(endpoint_method):
"""
Decorator that check if API calls are authenticated
"""
def check_login(self, request, *args, **kwargs):
try:
user_id = request.user_id
user_token = request.user_token
if (user_id is not None and user_token is not None):
# Validate user
(user, timestamp) = User.get_by_auth_token(user_id, user_token)
if user is not None:
return endpoint_method(self, request, user, *args, **kwargs )
raise endpoints.UnauthorizedException('Invalid user_id or access_token')
except:
raise endpoints.UnauthorizedException('Invalid access token')
@endpoints.api(name='blah', version='v1', allowed_client_ids = env.CLIENT_IDS, auth=AUTH_CONFIG)
class BlahApi(remote.Service):
# Add user_id/user_token to the request
Blah_Req = get_request_class(message_types.VoidMessage)
@endpoints.method(Blah_Req, BlahMessage, path='list', name='list')
@authenticated_required
def blah_list(self, request, user):
newMessage = BlahMessage(Blah.query().get())
return newMessage
```
Note:
* I am using this library to handle facebook authentication checking on server: <https://github.com/pythonforfacebook/facebook-sdk> |
53,894,343 | In my table view cell I have a UIView that shows 5 stars rating. Users can tap it to change the rating. The problem is, when users change the rating the `didSelectRow` on the table view row is triggered. What is the best way of preventing this? Is there a way to block the UIView from passing the touch events to the table view? I still want the table view cell to be tappable outside the rating view. | 2018/12/22 | [
"https://Stackoverflow.com/questions/53894343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/297131/"
] | 1.If you are using buttons in ratting view for ratting?
if yes then **increase button size**
2.Otherwise you have to **increase cell height** for ratting view clickable.
I request you to provide **screenshot** of your tableview
and Answer if you are using any library for ratting. | You could override `UIResponder`'s `next` property to break the responder chain:
```
extension CosmosView {
open override var next: UIResponder? {
return nil
}
}
```
See <https://developer.apple.com/documentation/uikit/uiresponder/1621099-next>. |
53,079 | Are the 144,000 in Revelation 7 the same as those spoken of in Chapter 14?
While there are similarities there are also differences. The 144,000 of chapter 7 are Jewish as indicated belonging to the 12 tribes with the seal of the Father. The 144,000 of chapter 14 have the Father and Son's seal and were redeemed from the earth. | 2020/11/17 | [
"https://hermeneutics.stackexchange.com/questions/53079",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/39176/"
] | In the NT the apostle Paul and others are at pains to eliminate the distinction between literal and spiritual Israel, or "Israel of God". We note the following:
* Rom 9:6-8 - It is not as though God’s word has failed. For not all who are descended from Israel are Israel. Nor because they are Abraham’s descendants are they all his children ... So it is not the children of the flesh who are God’s children, but it is the children of the promise who are regarded as offspring.
* Eph 2:11-13 - Therefore remember that formerly you who are Gentiles in the flesh and called uncircumcised by the so-called circumcision (that done in the body by human hands)— remember that at that time you were separate from Christ, alienated from the commonwealth of Israel, and strangers to the covenants of the promise, without hope and without God in the world. But now in Christ Jesus you who once were far away have been brought near through the blood of Christ.
* Gal 3:26-29 - You are all sons of God through faith in Christ Jesus. For all of you who were baptized into Christ have clothed yourselves with Christ. There is neither Jew nor Greek, slave nor free, male nor female, for you are all one in Christ Jesus. And if you belong to Christ, then you are Abraham’s seed and heirs according to the promise.
* Gal 6:15, 16 - For neither circumcision nor uncircumcision means anything. What counts is a new creation. Peace and mercy to all who walk by this rule, even to the Israel of God.
* Mark 11:17 - Then Jesus began to teach them, and He declared, “Is it not written: ‘My house will be called a house of prayer for all the nations’? ...
The same can be seen in Rev 7 with the description of the 144,000 and their 12 "tribes": such a list of the 12 tribes occurs nowhere in the OT and is unique:
* There is no tribe of Dan
* There is a tribe of Joseph and a tribes of Manasseh and Ephraim
* The order is also quite different - Judah comes first which was never the case in the OT
* Levi is listed as a "tribe" despite no being such in the OT
However, we note that in both Rev 7 & 14, the 144,000 have the single distinguishing characteristic of having the "seal of God" (Rev 7:3, 4, 14:1) on their foreheads, namely the Name of God.
The "seal of God" denotes the protection enjoyed by God’s faithful people (Rev 7:2, 9:4). Thus, God’s people are miraculously preserved who have the seal of God which denotes the Name of the Lamb and the Father written on the forehead (Rev 14:2; see also Ex 13:9, 28:38, Eze 9:4).
This seal of God is shown to be the Holy Spirit is several places such as 2 Cor 1:22, Eph 1:13, 14, 4:30; and this seal is the mark of ownership of God's people, 2 Tim 2:19. Thus, the 144,000 are those who (Rev 14:3-5) -
* had been redeemed from the earth.
* have not been defiled with women, for they are virgins.
* follow the Lamb wherever He goes.
* have been redeemed from among men as firstfruits to God and to the Lamb.
* no lie was found in their mouths;
* are blameless.
* Are sealed in their foreheads with the Name of the Lamb and the Father's Name by the Holy Spirit | No 144000 in chap 7 are specifically named by tribe. The 144000 are distinct, these are the ones who have not been defiled with women for they kept themselves chaste. These are the ones who follow the Lamb wherever He goes. The 144000 were not purchased in chapter 7. 14:4 these have been purchased from among men as first fruits to god and to the Lamb. Two separate set of people! |
16,799,769 | Here is my code:
```
<?php
$num1 = 10;
$num2 = 15;
echo "<font color='red'>$num1 + $num2</font>" . "<br>";
?>
```
I expect it to equal "25", when I add a font color it equals "10 + 15". Why? | 2013/05/28 | [
"https://Stackoverflow.com/questions/16799769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2429886/"
] | change
```
echo "<font color='red'>$num1 + $num2</font>" . "<br>";
```
to
```
echo "<font color='red'>",($num1 + $num2),"</font><br>";
``` | You need to concatenate your string otherwise math will not work
```
echo "<font color='red'>".($num1 + $num2)."</font>" . "<br>";
``` |
14,326,992 | hi I am using the following code to insert a ulabel in a UITableView
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier;
CellIdentifier = [NSString stringWithFormat:@"myTableViewCell %i,%i",
[indexPath indexAtPosition:0], [indexPath indexAtPosition:1]];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
lblNombre= [[UILabel alloc] initWithFrame:CGRectMake(110, 10, 170,40)];
lblNombre.textColor = [UIColor colorWithRed:90/255.0f green:132/255.0f blue:172/255.0f alpha:1];
lblNombre.backgroundColor = [UIColor clearColor];
lblNombre.text=@"Nicolas ahumada";
lblNombre.numberOfLines=2;
lblNombre.font = [UIFont fontWithName:@"Magra" size:18.0 ];
[cell.contentView addSubview:lblNombre ];
}
lblNombre.text=[[jsonpodio valueForKey:@"name"]objectAtIndex:indexPath.row ];
[cell.contentView addSubview:lblNombre ];
return cell;
}
```
but when I scroll or table is recharged, the UILabel is overwritten

Image above is overwritten and the picture below average,
thank you very much for your help | 2013/01/14 | [
"https://Stackoverflow.com/questions/14326992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1664226/"
] | Try this, you have issues with your cell re-use logic as well as how you're using lblNombre
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier;
// use a single Cell Identifier for re-use!
CellIdentifier = @"myCell";
// make lblNombre a local variable!
UILabel *lblNombre;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
// No re-usable cell, create one here...
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// get rid of class instance lblNombre, just use local variable!
lblNombre= [[UILabel alloc] initWithFrame:CGRectMake(110, 10, 170,40)];
lblNombre.tag = 1001; // set a tag for this View so you can get at it later
lblNombre.textColor = [UIColor colorWithRed:90/255.0f green:132/255.0f blue:172/255.0f alpha:1];
lblNombre.backgroundColor = [UIColor clearColor];
lblNombre.numberOfLines=2;
lblNombre.font = [UIFont fontWithName:@"Magra" size:18.0 ];
[cell.contentView addSubview:lblNombre ];
}
else
{
// use viewWithTag to find lblNombre in the re-usable cell.contentView
lblNombre = (UILabel *)[cell.contentView viewWithTag:1001];
}
// finally, always set the label text from your data model
lbl.text=[[jsonpodio valueForKey:@"name"]objectAtIndex:indexPath.row ];
return cell;
}
``` | Can you try the following code
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier;
// Was not sure why you had a reuse identifier which was different for each cell. You created a reuse identifier based on the index. Looks like your cells are all the same looking. So just use a constant string to identify the cell to be used.
CellIdentifier = [NSString stringWithFormat:@"myTableViewCell"];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// Find a subview with a tag of 100 and remove it. See below as to why
[cell viewWithTag:100] removeFromSuperview];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// I removed code from here and put it down, assuming that you have a data model which is feeding the data into the label
}
lblNombre= [[UILabel alloc] initWithFrame:CGRectMake(110, 10, 170,40)];
lblNombre.textColor = [UIColor colorWithRed:90/255.0f green:132/255.0f blue:172/255.0f alpha:1];
lblNombre.backgroundColor = [UIColor clearColor];
lblNombre.numberOfLines=2;
lblNombre.font = [UIFont fontWithName:@"Magra" size:18.0 ];
[cell.contentView addSubview:lblNombre ];
lblNombre.text=[[jsonpodio valueForKey:@"name"]objectAtIndex:indexPath.row ];
[cell.contentView addSubview:lblNombre ];
// Use tag or some thing to identify this subview, since you cannot keep on adding subviews. You need to remove it next time you come because you are reusing the cells and you will get back a cell which you created before and that will have the label you added last time
[lblNombre setTag:100];
return cell;
}
``` |
97,500 | I have buttons for very specific actions. That ends up with button labels like *"Send/Receive all data from sources"* or *"Create predefined calculated channels"*.
Each button has also an icon that goes with it. It results in big ugly buttons that are overloaded with information. The interface is also for tactile so a tool-tip is not an option.
Any alternatives/tips to make it more usable/esthetic ? | 2016/08/01 | [
"https://ux.stackexchange.com/questions/97500",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/87155/"
] | I would suggest evaluating what is unneeded information. For "Create predefined calculated channels", unless there are other buttons for creating channels in a different way then "Create channels" should be sufficient and further details can be left to documentation.
If there are multiple methods for creating channels then you could use a radio button approach: create a box with a label "Create Channels", add radio buttons for the various methods (e.g. "Predefined", "Calculated", "Estimated" and then a single "Create" button).
As a general advice I would take the time to understand the terminology. The words "predefined calculated" likely aren't accurate, the combination doesn't make much sense (predefined and calculated are almost opposites). A lot of times programmers are asked to automate very old processes with antiquated terminology. One aspect of the job is to learn enough of it to simplify and organize in a way that makes sense to someone without all that history. | Related to Rat In A Hat's answer, my choice would be to have the button with just the icon - maybe with a short description if you must have it - and a small icon next to it that can be tapped to expand the information for the button. Tapping the description should make it go away again.
This way, once a user is familiar with everything, the extra information remains hidden and doesn't clutter things up.
I've tried to illustrate this in the attached image.
[](https://i.stack.imgur.com/9rwV7.jpg) |
65,728,497 | I have this:
```
* ea626d4 (HEAD -> main) Merging
|\
| * 27069d1 (origin/main, origin/HEAD)
* | 5b02356
|/
* 8978bec
```
I want to remove commit 5b02356 but preserve commit ea626d4
```
* ea626d4 (HEAD -> main) Merging, maybe with changed name
|
* 27069d1 (origin/main, origin/HEAD)
|
* 8978bec
```
How can I do it? I tried `git rebase -i 8978bec`, but it removes last commit, | 2021/01/14 | [
"https://Stackoverflow.com/questions/65728497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10779391/"
] | ```
git reset --soft 27069d1
git commit
```
With `--soft`, the `reset` command jumps back to the given commit, but without changing the working directory, and leaving the files that differed between the two commits marked as "to be committed". The new commit will have the same content as the original one, but will be a regular non-merge commit.
Note that it is not actually possible to modify a commit in any way (changing its content, message, author, timestamp, parent(s), whether it's a merge, etc.) - whenever git lets you "modify" a commit, it's actually creating a *new* commit with a different SHA (and typically dropping the reference to the original commit, so it looks like you made an in-place modification). So your resulting non-merge commit will have a different SHA; there is no way to make the change you want and retain the commit SHA `ea626d4`. | >
> I want to remove commit 5b02356 but preserve commit ea626d4
>
>
>
If you remove 5b02356 there's no need for a merge.
```
* ea626d4 (HEAD -> main) Merging
|\
| * 27069d1 (origin/main, origin/HEAD)
| |
|/
* 8978bec
```
It might as well be...
```
* 27069d1 (origin/main, origin/HEAD)
|
|
* 8978bec
```
You can force an empty merge with `git merge --no-ff` and that is useful to retain "feature bubbles"; indications that work was done in a branch. |
35,336 | I think I did something wrong in the Hircine's Ring/Sinding the Werewolf quest because now there seems to be no way to complete it.
After killing the beast and summoning Hircine, I went to kill the other hunters. They were already dead (except one of them who was dying and told me to watch out for the "prey" then died.)
Then I went to see Sinding (now in werewolf form and in the woods) and his dialog indicated that he thought we were about to go kill the hunters. When he finished talking he said "Let's go" and ran for about half a second before stopping.
He just stood there and all he would say is "I didn't expect to see you again." After a while I got bored and attacked him, which caused him to run away. A few days later I went back to the jail cell in Falkreath and he was back in there (in werewolf form.) There's no apparent way to open his cell door. I can kill him with magic or arrows (and the guard doesn't care) but a few days later he'll be back. Once I left the jail and somehow he followed me. The guards attacked him and he ran away again. I was able to keep up this time on my horse, but he just kept running in large circles around the woods.
So now I have Hircine's ring on and I can't take it off or wear any other rings. People on the street tell me that I look sick and there are no map markers anywhere for this unfinished quest.
How can I either complete the quest or get rid of the ring? | 2011/11/12 | [
"https://gaming.stackexchange.com/questions/35336",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/8771/"
] | If you decided to help sinding you had to leave the cave without attacking him after killing all the hunters. when you leave Hircine appears and congratulates you on killing the hunters and gives you the ring | I had a similar issue, being unable to talk to Sinding after killing all the hunters. All I needed to do was exit to the world map. Sinding followed me outside where I was able to talk to him, receive the ring from Hircine, and then kill Sinding to retrieve the Saviours Hide. |
10,169,344 | I have 2 select boxes called 'primaryTag' and 'primaryCategory'
primaryCategory depends on primaryTag
There are also 2 multi-select options called 'tags' and 'categories'.
When a 'primaryTag' changes, the 'tags' should get deselected.
When a 'primaryCategory' changes, the 'categories' multi-select options should get deselected. **Even if the 'primaryCategory' gets changed after the change event on primaryTags, the 'categories' multi-select should be reset.**
I have the following code:
```
$('document').ready(function(){
$("#primaryTag").change(function () {
tagId = $("#{{ admin.uniqId }}_primaryTag option:selected").val();
$("#primaryCategory").val("option:first");
$("#tags *").attr("selected", false);
});
$("#primaryCategory").change(function () {
$("#categories *").attr("selected", false);
});
});
```
`primaryTag` and `primaryCategory` are select boxes.
`tags` and `categories` are multi-select boxes.
When I change a primaryTag, the primaryCategory select box gets populated with the default value of the first option as desired. However, I also want the categories multi-select box to be reset (all options deselected). And this is not happening. How can I accomplish this?
Here's the HTML | 2012/04/16 | [
"https://Stackoverflow.com/questions/10169344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/394514/"
] | `$('document')` has to be `$(document)`. After that remember the default primary category. On *primary tag* change set the default primary category and reset the tag options. On *primary category* change reset the category options.
```
$(document).ready(function() {
var iDefault = $("#primaryCategory").val();
$("#primaryTag").change(function () {
$("#primaryCategory").val(iDefault);
$("#tags option").attr("selected", false);
});
$("#primaryCategory").change(function () {
$("#categories option").attr("selected", false);
});
});
```
Also see [this example](http://jsfiddle.net/cXqxZ/).
=== UPDATE ===
If you want to set the first option of the *primary categories* replace with:
```
$(document).ready(function() {
$("#primaryTag").change(function () {
$("#primaryCategory option:first").attr("selected", true);
$("#tags option").attr("selected", false);
});
$("#primaryCategory").change(function () {
$("#categories option").attr("selected", false);
});
});
```
Also see [this example](http://jsfiddle.net/cXqxZ/1/).
=== UPDATE ===
If you want that the categories will be resetted after the *primary category* was resetted, replace the first version with:
```
$(document).ready(function() {
var iDefault = $("#primaryCategory").val();
$("#primaryTag").change(function () {
$("#primaryCategory").val(iDefault);
$("#primaryCategory").change();
$("#tags option").attr("selected", false);
});
$("#primaryCategory").change(function () {
$("#categories option").attr("selected", false);
});
});
```
Also see this [updated example](http://jsfiddle.net/r9d2f/1/). | There are basically two ways to clear a multi-select box using jQuery:
```
$("#my_select_box").val(null);
```
or
```
$("#my_select_box option").attr("selected",false);
```
The first changes the value of the select element to nothing. The second removes the selected attribute of all of the options in the select element.
I am guessing the effect of your code is:
```
$("#my_select_box").attr("selected",false);
```
which doesn't work because `#my_select_box` is the actual select element. Removing the `selected` attribute of the select element itself has no effect because that attribute has meaning only for the options inside it.
You really must try [Firebug](http://getfirebug.com/), or the developer tools built into chrome. They can help immensely in debugging javascript and jQuery code. |
20,212,378 | I need any api or library that can convert some file formats to a PDF file using C#.
The source file format can be: .doc, .docx, .jpg, .png, .tif, .xlsx, .xls, .bmp, .rtf
Is there any library or exe which I can install on my server and it converts the file to pdf as soon as it is uploaded.
I have worked with ffmpeg which converts videos to a desired video format, looking something similar which works with document files.
Server is a windows server and working with Silver Light. | 2013/11/26 | [
"https://Stackoverflow.com/questions/20212378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459573/"
] | You're probably getting the exception here:
```
String[] retArray = result.split(" ");
return Float.valueOf(retArray[1]);
```
If you split according to `" "`, sometimes there might be no second element. You need to check that:
```
String[] retArray = result.split(" ");
if(retArray.length >= 2) {
return Float.valueOf(retArray[1]);
}
```
Note that I write the condition only to demonstrate the issue. You might want to reconsider your logic.
Also recall that arrays in Java are *zero-based*, when you return `retArray[1]`, you're actually returning the second element in the array. | Check String result, either it will be empty or it will have data which doesn't have space delimiter also check the length of the retArray before access retArray[1] (by retArray[1] actually you are trying to access 2 element in the array.) |
25,127,682 | I have a Spring Batch job that reads from a file and writes to two flat files (in different formats). It uses a CompositeWriter that has two delegates which are custom classes that extend FlatFileItemWriter. Each writer writes only certain records. For example, with 14 input records the GoodFileWriter will write 12 records and the SkipFileWriter will write only two. This works just fine. However, if the job fails in the middle and I restart it the good file is missing records. It seems like Spring Batch is only maintaining the file size / record count of one of the files. I will be happy to provide examples if need be.
I have to believe this is just due to my incompetence with Spring Batch so any pointers would be greatly appreciated.
Thank you | 2014/08/04 | [
"https://Stackoverflow.com/questions/25127682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3813035/"
] | I am not sure, but according to this(www.w3schools.com/sql/sql\_join\_full.asp) FULL OUTER JOIN returns all rows from the left table and right table
while inner join(www.w3schools.com/sql/sql\_join\_full.asp) selects all rows from both tables as long as there is a match. So with inner join not only
haves to go through both tables now it must make a check. So I would think inner join takes longer to build its
list of results. However, memory is another issue. Inner join most likely returns less things sometimes (depending
on what the criteria is) while full outer join will return both tables, which means more data on memory.
But it might take less time for inner join in comparison to left outer join or right outer join because
those outer joins also have to match.(<http://www.techonthenet.com/sql/joins.php>) | It's actually somewhat of a complicated question to answer. Yes, there can be a difference in performance when INNER JOINS are written as OUTER JOINS. But I'll read into your question a bit and re-ask it a bit differently:
"Why do I see people writing INNER JOINs as OUTER JOINS?"
People use this technique frequently when creating views. In a view, you don't necessarily know what tables the user of the view wants -- they may want less than all of the columns. In cases when users *don't* want all of the columns, they may, in fact, not want whole tables. Consider a schema such as a star schema, where many "small" dimension tables reference a single "fact" table. As an example, let's say there's a table called Sales, which has a bunch of other related tables like Date, Salesperson, and Territory. You create a view which "flattens this out" by joining all of the tables to the fact tables.
If you used INNER JOINs, every time someone used the view, the database server would often generate a query plan which referenced every table in the view. So even if you wrote a query like "SELECT TerritoryName, SUM(Sales) from vw\_AllSales", an INNER JOIN based view would still query Date and Salesperson. Using an OUTER JOIN in the view definition will often let the optimizer "optimize away" references to tables that the view consumer doesn't care about. |
50,994,006 | I have an enumerated type and I need to pass an array of this type as parameter:
```
type
TTest = (a,b,c);
procedure DoTest(stest: TArray<TTest>);
```
When I compile
```
DoTest([a]);
```
I receiv the error below:
>
> Error: E2010 Incompatible types: 'System.TArray' and 'Set'\*
>
>
>
So, how can I call `DoTest` without creating a variable of type `TArray<TTest>`? | 2018/06/22 | [
"https://Stackoverflow.com/questions/50994006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2399713/"
] | One way to do what you want is to change the parameter to an [open array](http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Open_Arrays) of TTest, i.e.
```
procedure DoTest(const stest: array of TTest);
```
But supposed you don't want to change the parameter, and really want it to be a `TArray<TTest>`, then you can simply use the array pseudo-constructor syntax to call it (in almost all versions of Delphi, except the very old ones). Say you have something like:
```
type
TTest = (a, b, c);
procedure DoTest(const stest: TArray<TTest>);
// simple demo implementation
var
I: Integer;
begin
for I := Low(stest) to High(stest) do
Write(Integer(stest[I]), ' ');
Writeln;
end;
```
Then it can be called, using the Create syntax without having to declare a variable or having to fill it manually. The compiler will do this for you:
```
begin
DoTest(TArray<TTest>.Create(a, c, b, a, c));
end.
```
The output is, as expected:
```
0 2 1 0 2
``` | I'm assuming that with "how can I call DoTest without creating a variable of type TArray" you want to avoid declaring and initializing local variable, ie code like
```
var arr: TArray<TTest>;
begin
SetLength(arr, 1);
arr[0] := a;
DoTest(arr);
```
For this you can use the array constructor like:
```
DoTest(TArray<TTest>.Create(a));
```
This syntaxs is supported at least since Delphi 2010. |
5,267,307 | I created a WCF project by going to Add New Project -> WCF service library and when I run it on the development environment, it opens up the WCF test client. How do I install this service on a server that doesn't have Visual Studio installed (I'd like to not host it on IIS). Should I write a new windows service? | 2011/03/10 | [
"https://Stackoverflow.com/questions/5267307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609866/"
] | Create a Windows Service project.
Add your WCF Service to this project.
In the main Windows Service class (defaults to Service1.cs), add a member:
```
internal static ServiceHost myServiceHost = null;
```
Modify OnStart() to start a new ServiceHost with your WCF Service type:
```
protected override void OnStart(string[] args)
{
if (myServiceHost != null)
{
myServiceHost.Close();
}
myServiceHost = new ServiceHost(typeof(MyService));
myServiceHost.Open();
}
```
Modify OnStop():
```
protected override void OnStop()
{
if (myServiceHost != null)
{
myServiceHost.Close();
myServiceHost = null;
}
}
```
Add a Setup and Deployment project (Setup Project) to your solution. Set output of that project to be the main output of the Windows Service project. When you build the Setup and Deployment project, you should see a Setup.exe file that you can use to install the service.
Keep in mind you still need to setup your endpoints and bindings. Look into using nettcpbinding for this setup.
As a final note, reference: [Error 5 : Access Denied when starting windows service](https://stackoverflow.com/questions/4267051/error-5-access-denied-when-starting-windows-service/5207840#5207840) if you are experiencing problems when starting the Windows Service after installation. | You need to create a windows service project and then add reference to your WCF service and host it. In order to install the service, you do not need visual studio, you need to use `installutil.exe`.
Have a look [here](http://msdn.microsoft.com/en-us/library/ms733069.aspx). |
64,509,930 | I want to identify shipments from a table which have routes that have established contracts for the particular route, but the wrong carrier was used.
[](https://i.stack.imgur.com/aobME.png)
[](https://i.stack.imgur.com/lGWXK.png)
[](https://i.stack.imgur.com/uWVny.png)
I am able to separately query and identify the Contract Types where the Route/Carrier match and where the Route has not been contracted for any Carrier. Respectively, this is how I did those:
```
SELECT s.*,c.*
FROM Shipments s
INNER JOIN Contracts c ON s.Route=c.Route and s.Carrier=c.Carrier;
SELECT s.*,c.*
FROM Shipments s
LEFT JOIN Contracts c ON s.Route=c.Route
WHERE c.Route IS NULL;
```
The row that is yellow highlighted, however, I need help to solve. It is the case where a Route has been contracted for, but the wrong carrier was used, thus negated the effort of negotiating the contract (yes, this is a real world scenario).
I've tried the following, but they do not isolate the yellow line, which is my goal.
```
SELECT s.*,c.*
FROM Shipments s
LEFT JOIN Contracts c ON s.Route=c.Route and s.Carrier!=c.Carrier;
SELECT s.*,c.*
FROM Shipments s
LEFT JOIN Contracts c ON s.Route=c.Route and s.Carrier=c.Carrier
WHERE c.Carrier IS NULL;
SELECT s.*,c.*
FROM Shipments s
LEFT JOIN Contracts c ON s.Route=c.Route
WHERE c.Carrier IS NULL;
```
I'm trying to implement this in Excel VBA using ADODB, but for the moment, I'm really interested in just understanding conceptually how I would achieve this generically in SQL -- if possible -- or what a better strategy to do this would be. Thank you in advance for any help. | 2020/10/24 | [
"https://Stackoverflow.com/questions/64509930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3601357/"
] | You need an additional join to see if the route has a contract and then `CASE` logic:
```
SELECT s.*,
(CASE WHEN cr.route IS NULL THEN 'Route has no contract'
WHEN c.route IS NULL THEN 'Route assigned to wrong carrier'
ELSE 'Correct'
END)
FROM Shipments s LEFT JOIN
Contracts c
ON s.Route = c.Route AND s.carrier = c.carrier LEFT JOIN
(SELECT DISTINCT c.Route
FROM Contracts c
) cr
ON cr.Route = s.Route
``` | ```
SELECT s.*,c.*
FROM Shipments s
LEFT JOIN Contracts c ON s.Route=c.Route and s.Carrier=c.Carrier;
```
if `c.Route` is null, those shipments have no contract. |
35,861,047 | I am using CGAffineTransformMakeRotation to rotate my button.But my button getting scaled(big or small) according to my value to rotate.How to stop scaling of my button? sample code i have used
```
UIView.animateWithDuration(2.5, animations: {
self.btnMeter.transform = CGAffineTransformRotate(CGAffineTransformIdentity, (45 * CGFloat(M_PI)) / 180.0)
})
``` | 2016/03/08 | [
"https://Stackoverflow.com/questions/35861047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/599561/"
] | Well you need to decide whether these numbers are meant to be part of the state of your object or not. If they are, make them fields. If they're not, don't. In this case, I'd probably keep them as local variables and change your `NumSelect` code to simply return *one* number entered by the user - and call it twice:
```
public int NumSelect()
{
string line = Console.ReadLine();
return int.Parse(line);
}
static void Main()
{
SimpleMath operation = new SimpleMath();
Console.WriteLine("Give me two numbers and I will add them");
int number1 = operation.NumSelect();
int number2 = operation.NumSelect();
int result = operation.Add(number1, number2);
Console.WriteLine("{0} + {1} = {2}", number1, number2, result);
}
```
You *could* change your whole class to make the values fields, and remove the parameters, like this:
```
class SimpleMath
{
private int number1;
private int number2;
public int Add()
{
int result = number1 + number2;
return result;
}
public int Subtract()
{
int result = number1 - number2;
return result;
}
public int SelectNumbers()
{
number1 = int.Parse(Console.ReadLine());
number2 = int.Parse(Console.ReadLine());
}
static void Main()
{
SimpleMath operation = new SimpleMath();
Console.WriteLine("Give me two numbers and I will add them");
operation.NumSelect();
int result = operation.Add();
Console.WriteLine(
"{0} + {1} = {2}",
operation.number1,
operation.number2,
result);
}
}
```
This *doesn't* feel like the best approach to me - I'd take the earlier approach of using local variables in `Main` - but I wanted to show you the alternative. Note that you can only access `operation.number1` in `Main` because the `Main` method is in the same type - that should raise warning bells for you. | Put your two numbers as `class` fields rather than methods'.
```
int number1 = 0, number2 = 0; //have them as class fields like this
public int NumSelect()
{
number1 = Console.ReadLine();
number2 = Console.ReadLine();
}
```
This way, you could access your `number1` and `number2` across different methods.
Method's fields/arguments are only valid *within* the method:
```
//number1 and number2 are method arguments, only accessible in the method
public int Add(int number1, int number2)
{
int result = number1 + number2;
return result;
}
//not accessible elsewhere
public int NumSelect() //number1 and number2 are unknown in this method
{
number1 = Console.ReadLine();
number2 = Console.ReadLine();
}
``` |
987,000 | I have a program that I intend to install on Linux and Windows machines. I have it cross-compiling fine (with autotools), but at some point I would like the program to be able to update its binaries. The only ways I can think of doing this are:
* Give users write access to "C:\Program Files\Foo Program" or "/usr/bin/foo\_program".
or
* Install the program to the user's profile/home directory.
Neither of these seems like a good idea. What would you do? | 2009/06/12 | [
"https://Stackoverflow.com/questions/987000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121545/"
] | Sounds like the identity seed got corrupted or reset somehow. Easiest solution will be to reset the seed to the current max value of the identity column:
```
DECLARE @nextid INT;
SET @nextid = (SELECT MAX([columnname]) FROM [tablename]);
DBCC CHECKIDENT ([tablename], RESEED, @nextid);
``` | While I don't have an explanation as to a potential cause, it is certinaly possible to change the seed value of an identity column. If the seed were lowered to where the next value would already exist in the table, then that could certainly cause what you're seeing. Try running `DBCC CHECKIDENT (table_name)` and see what it gives you.
For more information, check out [this page](https://web.archive.org/web/1/http://blogs.techrepublic%2ecom%2ecom/datacenter/?p=406) |
4,346,399 | How can I tell gnu make not to build some recipe in parallel. Let's say I have the following makefile :
```
sources = a.xxx b.xxx c.xxx
target = program
all : $(target)
$(target) : $(patsubst %.xxx,%.o,$(sources))
$(CXX) -o $@ $<
%.o : %.cpp
$(CXX) -c -o $@ $<
%.cpp : %.xxx
my-pre-processor -o $@ $<
```
However, the `my-pre-processor` command create temporary files with fixed name (I cannot change this). This is working fine if I just use make without the `-j` parameter. However, if the `-j` option is used, the build sometimes fails because two concurrent invocation of `my-pre-processor` overwrite their temporary files.
I'd like to know if there is a way to tell make that it must not build the try to parallelize the execution of the `%.cpp : %.xxx` recipes. | 2010/12/03 | [
"https://Stackoverflow.com/questions/4346399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5353/"
] | This is a horrible kludge, but it will do the job:
```
b.cpp: a.cpp
c.cpp: b.cpp
```
Or if there are actually a lot of these, you can have a few stiff drinks and do this:
```
c-sources = $(sources:.xxx=.cpp)
ALLBUTFIRST = $(filter-out $(firstword $(c-sources)), $(c-sources))
ALLBUTLAST = $(filter-out $(lastword $(c-sources)), $(c-sources))
PAIRS = $(join $(ALLBUTLAST),$(addprefix :,$(ALLBUTFIRST)))
$(foreach pair,$(PAIRS),$(eval $(pair)))
```
(This works in GNUMake, I don't know about other versions.) | You would do well to study the operation of the `ylwrap` tool that comes with `automake`: It solves most of the same problems for old versions of `lex` and `yacc`:
<http://git.savannah.gnu.org/cgit/automake.git/tree/lib/ylwrap> |
7,234,096 | I created a notification at the top of the page that fades in:
HTML/PHP:
```
<?php if ( ! is_user_logged_in() ) : ?>
<div class="notification">
<span><?php _e( 'Welcome to Taiwantalk' ); ?></span>
</div><!-- #container -->
<?php endif; ?>
```
CSS:
```
.notification {
background-color: #444;
color: #FFF;
height: 0;
opacity: 0;
padding: 8px 0 0;
}
```
JS:
```
var $j = jQuery.noConflict();
$j(document).ready(function() {
$j(".notification").animate({
height: "22px",
opacity: 1
}, 1000 );
});
```
Now I would like to create a button at the right that closes the div with the same animation that it was used to make it fade in.
Any suggestions of how to accomplish this? | 2011/08/29 | [
"https://Stackoverflow.com/questions/7234096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122536/"
] | Practically the same thing as you already have. Just set height to 0px instead and opacity to 0. Assuming you want it to slide up and fade out. If you just want it to fade out then set opacity to 0. You can also use the jQuery fadeIn/fadeOut methods.
```
<input type="button" value="click" id="mybutton" />
//note that $j is relevant to the asker's code example. Typically jQuery just uses $.
//See Roxon's answer for an example.
var $j = jQuery.noConflict();
$j(document).ready(function() {
$j(".notification").animate({
height: "22px",
opacity: 1
}, 1000 );
$j("#mybutton").click( function() {
$j(".notification").animate({
height: "0px",
opacity: 0
}, 1000 );
});
});
``` | I would animate toggle a class instead of setting the height and opacity. You could do this on the document ready event as well. This allows you to keep your style separated from your functionality.
Something like this:
```
$( "#close_button" ).click(function() {
$( ".notification").toggleClass( "notificationVisible", 1000 );
return false;
});
```
and in your css, just have this:
```
.notificationVisible { height: 22px; opactiy: 1; }
``` |
3,983,943 | >
> **Possible Duplicate:**
>
> [What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?](https://stackoverflow.com/questions/1604968/what-does-a-colon-in-a-struct-declaration-mean-such-as-1-7-16-or-32)
>
>
>
This is C code sample of a reference page.
```
signed int _exponent:8;
```
What's the meaning of the colon before '8' and '8' itself? | 2010/10/21 | [
"https://Stackoverflow.com/questions/3983943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/246776/"
] | It's a bitfield. It's only valid in a `struct` definition, and it means that the system will only use 8 bits for your integer. | When that statement is inside a structure, means [bit fields](http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=/com.ibm.vacpp6m.doc/language/ref/clrc03defbitf.htm). |
7,652,945 | I have a big maven project with lots of modules. One of the modules is not 'real' development project. It contains data for the final system. The data is deployed to the system using a special jar. The pom now makes sure that the jar is downloaded and all the other data and batch files are packaged into a zip. It uses the maven assembly plugin. There is no much magic to this pom file. The magic starts when unpacking the zip file with Windows compressed folder. It will only recognize the jar file which is rather big (9MB) and not the batch and data files (a few KB). I didn't notice this right away because my really old Winzip does not have any issues with the artifact.
Does anybody has an idea or has seen similar issues?
---
the plugin configuration from pom file
```
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>assembly.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
```
---
My assembly xml
```
<?xml version="1.0" encoding="UTF-8"?>
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<formats>
<format>zip</format>
</formats>
<dependencySets>
<dependencySet>
<outputDirectory></outputDirectory>
<includes>
<include>com.group:product-development-cli</include>
</includes>
<outputFileNameMapping>product-development-cli-${ext.version}.${extension}</outputFileNameMapping>
</dependencySet>
</dependencySets>
<fileSets>
<fileSet>
<directory>.</directory>
<excludes>
<exclude>pom.xml</exclude>
<exclude>assembly.xml</exclude>
<exclude>target</exclude>
</excludes>
</fileSet>
</fileSets>
</assembly>
```
---
My folder structure:
module
+- data1
+- more files
+- data2
+- more files
+- pom.xml
+- assembly.xml
+- more files | 2011/10/04 | [
"https://Stackoverflow.com/questions/7652945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/204042/"
] | Objective-C version:
```
NSArray *fileURLs = [NSArray arrayWithObjects:fileURL1, /* ... */ nil];
[[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:fileURLs];
``` | When opening a file at `path`:
```
NSString* path = @"/Users/user/Downloads/my file"
NSArray *fileURLs = [NSArray arrayWithObjects:[NSURL fileURLWithPath:path], nil];
[[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:fileURLs];
``` |
68,219 | I saw this sentence on Internet recently written by a native speaker, so I wondered why native speakers tend to use this grammar.
Explain to me why I should I use "is" instead of "are"? Is it grammatically correct?
>
> "There is rice, meat and tomatoes on my plate"
>
>
>
Why "There are rice, meat and tomatoes on my plate" is not correct? | 2015/09/16 | [
"https://ell.stackexchange.com/questions/68219",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/24318/"
] | I think there is some confusion here between *"X and Y is/are Z"* and *"There is/are X and Y on Z"*; in the former case 'is/are' should agree with X and Y, but in the latter case 'is/are' should theoretically agree with 'There', though as we'll see this does not always sound right.
First compare:
>
> '*My fish and chips was tasty*' vs '*My fish and chips were tasty*'
>
>
>
Both are acceptable, but mean (to me) something slightly different. The first treats 'fish and chips' as a unit - a single dish, as opposed to them each individually being tasty (as per Victor Barazov's answer). If you said '*my taxi and my plane were late*' that's obviously a plural; there's no possibility of '\*my taxi and my plane was late'. In this situation (noun / noun-clause in question precedes the verb), this is a simple matter that the verb needs to agree (in terms of singular / plural status) with the noun-clause.
Next we have the conceivably separate point of 'there is / there are'. Let's take an example which is clearly plural, and doesn't fall into the 'fish and chips' category which might in fact be singular (as a dish).
>
> '*There is a fly and a cockroach on my plate*' vs '*There are a fly and a cockroach on my plate*'.
>
>
>
Now, as a native British English speaker, I'd say the former (or more likely contract it to *'There's a fly and a cockroach on my plate'*. I can't explain why, and perhaps it's technically wrong, especially as I'd say '*There are three flies on my plate*' or '*There are cockroaches on my plate*' or '*There are flies and cockroaches on my plate*'. But I'd also say '*There is a fly and three cockroaches on my plate*', or '*There are three cockroaches and a fly on my plate*'. My only weak explanation is that this is a contraction of "*There is/are X [and there is/are] Y on my plate*"
So to your example:
>
> There is rice, meat and tomatoes on my plate
>
>
>
If "rice, meat, and tomatoes" was a dish, that would be acceptable.
It also might be accepable as 'rice' is singular despite the other nouns meaning there was a plurality of objects (see my inexplicable paragraph),
If it were "*There is tomatoes, rice, and meat on my plate*" that wouldn't sound right (per my para above), and should be 'are'.
'Are' would be acceptable in any case I guess. | To answer the question provided (In the examples provided) either could be used. Generally the US apply plurality to the sentence whereas in the UK we do not.
Unfortunately, English has a lot of subtleties and the sentence does not sound correct in the first place to my ear. Most folks would state "I have rice, meat and tomatoes on my plate." thus avoiding this issue in the first place and is neutral. The consequence is that one avoids this question in the first place and all the cultural divergences.
And yes I am a native English speaker, I do not speak American. See the point?
You can have even more fun with the Oxford comma - this is whether you use the comma after an "and". |
33,142,657 | I got a really annoying problem with calendar class. I have two JTextFields to enter a period of date (txtStart & txtEnd). If start date begins at the first day of month (01.), I set the end date to "last day of month".
Now the user can change change the period by clicking a plus or minus button, then I want to increase or decrease only the month of start & end date.
```
Calendar tempStart = Calendar.getInstance();
Calendar tempEnd = Calendar.getInstance();
if (txtStart.getText().trim().startsWith("01.")) {
System.out.println("get dates typed by user, and set \"last day of month\" to txtEnd");
tempStart = convStringToDate(txtStart.getText().trim(), false);
System.out.println(tempStart.getTime() + " #+#+###++ ");
tempEnd = getLastDayOfMonth(txtStart.getText().trim());
System.out.println(tempEnd.getTime() + " #+#+###++ ");
System.out.println(" ");
System.out.println("multi is either +1 or -1, increasing or decreasing only the month !");
tempStart.set(Calendar.MONTH, tempStart.get(Calendar.MONTH) + multi);
System.out.println(tempStart.getTime() + " #+#+###++ ");
tempEnd.set(Calendar.MONTH, tempEnd.get(Calendar.MONTH) + multi);
System.out.println(tempEnd.getTime() + " #+#+###++ ");
System.out.println(" ");
}
```
My methods are working correctly. Now I got some bewildering output.
If I enter 01.11.2015 at txtStart (dd.MM.yyy) I got following output:
```
get dates typed by user, and set "last day of month" to txtEnd
Sun Nov 01 00:00:01 GMT 2015 #+#+###++
Mon Nov 30 23:59:59 GMT 2015 #+#+###++
multi is either +1 or -1, increasing or decreasing only the month !
Tue Dec 01 00:00:01 GMT 2015 #+#+###++
Wed Dec 30 23:59:59 GMT 2015 #+#+###++
```
Looks pretty nice and everthing seems to work correctly, but if I enter 01.10.2015 at txtStart (dd.MM.yyy) I got following output:
```
get dates typed by user, and set "last day of month" to txtEnd
Thu Oct 01 00:00:01 GMT 2015 #+#+###++
Sat Oct 31 23:59:59 GMT 2015 #+#+###++
multi is either +1 or -1, increasing or decreasing only the month !
Sun Nov 01 00:00:01 GMT 2015 #+#+###++
Tue Dec 01 23:59:59 GMT 2015 #+#+###++
```
May anyone have an idea why my end date is wrong at output 2.
EDIT:
multi = +1 or -1 (see in output1 or output2 comment)
```
private Calendar getLastDayOfMonth(String sDate) {
Calendar cal = convStringToDate(sDate, true);
// passing month-1 because 0-->jan, 1-->feb... 11-->dec
// calendar.set(year, month - 1, 1);
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
cal.set(Calendar.HOUR_OF_DAY, MAX_ZEIT[0]); // 23
cal.set(Calendar.MINUTE, MAX_ZEIT[1]); // 59
cal.set(Calendar.SECOND, MAX_ZEIT[2]); // 59
cal.set(Calendar.MILLISECOND, MAX_ZEIT[3]); // 0
// Time: 23:59:59:0
return cal;
}
```
############## SOLUTION: ####################.
```
if (txtStart.getText().trim().startsWith("01.")) {
tempStart = convStringToDate(txtStart.getText().trim(), false);
tempEnd = (Calendar) tempStart.clone(); // set the date somewhere at the same month ( e.g. at start date )
tempStart.set(Calendar.MONTH, tempStart.get(Calendar.MONTH) + multi); // inc- or decrease the month first
tempEnd.set(Calendar.MONTH, tempEnd.get(Calendar.MONTH) + multi); // inc- or decrease the month first ( now there is no overflow due to the 30th or 31th day )
tempEnd = getLastDayOfMonth(df2.format(tempEnd.getTime())); // finally setting the "last day of month"
}
```
The solution is to do first of all to increase or decrease the month, after that I can set the last day of month without getting any overflow problems.
Output:
```
get dates typed by user, and set "last day of month" to txtEnd
Thu Oct 01 00:00:01 GMT 2015 #+#+###++
Thu Oct 01 00:00:01 GMT 2015 #+#+###++
multi is either +1 or -1, increasing or decreasing only the month !
Sun Nov 01 00:00:01 GMT 2015 #+#+###++
Sun Nov 01 00:00:01 GMT 2015 #+#+###++
FINALLY
Sun Nov 01 00:00:01 GMT 2015 #+#+###++
Mon Nov 30 23:59:59 GMT 2015 #+#+###++
```
I thank you all for your help !!! | 2015/10/15 | [
"https://Stackoverflow.com/questions/33142657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3118667/"
] | The end date is incorrect in the first example, as well. It shows 30/12 whereas the last day of December is the 31st. When you add +1 to the month you don't check whether the following month has the same number of days.
November has 30 days. Therefore, incrementing October 31st gives November "31st" which is actually December 1st.
Lots of programmers need to do arithmetic on dates. That's why java.util.Calendar class has a method add() that you can use that encapsulates all the calculations you need. Check the JavaDocs: <http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#add(int,%20int)> | After you have incremented or decremented the month of the start date, use
```
int lastDayOfMonth = startDate.getActualMaximum(Calendar.DAY_OF_MONTH);
```
and use startDate in combination with day-of-month set to this value as the endDate.
```
Calendar sd = new GregorianCalendar( 2015, 1, 1 );
int last = sd.getActualMaximum(Calendar.DAY_OF_MONTH);
Calendar ed = new GregorianCalendar( sd.get(Calendar.YEAR),
sd.get(Calendar.MONTH),
last );
System.out.println( sd.getTime() + " " + ed.getTime() );
sd.add( Calendar.MONTH, 1 );
last = sd.getActualMaximum(Calendar.DAY_OF_MONTH);
ed = new GregorianCalendar( sd.get(Calendar.YEAR),
sd.get(Calendar.MONTH),
last );
System.out.println( sd.getTime() + " " + ed.getTime() );
``` |
12 | There are some really great security questions asked on Stack Overflow / Superuser sites, with some really excellent answers. Had this site been around back then, here would have been a much more natural place for it.
Should we migrate those questions to here, in order to consolidate? Just copy the core points over? Or leave them there, since obviously they were on-topic originally...
My thought being that this site should eventually be the central repository for security information... | 2010/11/12 | [
"https://security.meta.stackexchange.com/questions/12",
"https://security.meta.stackexchange.com",
"https://security.meta.stackexchange.com/users/33/"
] | Sure, better would if all security related questions are gathered in one place - here. But doubling them could bring some disorder. Ideal solution would be just to move them here and maybe leave notice about this replacement on the place of previous topic.
Simply, there are big chances that those question will be asked again here, because not all users are aware of those answers existence in some other place. | Even if there are duplicates, I'm sure the tone and response will be geared for this specific community as it grows. I'll find the different perspectives educational, just as I currently do when I compare the overlap in the existing sites. |
2,007,540 | i found a way to send plain text email using intent:
```
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("text/plain");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new
String[]{"example@mail.com"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Test");
```
But I need to send HTML formatted text.
Trying to setType("text/html") doesn't work. | 2010/01/05 | [
"https://Stackoverflow.com/questions/2007540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238123/"
] | You can pass `Spanned` text in your extra. To ensure that the intent resolves only to activities that handle email (e.g. Gmail and Email apps), you can use `ACTION_SENDTO` with a Uri beginning with the mailto scheme. This will also work if you don't know the recipient beforehand:
```
final Intent shareIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"));
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "The Subject");
shareIntent.putExtra(
Intent.EXTRA_TEXT,
Html.fromHtml(new StringBuilder()
.append("<p><b>Some Content</b></p>")
.append("<small><p>More content</p></small>")
.toString())
);
``` | I haven't (yet) started Android development, but the [documentation](http://developer.android.com/reference/android/content/Intent.html#ACTION_SEND) for the intent says that if you use EXTRA\_TEXT, the MIME type should be text/plain. Seems like if you want to see HTML, you'd have to use EXTRA\_STREAM instead... |
303,510 | I found a nice blueprint for an assault rifle as well as some augments. I researched both, but now I don't see any option to actually apply the augment to the assault rifle.
[](https://i.stack.imgur.com/NzY5g.jpg)
From the description in-game I would have expected this to happen in the development phase, but there is no option here to add an augment. I can craft the Valkyrie assault rifle I researched here, and I can see the augments in my inventory, but I can't find any option to select an augment here.
So, how do I apply an augment to my weapon? | 2017/03/19 | [
"https://gaming.stackexchange.com/questions/303510",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/4103/"
] | Slots for augmentations only appear on higher level versions of items.
Augmentations are added during the development of the item by selecting the augment slots in the same way as you would when adding mods on the load out screen:
[](https://i.stack.imgur.com/WrIjM.png) | Most weapon at lvl 2 got augmentation slot. The first lvl for all weapon do not have. You will need to research the second lvl for that rifle. |
4,781,669 | I have an group of checkboxes with id's starting with `somename` and i want catch the click event of these checkboxes. Previously i have done this through jquery. i.e. `$("input[id^='somename']").click(function(){
// my code follows here
})`
but this is not working this time around. why?
P.S. The element is created via javascript after the page is fully loaded after making some ajax request. i don't know if this may be the problem? | 2011/01/24 | [
"https://Stackoverflow.com/questions/4781669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/546779/"
] | I believe that because you want this applied to dynamically created elements in the DOM you are going to have to use the the jQuery .[live()](http://api.jquery.com/live/) method:
```
$("input[id^='somename']").live('click', function(e) {
// Your code
});
``` | Instead of `.click()` try `.change()` event. |
67,945,097 | I am using AlphaVantage API to download data points, which I then convert to a pandas DataFrame.
I want to plot the new DataFrame with a Scatter/Line graph using Plotly.
The graphs seems to come out perfect when plotting them in Google Colab, however, I seem to be unable to replicate my results in PyCharm and Jupiter Notebook.
When plotting in either PyCharm and JN, the Y-Axis values are plotted out of order, like the graph is trying to create as straight of a line as possible (see 2nd image and look closely at y-axis).
Here is a simplified example of the code and graphs:
Exact Same code used in both instances
Desired Outcome (Sample from Colab):
[](https://i.stack.imgur.com/wuyXI.png)
Outcome on PyCharm and JN (Current Issue Graph):
[](https://i.stack.imgur.com/iQB9a.png)
See Code:
```
import requests
import pandas as pd
import plotly.graph_objects as go
# DATA FROM API
response = requests.get(url='https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY&symbol=IBM&apikey=demo')
response.raise_for_status()
stock_weekly = response.json()['Weekly Time Series']
# CHANGE DATA FORMAT, RENAME COLUMNS AND CONVERT TO DATETIME, FINALLY FLIP TO HAVE DATE IN ASCENDING ORDER
raw_weekly_data = pd.DataFrame(stock_weekly)
weekly_data = raw_weekly_data.T
weekly_data.reset_index(level=0, inplace=True)
weekly_data.rename(columns={
'index': 'DATE',
'1. open': 'OPEN',
'2. high': 'HIGH',
'3. low': 'LOW',
'4. close': 'CLOSE',
'5. volume': 'VOLUME'
},
inplace=True)
weekly_data['DATE'] = pd.to_datetime(weekly_data['DATE'])
weekly_data = weekly_data[::-1]
weekly_data = weekly_data.reset_index(drop=True)
# PLOT
fig = go.Figure()
fig.add_trace(go.Scatter(
x=weekly_data['DATE'],
y=weekly_data['CLOSE']))
fig.show()
``` | 2021/06/12 | [
"https://Stackoverflow.com/questions/67945097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15757379/"
] | I received an answer to my question on plotly and decided to share. I used a combination of both of the following techniques:
>
> The error is due to the data types of your columns in your dataframe.
> dtypes The values are of type object.
>
>
> However this was not a problem is previous versions of plotly (which
> must be installed on your Google Collab). The newer releases requires
> the values to be numeric.
>
>
>
You can either convert the columns to numeric like this:
```
#converting to type numeric
cols = weekly_data.columns.drop('DATE')
weekly_data[cols] = weekly_data[cols].apply(pd.to_numeric)
```
or just add autotypenumbers=‘convert types’ to update your figure:
```
fig = go.Figure()
fig.add_trace(go.Scatter(
x=weekly_data['DATE'],
y=weekly_data['CLOSE']))
fig.update_layout(autotypenumbers='convert types')
fig.show()
``` | The error lies in the data type of your y-axis values. I would guess they are currently strings. Try converting the values to float, and that should solve the problem. To convert all the values in your y-axis to float (which would be the 'CLOSE' column in the dataframe), you can do:
`weekly_data['CLOSE'] = weekly_data['CLOSE'].astype(float)` |
43,708,661 | I want to initializes a dataframe and set its column and index as shown below but I face some issues while do like this:
```
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
record = pd.DataFrame(MAE, columns=dataset, index=classifier).transpose()
plt.figure(figsize=(8, 8))
plt.title('MAE HeatMap Dataset vs Classifier')
sns.heatmap(record, linewidths=0.5, annot=True)
plt.show()
```
From above Matrix define as:
before Update:
```
MAE = [[[0], [0], [0]],
[[0], [0], [0]]]
```
After Update:
```
MAE = [[array([ 27.5]), array([ 29.9]), array([ 37.8])],
[array([ 6.51]), array([ 7.51]), array([ 9.81])]]
```
and dataset as:
```
da = ['Xtrain','Ytrain']
```
and cl as:
```
classifier = ['Ax','Bx','Cx']
```
following error is occur while executing this line:
```
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-45-f0449c7e5b93> in <module>()
43 return
44
---> 45 main()
<ipython-input-45-f0449c7e5b93> in main()
29 DisplayWTL(dataset[city] + ' R2 Score', WTL_R2[0], classifier)
30
---> 31 record = pd.DataFrame(MAE, columns=dataset, index=classifier).transpose()
32 plt.figure(figsize=(8, 8))
33 plt.title('MAE HeatMap Dataset vs Classifier')
/home/AAK/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy)
303 if is_named_tuple(data[0]) and columns is None:
304 columns = data[0]._fields
--> 305 arrays, columns = _to_arrays(data, columns, dtype=dtype)
306 columns = _ensure_index(columns)
307
/home/AAK/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in _to_arrays(data, columns, coerce_float, dtype)
5517 if isinstance(data[0], (list, tuple)):
5518 return _list_to_arrays(data, columns, coerce_float=coerce_float,
-> 5519 dtype=dtype)
5520 elif isinstance(data[0], collections.Mapping):
5521 return _list_of_dict_to_arrays(data, columns,
/home/AAK/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in _list_to_arrays(data, columns, coerce_float, dtype)
5596 content = list(lib.to_object_array(data).T)
5597 return _convert_object_array(content, columns, dtype=dtype,
-> 5598 coerce_float=coerce_float)
5599
5600
/home/AAK/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in _convert_object_array(content, columns, coerce_float, dtype)
5655 # caller's responsibility to check for this...
5656 raise AssertionError('%d columns passed, passed data had %s '
-> 5657 'columns' % (len(columns), len(content)))
5658
5659 # provide soft conversion of object dtypes
AssertionError: 2 columns passed, passed data had 3 columns
```
how to resolve this problem in python dataframe? | 2017/04/30 | [
"https://Stackoverflow.com/questions/43708661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Using only what you would know from, "Automate the Boring Stuff with Python."
```
spam = ['apples', 'bananas' , 'tofu', 'cats']
def commaCode(listValue):
for i in range(len(listValue)-1):
print(listValue[i], end=', ') # the end keyword argument was presented in ch.(3)
print('and ' + listValue[-1])
commaCode(spam)
``` | There is another short way of compiling a simple code for this task:
```
def CommaCode(list):
h = list[-2] + ' and ' + list[-1]
for i in list[0:len(list)-2]:
print(str(i), end = ', ')
print(h)
```
And if you run it with the spam list to check:
```
CommaCode(spam)
apples, bananas, tofu and cats
``` |
2,695,202 | If you have an HTML `<select multiple>` of a certain width and height (set in CSS), if there are more values then you can possibly fit in that height, then the browser adds a vertical scroll bar. Now if the text is longer than the available width, is it possible to instruct the browser to add a horizontal scrollbar? | 2010/04/22 | [
"https://Stackoverflow.com/questions/2695202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5295/"
] | Although it is an old question and OP asked for CallByName in a standard module, the correct pieces of advice are scattered through answers and comments, and some may not be that accurate, at least in 2020.
As SlowLearner stated, Application.run DOES return a Variant, and in that way both branchs below are equivalent, except by handling errors, as commented around Horowitz's answer:
```
Dim LoadEnumAndDataFrom as Variant
'FunctionName returns a Variant Array
if fCallByName then
LoadEnumAndDataFrom = CallByName(ClassObj, "FunctionNameAtClass", VbMethod)
else
'After moving back function for a standard module
LoadEnumAndDataFrom = Application.Run("StandardModuleName" & "." & "FunctionNameAtStandard")
endif
```
I actually just did this above and had no errors at all, tested in Word, Excel and Access, and both return the same Array.
Unfortunately, there is an exception: Outlook's object Model is too protected and it does not have the Run method. | Modules in VB6 and VBA are something like static classes, but unfortunately VB doesn't accept Module1 as an object. You can write Module1.Func1 like C.Func1 (C being an instance of some Class1), but this is obviously done by the Compiler, not at runtime.
Idea: Convert the Module1 to a class, Create a "Public Module1 as Module1" in your Startup-module and "Set Module1 = New Module1" in your "Sub Main". |
57,810,879 | Is there a parameter or a setting for running pipelines in sequence in azure devops?
I currently have a single dev pipeline in my azure DevOps project. I use this for infrastructure because I build, test, and deploy using scripts in multiple stages in my pipeline.
My issue is that my stages are sequential, but my pipelines are not. If I run my pipeline multiple times back-to-back, agents will be assigned to every run and my deploy scripts will therefore run in parallel.
This is an issue if our developers commit close together because each commit kicks off a pipeline run. | 2019/09/05 | [
"https://Stackoverflow.com/questions/57810879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8672160/"
] | There is a new update to Azure DevOps that will allow sequential pipeline runs. All you need to do is add a lockBehavior parameter to your YAML.
<https://learn.microsoft.com/en-us/azure/devops/release-notes/2021/sprint-190-update> | Bevan's solution can achieve what you want, but there has an disadvantage that you need to change the parallel number manually **back and forth** if sometimes need parallel job and other times need running in sequence. This is little unconvenient.
Until now, there's no directly configuration to forbid the pipeline running. But there has a workaruond that use an parameter to limit the agent used. You can set the **demand** in pipeline.
[](https://i.stack.imgur.com/yketV.png)
After set it, you'll don't need to change the parallel number back and forth any more. Just define the demand to limit the agent used. When the pipeline running, it will pick up the relevant agent to execute the pipeline.
But, as well, this still has disadvantage. This will also limit the job parallel.
I think this feature should be expand into Azure Devops thus user can have better experience of Azure Devops. You can raise the suggestion in our [official Suggestion forum](https://developercommunity.visualstudio.com/content/idea/post.html?space=21). Then vote it. Our product group and PMs will review it and consider taking it into next quarter roadmap. |
14,206 | I'm looking to gather some more background, context, sources and opinions, regarding Mordechai's religiousness, or lack thereof.
This was the topic of a recent comment thread on [Was Darius Jewish?](https://judaism.stackexchange.com/q/13095/459), specifically on [@avi](https://judaism.stackexchange.com/users/597/avi)'s [answer](https://judaism.stackexchange.com/a/13099/459).
Though this was not the topic of the question nor the answer, a side comment turned into a long thread on this.
Instead of hashing it out there, and just between us, I thought it would be a good idea to gather some additional voices.
So, to the issue:
Many well-known midrashim pose Mordechai as a tzaddik, a religious leader, and even a member of the Sanhedrin. I'm sure we all learned these at one point or another.
On the other hand, reading the Megilla as a "story", focusing on the pshat, but taking into account the historical and cultural context, in addition to relevant background added by other books in the Tanach (such as Melachim Bet, Divrei Hayamim, and other Nevi'im) - it would seem that this was not the case. At the least, there is no evidence or basis for the "religious figure" theory, but rather the evidence seems (at least to me) to point in the opposite direction.
Now, taking into account the intended ambiguity, which is one of the most fundamental motifs of the Megilla, and the obvious historical distance, I don't expect to find "the one true history"...
But I am interested in hearing, what is the basis for the "religious leader" theory? Is there evidence for this, or is it "just" Midrash\* ? What was the original source? What is the Midrash based on? (Obviously besides the Midrash itself, and the persuant discussions in e.g. Gmara\*... )
Or, alternatively (and preferably), sources and explanations for the opposite theory?
EDIT: To emphasize, I am referring to Mordechai's "back story". Even according to the "non-religious" theory, there is plenty of room to allow for a change of heart as a result of the Purim events. Therefore anything that relates to his situation *after* the fact (such as @follick's excellent source in Nechemia) would be besides the point.
EDIT2: I don't intend on *ignoring* the midrashim, nor do I expect to be completely independant of them. Rather, I'm interested in the *basis* of those midrashim, as these are usually based on *something*, be it a reference, alliteration, extraneous wording, "secret" story, etc.
---
(\*) I'm not belittling the importance of those Midrashim or the discussions in the Gmara, of course, but it is both [important and extremely difficult](https://judaism.stackexchange.com/questions/4037/does-one-have-to-take-a-midrash-aggadah-literally) to discern which stories are intended to be accepted literally, as "historical fact", and which not.
Hence this question. | 2012/02/12 | [
"https://judaism.stackexchange.com/questions/14206",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/459/"
] | There was [Nechemia 7:7](http://www.chabad.org/library/bible_cdo/aid/16514/jewish/Chapter-7.htm) Which lists Mordechai amongst the leaders of Israel. And also [Ezra 2:2](http://www.chabad.org/library/bible_cdo/aid/16499/jewish/Chapter-2.htm) Which does likewise. | Here is a book you may be interested in: [Yoram Hazony, *The Dawn. Political Teachings of the Book of Esther*](http://rads.stackoverflow.com/amzn/click/9657052068). I recommend it. It is well-reasearched and is based on the classical Jewish sources. It probably won't sit well with the ultra-orthodox public (I'm not being disrespectful here, it's just the shortest way to express what I mean).
Hazony treats Mordechai mainly as a political figure. His main thrust is the political lessons that Jews in Diaspora can learn from The Book of Esther. He also underscores in what respects Mordechai's moves are uniquely informed by his Jewish worldview - unlike his adversaries that are moved by mostly unrestrained dark emotions.
The fact that Mordechai was a historic figure is not corroborated by independent sources. So the Meggilah is our only source of information about him - we do not know any other Mordechai, if you will. The Meggilah calls him Mordechai Ha-Yehudi - being Jewish is his essential quality. It's in the text, you can't argue with it (well, unless you are Jewish ;) ). Now, for the Rabbis being Jewish meant (and means) being pious, observant, G-d-rearing - in short, a Tzaddik. At 'worst' he'd be a baal-teshuva. That's, in my opinion, is the basis for all those well-known midrashim. (This reminds me of a famous joke: *"There is a proof from the Torah that Moshe wore a shtreimel, it says: וילך משה ('and Moshe went'). Can you imagine that he went without a shtreimel?"*).
For Hazony, on the other hand, who is more concerned with the political future of the Jewish 'enterprise' in general and the Zionist enterprise in particular - he is first and foremost a political leader. |
18,688 | Is there any thing that Buddhism can add to a Stoic Pursuit?
Below is a friendly laid-back discourse between a Stoic and a Buddhist, which could be used as a guide to what I’m trying to compare.
Buddhist: *Birth is suffering, aging is suffering, death is suffering; sorrow, lamentation, pain, grief, & despair are suffering; association with the unbeloved is suffering; separation from the loved is suffering; not getting what is wanted is suffering. In short, the five clinging-aggregates are suffering.*
Stoic: *Yes, if you attach yourself to what is not given you will sure suffer. These five aggregates you counted must have been something not in your power. Have you nothing which is in your own power, which depends on yourself only and cannot be taken from you, or have you any thing of the kind?*
Buddhist: *what do you mean, there are only five aggregates there is no I or mine*
Stoic: *what? Is any man able to make you assent to that which is false or compel you to desire what you do not wish?*
Buddhist: *No*
Stoic: *In the matter of assent and desire then you are free from hindrance and obstruction?*
Buddhist: *Yes*
Stoic: *So, if we let go of the body which is subject to revolution of the whole and withdraw from externals, turns to our will to exercise it and to improve it by labor, so as to make it conformable to nature, elevated, free, unrestrained, unimpeded, faithful, modest, and virtuous will we not achieve tranquility and avoid suffering.*
Buddhist: *Well said, training an act of will is a noble did, but until you learn that there is no “I or my-self” you would remain in cycle of rebirth.*
Stoic: *what do you mean?*
Buddhist: *But what is that you call my-self or I?*
Stoic: *Sir, it’s my soul. If you ask me what is a soul I can’t say this or that, but I have just told you an attribute of mine which is not bound by suffering. Will you be kind enough to show me that my act of will is not mine?*
Buddhist: *If that you call mine is the volitional formation you should know that it has ignorance as conditions and he who assume volition to be the self will surely be afflicted in mind.*
Stoic: *I do not understand, you seem to me to be talking very obscure, you surly do not mean that the all wise will not act?*
Buddhist: *No, I’m saying you should not say volition is mine.*
Stoic: *Why?*
Buddhist: *Perhaps you will understand if you look at it from another angle. Answer my question, by acting virtuously and by wisdom you are training the will towards the good?*
Stoic: *Yes*
Buddhist: *When the will become all virtuous, all wise and attain the good with no trace of ignorance will you claim that all wise will to be yours.*
Stoic: *Far from it, there is but only one wise. If at all possible to reach of what you speak without quitting the body then the act of will be one with the one.*
HE | 2016/12/30 | [
"https://buddhism.stackexchange.com/questions/18688",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/-1/"
] | Stoicism is straight to the point, which is nice, but Buddhism covers a bit more territory. Also, Stoicism requires less etymology to understand.
There are a few kinds of attachments that cause mental anguish. Buddhism attempts to end all forms of this, plus increase insight and awareness, and allow one to experience different mental states, like jhanas.
So, for example, if someone insults Jane, an all too often reaction is for her to defend her identity, her values, what she owns, and what she thinks she is. This creates a lot of unnecessary stress, and this defensiveness can turn into an argument.
Buddhism aims to increase empathy and compassion, decreasing conflict: By understanding ourselves we understand the world better. This in turn removes conflict and ill-will, removing unnecessary stress.
Buddhism aims to remove mana, which is a kind of comparison that creates jealousy and hurt.
Eventually Buddhism overlaps with Stoicism, removing quite a bit of attachment. However, as far as I can tell that's where Stoicism mostly begins and ends. Buddhism gets to the point where new attachment is not created, so that there is no future suffering. However, I haven't seen anywhere in Stoicism going this far, only dissolving attachment once the suffering has started.
All in all, Stoicism and Buddhism do overlap, but Stoicism is a bit of a blip on the map. | I don't know Stoicism well enough, but your question seems to wonder how to add something that somehow enhances Stoicism. This is the wrong approach.
Eg: rebirth is a central tenet of Buddhism IMHO, what does Stoicism say about that? Helping other, creating merit and virtue, cultivating the mind are central to Mahayana Buddhism AFAIK, what does Stoicism say about that? I feel that it's like a blip in the Buddhist map, like someone said. |
15,488,354 | I dont know why I am getting this error, I think this morning i ran this query without errors and it worked.. I am trying to merge two different tables into one table, the tables have the same fields, but different values.
I am using:
```
create table jos_properties_merged engine = MERGE UNION =
(mergecasas.jos_properties_contacts,viftestdb.buu_properties_contacts);
```
And i get
```
"#1113 - A table must have at least 1 column "
```
DO you know what I am doing wrong, please? | 2013/03/18 | [
"https://Stackoverflow.com/questions/15488354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2105729/"
] | according to [this link](http://dev.mysql.com/doc/refman/5.0/en/merge-storage-engine.html) you need to specify the exact same columns existing in your 2 tables:
>
> CREATE TABLE t1 (
> a INT NOT NULL AUTO\_INCREMENT PRIMARY KEY,
> message CHAR(20)) ENGINE=MyISAM;
>
>
> CREATE TABLE t2 (
> a INT NOT NULL AUTO\_INCREMENT PRIMARY KEY,
> message CHAR(20)) ENGINE=MyISAM;
>
>
> INSERT INTO t1 (message) VALUES ('Testing'),('table'),('t1'); mysql> INSERT INTO t2
> (message) VALUES ('Testing'),('table'),('t2');
>
>
> CREATE TABLE
> total (
> -> a INT NOT NULL AUTO\_INCREMENT,
> -> message CHAR(20), INDEX(a))
> -> ENGINE=MERGE UNION=(t1,t2) INSERT\_METHOD=LAST;
>
>
> | ```
CREATE TABLE [IF NOT EXISTS] table_name(
column_1_definition,
column_2_definition,
...,
table_constraints
) ENGINE=storage_engine;
```
>
> Or: (example)
>
>
> mysql>
>
>
>
```sql
Create Table films (
name varchar(20),
production varchar(20),
language varchar(20)
);
``` |
47,223,183 | I am unable to grep a file from a shell script written. Below is the code
```
#!/bin/bash
startline6=`cat /root/storelinenumber/linestitch6.txt`
endline6="$(wc -l < /mnt/logs/arcfilechunk-aim-stitch6.log.2017-11-08)"
awk 'NR>=$startline6 && NR<=$endline6' /mnt/logs/arcfilechunk-aim-stitch6.log.2017-11-08 | grep -C 100 'Error in downloading indivisual chunk' > /root/storelinenumber/error2.txt
```
The awk command is working on standalone basis though when the start and end line numbers are given manually. | 2017/11/10 | [
"https://Stackoverflow.com/questions/47223183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4042248/"
] | According with how the log4j works, it will log everything that matches the filter into the file.
But the root logger will still log all related "INFO" from all the sources....
So its not possible to remove from the root logger this behavior. What you can do is: put something more detailed for the filter and interchange both.
Like below:
```
<logger name="my.package.a" level="INFO" additivity="false">
<appender-ref ref="FILE-A"/>
</logger>
<root level="WARN">
<appender-ref ref="FILE-STD"/>
</root>
``` | From [documentation](https://logback.qos.ch/manual/configuration.html):
>
> logger has its additivity flag set to false such that its logging output will be sent to the appender named FILE but not to any appender attached **higher** in the hierarchy
>
>
>
So, it's all about ordering of appenders and loggers in your *logback.xml*.
Appenders should be declared **higher** than this logger. |
49,381 | My native iPhone Contacts show not only my contacts with phone numbers, but also any email address I’ve ever sent an email to or received an email from. I really would rather not have email contacts save into my contact list automatically. Is there a way to stop this from happening? | 2012/04/22 | [
"https://apple.stackexchange.com/questions/49381",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/21962/"
] | In Gmail Settings, under General, check the following option:
[](https://i.stack.imgur.com/1DbCC.png)
Then go to Contacts and delete all the Other Contacts that were previously added automatically. Performing this action in Gmail will be faster than on your iPhone because you can select all those contacts with a single click. Then, just wait for the deletions to propagate to your iPhone. | Go to Phone then select Contacts, or select the Contacts app directly. In the upper left corner select Groups, then remove Suggested Contacts from the list of synced contacts. |
6,366,411 | I have some object, which extends movie clip:
```
public class MyClass extends MovieClip { ... }
```
Now, I want to put two of this in the stage:
```
var obj:MyClass = new MyClass();
addChild(obj);
```
That would put one, but the other I want it to be exactly the same as the first, so I just need to add a "reference" of `obj` to the stage, along with `obj` itself.
In the end, I want two objects of type MyClass doing the same thing in the stage. If I try to simply do:
```
var obj2 = obj;
addChild(obj2);
```
only obj2 will appear in the stage.
How could I achieve that with references? (in order to save memory and CPU time (it is really important))
Thanks in advance! | 2011/06/16 | [
"https://Stackoverflow.com/questions/6366411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/488229/"
] | If you're going to create multiple instance simultaneously, just use a for loop:
```
var i:uint = 0;
for(i; i<2; i++)
{
var t:MyClass = new MyClass();
// properties of t
addChild(t);
}
```
If you want to do it later on down the track, you could try something like this:
```
function getCopy(taget:MyClass, ...attrs):MyClass
{
var t:MyClass = new MyClass();
var i:String;
for each(i in attrs)
{
t[i] = target[i];
}
return t;
}
```
The downside is that you have to specify what properties you want to inherit.
```
var m:MyClass = new MyClass();
m.x = 10;
m.y = 30;
var b:MyClass = getCopy(m, "x", "y");
trace(b.x, b.y); //output: 10, 30
``` | You can't. You have to create 2 instances. |
233,158 | I use Ubuntu 9.10 (Karmic) and I have a directory with many files, among them these two files:
```
./baer.jpg
./bär.jpg
```
I would like to delete `bär.jpg` but I can't.
If I type `rm b` and hit `TAB`, it shows me both files, if I append `ä` and hit `TAB`, nothing gets displayed.
What must be done in order to delete `bär.jpg`?
Deleting the parent folder is not a solution for me, as there are plenty of files in this directory that are used by a productive environment. | 2012/12/27 | [
"https://askubuntu.com/questions/233158",
"https://askubuntu.com",
"https://askubuntu.com/users/10561/"
] | I just found out how to delete such files witch special characters:
1. `cd <directory with that file>`
2. `ls -ali`
3. At the very left of the directory listing you see the ID of the inode of each file.
4. Delete your file via inode ID:
`find . -inum <inode ID of your file> -exec rm -i {} \;`
This worked fine for my issue. Hope this helps! | You could use [bash wildcards](http://www.tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm) with
```
rm b?r.jpg
```
where `?` stands for exactly one character. An alternative (if both file names were the same length) would be
```
rm b[!e]r.jpg
```
where `[!e]` means any character except "e". |
15,744,424 | ya'll I have a bit of a structural/procedural question for ya.
So I have a pretty simple ember app, trying to use ember-data and I'm just not sure if I'm 'doing it right'. So the user hits my index template, I grab their location coordinates and encode a hash of it (that part works). Then on my server I have a db that stores 'tiles' named after there hash'd coords (if i hit my `#/tiles/H1A2S3H4E5D` route I get back properly formatted JSON).
What I would like to happen next, if to display each of the returned tiles to the user on the bottom of the first page (like in a partial maybe? if handlebars does that).
I have a `DS.Model` for the tiles, if I hard code the Hash'd cords into a `App.find(H1A2S3H4E5D)`; I can see my server properly responding to the query. However, I cannot seem to be able to figure out how to access the returned JSON object, or how to display it to the user.
I did watch a few tutorial videos but they all seem to be outdated with the old router.
Mainly I would like to know:
1. Where does the information returned by `App.find()`; live & how to access it?
2. what is the 'correct' way to structure my templates/views to handle this?
3. how should I pass that id (the hash'd coords) to `App.find`? as a global variable? or is there a better way?
the biggest problem(to me) seems to be that the id I search by doesn't exist until the user hit the page tho first time. (since its dynamically generated) so I can't just grab it when the page loads.
*I can post a fiddle if required, but I'm looking for more of a conceptual/instructional answer rather then some one to just write my code for me* | 2013/04/01 | [
"https://Stackoverflow.com/questions/15744424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/910296/"
] | If you use pipe to redirect contents to your function/script it will run your command in a sub-shell and set stdin (`0`) to a pipe, which can be checked by
```sh
$ ls -l /dev/fd/
lr-x------ 1 root root 64 May 27 14:08 0 -> pipe:[2033522138]
lrwx------ 1 root root 64 May 27 14:08 1 -> /dev/pts/11
lrwx------ 1 root root 64 May 27 14:08 2 -> /dev/pts/11
lr-x------ 1 root root 64 May 27 14:08 3 -> /proc/49806/fd
```
And if you called `read`/`readarray`/... command in that function/script, the `read` command would return immediately whatever read from that pipe as the stdin has been set to that pipe rather than the tty, which explained why `read` command didn't wait for input. To make `read` command wait for input in such case you have to restore stdin to tty by `exec 0< /dev/tty` before the call to `read` command. | Seems I'm late to the party, but `echo -n "Your prompt" && sed 1q` does the trick on a POSIX-compliant shell.
This prints a prompt, and grabs a line from STDIN.
Alternatively, you could expand that input into a variable:
```
echo -n "Your prompt"
YOUR_VAR=$(sed 1q)
``` |
9,153,084 | I'm trying to parse the result string from a system command to an external program.
```
[status,result] = system(cmd);
```
result prints out on my console with its lines correctly broken out, i.e.
line1
line2
...
But it's actually just a single long character array, and there are no newline characters anywhere. How does matlab know when to print out a new line? And how can I separate the char array into its separate lines for further parsing. Thanks! | 2012/02/05 | [
"https://Stackoverflow.com/questions/9153084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1122623/"
] | Further to Andrey's answer, you can split the string into a cell array using the following command:
```
split_result = regexp(result, '\n', 'split');
```
This uses regular expressions to split the string at each newline character.
You can then access each line of the system command output using:
```
split_result{index}
``` | As of Matlab R2016b you may also use the command `splitlines()` which will automatically handle the newline definitions for you. |
59,060,791 | I was finally able to get the array copied and reversed instead of replaced and reversed. what can I try next?
```js
function copyAndReverseArray(array) {
array.slice(0).reverse().map(function(reversed) {
return reversed;
});
}
//Don't change below this line
const original = [1, 2, 9, 8];
const reversed = copyAndReverseArray(original);
console.log(original, '<--this should be [1, 2, 9, 8]');
console.log(reversed, '<--this should be [8, 9, 2, 1]');
```
I know my reverse function is working, when I console.log the reversed array, directly in the function.
```js
function copyAndReverseArray(array) {
array.slice(0).reverse().map(function(reversed) {
console.log(reversed);
return reversed;
});
}
//Don't change below this line
const original = [1, 2, 9, 8];
const reversed = copyAndReverseArray(original);
console.log(original, '<--this should be [1, 2, 9, 8]');
console.log(reversed, '<--this should be [8, 9, 2, 1]');
```
How do I get "reversed" to print from the console.log calling it at the bottom without changing the code below the "//Don't change below this line"? | 2019/11/26 | [
"https://Stackoverflow.com/questions/59060791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10665079/"
] | Your code its ok, just dont forget the scope theory.
The map actually reversed the list as you spect and return the reversed list, but that result only live into the fuction scope (copyAndReverseArray), so you need to return that value again for got it in a superior scope: global scope in this case. If not return the result, you will continue to have an undefined value
so, try this:
```
function copyAndReverseArray(array){
return array.slice(0).reverse().map(function (reversed) {
return reversed
});
}
```
And then, you can assign the result to a var as you have been trying
```
const original = [1, 2, 9, 8];
const reversed = copyAndReverseArray(original);
console.log(original, '<--this should be [1, 2, 9, 8]');
console.log(reversed, '<--this should be [8, 9, 2, 1]');
``` | Does this work for you?
```
function copyAndReverseArray(array){
reversedArray = Object.assign([],array)
return reversedArray.reverse()
}
``` |
31,885,207 | I would like to disable the seekbar but keep the pause and play buttons in a media controller object. I don't want users to be able to skip through the video, but they can pause if needed.
I've looked at other questions like this but they didn't make sense to me. If I could get any help on this that would be great! | 2015/08/07 | [
"https://Stackoverflow.com/questions/31885207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5203393/"
] | In order to use WebSockets you first need to get a `token` calling the `authorization` api. Then you will add that `token` into the `url`.
The Websocket url is:
```
wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize?watson-token=TOKEN
```
Where `TOKEN` can be created by doing (example in curl):
```
curl -u USERNAME:PASSWORD "https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api"
```
`USERNAME` and `PASSWORD` are your service credentials.
That's basically a `GET` request to
```
https://stream.watsonplatform.net/authorization/api/v1/token
```
with a `url` query parameter that is the service you want to get the token for. In this case:
```
https://stream.watsonplatform.net/speech-to-text/api
```
---
If you are using nodejs, I would suggest you to use the `watson-developer-cloud` npm module. Take a look at [this](https://gist.github.com/germanattanasio/359580d99ea22f47c6ba) snippet which shows you how to do real time transcription using the Speech to Text service. | Watson's Speech-to-Text Service does not support Web Sockets. [A detailed explanation can be found here](https://developer.ibm.com/answers/questions/174846/using-websockets-in-speech-to-text.html).
You are going to need to use a different protocol. A guide to connecting to Watson's API via Node.js can be found [here](https://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/getting_started/gs-quick-nodejs.shtml#quickStart).
Hope this helps! |
49,655,473 | ```
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class ProductoServiceService {
constructor(private http:Http) {}
//Generamos las funciones que nos serviran para manipular nuestras entidades
listar() {
return
```
this.http.get('<http://localhost:4200/www/appArtemaya/src/app/productos.php>');
```
}
}
``` | 2018/04/04 | [
"https://Stackoverflow.com/questions/49655473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7393514/"
] | You can do chain:
```
if (apple && apple.details && apple.details.price) { ... }
```
But it's not convenient if the chain is long. Instead you can use [lodash.get method](https://lodash.com/docs/4.17.5#get)
With lodash:
```
if (get(apple, 'details.price')) { ... }
``` | You may try solution of @Sphinx
I would also suggest \_.get(apple, 'details.price') of [lodash](http://lodash.com), but surely it is not worth to include whole library for simple project or few tasks.
\_.get() function also prevents from throwing error, when even apple variable is not defined (undefined) |
80,148 | There are numerous Christians hymns and references in Christian literature that Jesus was "forsaken by all mankind, yet to be in Heaven' enthroned", etc.
In essence, there is this powerful image of Christ hanging crucified on the cross bearing the sins of all mankind, totally abandoned. (cf. Mark 15:34)
The Gospels, however, at least the Gospel of John, presents the apostle John and Mary the mother of Jesus present at the crucifixion (cf. John 19:26–27), showing somehow that not every human betrayed or forsaken Christ.
Are the Christian hymns a simple exaggeration to make a point, or was Jesus indeed literary forsaken by all humans? If so, how are we to interpret the passages cited in John's Gospel? | 2020/12/21 | [
"https://christianity.stackexchange.com/questions/80148",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/18392/"
] | Many hymns get some of their lyrics wrong, either stretching, or glossing over a point to make the meter fit the tune, and there is always the danger of wrong theology when deviating from the actual words of scripture. The line you quote is a case in point. Witnessing Christ’s crucifixion was his mother, Mary, her sister, Mary the wife of Cleophas, and Mary Magdalene, and the apostle John (John 19:25).
However, the word ‘mankind’ does not necessarily mean every human alive at any given time! The abandonment that happened was the fulfilment of the ancient prophecy that God would “strike the shepherd and the sheep will be scattered” Zechariah 13:7, quoted by Jesus in Matthew 26:31, before the event. Even though he knew he would be abandoned by virtually all his followers, the worst abandonment was that of the Father, forsaking the Son (Mark 15:34).
I searched through a lot of hymns without finding even one verse that said Jesus was totally and utterly abandoned. But when I do find verses that are not entirely scriptural, I either don’t sing them, or personally modify the offending words. In the line you quote, I would view it as portraying how none was ever so abandoned as was Christ, on the cross. Humanity, during those dark hours, had no idea what was really going on, including his own disciples, and his own mother. It wasn’t until after his resurrection that they saw it all differently, from the divine perspective. No doubt those who had abandoned him were cut to their hearts and truly repented, none more so than Peter. | Luke 23 (KJV):
>
> 39 And one of the malefactors which were hanged railed on him, saying,
> If thou be Christ, save thyself and us.
>
>
> 40 But the other answering rebuked him, saying, Dost not thou fear
> God, seeing thou art in the same condemnation?
>
>
> 41 And we indeed justly; for we receive the due reward of our deeds:
> **but this man hath done nothing amiss.**
>
>
> 42 **And he said unto Jesus, Lord, remember me when thou comest into thy
> kingdom.**
>
>
> 43 **And Jesus said unto him, Verily I say unto thee, Today shalt thou
> be with me in paradise.**
>
>
>
Clearly this was one human who believed in Jesus and not "abandoned" him, even under the direst of circumstances. |
6,691,979 | I have a Gmap that has to zoom in bit by bit. To achieve this I need the Google map zoom level to be formatted like this '4.001'. I tried doing this by simply add this value as zoom level but it doesn't work.
So my question is how to achieve a Google map zoom level using multiple numbers behind the decimal. Is it even possible? If not, how do I achieve the slowly precise zooming?
Thanks | 2011/07/14 | [
"https://Stackoverflow.com/questions/6691979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/475362/"
] | You can gradually CSS-zoom the map canvas from 1 to 2, perhaps also masking the surroundings with elements.
Then in one call change the css-zoom back to 1 and decrease the maps-zoom by one.
You will see that streets, names and lines zoom along during the zoom, which is an unwanted artefact, but it sure looks smoother than the maps' zoom.
A zoom of 4.5 could be achieved by setting the maps zoom to 4 and the CSS-zoom to 1.5.
If you don't like the lo-res result you could do the opposite: set the CSS-zoom to 0.5 and the maps-zoom to 5. Both wil have their pros and cons in terms of data-usage, pixel density, object sizes. | In the Chrome browser, a workaround is to alternate zooming between the GMaps + and - and using "Ctrl -" and "Ctrl +" on your keyboard. This latter zoom is within Chrome.
Between the two methods you can get a more customized zoom level. One benefit from going back and forth is that you can optimize text size at the same time. |
54,540,928 | I have a field which is a varchar(20)
When this query is executed, it is fast (Uses index seek):
```
SELECT * FROM [dbo].[phone] WHERE phone = '5554474477'
```
But this one is slow (uses index scan).
```
SELECT * FROM [dbo].[phone] WHERE phone = N'5554474477'
```
I am guessing that if I change the field to an nvarchar, then it would use the Index Seek. | 2019/02/05 | [
"https://Stackoverflow.com/questions/54540928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/425823/"
] | Because `nvarchar` has higher [datatype precedence](https://learn.microsoft.com/en-us/sql/t-sql/data-types/data-type-precedence-transact-sql?view=sql-server-2017) than `varchar` so it needs to perform an implicit cast of the column to `nvarchar` and this prevents an index seek.
Under some collations it is able to still use a seek and just push the `cast` into a residual predicate against the rows matched by the seek (rather than needing to do this for every row in the entire table via a scan) but presumably you aren't using such a collation.
The effect of collation on this is illustrated below. When using the SQL collation you get a scan, for the Windows collation it calls the internal function [`GetRangeThroughConvert`](https://blogs.msdn.microsoft.com/arvindsh/2012/09/17/sql-collation-and-performance/) and is able to convert it into a seek.
```
CREATE TABLE [dbo].[phone]
(
phone1 VARCHAR(500) COLLATE sql_latin1_general_cp1_ci_as CONSTRAINT uq1 UNIQUE,
phone2 VARCHAR(500) COLLATE latin1_general_ci_as CONSTRAINT uq2 UNIQUE,
);
SELECT phone1 FROM [dbo].[phone] WHERE phone1 = N'5554474477';
SELECT phone2 FROM [dbo].[phone] WHERE phone2 = N'5554474477';
```
[](https://i.stack.imgur.com/hpEU9.png)
The `SHOWPLAN_TEXT` is below
**Query 1**
```
|--Index Scan(OBJECT:([tempdb].[dbo].[phone].[uq1]), WHERE:(CONVERT_IMPLICIT(nvarchar(500),[tempdb].[dbo].[phone].[phone1],0)=CONVERT_IMPLICIT(nvarchar(4000),[@1],0)))
```
**Query 2**
```
|--Nested Loops(Inner Join, OUTER REFERENCES:([Expr1005], [Expr1006], [Expr1004]))
|--Compute Scalar(DEFINE:(([Expr1005],[Expr1006],[Expr1004])=GetRangeThroughConvert([@1],[@1],(62))))
| |--Constant Scan
|--Index Seek(OBJECT:([tempdb].[dbo].[phone].[uq2]), SEEK:([tempdb].[dbo].[phone].[phone2] > [Expr1005] AND [tempdb].[dbo].[phone].[phone2] < [Expr1006]), WHERE:(CONVERT_IMPLICIT(nvarchar(500),[tempdb].[dbo].[phone].[phone2],0)=[@1]) ORDERED FORWARD)
```
In the second case the compute scalar [emits the following values](https://www.sqlshack.com/query-trace-column-values/)
```
Expr1004 = 62
Expr1005 = '5554474477'
Expr1006 = '5554474478'
```
the seek predicate shown in the plan is on `phone2 > Expr1005 and phone2 < Expr1006` so on the face of it would exclude `'5554474477'` but the flag `62` means that this does match. | Other answers already explain *what* happens; we've seen `NVARCHAR` has higher type precedence than `VARCHAR`. I want to explain **why** the database must cast every row for the column as an `NVARCHAR`, rather than casting the single supplied value as `VARCHAR`, even though the second option is clearly much faster, both intuitively and empirically. Also, I want to explain why the performance impact can be so drastic.
Casting from `NVARCHAR` to `VARCHAR` is a **narrowing** conversion. That is, `NVARCHAR` has potentially more information than a similar `VARCHAR` value. It's not possible to represent every `NVARCHAR` input with a `VARCHAR` output, so casting from the former to the latter potentially *loses information*. The opposite cast is a *widening* conversion. Casting from a `VARCHAR` value to an `NVARCHAR` value never loses information; it's **safe**.
The principle is for SQL Server to always choose the safe conversion when presented with two mismatched types. It's the same old "correctness trumps performance" mantra. Or, to paraphrase [Benjamin Franklin](https://oll.libertyfund.org/quotes/484), "He who would trade essential correctness for a little performance deserve neither correctness nor performance." The type precedence rules, then, are designed to ensure the safe conversions are chosen.
Now you and I both know your narrowing conversion is also safe for this particular data, but the SQL Server query optimizer doesn't care about that. For better or worse, it sees the data type information first when building the execution plan and follows the type precedence rules.
---
This explains why SQL Server has to take the slower option. Now let's talk about why the difference is so drastic. The kicker is once we've determined we have to cast the stored data, rather than the constant value in the query, we have to do it for ***every row in the table***. This is true even for rows which would not otherwise match the comparison filter, because you don't know if the row will match for the filter or not until after you cast the value for the comparison.
But it gets worse. The cast values from the column are *no longer the same as the values stored in any indexes* you might have defined. The result is **any index on the column is now worthless for this query**, which cuts to the core of database performance.
I think you're *very lucky* to get an index scan for this query, rather than a full table scan, and it's likely because there is a covering index that meets the needs of the query (the optimizer can choose to cast all the records in the index as easily as all the records in the table).
---
You can fix things for this query by explicitly resolving the type mismatch in a more favorable way. The best way to accomplish this is, of course, supplying a plain `VARCHAR` in the first place and avoid any need for casting/conversion at all:
```
SELECT * FROM [dbo].[phone] WHERE phone = '5554474477'
```
But I suspect what we're seeing is a value provided by an application, where you don't necessarily control that part of the literal. If so, you can still do this:
```
SELECT * FROM [dbo].[phone] WHERE phone = cast(N'5554474477' as varchar(20))
```
Either example favorably resolves the type mismatch from the original code. Even with the latter situation, you may have more control over the literal than you know. For example, if this query was created from a .Net program the problem is possibly related to the `AddWithValue()` function. [I've written about this issue in the past](https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) and how to handle it correctly.
These fixes also help demonstrate why things are this way.
---
It may be possible at some point in the future the SQL Server developers enhance the query optimizer to look at situations like this — where type precedence rules cause a per-row conversion resulting in a table or index scan, but the opposite conversion involves constant data and could be just an index seek — and in that case first look at the data to see if the faster narrowing conversion could also be safe.
However, I find it unlikely this will ever happen. In my opinion, the corrections to queries within the existing system are too easy relative to the additional cost of evaluating individual queries and the complexity in understanding what the optimizer is doing ("Why didn't the server follow the documented precedence rules here?") to justify it. |
3,561,894 | I am having trouble calculating the following integral:
$$ {\int \sqrt{c-\cos(t)} dt} $$
where $c$ is a constant.
In the very specific case where $c=1$, it is rather easy, but I cannot seem to be able to generalize that.
I tried running it with Wolfram but it produces higher-than-my-paygrade math ([example](https://www.wolframalpha.com/input/?i=integrate+sqrt%284+-+cos%28psi%29%29)) about elliptic integrals and I can't help but think it should be easier than that. | 2020/02/27 | [
"https://math.stackexchange.com/questions/3561894",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/349202/"
] | No, it is not easier than that. Wolfram showing you "weird" functions is a sure sign, if not a proof\*.
The elliptic integrals have become very classical. <https://en.wikipedia.org/wiki/Elliptic_integral>
It is easy to understand why the case of $c=1$ is simpler. In the plots you see that the blue curve *is* a (rectified) sinusoid, while the others are not, as can be checked analytically.
[](https://i.stack.imgur.com/Np7OX.png)
---
\*A proof is possible but highly technical, based on Liouville's theorem. <https://en.wikipedia.org/wiki/Liouville%27s_theorem_(differential_algebra)>
---
Also note that a simple integrand rarely means a simple antiderivative. Try `integrate 1/(x^5+1)`. | For the specific case where $~=1~$, this integral is rather easy because here you can use a trigonometric formula $~1-\cos t~=~2\sin^2\left(\frac{t}{2}\right)~$ directly in the second line and got a known trigonometric function $\big($here it is $\sin\left(\frac{t}{2}\right)\big)$ which can be integrable by known formula (as we have the knowledge that anti-derivative of $~\cos t~$ is $~\sin t~+~c$, where $c$ is a constant) . But for the value $~c=2~$or more you can't find such form.
**For example**, if you take $~c=2~$, you got (after some steps) a function as $~\sqrt{2\sin^2\left(\dfrac{t}{2}\right)+1}~$. There is no elementary function whose derivative is $~\sqrt{2\sin^2\left(\dfrac{t}{2}\right)+1}~$. Here you have to allow yourself to know about a special integral called **[incomplete elliptic integral of the second kind](https://en.wikipedia.org/wiki/Elliptic_integral#Incomplete_elliptic_integral_of_the_second_kind)**.
* Here is the complete solution of the given integral.
\begin{equation}
I={\displaystyle\int}\sqrt{c-\cos\left(t\right)}\,\mathrm{d}t\\
={\displaystyle\int}\sqrt{c-1}\cdot\sqrt{\dfrac{2\sin^2\left(\frac{t}{2}\right)}{c-1}+1}\,~\mathrm{d}t\\
\end{equation}
Substituting $~u=\dfrac{t}{2}~$, so $~\mathrm{d}t=2\,\mathrm{d}u~$. Now
\begin{equation}
I=\class{steps-node}{\cssId{steps-node-1}{2\sqrt{c-1}}}{\cdot}{\displaystyle\int}\sqrt{\dfrac{2\sin^2\left(u\right)}{c-1}+1}\,~\mathrm{d}u\tag1
\end{equation}
>
> We know that
> \begin{equation}
> {\displaystyle\int}\sqrt{\dfrac{2\sin^2\left(u\right)}{c-1}+1}\,\mathrm{d}u~~
> =~~\operatorname{E}\left(u\,\middle|\,-\dfrac{2}{c-1}\right)
> \end{equation}
> This is a special integral ([incomplete elliptic integral of the second kind](https://en.wikipedia.org/wiki/Elliptic_integral#Incomplete_elliptic_integral_of_the_second_kind)).
>
>
>
Hence from $(1)$ ,
\begin{equation}
I~=~2\sqrt{c-1}~\operatorname{E}\left(u\,\middle|\,-\dfrac{2}{c-1}\right)~+~K\\
=2\sqrt{c-1}\operatorname{E}\left(\dfrac{t}{2}\,\middle|\,-\dfrac{2}{c-1}\right)~+~K
\end{equation}
where $~K~$ is constant and $~c\ne 1~$.
For $~c=1~$, the value of the integral is $$~I~=~-2^\frac{3}{2}\cos\left(\dfrac{t}{2}\right)+K~$$ |
190,086 | I am a software developer with 10 years of professional experience. In order to gain experience leading a team, I have decided to be involved in a side project with a friend who switched careers via a coding bootcamp, people he met there and some fresh college grads. This friend has over a decade of experience in other fields with some management experience. So he runs the weekly meeting. Said friend and I are responsible for the back-end programming portion of the project.
Most meetings or weekends when I try to work with him, he says he's too tired from his day job or family. He did ask me to help once, but I had unplanned obligations and when I got home, I followed up to which he replied he was burned out.
I have written functioning code and given it to friend to make some changes to. It's a good opportunity to gain experience and ask questions. I have written instructions on how to run everything he needs, and prerequisites he needs like Python and a JRE. However, I didn't go through every step to install the prerequisites; I gave him links with instructions. He is insisting that he be provided with explicit numbered instructions; I explained that the purpose is to move from an I'm lost mindset to an I can solve this mindset. All of this can be learned by searching and reading.
It's an important skill in software development when you're faced with a challenge which is why I objected. Later, he told me I make the meetings toxic that I need to be supportive and honestly, I'm aggravated. I would be more receptive if he tried things and had questions. I find helping people who ask programming questions at work rewarding when I can solve them, but it seems like he just wants to be spoon fed. What can I do to lead appropriately? Am I asking too much of someone with coding bootcamp experience?
Edit: I've been texting him since November and asking at the meeting if he looked at it and to reach out with questions. He almost always said he was tired. He has only recently said he looked at it. | 2023/02/17 | [
"https://workplace.stackexchange.com/questions/190086",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/-1/"
] | Incremental Learning only works if there's something to increment on.
The poor guy has nothing. The DEV environment isn't working, the configuration instructions are incomplete, and he has no idea what's going on, since setting up the DEV environment is really a Systems Administration task.
Without a working environment, he has nothing, and building on top of nothing is literally one of the most difficult task in existence.
Your first task for this (effectively) junior developer shouldn't be setting up a DEV environment, but to run code.
In addition, you also mention both Python and JRE (Java). That's just about as confusing as ever. He might be trying to `python main.java` and have no idea what's happening. Python isn't going to tell him that he shouldn't be running Java code in Python. | It seems like your friend hasn't moved past the "tutorial hell" stage.
One way to move past that stage is to find a project that has been done a thousand times before, so you can find many good tutorials on it and many github repos on it.
Then the person must start the project, only using general documentation, without following any of those specific tutorials/repos they found earlier. Even if that person does every single thing wrong, that's a very valuable thing to do. It primes their brain to receive the correct information.
And yes, once they're stuck for a certain amount of time, they can briefly look at one of those tutorials just like if it was a hint (and if one tutorial/hint doesn't work, they'll need to look at another one, hence the value of finding a project that has been done a thousand times before). And they'll need to repeat this cycle trial and error many times over.
Problem-solving is a muscle. If your friend doesn't practice that muscle, they're not going to progress.
>
> Am I asking too much of someone with coding bootcamp experience?
>
>
>
Not everyone from a coding bootcamp is stuck in tutorial hell.
With that said, I do think you've done too much for that person already. Stop writing the code for them. I don't think that's going to help. And no, I don't think numbered instructions are going to help either. Writing a bulletproof tutorial is going to take you forever to write, but pedagogically speaking, one more tutorial is not going to help them progress as a developer.
Aside from teaching them about "tutorial hell", you can also drill them and give them short bite-sized programming tasks from Codewars (or later on from Leetcode), but past a certain point, you may need to say "no" to them and walk away from this project.
Your friend is correct to a degree. If you two do not see eye to eye this issue, your meetings are going to become toxic. And good leaders know how to lead teams, yes, but they also know how to cut their losses and move on. |
612,897 | In my early days as KVM admin, when I had to do a backup of a VM image, I followed the next steps:
1. Pause the VM
2. Snapshot LVM volume
3. Resume the VM
4. Copy image
5. Remove LVM snapshot
Now I've got some machines in EC2, but I'm facing a doubt:
Amazon official documentation says
>
> "you should stop the instance before taking the snapshot"
>
>
>
but there's sometimes you can't stop a production instance.
I've been taking snapshots without stopping the instance and I've restored it (everything's gone fine) but the doubt is knocking my head time to time.
So my question is, can I pause (stop is not and option) an EC2 instance so that I can take a consistent snapshot of it? | 2014/07/16 | [
"https://serverfault.com/questions/612897",
"https://serverfault.com",
"https://serverfault.com/users/212052/"
] | No, it cannot be paused.
I also make snapshots on live servers and have yet to run into an issue, and I agree that it would be nice to be able to suspend writes during that time.
The other option is to use 'Create AMI from this instance' which seems to do something similar to a pause, in that it temporarily stops the instance but without releasing IP's or losing instance storage. It's not quite the same as creating a snapshot though, so may not be useful for daily backups. | No, you can't pause an EC2 instance, only stop.
Pausing a VM does not guarantee a consistent snapshot. In fact, pausing a VM to take an underlying snapshot is worse than taking a local LVM snapshot from a running system. Running an LVM snapshot will at least flush it's write buffers and wait for running writes to finish before creating the checkpoint (like [`fsfreeze`](http://manpages.courier-mta.org/htmlman8/fsfreeze.8.html) suggested by Diego F. Durán).
The main issue with snapshots are the applications that write to storage that are running at the time . What state are they in? To be sure of a snapshot you need to be able to quiesce your writing applications before you take the snapshot. Although Linux via LVM or fsfreeze can manage the OS, you are in no way guaranteed that the write operation you have paused is not part of a larger batch of writes that will half written in your backup.
Some databases may be able to recover from this by replaying the transaction log if both log and data are in the same snapshot, but most other applications aren't that capable. |
15,879,147 | I have this:
```
long int addsquares(int n, ...)
```
How can I access the parameters?
I can't use `va_start` and `va_arg`... | 2013/04/08 | [
"https://Stackoverflow.com/questions/15879147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2000363/"
] | If you are saying that you have a variadic function, and you're not allowed to use the variable argument macros (`va_xxx`) then you'd have to rewrite the content of those macro's yourself.
Unless you can change the function prototype, but I'm guessing that's now allowed either. | Check out the discussion in this thread... [How does the C compiler implement functions with Variable numbers of arguments?](https://stackoverflow.com/questions/2739496/how-does-the-c-compiler-implement-functions-with-variable-numbers-of-arguments)
I think you'll find it gets you going in the right direction. Pay particular attention to the discussion on the need to use one of the arguments as a means to sort out what and where the other arguments are. |
6,450,901 | I am working on a project where I need to run Google chromium over Linux FrameBuffer, I need to run it without any windowing system dependency ( It should draw on the buffer we provide it to draw, this will make its porting to any embedded system very easy) , I do not need its multi-tab GUI, I just need its renderer window in the buffer, has any body ever tried this? Any help on what approach should I use for this? | 2011/06/23 | [
"https://Stackoverflow.com/questions/6450901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/148869/"
] | try to port [webkit](http://www.webkit.org/) engine to the [netsurf framebuffer-based](http://www.netsurf-browser.org/about/screenshots/#framebuffer) code.
HTH | You could buy one of the remaining 10 (or so) OGD1 boards.
<http://en.wikipedia.org/wiki/Open_Graphics_Project>
Then you can talk directly to hardware using libpci.
However you will still need code that draws a picture into a memory buffer.
I realize this answer is more a shameless plug.
But people who are interested in your question might want such a board.
I already have a board like this and it would help a lot if it got more exposure. |
922,052 | I'm trying list all of the monospaced fonts available on a user's machine. I can get all of the font families in Swing via:
```
String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getAvailableFontFamilyNames();
```
Is there a way to figure out which of these are monospaced?
Thanks in advance. | 2009/05/28 | [
"https://Stackoverflow.com/questions/922052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | A simpler method that doesn't require making a BufferedImage to get a Graphics object etc.:
```
Font fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
List<Font> monoFonts1 = new ArrayList<>();
FontRenderContext frc = new FontRenderContext(null, RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT, RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT);
for (Font font : fonts) {
Rectangle2D iBounds = font.getStringBounds("i", frc);
Rectangle2D mBounds = font.getStringBounds("m", frc);
if (iBounds.getWidth() == mBounds.getWidth()) {
monoFonts1.add(font);
}
}
``` | Probably not applicable for your case, but if you simply want to set the font to a monospaced font, use the logical font name:
```
Font mono = new Font("Monospaced", Font.PLAIN, 12);
```
This will be a guaranteed monospaced font on your system. |
11,862,479 | We're setting up a new project and decided to use eclipselink for JPA. When creating our domain model we ran into a problem.
We have a base class called organisation. We also have Supplier and Customer which both extend organisation. When JPA created the tables I saw that it uses a discriminator, the problem with this is that a supplier can also be a organisation.
So what I basically want is (these are database tables to get the idea):

A little example to help clarify this:
We have a Customer called SparklingGlass. SparklingGlass buys computers from us so SparklingGlass is saved as our Customer. We in turn buy our windows from SparklingGlass, so SparklingGlass is also our Supplier. This is what we want to realize in our system.
Is this in any way possible in JPA and ifnot, what is the best practice in these cases?
BTW we use the JOINED inheritance type | 2012/08/08 | [
"https://Stackoverflow.com/questions/11862479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755949/"
] | This is from a project and isn't tested, but one of these should work.
```
$select->from(array("table_name" => "table_name"), array("my_col" => "COUNT(id)"));
```
**OR**
```
$select->from(array("table_name"), array("my_col" => "COUNT(id)"));
```
This is the same as
```
SELECT COUNT(id) as my_col FROM table_name
```
Hope that helps
Jake | To use a mysql command in a select, you need to use Zend\_Db\_Expr:
```
$select = $this->select()
->from('myTable', new Zend_Db_Expr('COUNT(id) as count'));
echo $select; //SELECT COUNT(id) as count FROM myTable;
``` |
18,793,827 | I need some help with following problem:
**Problem:**
In the design view frames that appear around selected Swing-elements are not displayed at their correct positions. Also the content pane is not located at its right position inside the window (JFrame). It seems no matter whether layout is used (e. a. BorderLayout, GroupLayout).
For example, the frame of a selected button is display many pixels above or beside the button. In this case, if you want to select a GUI component by clicking it with your courser you should not click on the graphical representation of that element but some pixels above or where ever the frame could be – you have to consider the offset of the shifting.
By nearly every refresh of the design view (F5) or if you shift some components in the content pane the offset of the wrong placed frames changes for some pixels – sometimes the frames are above, sometimes below or beside.
*Are there other persons with this problem?*
*Are there persons that don‘t have these problems with WindowBuilder Pro with Ubuntu 12.04?*
*What could cause this error and how it might be solved?*
**System environment under which the error occurs:**
* One desktop PC / One laptop
* Ubuntu 12.04 (with Unity) / Kubuntu 12.04 (with KDE)
* Oracle Java 7
* Eclipse 64 Bit:
+ Eclipse 4.3 Java EE / Eclipse 4.3 Standard / Eclipse 4.3 Modeling Tools
+ Installed under „/opt/eclipse“. The error occurs, no matter whether the folders belong to root or to normal user.
* WindowBuilder Pro 1.6.0 (Eclipse plugin installed with eclipse software manager)
* I also tried WindowBuilder Pro in Ubuntu 13.04 in VirtualBox. But as soon I am moving the mouse on the palette eclipse crashes.
**Hints:**
* The error seems to occur only, if the content pane is not correctly positioned inside the window (JFrame). Sometimes the content pane is out of place by a few dozen pixels, sometimes it is as wide as the JFrame itself, sometimes it is little bigger than the window.
* The error does not occur with Windwos 7 and with Xubuntu 13.04 under otherwise identical conditions (I did not tested Xubuntu 12.04). But the error occures with Ubuntu 12.04 and Kubuntu 12.04.
* My workaround is to use WindowBuilder Pro with Xubuntu 13.04 installed in VirtualBox. Of course this can not be a permanent solution, because I want to continue to use Ubuntu 12.04 LTS.
* I have read <http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.wb.doc.user%2Fhtml%2Ffaq.html>.
* Here the same problem is described, but there are no answers: <https://stackoverflow.com/questions/15818379/windowbuilder-eclipse-away-from-the-actual-component?rq=1>
* Here a possible workaround is descibed: <https://bugs.eclipse.org/bugs/show_bug.cgi?id=417224> | 2013/09/13 | [
"https://Stackoverflow.com/questions/18793827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2777610/"
] | If you need to support IE7 you can use:
```
div > div > div > div + div + div,
div > div > div > div:first-child {
color: orange;
}
```
<http://jsfiddle.net/4TYcb/1/> | ```
div div div :not(:nth-child(2))
```
will select just those divs |
2,093,792 | There are $10$ white and $10$ black balls in the first box, and $8$ white and $10$ black balls in the second box. Two balls are put from the first to the second box, then we choose one ball from the second box. What is the probability that the chosen ball from the second box is white?
From the first box, we can choose two balls in ${20\choose 2}=190$ ways. Possible combinations are $\{BB,BW,WB,WW\}$.
After putting two balls from the first to the second box, there are total $18$ balls in the first, and $20$ in the second.
From the second box, we can choose one ball in ${20\choose 1}=20$ ways.
How can we find the probability that the chosen ball from the second box is white? | 2017/01/11 | [
"https://math.stackexchange.com/questions/2093792",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/222321/"
] | It suffices to take the inverse of a continuous bijection (whose inverse fails to be continuous).
Here, then, is my go-to example: consider $S^1 \subset \Bbb R^2$, and the map
$$
f:S^1 \subset \Bbb R^2 \to (-\pi,\pi]\\
(\cos( x), \sin(x)) \mapsto x
$$
If we extend this example to the whole plane, we get something classic: the map $z \in \Bbb C \mapsto \ln(z)$ (with the usual branch cut) is open, but not continuous.
Or, if you prefer, take $z \in \Bbb C \mapsto \text{Arg}(z) \in \Bbb R$.
This gives us an $\Bbb R^2 \to \Bbb R$ example, which I think is as low as we can go for $\Bbb R^n \to \Bbb R^m$.
---
It may be useful to note that for any open $f:X \to Y$: if $f$ is injective, $X$ is Hausdorff, and $f(X)$ is compact, then the map is necessarily continuous. | All you have to do is take the identity function onto the discrete topology on the same space. All discrete topologies are metrizable. |
31,227,055 | How should I go about detecting if typing has stopped in a `UITextField`? Should I use the `UITextFieldTextDidEndEditingNotification` function of some sorts? I a trying to create a instagram like search where it will display the results after a second of not typing. | 2015/07/05 | [
"https://Stackoverflow.com/questions/31227055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4335880/"
] | This approach uses an NSTimer to schedule a search 1 second after the text field changes. If a new character is typed before that second is up, the timer starts over. This way, the search is only triggered starts after the last change.
**First things first, make sure the ViewController is conforms to the UITextFieldDelegate protocol:**
```
//
// ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITextFieldDelegate>
@end
```
**Then, implement the timed search:**
```
//
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *textfield;
@property (strong, nonatomic) NSTimer * searchTimer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// declare this view controller as the delegate
self.textfield.delegate = self;
// handle the change event (UIControlEventEditingChanged) by calling (textFieldDidChange:)
[self.textfield addTarget:self
action:@selector(textFieldDidChange:)
forControlEvents:UIControlEventEditingChanged];
}
// reset the search timer whenever the text field changes
-(void)textFieldDidChange :(UITextField *)textField{
// if a timer is already active, prevent it from firing
if (self.searchTimer != nil) {
[self.searchTimer invalidate];
self.searchTimer = nil;
}
// reschedule the search: in 1.0 second, call the searchForKeyword: method on the new textfield content
self.searchTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0
target: self
selector: @selector(searchForKeyword:)
userInfo: self.textfield.text
repeats: NO];
}
- (void) searchForKeyword:(NSTimer *)timer
{
// retrieve the keyword from user info
NSString *keyword = (NSString*)timer.userInfo;
// perform your search (stubbed here using NSLog)
NSLog(@"Searching for keyword %@", keyword);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
``` | swift
xcode - 10
```swift
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
NSObject.cancelPreviousPerformRequests(
withTarget: self,
selector: #selector(self.getHintsFromTextField),
object: textField)
self.perform(
#selector(self.getHintsFromTextField),
with: textField,
afterDelay: 0.5)
return true
}
@objc func getHintsFromTextField(textField: UITextField) {
print("Hints for textField: \(textField)")
}
``` |
527,849 | I have an asp form that has a checkbox and dropdown menu. If the checkbox in not selected then I need to make sure the dropdown is either not selected or disabled. | 2009/02/09 | [
"https://Stackoverflow.com/questions/527849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64134/"
] | Are you sure you're pointing your unit tests at the instrumented classes for the external method call? | Can't help you with Emma. But what you need is a code coverage tool that can combine test coverage data from multiple projects into a coherent whole.
SD's test coverage tools (including the one for Java) can do this out of the box. This allows one to keep lots of "projects" that each make up a significant part of a much larger (meta)project (e.g., Eclipse!), and get a picture of coverage of the metaproject.
We've uses this to handle systems with 45,000 compileable Java programs.
They can also combine data from multiple test coverage runs on a single project into coherent information for that project.
See <http://www.semanticdesigns.com/Products/TestCoverage/index.html>
(Hi Kurt). |
38,854 | I'm looking for an understandable book about mathematical proofs.
As an engineer/computer scientist major I'm used to do higher math on a daily base, but whenever I'm asked in an exercise to "show" something I get the "where should I start? and what exactly do they want me to do?" syndrome. | 2011/05/13 | [
"https://math.stackexchange.com/questions/38854",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/10224/"
] | Read Pólya's [How to Solve It](http://en.wikipedia.org/wiki/How_to_solve_it). See also these [slides](http://cs.swan.ac.uk/~csgs/howtoproveit.pdf). | You can search for "thoughts - Alpha" this is a free downloadable online PDF book for mathematical proofs. the book is a compilation of proofs for basic mathematics (Trigonometric Identities, logarithms, basic series, volumes and surfaces, basic calculus)
Book's webpage:
<http://thoughtsseries.weebly.com/>
Author's scribd page:
<https://www.scribd.com/user/295650299/Daniel-Benjamin-Rodriguez-Ortega> |
60,091,570 | Is there any way to create the homepage Home.aspx in Sharepoint under the template Team Site using CSOM in C# ? | 2020/02/06 | [
"https://Stackoverflow.com/questions/60091570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9939945/"
] | The following code snippet for your reference.
```
string siteUrl = "https://*****.sharepoint.com/sites/team";
string userName = "admin@****.onmicrosoft.com";
string password = "***";
OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
#region O365
using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
Web web = ctx.Web;
ctx.Load(web.Lists);
ctx.Load(web, w => w.SupportedUILanguageIds);
ctx.Load(web);
ctx.ExecuteQueryRetry();
//Create the Page
var homePage = ctx.Web.AddClientSidePage("HomePage.aspx", true);
homePage.AddSection(CanvasSectionTemplate.ThreeColumn, 5);
homePage.Save();
}
```
More information is here: [How To Create A Modern Pages Programmatically In SharePoint Office 365 Using Patterns And Practice (OfficeDevPNP)](https://www.sharepointpals.com/post/how-to-create-a-modern-pages-programmatically-in-sharepoint-office-365-using-patterns-and-practice-officedevpnp/)
We can also use PnP PowerShell below to achieve it.
```
$siteUrl="https://tenant.sharepoint.com/sites/team";
$cred = Get-Credential
Connect-PnPOnline -Url $siteUrl -Credential $cred
Add-PnPClientSidePage -Name "HomePage"
Set-PnPHomePage -RootFolderRelativeUrl SitePages/HomePage.aspx
``` | Try this approach:
```
OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
string siteUrl = "https://******.sharepoint.com/sites/CommunitySite";
string userName = "userh@******.onmicrosoft.com";
string password = "******";
using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
Web web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQueryRetry();
List sitePagesList = web.Lists.GetByTitle("Site Pages");
ctx.Load(sitePagesList);
ctx.Load(sitePagesList.RootFolder);
ctx.ExecuteQueryRetry();
var pageTitle = "home.aspx";
sitePagesList.RootFolder.Files.AddTemplateFile(sitePagesList.RootFolder.ServerRelativeUrl + "/" + pageTitle, TemplateFileType.StandardPage);
ctx.ExecuteQueryRetry();
}
}
```
Switch between modern and classic design:
```
#Get the Web Scoped Feature
$web = $context.Web
# Feature Title : EnableDefaultListLibrarExperience, Scope : Web
$featureguid = new-object System.Guid "52E14B6F-B1BB-4969-B89B-C4FAA56745EF"
#To Enable/Disable the Modern UI, comment and uncomment the below two lines, either to Add or Remove
#$web.Features.Add($featureguid, $true, [Microsoft.SharePoint.Client.FeatureDefinitionScope]::None)
$web.Features.Remove($featureguid, $true)
$context.ExecuteQuery()
``` |
22,401,464 | Hi I want to autowire boolean value from properties file have referred following link with maps url
[Spring properties (property-placeholder) autowiring](https://stackoverflow.com/questions/2882545/spring-properties-property-placeholder-autowiring)
but I want to auto wire a boolean property, also have referred question **Spring Autowire primitive boolean** [Spring Autowire primitive boolean](https://stackoverflow.com/questions/15042006/spring-autowire-primitive-boolean)
but that was for bean value and in my case I want to do the same using property value which is dot separated.
`${does.it.allow}`
// which fails and gives String cannot be cast to boolean
`#{does.it.allow}`
// this gives no bean/property defined with name **does** but I have the correct property file and it proves that container is able to load it because of first error. | 2014/03/14 | [
"https://Stackoverflow.com/questions/22401464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2320457/"
] | It doesn't work for me with primitive boolean. But it does with Boolean type.
This is my spring configuration declaration of the properties file:
```
<context:property-placeholder location="classpath:path/to/file/configuracion.properties" />
```
This is what i have in my properties file:
```
my.property=false
```
And this is my successful service class:
```
...
@Service
public class MyServiceImpl implements MyService{
...
@Value("${my.property}")
private Boolean nameOfProperty;
...
``` | At least from Spring 5 (I didn't test previous versions), you can autowire boolean primitive.
In application properties:
```
my.property=true
```
In your class:
```
@Value("${my.property}")
private boolean myProperty;
``` |
9,616,165 | I am currently working on making a multiplayer Snake game in HTML5 Canvas with Javascript.
The code below is function that handles the random placement of food for the snake. The problem with the piece of code is that it give me the x and y in while(map[x][y]); back as something he can not read even though it does generate a random number.
This is the exact error:
```
"Uncaught TypeError: Cannot read property '20' of undefined"
```
The '20' is the random generated number (and will be the grid position of the food in a two dimensional array) and changes every time I restart the program or refresh the webpage. Can someone explain what I need the change in order to define x and y and place my food?
```
function rand_food(){
var x, y;
do {
x = MR() * this.rect_w|0;
y = MR() * this.rect_h|0;
}
while (map[x][y]); <-- Here is the error
map[x][y] = 1;
this.ctx.strokeRect(x * 10+1, y * 10+1, 8, 8);
}
```
Here is another code snippet which defines the map.
```
this.map = [];
// Map positions
//*
for (i = 0; i < this.rect_w; i++){
map[i] = [];
}//*/
```
After trying Sean's suggestion my code now looks like this: But it still gives me same error. Any other suggestion?
```
function SnakeGame(){
this.map = [];
for (i = 0; i < this.rect_w; i++){
this.map[i] = [];
}
function rand_food(){
var x, y;
console.log("Map length: " + this.map.length);
do {
x = MR() * this.rect_w|0;
y = MR() * this.rect_h|0;
console.log("x: " + x);
console.log("y: " + y);
}
while (this.map[x][y]);
this.map[x][y] = 1;
this.ctx.strokeRect(x * 10+1, y * 10+1, 8, 8);
}
``` | 2012/03/08 | [
"https://Stackoverflow.com/questions/9616165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1180646/"
] | ```
XDocument xDoc = XDocument.Load(.....);
xDoc.Descendants("Title").First().Value = "New Value";
xDoc.Save(...)
``` | ```
XmlDocument xml = new XmlDocument();
xml.Load(...);
var newTitle = "MODIFIED";
var title_node = xml.GetElementsByTagName("Title");
if(!string.IsNullOrEmpty(newTitle) && title_node.Count > 0)
{
title_node[0].InnerText = newTitle;
}
``` |
37,161,695 | [](https://i.stack.imgur.com/BEPi7.png)
The HTML code for this form (left hand side) is like below.
```
<div class="lp-element lp-pom-form" id="lp-pom-form-410">
<form action="#" method="POST">
<div class="lp-pom-form-field clearfix" id="container_name">
<input type="text" id="name" name="name" class="text form_elem_name" placeholder="Name">
</div>
<div class="lp-pom-form-field clearfix" id="container_email">
<input type="text" id="email" name="email" class="text form_elem_email" placeholder="Email">
</div>
</form>
<a class="lp-element lp-pom-button" id="lp-pom-button-411" href="#"><span class="label">GET MY DEMO</span></a>
</div>
```
I am trying to convert it to aspx and the back-end code for it into vb.net shown below.
```
<form id="form1" runat="server">
<asp:Panel runat="server" ID="uxForm">
<div class="lp-pom-form-field clearfix" id="container_name">
<asp:TextBox ID="uxName" runat="server" CssClass="text form_elem_name" placeholder="Name" />
</div>
<div class="lp-pom-form-field clearfix" id="container_email">
<asp:TextBox ID="uxEmail" runat="server" CssClass="text form_elem_email" placeholder="Email" />
</div>
</asp:Panel>
</form>
```
The problem is that I cannot convert the get my demo button in to asp button.
I have tried the following:
```
<asp:LinkButton runat="server" ID="btnSave" CssClass="lp-element lp-pom-button" Text="Get My Demo" />
```
but it just become invisible like the picture (right hand side form)
I have also tried
```
<a class="lp-element lp-pom-button" id="save" runat="server"><span class="label">GET MY DEMO</span></a>
```
But then also the button goes invisible and the text get my demo is in the name field as shown in the 2nd picture.
[](https://i.stack.imgur.com/W1PmE.png)
What has gone wrong and how can I correct it? **the button goes invisible..even without css class**
For your information I have not created the vb.net codes yet. Could that be the issue?
---
CSS
```
#lp-pom-button-411 {
display:block;
border-style:none;
behavior:url(/PIE.htc);
border-radius:9px;
left:0px;
top:251px;
z-index:16;
width:348px;
height:50px;
position:absolute;
background-color:#f7941d;
background:-webkit-linear-gradient(#fd494b,#fb2c2f);
background:-moz-linear-gradient(#fd494b,#fb2c2f);
background:-ms-linear-gradient(#fd494b,#fb2c2f);
background:-o-linear-gradient(#fd494b,#fb2c2f);
background:linear-gradient(#fd494b,#fb2c2f);
box-shadow:inset 0px 1px 0px #ff9697,inset 0 -1px 2px #c72325;
text-shadow:1px 1px #7a0404;
-pie-background:linear-gradient(#fd494b,#fb2c2f);
color:#fff;
border-width:undefinedpx;
border-color:#undefined;
font-size:25px;
line-height:30px;
font-weight:bold;
font-family:Raleway;
text-align:center;
background-repeat:no-repeat;
}
.button{
display: inline-block;
padding: 17px 34px;
border: 3px solid #fff;
color: #fff;
font-size: 22px;
font-weight: bold;
text-decoration: none;
height: 52px;
width: 123px;
font-family: 'Lato', sans-serif;
background: red;
background: -webkit-linear-gradient(#fe4d4f, #fb2d2e);
background: -o-linear-gradient(#fe4d4f, #fb2d2e);
background: -moz-linear-gradient(#fe4d4f, #fb2d2e);
background: linear-gradient(#fe4d4f, #fb2d2e);
margin-left: 49px;
text-shadow: #000000 1px 0px 1px;
}
.button:hover{
background: red;
background: -webkit-linear-gradient(#f13839, #ee2526);
background: -o-linear-gradient(#f13839, #ee2526);
background: -moz-linear-gradient(#f13839, #ee2526);
background: linear-gradient(#f13839, #ee2526);
}
```
picture 3
[](https://i.stack.imgur.com/t3Gmj.jpg) | 2016/05/11 | [
"https://Stackoverflow.com/questions/37161695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3560248/"
] | Try this:
```
<asp:LinkButton runat="server" ID="btnGetDemo" CssClass="lp-element lp-pom-button lp-pom-button-411"><span class="label">GET MY DEMO</span></asp:LinkButton>
```
My guess is that the "label" class on the span has something to do with it.
EDIT:
I changed the LinkButton markup a bit AND do change the CSS aswell to:
```
.lp-pom-button-411 {
display:block;
border-style:none;
behavior:url(/PIE.htc);
border-radius:9px;
left:0px;
top:251px;
z-index:16;
width:348px;
height:50px;
position:absolute;
background-color:#f7941d;
background:-webkit-linear-gradient(#fd494b,#fb2c2f);
background:-moz-linear-gradient(#fd494b,#fb2c2f);
background:-ms-linear-gradient(#fd494b,#fb2c2f);
background:-o-linear-gradient(#fd494b,#fb2c2f);
background:linear-gradient(#fd494b,#fb2c2f);
box-shadow:inset 0px 1px 0px #ff9697,inset 0 -1px 2px #c72325;
text-shadow:1px 1px #7a0404;
-pie-background:linear-gradient(#fd494b,#fb2c2f);
color:#fff;
border-width:undefinedpx;
border-color:#undefined;
font-size:25px;
line-height:30px;
font-weight:bold;
font-family:Raleway;
text-align:center;
background-repeat:no-repeat;
}
``` | Use this:
```
<form id="form1" runat="server">
<asp:Panel runat="server" ID="uxForm">
<div class="lp-pom-form-field clearfix" id="container_name">
<asp:TextBox ID="uxName" runat="server" CssClass="text form_elem_name" placeholder="Name" />
</div>
<div class="lp-pom-form-field clearfix" id="container_email">
<asp:TextBox ID="uxEmail" runat="server" CssClass="text form_elem_email" placeholder="Email" />
</div>
<asp:Button ID="btnSave" runat="server" Text="Get My Demo" CssClass="lp-element lp-pom-button" />
</asp:Panel>
</form>
``` |
69,222,896 | In Snowflake there is a number column storing values like: 8,123,456. I am struggling determining how to structure select statement to return a value like: 00008123456.
In SQL SERVER you can do something like this:
```
right(replicate('0', 11) + convert(varchar(11), job_no), 11) AS job_no
```
I understand Snowflake to\_varchar function can be used, but not sure how to structure like in SQL Server. | 2021/09/17 | [
"https://Stackoverflow.com/questions/69222896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/331896/"
] | Just add a format string on to\_varchar():
```
select to_varchar(8123456, '00000000000');
``` | a solution provided by Greg Pavlik saved me.
I just switched from DB2 to Snowflake.
So, `TO_VARCHAR( <numeric_expr> [, '<format>' ] )` worked. |
49,602,983 | I managed to build AV1 codec <https://aomedia.googlesource.com/aom/> with visual studio thanks to the command
```
cmake path/to/aom -G "Visual Studio 15 2017 Win64"
```
however the encoder only use one thread even with the option --threads, in the code it seems to use pthread. Do I need to do a different build with pthread emulation or do I miss a flag to enable multi-threading on windows 10 64bit for this codec? | 2018/04/01 | [
"https://Stackoverflow.com/questions/49602983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/664329/"
] | i make AOM AV1 encoder to work in parallel by adding tiles `--tile-columns=1 --tile-rows=0` , where `--tile-columns` and `--tile-rows` denote log2 of tile columns and rows. | hmm, well av1 is missing multi-threading, should arrive when they get around finishing specs lol |
23,339,922 | Suppose an array *arr[1..N]* of integers. The array is changed in two ways:
* Values are being overwritten
* Items are considered invalid (by setting special value `-1`, for example)
I am looking for a data structure that gives answer to "What is the *k*-th valid item?" quickly.
With single invalid value, this is trivial. With many such values, it becomes a bit of a tangle.
I tried keeping an auxiliary array, which would contain `1` for invalid indices and `0` otherwise. I can keep prefix sums for this array and query them in *O(log n)* time. Then I know that there are *sum(k)* invalid items between 1 and *k*, so that the *k*-th item is actually at *k + sum(k)*. But, between *k* and *k + sum(k)*, there may be some invalid items again - and it gets ugly.
Is there a better solution to this problem, presumably in *O(log n)* time?
Have a nice day! | 2014/04/28 | [
"https://Stackoverflow.com/questions/23339922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402141/"
] | Its `undefined` because, `console.log(response)` runs before `doCall(urlToCall);` is finished. You have to pass in a callback function aswell, that runs when your *request* is done.
First, your function. Pass it a callback:
```
function doCall(urlToCall, callback) {
urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return callback(finalData);
});
}
```
Now:
```
var urlToCall = "http://myUrlToCall";
doCall(urlToCall, function(response){
// Here you have access to your variable
console.log(response);
})
```
@Rodrigo, posted a [good resource](https://github.com/maxogden/art-of-node#callbacks) in the comments. Read about *callbacks* in node and how they work. Remember, it is asynchronous code. | If what you want is to get your code working without modifying too much. You can try this solution which **gets rid of callbacks** and **keeps the same code workflow**:
Given that you are using Node.js, you can use [co](https://github.com/tj/co) and [co-request](https://github.com/denys/co-request) to achieve the same goal without callback concerns.
Basically, you can do something like this:
```
function doCall(urlToCall) {
return co(function *(){
var response = yield urllib.request(urlToCall, { wd: 'nodejs' }); // This is co-request.
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return finalData;
});
}
```
Then,
```
var response = yield doCall(urlToCall); // "yield" garuantees the callback finished.
console.log(response) // The response will not be undefined anymore.
```
By doing this, we wait until the callback function finishes, then get the value from it. Somehow, it solves your problem. |
186,573 | Recently I had a paper sent back to me (rejected) with two referee reports. This is not that surprising as this was a very good journal. The problem is that the identity of one of the referees is revealed even though it's supposed to be a single-blind system. This wouldn't be too much of a problem usually, but the identity of the referee turns out to be one of my letter writers, and someone I've worked with closely.
This creates a very awkward situation for me. Any advice? | 2022/07/01 | [
"https://academia.stackexchange.com/questions/186573",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/143051/"
] | Let it go.
They were doing their job. If their commentary was fair there is nothing for you to do here, but forget about the incident. This is a rather explicit case, but in the future there will be many cases where you can quite accurately infer the identity of a referee. Some of those referees will be people you know, some reports will be negative. It something you have to (learn to) deal with.
If their comments where exceptionally harsh to the point of them clearly not respecting you or your work, then it may be better to remove them from your list of letter writers.
(As an aside, if they are writing letters for you, it would probably have been better if they had recused themselves from reviewing your work.) | There is a good rule: "If in doubt, do nothing."
Other people believe that you should notify the editor. I wouldn't do that, as you cannot be sure the editor would not notify the referee, and that would be more awkward :-)
I don't see how the current situation is awkward for you, unless you let the referee know what you now know. Actually, you just obtained some valuable information. If we knew what other people say about us behind our back, we might lose some illusions, but I am not sure this would be a bad thing :-)
The only thing you may wish to do is consider if you should ask this person to write support letters for you, although you cannot be sure other potential letter writers say nicer things about you behind your back :-) |
131,666 | What is the right place to store program data files which are the same for every user but have to be writeable for the program? What would be the equivalent location on MS Windows XP? I have read that C:\ProgramData is not writeable after installation by normal users. Is that true? How can I retrieve that directory programmatically using the Platform SDK? | 2008/09/25 | [
"https://Stackoverflow.com/questions/131666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21683/"
] | `SHGetFolderPath()` with CSIDL of `CSIDL_COMMON_APPDATA`.
Read more at <http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx>
If you need the path in a batch file, you can also use the `%ALLUSERSPROFILE%` environment variable. | Actually [`SHGetFolderPath`](http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx) is deprecated.
[`SHGetKnownFolderPath`](http://msdn.microsoft.com/en-us/library/bb762188(VS.85).aspx) should be used instead. |
943,330 | I have some action methods behind an Authorize like:
```
[AcceptVerbs(HttpVerbs.Post), Authorize]
public ActionResult Create(int siteId, Comment comment) {
```
The problem I have is that I'm sending a request through AJAX to Comment/Create with
```
X-Requested-With=XMLHttpRequest
```
which helps identify the request as AJAX. When the user is not logged in and hits the Authorize wall it gets redirected to
```
/Account/LogOn?ReturnUrl=Comment%2fCreate
```
which breaks the AJAX workflow. I need to be redirected to
```
/Account/LogOn?X-Requested-With=XMLHttpRequest
```
Any ideas how that can be achieved? Any ways to gain more control over what happens when Authorization is requested? | 2009/06/03 | [
"https://Stackoverflow.com/questions/943330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] | Thanks to Lewis comments I was able to reach this solution (which is far from perfect, posted with my own comments, if you have the fixes feel free to edit and remove this phrase), but it works:
```
public class AjaxAuthorizeAttribute : AuthorizeAttribute {
override public void OnAuthorization(AuthorizationContext filterContext) {
base.OnAuthorization(filterContext);
// Only do something if we are about to give a HttpUnauthorizedResult and we are in AJAX mode.
if (filterContext.Result is HttpUnauthorizedResult && filterContext.HttpContext.Request.IsAjaxRequest()) {
// TODO: fix the URL building:
// 1- Use some class to build URLs just in case LoginUrl actually has some query already.
// 2- When leaving Result as a HttpUnauthorizedResult, ASP.Net actually does some nice automatic stuff, like adding a ReturnURL, when hardcodding the URL here, that is lost.
String url = System.Web.Security.FormsAuthentication.LoginUrl + "?X-Requested-With=XMLHttpRequest";
filterContext.Result = new RedirectResult(url);
}
}
}
``` | Recently I ran into exactly the same problem and used the code posted by J. Pablo Fernández
with a modification to account for return URLs. Here it is:
```
public class AuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
{
override public void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
// Only do something if we are about to give a HttpUnauthorizedResult and we are in AJAX mode.
if (filterContext.Result is HttpUnauthorizedResult && filterContext.HttpContext.Request.IsAjaxRequest())
{
// TODO: fix the URL building:
// 1- Use some class to build URLs just in case LoginUrl actually has some query already.
HttpRequestBase request = filterContext.HttpContext.Request;
string returnUrl = request.Path;
bool queryStringPresent = request.QueryString.Count > 0;
if (queryStringPresent || request.Form.Count > 0)
returnUrl += '?' + request.QueryString.ToString();
if (queryStringPresent)
returnUrl += '&';
returnUrl += request.Form;
String url = System.Web.Security.FormsAuthentication.LoginUrl +
"?X-Requested-With=XMLHttpRequest&ReturnUrl=" +
HttpUtility.UrlEncode(returnUrl);
filterContext.Result = new RedirectResult(url);
}
}
}
``` |
7,424,959 | I want to make simple project which play flash video file from online.
I've searched some articles and read carefully.
But I can't understand, how to play flash video files on iPad by Code.
So I need help from you.
Please. | 2011/09/15 | [
"https://Stackoverflow.com/questions/7424959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/931872/"
] | Simply put, without being jailbroken, No you cannot.
The closest thing to being able to view flash in iOS is Frash, and I am not even sure if it is actively being developed or supported any more.
You can always check out the [open source project for **Frash**](https://github.com/comex/frash). by Comex. | At the end of the day, the Flash video format is a container for a movie that’s been compressed by some codec. If you can get to the source file, you know the format of the container, you know the codec that was used to encode the video, and you know how to write code to convert that into audio streams and video frames, then *yes*, you can play Flash videos on the iPad.
So, to recap:
1. Get the Flash video file.
2. Get to the encoded video data in the Flash file.
3. Decode the video and convert it, either into raw audio and video or to another format that the iPad can play.
4. Play the result of #3.
Needless to say, this is quite the endeavor. It’s better to download the movies to your desktop and convert them there before loading them into your application. |
6,160 | I just got following entities Employee, Client and Company. Where Employee and Client have one to many relationship with Company ie A single employee may be mapped to attend to many companies and same for clients too. How would i design a optimized table for this situation.
I had thought of below
**Employee:**
-------------
Id
Name
CompanyId
but since it is one to many companyid would have to be saved as comma seperated company id's. What do i do in this situation. | 2011/09/26 | [
"https://dba.stackexchange.com/questions/6160",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/592/"
] | You have a many-many (aka link or junction) table between the 2
EmployeeCompany
Columns:
* EmployeeID
* CompanyID
Keys:
* Primary key is (EmployeeID, CompanyID)
* Add a unique index (CompanyID, EmployeeID)
* EmployeeID has FK to Employeetable
* CompanyID has FK to Company table
**Do not** store a CSV in a column: this is bad practice, can't enforce data integrity, can't search it efficiently, has no meaning etc
Note: A column called "ID" is very ambiguous so this is one case where you prefix with the table name | Assuming a `company` can be "attended to" by more than one `employee`, and likewise for `client`, you would model like this:

So both relations are 'many:many'. As gbn also said, adding "comma separated ids" would be something of a disaster in database design: you would regret it many times over. |
125,388 | I've downloaded jmeter and put it in my Applications folder.
I've made it executable.
I can cd to /Applications/apache-jmeter-2.11/bin and can run it in a terminal with
```
$ ./jmeter
```
or by double-clicking the icon from the finder.
How can I add the program as a shortcut (icon) on the main application icon launcher bar ('Dock') on a Mac, similar to programs such as browsers, MS Outlook, gitx, etc? | 2014/03/24 | [
"https://apple.stackexchange.com/questions/125388",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/24565/"
] | You can use AppleScript to make a `.app` file for this (That is the only file type that can go in the left side of the dock). It is in `/Applications/Utilities/AppleScript Editor` and when you make a new file you can put in `do shell script "/Applications/apache-jmeter-2.11/bin/jmeter"`. I do this all the time for shell scripts, so I can access them easily. Then you can save and choose "app" near the bottom of the Save sheet. This will create an app file that you can put in, say, the folder above `bin` which can be dragged into the Dock.
```
tell app "Terminal"
activate
do script "/Applications/apache-jmeter-2.11/bin/jmeter"
end
```
is what you will need if jmeter writes to the terminal. | Such binaries can't be added to the left side of the Dock where applications are stored.
**Add it to the right side of the Dock instead**
Right of the separator:
 |
14,290,413 | apology for this newbie question.
I have created an html page (dash.html) that uses the same `header` as the other pages.
it calls this PHP function `<?php include 'header.php'; ?>`
the dash.html contains a special `<div>` made specially for that page; and it must be placed inside the `header.php`
im trying to figure out how to enable/disable a certain `div` on a certain html page.
will it require a PHP conditional statement? | 2013/01/12 | [
"https://Stackoverflow.com/questions/14290413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1933824/"
] | If you trying to create a hierarchy of views like this, you should probably be using these:
```
[self.navigationController pushViewController:ViewController animated:BOOL completion:nil];
[self.navigationController popViewControllerAnimated:BOOL completion:nil];
```
Instead of:
```
[self presentViewController:ViewController animated:BOOL completion:nil];
[self dimissViewControllerAnimated:BOOL completion:nil];
```
PresentViewController is usually used to show a single view controller then dismiss it, not generally when you want to show several view controllers in a chain, then work your way back up the chain.
The former is advisable because it uses the stack concept to push and pop view controllers. So you can start with your initial list set up as the root view controller, push on your post compose view, then push on the third view to go to posting. Then when you want to go back to the first view controller by popping off two view controllers, you can use:
```
[self popToRootViewControllerAnimated:BOOL completion:nil];
```
You might find the [UINavigationController](http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UINavigationController_Class/Reference/Reference.html) reference useful.
Good luck. | I'm a little confused about what you're trying to do. If you're using a navigation controller, you should be doing pushes and pops, not presenting and dismissing. If you want to use navigation controllers, then you can use popToViewController:animated: to go back to any particular controller without passing through the ones in between. You would have to create a custom back button, though, or do it in code, because the standard back button will only take you back to the previous view controller. |
51,994 | My line manager does not have any computational skills: no advanced data analysis, no scripting, no programming. Recently he switched the frequency of our meetings to weekly (from one every 2 weeks) and he wants to check my code week after week.
Background: he's not technical and he's mainly trying to monopolise access to my technical expertise, e.g. **if you want to use technology X you must go through me.**
But other people have been very happy about my work and nobody else ever complained.
He doesn't really know anything about software development. I think that he wants to control my code by either counting the lines or giving it to some friend of his who will tell him "this sucks, pay me and I will do it for less".
I think that giving him access to my code will only slow me down. Should I allow my manager to do this? | 2015/08/11 | [
"https://workplace.stackexchange.com/questions/51994",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/-1/"
] | >
> Should I allow my manager to do this?
>
>
>
**Yes, almost certainly.** If you are in a normal employment relationship, the code you write belongs to your company and you have no right to refuse that your manager sees your code. Refusing would almost certainly be seen as unreasonable or suspicious and could trigger disciplinary action.
>
> he wants to check my code week after week
>
>
>
**If this bothers you, find out what he actually needs.** When this next comes up, talk to him about this. If it's mutually acknowledged that he doesn't program, ask what he'd like to do with it and how you can help him achieve that. If what he wants is numbers, and you don't want to be judged by lines, find alternative metrics that you feel better reflect the work you do, e.g. test coverage.
**Don't be defensive, be proud of your code.**
(Unless it's really bad code, in which case, stop writing bad code!) | Strange sounding question.
Normally for software development you always have a version control system where everyone who has the rights can access the code and see its development history. Your question sounds like either you have your code local or in a non-accessible repository (*which is an extremely bad idea by itself, data loss is always imminent*) or your manager is not aware how the software is stored (*which makes him helpless if you decide to leave or a truck hits you*).
This raise alarm bells, as all others have already pointed out, *the code does not belong to you and you have absolutely no right to deny access*. The only exception is if you are a freelancer and you have reserved your rights concerning your code.
My crystall ball suggests that perhaps other people have access and you fear that your line manager is a [pointy-haired boss](https://en.wikipedia.org/wiki/Pointy-haired_Boss) ? There are many reasons why he wants to access your code and some are entirely harmless.
* He does not actually want to look into your code, he simply wants to know how it is stored and how can it be accessed and is too proud to admit that he feels dumb. By demanding to see the code he can throw in this question as valid inquiry without losing face.
* He in fact tries to judge your code by showing (parts of) it to other persons he thinks have knowledge. Yes, having no clue this *could* backfire for you because he cannot determine if the other person is bullshitting him, but if not, it is completely ok. Code reviews by other persons who have knowledge are a standard practice, especially because people have specific advantages and weaknesses: They avoid certain errors, but are also falling in specific traps. If you do not want that, the problem is *you*.
* Your line manager is a person who cannot concede that he is powerless and tries to maintain the appearance that he is in charge. Therefore the meetings and demands to see the code. This depends on the person if it is either mostly harmless (time-waste meeting) or extremely annoying (he really tries to use senseless metrics, stupidly comments your code or has found a new silver-bullet programming guru).
* The worst case: Some people have decided that they are not satisfied with your work and seek replacement. Now they realize that a maximum credible accident has happened: They have no clue how your code works and try to fix it. Counterargument: If that would be the case, it is more likely that he would press the matter with daily meetings.
Live with it, do what he wants (user52889s good answer is to talk to find out what he really wants) and if it goes wrong, either solve the problem by complaining to a higher instance or take consequences. |
3,689,027 | I have a Time column in a database table. The date is not important, we just want a time in the day. What type would be best to represent it in C#? I was going to use a DateTime, but I don't like the idea of having a date. | 2010/09/10 | [
"https://Stackoverflow.com/questions/3689027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62642/"
] | You could use a [TimeSpan](http://msdn.microsoft.com/en-us/library/system.timespan.aspx) structure to represent a time in .NET. | We actually rolled our own Time class. The issue we ran into is TimeSpan has no knowledge of timezone offsets which we still needed. So We created a TimeSpanOffset class. Kind of analogous to the DateTimeOffset class. If timezone is not important than I would definitely stick with the TimeSpan. |
43,157,095 | How do you output all images in a directory to the same pdf output using fpdf. I can get the last file in the folder to output as a pdf or output multiple pdfs for each image, but not all images in the same pdf like a catalog. I'm sure it is the for loop but can't sort it out properly.
```
from fpdf import FPDF
from PIL import Image
import glob
import os
# set here
image_directory = '/home/User/Desktop/images/'
extensions = ('*.jpg','*.jpeg','*.png','*.gif')
# set 0 if you want to fit pdf to image
# unit : pt
margin = 10
imagelist=[]
for ext in extensions:
imagelist.extend(glob.glob(os.path.join(image_directory,ext)))
pdf = FPDF(unit="pt", format=[width + 2*margin, height + 2*margin])
pdf.add_page()
cover = Image.open(imagePath)
width, height = cover.size
for imagePath in imagelist:
pdf.image(imagePath, margin, margin)
destination = os.path.splitext(imagePath)[0]
pdf.output(destination + ".pdf", "F")
``` | 2017/04/01 | [
"https://Stackoverflow.com/questions/43157095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7801566/"
] | Still not sure why fpdf was not grouping the iteration of image files as a single PDF output but img2pdf accepted a list of file names worked very nicely.
```
import img2pdf
imagefiles = ["test1.jpg", "test2.png"]
with open("images.pdf","wb") as f:
f.write(img2pdf.convert(imagefiles))
``` | You will have to start a new page for every picture in the beginning of the for loop and end with writing everything to the PDF.
```
pdf = FPDF()
imagefiles = ["test1.png","test2.png"]
for one_image in imagefiles:
pdf.add_page()
pdf.image(one_image,x,y,w,h)
pdf.output("out.pdf")
``` |
583,673 | I add new folder (actually I cloned it from another repo, and forgot that), then I did some changes there. Additionally I did a lot of changes in another places, when I tried to do git add
```
# Changes not staged for commit:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
# (commit or discard the untracked or modified content in submodules)
#
# modified: protected/ext/SpecificFolder (modified content)
#
```
Then I remember that maybe there was .git folder (because previous I did git clone there).
I went to that folder and remove non needed files (folders) and .git folder too.
I checked git status, nothing strange. Then commit and checkout to another branch and suddenly I figure out that this folder was not added to last commit. Actually folder was added but files inside was ignored. Now even when I'm trying to do `git add` for that folder nothing happenning and `git status` do not show any changes :(
What can I do ? | 2013/04/16 | [
"https://superuser.com/questions/583673",
"https://superuser.com",
"https://superuser.com/users/119595/"
] | I happened to do exactly what this user did: Add an existing git repository inside another one.
The symptom was that git recognised that directory as a file, and thus was unable to add the directory's files.
To solve that question, I deleted the `.git` folder in the folder, moved that folder in another directory, cleared the index, removed the directory where in my repo, and then I was able to add the directory properly.
The moral of this is: don't add a repository inside another one. | Try adding a file in that directory.
```
$ git add my-dir/index.html
```
If you see a output like the below:
```
The following paths are ignored by one of your .gitignore files:
my-dir/index.html
Use -f if you really want to add them.
fatal: no files added
```
There's a rule in one of your gitignores that prevent you from adding that directory. |
15,116,675 | I have a little problem with CSS.
I'm following a book to learn CSS3 and I just discovered the function Transition.
So I decided to make an attempt and I can not figure out where I'm wrong, I hope you can help me.
This is my Index.html file
```
<html>
<head>
<title>My Test</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div class="box"></div>
<div class="ssin"></div>
</body>
</html>
```
nothing special ! and this is the main.css
```
.box{
height: 200px;
width: 200px;
background-color: #333333;
}
.ssin{
height: 200px;
width: 200px;
background-color: red;
}
.box:hover .ssin{
width: 500
}
```
i think the problem is around here ...
```
.box:hover .ssin{
width: 500;
}
```
If I hove .box nothing happen, theoretically it should change the width of ssin div.
Could you please help me (I know this is stupid, but I'am still learning)
Thank you | 2013/02/27 | [
"https://Stackoverflow.com/questions/15116675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1875391/"
] | You're missing the measurements from the `width` property, but your markup won't allow what you're trying to achieve.
`.box:hover .ssin` will only make trigger when `.ssin` is a child of `.box`. If you want to animate the width of `.ssin` when `.box` is hovered, you'll have to use the adjacent sibling selector in CSS (`+`):
```
.box:hover + .ssin {
width: 500px;
}
```
If you want the element to be animated, you need to add the relevant CSS properties too:
```
.ssin {
-webkit-transition: width 0.2s linear;
-moz-transition: width 0.2s linear;
transition: width 0.2s linear;
}
```
Here's a [**jsFiddle demo**](http://jsfiddle.net/Ph2jH/1/). | Since you are trying to look into CSS3 Transition, I will assume you are trying to increase the size of the box. SO, your markup is slightly wrong. The `ssin` should be inside the `.box`
```
<div class="box">
<div class="ssin"></div>
</div>
```
And add the transition css to your code
```
.ssin {
-webkit-transition: all 0.5s linear;
-moz-transition: all 0.5s linear;
transition: all 0.5s linear;
}
``` |
20,126,882 | I have two `<a>` in a `<p>` and I want to assign them different borders when selected.
When the user clicks on a `<a>` a JavaScript sets the class to `"selected"` and the border shall turn to green if it is the first `<a>` but if the second `<a>` is clicked and assigned class="selected" the border shall turn to red.
What I would like to do in CSS is something like:
```
a:first-child.selected {border-color:green}
a.selected {border-color:red}
```
But that does not work.
There are a lot of examples out there which describes how to select the first-child of a specific class but none which describes how to select the first-child of a certain tag IF it has a certain class.
Is this possible to achieve at all?
What I have done now is to set the first `<a>` as `class="yesselected"` and if the second is clicked it will have `class="noselected"`.
But i would really like to know if it is possible to select a tag if it is the first one and it has a certain class | 2013/11/21 | [
"https://Stackoverflow.com/questions/20126882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2217238/"
] | I originally thought your css was slightly off, you needed the pseudo element at the end. That appears to be wrong in the case of pseudo classes. Thanks to @BoltClock's a Unicorn
```
a.selected:first-child {border-color:green}
a.selected {border-color:red}
```
However I have to ask if your css sets the border to appear somewhere else with all of the needed border value declarations?
```
a{border: 1px solid transparent;}
a.selected:first-child {border-color:green}
a.selected {border-color:red}
```
<http://jsfiddle.net/8hPw8/> | Shouldn't it be
a.selected:first-child
?
Edit: Boltclock is right, the ordering doesn't matter.
It's to do with the exact behaviour of the [:first-child](http://www.w3schools.com/cssref/sel_firstchild.asp) selector.
```
a:first-child
```
refers to the ***a*** tag that is the first child of it's parent element and not to the first **a** child of an element. |
25,959,049 | I have the following class:
package ajia.messaging;
```
public class MessageCommunicator {
public void deliver(String message) {
System.out.println(message);
}
public void deliver(String person, String message) {
System.out.println(person + ", " + message);
}
}
```
And the following advice:
```
package ajia.security;
import ajia.messaging.MessageCommunicator;
public aspect SecurityAspect {
private Authenticator authenticator = new Authenticator();
pointcut secureAccess()
: execution(* MessageCommunicator.deliver(..));
before() : secureAccess() {
System.out.println("Checking and authenticating user");
authenticator.authenticate();
}
}
```
I compile everything like this - `ajc -source 5 ajia\messaging\MessageCommunicator.java ajia\security\SecurityAspect.aj`
As I understand the resulting `MessageCommunicator.class` will already have aspect code included. I was wandering if standard java decompilers will decompile the class correctly? | 2014/09/21 | [
"https://Stackoverflow.com/questions/25959049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1125515/"
] | ```
var addedLis=0
$(function(){
$("#myList").on("click",".myButton",function(){
addedLis++;
var _newLI='<li id="addedItem'+addedLis+'">Added Item '+addedLis+' <a href="javascript:void(0)" class="myButton">Add</a></li>'
$(this).parent().after(_newLI);
});
});
```
`**[Example](http://jsfiddle.net/TheBanana/bvhuj98k/)**` | ```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<ul id="myList">
<li id="item1">Item 1 <a onclick='$(this).append("<li>a</li>");' class="myButton">Add</a></li>
<li id="item2">Item 2 <a onclick='$(this).append("<li>a</li>");' class="myButton">Add</a></li>
<li id="item3">Item 3<a onclick='$(this).append("<li>a</li>");' class="myButton">Add</a></li>
<li id="item4">Item 4 <a onclick='$(this).append("<li>a</li>");' class="myButton">Add</a></li>
<li id="item5">Item 5 <a onclick='$(this).append("<li>a</li>");' class="myButton">Add</a></li>
</ul>
``` |
10,991,455 | Spreadsheet based Apps that were published as services had URLs of this form:
https: //spreadsheets3.google.com/a/macros/my-domain.com/exec?service=AKfycbwly1SYZhdnPOoKfkH\_xB7oMKDeYifYm8M
Today, these URLs are resulting in an error page with a Google Drive logo and the message "Google Docs has encountered a server error. If reloading the page doesn't help, please contact us.". They have an HTTP 500 error if you look at the headers. | 2012/06/12 | [
"https://Stackoverflow.com/questions/10991455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/298650/"
] | Sounds like you want everything in `array2` *except* what's in `array1`:
```
var onlyInArray2 = array2.Except(array1);
```
Of course, if you *also* wanted to know what was only in `array1` you could use:
```
var onlyInArray1 = array1.Except(array2);
```
(This all requires .NET 3.5 or higher, or an alternative LINQ to Objects implementation such as LINQBridge.)
I'm assuming that order isn't important when computing differences - `Except` is a set-based operator, so assumes that you're regarding the collections as sets.
Note that `Except` just returns an `IEnumerable<T>` - if you want the results as arrays, you'll need to call `ToArray`:
```
var onlyInArray2 = array2.Except(array1).ToArray();
var onlyInArray1 = array1.Except(array2).ToArray();
```
If you want the symmetric difference, i.e. you only care about which values are in a single array, rather than which array they came from, you could use:
```
var onlyInOneArray = array1.Union(array2).Except(array1.Intersect(array2));
```
or you could use `HashSet` directly:
```
var set = new HashSet<string>(array1);
// This modifies the set...
set.SymmetricExceptWith(array2);
```
In all of these, the resulting order is undefined, although in practice `Except` will preserve the original order of the first argument. While this is strictly speaking an implementation detail, I think it's very unlikely to change.
Like the other set-based operators in LINQ, `Except` will only return any element once - so if `COM8` appeared twice in `array2`, it would only appear once in the result. | You could use [IEnumerable.Except](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.except.aspx). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.