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 |
|---|---|---|---|---|---|
24,235,467 | I am writing some program to get the list of shortcut files on Desktop.
and I find some strange things about this.
Most programs will create shortcut files on Windows Desktop like "Mozilla Firefox.lnk" or "Google Chrome.lnk" after installed. I can see these shortcuts on Desktop and use them to launch programs.
But I find that if you use Windows Explorer to open the desktop folder, you can't see these lnk files on the list. Some lnk files are visible while some are not (e.g. Mozilla Firefox, Google Chrome, Opera). That's the strangest part. I can't tell what's the different between them.
Then I try to open the cmd program and use "dir" command to list the files on Desktop and also can not see these files.
Then I try to write some code to test with C#
File.Exists(@"C:\Documents and Settings\user\Desktop\Google Chrome.lnk")
The result is "False", that means the lnk file is not exist on the Desktop.
Then I move the "Google Chrome.lnk" from desktop to a folder and move it back.
Now I can see it on Windows Explorer and cmd "dir" command
and the result of the code
File.Exists(@"C:\Documents and Settings\user\Desktop\Google Chrome.lnk")
is "True".
I have no idea what has been changed after the lnk file move out from desktop and move back, but now it appears like a normal file.
Does anyone notice this and know why it likes this?
Thanks. | 2014/06/16 | [
"https://Stackoverflow.com/questions/24235467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2351537/"
] | The answer is:
Some lnk files are in the "All Users\Desktop" folder
not in the current user's Desktop
Thanks to @DanielA.White | I know this is a really old thread, but I thought I'd share anyway. I had a .Ink file on my desktop that would not delete. After trying to delete it a number of times in different ways I decided to just right click the desktop and click refresh. It disappeared! Sounds too easy to be true doesn't it? |
1,824,214 | Is there any way to open the YouTube app from my app, with a defined search query?
If not, is there a way to just *open* YouTube, without playing any video?
All I'm finding is ways to play videos. | 2009/12/01 | [
"https://Stackoverflow.com/questions/1824214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/87158/"
] | You can use [*event delegation*](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation) for that. Basically you add one clickhandler to your table. This handler reads out the tagname of the clicked element and moves up the DOM tree until the containing row is found. If a row is found, it acts on it and returns. Something like (not tested yet, but may give you ideas):
```
var table = document.getElementById('my_table');
table.onclick = function(e) {
e = e || event;
var eventEl = e.srcElement || e.target,
parent = eventEl.parentNode,
isRow = function(el) {
return el.tagName.match(/tr/i));
};
//move up the DOM until tr is reached
while (parent = parent.parentNode) {
if (isRow(parent)) {
//row found, do something with it and return, e.g.
alert(parent.rowIndex + 1);
return true;
}
}
return false;
};
``` | The `this` keyword can be used to get the `parentNode` of the cell, which is a `<tr>` element. The `<tr>` element has a property for the row number, `.rowIndex`.
The Event:
----------
```
onclick='fncEditCell(this)'
```
The Function:
-------------
```
window.fncEditCell = function(argThis) {
alert('Row number of Row Clicked: ' + argThis.parentNode.rowIndex);
};
```
Full Working Example Here:
--------------------------
[jsFiddle](http://jsfiddle.net/fsPN2/)
Dynamically Set OnClick Event
-----------------------------
Use `.setAttribute` to inject a click event:
```
cell2.setAttribute("onmouseup", 'editLst(this)');
```
Example of Dynamically Creating a Table:
----------------------------------------
```
for(var prprtyName in rtrnTheData) {
var subArray = JSON.parse(rtrnTheData[prprtyName]);
window.row = tblList.insertRow(-1);
window.cell1 = row.insertCell(0);
window.cell2 = row.insertCell(1);
window.cell3 = row.insertCell(2);
window.cell4 = row.insertCell(3);
window.cell5 = row.insertCell(4);
window.cell6 = row.insertCell(5);
window.cell7 = row.insertCell(6);
window.cell8 = row.insertCell(7);
window.cell9 = row.insertCell(8);
cell1.setAttribute("onmouseup", 'dletListing(this.title)');
cell1.setAttribute("title", "'" + subArray.aa + "'");
cell2.setAttribute("onmouseup", 'editLst(this)');
cell2.setAttribute("title", "'" + subArray.aa + "'");
cell1.innerHTML = "Dlet";
cell2.innerHTML = "Edit";
cell3.innerHTML = subArray.ab;
cell4.innerHTML = "$" + subArray.ac;
cell5.innerHTML = subArray.ad;
cell6.innerHTML = subArray.ae;
cell7.innerHTML = subArray.af;
cell8.innerHTML = subArray.ag;
cell9.innerHTML = subArray.meet;
};
``` |
31,632,922 | The situation
-------------
In table I have columns configurated as `ENUM('0','1')`. I have select query build with PDO like this example
```
$value = isset($_POST['value']) ? $_POST['value'] : (isset($_GET["value"]) ? $_GET["value"] : null);
$sql = $pdo->prepare("SELECT * FROM tablename WHERE column = :value");
$sql->bindValue(':value', $_POST['value']); // post contains 0 or 1
$sql->execute();
```
---
The problem
-----------
When printing the results, value 1 is working normally. But when using value 0, all rows are showing including rows with value 1.
Following query is working normally when trying it in HeidiSQL, but it's not with PHP. What's wrong?
```
SELECT * FROM tablename WHERE column = '0'
```
I noticed that PHP thinks `$_POST['value']` is unset when its value is zero. I'm using `isset()`
---
Trying to solve the problem
---------------------------
* **No effect** either if using `$_GET['value']` and url like `index.php?value=0`
* Tried following, **not working**
```
$sql->bindValue(':value', '0'); // post contains 0 or 1
```
* I changed column type to `TINYINT(1)` - **no effect.** When looking for zero, all are showing.
* Set PDO `bindValue()` `$data_type` to `PDO::PARAM_BOOL`, **not working** | 2015/07/26 | [
"https://Stackoverflow.com/questions/31632922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4530969/"
] | To make sure `num` is a whole number, without having to define all possibilities, use:
```
if (num % 1 == 0)
``` | You have to edit the "If" loop:
```
if (num == 1 || num == 2 || num == 3 || num == 4 || num == 5)
``` |
10,554 | I claim that it is commonly believed that Mathematical objects can be seen as genuinely static, with no "Platonic" time in which they do genuinely evolve.
Nevertheless time has its place in mathematics:
1. An [endomorphism](https://en.wikipedia.org/wiki/Endomorphism) of a set (seen as a set of states of a system) into itself can be seen as evolution of the system in discrete time steps.
2. For a function of a totally ordered set into a set (seen as above) the ordered set can be seen as "time".
3. as the time-like component in Minkowski space
Questions (slightly modified after Qiaochu's comment and Vhailor's answer):
>
> Which other constructs do give you a "time feeling" or give rise to "dynamic intuition" admit a comparable straight-forward
> interpretation as "time"?
>
>
> The examples above are set-theoretical ("concrete"). Is there a more abstract modelling of "time", maybe in category theory?
>
>
> | 2010/11/16 | [
"https://math.stackexchange.com/questions/10554",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/1792/"
] | I wish I had this reference handy, but Atiyah said something to the effect that algebra is about time and geometry is about space. The "processes" in mathematics are, in the broadest sense, the things concerned with time. (This doesn't take into account the idea of "reification", the transformation of a process into an object, which is central to mathematical practice.) | If you consider TCS to be maths, then formal semantics, in particular small-step or big-step semantics, might be of interest. Those map input data and a series of operations to a sequence of universes/states, on per time step. |
43,984,504 | I am having a Dictionary which have multiple values for each key. Now, I need to get the count of each distinct value instance for that key.
lets say
```
dict(key, list{value}) = ({1,{1,1,2,3,3}},{2,{1,1,1,2,3,3}})
```
I need
```
count of 1 for key 1 : 2
count of 2 for key 1 : 1
count of 3 for key 1 : 2
```
I need to do this for every key in my dictionary. Any help is greatly appreciated. Thanks. | 2017/05/15 | [
"https://Stackoverflow.com/questions/43984504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7643826/"
] | Well, problem was solved by simply deleting everything related to vue-cli installed before. And re-installing vue-cli. | I have faced simillar issue and re-installing vue-cli didn't work for me. Strange thing is vue and vue-cli get installed successfully but once I tried to create project by using below command
```
vue init webpack myfirstproject
```
I get below error:
```
'vue' is not recognized as an internal or external command,operable program or batch file.
```
Tried various solutions but nothing worked for me. Please find my NPM and Node details below:
```
NPM version: 6.2.0
Node version: 8.7.0
```
Actually the issue was "vue-cli" is not supporting to my Node(8.7.0). It requires Node >=8.9. Once I upgraded my Node version. everything is working fine.
```
upgrading your Node version is the correct way to deal with this issue
``` |
28 | And other than public domain science fiction, how can I track down Creative Commons science fiction that is safe for re-mixing, i.e. fan fic? | 2011/01/11 | [
"https://scifi.stackexchange.com/questions/28",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/10/"
] | The [Dryden Experiment](https://web.archive.org/web/20140510000931/http://www.thedrydenexperiment.com/) is an entirely Creative Commons 3.0 driven universe. | The universe I created in Blaze Master Mysterium of the Universe is safe for use in your fanfictions, if you like my stories feel free to use the world and settings, I am a little attached to the main character though, but feel free to use the rest, just credit me on the ideas you use. |
3,309,754 | 1. Is the series $$\sum\_{k=1}^{\infty} \frac{\sqrt{k}}{k^2+1}$$ convergent?
This behaves similar to $\frac{\sqrt{k}}{k^2} = \frac{1}{k^{3/2}}$ so do we use the comparison test??? | 2019/07/31 | [
"https://math.stackexchange.com/questions/3309754",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/619325/"
] | Note that for all $k\geq 1$,
$$
0\leq\frac{\sqrt{k}}{k^{2}+1}\leq\frac{\sqrt{k}}{k^{2}}=\frac{1}{k^{3/2}}.
$$
The series
$$
\sum\_{k=1}^{\infty}\frac{1}{k^{3/2}}
$$
converges since $3/2>1$. Therefore, by the Basic Comparison test, your series also converges. | Yes, since $\frac{\sqrt{k}}{k^2+1} \le \frac{\sqrt{k}}{k^2}$, this is exactly the right approach. Then use the $p$-series test. |
55,011,646 | 1st week into a JS and trying to solve first Kata in CodeWars.
Your task is to write a function that takes a string and return a new string with all vowels removed.
For example, the string "This website is for losers LOL!" would become "Ths wbst s fr lsrs LL!".
My code:
```js
function disemvowel(str) {
var newStr = "";
for (i = 0; i <= str.length; i++) {
if (str.charAt(i) != "a" || str.charAt(i) != "e" || str.charAt(i) != "i" || str.charAt(i) != "o" || str.charAt(i) != "u") {
newStr += str.charAt(i)
}
return newStr;
}
}
```
Expected: 'Ths wbst s fr lsrs LL!', instead got: 'T'
Why does my loop stops? It doesn't continue with i++? Probably beginner's mistake. Appreciate any help. | 2019/03/05 | [
"https://Stackoverflow.com/questions/55011646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11156342/"
] | Some annotations:
* declare `i`,
* loop until `i < str.length`, because arrays and strings are zero based,
* take a string for checking a character with [`String#includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes),
* use a single character by taking a [property accessor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors) with the index, instead of [`String.charAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt) (it is shorter),
* take a small letter case for checking
* [`continue`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue) the `for` statement, if a character is found,
* move the [`return` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return) to the end of the function.
```js
function disemvowel(str) {
var newStr = "",
i;
for (i = 0; i < str.length; i++) {
if ("aeiou".includes(str[i].toLowerCase())) continue;
newStr += str[i];
}
return newStr;
}
console.log(disemvowel("This website is for losers LOL!"));
``` | My Solution !
```
function disemvowel(str) {
let newStr = (str.replace(/A|E|I|O|U|a|e|i|o|u/g, ''))
return newStr;
}
``` |
67,405,791 | I just updated Android Studio to version 4.2. I was surprised to not see the Gradle tasks in my project.
In the previous version, 4.1.3, I could see the tasks as shown here:
[](https://i.stack.imgur.com/7fhMP.png)
But now I only see the dependencies in version 4.2:
[](https://i.stack.imgur.com/ScuhS.png)
I tried to clear Android Studio's cache and sync my project again, but there was no change.
Is this a feature change? | 2021/05/05 | [
"https://Stackoverflow.com/questions/67405791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4424400/"
] | **Solution 1:**
You can alternatively use the below gradle command to get all the tasks and run those in terminal
```
./gradlew tasks --all
```
**Solution 2.**
You can also create run configuration to run the tasks like below:
Step 1:
[](https://i.stack.imgur.com/EYUAn.png)
Step 2:
[](https://i.stack.imgur.com/ySify.png)
Step 3:
[](https://i.stack.imgur.com/zrswj.png)
Then your run configuration will be listed like in step 1 image. You can choose and simply run it as usual. | I had a similar issue and I solved it by executing the following terminal command in my Android Studio Terminal:
```
./gradlew tasks --all
``` |
67,045,725 | Hi i'm new to python and i am having issues with exceptions. i have added an exception but it is not working. Below is a sample of my problem.
```
if x == '1':
print("----------------------------------")
print("1. REQUEST FOR A DOG WALKER")
print("----------------------------------")
try:
print("Select a Date (DD/MM/YY) - eg 12/04/21")
except ValueError:
raise ValueError('empty string')
date = input()
try:
print("Select a Duration (in hours) - eg 2")
duration = input()
except ValueError:
print('empty string')
print("Select a breed : 1 - Rottwieler , 2 - Labrador Retriever, 3 - Pitbull, 4 - Other ")
breed = input()
print("Number of Dogs - eg 3 ")
dogsNumber = input()
``` | 2021/04/11 | [
"https://Stackoverflow.com/questions/67045725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7174831/"
] | Whenever you use a try/except statement you are trying to catch something happening in the code the shouldn't have happened. In your example, you are haveing the user enter a number for a duration:
```
print("Select a Duration (in hours) - eg 2")
duration = input()
```
At this point, duration might equal something like '2'. If you wanted to add 10 to it then you could not because it is a string(you cannot and int+str). In order to do something like this, you would have to convert the user input to an int. For example:
duration = int(input())
The problem is that if the user enters a letter A, then the program will break when it tries to convert it to an int. Using a try/except statement will catch this behavior and handle it properly. For example:
```
try:
print("Select a Duration (in hours) - eg 2")
duration = int(input())
except ValueError:
print('empty string')
``` | There is nothing in your code that can produce `ValueError`.
So the `except ValueError:` is not matched. |
145,563 | Scenario:
I was unemployed from January through July 2021.
I started new job at the end of July 2021.
Employer allows me to join 401k plan after 90 days, which means I’m enrolled starting November 1, 2021.
On a 40 hour week, paid hourly, assuming no vacations taken/holidays taken (as they are unpaid), my income would max out at around the $100k mark.
I am paid weekly on Fridays.
From the above, there are 4 Fridays in November and 5 Fridays in December. Max gross pay, disregarding all the unpaid holidays, tops out at just shy of 17k.
I’m not entirely sure what the dollar amount would be if I decided to contribute the remainder of all my paychecks to the 401k plan, but regardless, my theoretical maximums would be below the $19,500 deduction limit. Would I be able to contribute other money I have (savings, etc) to hit the maximum? | 2021/10/12 | [
"https://money.stackexchange.com/questions/145563",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/106986/"
] | >
> So my question is... suppose a stock price were to continuously drop despite high company performance (profits)... Is there something the shareholders can do to get some share of the profits?
>
>
>
This seems like a faulty premise. The stock price is based on the market's estimate of the company's future prospects. It's unlikely that a company that has high performance now will experience major downturn, and even more unlikely that investors will be able to predict this and factor it into the stock price.
Stock prices don't move by themselves, they're the result of investors actually buying and selling shares. Theoretically, their decisions about what price to buy/sell at are based on reliable information about the company's activity and prospects. Of course, information isn't always perfect and complete, and predicting the future reliably is impossible, which is why different investors may have different valuations of the same company, and this is what fuels the market. But generally the stock price is a reasonable representation of the company's value.
There can be exceptions. A company might be doing well in a market whose future prospects are dim. For instance, when cars took over from horses as the dominant form of transportation, investors could predict that the horse-drawn wagon industry would decline, and companies that didn't make the transition were in trouble.
There can also be anomalies like the [GameStop short squeeze](https://en.wikipedia.org/wiki/GameStop_short_squeeze) early this year, where a group of investors triggered a sudden run-up of the share price. This is unusual because the perpetrators of this also suffered losses as a result -- they were essentially sacrificing small losses by each individual to cause large hedge funds to lose millions of dollars.
All that said, I've often had a similar feeling to yours. It does seem like the stock market is just a big game. Yes, I can vote my shares, but the majority investors have almost total control, so my vote has little significance (Mark Zuckerberg personally owns a majority of Facebook stock, so no one can outvote him). Non-dividend shares of stock don't produce any intrinsic returns unless the company liquidates and distributes assets to investors.
But the market works because investors *want* it to work. It's not a Ponzi scheme because there is some underlying valuation involved. The companies we invest in make things and/or perform services. While it sometimes feels like gambling, it's not like a casino because outcomes aren't random: well-run companies in a healthy industry generally do well, poorly run companies and companies in a declining industry don't. And if you do your due diligence, you can usually tell which are which. If you want to compare it with games, it's more like sports betting than roulette -- you can look at the records of all the teams when deciding which one to place your bet on.
There's a reason why there are successful investors and fund managers like Warren Buffett and Peter Lynch -- knowledge and experience actually matter when deciding what to invest in. | A dollar bill has the same intrinsic value as a 100 dollar bill yet I'm sure you'd rather have someone give you the latter; the entire premise of this question is completely flawed. Perception is reality, and in everyday life you will constantly encounter countless things with low intrinsic value yet are highly valued, the fashion industry in particular is built around this concept. Nobody buys a $10,000 watch because it tells the time better, in fact it does worse than even a 5 buck one that uses quartz rather than mechanical movement. |
343,896 | While easy on Linux, not as easy on Windows from what I've been able to gather so far. I've found the command that kinda does what I want which is:
```
net user username /domain
```
However I wish to strip all of the data except for the list of the groups. I think findstr may be the answer but I'm not sure of how to use this to do that. Essentially, I guess the script would do something like this (unless there is a more specific command which would be fabulous):
```
net user username /domain > temp.txt
findstr (or some other command) file.txt > groups.txt
del temp.txt
```
The output of the data would be a list like this:
group1; group2; group3
Now, I could be going about this a complicated way, so as I mentioned if there is a command that can output ONLY a user's security groups that would be fantastic. | 2011/10/07 | [
"https://superuser.com/questions/343896",
"https://superuser.com",
"https://superuser.com/users/100387/"
] | ```
dsquery user -name "My Full Name" | dsget user -memberof | dsget group -samid
```
I found this pretty much gives me what I was looking for, in case anyone was curious! :) | Use PowerShell!
```
$user = [wmi] "Win32_UserAccount.Name='JohnDoe',Domain='YourDomainName'"
$user.GetRelated('Win32_Group')
```
or only for group names:
```
$user = [wmi] "Win32_UserAccount.Name='JohnDoe',Domain='YourDomainName'"
$user.GetRelated('Win32_Group') | Select Name
```
<http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/67defa12-6ad1-439b-bd11-3abfc5b5208a/> |
42,630,042 | I have set up a stored procedure which I am passing a data table into and calling directly from Entity Framework.
I have created a Type with the following sql:
```
CREATE TYPE Regions AS TABLE
( RegionId int,
Region varchar(max),
BodyId int NULL,
Body varchar(max),
AreaId int NULL,
Area varchar(max),
Location varchar(max),
LocationId int
)
```
My test stored procedure is as follows:
```
CREATE PROCEDURE [dbo].[GetStats]
@regions dbo.Regions READONLY
AS
BEGIN
SELECT * INTO #tmptble from @regions
Select * from #tmptble
END
```
I am using the following to call the stored procedure:
```
SqlParameter param = new SqlParameter();
param.SqlDbType = SqlDbType.Structured;
param.TypeName = "dbo.Regions";
param.Value = myDataTable;
param.ParameterName = "@regions";
return _context.Database.SqlQuery<RegionDetails>("GetStats", param);
```
My datatable is definitely the correct format as I have run this through profiler passing it in to the stored procedure and you can see all the inserts appearing.
If I generate a test table from all the insert statements the procedure runs fine against that but when I run it with the passed in datatable it just returns no rows.
**EDIT - for further info**
When I run this through profiler I get the following:
```
declare @p3 dbo.Regions
~~~a Load of insert statements of all my datatable data~~~
exec sp_executesql N'GetStats',N'@regions [dbo].[Regions] READONLY',@regions =@p3
```
**UPDATE on the above**
I have been playing around with what is shown in profiler and if I replace
>
> exec sp\_executesql N'GetStats',N'@regions [dbo].[Regions]
> READONLY',@regions =@p3
>
>
>
with
>
> EXEC GetStats @p3
>
>
>
Again it works. Has anyone got any clue why? | 2017/03/06 | [
"https://Stackoverflow.com/questions/42630042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/390501/"
] | Try this approach:
```
//create parameter
var param = new SqlParameter("@regions", SqlDbType.Structured);
param.Value = myDataTable;
param.TypeName = "dbo.Regions";
//return result set
return _context.ExecuteFunction<RegionDetails>("dbo.Regions", param);
//OR
//execute stored procedure for inserts, returns rows effective
return _context.Database.ExecuteSqlCommand("exec dbo.Regions @regions", param);
``` | Answer based on @SteveD's answer but to clarify exactly what I did incase it helps any one else.
There was nothing wrong with my stored procedure. It was purely my calling of it. It needed the parameter name in the actual call like so:
```
SqlParameter param = new SqlParameter();
param.SqlDbType = SqlDbType.Structured;
param.TypeName = "dbo.Regions";
param.Value = myDataTable;
param.ParameterName = "@regions";
return _context.Database.SqlQuery<RegionDetails>("GetStats @regions", param);
``` |
68,218,092 | I'm trying to do cost optimization to reduce the cost of using AWS resources by stopping EC2 and RDS instance when they are not in use.
I managed to create a scheduler using AWS CloudFormation service, and the instances are stopping according to the scheduler configurations but the problem is that after the instance gets stopped, AWS initiate another one.
Please advice if there is a way to control this behavior or change it.
Regards. | 2021/07/01 | [
"https://Stackoverflow.com/questions/68218092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5692288/"
] | You **can't stop** instances in Elastic Beanstalk (EB) by just stopping, as they run in [AutoScaling Group](https://docs.aws.amazon.com/autoscaling/ec2/userguide/what-is-amazon-ec2-auto-scaling.html). So once you stop the instance, ASG will launch a replacement, which is expected.
The proper way to stop the instances in auto-scaling group is to [detach](https://docs.aws.amazon.com/autoscaling/ec2/userguide/detach-instance-asg.html) them first, or best to set [min and desired capacity to 0](https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-capacity-limits.html). The last option will terminate the instances, but this is the easiest strategy to reduce cost of running instances in ASG when not needed.
But since you are terminating instances, you may as well terminate entire EB environment, and launch new one when needed. This should be easy if you do it using CloudFormation. | I would like to thank @**Marcin** and @**Jatin** for their answers.
>
> Notes:
>
>
>
* Detaching EC2 instance without setting the Desired capacity and
Minimum capacity to 0 won't help because ASG will launch a new
instance.
* If you set Desired capacity and Minimum capacity to 0 instance will
get terminated automatically.
* Detaching EC2 and setting Desired capacity and Minimum capacity to 0 (if allowed)
will lead to a sever health status in your ELB Environment and you
won't be able to restart your APP or rebuild the environment until
you set the Desired capacity and Minimum capacity to 1 and do the
process over again.
* You can't put EC2 on standby if Desired capacity and Minimum capacity
are set to 0.
>
> My approach to solving the problem:
>
>
>
1. Set Desired capacity to 1 and Minimum capacity to 0 in the [Auto
Scaling group][1] details.
2. Scroll down to the `Advanced configurations` and add `Terminate` to the
`Suspended processes`.
3. Go to `Automatic Scaling` tab of the Auto Scaling group, choose first
policy on the left then click `edit` from the `Actions` menu. In the
`Take the action` field, choose `set to` instead of `remove` then click update.
4. Go to your EC2 instance the you need to schedule and and add the
scheduler `tag` to it.
The Previous approach will help you schedule the [stop & start] of ELB EC2 instance, if your project runs on one instance and you need to do cost optimization.
If you are using more than one EC2 instance, you need to adjust the previous configurations. |
9,629,659 | Say I have an appropriately sized image inside an `Image()`
I want to change the Thumb or Knob of the `JScrollBar` component to be this image.
I know I need to subclass the `ScrollBarUI`
Here is where I am at right now.
```
public class aScrollBar extends JScrollBar {
public aScrollBar(Image img) {
super();
this.setUI(new ScrollBarCustomUI(img));
}
public class ScrollBarCustomUI extends BasicScrollBarUI {
private final Image image;
public ScrollBarCustomUI(Image img) {
this.image = img;
}
@Override
protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) {
Graphics2D g2g = (Graphics2D) g;
g2g.dispose();
g2g.drawImage(image, 0, 0, null);
super.paintThumb(g2g, c, thumbBounds);
}
@Override
protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) {
super.paintTrack(g, c, trackBounds);
}
@Override
protected void setThumbBounds(int x, int y, int width, int height) {
super.setThumbBounds(0, 0, 0, 0);
}
@Override
protected Dimension getMinimumThumbSize() {
return new Dimension(0, 0);
}
@Override
protected Dimension getMaximumThumbSize() {
return new Dimension(0, 0);
}
}
}
```
Right now I don't see any Thumb, only a Track when I try to click around the ScrollBar.
I checked out [this](https://stackoverflow.com/questions/2865108/custom-jscrollbar-problem-change-the-knob-thumb) article and saw people recommended you read [this](http://explodingpixels.wordpress.com/2008/12/08/skinning-a-scroll-bar-part-1/) but nowhere does he mention images so this is what I came up with.
Hopefully someone can help me, Thanks! | 2012/03/09 | [
"https://Stackoverflow.com/questions/9629659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/625562/"
] | i am using this for sending email, in ASP.net MVC3
```
System.Web.Helpers.WebMail.SmtpServer = smtp_server;
System.Web.Helpers.WebMail.SmtpPort = smtp_port;
System.Web.Helpers.WebMail.EnableSsl = true;
System.Web.Helpers.WebMail.From = "fromaddress";
StringBuilder sb = new StringBuilder();
sb.Append("<table><tr><td>");
sb.Append(msg);
sb.Append("</td></tr></table>");
string body = sb.ToString();
string To = toemail;
System.Web.Helpers.WebMail.Send(To,subject, body);
``` | It look like you are trying to send emails through GMail's SMTP service, which this SO question already covers: [Sending email in .NET through Gmail](https://stackoverflow.com/questions/32260/sending-email-in-net-through-gmail)
The only thing that looks missing in your code is that you've set `client.UseDefaultCredentials = true`, I think you want to set this to `false` and provide your own credentials. I've never tried using GMail to send through emails, but I'm guessing you'll need to use a GMail account as your credentials in order to authenticate properly. |
5,366,761 | I have an app that speaks words. However, when word B is pressed, I want to stop word A. Is there a way to do that? This is my code for speaking the words:
```
-(IBAction)sayIt:(id)sender
{
//NSLog(@"%s", __FUNCTION__);
CFBundleRef mainBundle = CFBundleGetMainBundle();
FlashCardsAppDelegate *mainDelegate = (FlashCardsAppDelegate *)[[UIApplication sharedApplication] delegate];
CFURLRef soundFileURLRef;
soundFileURLRef= CFBundleCopyResourceURL (mainBundle, (CFStringRef)[mainDelegate soundFile], CFSTR("caf"), NULL);
UInt32 soundID;
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
AudioServicesPlaySystemSound(soundID);
}
``` | 2011/03/20 | [
"https://Stackoverflow.com/questions/5366761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/542019/"
] | Sadly, there isn't one at the moment, although a lot of people would love there to be one. My advice to anyone who asks this question is to simply output the report as a PDF on the server, and host it in an Iframe overlayed on your application (or hosted in the WebBrowser control if running outside the browser). I include links to an article I've written on the topic, and the code associated with my book (that also covers this topic, but also includes support for OOB) in this similar question: [Show pdf inside silverlight application. PDF to XAML](https://stackoverflow.com/questions/4770952/show-pdf-inside-silverlight-application-pdf-to-xaml/4772963#4772963).
Hope this helps...
Chris Anderson | There is no free viewer I am aware of, but commercially you have this - <http://www.perpetuumsoft.com/Silverlight-Viewer-for-Reporting-Services.aspx> |
20,628,525 | I have a small script.
```
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$( "p" ).first().replaceWith("Hello world!");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Replace the first p element with new text</button>
```
This replaces the content inside the first with "Hello world!".
I got same result with 2 jquery script.
```
1) ( "p:first" )
2) ("p").first()
```
What is the exact difference between these 2 scripts. | 2013/12/17 | [
"https://Stackoverflow.com/questions/20628525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1455347/"
] | According to performance test [found here](http://jsperf.com/jquery-first-vs-first-selector) the second way (`$("p").first();`) is much faster. | First on `:filter` is slower as it includes sizzler library. which needs to do extra work.
[Here is a test to run and see performance](http://jsperf.com/eq-vs-eq) |
9,594,482 | Running Mac Eclipse Helios SR2, the menu that appears on `command`-hovering over a method sometimes comes up empty instead of the usual Declaration/Implementation option:

The last time this happened, it went back to normal after a few days with no obvious intervention on my part, but I haven't been able to make that happen again this time. While not debilitating, it's certainly obnoxious and any help is greatly appreciated. | 2012/03/07 | [
"https://Stackoverflow.com/questions/9594482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85950/"
] | There is a CTags package for Sublime Text that makes it possible to use a project level ~~.ctags~~ `.tags` index file to jump to the definition of the symbol under the cursor by hitting `ctrl`+`t` twice: <https://github.com/SublimeText/CTags> | For Python,
I added the project to sublime.
I press `CTRL+R` and then start typing the name of my function. The cursor then points to the beginning of function definition.
Hope this helps. |
22,273,504 | I have a list of categories and items, and I want to return only the categories that have one type of Item. For instance:
Stuff table:
```
Cat 1 | Item 1
Cat 1 | Item 1
Cat 1 | Item 2
Cat 1 | Item 2
Cat 1 | Item 3
Cat 1 | Item 3
Cat 1 | Item 3
Cat 2 | Item 1
Cat 2 | Item 1
```
I would like to return
```
Cat 2 | Item 1
```
I tried:
```
SELECT category, item
FROM stuff
GROUP BY category, item
HAVING Count(Distinct item) = 1
```
But it's not working. I returns:
```
Cat 1 | Item 1
Cat 1 | Item 2
Cat 1 | Item 3
Cat 2 | Item 1
``` | 2014/03/08 | [
"https://Stackoverflow.com/questions/22273504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1629047/"
] | You should remove `item` from your `GROUP BY` clause and run this instead:
```
SELECT category, MAX(item)
FROM stuff
GROUP BY category
HAVING COUNT(DISTINCT item) = 1
```
Example [SQLFiddle](http://sqlfiddle.com/#!6/e1f4aa/1).
Otherwise, each group returned from the `GROUP BY` clause will naturally have exactly one distinct item. | Possibly your database does not allow you to have a variable in the select that is neither in the group by nor aggregated.
Taking advantage that there is only one item, you could try:
```
SELECT category, MIN(item) AS item
FROM stuff
GROUP BY category
HAVING Count(Distinct item) = 1
``` |
3,681 | There is the concept of faith (śraddhā) in Buddhism. There is also the concept of faith found in Christianity. Both concepts have been translated into the English word faith but in what ways are the concepts different and also are there ways in with the concepts have similarities.
I'd find it particularly interesting if anyone knows the original roots of the word faith in Christianity (i.e. what was the original word in Greek or Hebrew) and how the translation compares to how śraddhā has been translated. Do the words have nuances that have been lost in the translation to the simple English word faith? | 2014/09/20 | [
"https://buddhism.stackexchange.com/questions/3681",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/157/"
] | There's [a Wikipedia article here](http://en.wikipedia.org/wiki/Faith_in_Christianity#New_Testament) about the word "faith" in Christianity; which begins,
>
> The word "faith", translated from the Greek πιστις (pi'stis), was primarily used in the New Testament with the Greek perfect tense and translates as a noun-verb hybrid; which is not adequately conveyed by the English noun.
>
>
>
An explanation of what the Greek perfect tense is [can be found here](http://www.ntgreek.org/learn_nt_greek/verbs1.htm#PERFECT):
>
> **Perfect Tense**
>
>
> The basic thought of the perfect tense is that the progress of an
> action has been completed and the results of the action are continuing
> on, in full effect. In other words, the progress of the action has
> reached its culmination and the finished results are now in existence.
> Unlike the English perfect, which indicates a completed past action,
> the Greek perfect tense indicates the continuation and present state
> of a completed past action.
>
>
> For example, Galatians 2:20 should be translated "I am in a present
> state of having been crucified with Christ," indicating that not only
> was I crucified with Christ in the past, but I am existing now in that
> present condition.
>
>
>
> >
> > "...having been rooted and grounded in love," Eph
> > 3:17
> >
> >
> >
>
>
>
Sentences which summarize it include,
>
> The pi'stis-group words in the New Testament can thus be interpreted as relating to ideas of faithfulness, fidelity, loyalty, commitment, trust, belief, and proof. The most appropriate interpretation and translation of pi'stis-group words in the New Testament is a matter of recent controversy, particularly over the meaning of pi'stis when it is directed towards Jesus.[4]
>
>
>
*Do the words have nuances that have been lost in the translation to the simple English word faith?*
Based on the Wikipedia article, perhaps it implies a personal connection, the "fidelity" of human relationships: "Jesus is/was my friend", and "do this is remembrance of me", that kind of thing.
I won't try to say what the same word was used to mean, in the Old Testament.
The use of the "perfect" tense ([meaning 'completed'](https://www.google.com/search?q=define%3Aperfect), not meaning 'without fault') is appropriate for referring to actions which have been completed (e.g. Jesus's life, death, and resurrection; a Christian's past baptism causing their present salvation; etc.): see also the notion of Christianity as "good news".
---
Per Wikipedia ([here](http://en.wikipedia.org/wiki/%C5%9Araddh%C4%81) and [here](http://en.wikipedia.org/wiki/Faith_in_Buddhism)), the Buddhist word "faith" also (i.e. perhaps similarly to the Christian word) includes the meanings of "trust" and "loyalty".
The descriptions given in [this article](http://en.wikipedia.org/wiki/Faith) seem to me to imply that the words have the following in common:
* Hear that something exists (dharma or law)
* Trust in the spiritual attainment of the teacher (Buddha or Christ)
* Practice/study/discovery of what the message really means
* Happiness, confidence, satisfaction if/when/because one is able to align one's life with one's faith | The role of faith is as follows:
* Other teachings: unquestioned belief in a dogma or central teaching, which cannot be verified through practice, which cannot be questioned or scrutinised, and which generally is a promise after death that cannot be realized within this lifetime and experienced here and now. Also here is an entity which saves a person or decided the fate of an individual or a law giver. Also there is a sect which is rewarded concept based on acceptance, faith, etc.
* Buddhism: faith is some belief in the practice to seriously try it out to start with. Each step in the Dhamma when you get close to the final goal thus your faith is strengthened when you see / verify / understand the teaching at the experiential level here and now. The teaching is not a promise after death which is not verifiable, hence you can gain and strengthen your faith when you see things as they are, though practice and direct experience. If needed the Dhamma is open for scrutiny as it can stand such scrutiny thus a source of inspiration and faith after such exercise (this is how many of the early western Buddhists did become Buddhists). In Buddhism there is not law give. Regardless of what you call your self (Christian, Muslim, Hindu, etc.), if you practice according to the teachings you will get the same benefits (Also see: <http://en.wikipedia.org/wiki/Dharma_(Buddhism)#Qualities_of_Buddha_Dharma>)
To elaborate more on the Buddhist view on faith I give the following example. If you do not have faith in a doctor your will not got to him. If you do not have faith in his medicine you will not take it. Once you have faith in the doctor and medicine and you take the medicine and then you get better you know the prescription works and the doctor is indeed not a quaker. In this case Buddha is the doctor and the prescription is the Dhamma. Buddhism is based on psychology and Buddha was one of the greatest psychologist. In this regard you can draw a week parallel on the role of faith in compassion as faith you will have in a psychologist or particular treatment and faith in a religion. As I said this is a week analogy as Buddhists you have to have lot of gratitude as if not for his discovery we will not have this treatment and if not for the monastic tradition that did not preserved this we will have not got it. According to the birth stories the search for the solution lasted unimaginable life times and lot of pain, hence much deeper gratitude is required towards the Buddha than a doctor who might cure you one. (See [Buddhism and Modern Psychology](https://www.coursera.org/course/psychbuddhism) and [Buddhist Meditation and the Modern World](https://www.coursera.org/course/meditation))
Also another analogy is teacher student relationship. If you do not trust your teacher you will not lean what he teachers and hence cannot benefit from what you have been taught. E.g. if some one is teaching you archery, and you do not think what is taught is indeed the best way to aim, or your teacher is good at it, you will not learn and also will not be skilled at it as you have not practiced as taught. Also again you need deeper gratitude towards the Buddha for his higher dedication for teaching and also the quality of the teaching. In comparison to Western Psychology, the Buddhist treatment is much superior in terms of the results and consistency.
The Pali word Sradha doesn't translate well into English as faith since when you say faith it can be a belief with no proof or warrent. Better term would be confidence. Buddhism is not faith based but confidence players a significant role. Good analogy would be a Buddhist science teacher teaching. If you follow the instructions in the experiment as it is you can get reproducible results regardless of whether the students call them selves Christian, Muslim, etc. but you have to have confidence in the teacher to the extent that he is knowledgeable and teaching you the right method. Lack of confidence mean that you will not learn properly and also follow the method properly. In case you follow the instructions accordingly you get the results and not doing so will not give you the results, but each and everyone who take the right steps will get results. Also you can compare this to baking a cake. More faithful you are to a great recipe, more better the outcome would be. (Keep in mind that the reproducibility is more like in a drug trial, or balance of probability, or statistical than that of a physics or chemistry experiment.)
Also there are 3 stages of wisdom which is linked to confidence:
* on hearing you feel the message sounds right
* on further thinking about what you heard you see it is logical
* when you practice and see for yourself your confidence becomes even stronger
I am answering this in a more generic fashion than targeted at a particular other faith by negation (taking the opposite meaning) of the 6 qualities of the Buddha Dhamma. So this is not targeted at any faith, but should be opposite of qualities of the Dhamma. Some faith based systems may not have or not have this at a varying degree. I just bundled this "other teachings", but some may have some of the characteristics the Dhamma. (See: <http://en.wikipedia.org/wiki/Dharma_(Buddhism)#Qualities_of_Buddha_Dharma>)
The 6 qualities of the Dhamma in detail (taken from **Wikipedia**):
>
> Svākkhāto (Sanskrit: Svākhyāta "well proclaimed" or "self-announced"). The Buddha's teaching **is not a speculative philosophy but an exposition of the Universal Law of Nature based on a causal analysis of natural phenomena**. **It is taught, therefore, as a science rather than a sectarian belief system**. Full comprehension (enlightenment) of the teaching may take varying lengths of time but Buddhists traditionally say that the course of study is 'excellent in the beginning (sīla – Sanskrit śīla – moral principles), excellent in the middle (samādhi – concentration) and excellent in the end' (paññā - Sanskrit prajñā . . . Wisdom).
>
>
> Sandiṭṭhiko (Sanskrit: Sāṃdṛṣṭika "able to be examined"). *The Dharma is open to scientific and other types of scrutiny and is **not based on faith**. It can be **tested by personal practice** and one who follows it will **see the result for oneself by means of one's own experience***. Sandiṭṭhiko comes from the word sandiṭṭhika which means visible in this world and is derived from the word sandiṭṭhi-. Since Dhamma is visible, it can be "seen": known and be experienced within one's life.
>
>
> Akāliko (Sanskrit: Akālika "timeless, immediate"). *The Dhamma is able to bestow timeless and **immediate results here and now***. **There is no need to wait for the future or a next existence**. The dhamma does not change over time and it is not relative to time.
> Ehipassiko (Sanskrit: Ehipaśyika "which you can come and see" — from the phrase ehi, paśya "come, see!"). The Dhamma invites all beings to put it to the test and come see for themselves.
>
>
> Opanayiko (Sanskrit: Avapraṇayika "**leading one close to**"). **Followed as a part of one's life the dhamma leads one to liberation**. In the "Vishuddhimagga" this is also referred to as "Upanayanam." Opanayiko means "to be brought inside oneself". This can be understood with an analogy as follows. If one says a ripe mango tastes delicious, and if several people listen and come to believe it, they would imagine the taste of the mango according to their previous experiences of other delicious mangoes. Yet, they will still not really know exactly how this mango tastes. Also, if there is a person who has never tasted a ripe mango before, that person has no way of knowing exactly for himself how it tastes. So, the only way to know the exact taste is to experience it. In the same way, dhamma is said to be Opanayiko which means that a person needs to experience it within to see exactly what it is.
>
>
> Paccattaṃ veditabbo viññūhi (Sanskrit: Pratyātmaṃ veditavyo vijñaiḥ "To be meant to perceive directly"). The Dhamma can be perfectly realized only by the noble disciples (Buddha) who have matured in supreme wisdom. **No one can "enlighten" another person**. **Each intelligent person has to attain and experience for themselves**. As an analogy, no one can simply make another know how to swim. Each person individually has to learn how to swim. In the same way, dhamma cannot be transferred or bestowed upon someone. Each one has to know for themselves.
>
>
>
*Sourced: <http://en.wikipedia.org/wiki/Dharma_(Buddhism)>* |
30,474,008 | I am using cells with two heights based on some status.
When start is **StatusAwarded** it shows full cell else it will show a part of it.
Here is the code to achieve this.
```
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
SomeClass *someClass = dataArray[indexPath.row];
if (someClass.status == StatusAwarded) {
return 252.0f;
}
return 110.0f;
}
```
It works all fine but when it is in edit mode, it has this issue as shown below.
I am having effect like this while editing (Deleting).
 
**Question:**
Why is this happening? How to fix this?
Note: `Clip Subviews` is set to `YES` | 2015/05/27 | [
"https://Stackoverflow.com/questions/30474008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2099097/"
] | I found a similar [question](https://stackoverflow.com/a/35580597/1334228). In which the solution is explained better by @augusto-goncalves. His solution works for me. It is similar to the solution of @victor-behar but more elaborated and clears confusion. | There's also a way to transpile scss in express using node sass middleware, for example <https://github.com/sass/node-sass-middleware>.
That way you can override bootstrap scss. You can do the same for JS with webpack: transpile client-side js and then include the bundle.js in your frontend. |
1,416,113 | Data I possess: Transaction Date (A:A), Customer Name (B:B), Sales Order Number (C:C), Product Name (D:D), Units (E:E), Revenue (F:F)
New order would be anything that the customer hasn't ordered in the past 6 months or ever.
A reorder would be if the customer had purchased that specific product in the past 6 months.
I can't wrap my head around how to put this logic into an excel formula. | 2019/03/21 | [
"https://superuser.com/questions/1416113",
"https://superuser.com",
"https://superuser.com/users/1010291/"
] | Perhaps I’m misunderstanding something, but this seems to be fairly simple.
My understanding of the question is that a row represents a reorder
if there is at least one row above the current one
that has the same Customer Name (Column `B`) as the current row,
the same Product Name (Column `D`), and a Transaction Date (Column `A`)
within the past six months of the current Transaction Date.
Columns `C`, `E` and `F` can be ignored.
I assume that the rows are sorted by Transaction Date
(although I guess I don’t need to make that assumption).
The Transaction Date criterion is the “hardest” (I use that term loosely).
A past date is within the past six months of `A2` if it is
```
> EDATE(A2,-6)
```
So, to count the rows through the current one
that satisfy the three criteria, we use
```
=COUNTIFS(A$2:A2, ">" & EDATE(A2,-6), B$2:B2, B2, D$2:D2, D2)
```
The `A$2:A2` notation is interesting.
It represents a range that starts in Row 2 and ends in the current row;
i.e., everything up through (and including) the current row.
This count will always be at least 1, because the current row counts.
If it’s greater than 1,
there was at least one previous row that also matched.
So the answer is to enter
```
=IF(COUNTIFS(A$2:A2, ">" & EDATE(A2,-6), B$2:B2, B2, D$2:D2, D2)<=1, "New Order", "Reorder")
```
into `H2` (or wherever you want it) and drag/fill down.
[](https://i.stack.imgur.com/noyhI.png)
---
If the rows might be out of order, we need to search the entire table
and test that the date is less than the current date:
```
=IF(COUNTIFS(A$2:A$99, ">" & EDATE(A2,-6), A$2:A$99, "<" & A2,
B$2:B$99, B2, D$2:D$99, D2)=0, "New Order", "Reorder")
```
where I’m using `99` to represent the last row of the data.
I changed the test from `<=1` to `=0`
because the `< A2` test eliminates the current row.
If your data might include multiple rows
with the same Customer Name and Product Name,
and the exact same Transaction Date,
please specify how they should be handled. | *My approach is bit different to solve the issue, since I've picked OP's thread,,*
1. **New order would be anything that the customer
hasn't ordered in the past 6 months or ever.**
2. **A reorder would be if the customer had
purchased that specific product in the past
6 months.**
---
[](https://i.stack.imgur.com/UZ9O0.png)
* An Array (CSE) Formula in Cell `H41`, finish
with **Ctrl+Shift+Enter**.
`{=IFERROR(LOOKUP(DATEDIF(IFERROR(INDEX($A$41:$A$47,MATCH(1,($B$41:$B$47=J41)*($D$41:$D$47=K41),0)),"No Match"),I41,"m"),{0,6,12},{"New Order","Order before 6 month","Order before 12 months"}),"Cust's. New Pro. Order")}`
---
**Situation 1:**
New Traction Date: `03/26/19`.
Customer Name: `Bob`.
Product's Name: `Cake`.
Order Sataus: `Order before 12 months`.
[](https://i.stack.imgur.com/zTszQ.png)
---
**Situation 2:**
New Traction Date: `03/26/19`.
Customer Name: `Bob`.
Product's Name: `Milk`.
Order Sataus: `New Order`.
[](https://i.stack.imgur.com/JGFL2.png)
**N.B.**
*Because difference between Old Transaction Date (`10/01/18`) and New Transaction Date (`03/26/19`) is less than 6 Months.*
---
**Situation 3:**
New Traction Date: `03/26/19`.
Customer Name: `Bob`.
Product's Name: `Wheat`.
Order Sataus: `Order before 6 months`.
[](https://i.stack.imgur.com/0ZQBx.png)
**Situation 4:**
New Traction Date: `03/26/19`.
Customer Name: `Bob`.
Product's Name: `Fruit`.
Order Sataus: `Cust's. New Pro.Order`.
[](https://i.stack.imgur.com/5XJ1p.png)
---
**Note:**
*If you enter new Customer's Name and either Old or New Product and Date you get `Cust's . New Pro. Order` as status.*
[](https://i.stack.imgur.com/FHcSD.png)
---
**Now let me explain how the Formula works.**
*Formula can be divide into two parts.*
`Part 1`
```
{=IFERROR(INDEX($A$41:$A$47,MATCH(1,($B$41:$B$47=J41)*($D$41:$D$47=K41),0)),"No Match")}
```
*Basically it's 2 Criteria Lookup which finds `Old Transaction Date` for `Customer & the Product`, and the Formula considers it as `Start Date` for `DATEDIF` formula is within `A41:A47`..*
`Part 2`
The original `DATEDIF` is,
```
{=LOOKUP(DATEDIF(A41:A47,I41,"m"),{0,6,12},{"New order","Order before 6 month","Order before 12 months"})}
```
*Where `A41:A47` is been replaced with the `Part 1` Formula as `Start Date` and the `End Date` is in cell `I41`.*
And both parts are nicely wrapped with `IFERROR`.
**N.B**
* You may adjust cell references as needed.
* Messages with the Formula alos can be altered
as your choice. |
17,760,311 | How to go about mimicking ::MessageBox() behavior in a custom popup(WS\_POPUP) window, where the popup window waits for user click on one of the buttons and return the result of the click ? like in a ::MessageBox() when you have MB\_YESNO in uType and handle to the owner window is supplied, it returns either ID\_YES or ID\_NO depending on which button was clicked.
In pure win32 api and c++. | 2013/07/20 | [
"https://Stackoverflow.com/questions/17760311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414923/"
] | DialogBox() is the core winapi function.
If you want to completely spin your own then you must:
1. iterate all top-level windows on the thread with EnumThreadWindows() and disable them with EnableWindow
2. run a message loop with GetMessage + DispatchMessage
3. add an exit condition to that loop, using a variable that represents the dialog return value
4. write message handlers for the buttons, they must set that variable
5. repeat step 1, re-enabling the windows
6. destroy the dialog window
7. return the variable value | When you handle button's `BN_CLICKED` notification, delivered to the owner window via `WM_COMMAND` message, a call of [`EndDialog(m_hWnd, IDYES)`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms645472%28v=vs.85%29.aspx) ends dialog box and supplies the API with a value (`IDYES`) to return to higher level caller.
Non-modal popup windows don't have returned codes (as opposed to modal dialogs and `MessageBox` modal dialog in particular), you close them with `WM_CLOSE` and you have to elaborate some way to obtain resulting codes/values from the window, if necessary. |
29,876,631 | I'm trying to simplify Parcelable code in Kotlin:
```
public class C() : Parcelable {
var b1: Boolean = false
var b2: Boolean = false
var b3: Boolean = false
var i1: Int = 0
var i2: Int = 0
val parcelBooleans = listOf(b1, b2, b3)
val parcelInts = listOf(i1, i2)
override fun writeToParcel(p: Parcel, flags: Int) {
parcelBooleans.forEach { p.writeBoolean(it) }
parcelInts.forEach { p.writeInt(it) }
}
private fun readFromParcel(p: Parcel) {
parcelBooleans.forEach{ it = p.readBoolean() } // does not compile as "it" is a "val"
}
// ... parcel creator bla bla
}
```
writeBoolean() and readBoolean() are extension functions.
Is there a way to have a forEach on list with an assignable "it"?
***Update:*** *in a comment to one of the answers the author clarifies this question as:*
>
> My point is that my list is not mutable, the elements inside are. Elements are my properties. But I'm realizing that maybe, listOf is making a value copy of my properties… so either I must rely on reflection, or wrapping basic type into an class to allow change to their value.
>
>
>
The intent is via the readonly list `parcelBooleans` which holds references to `b1`, `b2`, and `b3` modify the values of `b1`, `b2`, and `b3`; but not mutating the list itself. | 2015/04/26 | [
"https://Stackoverflow.com/questions/29876631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/600351/"
] | ***NOTE:*** *The question is not clear if the author is trying to mutate properties `b1`, `b2`, `b3` via a reference within the list. Or if he is trying to modify the contents of list `parcelBooleans` which is a copy of the values from the properties. If the first, see answer from @Bashor (or just make the values of the list something who's sub-contents is mutable), if second, this answer is correct.*
Given the extension functions defined in this other Stack Overflow question ["how do you modify the contents of a list while iterating"](https://stackoverflow.com/questions/34608551/in-kotlin-how-do-you-modify-the-contents-of-a-list-while-iterating) you can change your code to simply:
```
public class C() : Parcelable {
var b1: Boolean = false
var b2: Boolean = false
var b3: Boolean = false
var i1: Int = 0
var i2: Int = 0
// CHANGED: use mutable list, array, or primitive array
val parcelBooleans = arrayListOf(b1, b2, b3)
val parcelInts = listOf(i1, i2)
override fun writeToParcel(p: Parcel, flags: Int) {
parcelBooleans.forEach { p.writeBoolean(it) }
parcelInts.forEach { p.writeInt(it) }
}
private fun readFromParcel(p: Parcel) {
// CHANGED: using the extension function
parcelBooleans.mapInPlace { p.readBoolean() }
}
// ... parcel creator bla bla
}
``` | A way to do it is to map each value:
```
parcelBooleans = parcelBooleans.map{ p.readBoolean() }
```
You have to make `parcelBooleans` a mutable variable, though. |
936,241 | If I have code like this:
```
<script>
function determine()
{
// ????
}
</script>
<a href="blah1" onclick="determine()">blah1</a>
<a href="blah2" onclick="determine()">blah2</a>
```
Is there a way in `determine()` to see which link was clicked?
(Yes, I know, the easy and correct thing to do would be to pass `this` to `determine()`, but in this case that's not going to be easy to do because of legacy code issues.)
**EDIT:** I probably should have mentioned this at the beginning...our site is not currently using (and cannot use, for the time being) jQuery, so jQuery answers (while valuable in general for this type of question) won't actually help me. | 2009/06/01 | [
"https://Stackoverflow.com/questions/936241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/57120/"
] | You can with straight up JavaScript, but I prefer to use something like jQuery:
```
<a href="blah1">blah1</a>
<script type="text/javascript">
$('a[href=blah1]').click(function() {
var link = $(this); // here's your link.
return false; // acts like the link was not clicked. return true to carry out the click.
});
</script>
```
Assuming you are using the `$().click()` functionality, `$(this)` will give you the link. | Another solution:
Add an onclick handler to the document. When a user clicks the link, the click event will "bubble" up to the window, and you will have access to the event to determine which link was clicked.
This might be useful if you only want the code to run for those links that already have onclick="determine()" - you could set the determine() function to set a variable. Then when the user clicks the link, the determine() function runs to set the variable, and when the document click handler runs you could check for the variable - then you will know that the link had onclick="determine()".
Let me know if I can make this a little more complicated for you... :-) |
26,285,183 | I create a new activity (when the timer ended), but it didn't show, because my app was minimized. How can I fix it? | 2014/10/09 | [
"https://Stackoverflow.com/questions/26285183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4126554/"
] | in your onResume of the parent activity from where you are firing the intent check if timer has finished or not. if yes then fire the intent from onResume() itself.
In this was if the app was minimised and user enters the app again he will directly navigated to the fired intent activity . | When your activity is minimized then all the operations that you perform in code are not executed as the application goes to PAUSE state. Better you start an SERVICE when your timer count ends and from that particular SERVICE do what you want to do.
Advantage:
Service will never go to halt state when your application is minimized and will keep on performing it's operations in the background. |
56,347,818 | I am trying to split a string of nucleotides in a way that allows me to find the outlier in the center of the nucleotide sequence, and turn it into a triplet by adding "n" to fill in the gaps.
I have tried splitting by number of characters, but the problem is that it happens from left to right, and I have been trying to find a way to do it right to left. So what I have done is find the length of the sequence, which in this one example is 52. Then, I take that length number and divide it by 3, to find the number of potential triplets that there will be. Then, I divide by 2 to know (obviously rounding) how many groups of 3 there will be roughly on each side of the outlier. Ideally, I want one more triplet on the left hand side than on the right hand side. The outlier would remain in the middle (either as one nucleotide, or two). For example:
```
nucleobases <- 'TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC'
nucleolength <- nchar("TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC")
num1 <- round(nucleolength/6)*3
firstsplit <- gsub("(.{27})", "\\1 ", nucleobases) #This works for the first half
secondsplit <- gsub("(.{24})", "\\1 ", firstsplit, rev) #This works, but not in the ideal way that it is supposed to.
```
I do not have any trouble translating the sequences into amino acids, which is my end goal. What I want is to add "n" in the places where it belongs in the sequence (on the outlier) so the ends of the sequences become the correct amino acids. This is ultimately what I would like:
```
#original sequence: TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC
#split up in the correct places: TGTGCCAGCAGTTTAAGGTAGATAGCG G GATTCCTACAATGAGCAGTTCTTC
#"N" fills in the outlier: TGTGCCAGCAGTTTAAGGTAGATAGCG GNN GATTCCTACAATGAGCAGTTCTTC
#Gaps are then eliminated and sequence is translated: TGTGCCAGCAGTTTAAGGTAGATAGCGGNNGATTCCTACAATGAGCAGTTCTTC
#Translated sequence: CASSLR-IAXDSYNEQFF
```
If anyone has an idea of how to do this in an efficient way possible, it would be great to know! Also, something to keep in mind is that this is not the only sequence. There are other sequences with different lengths (47, 46, 35, etc.). To reiterate, the grouped sequence on the left should be longer than the right, with the outlier in the middle. Please keep in mind that the groups should be a multiple of 3 (since they are codons), all except for the outlier. Thank you!! | 2019/05/28 | [
"https://Stackoverflow.com/questions/56347818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10577019/"
] | Apparently the WebSocket functionality was added in FastAPI 0.24, which was just released. I was using an older version. | run `pip install websockets` and configure it as following:
```
from fastapi import FastAPI, WebSocket
@app.websocket("/ws")
async def send_data(websocket:WebSocket):
print('CONNECTING...')
await websocket.accept()
while True:
try:
await websocket.receive_text()
resp = {
"message":"message from websocket"
}
await websocket.send_json(resp)
except Exception as e:
print(e)
break
print("CONNECTION DEAD...")
``` |
6,476,736 | I have a big winform with 6 tabs on it, filled with controls. The first tab is the main tab, the other 5 tabs are part of the main tab. In database terms, the other 5 tabs have a reference to the main tab.
As you can imagine, my form is becoming very large and hard to maintain. So my question is, how do you deal with large UI's? How do you handle that? | 2011/06/25 | [
"https://Stackoverflow.com/questions/6476736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40676/"
] | Consider your aim before you start. You want to aim for [SOLID principles](http://en.wikipedia.org/wiki/Solid_%28object-oriented_design%29), in my opinion. This means, amongst other things, that a class/method should have a **single responsibility**. In your case, your form code is probably coordinating UI stuff *and* business rules/domain methods.
Breaking down into [usercontrols](http://msdn.microsoft.com/en-us/library/aa302342.aspx) is a good way to start. Perhaps in your case each tab would have only one usercontrol, for example. You can then keep the actual form code very simple, loading and populating usercontrols. You should have a Command Processor implementation that these usercontrols can publish/subscribe to, to enable inter-view conversations.
Also, research UI design patterns. [M-V-C](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) is very popular and well-established, though difficult to implement in stateful desktop-based apps. This has given rise to [M-V-P](http://en.wikipedia.org/wiki/Model-view-presenter)/[passive view](http://martinfowler.com/eaaDev/PassiveScreen.html) and [M-V-VM](http://en.wikipedia.org/wiki/Model_View_ViewModel) patterns. Personally I go for MVVM but you can end up building a lot of "framework code" when implementing in WinForms if you're not careful - keep it simple.
Also, start thinking in terms of "Tasks" or "Actions" therefore building a [task-based UI](http://en.wikipedia.org/wiki/Task-focused_interface) rather than having what amounts to a [create/read/update/delete (CRUD)](http://en.wikipedia.org/wiki/Create,_read,_update_and_delete) UI. Consider the object bound to the first tab to be an [aggregate root](https://stackoverflow.com/questions/1958621/whats-an-aggregate-root), and have buttons/toolbars/linklabels that users can click on to perform certain tasks. When they do so, they may be navigated to a totally different page that aggregates only the specific fields required to do that job, therefore removing the complexity.
Command Processor
-----------------
The Command Processor pattern is basically a synchronous [publisher/consumer pattern](http://en.wikipedia.org/wiki/Producer-consumer_problem) for user-initiated events. A basic (and fairly naive) example is included below.
Essentially what you're trying to achieve with this pattern is to move the actual *handling* of events from the form itself. The form might still deal with UI issues such as hiding/[dis/en]abling controls, animation, etc, but a clean separation of concerns for the real business logic is what you're aiming for. If you have a [rich domain model](http://martinfowler.com/eaaCatalog/domainModel.html), the "command handlers" will essentially coordinate calls to methods on the domain model. The command processor itself gives you a useful place to wrap handler methods in transactions or provide [AOP](http://blogs.msdn.com/b/ericgu/archive/2004/06/29/169394.aspx)-style stuff like auditing and logging, too.
```
public class UserForm : Form
{
private ICommandProcessor _commandProcessor;
public UserForm()
{
// Poor-man's IoC, try to avoid this by using an IoC container
_commandProcessor = new CommandProcessor();
}
private void saveUserButton_Click(object sender, EventArgs e)
{
_commandProcessor.Process(new SaveUserCommand(GetUserFromFormFields()));
}
}
public class CommandProcessor : ICommandProcessor
{
public void Process(object command)
{
ICommandHandler[] handlers = FindHandlers(command);
foreach (ICommandHandler handler in handlers)
{
handler.Handle(command);
}
}
}
``` | I would suggest you to read about the CAB ( Composite UI Application Block ) from Microsoft practice and patterns, which features the following patterns : Command Pattern, Strategy Pattern, MVP Pattern ... etc.
[Microsoft Practice and patterns](http://msdn.microsoft.com/en-us/practices/bb190351)
[Composite UI Application Block](http://msdn.microsoft.com/en-us/library/aa480482.aspx?rssCatalog) |
106,947 | The WLAN module of my RPI 4 B+ disappeared. At first I thought that the hardware component had blown. How can I properly diagnose whether there is a hardware or software problem?
What I have done for diagnosting so far:
```
# uname -a
Linux xxx 4.19.88-1-ARCH #1 SMP PREEMPT Wed Dec 11 20:19:41 UTC 2019 armv7l GNU/Linux
# ip l
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT group default qlen 1000
link/ether dc:a6:32:xx:xx:xx brd ff:ff:ff:ff:ff:ff
# rfkill list
0: hci0: Bluetooth
Soft blocked: no
Hard blocked: no
# cat /boot/config.txt
[..]
gpu_mem=64
initramfs initramfs-linux.img followkernel
# dmesg | rg brcm
[ 5.053910] brcm-pcie fd500000.pcie: dmabounce: initialised - 32768 kB, threshold 0x00000000c0000000
[ 5.053953] brcm-pcie fd500000.pcie: could not get clock
[ 5.054007] brcm-pcie fd500000.pcie: host bridge /scb/pcie@7d500000 ranges:
[ 5.054049] brcm-pcie fd500000.pcie: MEM 0x600000000..0x603ffffff -> 0xf8000000
[ 5.094140] brcm-pcie fd500000.pcie: link up, 5.0 Gbps x1 (!SSC)
[ 5.094360] brcm-pcie fd500000.pcie: PCI host bridge to bus 0000:00
[ 5.334403] brcmstb_thermal fd5d2200.thermal: registered AVS TMON of-sensor driver
[ 10.018800] brcmfmac: brcmf_fw_alloc_request: using brcm/brcmfmac43455-sdio for chip BCM4345/6
[ 10.020754] brcmfmac mmc1:0001:1: Direct firmware load for brcm/brcmfmac43455-sdio.txt failed with error -2
[ 10.021792] usbcore: registered new interface driver brcmfmac
[ 11.027387] brcmfmac: brcmf_sdio_htclk: HT Avail timeout (1000000): clkctl 0x50
```
>
> Direct firmware load for brcm/brcmfmac43455-sdio.txt failed with error -2
>
>
>
From my point of view that clearly indicates a driver problem.
How should I proceed reasonably to fix this?
PS: The error probably occurred shortly after the encryption of the root partition.
**PPS: Text has been edited multiple times to comply to forum rules (make it a question) and to clean up.** | 2020/01/05 | [
"https://raspberrypi.stackexchange.com/questions/106947",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/-1/"
] | A little research reveals that the RPI4 is using the dual band wifi-chipset Cypress [CYW43455](https://github.com/sakaki-/genpi64-overlay/blob/master/README.md). I assume the chipset must be initialized in the early userland to work properly.
After encrypting the root partition the drivers can't be accessed from the early user space. To solve this you have to add the missing driver to the initramfs as files or preferably as binaries:
```
# nano /etc/mkinitcpio.conf
[..]
BINARIES=(/usr/lib/firmware/brcm/brcmfmac43455-sdio.bin /usr/lib/firmware/brcm/brcmfmac43455-sdio.clm_blob /usr/lib/firmware/brcm/brcmfmac43455-sdio.txt )
[..]
```
Afterwards refresh the initramfs and reboot:
```
# mkinitcpio -P
# reboot
```
The wlan0 module should reappear now:
```
# ip link show wlan0
3: wlan0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast state DOWN mode DEFAULT group default qlen 1000
link/ether dc:a6:32:xx:xx:xx brd ff:ff:ff:ff:ff:ff
# iw dev
phy#0
Interface wlan0
ifindex 3
wdev 0x1
addr dc:a6:32:xx:xx:xx
type managed
channel 34 (5170 MHz), width: 20 MHz, center1: 5170 MHz
txpower 31.00 dBm
```
In case you get
```
# iw dev wlan0 scan
[..] Interface does not support scanning [..]
```
or similar errors you probably [forgot](https://wiki.archlinux.org/index.php/Network_configuration/Wireless#Discover_access_points) to include the corrosponding .txt and .clm\_blob. | I can confirm that the missing .txt file needs to be included in the initramfs image. You can confirm this by reloading the driver once the system has fully booted and all the firmware files are available:
```
# rmmod brcmfmac
# modprobe brcmfmac
```
This got the `wlan0` device appearing for me, and `dmesg` reported the firmware having loaded correctly.
But of course it will break again on the next boot - this is only a temporary solution to confirm that all the correct firmware files are available on the system. The permanent solution (if this temporary fix works for you) is to try to get the extra files into the initramfs image.
(If the above workaround does nothing for you, then your problem is not one of the initramfs image missing some files.) |
228,229 | Is it possible to divide a matrix by another? If yes, What will be the result of $\dfrac AB$ if
$$
A = \begin{pmatrix}
a & b \\
c & d \\
\end{pmatrix},
B = \begin{pmatrix}
w & x \\
y & z \\
\end{pmatrix}?
$$ | 2012/11/03 | [
"https://math.stackexchange.com/questions/228229",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/33634/"
] | There is a way to perform a sort of division , but I am not sure if it is the way you are looking for. For motivation, consider the ordinary real numbers $\mathbb{R}$. We have that for two real numbers, $x/y$ is really the same as multiplying $x$ and $y^{-1}=1/y$. We call $y^{-1}$ the inverse of y, and note that it has the property that $yy^{-1}=1$.
The same goes for different algebraic structures. That is, for two elements $x,y$ in this algebraic structure we define $x/y$ as $xy^{-1}$ (under some operation). Most notably, we have a notion of division in any division ring (hence the name!) . It turns out that if you consider invertible $n \times n$ matrices with addition and ordinary matrix multiplication, there is a sensible way to define division since every invertible matrix has well, an inverse. So just to help you grip what an inverse is, say that you have a 2x2 matrix $$A= \begin{bmatrix} a & b \\ c & d \end{bmatrix}.$$
The inverse of A is then given by
$$A^{-1} = \dfrac{1}{(ad-bc)} \begin{bmatrix} d & -b \\ -c & a \end{bmatrix}$$
and you should check that $AA^{-1}=E$, the identity matrix. Now, for two matrices $B$ and $A$, $B/A = BA^{-1}$. | There are two issues: first, that matrices have divisors of zero; second, that matrix multiplication is in general not commutative.
To give meaning to $A/B$, you need to give meaning to $I/B$ (because then $A/B=A(I/B)$. Now, no one ever writes $I/B$, people actually write $B^{-1}$. Anyway, what is $B^{-1}$? It should be a matrix such that multiplied by $B$ gives you the identity. Now, there exist nonzero matrices $C$, $B$ with $BC=0$. If $B$ had an inverse $B^{-1}$, we would have
$$
0=B^{-1}0=B^{-1}BC=C,
$$
a contradiction. So such a matrix $B$ cannot have an inverse, i.e. "$I/B$" does not make sense.
The invertible matrices are exactly those with nonzero determinant. So, if $\det B\ne0$, then $AB^{-1}$ does make sense.
In you case, that would be the condition $wz-yx\ne0$. In that case,
$$
\begin{bmatrix}w&x\\ y&z\end{bmatrix}^{-1}=\frac1{wz-yx}\begin{bmatrix}z&-x\\ -y&w\end{bmatrix}
$$
The second issue is a non-issue, because it can be proven that, for matrices, if $B^{-1}A=I$, then $AB^{-1}=I$. |
47,657,851 | I am trying to make my code better, as every beginner I have problem to make it more "systematic", I would like your advice on how to do it.
I open few workbook, so now my macro looks like this.
```
Sub OpenWorkbooks()
workbooks.Open Filename :="C/.../file1.xlsx"
workbooks.Open Filename :="C/.../file2.xlsx"
workbooks.Open Filename :="C/.../file3.xlsx"
.
.
End sub
```
Its quite ugly, I would like to have each path in a cell. Let say from A1 to A3 and to loop this cell to open the workbooks. Any idea how I could do this?
In an other part of my code, nicely found on the web, I have the same problem. I would like to be able to enter my paths somewhere in my spreadsheet and then to loop it from there instead of entering manually one by one...
This is the second part of the code, quite clueless how I should do this...
```
Sub GetNumber()
Dim wWbPath As String, WbName As String
Dim WsName As String, CellRef As String
Dim Ret As String
Workbooks("file1").Close SaveChanges:=True
wbPath = "C:/etc...."
WbName = "file1.xlsx"
WsName = "Sheet1"
CellRef = "AD30"
arg = "'" & wbPath & "[" & wbName & "]" & _
wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1)
Worksheets("Sheet1").Range("A1") = ExecuteExcel4Macro(arg)
'Then I need to do all again for the second workbook etc....
End sub
```
Any idea is welcome,
Thank you! | 2017/12/05 | [
"https://Stackoverflow.com/questions/47657851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6457870/"
] | To answer the first part of your question:
```
Sub OpenWorkbooks()
For i = 1 to 3 ' Loop 3 times
Workbooks.Open Filename:=Sheet1.cells(i,1).value
'Cells refers to Row and column, so i will iterate three times while keeping the column the same.
Next i
End sub
```
If you don't know how many loops you will want to make, you could use the following to check the Last Row with data and loop until you reach it:
```
Sub OpenWorkbooks()
LastRow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 to LastRow ' Loop as many times until the last row with data
Workbooks.Open Filename:=Sheet1.cells(i,1).value
'Cells refers to Row and column, so i will iterate three times while keeping the column the same.
Next i
End sub
```
For the second part of your code you could do something like:
```
Sub GetNumber()
Dim wWbPath As String, WbName As String
Dim WsName As String, CellRef As String
Dim Ret As String
For i = 1 to 5 'Change this to however many files you will be using
FileName = Sheet1.cells(i,1).value
Workbooks(FileName).Close SaveChanges:=True
wbPath = "C:/etc...."
WbName = FileName & ".xlsx"
WsName = "Sheet1"
CellRef = "AD30"
arg = "'" & wbPath & "[" & wbName & "]" & _
wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1)
Worksheets("Sheet1").Range("A" & i) = ExecuteExcel4Macro(arg)
'Then I need to do all again for the second workbook etc....
Next i
End sub
``` | I had to figure out how do something similar recently. Try this ...
```
Dim i As Long
Dim SelectedFiles As Variant
SelectedFiles = Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx", _
Title:="Select files", MultiSelect:=True)
If IsArray(SelectedFiles) Then
For i = LBound(SelectedFiles) To UBound(SelectedFiles)
Set wbkToOpen = Workbooks.Open(Filename:=SelectedFiles(i), corruptload:=xlRepairFile)
Debug.Print wbkToOpen.Name
Debug.Print SelectedFiles(i)
wbkToOpen.Close savechanges:=False
Next
End If
``` |
60,727,208 | I was trying to install one of my go files. But I bumped into this error
```
C:\mygoproject>go install kafkapublisher.go
\#command-line-arguments
.\kafkapublisher.go:8:65: undefined: kafka.Message
.\kafkapublisher.go:10:19: undefined: kafka.NewProducer
.\kafkapublisher.go:10:38: undefined: kafka.ConfigMap
.\kafkapublisher.go:17:31: undefined: kafka.Event
.\kafkapublisher.go:19:26: undefined: kafka.Message
```
On my kafkapublisher.go file, I already imported the kafka dependency:
```
import (
"github.com/confluentinc/confluent-kafka-go/kafka"
"log"
)
```
even on my `go.mod` file
```
module mymodule
go 1.12
require (
github.com/aws/aws-lambda-go v1.15.0
github.com/confluentinc/confluent-kafka-go v1.3.0
)
```
I followed this documentation: <https://docs.confluent.io/current/clients/go.html>
[screenshot](https://i.stack.imgur.com/2SXEP.png) | 2020/03/17 | [
"https://Stackoverflow.com/questions/60727208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12816111/"
] | I already figured out this one. I installed Confluent's Kafka Go Client.
Instructions are here: <https://docs.confluent.io/current/clients/go.html#>
The library is not supported on windows though, so I had to use virtual machine (Oracle VM Box) to build and run my code.
I also needed to compile and install librdkafka before installing the Confluent's GO Kafka Client: <https://github.com/confluentinc/confluent-kafka-go/blame/master/README.md#L133>
Thanks. | CGO\_ENABLED=1 go build -ldflags"$(shell ./build/scripts/go-build-ldflags.sh $(MODULE\_ROOT)/ldflags)" -o bin/XXX/main.go
tips:
test in mac & linux os ,as for reason,i think it depends on some C language library |
42,646,168 | This question **is not** a copy of another: I have an issue that I don't find somewhere else.
I want to convert a date as `String` to the `Date` format. This `String` date is supposed to be the same format as `Date` because I used to upload it as String in a database. Here is what the `String` date looks like:
"2017-03-10 22:16:00 +0000";
I'm trying to convert it like that:
```
let df: DateFormatter = DateFormatter()
df.dateFormat = "yyyy-MM-dd hh:mm:ss Z"
print(beginDateString) // "2017-03-10 22:16:00 +0000"
let beginDate = df.date(from: beginDateString)
print(beginDate) // App crashs here because of nil value.
```
The issue is that it gives me a nil value for the variable `beginDate`.
I also tried with other `dateFormat` like this one: `"yyyy-MM-dd hh:mm:ss"` but it still doesn't work. | 2017/03/07 | [
"https://Stackoverflow.com/questions/42646168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6855056/"
] | Use `yyyy-MM-dd HH:mm:ss Z` not `yyyy-MM-dd hh:mm:ss Z`.
Because `hh` for ***hour in am/pm (1~12).***
You also can do with: `yyyy-MM-dd HH:mm:ss xxxx` or `yyyy-MM-dd HH:mm:ss XXXX`, etc.
[Read more](http://userguide.icu-project.org/formatparse/datetime) | Try this...
```
let beginDateString: String = "2017-03-10 22:16:00 +0000"
let df: DateFormatter = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
if let beginDate = df.date(from: beginDateString)
{
print(beginDate)
}
```
And as @javimuu said you have to change your template. |
334,059 | This is my first time using LaTeX and I am running into the following issue:
I am trying to denote a set of functions `x_t` which belong to `K` but for some reason the entire sentence gets italicized. I have attached screenshots of my code as well as the compiled result. Can anyone help me fix this? Cheers
[](https://i.stack.imgur.com/9t4FM.png)
[](https://i.stack.imgur.com/YPSDW.png) | 2016/10/14 | [
"https://tex.stackexchange.com/questions/334059",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/116354/"
] | That code is surely giving you errors when you compile, which will be telling you at least something about the problem. TeX will complain about missing `$` signs and add them in, but it can only guess where to put them.
You want everything from `f_{t}` to `\mathbb{R}`between one set of `$ ... $` and then from `x_{t}` to the end between another set. `f_{t} :` etc. is maths and you have it set as text. Similarly, `\mapsto` etc.
```
$f_{t} \colon \mathcal{K} \mapsto \mathbb{R}$
...
$x_{t} \in \mathcal{K}$
```
**EDIT** Use `\colon` as suggested by Mico. | `<rant>`
As a regular user of Mathematics.SE, I'm really impressed about the poor quality of TeX/LaTeX input. I acknowledge that some compromise with the limited possibilities offered by MathJax is necessary, but when I see
```
$\rm\ (p-1)!\ mod\ p\:$
```
written by a high rep user, my heart bleeds. Apart from the personal choice of using upright letters everywhere, typing `\mod{p}` shouldn't be too difficult.
One of the most common errors, that I also find in students' typescripts, is believing that `$...$` is just a way to enable special characters. It is not.
Everything which is math *must* be typed in as math, even if it is a standalone variable. In MathJax and, *a fortiori*, in LaTeX.
`</rant>`
So
```
We model our decision set, $\mathcal{K}$, as a convex set
in Euclidean space. Furthermore, we define our convex loss
function as $f_{t}\colon \mathcal{K} \rightarrow \mathbb{R}$.
At any finite time $t$, we denote our player's decision
as $x_{t} \in \mathcal{K}$.
```
Style manuals say the colon should not be used after "as". Also `\mapsto` is the wrong symbol for functions, it is used to denote a function's action on elements. Also no space should ever precede a comma. |
19,634,454 | I am trying get **confirmation** message **while click** on **delete** button in **GridView**. If I **conform** only the row will be delete in **GridView**.
\***.ASPX**
```
<Columns>
<asp:CommandField ButtonType="Button" ShowDeleteButton="true" />
</Columns>
```
\***.ASPX.CS**
```
protected void grdPersTable_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button buttonCommandField = e.Row.Cells[0].Controls[0] as Button;
buttonCommandField.Attributes["onClick"] =
string.Format("return confirm('Are you want delete ')");
}
}
protected void grdPersTable_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lbl0 = (Label)grdPersTable.Rows[e.RowIndex].FindControl("lblId");
txtId.Text = lbl0.Text;
obj.DeleteV(Convert.ToInt32(txtId.Text));
grdPersTable.DataSource = obj.GetTableValues();
grdPersTable.DataBind();
lblMessage.Text = "Deleted successfully !";
}
``` | 2013/10/28 | [
"https://Stackoverflow.com/questions/19634454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2590999/"
] | Change the rowdatabound event as below.
```
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
((Button)e.Row.Cells[0].Controls[0]).OnClientClick = "return confirm('Are you sure you want to delete?');";
}
}
``` | ```
<asp:TemplateField HeaderText="DELETE" ShowHeader="False">
<ItemTemplate>
<span onclick="return confirm('Are you sure to Delete?')">
<asp:Button ID="Button1" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
``` |
34,503,445 | ```
OS: Ubuntu 14.04
```
I created a test file called test and in it I have:
```
#!/bin/bash
NEW_VALUE = "/home/"
echo $NEW_VALUE
chmod +x test
./test
```
Produces the following:
```
./test: line 2: NEW_VALUE: command not found
```
Any ideas why this is not working? | 2015/12/29 | [
"https://Stackoverflow.com/questions/34503445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016958/"
] | In Bash you can't have any space around the `=` sign when assigning a variable.
Any space will end the assignment, even after the `=`, e.g.:
```
test_var=this is bad
#=> is: command not found
```
[@CharlesDuffy's comment explaining why this happens](https://stackoverflow.com/questions/34503445/assigning-value-not-working-in-a-shell/34503472?noredirect=1#comment56749781_34503472)
Check this link for more information on variable assignment in bash: <http://wiki.bash-hackers.org/scripting/newbie_traps#setting_variables> | Remove the white space while assigning then it'll work fine. just like:
```
#!/bin/bash
NEW_VALUE="/home/"
echo $NEW_VALUE
``` |
23,239,357 | Android activities A which is a list activity , B is a detail information about list item
A is calling B and send data Id and Category
```
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String newsid = ((TextView) view.findViewById(R.id.idTV))
.getText().toString();
Bundle bndl=new Bundle();
bndl.putString("id", newsid);
bndl.putString("cat", "sport");
bndl.putString("prev", "SPORTPANEL");
Intent in = new Intent("com.contact.lebadagency.SINGLECONTACTACTIVITY");
//in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//in.putExtra("id", newsid);
//in.putExtra("cat", "sport");
in.putExtras(bndl);
startActivity(in);
}
});
```
and the second Activity B :
```
Intent in=new Intent();
in=getIntent();
Bundle bundle = this.getIntent().getExtras();
String news = bundle.getString("id").toString();
String cat = bundle.getString("cat").toString();
```
When i install and run the application i click on any item on A activity and the correct data shown , the problem is that first selected data is stuck in Activity B , Stuck forever on the Activity B, i click on other items in list A and the old (first selected item) is stuck.
I hope i describe my problem well, any help ? | 2014/04/23 | [
"https://Stackoverflow.com/questions/23239357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3450082/"
] | Apart from that you forgot to specify class name in the definition of member function getState (there must be
```
int Node::getState(void)
{
//return 0;
return state;
}
```
) your code is invalid. First of all the class has no constructor with two parameters. SO the compiler shall issue an error for statements like this
```
Node* b=new Node(INPUT, "B");
```
Also you are trying to use the subscript operator for empty vector inputs (inputs[j]->setState(rand()%2); )
```
vector<Node*> inputs;
vector<Node*> outputs;
for(int i=0;i<5;i++) {
for(unsigned int j=0;j<inputs.size();j++) {
inputs[j]->setState(rand()%2);
cout << inputs[j]->getState(); // THIS LINE IS GIVING THE ERROR
}
}
```
That is the inner loop will be never executed. | Just indicate which class `int getState(void)` belongs to, with `int Node::getState(){return state;}` |
25,153,523 | i have gridview and i used stored procedure in backend . The issue is i have not used any textbox or label only gridview.
When i run my code, It shows a compilation error that spproduct1 expects parameter @id which is expected not supplied.
Can you please fix the error
```
public partial class WebForm1 : System.Web.UI.Page
{
string _strsql = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
string cs = ("Data Source=172.16.6.173;Initial Catalog=servion_hari;User ID=sa;Password=Servion@123");
_strsql = "select * from tblproduct where id=@id and Name=@Name and Description=@Description";
SqlConnection con = new SqlConnection(cs);
con.Open();
SqlDataAdapter da = new SqlDataAdapter("spgetproducts1", con);
SqlCommand cmd = new SqlCommand();
SqlParameter id = new SqlParameter("@id", SqlDbType.Int.ToString());
id.Value = GridView1.ToString();
da.SelectCommand.CommandType = CommandType.StoredProcedure;
con.Close();
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
``` | 2014/08/06 | [
"https://Stackoverflow.com/questions/25153523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3904158/"
] | If you want to add a value to a parameter defined in your query you can use the following:
```
cmd.Parameters.AddWithValue("@id", GridView1.ToString());
```
for a better implementation:
1. try to put all database related functions in a separate file and call them in your form.
2. define an stored procedure over your database and call it via C# code. this way of using stored procedure is poor
**Edited**
step1:
declare your stored procedure on your database like this:
```
CREATE PROCEDURE [dbo].[GET_PRODUCTS_SP]
/*Type of this variables should be their column types*/
@id int,
@name varchar(MAX),
@description varchar(MAX)
AS
BEGIN
SELECT * FROM [dbo].[tblproduct]
WHERE id=@id AND
Name=@name AND
Description=@description
END
```
step 2: call the stored procedure like this:
```
DataTable dt = new DataTable();
String conStr = "Data Source=172.16.6.173;Initial Catalog=servion_hari;User ID=sa;Password=Servion@123";
SqlConnection con = new SqlConnection(conStr);
SqlCommand com = new SqlCommand("GET_PRODUCTS_SP", con);
com.Parameters.AddWithValue("@id", yourIdValue);
com.Parameters.AddWithValue("@name", yourNameValue);
com.Parameters.AddWithValue("@description", yourDescriptionValue);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
try
{
con.Open();
da.Fill(dt);
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
GridView1.DataSource = dt;
GridView1.DataBind();
```
<https://studio.youtube.com/video/Aqoq_5teKtY/edit?utm_campaign=upgrade&utm_medium=redirect&utm_source=%2Fmy_videos> | ```
protected void Button3_Click(object sender, EventArgs e)
{
viewrecord s = new viewrecord();
s.std_id = Convert.ToInt32(TextBox2.Text);
SqlConnection conn2 = new SqlConnection(connstring);
try
{
SqlDataAdapter da = new SqlDataAdapter("viewrecord", conn2);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.AddWithValue("@std_id", s.std_id);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataSourceID = "";
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Redirect("ErrorMsgBoxBack.aspx");
}
finally
{
conn2.Close();
}
```
} |
36,218,643 | I tried to create a repeat loop function based on logical case as follow:
```
n=5 # number of element in lambda
t=10 # limit state
lambda=c(runif(n,2,4)) #vector to be tested
tes=function(x)
{
if(x>=t) {a=0;b=0;c=0}
else
{
repeat
{
a=runif(1,0.5,0.8)
b=runif(1, 5, 8)
c=x+a+b
print(a)
print(b)
if (c>=t) {break}
}
}
return(list(a,b,c))
}
```
I need to save all of the repeat loop iterations output into an object in the workspace to be used afterwards. however my function only save the latest value of the iterations.
here's the example of iteration for `lambda[1]`:
The iteration:
```
[1] 0.6714837
[1] 5.840948
[1] 0.7914275
[1] 7.264076
```
The saved result in the list:
```
[[1]]
[[1]][[1]]
[1] 0.7914275
[[1]][[2]]
[1] 7.264076
[[1]][[3]]
[1] 11.03819
```
how to save each of the result per iterations in the output list?
I’ve looked through other thread, but I haven’t found a suitable solution for my case yet. Thank you. | 2016/03/25 | [
"https://Stackoverflow.com/questions/36218643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6092897/"
] | You can accumulate the results onto a data.frame.
I would also recommend you not assign identifiers like `c` and `t`, since those are built-in functions which can be masked by locals, especially if you're passing around functions as arguments, such as `do.call(c,...)`.
I also suggest that it's probably appropriate to pass the limit state variable as another argument to the function.
```
tes <- function(x,lim) {
res <- data.frame(a=double(),b=double(),c=double());
if (x >= lim) {
res[1L,] <- c(0,0,0);
} else {
i <- 1L;
repeat {
ta <- runif(1L,0.5,0.8);
tb <- runif(1L,5,8);
tc <- x+ta+tb;
res[i,] <- c(ta,tb,tc);
print(ta);
print(tb);
if (tc >= lim) break;
i <- i+1L;
};
};
return(res);
};
```
Demo:
```
set.seed(5L);
n <- 5L; ## number of elements in lambda
lambda <- runif(n,2,4); ## vector to be tested
lambda;
## [1] 2.400429 3.370437 3.833752 2.568799 2.209300
res <- lapply(lambda,tes,10);
## [1] 0.7103172
## [1] 6.58388
## [1] 0.7423806
## [1] 7.8695
## [1] 0.5331359
## [1] 5.819855
## [1] 0.647154
## [1] 5.955212
## [1] 0.6677518
## [1] 5.787779
## [1] 0.5605626
## [1] 6.162577
## [1] 0.7663609
## [1] 6.664768
## [1] 0.7526538
## [1] 7.670621
## [1] 0.7162103
## [1] 5.634021
## [1] 0.5677152
## [1] 5.419951
## [1] 0.6439742
## [1] 6.312236
## [1] 0.7897892
## [1] 5.425742
## [1] 0.7864937
## [1] 6.334192
## [1] 0.5178087
## [1] 5.825448
## [1] 0.5093445
## [1] 5.043447
## [1] 0.6461507
## [1] 6.785455
## [1] 0.6793559
## [1] 6.193042
## [1] 0.6190491
## [1] 7.448228
res;
## [[1]]
## a b c
## 1 0.7103172 6.58388 9.694626
## 2 0.7423806 7.86950 11.012310
##
## [[2]]
## a b c
## 1 0.5331359 5.819855 9.723428
## 2 0.6471540 5.955212 9.972803
## 3 0.6677518 5.787779 9.825968
## 4 0.5605626 6.162577 10.093577
##
## [[3]]
## a b c
## 1 0.7663609 6.664768 11.26488
##
## [[4]]
## a b c
## 1 0.7526538 7.670621 10.99207
##
## [[5]]
## a b c
## 1 0.7162103 5.634021 8.559531
## 2 0.5677152 5.419951 8.196967
## 3 0.6439742 6.312236 9.165510
## 4 0.7897892 5.425742 8.424831
## 5 0.7864937 6.334192 9.329986
## 6 0.5178087 5.825448 8.552557
## 7 0.5093445 5.043447 7.762092
## 8 0.6461507 6.785455 9.640906
## 9 0.6793559 6.193042 9.081698
## 10 0.6190491 7.448228 10.276578
``` | You can save the intermediate results in a list, then return it (`loop_results`). See below. I have also formatted a bit your code so that, intermediate results are printed in a more intelligible/compact way, and the returned list is named.
```
tes <- function(x) {
if(x>=t) {
a=0;b=0;c=0
} else {
loop_results <- list()
i=0
repeat
{
i <- i+1
a=runif(1,0.5,0.8)
b=runif(1, 5, 8)
c=x+a+b
cat("iteration ", i, "a: ", a, "b: ", b, "\n")
loop_results[[i]] <- list(a=a, b=b, c=c)
if (c>=t) {break}
}
}
return(list(a=a, b=b, c=c, loop_results=loop_results))
}
``` |
8,157,081 | I'm having trouble with loading textures regarding their resolution on openGL for Android. If the texture is 256x256 everything works perfectly, but if it's other resolution, the program throws this exception on start:
android.content.res.Resources$NotFoundException: Resource ID #0x........
I found a code on the internet that changes the density of the bitmap this way:
```
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDensity = 240;
```
and by doing this, I can load 512x512 textures. But I'm not able to load for example 128x128 bitmaps, because I don't know which density I have to use. I'm not sure either that this is the normal procedure to load textures, because I don't found many information on the internet.
Thank you for reading! | 2011/11/16 | [
"https://Stackoverflow.com/questions/8157081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1050323/"
] | You need `$id = isset( $_GET['id']) ? intval( $_GET['id']) : 0;` at the top of your download script. | ```
<?php
$id = $_GET['ID'];
if($id)
{
getting info from db
}
?>
``` |
353,130 | When talking about end-game builds, a lot of players commonly refer to their builds having "x amount of Shaper DPS". That said, I don't actually understand what Shaper DPS is.
I know there is tooltip DPS, which shows me how much average DPS I am dealing with a specific skill, but the game itself has no listed stat for Shaper DPS, nor can I understand why the Shaper is used to measure DPS.
What is the difference between Shaper DPS and tooltip DPS? | 2019/06/19 | [
"https://gaming.stackexchange.com/questions/353130",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/18916/"
] | >
> What is the difference between Shaper DPS and tooltip DPS?
>
>
>
[The Shaper](https://poedb.tw/us/mon.php?n=The+Shaper) has 40% elemental resistances, 25% chaos resistance, and 66% reduced curse effectiveness. These effects can significantly reduce the damage that many builds can deal against him, especially builds which rely on elemental damage and/or curses.
The same properties are present on many other endgame bosses, like [The Elder](https://poedb.tw/us/mon.php?n=The+Elder), [Shaper guardians](https://poedb.tw/us/mon.php?n=Guardian+of+the+Phoenix), [Elder guardians](https://poedb.tw/us/mon.php?n=The+Eradicator), and [Legion generals](https://poedb.tw/us/mon.php?n=Queen+Hyrri+Ngamaku), as well as in lesser forms on [Atziri](https://poedb.tw/us/mon.php?n=Atziri%2C+Queen+of+the+Vaal), [Delve bosses](https://poedb.tw/us/mon.php?n=Ahuatotli%2C+the+Blind), [Abyssal liches](https://poedb.tw/us/mon.php?n=Ulaman%2C+Sovereign+of+the+Well), [Incursion architects](https://poedb.tw/us/mon.php?n=Quipolatl%2C+Architect+of+the+Nexus), etc. As such, "Shaper DPS" is a useful proxy for a build's effectiveness against endgame content.
---
Additionally, "tooltip DPS" generally refers to the number displayed on the in-game tooltip. This number is calculated in a relatively simplistic fashion, by summing all types of damage dealt by a skill and multiplying by attack/cast speed; it does not take into account other effects which may boost a player's effective damage, like elemental penetration, debuffs placed on enemies, conditional bonuses, or damage-over-time effects you can cause such as ignite, bleed, or poison. (It is also entirely ineffective at calculating DPS for skills which deal damage indirectly, like minions, traps, or mines, or for skills which are triggered by Cast on Critical Hit or other trigger supports.)
"Shaper DPS" is generally calculated using the third-party [Path of Building](https://github.com/Openarl/PathOfBuilding) tool, which can take most of these effects into account. | The existing answers are fine but there's a fine distinction:
a. Tooltip dps - literally the in-game displayed tooltip, which is commonly a number made up by multiplying your skill's base dmg \* attacks/casts per second \* crit chance \* crit multiplier \* accuracy rolls (for attacks)
b. A skill's "real" dps - a computed estimate based on the skill's actual mechanics, ex. barrage fires several projectiles per attack. The tooltip only reflects the damage from a single projectile hitting, while depending on positioning, you could get several projectiles to hit a single target/boss. Practically all totem/trap/mine setups fall into this same example of vastly different tooltip and real dps.
On this standard of "real" dps, there's the side of both conditional buffs on you (flasks most commonly and power/frenzy/endurance charges) and debuffs on the enemy (curses, status ailments etc) and sometimes a combination of the two along with all the extra statuses and effects from unique and ascendancy interactions.
Shaper has just been the standard endgame boss for a while, since the era of Path of Building - PoB (a software build simulator and planning tool for PoE) which does a lot (but not even close to all) of these scenario settings and calculations for you.
Others have already mentioned about Boss/shaper chaos/elemental res and curse reduction etc. which lowers the effective dps of most builds.
Tl;DR; - with the advent of PoB allowing people to mock up and share builds pretty effectively, Shaper just became the most commonly used standard reference point to demonstrate a build's dps for the purpose of comparing two builds. It's complete BS to go on this alone btw... but it's a handy reference check when most of the time comparing builds is like comparing apples to oranges. |
37,634,486 | In one definition of my view I am doing this
```
return HttpResponseRedirect(reverse('home'),{"fail":"true"})
```
then the destination receiving definition in a view does this
```
def Validate(request):
rslt = request.GET.get("fail", "False") #--->fail is always false
....
....
```
In the above the variable fail is always `false` . Any suggestions on why I am always getting a false. Why is my new parameter not being passed ? | 2016/06/04 | [
"https://Stackoverflow.com/questions/37634486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1305891/"
] | The `args` and `kwargs` passed to the `HttpResponseRedirect` constructor
```
def __init__(self, redirect_to, *args, **kwargs):
...
```
are not being used to construct a `QueryDict` (get or post). You are initialising a response here, not a request. As doniyor has already stated you basically have to append the querystring manually to the path returned by `reverse()`:
```
return HttpResponseRedirect('{to}?{query}'.format(
to=reverse('home'),
query=urllib.urlencode({"fail":"true"})
))
```
This has nothing to do with django, but general http redirection. You can only redirect a request to a location (to which you can add a query string), but you cannot tamper with the request itself, like adding POST-data or setting headers. | You need give a second parameter at reverse function... as de arguments... this works well for me!!!
```
return reverse('home', args='true')
``` |
8,342,950 | From what I understand using `.stop()` will prevent the callback functions to fire, right?
Unfortunately, it seems that this does not work in my current script:
```
newSubMenu.stop().slideToggle(250, function() {
newSubMenu.css('visibility', 'visible').addClass('open');
});
```
The animation now stops when double clicking, but `newSubMenu` still gets the class `open` and I cant figure out why.
The goal I am trying to achieve, is to NOT apply the class `open` until the animation is complete. | 2011/12/01 | [
"https://Stackoverflow.com/questions/8342950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/668190/"
] | From the [documentation](http://api.jquery.com/stop/):
>
> When `.stop()` is called on an element, the currently-running animation (if any) is immediately stopped. … Callback functions are not called.
>
>
>
Callback functions *are* called if the third argument to `stop()` is `true`.
In the code you provide, though, the callback will run because you're stopping already running animations, not the `slideToggle()` animation which has yet to run when `stop()` is called.
Here is a [working example showing the callback being stopped](http://jsfiddle.net/Dg3yC/). | To see why this happens, you have to understand, what toggle does.
Everytime you click, the `slideToggle` gets itself the information to `slideDown` or `slideUp`.
The conclusion is: everytime the toggle is complete, your function will be called and your newSubMenu gets the `visibility:visible` *style*, plus the class `"open"` if it doesn't exist.
```
Click-> Stop all animations on element -> toggle slide -> call/excecute function
``` |
55,271,298 | I want to create a series of possible equations based on a general specification:
```
test = ["12", "34=", "56=", "78"]
```
Each string (e.g. "12") represents a possible character at that location, in this case '1' or '2'.)
So possible equations from test would be "13=7" or "1=68".
I know the examples I give are not balanced but that's because I'm deliberately giving a simplified short string.
(I also know that I could use 'sequence' to search all possibilities but I want to be more intelligent so I need a different approach explained below.)
What I want is to try fixing each of the equals in turn and then removing all other equals in the equation. So I want:
```
[["12","=","56","78"],["12","34","=","78”]]
```
I've written this nested list comprehension:
(it needs: {-# LANGUAGE ParallelListComp #-} )
```
fixEquals :: [String] -> [[String]]
fixEquals re
= [
[
if index == outerIndex then equals else remain
| equals <- map (filter (== '=')) re
| remain <- map (filter (/= '=')) re
| index <- [1..]
]
| outerIndex <- [1..length re]
]
```
This produces:
```
[["","34","56","78"],["12","=","56","78"],["12","34","=","78"],["12","34","56","”]]
```
but I want to filter out any with empty lists within them. i.e. in this case, the first and last.
I can do:
```
countOfEmpty :: (Eq a) => [[a]] -> Int
countOfEmpty = length . filter (== [])
fixEqualsFiltered :: [String] -> [[String]]
fixEqualsFiltered re = filter (\x -> countOfEmpty x == 0) (fixEquals re)
```
so that "fixEqualsFiltered test" gives:
```
[["12","=","56","78"],["12","34","=","78”]]
```
which is what I want but it doesn’t seem elegant.
I can’t help thinking there’s another way to filter these out.
After all, it’s whenever "equals" is used in the if statement and is empty that we want to drop the equals so it seems a waste to build the list (e.g. ["","34","56","78”] and then ditch it.)
Any thoughts appreciated. | 2019/03/20 | [
"https://Stackoverflow.com/questions/55271298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2335363/"
] | Let
```
xs = [["","34","56","78"],["12","=","56","78"],["12","34","=","78"],["12","34","56",""]]
```
in
```
filter (not . any null) xs
```
will give
```
[["12","=","56","78"],["12","34","=","78"]]
```
If you want list comprehension then do
```
[x | x <- xs, and [not $ null y | y <- x]]
``` | The easiest waty to achieve what you want is to create all the combinations and to filter the ones that have a meaning:
```
Prelude> test = ["12", "34=", "56=", "78"]
Prelude> sequence test
["1357","1358","1367","1368","13=7","13=8","1457","1458","1467","1468","14=7","14=8","1=57","1=58","1=67","1=68","1==7","1==8","2357","2358","2367","2368","23=7","23=8","2457","2458","2467","2468","24=7","24=8"
Prelude> filter ((1==).length.filter('='==)) $ sequence test
["13=7","13=8","14=7","14=8","1=57","1=58","1=67","1=68","23=7","23=8","24=7","24=8","2=57","2=58","2=67","2=68"]
```
You pointed the drawback: imagine we have the followig list of strings: `["=", "=", "0123456789", "0123456789"]`. We will generate 100 combinations and drop them all.
You can look at the combinations as a tree. For the `["12", "34"]`, you have:
```
/ \
1 2
/ \ / \
3 4 3 4
```
You can prune the tree: just ignore the subtrees when you have two `=` on the path.
Let's try to do it. First, a simple `combinations` function:
```
Prelude> :set +m
Prelude> let combinations :: [String] -> [String]
Prelude| combinations [] = [""]
Prelude| combinations (cs:ts) = [c:t | c<-cs, t<-combinations ts]
Prelude|
Prelude> combinations test
["1357","1358","1367","1368","13=7","13=8","1457","1458","1467","1468","14=7","14=8","1=57","1=58","1=67","1=68","1==7","1==8","2357","2358","2367","2368","23=7","23=8","2457","2458","2467","2468","24=7","24=8", ...]
```
Second, we need a variable to store the current number of `=` signs met:
* if we find a second `=` sign, just drop the subtree
* if we reach the end of a combination with no `=`, drop the combination
That is:
```
Prelude> let combinations' :: [String] -> Int -> [String]
Prelude| combinations' [] n= if n==1 then [""] else []
Prelude| combinations' (cs:ts) n = [c:t | c<-cs, let p = n+(fromEnum $ c=='='), p <= 1, t<-combinations' ts p]
Prelude|
Prelude> combinations' test 0
["13=7","13=8","14=7","14=8","1=57","1=58","1=67","1=68","23=7","23=8","24=7","24=8","2=57","2=58","2=67","2=68"]
```
* We use `p` as the new number of `=` sign on the path: if `p>1`, drop the subtree.
* If `n` is zero, we don't have any `=` sign in the path, drop the combination.
You may use the variable `n` to store more information, eg type of the last char (to avoid `+*` sequences). |
18,263,668 | I have a webpage which I want to display users who have that page opened. (I'm using node.js for server side)
**My current attempt:**
On server side, there's a counter that counts the amount of time he submits the GET request to that webpage. Hence if he opens that page more than once, `counter++`
Everytime the user leaves the webpage, it sends a websocket to the server using socket.io.
```
window.onbeforeunload = function() {
socket.emit('ClosePage');
}
```
Then on the server side, when it receives this socket, it decreases his counter by 1, a.k.a `counter--`
So using this logic, it's possible to detect when an user has the webpage opened and when he actually closes the webpage for real.
**HOWEVER**, the problem occurs when an user refreshes the page like crazy, the server will just adds up continuously the counter without decreasing it afterward, because the window has not unloaded yet (my guess).
Does anyone know how to fix stuffs like this? Or does anyone know what algorithm does most forums use when they display users or strangers who are reading a post?
Thanks a lot! | 2013/08/15 | [
"https://Stackoverflow.com/questions/18263668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2567834/"
] | I think the real way to do this would be to override the default `$interpolateProvider` to enable filters that return promises. That way, you could defer the rendering of certain filtered expressions until they are resolved.
Remember, though, that you cannot do this for chained filters trivially. You will probably be forced to rewrite `$parse` as well to enable support for chaining of promises.
I am faced with the very same problem at the moment, and as such, I might go ahead and just do it. If so, I will make sure to post a link to the answer on the github repository for my project (<http://github.com/agileapes/bootstrapui>).
**EDIT**
Another (mostly) easy way to do it is to pass an arbitrary argument to your filter that is updated via the HTTP call (or any other means):
```
.controller("MyController", function ($scope, $q, $timeout) {
$scope.result = null;
var deferred = $q.defer();
$timeout(function () {
$scope.result = [1, 2, 3, 4];
}, 2000);
});
```
here I have just updated the result via a timeout, but I don't have to do it that way. This is just for demonstration. You could update `$scope.result` in any way you choose.
Here is a sample filter, that will only include *even* numbers in the result:
```
.filter('even', function () {
return function (input) {
if (!angular.isArray(input)) {
return input;
}
var result = [];
angular.forEach(input, function (x) {
if (x % 2 == 0) {
result.push(x);
}
});
return result;
}
});
```
Now, in my view, I can use them together, this way:
```
<div ng-controller="MyController">
<ul ng-if="result.length"> <!-- It is nice to not pollute the DOM with empty lists -->
<li ng-repeat="item in result | even">{{item}}</li>
</ul>
</div>
```
After a couple of seconds or so, the list should be populated and the `ngRepeat` directive should receive the filtered result.
The trick, here, is that I have made a digest cycle happen for that particular `result` variable, which means that the filter that is being fed that variable will also be re-executed, which in turns means that everything will happen smoothly and as expected. | For anyone that is interested:
I solved this by simply catching the error thrown due to undefined object, and then I throw an error like `throw "Object not yet loaded. Trying again...";`
```
app.filter('translate', function() {
return function(input) {
try {
var index = input.toUpperCase();
if (app.translation[index]) {
if (input[0] === index[0])
return app.translation[index].capitalize();
return app.translation[index];
}
return input;
}
catch(err) {
throw "Translation not loaded yet, trying again...";
}
};
})
app.run(function($http) {
$http.get("translations/" + "NB_ENG" + ".json", {
cache: true
}).success(function(data) {
app.translation = data;
console.info("Translation loaded.");
}).error(function(q,w,e) {
app.translation = 1;
console.error("Failed getting translation: "+q + " | " + w + " | " + e + " | ");
});
});
```
Here I am awaiting the translation file, before being able to translate all the words. Angular runs the filter again and again until it gets a valid return. |
36,416,427 | Since a few days ago we've been getting an error response from Instagram API - it complains that we are using an invalid cursor 'min\_id' when accessing the Tags endpoint.
Thing is we don't use 'min\_id'. We use 'min\_tag\_id', which according to the documentation ([deprecated](https://www.instagram.com/developer/deprecated/endpoints/tags/#get_tags_media_recent) & [current](https://www.instagram.com/developer/endpoints/tags/#get_tags_media_recent)) is a valid cursor for this endpoint.
Doing some research I see that some people have been getting unexpected errors too (though different ones) around this week.
Example API request (plug an access token and paste in a browser to see for yourselves):
```
https://api.instagram.com/v1/tags/nofilter/media/recent?access_token=<ACCESS_TOKEN>&min_tag_id=AQCvuinNA31T_hoSa-RaCsQigBknfYaBv2_VcCn1kp4MX5whyr7v7AfpOzio8E4lcQ9TZIKZbN_ZAqEmuzmslq8qMmFTQF-1ocNntqDIjlN4va4GxocNeBxmo29nXEOjKIRVvce5PuvoXk3MY9nuNd6hbxFj7TW_FEWTWpdx9FNzEQ
```
And the response:
```
{"meta":{"error_type":"APIInvalidParametersError","code":400,"error_message":"min_id is not a valid cursor for this tag."}}
```
Any idea? | 2016/04/05 | [
"https://Stackoverflow.com/questions/36416427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124132/"
] | I got this response from Instagram when enquiring about invalid pagination tokens
>
> "Thanks for the report. We are aware of this issue and it happens when
> pictures are un-tagged (e.g. The comment with the tag is deleted). We
> are working on a fix but I don’t have an eta to share at the moment."
>
>
> | OK, so this is how I solved it - after waiting for a few days and seeing that nothing happens then I have deleted all min\_tag\_id values that I have in store. I also altered my app logic to deal with the situation (in my case when there's no min\_tag\_id then I load some historical posts, which I commented out for this fix).
I ran the import process and this repopulated the min\_tag\_id field. The new values have no problems. Either they fixed the issue or the un-tagging thing didn't happen to me again yet.
So far so good. Will post updates if any. |
98,453 | I have done a research paper with someone in industry, while doing a Phd. Is it important to include my supervisor name also in research paper. Will three names be a good thing or should i go with 2 names. | 2017/11/06 | [
"https://academia.stackexchange.com/questions/98453",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/82494/"
] | Authorship should be decided by who made intellectual contributions to the work, not by feelings that three is or is not a better number than two. | The [Vancouver Protocol](https://www.etikkom.no/en/ethical-guidelines-for-research/medical-and-health-research/the-vancouver-protocol/) is generally considered as the authoritative guideline for ethics in science publishing. Here it is stated:
"Authorship should be limited to those who have made a significant contribution to the concept, design, execution or interpretation of the research study. All those who have made significant contributions should be offered the opportunity to be listed as authors. Other individuals who have contributed to the study should be acknowledged, but not identified as authors. The sources of financial support for the project should be disclosed."
So:
If your supervisor did not make any contribution, she should not be included on the author list.
If your supervisor made a significant contribution, she should be offered authorship.
There is clearly a middle category here. In my field it is usually considered "nice" to offer a contributor who have made a contribution bordering significant, a chance to contribute enough to warrant authorship before the project is finished.
In any case, you should discuss the matter with your supervisor before publishing. You also ought to investigate whether your university has a course on publishing ethics, and consider taking it. |
276,197 | **Problem:**
Need to disable hibernation ( or enable Wake On Lan/ pattern ) for backup routine.
**Issue:**
Computer does not respond to WOL or any type of network requests. Also, hibernates regardless of NIC or power settings.
**Specs:**
Model: Dell Opti 780
NIC: 82567LM-3 Intel
**What I've Tried**
* Wake On LAN and Wake On Pattern enabled in NIC configuration.
* Low Power Mode disabled and Remote Wake Up enabled in BIOS
* High-Performance power scheme with everything set to "never".
* powercfg.exe /hibernate off. Also, -h off
* Sleep set to never.
There used to be a simple, easy to find checkmark in XP that said 'enable hibernation'.
One could uncheck it and be done with hibernation.
Apparently, someone in Redmond ( or maybe at Intel ) disliked the ease-of-use factor of this idea and decided to make it pure hell to disable hibernation or enable WOL in Win 7. | 2011/04/27 | [
"https://superuser.com/questions/276197",
"https://superuser.com",
"https://superuser.com/users/70813/"
] | You cannot remove/disable/or inhibit the functionality of links in NTFS. It's a feature of the base file-system. I am a bit curious as to why you're wanting to disable them. Symbolic & Hard links both have been used for decades in varying forms. As far as exploitability goes... if a virus/hacker/??? can get access to the file system with sufficient privileges to create/delete them... you have far more things to worry about. | You can't. Windows Vista and later actually actively use these filesystem features internally (an example is Vista/7's `%SystemDrive%\Documents and Settings` junction).
Symbolic links *already* require elevated (high-integrity) privileges for them to be created.
Think of these objects as "shortcuts". They allow Windows to store a single copy of some data on disk, and create pointers to it where needed. They cannot be "turned off", nor would it necessarily be a good idea if it was possible.
Windows XP was the last operating system to support operation without any of these features, because it can be installed on a FAT32 drive. FAT32 is much slower than NTFS, much less reliable in case of a system crash, and does not support security permissions.
NTFS added journaling (stability & reliability), filesystem-level permission support, and POSIX-style linking support (symlinks and hardlinks), which have existed in Unix/Linux for years. |
4,411,020 | I have this dll that I created a long time ago and use to connect to the db of a specific software that I develop for. I have had no issues for well over 4 years and countless applications with this dll.
Trying to deploy my latest creation, I get the following error:
```
System.IO.FileNotFoundException: Could not load file or assembly '***.dll' or one of its dependencies. The specified module could not be found.
```
So, for every dll I ever wrote, I always made a simple forms application to test that dll just by itself. Running that simple app yielded the same error. The dll doesn't load or use anything else than: System, System.Data, System.XML. So as far as depencies of it go, I don't see anything wrong.
By the way everything works on a dev station. The problem is limited to deployment stations. .Net and the necessary redistributables, since I do everything in C++, are deployed and working.
Running FUSLOGVW.exe showed everything as working fine.
Running depends.exe said: Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module.
I already tried rewriting the whole thing. Which yielded the same results.
Clues anyone?
**EDITS**
Here is the total error message:
```
See the end of this message for details on invoking \"
just-in-time (JIT) debugging instead of this dialog box.\"
************** Exception Text **************\"
System.IO.FileNotFoundException: Could not load file or assembly 'connectionTo.dll' or one of its dependencies. The specified module could not be found.\"
File name: 'connectionToJobboss32.dll'\"
at TESTConnection.Form1.button1_Click(Object sender, EventArgs e)\"
at System.Windows.Forms.Control.OnClick(EventArgs e)\"
at System.Windows.Forms.Button.OnClick(EventArgs e)\"
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)\"
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)\"
at System.Windows.Forms.Control.WndProc(Message& m)\"
at System.Windows.Forms.ButtonBase.WndProc(Message& m)\"
at System.Windows.Forms.Button.WndProc(Message& m)\"
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)\"
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)\"
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)\"
\"
************** Loaded Assemblies **************\"
mscorlib\"
Assembly Version: 4.0.0.0\"
Win32 Version: 4.0.30319.1 (RTMRel.030319-0100)\"
CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll\"
----------------------------------------\"
TESTConnection\"
Assembly Version: 1.0.3996.18980\"
Win32 Version: \"
CodeBase: file:///C:/Program%20Files%20(x86)/conn/TESTConnection.exe\"
----------------------------------------\"
System.Windows.Forms\"
Assembly Version: 4.0.0.0\"
Win32 Version: 4.0.30319.1 built by: RTMRel\"
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll\"
----------------------------------------\"
System.Drawing\"
Assembly Version: 4.0.0.0\"
Win32 Version: 4.0.30319.1 built by: RTMRel\"
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll\"
----------------------------------------\"
System\"
Assembly Version: 4.0.0.0\"
Win32 Version: 4.0.30319.1 built by: RTMRel\"
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll\"
----------------------------------------\"
```
There is no errors in the event viewer. | 2010/12/10 | [
"https://Stackoverflow.com/questions/4411020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4225/"
] | I had the same issue with a dll yesterday and all it referenced was System, System.Data, and System.Xml. Turns out the build configuration for the Platform type didn't line up. The dll was build for x86 and the program using it was "Any CPU" and since I am running a x64 machine, it ran the program as x64 and had issues with the x86 dll. I don't know if this is your issue or not, just thought that I would mention it as something else to check. | 1) Copy DLLs from "Externals\ffmpeg\bin" to your project's output directory (where executable stays);
2) Make sure your project is built for x86 target (runs in 32-bit mode).
[Follow this thread for more](http://www.aforgenet.com/forum/viewtopic.php?f=2&t=2230) |
164 | A recent example is 6 questions posted by [turkistany](https://cstheory.stackexchange.com/users/495/turkistany).
Right now when I look at
<https://cstheory.stackexchange.com/questions?sort=newest>
I see the following 11 questions posted by him among the newest questions:
1. [Best bounds for the longest path optimization problem in cubic Hamiltonian graph?](https://cstheory.stackexchange.com/questions/674/best-bounds-for-the-longest-path-optimization-problem-in-cubic-hamiltonian-graph)
2. [Is there a complexity theory analogue of Rice's theorem in computability theory?](https://cstheory.stackexchange.com/questions/668/is-there-a-complexity-theory-analogue-of-rices-theorem-in-computability-theory)
3. [Major conjectures used to prove complexity lower bounds?](https://cstheory.stackexchange.com/questions/653/what-are-the-major-conjectures-used-to-prove-complexity-lower-bounds)
4. [What is the complexity of computing a compatible 3-coloring of a complete graph?](https://cstheory.stackexchange.com/questions/652/what-is-the-complexity-of-computing-a-compatible-3-coloring-of-a-complete-graph)
5. [Sparsity of Horn satisfiability?](https://cstheory.stackexchange.com/questions/649/sparsity-of-horn-satisfiability)
6. [What is the most efficient algorithm to sample graphs with trivial automorphism groups ?](https://cstheory.stackexchange.com/questions/646/what-is-the-most-efficient-algorithm-to-sample-graphs-with-trivial-automorphism-g)
7. [What are the best known upper bounds and lower bounds for computing O(log n)-Clique?](https://cstheory.stackexchange.com/questions/609/what-are-the-best-known-upper-bounds-and-lower-bounds-for-computing-olog-n-cliq)
8. <https://cstheory.stackexchange.com/questions/596/which-algorithms-have-the-greatest-impact-on-our-civilization>
9. [What are the different notions of one-way functions?](https://cstheory.stackexchange.com/questions/558/what-are-the-different-notions-of-one-way-functions)
10. [PCP characterization of NP](https://cstheory.stackexchange.com/questions/522/what-is-the-best-pcp-characterization-of-p)
11. [Are there alternatives to using polynomials in defining the different notions of efficient computation?](https://cstheory.stackexchange.com/questions/515/are-there-alternatives-to-using-polynomials-in-defining-the-different-notions-of)
IMHO, this is not a nice practice, and I consider this as a possible sign that the author is not really interested in the questions (and maybe haven't spent much time trying to find out the answer by himself/herself).
Should we discourage this kind of behavior?
ps: I know that we are still in beta and this might be OK for this stage. | 2010/08/27 | [
"https://cstheory.meta.stackexchange.com/questions/164",
"https://cstheory.meta.stackexchange.com",
"https://cstheory.meta.stackexchange.com/users/186/"
] | I believe this behaviour is essentially destructive of the ethos of a high-level site for research-level questions. I think it should be discouraged, perhaps by posting the same questions in more fully fleshed out form (with a link back to the original question for attribution). This might be a better use of moderator attention than copy-editing poorly written one-liners.
Some of the value of a question is in sketching (or at least suggesting) the scenery within which the question lives. Even Randall Munroe will usually provide a few props to support the stick figures in [xkcd](http://xkcd.org/). | I think we need to have some policy on this type of thing. Or some way to strongly discourage badly phrased questions. For example, see this thread:
[Complexity of a variant of the Mandelbrot set decision problem?](https://cstheory.stackexchange.com/questions/778/complexity-of-a-variant-of-the-mandelbrot-set-decision-problem)
If you count all the comments, it took almost 30 comments to get a meaningful question out, and even then it seems like the OP keeps changing the question from iteration to iteration, much to the frustration of people posting answers. I'm not a subject area expert, but the frustration with this user's phrasing in this particular question is evident in that thread.
I've also noticed that this user's questions only start making sense after:
1. Several rounds of interrogation.
2. Suresh edits and fixes the question making it comprehensible (thanks for that, Suresh!)
Can we remedy this situation somehow? |
9,614,434 | my script, serializing a large array was working without problems on PHP 5.3.8 with APC. My server crashed I installed PHP 5.3.10 with APC and I get following error.
```
Allowed memory size of 31457280 bytes exhausted (tried to allocate 262263 bytes).
```
I increased memory\_limit to 256M in php.ini. On same script I verified with PhpInfo() and it is showing 256 MB. However I get the same error message. I disabled APC, and same error message again. | 2012/03/08 | [
"https://Stackoverflow.com/questions/9614434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490940/"
] | Well, its pretty clear that 31457280 bytes is 30 MB, therefore the limit has not been increased, so i'd check that again.
To make this answer more useful, you should probably be looking at serialising this large array in batches, as its never a good idea to hog so much memory at one time.
Also, you should probably look into [igbinary](https://github.com/phadej/igbinary) since the native way PHP stores and serialises array is *very* poor and memory inneficient | Call phpinfo() to check if the memory\_limit is actually changed. Maybe you simply edited the wrong php.ini file. |
58,551,754 | I have classes as below
```
public class ClassA
{
public int Id { get; set;}
}
public class ClassB : List<ClassA>
{
}
```
How do I convert List to ClassB?
I am doing simple casting as below but throws exception.
```
var list1= new List<ClassA>();
var list2= (ClassB)list1;
```
regards,
Alan | 2019/10/25 | [
"https://Stackoverflow.com/questions/58551754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/740902/"
] | expose a constructor to create instance of ClassB from List
```
public class ClassB : List<ClassA>
{
public ClassB(IList<ClassA> source) : base(source)
{
}
}
```
then use
```
var list1 = new List<ClassA>();
var list2 = new ClassB(list1);
```
you can also expose an explicit operator to make your casting possible:
```
public static explicit operator ClassB(List<ClassA> source)
{
return new ClassB(source);
}
```
but you can't create conversions from a base class, so you must use composition instead of inheritance, like for example:
```
public class ClassB : IEnumerable<ClassA>
{
private IList<ClassA> _source;
public ClassB(IList<ClassA> source)
{
_source = source;
}
public IEnumerator<ClassA> GetEnumerator() => _source.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => _source.GetEnumerator();
public static explicit operator ClassB(List<ClassA> source)
{
return new ClassB(source);
}
}
```
now it's possible to do:
```
var list1 = new List<ClassA>();
var list2 = (ClassB)list1;
```
by replacing `explicit` with `implicit` you can even skip the `ClassB` explicit casting but please try to not use conversion operators at all because too much magic is involved and unless you're the only developer in the project - it may confuse others | no,you can't.
parent class object cannot be converted to sub class
```
var list1= new List<ClassA>();
var list2= (ClassB)list1;
```
it can be simplified to below code
```
List<ClassA> list2 = new ClassB();
``` |
46,979,586 | I'm trying to set up related posts that show posts in the same category as the current. The way the clients blog is set up is that they all share the category "blog", the related posts will show the same thing for every post.
```
<?php $related = get_posts( array(
'category__in' => wp_get_post_categories($post->ID),
'numberposts' => 4,
'post__not_in' => array($post->ID)
) );
?>
```
I need to get posts that aren't the primary category (Blog). I can't do "`cateogry__not__in`" because then it would exclude everything. | 2017/10/27 | [
"https://Stackoverflow.com/questions/46979586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5636406/"
] | It worked for me after adding the **spring-boot-starter-aop dependency** like below:
```
compile ("org.springframework.boot:spring-boot-starter-aop:1.5.10.RELEASE")
``` | spring-retry uses spring aop, make sure you have aop added in your pom and try clean building the application.
for spring app :
```
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
```
for spring boot :
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>
``` |
49,360,887 | So, i'd like my user session to persist upon login/signup, which it does not.
The official documentation says to add this to start with :
```
app.use(express.session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());
```
which I did. Then it goes on to specify :
*In a typical web application, the credentials used to authenticate a user will only be transmitted during the login request. If authentication succeeds, a session will be established and maintained via a cookie set in the user's browser.
Each subsequent request will not contain credentials, but rather the unique cookie that identifies the session. In order to support login sessions, Passport will serialize and deserialize user instances to and from the session.*
```
passport.serializeUser(function(user, done) {
console.log("serialize user: ", user);
done(null, user[0]._id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
```
If I understand correctly, upon login, the user should see a new cookie being set.
My serialize and deserialize functions seem to work. The console will log the user details after I login a user. No error message in the console.
However, I don't see any cookie when I login a user.
Am I supposed to add an additional command manually ? something like this :
```
res.cookie('userid', user.id, { maxAge: 2592000000 });
```
I am using Redux, so am I supposed to deal with the persistent session via the reducer instead, with my authenticated (true or false) variable ?
I think I am a bit confused right now between what is supposed to be done on the server side and what is supposed to be done on the client side. | 2018/03/19 | [
"https://Stackoverflow.com/questions/49360887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7461599/"
] | ```
//npm modules
const express = require('express');
const uuid = require('uuid/v4')
const session = require('express-session')
const FileStore = require('session-file-store')(session);
const bodyParser = require('body-parser');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const users = [
{id: '2f24vvg', email: 'test@test.com', password: 'password'}
]
// configure passport.js to use the local strategy
passport.use(new LocalStrategy(
{ usernameField: 'email' },
(email, password, done) => {
console.log('Inside local strategy callback')
// here is where you make a call to the database
// to find the user based on their username or email address
// for now, we'll just pretend we found that it was users[0]
const user = users[0]
if(email === user.email && password === user.password) {
console.log('Local strategy returned true')
return done(null, user)
}
}
));
// tell passport how to serialize the user
passport.serializeUser((user, done) => {
console.log('Inside serializeUser callback. User id is save to the session file store here')
done(null, user.id);
});
// create the server
const app = express();
// add & configure middleware
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(session({
genid: (req) => {
console.log('Inside session middleware genid function')
console.log(`Request object sessionID from client: ${req.sessionID}`)
return uuid() // use UUIDs for session IDs
},
store: new FileStore(),
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}))
app.use(passport.initialize());
app.use(passport.session());
// create the homepage route at '/'
app.get('/', (req, res) => {
console.log('Inside the homepage callback')
console.log(req.sessionID)
res.send(`You got home page!\n`)
})
// create the login get and post routes
app.get('/login', (req, res) => {
console.log('Inside GET /login callback')
console.log(req.sessionID)
res.send(`You got the login page!\n`)
})
app.post('/login', (req, res, next) => {
console.log('Inside POST /login callback')
passport.authenticate('local', (err, user, info) => {
console.log('Inside passport.authenticate() callback');
console.log(`req.session.passport: ${JSON.stringify(req.session.passport)}`)
console.log(`req.user: ${JSON.stringify(req.user)}`)
req.login(user, (err) => {
console.log('Inside req.login() callback')
console.log(`req.session.passport: ${JSON.stringify(req.session.passport)}`)
console.log(`req.user: ${JSON.stringify(req.user)}`)
return res.send('You were authenticated & logged in!\n');
})
})(req, res, next);
})
// tell the server what port to listen on
app.listen(3000, () => {
console.log('Listening on localhost:3000')
})
```
try going through the link
<https://medium.com/@evangow/server-authentication-basics-express-sessions-passport-and-curl-359b7456003d> | 1
Check hostname.
In my case, cookie was set on `127.0.0.1`, not `localhost`.
2
Make sure `express session` is called before `passport session`. |
6,985,148 | For those who don't know what a 5-card Poker Straight is: <http://en.wikipedia.org/wiki/List_of_poker_hands#Straight>
I'm writing a small Poker simulator in Scala to help me learn the language, and I've created a *Hand* class with 5 ordered *Cards* in it. Each *Card* has a *Rank* and *Suit*, both defined as *Enumerations*. The *Hand* class has methods to evaluate the hand rank, and one of them checks whether the hand contains a Straight (we can ignore Straight Flushes for the moment). I know there are a few nice algorithms for determining a Straight, but I wanted to see whether I could design something with Scala's pattern matching, so I came up with the following:
```
def isStraight() = {
def matchesStraight(ranks: List[Rank.Value]): Boolean = ranks match {
case head :: Nil => true
case head :: tail if (Rank(head.id + 1) == tail.head) => matchesStraight(tail)
case _ => false
}
matchesStraight(cards.map(_.rank).toList)
}
```
That works fine and is fairly readable, but I was wondering if there is any way to get rid of that *if*. I'd imagine something like the following, though I can't get it to work:
```
private def isStraight() = {
def matchesStraight(ranks: List[Rank.Value]): Boolean = ranks match {
case head :: Nil => true
case head :: next(head.id + 1) :: tail => matchesStraight(next :: tail)
case _ => false
}
matchesStraight(cards.map(_.rank).toList)
}
```
Any ideas? Also, as a side question, what is the general opinion on the inner *matchesStraight* definition? Should this rather be private or perhaps done in a different way? | 2011/08/08 | [
"https://Stackoverflow.com/questions/6985148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/109191/"
] | You could do something like:
```
val ids = ranks.map(_.id)
ids.max - ids.min == 4 && ids.distinct.length == 5
```
Handling aces correctly requires a bit of work, though.
**Update:** Here's a much better solution:
```
(ids zip ids.tail).forall{case (p,q) => q%13==(p+1)%13}
```
The `% 13` in the comparison handles aces being both rank 1 and rank 14. | How about something like:
`def isStraight(cards:List[Card]) = (cards zip cards.tail) forall { case (c1,c2) => c1.rank+1 == c2.rank}`
`val cards = List(Card(1),Card(2),Card(3),Card(4))`
```
scala> isStraight(cards)
res2: Boolean = true
``` |
6,906,916 | This relates to [this question](https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript). I am using the code below from [this answer](https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523) to generate a UUID in JavaScript:
```
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
```
This solution appeared to be working fine, but I am getting collisions. Here's what I have:
* A web application running in Google Chrome.
* 16 users.
* about 4000 UUIDs have been generated in the past two months by these users.
* I got about 20 collisions - e.g., a new UUID generated today was the same as about two months ago (different user).
What is causing this issue and how can I avoid it? | 2011/08/02 | [
"https://Stackoverflow.com/questions/6906916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10793/"
] | Indeed there are collisions, but only under Google Chrome. Check out my experience on the topic in *[Google Chrome random number generator issue](https://web.archive.org/web/20190121220947/http://devoluk.com/google-chrome-math-random-issue.html)*
It seems like collisions only happen on the first few calls of Math.random. Because if you just run the createGUID / testGUIDs method above (which obviously was the first thing I tried), it just works without any collisions whatsoever.
So to make a full test one needs to restart Google Chrome, generate 32 byte, restart Chrome, generate, restart, generate, etc. | The answers here deal with "what's causing the issue?" (Chrome Math.random seed issue) but not "how can I avoid it?".
If you are still looking for how to avoid this issue, I wrote [this answer](https://stackoverflow.com/a/8809472/508537) a while back as a modified take on Broofa's function to get around this exact problem. It works by offsetting the first 13 hex numbers by a hex portion of the timestamp, meaning that even if Math.random is on the same seed it will still generate a different UUID unless generated at the exact same millisecond. |
26,508 | Check my profile and you will know all I have done on this site in the past 2-3 months is ask some questions. I want to answer some questions and be of use on this site(where a lot of easy questions must be piling up everyday). I have completed high school and I am about to join a college. I thought that there must be some questions out there that I can answer. But, guess what? Either they are already answered or it's way above my level. I tried to find some tags I might be of use with. But in the huge myriad of tags, I couldn't find any. Can anybody suggest ways I can be of use here? coz I really want to be.
Note: I am good at math, at least according to my friends and teachers(if that is relevant). | 2017/06/14 | [
"https://math.meta.stackexchange.com/questions/26508",
"https://math.meta.stackexchange.com",
"https://math.meta.stackexchange.com/users/425945/"
] | I looked at your profile and found
* 0 posts edited
* 0 helpful flags
* 4 votes cast
You can help this site by voting, editing and improving posts (+2 for your reputation), and, if it makes sense, flagging answers, posts and comments. The query uses a parameter Tag that you have to supply. You can enter % so that there all Tags are allowed.
And again, vote!
---
I tinkered around with *StackExchange Data Explorer* and created a query that searches for posts that don't have any answer and where the text of the question or the 'AbouMe' text of the user contains the word 'highschool'. Maybe this is useful to you.
<https://data.stackexchange.com/math/revision/685092/854111/unanswered-queries> | Looking at the [most popular tags](https://math.stackexchange.com/tags) I can suggest:
* [calculus](https://math.stackexchange.com/questions/tagged/calculus "show questions tagged 'calculus'") \*
* [probability](https://math.stackexchange.com/questions/tagged/probability "show questions tagged 'probability'") \*
* [algebra-precalculus](https://math.stackexchange.com/questions/tagged/algebra-precalculus "show questions tagged 'algebra-precalculus'")
* [combinatorics](https://math.stackexchange.com/questions/tagged/combinatorics "show questions tagged 'combinatorics'") \*
* [geometry](https://math.stackexchange.com/questions/tagged/geometry "show questions tagged 'geometry'")
* [elementary-number-theory](https://math.stackexchange.com/questions/tagged/elementary-number-theory "show questions tagged 'elementary-number-theory'") \*
* [functions](https://math.stackexchange.com/questions/tagged/functions "show questions tagged 'functions'")
* [trigonometry](https://math.stackexchange.com/questions/tagged/trigonometry "show questions tagged 'trigonometry'")
Where a \* means that some of the problems in that tag that are above your level. That's not to say that the ones without a \* will not contain problems you can't answer (indeed it would be impressive if you could answer all the questions in any tag) but just that the \* ones are meant for problems at several levels and some of those are going to be beyond you at this time. |
22,955,263 | This is the exception i am getting:
```
D:\Programming\Java\bin>JAVAC Demo.java
D:\Programming\Java\bin>java Demo
Error: Could not find or load main class Demo
D:\Programming\Java\bin>java -cp . Demo
Exception Born java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDrive
r
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:188)
at Demo.main(Demo.java:14)
```
This is my code:
```
// Oracle Connection Program
import java.io.*;
import java.sql.*;
public class Demo
{
public static void main(String[] args)throws IOException, SQLException
{
String inq = " insert into login values(10,'shri')" ;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:XE","system","admin");
Statement stmt = con.createStatement();
stmt.execute(inq);
con.close();
}
catch(Exception e)
{
System.out.println(" Exception Born "+e);
e.printStackTrace();
}
}
}
```
I have set the classpath to the odbc files in the oracle folder.. also copied them into the java bin folder. I've set classpath using the environment variable and also using cmd. But still the same error.
I'm even connecting to the database using sql. Table is created. What is the problem? Any Hints? | 2014/04/09 | [
"https://Stackoverflow.com/questions/22955263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3386500/"
] | When you launch a Java application you need to specify a classpath, otherwise it will not be able to find classes (like the Oracle JDBC driver).
You need to download the Oracle JDBC driver and put it somewhere on your system (say `C:\oraclejdbc\ojdbc7.jar`), then run Java with:
```
java -cp .;C:\oraclejdbc\ojdbc7.jar Demo
```
The `-cp` specifies where Java should look for the classes:
* `.` means current directory
* `C:\oraclejdbc\ojdbc7.jar` means: inside this jar file.
See also [Setting the Class Path](http://docs.oracle.com/javase/8/docs/technotes/tools/windows/classpath.html). That document also mentions the `CLASSPATH` environment variable, but in general you'd better steer clear of that. | I was facing a similar problem adding ;.; to the end of CLASSPATH worked for me.
eg. C:\Oracle\product\10.1.0\Client\_1\jdbc\lib\ojdbc14.jar;.; |
65,380,064 | I just learned how to use the machine learning model Random Forest; however, although I read about the random\_state parameter, I couldn't understand what it does. For example, what is the difference between `random_state = 0` and `random_state = 300`
Can someone please explain? | 2020/12/20 | [
"https://Stackoverflow.com/questions/65380064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14354649/"
] | You don't pass values from child to parent in React. React is unidirectional - data flows one way - from parent to child.
What you can do is to move given state from child to parent (so that you have one source of truth) and then pass to the child the data it needs as well as a function that allows to change the state in the parent. | you can pass the setGiftAid down to the child component and use that in the child component to set the state. |
19,062,631 | I want to read a string from keyboard and store in `buf` . I set a `char buf[6]` array , this array at most can store 5 characters and `\0` .
Then I type `123 456 789` it contain 11 characters and a `\0` , the program still can run , but if I type a longer string `123 456 789 123 456 789` it will crash at run time .
these two inputs also out of the range of `buf` , but one can run , the other crash?
Here is my code:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void read_str();
int main(){
read_str();
system("pause");
return 0;
}
void read_str(){
char buf[6] = {};
scanf("%[^\n]",buf);
printf("%d\n",strlen(buf));
printf("%s\n",buf);
}
``` | 2013/09/28 | [
"https://Stackoverflow.com/questions/19062631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2131116/"
] | Yes it is possible to call plain javascript function in data-binding. Try it in your project, it's working. There may be some problem in the jsfiddle script. | **Yes**, you can.
Please note the **[official Knockout documentation](http://knockoutjs.com/documentation/click-binding.html)** for the `click` binding:
>
> You can reference any JavaScript function - it doesn't have to be a function on your view model. You can reference a function on any object by writing click: someObject.someFunction.
>
>
>
---
Working example:
<https://jsbin.com/ciwofayegi/1/edit?html,css,js,output>
**HTML**
`<span data-bind="text: txt, click: outsideFn"></span>`
**Javascript**
```
var outsideFn = function () {
alert("outside function");
};
var vm = {
"txt": ko.observable("some text")
};
ko.applyBindings(vm);
``` |
9,708,266 | Hello I have a little problem with assigning property values from one lists items to anothers. I know i could solve it "the old way" by iterating through both lists etc. but I am looking for more elegant solution using LINQ.
Let's start with the code ...
```
class SourceType
{
public int Id;
public string Name;
// other properties
}
class DestinationType
{
public int Id;
public string Name;
// other properties
}
List<SourceType> sourceList = new List<SourceType>();
sourceList.Add(new SourceType { Id = 1, Name = "1111" });
sourceList.Add(new SourceType { Id = 2, Name = "2222" });
sourceList.Add(new SourceType { Id = 3, Name = "3333" });
sourceList.Add(new SourceType { Id = 5, Name = "5555" });
List<DestinationType> destinationList = new List<DestinationType>();
destinationList.Add(new DestinationType { Id = 1, Name = null });
destinationList.Add(new DestinationType { Id = 2, Name = null });
destinationList.Add(new DestinationType { Id = 3, Name = null });
destinationList.Add(new DestinationType { Id = 4, Name = null });
```
I would like to achieve the following:
* destinationList should be filled with Names of corresponding entries (by Id) in sourceList
* destinationList should not contain entries that are not present in both lists at once (eg. Id: 4,5 should be eliminated) - something like inner join
* I would like to avoid creating new destinationList with updated entries because both lists already exist and are very large,
so no "convert" or "select new".
In the end destinationList should contain:
```
1 "1111"
2 "2222"
3 "3333"
```
Is there some kind of elegant (one line Lambda? ;) solution to this using LINQ ?
Any help will be greatly appreciated! Thanks! | 2012/03/14 | [
"https://Stackoverflow.com/questions/9708266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269810/"
] | I would just build up a dictionary and use that:
```
Dictionary<int, string> map = sourceList.ToDictionary(x => x.Id, x => x.Name);
foreach (var item in destinationList)
if (map.ContainsKey(item.Id))
item.Name = map[item.Id];
destinationList.RemoveAll(x=> x.Name == null);
``` | Barring the last requirement of "avoid creating new destinationList" this should work
```
var newList = destinationList.Join(sourceList, d => d.Id, s => s.Id, (d, s) => s);
```
To take care of "avoid creating new destinationList", below can be used, which is not any different than looping thru whole list, except that it probably is less verbose.
```
destinationList.ForEach(d => {
var si = sourceList
.Where(s => s.Id == d.Id)
.FirstOrDefault();
d.Name = si != null ? si.Name : "";
});
destinationList.RemoveAll(d => string.IsNullOrEmpty(d.Name));
``` |
15,660 | In the spirit of the holidays, and as someone already started the winter theme([Build a snowman!](https://codegolf.stackexchange.com/questions/15648/build-a-snowman)) I propose a new challenge.
Print the number of days, hours, minutes, and seconds until Christmas(midnight(00:00:00) December 25th) on a stand alone window(not a console) in any unambiguous format you see fit, and continually update it as these values change.
Input - nothing, must read system time.
Shortest code wins :) The strings "Days", "Hours", "Minutes", "Seconds", and "Until Christmas" are free code. You can also flavour them up if you like. Flavouring them up is sheerly for the purpose of producing a nice output. You can not flavour strings for the purpose of making a magic number to save code. | 2013/12/06 | [
"https://codegolf.stackexchange.com/questions/15660",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/9516/"
] | Ruby with [Shoes](http://shoesrb.com/), 96 - 33 = 63
====================================================
```ruby
Shoes.app{p=para
animate{p.text="0 days 0 hours 0 minutes #{1387951200-Time.new.to_f} seconds"}}
```
Well, you never said we *couldn't*. ;)

Updates once every frame.
The magic number `1387951200` is Christmas - Dec 25, 2013 00:00.
Sample IRB session for where I got the numbers:
```
irb(main):211:0> "0 days 0 hours 0 minutes seconds".size
=> 33
irb(main):212:0> Time.new(2013,12,25,00,00,00).to_i
=> 1387951200
irb(main):213:0>
``` | Python 2, 115
-------------
```
from datetime import datetime as d
n=d.now()
print str(24-n.day),str(23-n.hour),str(59-n.minute),str(60-n.second)
```
This counts newlines as 2 characters. |
51,584,146 | Sort of new to Excel, so not sure if this is possible.
In Sheet 1 I have the fixtures of teams playing in matchday 1;
```
A B C D E
----------------------------
Matchday 1
Team 1 - Team 4
Team 2 - Team 5
Team 3 - Team 6
```
In Sheet 2 I have the previous years fixtures
```
A B C D E F
----------------------------------------------------------
Team 1 Team 2
Home Team Result Away Team Home Team Result Away Team
Team 1 1-0 Team 2 Team 2 0-1 Team 1
Team 1 1-1 Team 3 Team 2 2-1 Team 3
Team 1 1-2 Team 4 Team 2 0-1 Team 4
Team 1 2-2 Team 5 Team 2 1-1 Team 5
Team 1 1-0 Team 6 Team 2 3-1 Team 6
```
I want to be able to get the home teams name in Sheet 1, find that teams name in row 2 in Sheet 2, then finding the result based upon who the away team is.
For example, In Sheet 1, I want to find the result of Team 2 at home and Team 5 away from Sheet 2. So finding Team 2 in D1, then finding the result in E6. | 2018/07/29 | [
"https://Stackoverflow.com/questions/51584146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3113377/"
] | Since this question has changed from "What's the fastest way to parse a `float`?" to "What's the fastest way to get a `string` from a `char[]`?", I wrote some benchmarks with [`BenchmarkDotNet`](https://benchmarkdotnet.org/) to compare the various methods. My finding is that, if you already have a `char[]`, you can't get any faster than just passing it to the `string(char[])` constructor like you're already doing.
You say that your input file is "read into a `byte[]`, then the section of the `byte[]` that represents the `float` is extracted into a `char[]`." Since you have the `byte`s that make up the `float` text isolated in a `byte[]`, perhaps you can improve performance by skipping the intermediate `char[]`. Assuming you have something equivalent to...
```
byte[] floatBytes = new byte[] { 0x31, 0x33, 0x32, 0x2C, 0x32, 0x39 }; // "132,29"
```
...you could use [`Encoding.GetString()`](https://learn.microsoft.com/dotnet/api/system.text.encoding.getstring?System_Text_Encoding_GetString_System_Byte___)...
```
string floatString = Encoding.ASCII.GetString(floatBytes);
```
...which is nearly twice as fast as passing the result of [`Encoding.GetChars()`](https://learn.microsoft.com/dotnet/api/system.text.encoding.getchars?#System_Text_Encoding_GetChars_System_Byte___) to the `string(char[])` constructor...
```
char[] floatChars = Encoding.ASCII.GetChars(floatBytes);
string floatString = new string(floatChars);
```
You'll find those benchmarks listed last in my results...
```
BenchmarkDotNet=v0.11.0, OS=Windows 10.0.17134.165 (1803/April2018Update/Redstone4)
Intel Core i7 CPU 860 2.80GHz (Max: 2.79GHz) (Nehalem), 1 CPU, 8 logical and 4 physical cores
Frequency=2732436 Hz, Resolution=365.9738 ns, Timer=TSC
.NET Core SDK=2.1.202
[Host] : .NET Core 2.0.9 (CoreCLR 4.6.26614.01, CoreFX 4.6.26614.01), 64bit RyuJIT
Clr : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3131.0
Core : .NET Core 2.0.9 (CoreCLR 4.6.26614.01, CoreFX 4.6.26614.01), 64bit RyuJIT
Method | Runtime | Categories | Mean | Scaled |
----------------------------------------------------- |-------- |----------------- |----------:|-------:|
String_Constructor_CharArray | Clr | char[] => string | 13.51 ns | 1.00 |
String_Concat | Clr | char[] => string | 192.87 ns | 14.27 |
StringBuilder_Local_AppendSingleChar_DefaultCapacity | Clr | char[] => string | 60.74 ns | 4.49 |
StringBuilder_Local_AppendSingleChar_ExactCapacity | Clr | char[] => string | 60.26 ns | 4.46 |
StringBuilder_Local_AppendAllChars_DefaultCapacity | Clr | char[] => string | 51.27 ns | 3.79 |
StringBuilder_Local_AppendAllChars_ExactCapacity | Clr | char[] => string | 49.51 ns | 3.66 |
StringBuilder_Field_AppendSingleChar | Clr | char[] => string | 51.14 ns | 3.78 |
StringBuilder_Field_AppendAllChars | Clr | char[] => string | 32.95 ns | 2.44 |
| | | | |
String_Constructor_CharPointer | Clr | void* => string | 29.28 ns | 1.00 |
String_Constructor_SBytePointer | Clr | void* => string | 89.21 ns | 3.05 |
UnsafeArrayCopy_String_Constructor | Clr | void* => string | 42.82 ns | 1.46 |
| | | | |
Encoding_GetString | Clr | byte[] => string | 37.33 ns | 1.00 |
Encoding_GetChars_String_Constructor | Clr | byte[] => string | 60.83 ns | 1.63 |
SafeArrayCopy_String_Constructor | Clr | byte[] => string | 27.55 ns | 0.74 |
| | | | |
String_Constructor_CharArray | Core | char[] => string | 13.27 ns | 1.00 |
String_Concat | Core | char[] => string | 172.17 ns | 12.97 |
StringBuilder_Local_AppendSingleChar_DefaultCapacity | Core | char[] => string | 58.68 ns | 4.42 |
StringBuilder_Local_AppendSingleChar_ExactCapacity | Core | char[] => string | 59.85 ns | 4.51 |
StringBuilder_Local_AppendAllChars_DefaultCapacity | Core | char[] => string | 40.62 ns | 3.06 |
StringBuilder_Local_AppendAllChars_ExactCapacity | Core | char[] => string | 43.67 ns | 3.29 |
StringBuilder_Field_AppendSingleChar | Core | char[] => string | 54.49 ns | 4.11 |
StringBuilder_Field_AppendAllChars | Core | char[] => string | 31.05 ns | 2.34 |
| | | | |
String_Constructor_CharPointer | Core | void* => string | 22.87 ns | 1.00 |
String_Constructor_SBytePointer | Core | void* => string | 83.11 ns | 3.63 |
UnsafeArrayCopy_String_Constructor | Core | void* => string | 35.30 ns | 1.54 |
| | | | |
Encoding_GetString | Core | byte[] => string | 36.19 ns | 1.00 |
Encoding_GetChars_String_Constructor | Core | byte[] => string | 58.99 ns | 1.63 |
SafeArrayCopy_String_Constructor | Core | byte[] => string | 27.81 ns | 0.77 |
```
...from running this code (requires [`BenchmarkDotNet` assembly](https://www.nuget.org/packages/BenchmarkDotNet/) and compiling with `/unsafe`)...
```
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using BenchmarkDotNet.Attributes;
namespace StackOverflow_51584129
{
[CategoriesColumn()]
[ClrJob()]
[CoreJob()]
[GroupBenchmarksBy(BenchmarkDotNet.Configs.BenchmarkLogicalGroupRule.ByCategory)]
public class StringCreationBenchmarks
{
private static readonly Encoding InputEncoding = Encoding.ASCII;
private const string InputString = "132,29";
private static readonly byte[] InputBytes = InputEncoding.GetBytes(InputString);
private static readonly char[] InputChars = InputString.ToCharArray();
private static readonly sbyte[] InputSBytes = InputBytes.Select(Convert.ToSByte).ToArray();
private GCHandle _inputBytesHandle;
private GCHandle _inputCharsHandle;
private GCHandle _inputSBytesHandle;
private StringBuilder _builder;
[Benchmark(Baseline = true)]
[BenchmarkCategory("char[] => string")]
public string String_Constructor_CharArray()
{
return new string(InputChars);
}
[Benchmark(Baseline = true)]
[BenchmarkCategory("void* => string")]
public unsafe string String_Constructor_CharPointer()
{
var pointer = (char*) _inputCharsHandle.AddrOfPinnedObject();
return new string(pointer);
}
[Benchmark()]
[BenchmarkCategory("void* => string")]
public unsafe string String_Constructor_SBytePointer()
{
var pointer = (sbyte*) _inputSBytesHandle.AddrOfPinnedObject();
return new string(pointer);
}
[Benchmark()]
[BenchmarkCategory("char[] => string")]
public string String_Concat()
{
return string.Concat(InputChars);
}
[Benchmark()]
[BenchmarkCategory("char[] => string")]
public string StringBuilder_Local_AppendSingleChar_DefaultCapacity()
{
var builder = new StringBuilder();
foreach (var c in InputChars)
builder.Append(c);
return builder.ToString();
}
[Benchmark()]
[BenchmarkCategory("char[] => string")]
public string StringBuilder_Local_AppendSingleChar_ExactCapacity()
{
var builder = new StringBuilder(InputChars.Length);
foreach (var c in InputChars)
builder.Append(c);
return builder.ToString();
}
[Benchmark()]
[BenchmarkCategory("char[] => string")]
public string StringBuilder_Local_AppendAllChars_DefaultCapacity()
{
var builder = new StringBuilder().Append(InputChars);
return builder.ToString();
}
[Benchmark()]
[BenchmarkCategory("char[] => string")]
public string StringBuilder_Local_AppendAllChars_ExactCapacity()
{
var builder = new StringBuilder(InputChars.Length).Append(InputChars);
return builder.ToString();
}
[Benchmark()]
[BenchmarkCategory("char[] => string")]
public string StringBuilder_Field_AppendSingleChar()
{
_builder.Clear();
foreach (var c in InputChars)
_builder.Append(c);
return _builder.ToString();
}
[Benchmark()]
[BenchmarkCategory("char[] => string")]
public string StringBuilder_Field_AppendAllChars()
{
return _builder.Clear().Append(InputChars).ToString();
}
[Benchmark(Baseline = true)]
[BenchmarkCategory("byte[] => string")]
public string Encoding_GetString()
{
return InputEncoding.GetString(InputBytes);
}
[Benchmark()]
[BenchmarkCategory("byte[] => string")]
public string Encoding_GetChars_String_Constructor()
{
var chars = InputEncoding.GetChars(InputBytes);
return new string(chars);
}
[Benchmark()]
[BenchmarkCategory("byte[] => string")]
public string SafeArrayCopy_String_Constructor()
{
var chars = new char[InputString.Length];
for (int i = 0; i < InputString.Length; i++)
chars[i] = Convert.ToChar(InputBytes[i]);
return new string(chars);
}
[Benchmark()]
[BenchmarkCategory("void* => string")]
public unsafe string UnsafeArrayCopy_String_Constructor()
{
fixed (char* chars = new char[InputString.Length])
{
var bytes = (byte*) _inputBytesHandle.AddrOfPinnedObject();
for (int i = 0; i < InputString.Length; i++)
chars[i] = Convert.ToChar(bytes[i]);
return new string(chars);
}
}
[GlobalSetup(Targets = new[] { nameof(StringBuilder_Field_AppendAllChars), nameof(StringBuilder_Field_AppendSingleChar) })]
public void SetupStringBuilderField()
{
_builder = new StringBuilder();
}
[GlobalSetup(Target = nameof(UnsafeArrayCopy_String_Constructor))]
public void SetupBytesHandle()
{
_inputBytesHandle = GCHandle.Alloc(InputBytes, GCHandleType.Pinned);
}
[GlobalCleanup(Target = nameof(UnsafeArrayCopy_String_Constructor))]
public void CleanupBytesHandle()
{
_inputBytesHandle.Free();
}
[GlobalSetup(Target = nameof(String_Constructor_CharPointer))]
public void SetupCharsHandle()
{
_inputCharsHandle = GCHandle.Alloc(InputChars, GCHandleType.Pinned);
}
[GlobalCleanup(Target = nameof(String_Constructor_CharPointer))]
public void CleanupCharsHandle()
{
_inputCharsHandle.Free();
}
[GlobalSetup(Target = nameof(String_Constructor_SBytePointer))]
public void SetupSByteHandle()
{
_inputSBytesHandle = GCHandle.Alloc(InputSBytes, GCHandleType.Pinned);
}
[GlobalCleanup(Target = nameof(String_Constructor_SBytePointer))]
public void CleanupSByteHandle()
{
_inputSBytesHandle.Free();
}
public static void Main(string[] args)
{
BenchmarkDotNet.Running.BenchmarkRunner.Run<StringCreationBenchmarks>();
}
}
}
``` | Interesting topic for working out optimization details at home :) good health to you all..
My goal was: convert an Ascii CSV matrix into a float matrix as fast as possible in C#. For this purpose, it turns out string.Split() rows and converting each term separately will also introduce overhead. To overcome this, I modified BACON's solution for row parsing my floats, to use it like:
```
var falist = new List<float[]>();
for (int row=0; row<sRowList.Count; row++)
{
var sRow = sRowList[row];
falist.Add(CustomFloatParseRowByIndexing(nTerms, sRow.ToCharArray(), '.'));
}
```
Code for my row parser variant is below. These are benchmark results, converting a 40x31 matrix 1000x:
Benchmark0: Split row and Parse each term to convert to float matrix **dT=704 ms**
Benchmark1: Split row and TryParse each term to convert to float matrix **dT=640 ms**
Benchmark2: Split row and CustomFloatParseByIndexing to convert terms to float matrix **dT=211 ms**
Benchmark3: Use CustomFloatParseRowByIndexing to convert rows to float matrix **dT=120 ms**
```
public float[] CustomFloatParseRowByIndexing(int nItems, char[] InputBytes, char DecimalSeparator)
{
// Convert semicolon-separated floats from InputBytes into nItems float[] result.
// Constraints are:
// - no scientific notation or .x allowed
// - every row has exactly nItems values
// - semicolon delimiter after each value
// - terms 'u' or 'undef' or 'undefined' allowed for bad values
// - minus sign allowed
// - leading space allowed
// - all terms must comply
// FOR DEMO PURPOSE ONLY
// based on BACON on Stackoverflow, modified to read nItems delimited float values
// https://stackoverflow.com/questions/51584129/convert-a-float-formated-char-to-float
var currentIndex = 0;
var boundaryIndex = InputBytes.Length;
bool termready, ready = false;
float[] result = new float[nItems];
int cItem = 0;
while (currentIndex < boundaryIndex)
{
termready = false;
if ((char)InputBytes[currentIndex] == ' ') { currentIndex++; continue; }
char currentChar;
var wholePart = 0;
float sgn = 1;
while (currentIndex < boundaryIndex && (currentChar = (char)InputBytes[currentIndex++]) != DecimalSeparator)
{
if (currentChar == 'u')
{
while ((char)InputBytes[currentIndex++] != ';') ;
result[cItem++] = -9999.0f;
continue;
}
else
if (currentChar == ' ')
{
continue;
}
else
if (currentChar == ';')
{
termready = true;
break;
}
else
if (currentChar == '-') sgn = -1;
else
{
var currentDigit = currentChar - '0';
wholePart = 10 * wholePart + currentDigit;
}
}
var fractionalPart = 0F;
var nextFractionalDigitScale = 0.1F;
if (!termready)
while (currentIndex < boundaryIndex)
{
currentChar = (char)InputBytes[currentIndex++];
if (currentChar == ';')
{
termready = true;
break;
}
var currentDigit = currentChar - '0';
fractionalPart += currentDigit * nextFractionalDigitScale;
nextFractionalDigitScale *= 0.1F;
}
if (termready)
{
result[cItem++] = sgn * (wholePart + fractionalPart);
}
}
return result;
}
``` |
7,621,066 | I have a string that is made up of a list of numbers, seperated by commas. How would I add a space after each comma using Regex? | 2011/10/01 | [
"https://Stackoverflow.com/questions/7621066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67641/"
] | Use [`String.replace`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace) with a [regexp](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp).
```
> var input = '1,2,3,4,5',
output = input.replace(/(\d+,)/g, '$1 ');
> output
"1, 2, 3, 4, 5"
``` | ```
var numsStr = "1,2,3,4,5,6";
var regExpWay = numStr.replace(/,/g,", ");
var splitWay = numStr.split(",").join(", ");
``` |
31,405,793 | I have defined 2 numpy array 2,3 and horizontally concatenate them
```
a=numpy.array([[1,2,3],[4,5,6]])
b=numpy.array([[7,8,9],[10,11,12]])
C=numpy.concatenate((a,b),axis=0)
```
c becomes 4,3 matrix
Now I tried same thing with 1,3 list as
```
a=numpy.array([1,2,3])
b=numpy.array([4,5,6])
c=numpy.concatenate((a,b),axis=0)
```
Now I was expecting 2,3 matrix but instead I have 1,6. I understand that vstack etc will work but I am curious as to why this is happening? And what I am doing wrong with numpy.concatenate?
Thanks for the reply. I can get the result as suggested by having 1,3 array and then concatenation. But logic is I have to add rows to an empty matrix at each iteration. I tried append as Suggested:
```
testing=[]
for i in range(3):
testing=testing.append([1,2,3])
```
It gave error testing doesnot have attribute append as its of None Type. Further If I use logic of 1,3 array using np.array([[1,2,3]]) how can i do this inside for loop? | 2015/07/14 | [
"https://Stackoverflow.com/questions/31405793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5108825/"
] | You didn't do anything wrong. [`numpy.concatenate`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html) join a sequence of arrays together.which means it create an integrated array from the current array's element which in a 2D array the elements are nested lists and in a 1D array the elements are variables.
So this is not the `concatenate`'s job, as you said you can use `np.vstack` :
```
>>> c=numpy.vstack((a,b))
>>> c
array([[1, 2, 3],
[4, 5, 6]])
```
Also in your code `list.append` appends and element in-place to a list you can not assign it to a variable.instead you can just `append` to `testing` in each iteration.
```
testing=[]
for i in range(3):
testing.append([1,2,3])
```
also as a more efficient way you can create that list using a list comprehension list following :
```
testing=[[1,2,3] for _ in xrange(3)]
``` | This is happening because you are concatenating along `axis=0`.
In your first example:
```
a=numpy.array([[1,2,3],[4,5,6]]) # 2 elements in 0th dimension
b=numpy.array([[7,8,9],[10,11,12]]) # 2 elements in 0th dimension
C=numpy.concatenate((a,b),axis=0) # 4 elements in 0th dimension
```
In your second example:
```
a=numpy.array([1,2,3]) # 3 elements in 0th dimension
b=numpy.array([4,5,6]) # 3 elements in 0th dimension
c=numpy.concatenate((a,b),axis=0) # 6 elements in 0th dimension
```
Edit:
Note that in your second example, you only have one dimensional array.
```
In [35]: a=numpy.array([1,2,3])
In [36]: a.shape
Out[36]: (3,)
```
If the shape of the arrays was `(1,3)` you would get your expected result:
```
In [43]: a2=numpy.array([[1,2,3]])
In [44]: b2=numpy.array([[4,5,6]])
In [45]: numpy.concatenate((a2,b2), axis=0)
Out[45]:
array([[1, 2, 3],
[4, 5, 6]])
``` |
1,145,286 | I have a large xml file (40 Gb) that I need to split into smaller chunks. I am working with limited space, so is there a way to delete lines from the original file as I write them to new files?
Thanks! | 2009/07/17 | [
"https://Stackoverflow.com/questions/1145286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/98778/"
] | If you're on Linux/Unix, why not use the split command like [this guy](http://www.techiecorner.com/107/how-to-split-large-file-into-several-smaller-files-linux/) does?
```
split --bytes=100m /input/file /output/dir/prefix
```
EDIT: then use [csplit](http://linux.die.net/man/1/csplit). | Here is my script...
```
import string
import os
from ftplib import FTP
# make ftp connection
ftp = FTP('server')
ftp.login('user', 'pwd')
ftp.cwd('/dir')
f1 = open('large_file.xml', 'r')
size = 0
split = False
count = 0
for line in f1:
if not split:
file = 'split_'+str(count)+'.xml'
f2 = open(file, 'w')
if count > 0:
f2.write('<?xml version="1.0"?>\n')
f2.write('<StartTag xmlns="http://www.blah/1.2.0">\n')
size = 0
count += 1
split = True
if size < 1073741824:
f2.write(line)
size += len(line)
elif str(line) == '</EndTag>\n':
f2.write(line)
f2.write('</EndEndTag>\n')
print('completed file %s' %str(count))
f2.close()
f2 = open(file, 'r')
print("ftp'ing file...")
ftp.storbinary('STOR ' + file, f2)
print('ftp done.')
split = False
f2.close()
os.remove(file)
else:
f2.write(line)
size += len(line)
``` |
313,581 | The data was IN my phone or ON my phone?
Well, IN being generally more of a 'containment' preposition, I would think its usage here is okay, and the phone is perceived as `bag`. However, I wonder which preposition would end up being the one used because sometimes things in English have both a 'contained' property (where, if I'm not mistaken, we generally use `in`) and a `loaded` property (where we use `on`). I'm thinking than that my question ends up being also "how do the English perceive things that were saved to a phone? as put [e.g. in a bag] or loaded [e.g. on a bus]?" | 2016/03/14 | [
"https://english.stackexchange.com/questions/313581",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/121141/"
] | I would say **on** the computer/phone and **in** the computer/phone are equally common.
With a particular app/system **in** is more likely; in Sharepoint, in the database. But where it is stored physically is generally **on**; on disk, on tape, on a USB flash drive. | Data are saved **in** a register **on** a device. Thus, considering a phone mainly a register for contacts and messages, that information is saved **in** the phone, considering the phone as a device, the information is saved **on** the phone. |
12,682,660 | Ok i have a dynamic page where people can post events in the city, we will call that page: city.php. In order to get to the page though, you must select a state from states.php, then a city from allcities.php. The states and cities are all in mysql database. On the city.php page you can click "add event" and it will take you to createevent.php where you can create and add an event that shows on city.php. But here is what i want to do:
I want to make it so that city.php is the central spot for posting different things for that city. I want a page for events, news, jobs, and for sale. On the city.php you will select a link for those pages taking you to pages such as events.php, news.php, jobs.php, and sale.php. How can i keep all those pages dynamic and related to the selected city? I toyed around and couldn't figure it out. | 2012/10/01 | [
"https://Stackoverflow.com/questions/12682660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1665920/"
] | There are a number of ways to do something like this in PHP. I personally disagree with your method as it sounds. I could be wrong about what it seems like you're saying though.
As adam said, $\_SESSION is the first thing in mind. You can also look into $\_COOKIE:
<http://php.net/manual/en/features.cookies.php>
or just pass the city id as a $\_GET var:
<http://www.yoursite.com/events.php?city=2>
Then read it in PHP like
```
$city_id = $_GET['city'];
``` | Quite generic but key is in the relational db structure. Displaying is easy, so make sure that news, job, events tables has `id_city` for building correct queries.
Example DB style as answer to your comment:
```
cities : id_city | city_name | city_slug | id_state
events : id_event | id_city | event_name | other_event_data | ...
jobs : id_jobs | id_city | job_name | job_salary | etc.
```
So user clicks to `yoursite.com/washington`
Then you can query that comes from url (here is washington) like:
```
SELECT id_city FROM cities WHERE city_slug = "washington"
```
You got id\_city now. Then if it is jobs,
```
SELECT * FROM jobs WHERE id_city = "above gotten id_city"
```
Hope this helps. |
16,802 | I'm running GNU Emacs 24.5.4 on Mac OS X 10.10.5 in Terminal.app.
In this (stock) setup, Emacs has a transparent background. With a transparent background, the colors that Emacs uses to display text are auto-adjusted based on the color *underneath* Emacs. In my case, "underneath Emacs" is a Terminal.app window with an opaque black background.
(In the title I refer to the "effective" theme. I'm using that to mean to the colors that Emacs actually uses to render text - as opposed to the "specified" theme, which is different in this case.)
Here is what the default theme looks like when no background color is specified in Emacs, and Emacs is running in a Terminal.app window with an opaque black background:
[](https://i.stack.imgur.com/7bh4I.png)
And here is the same setup - except with a black background specified in Emacs:
[](https://i.stack.imgur.com/vYZr2.png)
While beauty is certainly in the eye of the beholder, I've gotten used to the colors in the top image.
So I'd like to duplicate those colors in GUI Emacs. But since GUI Emacs isn't a transparent window always running on top of something with a black background and hence having colors auto-adjusted, setting its background to black results in the coloring shown in the bottom screenshot.
How do I duplicate the 'effective' colors used in the top screenshot so that they are used in GUI Emacs as well?
P.S. Here's a video demonstrating the text color adjustments happening in real-time vs. changes to the background color of Terminal.app: vimeo.com/139967912. (I had to use an external camera since QuickTime Player's screen recording didn't work for this purpose.) | 2015/09/21 | [
"https://emacs.stackexchange.com/questions/16802",
"https://emacs.stackexchange.com",
"https://emacs.stackexchange.com/users/9589/"
] | A simple method, close to what you have:
```el
(defun current-line-empty-p ()
(string-match-p "\\`\\s-*$" (thing-at-point 'line)))
``` | Here is another simple solution for it, taken from `comment-dwim-2` package
```
(defun is-empty-line-p ()
(string-match-p "^[[:blank:]]*$"
(buffer-substring (line-beginning-position)
(line-end-position))))
``` |
3,377,954 | When I insert some text written in Unicode into database, they become question marks. Database encoding is set to UTF-8. What else may be incorrect? When I check in phpMyAdmin there are question marks inserted only!
This is the code I use for connecting to database:
```
define ("DB_HOST", "localhost"); // Set database host
define ("DB_USER", "root"); // Set database user
define ("DB_PASS","password"); // Set database password
define ("DB_NAME","name"); // Set database name
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
mysql_set_charset('utf8',$link);
mysql_query("SET CHARACTER SET utf8");
``` | 2010/07/31 | [
"https://Stackoverflow.com/questions/3377954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/352959/"
] | Is the text you inserted encoded in UTF-8 too? Or is your PHP files not UTF-8? Have you set the MySQL Client connection to UTF-8?
If not, then that is probably the cause of the problem. | ```
// First make sure your file produce UTF-8 characters
header('Content-Type: text/html; charset=utf-8');
// Make sure with your spelling
// write
mysql_query("SET CHARSET utf8");
// Instead of
mysql_query("SET CHARACTER SET utf8");
// For some reasons
mysql_query("SET CHARSET SET utf8");
// It works on some servers and for other servers not. I am not sure why.
// Try using mysql_set_charset("utf8"); only without mysql_query("SET CHARSET utf8");
// For me I had the same issue with my server
// When I used mysql_set_charset("utf8"); only --> the problem solved
// again make sure with your spelling and try again
``` |
60,897,536 | I can globally replace a regular expression with `re.sub()`, and I can count matches with
```
for match in re.finditer(): count++
```
Is there a way to combine these two, so that I can count my substitutions without making two passes through the source string?
Note: I'm not interested in whether the substitution matched, I'm interested in the exact count of matches in the same call, avoiding one call to count and one call to substitute. | 2020/03/28 | [
"https://Stackoverflow.com/questions/60897536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | You can pass a `repl` function while calling the `re.sub` function.
*The function takes a single match object argument, and returns the replacement string. The `repl` function is called for every non-overlapping occurrence of pattern.*
**Try this:**
```
count = 0
def count_repl(mobj): # --> mobj is of type re.Match
global count
count += 1 # --> count the substitutions
return "your_replacement_string" # --> return the replacement string
text = "The original text" # --> source string
new_text = re.sub(r"pattern", repl=count_repl, string=text) # count and replace the matching occurrences in one pass.
```
**OR,**
You can use [re.subn](https://docs.python.org/3/library/re.html#re.subn) which performs the same operation as [re.sub](https://docs.python.org/3/library/re.html#re.sub), but return a tuple (new\_string, number\_of\_subs\_made).
```
new_text, count = re.sub(r"pattern", repl="replacement", string=text)
```
---
**Example:**
```
count = 0
def count_repl(mobj):
global count
count += 1
return f"ID: {mobj.group(1)}"
text = "Jack 10, Lana 11, Tom 12, Arthur, Mark"
new_text = re.sub(r"(\d+)", repl=count_repl, string=text)
print(new_text)
print("Number of substitutions:", count)
```
**Output:**
```
Jack ID: 10, Lana ID: 11, Tom ID: 12
Number of substitutions: 3
``` | ```
import re
text = "Jack 10, Lana 11, Tom 12"
count = len([x for x in re.finditer(r"(\d+)", text)])
print(count)
# Output: 3
```
Ok, there's a better way
------------------------
```
import re
text = "Jack 10, Lana 11, Tom 12"
count = re.subn(r"(\d+)", repl="replacement", string=text)[1]
print(count)
# Output: 3
``` |
42,346,206 | ```
image(imageurl){
return "http://web.com/"+imageurl+".jpg";
```
How to use this url in CSS background-image ?
here is css
```
<div style="width: 100%;
height: 300px;
background-image: url ('image(post.postimage)');
background-repeat: no-repeat;
background-size: cover;">
</div>
``` | 2017/02/20 | [
"https://Stackoverflow.com/questions/42346206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | First of all, if `char` corresponds to `unsigned char`, a `char` cannot have a trap representation; [however if `char` corresponds to `signed char` it can have trap representations](https://stackoverflow.com/questions/6725809/trap-representation). Since using a trap representation has undefined behaviour, it is more interesting to modify the code to use `unsigned char`:
```
unsigned char A = A ? 0[&A] & !A : A^A;
putchar(A);
```
Initially I believed that there *isn't* any undefined behaviour in C. The question is is `A` uninitialized in a manner that has undefined behaviour, and the answer is "no", because, although it is a local variable with automatic storage duration, it has its address taken, so it must reside in memory, and its type is char, therefore its value is unspecified but specifically it cannot be a trap representation.
The C11 Appendix J.2. specifies that the following has undefined behaviour:
>
> An lvalue designating an object of automatic storage duration that could have been declared with the register storage class is used in a context that requires the value of the designated object, but the object is uninitialized. (6.3.2.1).
>
>
>
with 6.3.2.1p2 saying that
>
> If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.
>
>
>
Since the address of `A` is taken, it could not have been declared with the `register` storage class, and therefore its use does not has undefined behaviour as per this 6.3.2.1p2; instead it would have an unspecified yet valid `char` value; `char`s do not have trap representations.
However, the problem is that there is not any requirement that `A` must yield the same unspecified value all over, as unspecified value is
>
> valid value of the relevant type where this International Standard imposes no requirements on which value is chosen in *any instance*
>
>
>
And the answer to C11 [Defect Report 451](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1846.htm) seems to consider this to have **undefined behaviour** after all, saying that the result of using an indeterminate value (even with types that have no trap representations, such as `unsigned char`) in arithmetic expressions will also mean that the result will have unstable values and that *use of such values in library functions will have undefined behaviour*.
Thus:
```
unsigned char A = A ? 0[&A] & !A : A^A;
```
doesn't invoke undefined behaviour as such but `A` is still initialized with an indeterminate value, and use of such an indeterminate value in call to a library function `putchar(A)` should be considered as having undefined behaviour:
>
> Proposed Committee Response
>
>
> * The answer to question 1 is "yes", an uninitialized value under the conditions described can appear to change its value.
> * The answer to question 2 is that any operation performed on indeterminate values will have an indeterminate value as a result.
> * The answer to question 3 is that library functions will exhibit undefined behavior when used on indeterminate values.
> * These answers are appropriate for all types that do not have trap representations.
> * This viewpoint reaffirms the C99 DR260 position.
> * The committee agrees that this area would benefit from a new definition of something akin to a "wobbly" value and that this should
> be considered in any subsequent revision of this standard.
> * The committee also notes that padding bytes within structures are possibly a distinct form of "wobbly" representation.
>
>
> | This is a category of behavior where the Standard would strongly imply a behavior, and nothing in the Standard would invite an implementation to jump the rails, but the official "interpretation" would nonetheless allow compilers to behave in arbitrary fashion. As such, it would not be accurate to describe the behavior as "undefined" [because the text of the Standard does imply a behavior and says nothing to suggest that it shouldn't apply] nor would it be accurate to simply say it's "defined" [because the Committee says compilers may behave in arbitrary fashion]. Instead it's necessary to recognize an intermediate condition.
Because different application fields (number crunching, systems programming, etc.) benefit from different kinds of behavioral guarantees, and because some platforms may be able to uphold certain guarantees more cheaply than others, the authors of every C standard to date have generally sought to avoid passing judgment on the relative costs and benefits of various guarantees. Instead, they have shown significant deference to implementers' judgment with regard to what guarantees should be provided in what implementations.
If it is plausible that offering some particular behavioral guarantee would have no value in some application field (even if it may be vital in others), and waiving that guarantee might sometimes allow some implementations to be more efficient (even if in most cases it wouldn't), the authors of the Standard will generally not require that guarantee. Instead, they let implementers decide, based upon an implementation's target platform(s) and intended application field(s) whether the implementation should always support that guarantee, never support that guarantee, or allow programmers to select (via command-line options or other means) whether to support the guarantee.
A quality implementation intended for any particular purpose (e.g. systems programming) will support the kinds of behavioral guarantees that would make a compiler suitable for that purpose (e.g. reading an unsigned char that a program owns will never have any effect beyond yielding a possibly-meaningless value), whether the Standard requires it to do so or not. The authors of the C Standard don't require nor intend that all implementations be suitable for fields like systems programming, and thus don't require that implementation aimed at other fields like number crunching uphold such a guarantee. The fact that compilers targeting other fields may not uphold the kinds of guarantees required for systems programming means that it's important that systems programmers ensure that they use tools which are suitable for their purposes. Knowing that a tool promises to supports the guarantees one needs is far more important than knowing that present interpretations of the Standard support such a guarantee, given that a guarantee which is considered unambiguous today might disappear if a compiler writer can suggest that waiving it might *sometimes* be beneficial. |
52,024,365 | I want to transfer the negative values at the current row to the previous row by adding them to the previous row within each group.
Following is the sample raw data I have:
```
raw_data <- data.frame(GROUP = rep(c('A','B','C'),each = 6),
YEARMO = rep(c(201801:201806),3),
VALUE = c(100,-10,20,70,-50,30,20,60,40,-20,-10,50,0,10,-30,50,100,-100))
> raw_data
GROUP YEARMO VALUE
1 A 201801 100
2 A 201802 -10
3 A 201803 20
4 A 201804 70
5 A 201805 -50
6 A 201806 30
7 B 201801 20
8 B 201802 60
9 B 201803 40
10 B 201804 -20
11 B 201805 -10
12 B 201806 50
13 C 201801 0
14 C 201802 10
15 C 201803 -30
16 C 201804 50
17 C 201805 100
18 C 201806 -100
```
Following is the output that I want:
```
final_data <- data.frame(GROUP = rep(c('A','B','C'),each = 6),
YEARMO = rep(c(201801:201806),3),
VALUE = c(90,0,20,20,0,30,20,60,10,0,0,50,-20,0,0,50,0,0))
> final_data
GROUP YEARMO VALUE
1 A 201801 90
2 A 201802 0
3 A 201803 20
4 A 201804 20
5 A 201805 0
6 A 201806 30
7 B 201801 20
8 B 201802 60
9 B 201803 10
10 B 201804 0
11 B 201805 0
12 B 201806 50
13 C 201801 -20
14 C 201802 0
15 C 201803 0
16 C 201804 50
17 C 201805 0
18 C 201806 0
```
Following data frames will show how the transformation can be made in each group:
```
Trans_GRP_A <- data.frame(GROUP = rep('A',each = 6),
YEARMO = c(201801:201806),
VALUE = c(100,-10,20,70,-50,30),
ITER_1 = c(100,-10,20,20,0,30),
ITER_2 = c(90,0,20,20,0,30))
> Trans_GRP_A
GROUP YEARMO VALUE ITER_1 ITER_2
1 A 201801 100 100 90
2 A 201802 -10 -10 0
3 A 201803 20 20 20
4 A 201804 70 20 20
5 A 201805 -50 0 0
6 A 201806 30 30 30
> Trans_GRP_B <- data.frame(GROUP = rep('B',each = 6),
+ YEARMO = c(201801:201806),
+ VALUE = c(20,60,40,-20,-10,50),
+ ITER_1 = c(20,60,40,-30,0,50),
+ ITER_2 = c(20,60,10,0,0,50))
> Trans_GRP_B
GROUP YEARMO VALUE ITER_1 ITER_2
1 B 201801 20 20 20
2 B 201802 60 60 60
3 B 201803 40 40 10
4 B 201804 -20 -30 0
5 B 201805 -10 0 0
6 B 201806 50 50 50
> Trans_GRP_C <- data.frame(GROUP = rep('C',each = 6),
+ YEARMO = c(201801:201806),
+ VALUE = c(0,10,-30,50,100,-100),
+ ITER_1 = c(0,10,-30,50,0,0),
+ ITER_2 = c(0,-20,0,50,0,0),
+ ITER_3 = c(-20,0,0,50,0,0))
> Trans_GRP_C
GROUP YEARMO VALUE ITER_1 ITER_2 ITER_3
1 C 201801 0 0 0 -20
2 C 201802 10 10 -20 0
3 C 201803 -30 -30 0 0
4 C 201804 50 50 50 50
5 C 201805 100 0 0 0
6 C 201806 -100 0 0 0
```
The logic for transfer is as follows:
1. Replace the negative value with 0.
2. Add the negative value at current row to the value at previous row.
3. Transfer the negative value to the previous row until the value becomes positive or 0.
4. Transfer until the 1st row is encountered within the group if transferring doesn't result in a positive value, here 1st row is YEARMO = 201801 in each group.
Any solution is welcome. I think a solution which is vectorized might perform faster. | 2018/08/26 | [
"https://Stackoverflow.com/questions/52024365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7879423/"
] | ```
Right click on the console > Preferences > Console buffer size.
> Uncheck the "Limit console output" checkbox.
```
There was no error in my code.
It was just that the result had been truncated by the 80000 character limit.
I released the limit and got the result that I expected. | ```
Code written for to read multiple test files from multiple folder:
In the try block the FileReader reads a file and the second works as a constructor parameter and has a readline() method.
public static void main(String[] args) {
String dir = "c:\\html_test\\amdar";
File dir = new File(dir);
File[] folder = dir.listFiles();
for(File table : folder) {
if(table.isFile())
{
BufferedReader inputStream = null;
try{
inputStream = new BufferedReader(new FileReader(f));
String line;
while ((line = inputStream.readLine()) != null)
{
System.out.println(line);
}
}
finally {
if (inputStream != null) {
inputStream.close();
}
}
}
}
}
``` |
17,708,518 | I have a table with 3 fields "Start Date" and "End Date" and "Allocation %". I will need to find out all the records in this table which falls within 3 months from the current date,
And (this one is tricky) only the records with overlapped date ranges where the Sum(Allocation %) > 100.
Please help me to come up with a query.
This is the table schema.
```
Table (ResourceAssignment)
- ResourceAssignmentID (PK)
- ResourceID (FK)
- Assigned To (FK)
- Start Date
- End Date
- Allocation %
```
I will basically need to find all over allocated resources within a certain period (from current day to 3 months).
Thanks in advance! | 2013/07/17 | [
"https://Stackoverflow.com/questions/17708518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1336907/"
] | You have two general solutions. Which is best is dependent on the size of ResourceAllocation, the frequency of conflicts, and how you intend to present the data.
**Solution 1: Make a list of dates in the next 3 months and join against that to identify which dates are overallocated**
```
WITH
datelist AS (
SELECT CAST(GETDATE() AS date) [d] UNION ALL SELECT DATEADD(day,1,[d]) FROM datelist WHERE [d] < DATEADD(month,3,GETDATE())
),
allocations AS (
SELECT *,SUM([Allocation %]) OVER(PARTITION BY [ResourceID],[d]) AS [Total Allocation %]
FROM datelist
INNER JOIN ResourceAssignment ON ([d] BETWEEN [Start Date] AND [End Date])
)
SELECT *
FROM allocations
WHERE [Total Allocation %] >= 100
```
**Solution 2: Use a range-conflict query with a self-join on ResourceAssignment**
```
SELECT *
FROM (
SELECT
t1.*,SUM(t1.[Allocation %]) OVER(PARTITION BY t1.[ResourceID]) AS [Total Allocation %]
FROM ResourceAssignment t1
INNER JOIN ResourceAssignment t2 ON (
t1.[ResourceID] = t2.[ResourceID] AND
t1.[ResourceAssignmentID] <> t2.[ResourceAssignmentID] AND
t1.[Start Date] < t2.[End Date] AND
t2.[Start Date] < t1.[End Date]
)
WHERE
t1.[Start Date] <= CAST(GETDATE()+30 as date) AND
t2.[Start Date] <= CAST(GETDATE()+30 as date) AND
t1.[End Date] > CAST(GETDATE() as date) AND
t2.[End Date] > CAST(GETDATE() as date)
) t
WHERE [Total Allocation %] >= 100
``` | I assume that Start Date and End date are formatted as Date time or Date.
I'm not sure if you are trying to determine if the start date records fall within the past 3 months or the end date records.
Also you'll need a limit to determine the Sum(Allocation %). What unique records are you wanting to sum. Since you want to Sum Allocation % and then select only the ones that are greater than 100, you have to figure out which ones to pull then to sum.
You'll want to accomplish this using a With statement or creating sub "tables" (queries) that pull the information you want in stages. I'll present the subquery statements.
Written for Sql-Server 2008 R2
First Select data that is within the Past 3 months
```
Select ResourceAssignmentID, ResourceID, [Assigned To], [Allocation %]
From ResourceAssignment
Where [Start Date] >= dateadd(Month,-3,Now)
```
Then using this data you want to Sum the Allocation %. (I am assuming based on the combination of the 2 foreign keys)
```
Select Query1.ResourceID, Query1.[Assigned To], sum(Query1.[Allocation %]) as Sumofallocation
From
(Select ResourceAssignmentID, ResourceID, [Assigned To], [Allocation %]
From ResourceAssignment
Where [Start Date] >= dateadd(Month,-3,Now)) Query1
Group By Query1.ResourceID, Query1.[Assigned To], sum(Query1.[Allocation %])
```
You may be able to add the Where statement before the group by to filter out for your >100 requirement, but I would just add another Select statement to pull it all together
```
Select * From
(Select Query1.ResourceID, Query1.[Assigned To], sum(Query1.[Allocation %]) as Sumofallocation
From
(Select ResourceAssignmentID, ResourceID, [Assigned To], [Allocation %]
From ResourceAssignment
Where [Start Date] >= dateadd(Month,-3,Now)) Query1
Group By Query1.ResourceID, Query1.[Assigned To], sum(Query1.[Allocation %])
) Query2
Where Query2.Sumofallocation > 100
```
Also, it seems like you are working on a project management type program. Would Microsoft Project not work? You would be able to see who's over allocated in whatever time-frame you wished. If you have multiple projects, you could just merge them into one large Project file and see it that way...
Anyway, I hopes this helps. The SQL might not be perfect, but it should point you in a workable direction. |
21,598,804 | I have a json file with all link images from specific folder like this
```
["http://img1.png","http://img2.png","http://img3.png","http://img4.png"]
```
And I want to create a `<ul>` list with this but I don't know how.
Can someone help me with a small example?
Thanks | 2014/02/06 | [
"https://Stackoverflow.com/questions/21598804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3115043/"
] | Using json you can connect <http://shared1.ad-lister.co.uk/GetImagesList.aspx?contextId=c9d56aca-506c-40be-9068-037d0fba62c9&Folder=_design/car-marques>
```
$.post("http://shared1.ad-lister.co.uk/GetImagesList.aspx?contextId=c9d56aca-506c-40be-9068-037d0fba62c9&Folder=_design/car-marques", function (json) {
var html = '<ul>';
for (var i = 0; i < json.length; i++) {
html += '<li><img src="'+json[i]+'" /></li>';
}
html += '</ul>';
$('.contents').html(html);
});
``` | ```
var urls = ["http://img1.png","http://img2.png","http://img3.png","http://img4.png"];
var ul = $('<ul>');
for (var i = 0; i < urls.length; i++) {
var li = $('<li>');
li.appendTo(ul);
$('<img>').attr('src', urls[i]).appendTo(li);
}
var container = $('#container');
container.append(ul);
``` |
45,384,391 | How to use findOne() in Yii2 without using any parameters?
i mean querying like
"select top 1 \* from table1" or
"select \* from table1 LIMIT 1"
Thanks! | 2017/07/29 | [
"https://Stackoverflow.com/questions/45384391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8384514/"
] | query like below
```
$user = User::find()->one();
``` | Also query `$user = User::find()->limit(1)->one();` working faster then `$user = User::find()->one();` |
10,756 | >
> **Possible Duplicate:**
>
> [Will my new HTML5 website decrease my Google ranking?](https://webmasters.stackexchange.com/questions/9936/will-my-new-html5-website-decrease-my-google-ranking)
>
>
>
For example, currently, I understand that search engines give the most emphasis to `h1` elements, followed by `h2`, etc. However, it is valid in HTML5 to replace what is conventionally `h2` with `h1`, encased in `article` tags.
But are search engines such as Google updated to become "HTML5 friendly"? Or will my site somehow be penalized by some algorithm for "`h1`ing incorrectly"? | 2011/03/16 | [
"https://webmasters.stackexchange.com/questions/10756",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/-1/"
] | The HTML specs say that user agents that don't understand an HTML tag are to ignore it. Assuming that search engine bots follow this spec, and they do, then using HTML5 tags that aren't yet recognized by the search engines are ignored and shouldn't hurt your rankings.
In your example the `<h1>` tag is not being used incorrectly. It just is wrapped in a new tag that may or may not be recognized by the search engines. But that won't hurt you as that tag simply has no semantic meaning for now. But when it does you're rankings may benefit because of the increased semantic meaning. So use it without worry and with the expectations that in the future this will help you.
(One possible exception is the proposed multiple heading tag thing where you are allowed to have multiple `<h1>` tags on a page. I'd avoid this for now since that could cause issues as doing this previously could only be construed as an error in markup or manipulation of the SERPs. Obviously that may change). | There's an article [here](http://www.redsauce.com/update-on-html5-seo-and-google-how-html5-may-affect-your-page-rankings-5759) about that. It basically says that Google crawlers are used to not being able to parse all HTML markup – be it from broken HTML, embedded XML content or from the new HTML5 tags. And there is no special attention for HTML5.
So as far as understand Google does not penalize sites for using HTML5 nor it rewards using it. |
25,344 | I'm looking for a way to handle a grid field with the channel entry API.
Documentation has nothing, and could barely find anything else online about except for this: [Inserting a new Grid row using the API](https://expressionengine.stackexchange.com/questions/22448/inserting-a-new-grid-row-using-the-api), but there is no solution through the API.
Has anyone figured this one out yet? | 2014/08/27 | [
"https://expressionengine.stackexchange.com/questions/25344",
"https://expressionengine.stackexchange.com",
"https://expressionengine.stackexchange.com/users/1994/"
] | I'm pretty sure you can just pass in the fieldname the row and column like
```
$data['field_id_X'][rows][new_row_1][col_id_1] = 'row 1';
$data['field_id_X'][rows][new_row_2][col_id_1] = 'row 2';
```
Just increment new\_row\_x as needed and match up your col\_id\_x numbers | Very close to @johnathan-waters answer I imported new grid rows using this code
`$data['field_id_X']['rows']['new_row_Y']['col_id_Z'] = 'value';` |
166 | There are tons that are out there for recording routes, and such. There's also the physical mounting. Is the iPhone actually good/useful for bikers? | 2010/08/25 | [
"https://bicycles.stackexchange.com/questions/166",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/105/"
] | A lot of the jogging apps will work well for on the bicycle as well, since most of the data collection is done via the GPS. As for the mounts, I've seen [this one](http://www.thinkgeek.com/electronics/cell-phone/df25/) used a bit and it looks fairly sturdy. Not sure about the attachment to the bars, though.
I would just be careful with the kind of riding you're doing. An iPhone costs $400 to $600 dollars if you aren't signing a new contract, so if you're doing mountain biking, I would stray away from it. Anything mounted to your bars needs to be able to take a beating. If I take my iPhone on a mountain ride, I usually have it tucked way deep in my Camelbak.
For my bikes, I use a simple bike computer (for mileage, time moving, etc), and an iPod Shuffle (first generation) for music. The Shuffle actually attaches to the back of my helmet quite well, keeping it and the headphones cables out of my way. | Ride with GPS app is one of my favorites.
<https://ridewithgps.com/>
You can use the website to create routes, and the app to follow them. It's the best route creation and editing solution I've found. It also integrates with Wahoo Elemnt and Wahoo RFLKT+ computers.
It also allows you to record a ride whether you are following a route or not. It will try to add photos to your ride record if you take them with your phone during the ride.
The website will also let you export as .gpx or .tcx with turn-by-turn prompts and cues. |
37,800,195 | I have a jenkinsfile dropped into the root of my project and would like to pull in a groovy file for my pipeline and execute it. The only way that I've been able to get this to work is to create a separate project and use the `fileLoader.fromGit` command. I would like to do
```groovy
def pipeline = load 'groovy-file-name.groovy'
pipeline.pipeline()
``` | 2016/06/13 | [
"https://Stackoverflow.com/questions/37800195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4227839/"
] | If you have pipeline which loads more than one groovy file and those groovy files also share things among themselves:
**JenkinsFile.groovy**
```
def modules = [:]
pipeline {
agent any
stages {
stage('test') {
steps {
script{
modules.first = load "first.groovy"
modules.second = load "second.groovy"
modules.second.init(modules.first)
modules.first.test1()
modules.second.test2()
}
}
}
}
}
```
**first.groovy**
```
def test1(){
//add code for this method
}
def test2(){
//add code for this method
}
return this
```
**second.groovy**
```
import groovy.transform.Field
@Field private First = null
def init(first) {
First = first
}
def test1(){
//add code for this method
}
def test2(){
First.test2()
}
return this
``` | You have to do `checkout scm` (or some other way of checkouting code from SCM) before doing `load`. |
259 | There are many things you have to do/consider when you want to enable HTTP compression on IIS 6.0 (Windows Server 2003).
Can somebody please provide a comprehensive list of the actions you have to take in order to enable HTTP compression properly? | 2009/04/30 | [
"https://serverfault.com/questions/259",
"https://serverfault.com",
"https://serverfault.com/users/45/"
] | Does anyone know how you TEST if your IIS6 server is sending zipped content?
Is there a "test your website" site out there that can tell you??
Can you use Firefox to tell you (firebug or some other plug in?)
**[UPDATE]**
Using YSlow with FireBug. Click on the "components" tab and it shows raw and gzipped sizes. | I played around with getting this set-up on our server (IIS 6) and while enabling it was fairly simple, it didn't give us as much control over it as I needed. I ended up purchasing [httpZip from port80 Software](http://www.port80software.com/products/httpzip/). It made it trivial to enable and configure it. It looks like IIS 7 is much better about this. |
66,440,755 | I'm looking to take one table (Name to Dept) and look up corresponding entries on a second (Dept to Plan) to get a third column that's "flat", showing all plans each name corresponds to.
I have:
| Name | Dept |
| --- | --- |
| a | x |
| b | y |
| c | z |
| d | z |
and
| Dept | plan |
| --- | --- |
| x | 1 |
| x | 2 |
| y | 2 |
| z | 1 |
| z | 3 |
I want:
| Name | Plan |
| --- | --- |
| a | 1 |
| a | 2 |
| b | 2 |
| c | 1 |
| c | 3 |
| d | 1 |
| d | 3 |
I keep getting hung up on trying to get multiple entries for multiple names within a single dept.
Thanks! | 2021/03/02 | [
"https://Stackoverflow.com/questions/66440755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15315103/"
] | You can use the [**`onGloballyPositioned`**](https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/OnGloballyPositionedModifier) modifier:
```
var size by remember { mutableStateOf(IntSize.Zero) }
Box(Modifier.onGloballyPositioned { coordinates ->
size = coordinates.size
}) {
//...
}
```
Also the [`Canvas`](https://developer.android.com/reference/kotlin/androidx/compose/ui/graphics/Canvas.html) has a [`DrawScope`](https://developer.android.com/reference/kotlin/androidx/compose/ui/graphics/drawscope/DrawScope) which has the [`size`](https://developer.android.com/reference/kotlin/androidx/compose/ui/graphics/drawscope/DrawScope#size) property.
```
Canvas() {
val canvasSize = size
}
``` | You can do this several ways. `BoxWithConstraints` does not always return correct size because as the name describes it returns `Constraints`. **Max width or height** of `Constraints` doesn't always match **width or height** of your Composable.
Using Modifier.onSizeChanged{size:IntSize} or Modifier.onGloballyPositioned{} with a mutableState causes another recomposition which might cause change in UI on next frame.
You can check [this answer](https://stackoverflow.com/questions/73354911/how-to-get-exact-size-without-recomposition/73357119#73357119) out how to get exact size without recomposition and exact size on every occasion. |
25,078,497 | There is a report contains 1000s of pages of data.Is there any way to make a button on the first page of the report so that ,if click on the button it goes to the end of the pages.
Is there any expression to be written,with out writing the vb.net code? | 2014/08/01 | [
"https://Stackoverflow.com/questions/25078497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1254579/"
] | There is a button like that in SSRS (you can also type page number in the box and press enter):

EDIT:
You can add a bookmark at the end of your report and then make a textbox which will jump to it (textbox properties->Action->mark "go to bookmark" and select the bookmark you made. I am not sure, however, if it works well in excel. | There are 2 ways of reaching the last page or the data on the last page:
>
> **Sol 1.** @kyooryu has already mentioned above in his solution along with a screenshot.
>
>
> **Sol 2.** You can freeze the header and set the display result to show the data on a single page. This way you will not have multiple pages and you can directly hit the end button from keyboard on the report manager to reach the bottom result set. Freezing the header will help you in identifying the column names.
>
>
> |
16,569,449 | I'm passing a listview in to an onselect but theres a couple of ways it's called from different listviews. So i'm trying to work out which listview is being clicked.
I thought I could do the following however the string thats returned is like com.myapp.tool/id/32423423c (type thing) instead of lvAssets.
Here is what I've got:
```
@Override
public void onNumberRowSelect(ListView listview, clsNameID stat) {
if(listview.getAdapter().toString().equals("lvGenericAssets")){
} else if(listview.getAdapter().toString().equals("lvAssets")){
} else {
Functions.ShowToolTip(getApplicationContext(),
listview.getAdapter().toString());
}
}
``` | 2013/05/15 | [
"https://Stackoverflow.com/questions/16569449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/900659/"
] | The `urlExists` function doesn't have a `return` statement at all (so it will always return `undefined`).
The functions that do are event handlers assigned to the ajax handler. They won't even fire until after the HTTP response is received, which will be after the `urlExists` function has finished running and returned whatever it is going to return.
If you want to do something in reaction to the ajax response being processed, then you have to do it in the event handlers. You can't return to the caller because the it will have finished and gone away.
An extended explanation of this can be found in answers to [this question](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call). Your example doesn't care about returning the actual data, but the principles are the same. | the `success` and `error` functions are callback methods. They are not part of the function `urlExists`. Rather they are part of the parameters passed to `$.ajax`. |
20,163,753 | Instead of writing such lines again and again, what should be the professional way & optimized way to write this same code? Please help
```
$(function(){
$('<img src="map/map_slice_1.jpg"/>').appendTo('#map_slice_1');
$('<img src="map/map_slice_2.jpg"/>').appendTo('#map_slice_2');
$('<img src="map/map_slice_3.jpg"/>').appendTo('#map_slice_3');
$('<img src="map/map_slice_4.jpg"/>').appendTo('#map_slice_4');
$('<img src="map/map_slice_5.jpg"/>').appendTo('#map_slice_5');
$('<img src="map/map_slice_6.jpg"/>').appendTo('#map_slice_6');
$('<img src="map/map_slice_7.jpg"/>').appendTo('#map_slice_7');
$('<img src="map/map_slice_8.jpg"/>').appendTo('#map_slice_8');
});
``` | 2013/11/23 | [
"https://Stackoverflow.com/questions/20163753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1977954/"
] | I would do something like this :
```
$(function () {
var i = 0;
while (i++ < 8) {
$('#map_slice_' + i).append(
'<img src="map/map_slice_' + i + '.jpg"/>'
);
}
});
``` | try
```
$(function(){
for (var i=0; i<8; i++)
{
$('<img src="map/map_slice_" + i + ".jpg"/>').appendTo('#map_slice_' + i);
}
});
``` |
41,722,534 | I am trying to collaborate 3 queries to perform arithmetic operation. The queries are shown in
```
(SELECT ITEM_ID,ISNULL(SUM(REC_GOOD_QTY),0)
FROM INVENTORY_ITEM
WHERE COMPANY_ID = 1
AND INVENTORY_ITEM.COMPANY_BRANCH_ID = 1
AND INVENTORY_ITEM.INV_ITEM_STATUS = 'Inward'
AND GRN_DATE < CAST('2017-01-10 00:00:00.0' AS DATETIME)
GROUP BY INVENTORY_ITEM.ITEM_ID) -
(SELECT ITEM_ID, SUM ( TOTAL_LITRE )
FROM STOCK_REQUISITION_ITEM B, STOCK_REQUISITION A
WHERE A.ID = B.REQUISITION_ID
AND A.COMPANY_ID = 1
AND A.REQ_FROM_BRANCH_ID = 1
AND A.REQUISITION_DATE < CAST('2017-01-10 00:00:00.0' AS DATETIME)
GROUP BY B.ITEM_ID) +
(SELECT ITEM_ID, SUM ( RETURN_QUANTITY )
FROM STOCK_RETURN_ITEM B, STOCK_RETURN A
WHERE A.ID = B.STOCK_RETURN_ID
AND A.COMPANY_ID = 1
AND A.COMPANY_BRANCH_ID = 1
AND A.RETURN_DATE <= CAST('2017-01-10 00:00:00.0' AS DATETIME)
GROUP BY B.ITEM_ID)
```
I am getting this error.
>
> [Err] 42000 - [SQL Server]Incorrect syntax near '-'.
>
> 42000 - [SQL Server]Incorrect syntax near '+'
>
>
> | 2017/01/18 | [
"https://Stackoverflow.com/questions/41722534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4008515/"
] | This can happen for one of two reasons:
Firstly, either the `fromDate` or the `toDate` is out of that range, or (most likely):
One of your date variables (either `fromDate` or `toDate`) could not be parsed by the `TryParse()`. When this happens, the date is set to the default `C#` value of `0001-01-01`.
In `SQL Server` a `DATETIME` datatype can only hold values from `1753-01-01` to `9999-12-31`, and the `0001-01-01` that was being passed is out of range.
Check the value of the strings being parsed prior to execution. | Well, `SqlDbType.DateTime` has a value ranging from January 1, 1753 to December 31, 9999, so you should try to use `SqlDbType.DateTime2` instead.
Also, no point of parsing the `DateTimePicker.Text` property to `DateTime`, since it already has a DateTime property called `Value`.
Try this instead:
```
SqlDataAdapter da3 = new SqlDataAdapter("SELECT Bill_Date,Name,Item,Item_Code,MRP, Quantity,Amount as Total, Amount_After_Discount as Grand_Total From POS LEFT JOIN Customers ON POS.Customer=Customers.Customer_Id WHERE Bill_Date Between @From AND @To", con);
da3.SelectCommand.Parameters.Add("@From", SqlDbType.DateTime2).Value = dateTimePicker_FromByDateSaleReport.Value;
da3.SelectCommand.Parameters.Add("@To", SqlDbType.DateTime2).Value = dateTimePicker_ToByDateSaleReport.Value;
DataTable dt3 = new DataTable();
da3.Fill(dt);
dgv_ByDateSaleReport.DataSource = dt3;
``` |
54,459,442 | I'm trying to create a JupyterLab extension, it uses typescript.
I've successfully added the package "@types/node" allowing me to use packages such as 'require('http')'.
But as soon as I try to use child process, using 'require("child\_process")' I get the following error when trying to build the extension.
```
ModuleNotFoundError: Module not found: Error: Can't resolve 'child_process' in '/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/jupyerlab_xkdc/lib'
at factory.create (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/webpack/lib/Compilation.js:535:10)
at factory (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/webpack/lib/NormalModuleFactory.js:397:22)
at resolver (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/webpack/lib/NormalModuleFactory.js:130:21)
at asyncLib.parallel (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/webpack/lib/NormalModuleFactory.js:224:22)
at /home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/neo-async/async.js:2825:7
at /home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/neo-async/async.js:6886:13
at normalResolver.resolve (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/webpack/lib/NormalModuleFactory.js:214:25)
at doResolve (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/enhanced-resolve/lib/Resolver.js:184:12)
at hook.callAsync (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/enhanced-resolve/lib/Resolver.js:238:5)
at _fn0 (eval at create (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:15:1)
at resolver.doResolve (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js:37:5)
at hook.callAsync (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/enhanced-resolve/lib/Resolver.js:238:5)
at _fn0 (eval at create (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:15:1)
at hook.callAsync (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/enhanced-resolve/lib/Resolver.js:238:5)
at _fn0 (eval at create (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:12:1)
at resolver.doResolve (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js:42:38)
at hook.callAsync (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/enhanced-resolve/lib/Resolver.js:238:5)
at _fn41 (eval at create (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:381:1)
at resolver.doResolve (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/enhanced-resolve/lib/ModuleKindPlugin.js:23:37)
at hook.callAsync (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/enhanced-resolve/lib/Resolver.js:238:5)
at _fn0 (eval at create (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:15:1)
at hook.callAsync (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/enhanced-resolve/lib/Resolver.js:238:5)
at _fn0 (eval at create (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:15:1)
at args (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/enhanced-resolve/lib/forEachBail.js:30:14)
at hook.callAsync (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/enhanced-resolve/lib/Resolver.js:238:5)
at _fn0 (eval at create (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:15:1)
at resolver.doResolve (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js:37:5)
at hook.callAsync (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/enhanced-resolve/lib/Resolver.js:238:5)
at _fn0 (eval at create (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:15:1)
at hook.callAsync (/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/enhanced-resolve/lib/Resolver.js:238:5) resolve 'child_process' in '/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/jupyerlab_xkdc/lib' Parsed request is a module using description file: /home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/jupyerlab_xkdc/package.json (relative path: ./lib)
Field 'browser' doesn't contain a valid alias configuration
resolve as module
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/jupyerlab_xkdc/lib/node_modules doesn't exist or is not a directory
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/node_modules doesn't exist or is not a directory
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/node_modules doesn't exist or is not a directory
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/node_modules doesn't exist or is not a directory
/home/fionn/anaconda3/envs/jupyterlab-ext/share/node_modules doesn't exist or is not a directory
/home/fionn/anaconda3/envs/jupyterlab-ext/node_modules doesn't exist or is not a directory
/home/fionn/anaconda3/envs/node_modules doesn't exist or is not a directory
/home/fionn/anaconda3/node_modules doesn't exist or is not a directory
/home/fionn/node_modules doesn't exist or is not a directory
/home/node_modules doesn't exist or is not a directory
/node_modules doesn't exist or is not a directory
looking for modules in /home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/jupyerlab_xkdc/node_modules
using description file: /home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/jupyerlab_xkdc/package.json (relative path: ./node_modules)
Field 'browser' doesn't contain a valid alias configuration
looking for modules in /home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules
using description file: /home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/package.json (relative path: ./node_modules)
Field 'browser' doesn't contain a valid alias configuration
using description file: /home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process/package.json (relative path: .)
no extension
Field 'browser' doesn't contain a valid alias configuration
using description file: /home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/jupyerlab_xkdc/package.json (relative path: ./node_modules/child_process)
no extension
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process is not a file
.wasm
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/jupyerlab_xkdc/node_modules/child_process doesn't exist
.wasm
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process.wasm doesn't exist
.mjs
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/jupyerlab_xkdc/node_modules/child_process.wasm doesn't exist
.mjs
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process.mjs doesn't exist
.js
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/jupyerlab_xkdc/node_modules/child_process.mjs doesn't exist
.js
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process.js doesn't exist
.json
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/jupyerlab_xkdc/node_modules/child_process.js doesn't exist
.json
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process.json doesn't exist
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/jupyerlab_xkdc/node_modules/child_process.json doesn't exist
as directory
existing directory
use ./index.js from main in package.json
using description file: /home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process/package.json (relative path: .)
Field 'browser' doesn't contain a valid alias configuration
as directory
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/jupyerlab_xkdc/node_modules/child_process doesn't exist
using description file: /home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process/package.json (relative path: ./index.js)
no extension
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process/index.js doesn't exist
.wasm
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process/index.js.wasm doesn't exist
.mjs
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process/index.js.mjs doesn't exist
.js
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process/index.js.js doesn't exist
.json
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process/index.js.json doesn't exist
as directory
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process/index.js doesn't exist
using path: /home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process/index
using description file: /home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process/package.json (relative path: ./index)
no extension
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process/index doesn't exist
.wasm
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process/index.wasm doesn't exist
.mjs
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process/index.mjs doesn't exist
.js
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process/index.js doesn't exist
.json
Field 'browser' doesn't contain a valid alias configuration
/home/fionn/anaconda3/envs/jupyterlab-ext/share/jupyter/lab/staging/node_modules/child_process/index.json doesn't exist error Command failed with exit code 1.
```
I've googled around but still have no idea what to do to resolve this issue.
Any pointers or info at all would be greatly appreciated.
My packages.json file.
```
{
"name": "jupyerlab_xkdc",
"version": "0.1.0",
"description": "Short description",
"keywords": [
"jupyter",
"jupyterlab",
"jupyterlab-extension"
],
"homepage": "https://github.com/my_name/myextension",
"bugs": {
"url": "https://github.com/my_name/myextension/issues"
},
"license": "BSD-3-Clause",
"author": "Fionn McKnight",
"files": [
"lib/**/*.{d.ts,eot,gif,html,jpg,js,js.map,json,png,svg,woff2,ttf}",
"style/**/*.{css,eot,gif,html,jpg,json,png,svg,woff2,ttf}"
],
"main": "lib/index.js",
"types": "lib/index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/my_name/myextension.git"
},
"scripts": {
"build": "tsc",
"clean": "rimraf lib",
"prepare": "npm run clean && npm run build",
"watch": "tsc -w"
},
"dependencies": {
"@jupyterlab/application": "^0.19.1",
"@jupyterlab/apputils": "^0.19.1",
"@phosphor/coreutils": "^1.3.0",
"@phosphor/messaging": "^1.2.2",
"@phosphor/widgets": "^1.6.0",
"@types/jquery": "^3.3.29",
"@types/node": "^10.12.19",
"child_process": "^1.0.2",
"npm": "^6.7.0"
},
"devDependencies": {
"@types/node": "^10.12.19",
"rimraf": "^2.6.1",
"typescript": "~3.1.1"
},
"jupyterlab": {
"extension": true
}
}
``` | 2019/01/31 | [
"https://Stackoverflow.com/questions/54459442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1904282/"
] | In newer versions I used:
```
// webpack.config.js
...,
resolve: {
extensions: [".ts", ".js"],
fallback: {
"child_process": false,
// and also other packages that are not found
}
},
``` | I stayed blocked for a couple of times on that.
As far I understood, it seems impossible to execute some child\_process ( which is literally executing some cmd ) from the browser, which also makes sense at some point.
The solution given works for me, adding below to `package.json` is working
```
"browser": { "fs": false, "child_process": false }
```
**But** don't add it on your package.json (mean the one of your app), but instead the `package.json` from the lib then you are using where the
`require('child_process')` is.
That's being done, this fixe just said to the compiler that's it's ok to not have a lib even if this one is required somewhere on your code or dependencies (rather to crash ). If you want to use child\_process from your App I am afraid that it's complicated.
Here is the [source](https://github.com/wagenaartje/neataptic/issues/57#issuecomment-387303055) of my post |
3,266,117 | I am working on form and I am looking for a free calendar/date/timestamp app that i can include in my form. basically, in the input text, i want users to click on the calendar icon and pick a date and a time stamp. that value should populate in the input text.
my next question is, in my mysql db, i am calling this field as "datetime", so i am hoping the values can be written in the db.
i am working with php and mysql.
thanks. | 2010/07/16 | [
"https://Stackoverflow.com/questions/3266117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/255391/"
] | For the user interface you are describing to be added to the input field, jQuery Datepicker springs to mind.
<http://jqueryui.com/demos/datepicker/>
You'll need to include the jQuery library as well as the jQuery UI library. You can use the 'build your download' link and documentation on the jQuery library page to get a fully themed ui download to suit your design needs.
You'll need to make your form post to a server-side script that will take the field and insert it into the DB. Be careful - mysql date time is in the following format - YYYY-MM-DD HH:mm:SS. You can use strtotime and date to format the input from jQuery. After sanitizing the input, you could do something simple like:
```
date('Y/m/d H:i:s', strtotime($_POST['date']) )
```
You can use this to make sure in your server script that the date/time is in the proper format before it goes in the database. | This can be done with GUI
Take a look at jQuery UI Date-picker: <http://jqueryui.com/demos/datepicker/>
Regards to the date conversion there is plenty of functions to help you
<http://www.php.net/manual/en/ref.datetime.php> |
15,286 | Heatmaps are one of the best tools we have to mesure the impact of a design, not just in [UX terms](http://www.squidoo.com/heat-map) but also in [marketing/conversion](http://www.thoughtmechanics.com/analyze-the-heat-map-for-better-ctr-and-sales-conversions/) terms.
I've found that most of the free or less-expensive solutions are based on **tracking the position of the cursor instead of tracking the eyes of the viewer.**
I can understand the obvious technology restraint tracking eyeballs implies, but the question is: **Are cursor-generated heatmaps reliable?** Or rather they make an impressive picture but don't faithufully represent the areas of real interest?
Side note: [Here](http://www.webadicto.net/blogs/webadicto/post/2010/10/11/10-Herramientas-Heatmap-gratuitas-que-te-ayudaran-a-mejorar-tu-web.aspx) is a list of 10 free heatmap applications (Spanish site but English links). I'd appreciate mentions to any other cursor and eye-tracking software to generate heatmaps. | 2011/12/21 | [
"https://ux.stackexchange.com/questions/15286",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/5058/"
] | This is a question I've pondered myself. One major problem with heatmaps that I can think of is that I often move my cursor out of the way of what I want to look at, whether they be images, video, or text. So aside from when I'm actually moving the mouse to click on a link or button, I usually place my cursor in an empty area like the page margins to not block any content.
There's also little evidence that people will move their cursor towards non-clickable page elements which they're interested in or are focused on.
So it's most-likely only going to reveal what your most-often-clicked elements are, and maybe also highlight the typical path that the cursor travels to go between these elements. So if you have a CTA and a login button that are very popular with visitors, the heatmap might show a region between the two that is highly trafficked because it's the most direct route between two frequently clicked items. But that doesn't mean users are particularly drawn to the content in that region.
Maybe cursor-movement-generated heatmaps take these issues into account some how (I believe some marketing materials for mouse-tracking heatmap services do show side-by-side comparisons between eye-tracking-generated heatmaps and their own to show that their heatmaps are a reliable substitute). But if they don't, the results could be very misleading for people who try to interpret the heatmaps the same way as eye-tracking heatmaps. | Random cursor movements are generally an indication that the user doesn't actually understand what to do on a page. |
1,430,883 | If the PHP Engine is already in the middle of executing a script on the server what would happen to other simultaneous browser requests to the same script?
* Will the requests be queued?
* Will they be ignored?
* Will each request have its own script
instance?
* Any other possibility? | 2009/09/16 | [
"https://Stackoverflow.com/questions/1430883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142299/"
] | If 2 clients calls the server at the same time, the server is most probably able to reply both clients almost simultaneously. The clients here I define them to the browser level.
Meaning to say that on the same machine, if you're using 2 browsers to load the same website/page at the same time, both should be loaded at the same time.
however since we're talking about PHP, you need to take special notes about sessions. If your pages use sessions, the server only serve one page at a time. This is because session file will be locked, until a script exits.
Look at this example. The 2 files are loaded from the same session aka same browser same user.
```
scripta.php requested scripta.php served
------+---+---------------------------------+------------------------>
scripta.php started
scriptb.php requested scriptb.php started
---------------+-------------------------------+-----------------+--->
scriptb.php served.
```
Notice that scriptb.php is only started after scripta.php is served. this is because when scripta.php started, the session file is locked to other scripts so that scripta.php can write to the session file. When scripta.php completes, the session file is unlocked and thus other scripts are able to use it. Thus scriptb.php will wait until the session file is freed then it will lock the session file and use it.
This process will keep repeating to prevent multiple scripts writing to the same session file causing delays. Thus it is recommended to call [`session_write_close`](http://php.net/session_write_close)() when you are no longer using the session, especially on a website using many iframes or AJAX. | Just ran into this myself. Basically you need to call `session_write_close()` to prevent single user locking. Make sure once you call `session_write_close()` you don't try and modify any session variables though. Once you call it, treat sessions as read-only from then on. |
884,656 | I need to use an old Java applet for a certain website, but newer Java versions cannot run it, as it has a self-signed certificate. Reading on Oracle's Deployment Guide, I need to make my own deployment .JAR, with a proper certificate signing (not self signed), just to create the exception I need to run applets from a single domain.
I have found that there is a `%userprofile%\appdata\LocalLow\Sun\Java\Deployment\security\exception.sites` file, obviously one for each user. In there, one per line, is a list of domains I can set to exclude from NOT being executed. When I add the domain name, the user gets a single prompt, then it just allows that domain for that user. Great.
I know I could add this file to the **Default** user profile, for any new users being created. Unfortunately, I do not think that removing every user's profile from each of the systems is the right way to go. I can push commands to computers, but the commands run as my user - I can't use %USERPROFILE% for this. I do not want to put it in my login script, as I do not want the file getting large for users who constantly log in and off of systems. I also only want the single domain *added* to whatever is there, without wiping out the user's preferences that may already exist.
Because I do not want to wipe out their preferences, I thought of doing something along the lines of `echo http://www.example.com >> %userprofile%\appdata\LocalLow\Sun\Java\Deployment\security\exception.sites`, but that won't work, as it will keep adding to the file.
What can I do to add the list to the Exceptions rule, but only if the rule does not exist already? | 2015/02/11 | [
"https://superuser.com/questions/884656",
"https://superuser.com",
"https://superuser.com/users/24010/"
] | Just add the following files to `C:\Windows\Sun\Java\Deployment` folder.
**deployment.properties:**
```
deployment.user.security.exception.sites=C:/Windows/Sun/Java/Deployment/exception.sites
deployment.system.config.mandatory=True
```
**deployment.config:**
```
deployment.system.config=file:///C:/Windows/Sun/Java/Deployment/deployment.properties
deployment.system.config.mandatory=True
```
**exception.sites:**
```
http://some.trusted.site/
https://another.trusted.site/
```
This would affect all users of this machine.
Via:
* [Java 7u51 – System Wide Exception Site List an article posted on Systemsynergy](http://systemcentersynergy.com/java-7u51-system-wide-exception-site-list/)
* [Oracle Java SE Documentation - Deployment Configuration File and Properties](http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/jcp/properties.html)
* [Oracle Java SE Documentation - Exception Site List](http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/security/exception_site_list.html) | The exceptions are store here, C:\Users{username}\AppData\LocalLow\Sun\Java\Deployment\security\exception.sites
Populate your file with what you want to add, copy it to a file share and use a logon script to copy the file for each user. This will make it to where users will not be able to add new sites.
Source: <http://www.experts-exchange.com/Programming/Languages/Java/Q_28518522.html> |
261,548 | In known wordlists like crackstation.lst there are random emails in the list. Why are they there? | 2022/04/26 | [
"https://security.stackexchange.com/questions/261548",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/275693/"
] | Presumably it's just people using their email address as their password.. | There are two main reasons:
**1. People using them for privacy**
Some people are privacy oriented, and they will create random looking email addresses for different services. This way it's not easy to link all of its personas based on the email address.
**2. They are fake and used to track leakage**
They are called [Copyright Traps](http://archives.maproomblog.com/2005/11/copyright_traps.php). They are most common on maps and dictionaries, so anyone copying data from them would copy the fake streets or words too, and the owner of the data would know for sure who copied its information.
On leaks, sometimes the leaker will add fake emails that aren't expected to be found anywhere, and if anyone buys the data and leaks it later, the original "owner" of the data can know for sure who leaked the list by searching the traps on the leaked data. |
7,732,705 | Does anybody know how I can get the URL of any open IE processes on a computer?
I don't need to manipulate the IE instance at all -- just get information about the page that's currently loaded.
Thanks! | 2011/10/11 | [
"https://Stackoverflow.com/questions/7732705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/789476/"
] | A simple solution, and it works:
<http://omegacoder.com/?p=63> | * Start IE yourself through automation (i.e `var oIE = WScript.CreateObject("InternetExplorer.Application", "IE_");`) and listen to `NavigateComplete2`.
* Peek inot ROT (running objects table) - I think IE documents should show up there - Win32/COM - <http://msdn.microsoft.com/en-us/library/ms684004(VS.85).aspx>
* Just find all IE windows and take text from address well (see MusiGenesis answer for that). |
9,954,775 | Maybe you easily said how to I provide table names and row counts?
Pseudo SQL:
```
for "select tablename from system.Tables" into :tablename
execute "select count(*) from ? into ?" using :tablename, :count
return row(:tablename, :count)
end for
```
Can you tell me show me this script in T-SQL? | 2012/03/31 | [
"https://Stackoverflow.com/questions/9954775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/362214/"
] | ```
-- Shows all user tables and row counts for the current database
-- Remove OBJECTPROPERTY function call to include system objects
SELECT o.NAME,
i.rowcnt
FROM sysindexes AS i
INNER JOIN sysobjects AS o ON i.id = o.id
WHERE i.indid < 2 AND OBJECTPROPERTY(o.id, 'IsMSShipped') = 0
ORDER BY o.NAME
``` | Try this
```
-- drop table #tmpspace
create table #tmpspace (
name sysname
, rows int
, reserved varchar(50)
, data varchar(50)
, index_size varchar(50)
, unused varchar(50)
)
dbcc updateusage(0) with NO_INFOMSGS
exec sp_msforeachtable 'insert #tmpspace exec sp_spaceused ''?'''
select * from #tmpspace
order by convert(int, substring(reserved, 1, charindex(' ', reserved))) desc, rows desc, name
```
Works on sql2000 too.
`dbcc updateusage` might take some time but results will be 100% actual. Skip it if you need speed over accuracy. |
11,457,192 | I have a header that needs to delay for a certain amount of time on page load, then fade out. [It can be tested here](http://[http://jsfiddle.net/yurcj/][1]). I also add the code:
**html**
```
<header id="main-header">
<div id="inner"></div>
</header>
```
**css**
```
#main-header {height: 70px;}
#inner {height: 70px; background: red;}
```
**javascript**
```
$(function() {
$('#inner').stop().delay(2300).animate({"opacity": "0"}, 1500);
$('#main-header').hover(
function() {$('#inner').stop().animate({"opacity": "1"}, 1000);},
function() {$('#inner').stop().animate({"opacity": "0"}, 1500);}
);
});
```
When the cursor hovers over the area, it will fade back in.
Everything works flawlessly if the user waits until the initial delay/fade out is complete, but I am having an issue when the cursor hovers over the header before the initial delay/fade out completes. See the link above.
I am thinking I need to delay the hover from initializing somehow for, in this case, 2300ms.. but if anyone has a better solution, I would appreciate it. Thank you! | 2012/07/12 | [
"https://Stackoverflow.com/questions/11457192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1521516/"
] | `remove_method` should work in most cases. But if your `alias_method` overwrites an existing method, you may need to save the original via a separate `alias_method` call.
```
# assuming :contains? is already a method
alias_method :original_contains?, :contains?
alias_method :contains?, :include?
```
Then to restore the original state:
```
alias_method :contains?, :original_contains?
remove_method :original_contains? # optional
```
Note also that modifying a class that's used in multiple threads is prone to race conditions. And if you're trying to disallow libs from using the alias, you can't prevent that if you're calling those libs' methods while the alias exists. We might see a way to do this in ruby 2.0: <http://yehudakatz.com/2010/11/30/ruby-2-0-refinements-in-practice/>
It would be helpful if you could say why you want to remove the alias. If the method name did not exist before, no other libs should be affected by your monkey-patch. Also, you should consider subclassing `String` (or delegating to a string instance) rather than patching `String`. | ```
def hello
puts "Hello World"
end
alias :hi :hello
hi #=> "Hello World"
undef hi
hi #=> NameError
hello #=> "Hello World"
```
EDIT: Note that this will only work on methods created on the `main` object. In order to enact this on a class, you'd need to do something like , `Hello.class_eval("undef hi")`
However, from a metaprogramming standpoint, when dealing with classes, I like the usage of `remove_method :hi` since it'll cause the method lookup to fall down and grab the method from a parent class.
```
class Nums < Array
def include?
puts "Just Kidding"
end
end
n = Nums.new
n << 4 #=> [4]
n.include? #=> "Just kidding"
Nums.class_eval("remove_method :include?")
n.include? 4 #=> true
Number.class_eval("undef include?")
n.include? 4 #=> NoMethodError
```
`remove_method` is much more meta friendly. |
2,551 | Is it **always** valid to use *make* as a verb which causes a change by force in the personality/emotions/behaviors of objects?
Is it **always** valid to use *become* before all human emotions/senses/adjectives to express a change?
Is there any general rule which one to use when? | 2013/02/14 | [
"https://ell.stackexchange.com/questions/2551",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/476/"
] | Here, *make* is used in a context of "to cause something":
*You **make** me cry* — meaning, I was not crying, but because of you I start.
*Become* is simply *"to change {one's own} state"*.
Imagine Alice sees a sad Bob. Alice tells a funny joke to Bob, and he becomes happy. The following sentences are all valid:
* *Alice **made** Bob happy*;
* *Bob **became** happy*;
* *Alice **made** Bob ~~to~~ (1) **become** happy*;
So, as you see, *to make* applies to a causing subject, while *to become* applies to an object that changes.
(1) Thanks to @StoneyB; *make* takes bare infinitive, so can't use *to* here. | "make" is a transitive verb, therefore it infers an action to the object.
On the other hand, "become" is an intransitive verb, denoting a change in state.
For example:
>
> "She will make the dinner."
>
>
>
and
>
> "The acorn that became the mighty oak."
>
>
>
Both have wide usage, but usually there are more specific verbs that can be used in place of "make" or "become". For example:
>
> "She will cook the dinner."
>
>
>
and
>
> "He turned into a fine young man."
>
>
> |
59,868,755 | So I'm trying to update `Date` from `DF1` with values from `Date` in `DF2`, whenever two columns `ColA` and `ColB` match, like so:
DF1:
```
ColA | ColB | Date
a | b | 12/22/2099
a | s | 12/22/2099
v | p | 12/22/2099
v | s | 12/22/2099
m | p | 12/22/2099
DF1 = pd.DataFrame( { 'ColA': ['a','a','v','v','m'], 'ColB': ['b','s','p','s','p'], 'Date': ['12/22/2099','12/22/2099','12/22/2099','12/22/2099','12/22/2099'] } )
```
DF2:
```
ColA | ColB | Date
a | b | 9/11/2022
a | s | 9/11/2022
v | s | 10/9/2022
m | p | 9/25/2022
DF2 = pd.DataFrame( { 'ColA': ['a','a','v','m'], 'ColB': ['b','s','s','p'], 'Date': ['9/11/2022','9/11/2022','10/9/2022','9/25/2022'] } )
```
To update the dates in `DF1` I did:
```
>>> DF1.set_index(['ColA','ColB'], inplace=True)
>>> DF1.update(DF2.set_index(['ColA','ColB']))
>>> DF1.reset_index(inplace=True) # to recover the initial structure
```
But when I print show the result of `DF1` I get this:
```
ColA | ColB | Date
a | b | 9/11/2022
a | s | 9/11/2022
v | s | 10/09/2022
v | p | 4101580800000000000
m | p | 9/25/2022
```
So.. obviously what is going on with this line:
```
v | p | 4101580800000000000
```
It shouldn't have been updated at all, since it only exists in `DF1` and not `DF2`? What could be going on here? | 2020/01/22 | [
"https://Stackoverflow.com/questions/59868755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4573703/"
] | run:
```
DF1['Date'] = DF1['Date'].apply(pd.to_datetime)
DF2['Date'] = DF2['Date'].apply(pd.to_datetime)
```
then `update` | You can convert date to string before your operations:
```
DF1['Date'].strftime('%m/%d/%Y')
DF2['Date'].strftime('%m/%d/%Y')
``` |
6,953,498 | I have had a brief search in StackOverflow, it seems that for a webstart application, if some of the JARs are signed and other are unsigned, it will end up treated as unsigned if unsigned code are accessed in call stack.
However, what if I only put resources (e.g. config files) in an unsigned JAR? (In fact I have some environment-dependent configs that I want to centralize in a separate JAR). If all other JARs containing "code" are signed, will it runs fine as signed application? | 2011/08/05 | [
"https://Stackoverflow.com/questions/6953498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/395202/"
] | I think you need to try using `-webkit-transform` or `webkitTransform` instead of `webkit-transform`. | ```
el.style["-webkit-transition"] = "-webkit-transform 500ms linear";
el.style["webkit-transform"] = "translate3d(30px, 30px, 0px)";
```
Your missing the - on the second line, this could be the problem. |
68,363,529 | I wish to have a fast way to deal with rowwise calculations where values of cells depend on values in previous rows of different columns, prefering vectorization over looping through individual rows (follow-up from [here](https://stackoverflow.com/questions/67707005/fast-way-to-calculate-value-in-cell-based-on-value-in-previous-row-data-table)).
Say I have the following dataset `dt` and a `constant` (loaded libraries are `data.table`, `dplyr` and `purrr`)
```
dt <- structure(list(var1 = c(-92186.7470607738, -19163.5035325072,
-18178.8396858014, -9844.67882723287, -16494.7802822178, -17088.0576319257
), var2 = c(-3.12, NA, NA, NA, NA, NA), var3 = c(1, NA, NA, NA,
NA, NA)), class = c("data.table", "data.frame"), row.names = c(NA,
-6L))
constant <- 608383
print(dt)
var1 var2 var3
1: -92186.747 -3.12 1
2: -19163.504 NA NA
3: -18178.840 NA NA
4: -9844.679 NA NA
5: -16494.780 NA NA
6: -17088.058 NA NA
```
The fast, vectorized equivalent of
```
for(i in 2:nrow(dt)){
prev <- dt[(i-1),]
dt[i, var2 := prev$var2 - var1/constant]
}
```
would be
```
dt %>%
mutate(var2 = accumulate(var1[-1], .init = var2[1], ~ .x - .y /constant))
```
But what if I want to include more columns in the calculation? In this example `var3`, but in the real dataset there are >10 columns. I wish the solution to keep that into account. Example for loop (desired output):
```
for(i in 2:nrow(dt)){
prev <- dt[(i-1),]
dt[i, var2 := prev$var2 + prev$var3 - var1/constant]
dt[i, var3 := prev$var1 + 0.1 * var2/constant]
}
print(dt)
var1 var2 var3
1: -92186.747 -3.120000e+00 1.00
2: -19163.504 -2.088501e+00 -92186.75
3: -18178.840 -9.218881e+04 -19163.52
4: -9844.679 -1.113523e+05 -18178.86
5: -16494.780 -1.295311e+05 -9844.70
6: -17088.058 -1.393758e+05 -16494.80
``` | 2021/07/13 | [
"https://Stackoverflow.com/questions/68363529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12284689/"
] | Though [My friend's output/strategy](https://stackoverflow.com/a/68364377/2884859) is fabulous, but since we cannot have two input vectors in baseR's `Reduce()` so I used this trick-
* Generated fresh values of `var1` in `data.frame()` inside the `Reduce()`
* Where you want to use current values of `var1` use `.y`
* where previous values were to be used use `.x$var1` instead.
* used formula where I'd require to use current generated value of any variable.
* rest is pretty clear I think.
* `accumulate = TRUE` is obvious becuase you want all intermediate values.
* Since output here will be a list, that is `rbind` using `do.call`
In base R you can do
```r
do.call(rbind, Reduce(function(.x, .y) {data.frame(var1 = .y,
var2 = .x$var2 + .x$var3 -.y/constant,
var3 = .x$var1 + 0.1 * (.x$var2 + .x$var3 -.y/constant)/constant)},
dt$var1[-1],
init = data.frame(var1 = dt$var1[1], var2 = -3.12, var3 = 1),
accumulate = TRUE))
var1 var2 var3
1 -92186.747 -3.120000e+00 1.00
2 -19163.504 -2.088501e+00 -92186.75
3 -18178.840 -9.218881e+04 -19163.52
4 -9844.679 -1.113523e+05 -18178.86
5 -16494.780 -1.295311e+05 -9844.70
6 -17088.058 -1.393758e+05 -16494.80
```
which can be emulated in tidyverse/purrr as follows
```
library(purrr)
accumulate(dt$var1[-1], .init = data.frame(var1 = dt$var1[1], var2 = -3.12, var3 = 1),
~ data.frame(var1 = .y,
var2 = .x$var2 + .x$var3 -(.y/constant),
var3 = .x$var1 + 0.1 * (.x$var2 + .x$var3 -(.y/constant))/constant)) %>% map_df(~.x)
var1 var2 var3
1 -92186.747 -3.120000e+00 1.00
2 -19163.504 -2.088501e+00 -92186.75
3 -18178.840 -9.218881e+04 -19163.52
4 -9844.679 -1.113523e+05 -18178.86
5 -16494.780 -1.295311e+05 -9844.70
6 -17088.058 -1.393758e+05 -16494.80
``` | Here is another solution in base R you could use:
```
do.call(rbind, Reduce(function(x, y) {
data.frame(var1 = dt$var1[y],
var2 = x[["var2"]] + x[["var3"]] - (dt$var1[y] / constant),
var3 = dt$var1[y - 1] + 0.1 * ((x[["var2"]] + x[["var3"]] - (dt$var1[y] / constant)) / constant))
}, init = data.frame(var1 = dt$var1[1], var2 = -3.12, var3 = 1), 2:nrow(dt), accumulate = TRUE))
var1 var2 var3
1 -92186.747 -3.120000e+00 1.00
2 -19163.504 -2.088501e+00 -92186.75
3 -18178.840 -9.218881e+04 -19163.52
4 -9844.679 -1.113523e+05 -18178.86
5 -16494.780 -1.295311e+05 -9844.70
6 -17088.058 -1.393758e+05 -16494.80
```
I think you can use the following solution. Here are some notes on how it works:
* In this question we need to fill 2 vectors of length 6, two of which are already specified through `.init` argument and contrary to the previous question we are populating two variables so we need to create a `tibble` and start from there
* There remains 5 other varlues to populate as we supplied `.init` the first and second vector should be of equal length, otherwise the second vector should be one element shorter than the first one (without `.init`)
* Since we are dealing with actual and previous value of `var1`, I decided to use it twice each time omitting first and last value respectively, so that for example in calculating `var3` where you need `prev$var1` it is actually the first value of the second variable `var1[-n()]`
* `..1` is always the accumulated/previous value, here since we got two `var2` and `var3` we can subset it with `$` to specify which one we are referring to
* `..2` is the next value in sequence from first vector `.x` in general and `var1[-1]` here and `..3` is the next value in sequence from second vector `.y` in general and `var1[-n()]` here
If these notes were not suffice I would be glad to explain more.
```
library(purrr)
dt[,1] %>%
bind_cols(dt %>%
mutate(output = accumulate2(var1[-1], var1[-n()], .init = tibble(var2 = -3.12, var3 = 1),
~ tibble(var2 = (..1$var2 + ..1$var3 - (..2/constant)),
var3 = ..3 + 0.1 * ((..1$var2 + ..1$var3 - (..2/constant)) /constant)))) %>%
select(output) %>%
unnest(output))
var1 var2 var3
1: -92186.747 -3.120000e+00 1.00
2: -19163.504 -2.088501e+00 -92186.75
3: -18178.840 -9.218881e+04 -19163.52
4: -9844.679 -1.113523e+05 -18178.86
5: -16494.780 -1.295311e+05 -9844.70
6: -17088.058 -1.393758e+05 -16494.80
``` |
241,888 | Given an integer **N** from 1-9, you must print an **N**x**N** grid of **N**x**N** boxes that print alternating 1s and **N**s, with each box having an alternating starting integer.
**Examples**
```
Input: 1
Output:
1
Input: 2
Output:
12 21
21 12
21 12
12 21
Input: 3
Output:
131 313 131
313 131 313
131 313 131
313 131 313
131 313 131
313 131 313
131 313 131
313 131 313
131 313 131
Input: 4
Output:
1414 4141 1414 4141
4141 1414 4141 1414
1414 4141 1414 4141
4141 1414 4141 1414
4141 1414 4141 1414
1414 4141 1414 4141
4141 1414 4141 1414
1414 4141 1414 4141
1414 4141 1414 4141
4141 1414 4141 1414
1414 4141 1414 4141
4141 1414 4141 1414
4141 1414 4141 1414
1414 4141 1414 4141
4141 1414 4141 1414
1414 4141 1414 4141
```
An array (of NxN arrays) or text in this format is acceptable. | 2022/01/27 | [
"https://codegolf.stackexchange.com/questions/241888",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/103859/"
] | [Pari/GP](http://pari.math.u-bordeaux.fr/), 48 bytes
====================================================
```
n->matrix(n,,i,j,matrix(n,,k,l,n^((i+j+k+l)%2)))
```
[Try it online!](https://tio.run/##RcpBCoAgEEDRqwxBMIPjomirRwncGKM2ibjo9larNh8e/Bqa2KOOCG6o9WfoTW5UZuHEvzIX1h1RTDLZFJpXIhrxaqjgYGHYGGoT7a8nsP5NRP2eBw "Pari/GP – Try It Online") | [JavaScript (Node.js)](https://nodejs.org), 56 bytes
====================================================
```javascript
f=(n,w=4,y)=>w?[...Array(n)].map(_=>f(n,w-1,y=!y)):y?n:1
```
[Try it online!](https://tio.run/##bY3NCoJAFIX3PsVtNxd0QGqlXKXnqMjBNBS7I@OoDNGzT9oPbVqd78D5adWkhtI0vY1YXyrvaxIczrQLHVI25wcp5d4Y5QTjSd5UL86U1WskikNHG4eYuJyT2Ncjl7bRDHq0/WiXPNwDgEkZsECwdDBdfKl50F0lO30V9jVoKfsHrW64KPCt8IUj/2jl4BF8/raY@ic "JavaScript (Node.js) – Try It Online") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.