qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
2,273,679 | I am having a problem with a linked image.
```
<TR class="a">
<TD><A href="http://CA_NB_1_1-pr.jpg" rel="lightbox"><IMG src="CA_NB_1_1-th-pr.jpg"><BR><BR></A></TD>
<TD class="hdsmlbr"><A href="http://127.0.0.1/odds/aptrqr2/view/1">35 Savoie Drive, Moncton, New Brunswick, Canada</A></TD>
</TR>
```
This image has padding at the bottom of it that I cannot seem to find to kill. I have used CSS Reset from Yahoo to see if that helped, and even removed all CSS to see if I can locate the problem.
Using Firebug, I tried a few on the fly methods of nullifying the padding, but nothing seems to work.
Can anyone else figure out what the problem may be?
<http://monkeylook.bendauphinee.com/> | 2010/02/16 | [
"https://Stackoverflow.com/questions/2273679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/202184/"
] | It might be the two `<br>`'s... | you have two newlines in your a tag?
try this.
```
<TR class="a">
<TD><A href="http://CA_NB_1_1-pr.jpg" rel="lightbox"><IMG src="CA_NB_1_1-th-pr.jpg"></A></TD>
<TD class="hdsmlbr"><A href="http://127.0.0.1/odds/aptrqr2/view/1">35 Savoie Drive, Moncton, New Brunswick, Canada</A></TD>
</TR>
``` |
53,560,009 | I had installed sensenet using nuget package manager and visual studio and able to run sensenet using visual studio. But when i tried using IIS and same packages, error is coming. i didnt find any installation guide to run on IIS local host.
I had installed all the modules (Web pages, Work space using visual studio)
[Error details](https://i.stack.imgur.com/5USGf.png) | 2018/11/30 | [
"https://Stackoverflow.com/questions/53560009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10639620/"
] | There are some 'Hacky' ways to achieve what you desire. You can use express.Route to register middlewares on each route instead, but I think that you may want more specific logs about GraphQL rather than the request in particular.
context()
---------
Available as a callback inside ApolloServer, it receives an object with the request and response.
```
const myServer = new ApolloServer({
schema: ...,
context:({ req, res }) => {
// log here
}
});
```
fortmatResponse()
-----------------
Available as a callback inside ApolloServer, it receives the response and the query.
```
const server = new Apollo.ApolloServer({
schema: ...,
formatResponse: (res, query) => {
// log here
// notice you must return the response
return res;
},
});
```
Sources:
[formatResponse](https://github.com/apollographql/apollo-server/issues/216), [context](https://github.com/apollographql/apollo-server/issues/1066)
Edit
----
Another thing you can do is on morgan callback check if the req.path matches with the `/graphQL` path, and log only in that situation but this is much the same as log an Express.Route with morgan | With apollo server v2, its really simple to use it only on a single route. apply it as middleware.
i.e
```
const app = require('express')();
const apolloServer = new ApolloServer ({
typeDefs,
resolvers
})
// then use it on a particular route
apolloServer.applyMiddleware({ app, path: '/specialUrl' });
``` |
53,560,009 | I had installed sensenet using nuget package manager and visual studio and able to run sensenet using visual studio. But when i tried using IIS and same packages, error is coming. i didnt find any installation guide to run on IIS local host.
I had installed all the modules (Web pages, Work space using visual studio)
[Error details](https://i.stack.imgur.com/5USGf.png) | 2018/11/30 | [
"https://Stackoverflow.com/questions/53560009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10639620/"
] | There are some 'Hacky' ways to achieve what you desire. You can use express.Route to register middlewares on each route instead, but I think that you may want more specific logs about GraphQL rather than the request in particular.
context()
---------
Available as a callback inside ApolloServer, it receives an object with the request and response.
```
const myServer = new ApolloServer({
schema: ...,
context:({ req, res }) => {
// log here
}
});
```
fortmatResponse()
-----------------
Available as a callback inside ApolloServer, it receives the response and the query.
```
const server = new Apollo.ApolloServer({
schema: ...,
formatResponse: (res, query) => {
// log here
// notice you must return the response
return res;
},
});
```
Sources:
[formatResponse](https://github.com/apollographql/apollo-server/issues/216), [context](https://github.com/apollographql/apollo-server/issues/1066)
Edit
----
Another thing you can do is on morgan callback check if the req.path matches with the `/graphQL` path, and log only in that situation but this is much the same as log an Express.Route with morgan | ```
const express = require("express");
const router = express.Router();
const { ApolloServer, gql } = require('apollo-server-express');
const server = new ApolloServer({
schema: schema,
introspection: true
});
server.applyMiddleware({ app:router });
module.exports = router;
``` |
53,560,009 | I had installed sensenet using nuget package manager and visual studio and able to run sensenet using visual studio. But when i tried using IIS and same packages, error is coming. i didnt find any installation guide to run on IIS local host.
I had installed all the modules (Web pages, Work space using visual studio)
[Error details](https://i.stack.imgur.com/5USGf.png) | 2018/11/30 | [
"https://Stackoverflow.com/questions/53560009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10639620/"
] | There are some 'Hacky' ways to achieve what you desire. You can use express.Route to register middlewares on each route instead, but I think that you may want more specific logs about GraphQL rather than the request in particular.
context()
---------
Available as a callback inside ApolloServer, it receives an object with the request and response.
```
const myServer = new ApolloServer({
schema: ...,
context:({ req, res }) => {
// log here
}
});
```
fortmatResponse()
-----------------
Available as a callback inside ApolloServer, it receives the response and the query.
```
const server = new Apollo.ApolloServer({
schema: ...,
formatResponse: (res, query) => {
// log here
// notice you must return the response
return res;
},
});
```
Sources:
[formatResponse](https://github.com/apollographql/apollo-server/issues/216), [context](https://github.com/apollographql/apollo-server/issues/1066)
Edit
----
Another thing you can do is on morgan callback check if the req.path matches with the `/graphQL` path, and log only in that situation but this is much the same as log an Express.Route with morgan | There is a npm package [GraphQL-Router-Ware](https://www.npmjs.com/package/graphql-router-ware)
Using this you can add router level middlewares to your resolvers in a much similar way like we do in express.
You can setup your resolver something like this :
```js
import Router from 'graphql-router-ware';
import { checkPermission } from '../helpers/userhalper';
import Controller from '../controllers/page';
const resolvers = {
Query: {
singlePage: Router(Controller.singlePage)
},
Mutation: {
createPage: Router(checkPermission,Controller.create),
updatePage: Router(checkPermission,Controller.update),
}
}
export default resolvers;
```
Followed by your middleware :
```js
// ....
export checkPermission=({ ctx },next)=>{
if(!ctx.user){
return next(new Error('Not logged in'));
// or throw new Error('Not logged in')
}
// some more permission checks....
return next();
};
// ....
```
Hope this was helpful. |
53,560,009 | I had installed sensenet using nuget package manager and visual studio and able to run sensenet using visual studio. But when i tried using IIS and same packages, error is coming. i didnt find any installation guide to run on IIS local host.
I had installed all the modules (Web pages, Work space using visual studio)
[Error details](https://i.stack.imgur.com/5USGf.png) | 2018/11/30 | [
"https://Stackoverflow.com/questions/53560009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10639620/"
] | With apollo server v2, its really simple to use it only on a single route. apply it as middleware.
i.e
```
const app = require('express')();
const apolloServer = new ApolloServer ({
typeDefs,
resolvers
})
// then use it on a particular route
apolloServer.applyMiddleware({ app, path: '/specialUrl' });
``` | There is a npm package [GraphQL-Router-Ware](https://www.npmjs.com/package/graphql-router-ware)
Using this you can add router level middlewares to your resolvers in a much similar way like we do in express.
You can setup your resolver something like this :
```js
import Router from 'graphql-router-ware';
import { checkPermission } from '../helpers/userhalper';
import Controller from '../controllers/page';
const resolvers = {
Query: {
singlePage: Router(Controller.singlePage)
},
Mutation: {
createPage: Router(checkPermission,Controller.create),
updatePage: Router(checkPermission,Controller.update),
}
}
export default resolvers;
```
Followed by your middleware :
```js
// ....
export checkPermission=({ ctx },next)=>{
if(!ctx.user){
return next(new Error('Not logged in'));
// or throw new Error('Not logged in')
}
// some more permission checks....
return next();
};
// ....
```
Hope this was helpful. |
53,560,009 | I had installed sensenet using nuget package manager and visual studio and able to run sensenet using visual studio. But when i tried using IIS and same packages, error is coming. i didnt find any installation guide to run on IIS local host.
I had installed all the modules (Web pages, Work space using visual studio)
[Error details](https://i.stack.imgur.com/5USGf.png) | 2018/11/30 | [
"https://Stackoverflow.com/questions/53560009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10639620/"
] | ```
const express = require("express");
const router = express.Router();
const { ApolloServer, gql } = require('apollo-server-express');
const server = new ApolloServer({
schema: schema,
introspection: true
});
server.applyMiddleware({ app:router });
module.exports = router;
``` | There is a npm package [GraphQL-Router-Ware](https://www.npmjs.com/package/graphql-router-ware)
Using this you can add router level middlewares to your resolvers in a much similar way like we do in express.
You can setup your resolver something like this :
```js
import Router from 'graphql-router-ware';
import { checkPermission } from '../helpers/userhalper';
import Controller from '../controllers/page';
const resolvers = {
Query: {
singlePage: Router(Controller.singlePage)
},
Mutation: {
createPage: Router(checkPermission,Controller.create),
updatePage: Router(checkPermission,Controller.update),
}
}
export default resolvers;
```
Followed by your middleware :
```js
// ....
export checkPermission=({ ctx },next)=>{
if(!ctx.user){
return next(new Error('Not logged in'));
// or throw new Error('Not logged in')
}
// some more permission checks....
return next();
};
// ....
```
Hope this was helpful. |
66,589,462 | Trying to select one row per day table idea below:
```
ID|PageID|DateTime |Value|SiteID
1 | 1 |2021/03/06| 2001| 1
1 | 1 |2021/03/06| 2002| 1
1 | 2 |2021/03/06| 2003| 1
1 | 3 |2021/03/06| 2004| 1
1 | 4 |2021/03/06| 2004| 1
1 | 1 |2021/03/07| 2004| 1
1 | 2 |2021/03/07| 2005| 1
1 | 3 |2021/03/07| 2006| 1
```
So the site has multiple links with seperate links but PageID is a bit redundant here I'm trying to group by SiteID and retreive one row for each day grouped by SiteID
The value doesn't specifically matter as long as its once a day.
Attempt:
```
SELECT [DateTime], [Followers], [SiteID]
FROM test
WHERE datetime IN (
SELECT MAX(datetime)
FROM test Where SiteID = 1
GROUP BY datetime
);
``` | 2021/03/11 | [
"https://Stackoverflow.com/questions/66589462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10038284/"
] | until you provide desired output , here is one way :
```
select *
from (select * , row_number() over (partition by SiteId,Date) rn from table) tt
where tt.rn = 1
``` | It might help you:
```
select top (1) with ties t.*
from table t
order by Row_Number() Over(Partition By SiteId,convert(date, datetime) Order by (select null))
``` |
66,589,462 | Trying to select one row per day table idea below:
```
ID|PageID|DateTime |Value|SiteID
1 | 1 |2021/03/06| 2001| 1
1 | 1 |2021/03/06| 2002| 1
1 | 2 |2021/03/06| 2003| 1
1 | 3 |2021/03/06| 2004| 1
1 | 4 |2021/03/06| 2004| 1
1 | 1 |2021/03/07| 2004| 1
1 | 2 |2021/03/07| 2005| 1
1 | 3 |2021/03/07| 2006| 1
```
So the site has multiple links with seperate links but PageID is a bit redundant here I'm trying to group by SiteID and retreive one row for each day grouped by SiteID
The value doesn't specifically matter as long as its once a day.
Attempt:
```
SELECT [DateTime], [Followers], [SiteID]
FROM test
WHERE datetime IN (
SELECT MAX(datetime)
FROM test Where SiteID = 1
GROUP BY datetime
);
``` | 2021/03/11 | [
"https://Stackoverflow.com/questions/66589462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10038284/"
] | You can use window functions. But if the value is a `datetime`, you need to extract the date:
```
select *
from (select t.* ,
row_number() over (partition by SiteId, convert(date, datetime) order by (select null)) as seqnum
from t
) t
where seqnum = 1;
```
EDIT:
If performance is an issue, then a correlated subquery might have better performance:
```
select t.*
from t
where t.datetime = (select min(t2.datetime)
from t t2
where t2.siteId = t.siteId and
t2.date >= convert(date, t.date) and
t2.date < dateadd(day, 1, convert(date, t2.date))
);
```
Note: This assumes that `datetime` is unique. You can use any column for the comparison that is unique. | It might help you:
```
select top (1) with ties t.*
from table t
order by Row_Number() Over(Partition By SiteId,convert(date, datetime) Order by (select null))
``` |
53,961,170 | I have two forms in my access database, "Adjustment Form" and "Final Form".
On "Final Form", there is a button that when clicked, I would like it to close the current form and open the Adjustment Form to a new record.
FYI- The Adjustment Form will likely already be open, so if this is the case, just close the "Final Form" and move to a new record.
Here's what I have so far:
```
Private Sub Command438_Click()
DoCmd.RunCommand acCmdSaveRecord
DoCmd.Close
DoCmd.GoToRecord , "Adjustment Form", , acNewRec
End Sub
```
However, when I run this, I get the error "You can't go to the specified record".
Any idea how to correct this? | 2018/12/28 | [
"https://Stackoverflow.com/questions/53961170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4021184/"
] | It worked for me.
My ansible version is `ansible 2.9.18` and below is my playbook worked for ignoring the unreachable servers.
```
---
- name: Install the package
serial: 1
hosts: dev
become: yes
gather_facts: false
become_user: root
tasks:
- name: Install amazon efs package
yum:
name: ['packagename']
state: latest
ignore_unreachable: true
```
and Below is the sample o/p:
```
PLAY [Install the package] ******************************************************************************************************************************************************************
TASK [Install amazon efs package] ***********************************************************************************************************************************************************
fatal: [x.x.x.x]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ssh: connect to host x.x.x.x port 22: Connection timed out", "skip_reason": "Host x.x.x.x is unreachable", "unreachable": true}
PLAY [Install the package] ******************************************************************************************************************************************************************
TASK [Install amazon efs package] ***********************************************************************************************************************************************************
fatal: [x.x.x.x]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ssh: connect to host x.x.x.x port 22: Connection timed out", "skip_reason": "Host x.x.x.x is unreachable", "unreachable": true}
``` | You can also disable the debugger and the playbook will run undisturbed:
```yaml
- name: Play
hosts: all
debugger: never
```
More on the debugger [here](https://docs.ansible.com/ansible/latest/user_guide/playbooks_debugger.html) |
56,960,167 | Here's what I am trying to do,
I would like to create a batch file to compress multiple folders and files into one 7zip file for archival purposes.
I have external drives we can call [SOURCE DISK] and [DESTINATION DISK].
The File & Folders I want to compress are in the root of the [SOURCE DISK]. I would like to add all these folders and the file to a single 7zip archive with a designated name [ARCHIVE NAME].
I have 7zip 64bit installed.
Here's what I have tried;
```
C:\Program Files\7-Zip\7za a -tzip "[DESTINATION DISK]\[ARCHIVE NAME] %DATE:~12,2%%DATE:~4,2%%DATE:~7,2%_%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%.zip" "[SOURCE DISK]\[FIRST FOLDER], [SOURCE DISK]\[SECOND FOLDER], [SOURCE DISK]\[THIRD FOLDER], [SOURCE DISK]\[AN EXCEL DOCUMENT]" -mx5
C:\Program Files\7-Zip\7za a -tzip "[DESTINATION DISK]\[ARCHIVE NAME].zip" "[SOURCE DISK]\[FIRST FOLDER], [SOURCE DISK]\[SECOND FOLDER], [SOURCE DISK]\[THIRD FOLDER], [SOURCE DISK]\[AN EXCEL DOCUMENT]" -mx5
C:\Program Files\7-Zip\7za a -tzip "[DESTINATION DISK]\[ARCHIVE NAME].zip" "[SOURCE DISK]\[FIRST FOLDER]" -mx5
c:\Program Files\7-Zip\7z.exe a -tzip "[DESTINATION DISK]\[ARCHIVE NAME].zip" "[SOURCE DISK]\[FIRST FOLDER]" -mx5
c:\Program Files\7-Zip\7z.exe a -tzip "[DESTINATION DISK]\[ARCHIVE NAME].7z" "[SOURCE DISK]\[FIRST FOLDER]" -mx5
```
I am new to 7zip command line. I'm sure I am missing something crucial. When I manually execute the batch file a cmd prompt flickers but it seams nothing happens as my CPU usage doesn't steadily change as it would if I were to use the 7zip GUI. I believe the cmd prompt is flickering because it's started but there was a syntax error.
In the past I've used
```
for /d %%X in (*) do "c:\Program Files\7-Zip\7z.exe" a "%%X.7z" "%%X\"
```
to compress every folder within a current directory and it seamed to work nicely.
How can I specify Folders and Files to include in one archive using a batch.
Any tips will be greatly appreciated. | 2019/07/09 | [
"https://Stackoverflow.com/questions/56960167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9711276/"
] | ```
"C:\Program Files\7-Zip\7z.exe" a -pSECRET "[DESTINATION DISK]\[ARCHIVE NAME] %DATE:~10,4%%DATE:~4,2%%DATE:~7,2%_%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%.7z" "[SOURCE DISK][FIRST FOLDER]" [SOURCE DISK][SECONDFOLDER] "[SOURCE DISK]\[EXCEL DOCUMENT]" -mhe=on -mx5
```
I figured it out. Thanks for the support! After a bunch of reading and trial and error, I realized if the path of the source or destination includes a space: quotations are required. And if there is no space: don't include quotations. See the example above. Hope this helps others in the future.
Not to confuse, but I've added a password as well as hiding the file names before the password is entered. I do realize the password will be in the .bat but these archives will be transferred to other machines and the .bat will not be available to those in the future. | `C:\Program Files\7-Zip\7za` attempts to execute `C:\Program`. You need to quote it `"C:\Program Files\7-Zip\7za"` as you did in your "I've used" example.
Possibly one should draw your attention to the `-r` switch to recurse the archiving - and I believe all of the switches (like `-mx5`) should appear before the archive filename, otherwise it will assume that `-mx5` is a filename to be archived. |
56,960,167 | Here's what I am trying to do,
I would like to create a batch file to compress multiple folders and files into one 7zip file for archival purposes.
I have external drives we can call [SOURCE DISK] and [DESTINATION DISK].
The File & Folders I want to compress are in the root of the [SOURCE DISK]. I would like to add all these folders and the file to a single 7zip archive with a designated name [ARCHIVE NAME].
I have 7zip 64bit installed.
Here's what I have tried;
```
C:\Program Files\7-Zip\7za a -tzip "[DESTINATION DISK]\[ARCHIVE NAME] %DATE:~12,2%%DATE:~4,2%%DATE:~7,2%_%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%.zip" "[SOURCE DISK]\[FIRST FOLDER], [SOURCE DISK]\[SECOND FOLDER], [SOURCE DISK]\[THIRD FOLDER], [SOURCE DISK]\[AN EXCEL DOCUMENT]" -mx5
C:\Program Files\7-Zip\7za a -tzip "[DESTINATION DISK]\[ARCHIVE NAME].zip" "[SOURCE DISK]\[FIRST FOLDER], [SOURCE DISK]\[SECOND FOLDER], [SOURCE DISK]\[THIRD FOLDER], [SOURCE DISK]\[AN EXCEL DOCUMENT]" -mx5
C:\Program Files\7-Zip\7za a -tzip "[DESTINATION DISK]\[ARCHIVE NAME].zip" "[SOURCE DISK]\[FIRST FOLDER]" -mx5
c:\Program Files\7-Zip\7z.exe a -tzip "[DESTINATION DISK]\[ARCHIVE NAME].zip" "[SOURCE DISK]\[FIRST FOLDER]" -mx5
c:\Program Files\7-Zip\7z.exe a -tzip "[DESTINATION DISK]\[ARCHIVE NAME].7z" "[SOURCE DISK]\[FIRST FOLDER]" -mx5
```
I am new to 7zip command line. I'm sure I am missing something crucial. When I manually execute the batch file a cmd prompt flickers but it seams nothing happens as my CPU usage doesn't steadily change as it would if I were to use the 7zip GUI. I believe the cmd prompt is flickering because it's started but there was a syntax error.
In the past I've used
```
for /d %%X in (*) do "c:\Program Files\7-Zip\7z.exe" a "%%X.7z" "%%X\"
```
to compress every folder within a current directory and it seamed to work nicely.
How can I specify Folders and Files to include in one archive using a batch.
Any tips will be greatly appreciated. | 2019/07/09 | [
"https://Stackoverflow.com/questions/56960167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9711276/"
] | ```
"C:\Program Files\7-Zip\7z.exe" a -pSECRET "[DESTINATION DISK]\[ARCHIVE NAME] %DATE:~10,4%%DATE:~4,2%%DATE:~7,2%_%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%.7z" "[SOURCE DISK][FIRST FOLDER]" [SOURCE DISK][SECONDFOLDER] "[SOURCE DISK]\[EXCEL DOCUMENT]" -mhe=on -mx5
```
I figured it out. Thanks for the support! After a bunch of reading and trial and error, I realized if the path of the source or destination includes a space: quotations are required. And if there is no space: don't include quotations. See the example above. Hope this helps others in the future.
Not to confuse, but I've added a password as well as hiding the file names before the password is entered. I do realize the password will be in the .bat but these archives will be transferred to other machines and the .bat will not be available to those in the future. | You just need to have the correct options specified and make sure all of your paths are quoted
```
@(
SetLocal
Echo Off
SET "_Src="C:\Source\Path"
)
REM Get The Date Tokens and Time in ISO Format:
FOR /F "Tokens=1-7 delims=MTWFSmtwfsouehrandit:-\/. " %%A IN (
"%DATE% %TIME: =0%"
) DO (
FOR /F "Tokens=2-4 Skip=1 Delims=(-)" %%a IN ('
ECHO.^| DATE
') DO (
SET "%%~a=%%~A"
SET "%%~b=%%~B"
SET "%%~c=%%~C"
SET "IsoTime=%%~D.%%~E.%%~F.%%~G"
)
)
REM Set Archive Filename with Date:
SET "_Dst="D:\Destination\Path\ARCHIVE_NAME_%yy%-%mm%-%dd%_%IsoTime%.zip"
REM Run 7Zip Command:
"C:\Program Files\7-Zip\7z.exe" a -bd -tZip "%_Dst%" "%_Src%"
(
EndLocal
Exit /B
)
```
I out in a method to get the Date into ISO format that is region independent. as well since you have a different date/time format on your system then I do. You can change it around as you like. |
56,960,167 | Here's what I am trying to do,
I would like to create a batch file to compress multiple folders and files into one 7zip file for archival purposes.
I have external drives we can call [SOURCE DISK] and [DESTINATION DISK].
The File & Folders I want to compress are in the root of the [SOURCE DISK]. I would like to add all these folders and the file to a single 7zip archive with a designated name [ARCHIVE NAME].
I have 7zip 64bit installed.
Here's what I have tried;
```
C:\Program Files\7-Zip\7za a -tzip "[DESTINATION DISK]\[ARCHIVE NAME] %DATE:~12,2%%DATE:~4,2%%DATE:~7,2%_%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%.zip" "[SOURCE DISK]\[FIRST FOLDER], [SOURCE DISK]\[SECOND FOLDER], [SOURCE DISK]\[THIRD FOLDER], [SOURCE DISK]\[AN EXCEL DOCUMENT]" -mx5
C:\Program Files\7-Zip\7za a -tzip "[DESTINATION DISK]\[ARCHIVE NAME].zip" "[SOURCE DISK]\[FIRST FOLDER], [SOURCE DISK]\[SECOND FOLDER], [SOURCE DISK]\[THIRD FOLDER], [SOURCE DISK]\[AN EXCEL DOCUMENT]" -mx5
C:\Program Files\7-Zip\7za a -tzip "[DESTINATION DISK]\[ARCHIVE NAME].zip" "[SOURCE DISK]\[FIRST FOLDER]" -mx5
c:\Program Files\7-Zip\7z.exe a -tzip "[DESTINATION DISK]\[ARCHIVE NAME].zip" "[SOURCE DISK]\[FIRST FOLDER]" -mx5
c:\Program Files\7-Zip\7z.exe a -tzip "[DESTINATION DISK]\[ARCHIVE NAME].7z" "[SOURCE DISK]\[FIRST FOLDER]" -mx5
```
I am new to 7zip command line. I'm sure I am missing something crucial. When I manually execute the batch file a cmd prompt flickers but it seams nothing happens as my CPU usage doesn't steadily change as it would if I were to use the 7zip GUI. I believe the cmd prompt is flickering because it's started but there was a syntax error.
In the past I've used
```
for /d %%X in (*) do "c:\Program Files\7-Zip\7z.exe" a "%%X.7z" "%%X\"
```
to compress every folder within a current directory and it seamed to work nicely.
How can I specify Folders and Files to include in one archive using a batch.
Any tips will be greatly appreciated. | 2019/07/09 | [
"https://Stackoverflow.com/questions/56960167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9711276/"
] | ```
"C:\Program Files\7-Zip\7z.exe" a -pSECRET "[DESTINATION DISK]\[ARCHIVE NAME] %DATE:~10,4%%DATE:~4,2%%DATE:~7,2%_%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%.7z" "[SOURCE DISK][FIRST FOLDER]" [SOURCE DISK][SECONDFOLDER] "[SOURCE DISK]\[EXCEL DOCUMENT]" -mhe=on -mx5
```
I figured it out. Thanks for the support! After a bunch of reading and trial and error, I realized if the path of the source or destination includes a space: quotations are required. And if there is no space: don't include quotations. See the example above. Hope this helps others in the future.
Not to confuse, but I've added a password as well as hiding the file names before the password is entered. I do realize the password will be in the .bat but these archives will be transferred to other machines and the .bat will not be available to those in the future. | You can use text file containing a list of source paths as described [here](https://sevenzip.osdn.jp/chm/cmdline/syntax.htm).
Create `list.txt` with paths:
```
My programs\*.cpp
Src\*.cpp
```
Then use this file in the archive command:
```
7z a archive.7z @list.txt
``` |
42,477 | I was thinking of using some Aluminum coating/blanket but the temperatures can reach 550C+ in the Chamber I work at. I am concerned about melting.
Let me know.
P.S: I am an entry level Engineer. Please no judging. | 2021/04/08 | [
"https://engineering.stackexchange.com/questions/42477",
"https://engineering.stackexchange.com",
"https://engineering.stackexchange.com/users/32553/"
] | Polish the stainless. Depending how long at maximum temperature it will tint pink then blue . If necessary it could be repolished. If it will have long exposure with no repolish, maybe a thin sheet of gold or platinum. Gold foil is old technology if there is no abrasion or other physical contact. I doubt there is existing technology for chrome plating of stainless. | There are a number of factors to consider here, namely: ability to coat and bond to the stainless steel, corrosion, abrasion resistance, maintenance, how dirty the plate will get, melting point and how heat is absorbed by the steel substrate.
If you want to reflect as much heat as possible, you would want a material with a low absorbance across a wide range of wavelengths.
Gold is a possibility because of its inert nature, ability to be plated on, melting point of about 1064C. Platinum would work too. Silver may tarnish but it depends on the environment it is exposed to. Problem with reflectors is that if they start getting corroded, scratched or dirty, their reflectivity drops over time. These metals have poor abrasion resistance, and may make them the subject of theft.
The disadvantage of a metal reflective coating on a metal substrate is that heat is conducted by your coating into the substrate, which brings us to an alternative solution.
The alternative to having a high thermal reflective coat, is to have a coating that is a poor thermal conductor but may not be such a good reflector. In which case your coating increases in temperature, re-emits the absorbed heat as a black body radiator but doesn't transmit the heat so well to the stainless steel substrate. Many poor thermal conductors (aerogel, ceramics) do not bond so well to steel and can not be easily made into thin layers or coatings. |
31,212,087 | I've searched everywhere for this situation and can't find a solution **except for Dynamic SQL, which I don't want to use**.
Here is the table I want to UPDATE on server 2:
```
(Stuff Id UNIQUEIDENTIFIER
, stuffname NVARCHAR(64))
```
I need to update it from server 1.
So I have been attempting this:
```
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE [server2].database2.dbo.Stuff
SET stuffname=@newstuff
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
That takes 11 seconds. This next one using a literal runs in under 1 second
```
UPDATE [server2].database2.dbo.Stuff
SET stuffname='new stuff'
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
I have compared the actual execution plans. The slow one is doing a Remote scan that takes 100% of the cost, plus 5 other steps (filter, table spool, compute scalar, remote update, update). The fast one just does the UPDATE and Remote Query steps. I need to use variables, so I need a way to force it to do the whole query remotely.
I have tried using OPTION(RECOMPILE) but server1 is using SQL Server 2005. server2 is using SQL Server 2012. I can't change the database structure at all on server2 without serious problems. I am not having any authentication problems. I have tried aliasing the table when updating it.
I have also tried using Openquery. When I put the id filter within the query string, it gets back down to under 1 second:
```
UPDATE OPENQUERY([server2], 'select stuffname, stuffid from database2.dbo.stufftable where contactid=''4CA1D489-9221-E511-A441-005056C00008''')
SET stuffname = @newstuff
```
But I need that id to be a variable as well, and that open query does not take variables (<https://msdn.microsoft.com/en-CA/library/ms188427.aspx>). I tried running Openquery with the id filter outside the query, but that runs in 4 seconds. It's better than 11, but not great:
```
UPDATE OPENQUERY([server2],'select stuffname, stuffid from database2.dbo.stufftable')
set stuffname=@newstuff
where contactid='4CA1D489-9221-E511-A441-005056C00008'
```
Of course, I run openquery using exec(@sql), but I really don't want to go that way. I could do the whole update statement that way using literals and not even use OPENQUERY and get the same sort of result anyway.
Is there any way for me to get this performance fixed without using exec(@sql)? | 2015/07/03 | [
"https://Stackoverflow.com/questions/31212087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1738572/"
] | You can use dynamic SQL with parameters using sp\_executesql on the remote side.
```
declare @SQL nvarchar(max);
set @SQL = 'UPDATE database2.dbo.Stuff
SET stuffname=@newstuff
WHERE stuffId=''4893CD93-08B3-4981-851B-5DC972288290'''
exec [server2].master.dbo.sp_executesql @SQL, N'@newstuff nvarchar(64)', @newstuff
``` | I would do it like this. Rather than sending the actual `UPDATE` query to execute to server2, I would make a stored procedure on server2 with the necessary parameters and call it from server1.
Inside the stored procedure you can tweak the query as needed using all capabilities of server2 to make it run fast (like `OPTION(RECOMPILE)`, for example).
Besides, having explicit stored procedures like this defines an interface how two systems interact, which is good on its own. |
31,212,087 | I've searched everywhere for this situation and can't find a solution **except for Dynamic SQL, which I don't want to use**.
Here is the table I want to UPDATE on server 2:
```
(Stuff Id UNIQUEIDENTIFIER
, stuffname NVARCHAR(64))
```
I need to update it from server 1.
So I have been attempting this:
```
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE [server2].database2.dbo.Stuff
SET stuffname=@newstuff
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
That takes 11 seconds. This next one using a literal runs in under 1 second
```
UPDATE [server2].database2.dbo.Stuff
SET stuffname='new stuff'
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
I have compared the actual execution plans. The slow one is doing a Remote scan that takes 100% of the cost, plus 5 other steps (filter, table spool, compute scalar, remote update, update). The fast one just does the UPDATE and Remote Query steps. I need to use variables, so I need a way to force it to do the whole query remotely.
I have tried using OPTION(RECOMPILE) but server1 is using SQL Server 2005. server2 is using SQL Server 2012. I can't change the database structure at all on server2 without serious problems. I am not having any authentication problems. I have tried aliasing the table when updating it.
I have also tried using Openquery. When I put the id filter within the query string, it gets back down to under 1 second:
```
UPDATE OPENQUERY([server2], 'select stuffname, stuffid from database2.dbo.stufftable where contactid=''4CA1D489-9221-E511-A441-005056C00008''')
SET stuffname = @newstuff
```
But I need that id to be a variable as well, and that open query does not take variables (<https://msdn.microsoft.com/en-CA/library/ms188427.aspx>). I tried running Openquery with the id filter outside the query, but that runs in 4 seconds. It's better than 11, but not great:
```
UPDATE OPENQUERY([server2],'select stuffname, stuffid from database2.dbo.stufftable')
set stuffname=@newstuff
where contactid='4CA1D489-9221-E511-A441-005056C00008'
```
Of course, I run openquery using exec(@sql), but I really don't want to go that way. I could do the whole update statement that way using literals and not even use OPENQUERY and get the same sort of result anyway.
Is there any way for me to get this performance fixed without using exec(@sql)? | 2015/07/03 | [
"https://Stackoverflow.com/questions/31212087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1738572/"
] | You can use dynamic SQL with parameters using sp\_executesql on the remote side.
```
declare @SQL nvarchar(max);
set @SQL = 'UPDATE database2.dbo.Stuff
SET stuffname=@newstuff
WHERE stuffId=''4893CD93-08B3-4981-851B-5DC972288290'''
exec [server2].master.dbo.sp_executesql @SQL, N'@newstuff nvarchar(64)', @newstuff
``` | The solution to this should be that you ensure that the parameters you're using match the length and type of the columns. For instance, make sure that the NVARCHAR(64) column is targeted by a "DECLARE @var AS NVARCHAR(64)".
In your sample that seems to be the case, but when testing this in a local setup (with a SQLEXPRESS 2005 linked from a SQLEXPRESS 2014) I only get the "Remote Scan" when not matching up the length and type. |
31,212,087 | I've searched everywhere for this situation and can't find a solution **except for Dynamic SQL, which I don't want to use**.
Here is the table I want to UPDATE on server 2:
```
(Stuff Id UNIQUEIDENTIFIER
, stuffname NVARCHAR(64))
```
I need to update it from server 1.
So I have been attempting this:
```
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE [server2].database2.dbo.Stuff
SET stuffname=@newstuff
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
That takes 11 seconds. This next one using a literal runs in under 1 second
```
UPDATE [server2].database2.dbo.Stuff
SET stuffname='new stuff'
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
I have compared the actual execution plans. The slow one is doing a Remote scan that takes 100% of the cost, plus 5 other steps (filter, table spool, compute scalar, remote update, update). The fast one just does the UPDATE and Remote Query steps. I need to use variables, so I need a way to force it to do the whole query remotely.
I have tried using OPTION(RECOMPILE) but server1 is using SQL Server 2005. server2 is using SQL Server 2012. I can't change the database structure at all on server2 without serious problems. I am not having any authentication problems. I have tried aliasing the table when updating it.
I have also tried using Openquery. When I put the id filter within the query string, it gets back down to under 1 second:
```
UPDATE OPENQUERY([server2], 'select stuffname, stuffid from database2.dbo.stufftable where contactid=''4CA1D489-9221-E511-A441-005056C00008''')
SET stuffname = @newstuff
```
But I need that id to be a variable as well, and that open query does not take variables (<https://msdn.microsoft.com/en-CA/library/ms188427.aspx>). I tried running Openquery with the id filter outside the query, but that runs in 4 seconds. It's better than 11, but not great:
```
UPDATE OPENQUERY([server2],'select stuffname, stuffid from database2.dbo.stufftable')
set stuffname=@newstuff
where contactid='4CA1D489-9221-E511-A441-005056C00008'
```
Of course, I run openquery using exec(@sql), but I really don't want to go that way. I could do the whole update statement that way using literals and not even use OPENQUERY and get the same sort of result anyway.
Is there any way for me to get this performance fixed without using exec(@sql)? | 2015/07/03 | [
"https://Stackoverflow.com/questions/31212087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1738572/"
] | You can use dynamic SQL with parameters using sp\_executesql on the remote side.
```
declare @SQL nvarchar(max);
set @SQL = 'UPDATE database2.dbo.Stuff
SET stuffname=@newstuff
WHERE stuffId=''4893CD93-08B3-4981-851B-5DC972288290'''
exec [server2].master.dbo.sp_executesql @SQL, N'@newstuff nvarchar(64)', @newstuff
``` | Perhaps the issue has to do with the unique identifier column. Have you tried:
On server2 define the following stored procedure:
```
CREATE PROCEDURE updateStuff( @newstuff nvarchar(30), @stuffid varchar(36))
AS
UPDATE Stuff
SET stuffname=@newstuff
WHERE stuffId=convert(uniqueidentifier, @stuffid))
```
The from server 1 invoke:
exec server2.database2.updatestuff N'New stuff', '4893CD93-08B3-4981-851B-5DC972288290'
OLD suggestion:
Declare @stuffid uniqueidentifier
Set @stuffid = convert(uniqueidentifier,='4893CD93-08B3-4981-851B-5DC972288290')
UPDATE [server2].database2.dbo.Stuff
SET stuffname=@newstuff
WHERE stuffId=@stuffid |
31,212,087 | I've searched everywhere for this situation and can't find a solution **except for Dynamic SQL, which I don't want to use**.
Here is the table I want to UPDATE on server 2:
```
(Stuff Id UNIQUEIDENTIFIER
, stuffname NVARCHAR(64))
```
I need to update it from server 1.
So I have been attempting this:
```
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE [server2].database2.dbo.Stuff
SET stuffname=@newstuff
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
That takes 11 seconds. This next one using a literal runs in under 1 second
```
UPDATE [server2].database2.dbo.Stuff
SET stuffname='new stuff'
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
I have compared the actual execution plans. The slow one is doing a Remote scan that takes 100% of the cost, plus 5 other steps (filter, table spool, compute scalar, remote update, update). The fast one just does the UPDATE and Remote Query steps. I need to use variables, so I need a way to force it to do the whole query remotely.
I have tried using OPTION(RECOMPILE) but server1 is using SQL Server 2005. server2 is using SQL Server 2012. I can't change the database structure at all on server2 without serious problems. I am not having any authentication problems. I have tried aliasing the table when updating it.
I have also tried using Openquery. When I put the id filter within the query string, it gets back down to under 1 second:
```
UPDATE OPENQUERY([server2], 'select stuffname, stuffid from database2.dbo.stufftable where contactid=''4CA1D489-9221-E511-A441-005056C00008''')
SET stuffname = @newstuff
```
But I need that id to be a variable as well, and that open query does not take variables (<https://msdn.microsoft.com/en-CA/library/ms188427.aspx>). I tried running Openquery with the id filter outside the query, but that runs in 4 seconds. It's better than 11, but not great:
```
UPDATE OPENQUERY([server2],'select stuffname, stuffid from database2.dbo.stufftable')
set stuffname=@newstuff
where contactid='4CA1D489-9221-E511-A441-005056C00008'
```
Of course, I run openquery using exec(@sql), but I really don't want to go that way. I could do the whole update statement that way using literals and not even use OPENQUERY and get the same sort of result anyway.
Is there any way for me to get this performance fixed without using exec(@sql)? | 2015/07/03 | [
"https://Stackoverflow.com/questions/31212087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1738572/"
] | You can use dynamic SQL with parameters using sp\_executesql on the remote side.
```
declare @SQL nvarchar(max);
set @SQL = 'UPDATE database2.dbo.Stuff
SET stuffname=@newstuff
WHERE stuffId=''4893CD93-08B3-4981-851B-5DC972288290'''
exec [server2].master.dbo.sp_executesql @SQL, N'@newstuff nvarchar(64)', @newstuff
``` | You can try setting the value right in the variable declaration:
```
DECLARE @newstuff nvarchar(64) = 'new stuff'
UPDATE [server2].database2.dbo.Stuff
SET stuffname=@newstuff
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
I think deleting the `select` part would help. |
31,212,087 | I've searched everywhere for this situation and can't find a solution **except for Dynamic SQL, which I don't want to use**.
Here is the table I want to UPDATE on server 2:
```
(Stuff Id UNIQUEIDENTIFIER
, stuffname NVARCHAR(64))
```
I need to update it from server 1.
So I have been attempting this:
```
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE [server2].database2.dbo.Stuff
SET stuffname=@newstuff
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
That takes 11 seconds. This next one using a literal runs in under 1 second
```
UPDATE [server2].database2.dbo.Stuff
SET stuffname='new stuff'
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
I have compared the actual execution plans. The slow one is doing a Remote scan that takes 100% of the cost, plus 5 other steps (filter, table spool, compute scalar, remote update, update). The fast one just does the UPDATE and Remote Query steps. I need to use variables, so I need a way to force it to do the whole query remotely.
I have tried using OPTION(RECOMPILE) but server1 is using SQL Server 2005. server2 is using SQL Server 2012. I can't change the database structure at all on server2 without serious problems. I am not having any authentication problems. I have tried aliasing the table when updating it.
I have also tried using Openquery. When I put the id filter within the query string, it gets back down to under 1 second:
```
UPDATE OPENQUERY([server2], 'select stuffname, stuffid from database2.dbo.stufftable where contactid=''4CA1D489-9221-E511-A441-005056C00008''')
SET stuffname = @newstuff
```
But I need that id to be a variable as well, and that open query does not take variables (<https://msdn.microsoft.com/en-CA/library/ms188427.aspx>). I tried running Openquery with the id filter outside the query, but that runs in 4 seconds. It's better than 11, but not great:
```
UPDATE OPENQUERY([server2],'select stuffname, stuffid from database2.dbo.stufftable')
set stuffname=@newstuff
where contactid='4CA1D489-9221-E511-A441-005056C00008'
```
Of course, I run openquery using exec(@sql), but I really don't want to go that way. I could do the whole update statement that way using literals and not even use OPENQUERY and get the same sort of result anyway.
Is there any way for me to get this performance fixed without using exec(@sql)? | 2015/07/03 | [
"https://Stackoverflow.com/questions/31212087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1738572/"
] | I believe your problem is related to the permissions that you are running the connection to the LINKED server with.
there are links where this case has been explained and I have had similar experiences.
here are a couple of links:
[OPENQUERY when executing linked server queries in SQL Server](http://blogs.msdn.com/b/sqlsakthi/archive/2011/05/09/best-performer-distributed-query-four-part-or-openquery-when-executing-linked-server-queries-in-sql-server.aspx)
[TOP 3 PERFORMANCE KILLERS FOR LINKED SERVER QUERIES](http://thomaslarock.com/2013/05/top-3-performance-killers-for-linked-server-queries/)
I will post my solution below.
I have set up an environment to test your solution.
my server2 is sql server 2005
my server1 is sql server 2012.
On server2 I have created and populated the stuff table in the following way:
I use a database called tablebackups with a specific naming convention but I am sure you can understand:
The result is a table with a clustered primary key on a identity field and another field for the update. this table in my example has 100,000 records.
```
select @@version
--Microsoft SQL Server 2005 - 9.00.5000.00 (Intel X86)
--Dec 10 2010 10:56:29
--Copyright (c) 1988-2005 Microsoft Corporation
--Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2)
use tablebackups
go
CREATE TABLE dbo._MM_201504710_stuff ( Id UNIQUEIDENTIFIER
, stuffname NVARCHAR(64)
)
ALTER TABLE dbo._MM_201504710_stuff ADD CONSTRAINT [PK_Stuff] UNIQUE CLUSTERED ( ID );
-- add 100,000 records to the table so that we can have an idea of execution
SET NOCOUNT ON
insert into dbo._MM_201504710_stuff values (NewID(),'Radhe Radhe')
GO 100000 -- 100,000
SET NOCOUNT OFF
--this took 19:38
--just to test
SELECT TOP 100 * FROM dbo._MM_201504710_stuff
--18D4BDEA-6226-47E1-94DB-00402A29798F
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE dbo._MM_201504710_stuff
SET stuffname=@newstuff
WHERE Id='18D4BDEA-6226-47E1-94DB-00402A29798F'
UPDATE dbo._MM_201504710_stuff
SET stuffname='new stuff'
WHERE Id='18D4BDEA-6226-47E1-94DB-00402A29798F'
```
the execution plans of these updates are very similar and are not an issue.
As you can see on the picture below.

Before going to server1 I double check when the statistics of my stuff table have been updated, because this will influence the query plan generation.
Just to be sure.

Then I go to server1.
NO, Before I go to server1, on server2 I have this sql login with the following permissions:
I call it "monitor"

and for the permissions of "monitor"
I use this select:
```
SELECT p.[name], sp.permission_name, p.type_desc AS loginType FROM sys.server_principals p
JOIN sys.server_permissions Sp
ON p.principal_id = sp.grantee_principal_id WHERE sp.class = 100
```
That shows me these permissions:

NOW on server1 I have a linked server to server2 (sqlsalon1.dev.boden.local)
and this LINKED server use "monitor" to connect to server2.
as you could see above, this monitor sql user has all the required permissions to see and update the statistics and therefore we can use the best plan even when running remote transactions.
ON SERVER1:
I connect to server2 using the following linked server:


running these scripts (less than a sec)
```
-- just to test
select top 100 *
from [SQLSALON1.dev.boden.local].tablebackups.dbo._MM_201504710_stuff
--first update
UPDATE [SQLSALON1.dev.boden.local].tablebackups.dbo._MM_201504710_stuff
SET stuffname='new stuff'
WHERE Id='18D4BDEA-6226-47E1-94DB-00402A29798F'
--second update
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE [SQLSALON1.dev.boden.local].tablebackups.dbo._MM_201504710_stuff
SET stuffname=@newstuff
WHERE Id='18D4BDEA-6226-47E1-94DB-00402A29798F'
```
I get this query plan:

So, double check the permissions on the linked server account, if you copy mine I believe your problem will be solved, since this is working here, unless there is something else different, and in that case, please let me know, I will try to tackle it further.
**The other way round
From SQL 2005 Updating a table in SQL 2012**
on sql 2012
create and populate the table
```
select @@version
--Microsoft SQL Server 2012 - 11.0.5058.0 (X64)
-- May 14 2014 18:34:29
-- Copyright (c) Microsoft Corporation
-- Standard Edition (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
use tablebackups
go
CREATE TABLE dbo._MM_201504710_stuff ( Id UNIQUEIDENTIFIER
, stuffname NVARCHAR(64)
)
ALTER TABLE dbo._MM_201504710_stuff ADD CONSTRAINT [PK_Stuff] UNIQUE CLUSTERED ( ID );
-- add 100,000 records to the table so that we can have an idea of execution
SET NOCOUNT ON
insert into dbo._MM_201504710_stuff values (NewID(),'Radhe Radhe')
GO 100000 -- 100,000
SET NOCOUNT OFF
--this took 19:38
--just to test
SELECT TOP 100 * FROM dbo._MM_201504710_stuff
--3E29A8E5-BA57-4A9C-803E-003C13A80905
```
after the table is populated I check for the statistics

it turns out that the statistics were NOT updated
so I update the stats:
```
--================================================
-- HAD TO UPDATE THE STATS BEFORE RUNNING THE UPDATES
--================================================
UPDATE STATISTICS dbo._MM_201504710_stuff
```
I check again and it is fine this time.

Create the linked server from sql 2005 to sql 2012:
```
USE [master]
GO
/****** Object: LinkedServer [SQLMON1] Script Date: 13/07/2015 17:09:08 ******/
EXEC master.dbo.sp_addlinkedserver @server = N'SQLMON1', @srvproduct=N'SQL Server'
/* For security reasons the linked server remote logins password is changed with ######## */
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'SQLMON1',@useself=N'False',@locallogin=NULL,@rmtuser=N'monitor',@rmtpassword='########'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'collation compatible', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'data access', @optvalue=N'true'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'dist', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'pub', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'rpc', @optvalue=N'true'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'rpc out', @optvalue=N'true'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'sub', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'connect timeout', @optvalue=N'0'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'collation name', @optvalue=null
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'lazy schema validation', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'query timeout', @optvalue=N'0'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'use remote collation', @optvalue=N'true'
GO
```
I have removed the below server option.

Check the permissions of "monitor" on the target server
```
SELECT p.[name] collate database_default,
sp.permission_name,
p.type_desc AS loginType
FROM sys.server_principals p
JOIN sys.server_permissions Sp
ON p.principal_id = sp.grantee_principal_id
WHERE sp.class = 100
and name = 'monitor'
```

and after that we can run the updates from the sql 2005 server.
```
--first update
UPDATE [SQLMON1].tablebackups.dbo._MM_201504710_stuff
SET stuffname='new stuff'
WHERE Id='3E29A8E5-BA57-4A9C-803E-003C13A80905'
--second update
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE [SQLMON1].tablebackups.dbo._MM_201504710_stuff
SET stuffname=@newstuff
WHERE Id='3E29A8E5-BA57-4A9C-803E-003C13A80905'
```
and this will update the row, with or without a variable, in the same way.
quick as a bolt
 | I would do it like this. Rather than sending the actual `UPDATE` query to execute to server2, I would make a stored procedure on server2 with the necessary parameters and call it from server1.
Inside the stored procedure you can tweak the query as needed using all capabilities of server2 to make it run fast (like `OPTION(RECOMPILE)`, for example).
Besides, having explicit stored procedures like this defines an interface how two systems interact, which is good on its own. |
31,212,087 | I've searched everywhere for this situation and can't find a solution **except for Dynamic SQL, which I don't want to use**.
Here is the table I want to UPDATE on server 2:
```
(Stuff Id UNIQUEIDENTIFIER
, stuffname NVARCHAR(64))
```
I need to update it from server 1.
So I have been attempting this:
```
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE [server2].database2.dbo.Stuff
SET stuffname=@newstuff
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
That takes 11 seconds. This next one using a literal runs in under 1 second
```
UPDATE [server2].database2.dbo.Stuff
SET stuffname='new stuff'
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
I have compared the actual execution plans. The slow one is doing a Remote scan that takes 100% of the cost, plus 5 other steps (filter, table spool, compute scalar, remote update, update). The fast one just does the UPDATE and Remote Query steps. I need to use variables, so I need a way to force it to do the whole query remotely.
I have tried using OPTION(RECOMPILE) but server1 is using SQL Server 2005. server2 is using SQL Server 2012. I can't change the database structure at all on server2 without serious problems. I am not having any authentication problems. I have tried aliasing the table when updating it.
I have also tried using Openquery. When I put the id filter within the query string, it gets back down to under 1 second:
```
UPDATE OPENQUERY([server2], 'select stuffname, stuffid from database2.dbo.stufftable where contactid=''4CA1D489-9221-E511-A441-005056C00008''')
SET stuffname = @newstuff
```
But I need that id to be a variable as well, and that open query does not take variables (<https://msdn.microsoft.com/en-CA/library/ms188427.aspx>). I tried running Openquery with the id filter outside the query, but that runs in 4 seconds. It's better than 11, but not great:
```
UPDATE OPENQUERY([server2],'select stuffname, stuffid from database2.dbo.stufftable')
set stuffname=@newstuff
where contactid='4CA1D489-9221-E511-A441-005056C00008'
```
Of course, I run openquery using exec(@sql), but I really don't want to go that way. I could do the whole update statement that way using literals and not even use OPENQUERY and get the same sort of result anyway.
Is there any way for me to get this performance fixed without using exec(@sql)? | 2015/07/03 | [
"https://Stackoverflow.com/questions/31212087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1738572/"
] | I believe your problem is related to the permissions that you are running the connection to the LINKED server with.
there are links where this case has been explained and I have had similar experiences.
here are a couple of links:
[OPENQUERY when executing linked server queries in SQL Server](http://blogs.msdn.com/b/sqlsakthi/archive/2011/05/09/best-performer-distributed-query-four-part-or-openquery-when-executing-linked-server-queries-in-sql-server.aspx)
[TOP 3 PERFORMANCE KILLERS FOR LINKED SERVER QUERIES](http://thomaslarock.com/2013/05/top-3-performance-killers-for-linked-server-queries/)
I will post my solution below.
I have set up an environment to test your solution.
my server2 is sql server 2005
my server1 is sql server 2012.
On server2 I have created and populated the stuff table in the following way:
I use a database called tablebackups with a specific naming convention but I am sure you can understand:
The result is a table with a clustered primary key on a identity field and another field for the update. this table in my example has 100,000 records.
```
select @@version
--Microsoft SQL Server 2005 - 9.00.5000.00 (Intel X86)
--Dec 10 2010 10:56:29
--Copyright (c) 1988-2005 Microsoft Corporation
--Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2)
use tablebackups
go
CREATE TABLE dbo._MM_201504710_stuff ( Id UNIQUEIDENTIFIER
, stuffname NVARCHAR(64)
)
ALTER TABLE dbo._MM_201504710_stuff ADD CONSTRAINT [PK_Stuff] UNIQUE CLUSTERED ( ID );
-- add 100,000 records to the table so that we can have an idea of execution
SET NOCOUNT ON
insert into dbo._MM_201504710_stuff values (NewID(),'Radhe Radhe')
GO 100000 -- 100,000
SET NOCOUNT OFF
--this took 19:38
--just to test
SELECT TOP 100 * FROM dbo._MM_201504710_stuff
--18D4BDEA-6226-47E1-94DB-00402A29798F
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE dbo._MM_201504710_stuff
SET stuffname=@newstuff
WHERE Id='18D4BDEA-6226-47E1-94DB-00402A29798F'
UPDATE dbo._MM_201504710_stuff
SET stuffname='new stuff'
WHERE Id='18D4BDEA-6226-47E1-94DB-00402A29798F'
```
the execution plans of these updates are very similar and are not an issue.
As you can see on the picture below.

Before going to server1 I double check when the statistics of my stuff table have been updated, because this will influence the query plan generation.
Just to be sure.

Then I go to server1.
NO, Before I go to server1, on server2 I have this sql login with the following permissions:
I call it "monitor"

and for the permissions of "monitor"
I use this select:
```
SELECT p.[name], sp.permission_name, p.type_desc AS loginType FROM sys.server_principals p
JOIN sys.server_permissions Sp
ON p.principal_id = sp.grantee_principal_id WHERE sp.class = 100
```
That shows me these permissions:

NOW on server1 I have a linked server to server2 (sqlsalon1.dev.boden.local)
and this LINKED server use "monitor" to connect to server2.
as you could see above, this monitor sql user has all the required permissions to see and update the statistics and therefore we can use the best plan even when running remote transactions.
ON SERVER1:
I connect to server2 using the following linked server:


running these scripts (less than a sec)
```
-- just to test
select top 100 *
from [SQLSALON1.dev.boden.local].tablebackups.dbo._MM_201504710_stuff
--first update
UPDATE [SQLSALON1.dev.boden.local].tablebackups.dbo._MM_201504710_stuff
SET stuffname='new stuff'
WHERE Id='18D4BDEA-6226-47E1-94DB-00402A29798F'
--second update
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE [SQLSALON1.dev.boden.local].tablebackups.dbo._MM_201504710_stuff
SET stuffname=@newstuff
WHERE Id='18D4BDEA-6226-47E1-94DB-00402A29798F'
```
I get this query plan:

So, double check the permissions on the linked server account, if you copy mine I believe your problem will be solved, since this is working here, unless there is something else different, and in that case, please let me know, I will try to tackle it further.
**The other way round
From SQL 2005 Updating a table in SQL 2012**
on sql 2012
create and populate the table
```
select @@version
--Microsoft SQL Server 2012 - 11.0.5058.0 (X64)
-- May 14 2014 18:34:29
-- Copyright (c) Microsoft Corporation
-- Standard Edition (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
use tablebackups
go
CREATE TABLE dbo._MM_201504710_stuff ( Id UNIQUEIDENTIFIER
, stuffname NVARCHAR(64)
)
ALTER TABLE dbo._MM_201504710_stuff ADD CONSTRAINT [PK_Stuff] UNIQUE CLUSTERED ( ID );
-- add 100,000 records to the table so that we can have an idea of execution
SET NOCOUNT ON
insert into dbo._MM_201504710_stuff values (NewID(),'Radhe Radhe')
GO 100000 -- 100,000
SET NOCOUNT OFF
--this took 19:38
--just to test
SELECT TOP 100 * FROM dbo._MM_201504710_stuff
--3E29A8E5-BA57-4A9C-803E-003C13A80905
```
after the table is populated I check for the statistics

it turns out that the statistics were NOT updated
so I update the stats:
```
--================================================
-- HAD TO UPDATE THE STATS BEFORE RUNNING THE UPDATES
--================================================
UPDATE STATISTICS dbo._MM_201504710_stuff
```
I check again and it is fine this time.

Create the linked server from sql 2005 to sql 2012:
```
USE [master]
GO
/****** Object: LinkedServer [SQLMON1] Script Date: 13/07/2015 17:09:08 ******/
EXEC master.dbo.sp_addlinkedserver @server = N'SQLMON1', @srvproduct=N'SQL Server'
/* For security reasons the linked server remote logins password is changed with ######## */
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'SQLMON1',@useself=N'False',@locallogin=NULL,@rmtuser=N'monitor',@rmtpassword='########'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'collation compatible', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'data access', @optvalue=N'true'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'dist', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'pub', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'rpc', @optvalue=N'true'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'rpc out', @optvalue=N'true'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'sub', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'connect timeout', @optvalue=N'0'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'collation name', @optvalue=null
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'lazy schema validation', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'query timeout', @optvalue=N'0'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'use remote collation', @optvalue=N'true'
GO
```
I have removed the below server option.

Check the permissions of "monitor" on the target server
```
SELECT p.[name] collate database_default,
sp.permission_name,
p.type_desc AS loginType
FROM sys.server_principals p
JOIN sys.server_permissions Sp
ON p.principal_id = sp.grantee_principal_id
WHERE sp.class = 100
and name = 'monitor'
```

and after that we can run the updates from the sql 2005 server.
```
--first update
UPDATE [SQLMON1].tablebackups.dbo._MM_201504710_stuff
SET stuffname='new stuff'
WHERE Id='3E29A8E5-BA57-4A9C-803E-003C13A80905'
--second update
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE [SQLMON1].tablebackups.dbo._MM_201504710_stuff
SET stuffname=@newstuff
WHERE Id='3E29A8E5-BA57-4A9C-803E-003C13A80905'
```
and this will update the row, with or without a variable, in the same way.
quick as a bolt
 | The solution to this should be that you ensure that the parameters you're using match the length and type of the columns. For instance, make sure that the NVARCHAR(64) column is targeted by a "DECLARE @var AS NVARCHAR(64)".
In your sample that seems to be the case, but when testing this in a local setup (with a SQLEXPRESS 2005 linked from a SQLEXPRESS 2014) I only get the "Remote Scan" when not matching up the length and type. |
31,212,087 | I've searched everywhere for this situation and can't find a solution **except for Dynamic SQL, which I don't want to use**.
Here is the table I want to UPDATE on server 2:
```
(Stuff Id UNIQUEIDENTIFIER
, stuffname NVARCHAR(64))
```
I need to update it from server 1.
So I have been attempting this:
```
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE [server2].database2.dbo.Stuff
SET stuffname=@newstuff
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
That takes 11 seconds. This next one using a literal runs in under 1 second
```
UPDATE [server2].database2.dbo.Stuff
SET stuffname='new stuff'
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
I have compared the actual execution plans. The slow one is doing a Remote scan that takes 100% of the cost, plus 5 other steps (filter, table spool, compute scalar, remote update, update). The fast one just does the UPDATE and Remote Query steps. I need to use variables, so I need a way to force it to do the whole query remotely.
I have tried using OPTION(RECOMPILE) but server1 is using SQL Server 2005. server2 is using SQL Server 2012. I can't change the database structure at all on server2 without serious problems. I am not having any authentication problems. I have tried aliasing the table when updating it.
I have also tried using Openquery. When I put the id filter within the query string, it gets back down to under 1 second:
```
UPDATE OPENQUERY([server2], 'select stuffname, stuffid from database2.dbo.stufftable where contactid=''4CA1D489-9221-E511-A441-005056C00008''')
SET stuffname = @newstuff
```
But I need that id to be a variable as well, and that open query does not take variables (<https://msdn.microsoft.com/en-CA/library/ms188427.aspx>). I tried running Openquery with the id filter outside the query, but that runs in 4 seconds. It's better than 11, but not great:
```
UPDATE OPENQUERY([server2],'select stuffname, stuffid from database2.dbo.stufftable')
set stuffname=@newstuff
where contactid='4CA1D489-9221-E511-A441-005056C00008'
```
Of course, I run openquery using exec(@sql), but I really don't want to go that way. I could do the whole update statement that way using literals and not even use OPENQUERY and get the same sort of result anyway.
Is there any way for me to get this performance fixed without using exec(@sql)? | 2015/07/03 | [
"https://Stackoverflow.com/questions/31212087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1738572/"
] | I believe your problem is related to the permissions that you are running the connection to the LINKED server with.
there are links where this case has been explained and I have had similar experiences.
here are a couple of links:
[OPENQUERY when executing linked server queries in SQL Server](http://blogs.msdn.com/b/sqlsakthi/archive/2011/05/09/best-performer-distributed-query-four-part-or-openquery-when-executing-linked-server-queries-in-sql-server.aspx)
[TOP 3 PERFORMANCE KILLERS FOR LINKED SERVER QUERIES](http://thomaslarock.com/2013/05/top-3-performance-killers-for-linked-server-queries/)
I will post my solution below.
I have set up an environment to test your solution.
my server2 is sql server 2005
my server1 is sql server 2012.
On server2 I have created and populated the stuff table in the following way:
I use a database called tablebackups with a specific naming convention but I am sure you can understand:
The result is a table with a clustered primary key on a identity field and another field for the update. this table in my example has 100,000 records.
```
select @@version
--Microsoft SQL Server 2005 - 9.00.5000.00 (Intel X86)
--Dec 10 2010 10:56:29
--Copyright (c) 1988-2005 Microsoft Corporation
--Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2)
use tablebackups
go
CREATE TABLE dbo._MM_201504710_stuff ( Id UNIQUEIDENTIFIER
, stuffname NVARCHAR(64)
)
ALTER TABLE dbo._MM_201504710_stuff ADD CONSTRAINT [PK_Stuff] UNIQUE CLUSTERED ( ID );
-- add 100,000 records to the table so that we can have an idea of execution
SET NOCOUNT ON
insert into dbo._MM_201504710_stuff values (NewID(),'Radhe Radhe')
GO 100000 -- 100,000
SET NOCOUNT OFF
--this took 19:38
--just to test
SELECT TOP 100 * FROM dbo._MM_201504710_stuff
--18D4BDEA-6226-47E1-94DB-00402A29798F
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE dbo._MM_201504710_stuff
SET stuffname=@newstuff
WHERE Id='18D4BDEA-6226-47E1-94DB-00402A29798F'
UPDATE dbo._MM_201504710_stuff
SET stuffname='new stuff'
WHERE Id='18D4BDEA-6226-47E1-94DB-00402A29798F'
```
the execution plans of these updates are very similar and are not an issue.
As you can see on the picture below.

Before going to server1 I double check when the statistics of my stuff table have been updated, because this will influence the query plan generation.
Just to be sure.

Then I go to server1.
NO, Before I go to server1, on server2 I have this sql login with the following permissions:
I call it "monitor"

and for the permissions of "monitor"
I use this select:
```
SELECT p.[name], sp.permission_name, p.type_desc AS loginType FROM sys.server_principals p
JOIN sys.server_permissions Sp
ON p.principal_id = sp.grantee_principal_id WHERE sp.class = 100
```
That shows me these permissions:

NOW on server1 I have a linked server to server2 (sqlsalon1.dev.boden.local)
and this LINKED server use "monitor" to connect to server2.
as you could see above, this monitor sql user has all the required permissions to see and update the statistics and therefore we can use the best plan even when running remote transactions.
ON SERVER1:
I connect to server2 using the following linked server:


running these scripts (less than a sec)
```
-- just to test
select top 100 *
from [SQLSALON1.dev.boden.local].tablebackups.dbo._MM_201504710_stuff
--first update
UPDATE [SQLSALON1.dev.boden.local].tablebackups.dbo._MM_201504710_stuff
SET stuffname='new stuff'
WHERE Id='18D4BDEA-6226-47E1-94DB-00402A29798F'
--second update
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE [SQLSALON1.dev.boden.local].tablebackups.dbo._MM_201504710_stuff
SET stuffname=@newstuff
WHERE Id='18D4BDEA-6226-47E1-94DB-00402A29798F'
```
I get this query plan:

So, double check the permissions on the linked server account, if you copy mine I believe your problem will be solved, since this is working here, unless there is something else different, and in that case, please let me know, I will try to tackle it further.
**The other way round
From SQL 2005 Updating a table in SQL 2012**
on sql 2012
create and populate the table
```
select @@version
--Microsoft SQL Server 2012 - 11.0.5058.0 (X64)
-- May 14 2014 18:34:29
-- Copyright (c) Microsoft Corporation
-- Standard Edition (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
use tablebackups
go
CREATE TABLE dbo._MM_201504710_stuff ( Id UNIQUEIDENTIFIER
, stuffname NVARCHAR(64)
)
ALTER TABLE dbo._MM_201504710_stuff ADD CONSTRAINT [PK_Stuff] UNIQUE CLUSTERED ( ID );
-- add 100,000 records to the table so that we can have an idea of execution
SET NOCOUNT ON
insert into dbo._MM_201504710_stuff values (NewID(),'Radhe Radhe')
GO 100000 -- 100,000
SET NOCOUNT OFF
--this took 19:38
--just to test
SELECT TOP 100 * FROM dbo._MM_201504710_stuff
--3E29A8E5-BA57-4A9C-803E-003C13A80905
```
after the table is populated I check for the statistics

it turns out that the statistics were NOT updated
so I update the stats:
```
--================================================
-- HAD TO UPDATE THE STATS BEFORE RUNNING THE UPDATES
--================================================
UPDATE STATISTICS dbo._MM_201504710_stuff
```
I check again and it is fine this time.

Create the linked server from sql 2005 to sql 2012:
```
USE [master]
GO
/****** Object: LinkedServer [SQLMON1] Script Date: 13/07/2015 17:09:08 ******/
EXEC master.dbo.sp_addlinkedserver @server = N'SQLMON1', @srvproduct=N'SQL Server'
/* For security reasons the linked server remote logins password is changed with ######## */
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'SQLMON1',@useself=N'False',@locallogin=NULL,@rmtuser=N'monitor',@rmtpassword='########'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'collation compatible', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'data access', @optvalue=N'true'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'dist', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'pub', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'rpc', @optvalue=N'true'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'rpc out', @optvalue=N'true'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'sub', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'connect timeout', @optvalue=N'0'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'collation name', @optvalue=null
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'lazy schema validation', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'query timeout', @optvalue=N'0'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'use remote collation', @optvalue=N'true'
GO
```
I have removed the below server option.

Check the permissions of "monitor" on the target server
```
SELECT p.[name] collate database_default,
sp.permission_name,
p.type_desc AS loginType
FROM sys.server_principals p
JOIN sys.server_permissions Sp
ON p.principal_id = sp.grantee_principal_id
WHERE sp.class = 100
and name = 'monitor'
```

and after that we can run the updates from the sql 2005 server.
```
--first update
UPDATE [SQLMON1].tablebackups.dbo._MM_201504710_stuff
SET stuffname='new stuff'
WHERE Id='3E29A8E5-BA57-4A9C-803E-003C13A80905'
--second update
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE [SQLMON1].tablebackups.dbo._MM_201504710_stuff
SET stuffname=@newstuff
WHERE Id='3E29A8E5-BA57-4A9C-803E-003C13A80905'
```
and this will update the row, with or without a variable, in the same way.
quick as a bolt
 | Perhaps the issue has to do with the unique identifier column. Have you tried:
On server2 define the following stored procedure:
```
CREATE PROCEDURE updateStuff( @newstuff nvarchar(30), @stuffid varchar(36))
AS
UPDATE Stuff
SET stuffname=@newstuff
WHERE stuffId=convert(uniqueidentifier, @stuffid))
```
The from server 1 invoke:
exec server2.database2.updatestuff N'New stuff', '4893CD93-08B3-4981-851B-5DC972288290'
OLD suggestion:
Declare @stuffid uniqueidentifier
Set @stuffid = convert(uniqueidentifier,='4893CD93-08B3-4981-851B-5DC972288290')
UPDATE [server2].database2.dbo.Stuff
SET stuffname=@newstuff
WHERE stuffId=@stuffid |
31,212,087 | I've searched everywhere for this situation and can't find a solution **except for Dynamic SQL, which I don't want to use**.
Here is the table I want to UPDATE on server 2:
```
(Stuff Id UNIQUEIDENTIFIER
, stuffname NVARCHAR(64))
```
I need to update it from server 1.
So I have been attempting this:
```
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE [server2].database2.dbo.Stuff
SET stuffname=@newstuff
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
That takes 11 seconds. This next one using a literal runs in under 1 second
```
UPDATE [server2].database2.dbo.Stuff
SET stuffname='new stuff'
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
I have compared the actual execution plans. The slow one is doing a Remote scan that takes 100% of the cost, plus 5 other steps (filter, table spool, compute scalar, remote update, update). The fast one just does the UPDATE and Remote Query steps. I need to use variables, so I need a way to force it to do the whole query remotely.
I have tried using OPTION(RECOMPILE) but server1 is using SQL Server 2005. server2 is using SQL Server 2012. I can't change the database structure at all on server2 without serious problems. I am not having any authentication problems. I have tried aliasing the table when updating it.
I have also tried using Openquery. When I put the id filter within the query string, it gets back down to under 1 second:
```
UPDATE OPENQUERY([server2], 'select stuffname, stuffid from database2.dbo.stufftable where contactid=''4CA1D489-9221-E511-A441-005056C00008''')
SET stuffname = @newstuff
```
But I need that id to be a variable as well, and that open query does not take variables (<https://msdn.microsoft.com/en-CA/library/ms188427.aspx>). I tried running Openquery with the id filter outside the query, but that runs in 4 seconds. It's better than 11, but not great:
```
UPDATE OPENQUERY([server2],'select stuffname, stuffid from database2.dbo.stufftable')
set stuffname=@newstuff
where contactid='4CA1D489-9221-E511-A441-005056C00008'
```
Of course, I run openquery using exec(@sql), but I really don't want to go that way. I could do the whole update statement that way using literals and not even use OPENQUERY and get the same sort of result anyway.
Is there any way for me to get this performance fixed without using exec(@sql)? | 2015/07/03 | [
"https://Stackoverflow.com/questions/31212087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1738572/"
] | I believe your problem is related to the permissions that you are running the connection to the LINKED server with.
there are links where this case has been explained and I have had similar experiences.
here are a couple of links:
[OPENQUERY when executing linked server queries in SQL Server](http://blogs.msdn.com/b/sqlsakthi/archive/2011/05/09/best-performer-distributed-query-four-part-or-openquery-when-executing-linked-server-queries-in-sql-server.aspx)
[TOP 3 PERFORMANCE KILLERS FOR LINKED SERVER QUERIES](http://thomaslarock.com/2013/05/top-3-performance-killers-for-linked-server-queries/)
I will post my solution below.
I have set up an environment to test your solution.
my server2 is sql server 2005
my server1 is sql server 2012.
On server2 I have created and populated the stuff table in the following way:
I use a database called tablebackups with a specific naming convention but I am sure you can understand:
The result is a table with a clustered primary key on a identity field and another field for the update. this table in my example has 100,000 records.
```
select @@version
--Microsoft SQL Server 2005 - 9.00.5000.00 (Intel X86)
--Dec 10 2010 10:56:29
--Copyright (c) 1988-2005 Microsoft Corporation
--Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2)
use tablebackups
go
CREATE TABLE dbo._MM_201504710_stuff ( Id UNIQUEIDENTIFIER
, stuffname NVARCHAR(64)
)
ALTER TABLE dbo._MM_201504710_stuff ADD CONSTRAINT [PK_Stuff] UNIQUE CLUSTERED ( ID );
-- add 100,000 records to the table so that we can have an idea of execution
SET NOCOUNT ON
insert into dbo._MM_201504710_stuff values (NewID(),'Radhe Radhe')
GO 100000 -- 100,000
SET NOCOUNT OFF
--this took 19:38
--just to test
SELECT TOP 100 * FROM dbo._MM_201504710_stuff
--18D4BDEA-6226-47E1-94DB-00402A29798F
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE dbo._MM_201504710_stuff
SET stuffname=@newstuff
WHERE Id='18D4BDEA-6226-47E1-94DB-00402A29798F'
UPDATE dbo._MM_201504710_stuff
SET stuffname='new stuff'
WHERE Id='18D4BDEA-6226-47E1-94DB-00402A29798F'
```
the execution plans of these updates are very similar and are not an issue.
As you can see on the picture below.

Before going to server1 I double check when the statistics of my stuff table have been updated, because this will influence the query plan generation.
Just to be sure.

Then I go to server1.
NO, Before I go to server1, on server2 I have this sql login with the following permissions:
I call it "monitor"

and for the permissions of "monitor"
I use this select:
```
SELECT p.[name], sp.permission_name, p.type_desc AS loginType FROM sys.server_principals p
JOIN sys.server_permissions Sp
ON p.principal_id = sp.grantee_principal_id WHERE sp.class = 100
```
That shows me these permissions:

NOW on server1 I have a linked server to server2 (sqlsalon1.dev.boden.local)
and this LINKED server use "monitor" to connect to server2.
as you could see above, this monitor sql user has all the required permissions to see and update the statistics and therefore we can use the best plan even when running remote transactions.
ON SERVER1:
I connect to server2 using the following linked server:


running these scripts (less than a sec)
```
-- just to test
select top 100 *
from [SQLSALON1.dev.boden.local].tablebackups.dbo._MM_201504710_stuff
--first update
UPDATE [SQLSALON1.dev.boden.local].tablebackups.dbo._MM_201504710_stuff
SET stuffname='new stuff'
WHERE Id='18D4BDEA-6226-47E1-94DB-00402A29798F'
--second update
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE [SQLSALON1.dev.boden.local].tablebackups.dbo._MM_201504710_stuff
SET stuffname=@newstuff
WHERE Id='18D4BDEA-6226-47E1-94DB-00402A29798F'
```
I get this query plan:

So, double check the permissions on the linked server account, if you copy mine I believe your problem will be solved, since this is working here, unless there is something else different, and in that case, please let me know, I will try to tackle it further.
**The other way round
From SQL 2005 Updating a table in SQL 2012**
on sql 2012
create and populate the table
```
select @@version
--Microsoft SQL Server 2012 - 11.0.5058.0 (X64)
-- May 14 2014 18:34:29
-- Copyright (c) Microsoft Corporation
-- Standard Edition (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
use tablebackups
go
CREATE TABLE dbo._MM_201504710_stuff ( Id UNIQUEIDENTIFIER
, stuffname NVARCHAR(64)
)
ALTER TABLE dbo._MM_201504710_stuff ADD CONSTRAINT [PK_Stuff] UNIQUE CLUSTERED ( ID );
-- add 100,000 records to the table so that we can have an idea of execution
SET NOCOUNT ON
insert into dbo._MM_201504710_stuff values (NewID(),'Radhe Radhe')
GO 100000 -- 100,000
SET NOCOUNT OFF
--this took 19:38
--just to test
SELECT TOP 100 * FROM dbo._MM_201504710_stuff
--3E29A8E5-BA57-4A9C-803E-003C13A80905
```
after the table is populated I check for the statistics

it turns out that the statistics were NOT updated
so I update the stats:
```
--================================================
-- HAD TO UPDATE THE STATS BEFORE RUNNING THE UPDATES
--================================================
UPDATE STATISTICS dbo._MM_201504710_stuff
```
I check again and it is fine this time.

Create the linked server from sql 2005 to sql 2012:
```
USE [master]
GO
/****** Object: LinkedServer [SQLMON1] Script Date: 13/07/2015 17:09:08 ******/
EXEC master.dbo.sp_addlinkedserver @server = N'SQLMON1', @srvproduct=N'SQL Server'
/* For security reasons the linked server remote logins password is changed with ######## */
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'SQLMON1',@useself=N'False',@locallogin=NULL,@rmtuser=N'monitor',@rmtpassword='########'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'collation compatible', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'data access', @optvalue=N'true'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'dist', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'pub', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'rpc', @optvalue=N'true'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'rpc out', @optvalue=N'true'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'sub', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'connect timeout', @optvalue=N'0'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'collation name', @optvalue=null
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'lazy schema validation', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'query timeout', @optvalue=N'0'
GO
EXEC master.dbo.sp_serveroption @server=N'SQLMON1', @optname=N'use remote collation', @optvalue=N'true'
GO
```
I have removed the below server option.

Check the permissions of "monitor" on the target server
```
SELECT p.[name] collate database_default,
sp.permission_name,
p.type_desc AS loginType
FROM sys.server_principals p
JOIN sys.server_permissions Sp
ON p.principal_id = sp.grantee_principal_id
WHERE sp.class = 100
and name = 'monitor'
```

and after that we can run the updates from the sql 2005 server.
```
--first update
UPDATE [SQLMON1].tablebackups.dbo._MM_201504710_stuff
SET stuffname='new stuff'
WHERE Id='3E29A8E5-BA57-4A9C-803E-003C13A80905'
--second update
DECLARE @newstuff nvarchar(64)
SELECT @newstuff = 'new stuff'
UPDATE [SQLMON1].tablebackups.dbo._MM_201504710_stuff
SET stuffname=@newstuff
WHERE Id='3E29A8E5-BA57-4A9C-803E-003C13A80905'
```
and this will update the row, with or without a variable, in the same way.
quick as a bolt
 | You can try setting the value right in the variable declaration:
```
DECLARE @newstuff nvarchar(64) = 'new stuff'
UPDATE [server2].database2.dbo.Stuff
SET stuffname=@newstuff
WHERE stuffId='4893CD93-08B3-4981-851B-5DC972288290'
```
I think deleting the `select` part would help. |
61,479,529 | I have created the following dummy data frame, called **aa** :
```
a b
1 5
2 6
3 7
4 8
```
and the following code:
```
aa_ <-
aa %>%
mutate_at(.vars = vars("a"),
.funs = list(.*b))
```
throws the following error:
>
> Error: expecting a one sided formula, a function, or a function name.
>
>
>
What am I doing wrong?
PD: If I change **"a"** for **a** in the mutate\_at command nothing changes | 2020/04/28 | [
"https://Stackoverflow.com/questions/61479529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13314495/"
] | When using `.` in `mutate_at` you need to specify `~`. Try :
```
library(dplyr)
aa %>% mutate_at(.vars = vars("a"),.funs = list(~. * b))
```
However, `mutate_at` is used when you have a function to apply for more than one column. For only one column, you can directly do :
```
aa %>% mutate(a = a * b)
``` | We can use `mutate_` without the `list`
```
library(dplyr)
aa %>%
mutate_at(vars('a'), ~ . * b)
``` |
36,313,122 | In C#, I have a string array that I have written full full of "getter" method calls. They call methods in another class so that the array is populated with the needed strings. It looks something like this:
```
string[] mCalls = {c.get1(), c.get2(), c.get3()};
```
I'm sure this situation could apply to any program. However, in my program the variables these methods return are initially set with the string `"Unchecked"` - thus filling this example array with Unchecked 3 times. As my program goes on and things are checked, the values of the string variables get changed within the class they're in. I've been simply re-calling the getter methods at appropriate times to change what's in my array, like this:
```
mCalls[0] = c.get1();
mCalls[1] = c.get2();
mCalls[2] = c.get3();
```
I don't really like this. It seems inevitable that one day I'll have to change something, and if that happens I will have to manually do the tedious work of changing all of the indexing throughout my program. If this happens to be the best way I'm fine with that, but I assume there are better ways. So, in any case, **is there a way** to "refresh" the values in an array that is set up like this? And if so, what is it? | 2016/03/30 | [
"https://Stackoverflow.com/questions/36313122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6046887/"
] | You could change your array to contain functions instead of strings like this:
```
Func<string>[] mCalls = { c.get1, c.get2, c.get3...};
```
And then use it this way:
```
string c2 = mCalls[1]();
```
But note that this way *every* access is a method call. I'm not sure what you are really trying to achieve, there may be better overall designs than this approach. | Couple of options:
Create an array of lambdas:
```
var mCalls = new Func<object, string>[] {
(object o) => o.ToString() ,
(object o) => o.GetHashCode().ToString(),
(object o) => o.GetType().ToString(),
};
```
If the input to each lambda is the same you can create a lambda that returns an array:
```
Func<object, string[]> GetValues = (object o) => new string[]
{
o.ToString() ,
o.GetHashCode().ToString(),
o.GetType().ToString(),
};
```
Then just reload the array by calling the lambda:
```
mCalls = GetValues(c);
```
Note that it isn't technically *refreshing* the array, it's creating a *new* array. If you need to keep the array the same but just update the values you'd ned to loop through the array and assign the values by index. |
36,313,122 | In C#, I have a string array that I have written full full of "getter" method calls. They call methods in another class so that the array is populated with the needed strings. It looks something like this:
```
string[] mCalls = {c.get1(), c.get2(), c.get3()};
```
I'm sure this situation could apply to any program. However, in my program the variables these methods return are initially set with the string `"Unchecked"` - thus filling this example array with Unchecked 3 times. As my program goes on and things are checked, the values of the string variables get changed within the class they're in. I've been simply re-calling the getter methods at appropriate times to change what's in my array, like this:
```
mCalls[0] = c.get1();
mCalls[1] = c.get2();
mCalls[2] = c.get3();
```
I don't really like this. It seems inevitable that one day I'll have to change something, and if that happens I will have to manually do the tedious work of changing all of the indexing throughout my program. If this happens to be the best way I'm fine with that, but I assume there are better ways. So, in any case, **is there a way** to "refresh" the values in an array that is set up like this? And if so, what is it? | 2016/03/30 | [
"https://Stackoverflow.com/questions/36313122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6046887/"
] | You want something like this:
```
public string[] MCalls
{
get
{
return new string[]{c.get1(), c.get2(), c.get3()};
}
private set;
}
```
and then use MCalls as if it is a regular variable whenever you want to access the arrays | Couple of options:
Create an array of lambdas:
```
var mCalls = new Func<object, string>[] {
(object o) => o.ToString() ,
(object o) => o.GetHashCode().ToString(),
(object o) => o.GetType().ToString(),
};
```
If the input to each lambda is the same you can create a lambda that returns an array:
```
Func<object, string[]> GetValues = (object o) => new string[]
{
o.ToString() ,
o.GetHashCode().ToString(),
o.GetType().ToString(),
};
```
Then just reload the array by calling the lambda:
```
mCalls = GetValues(c);
```
Note that it isn't technically *refreshing* the array, it's creating a *new* array. If you need to keep the array the same but just update the values you'd ned to loop through the array and assign the values by index. |
36,313,122 | In C#, I have a string array that I have written full full of "getter" method calls. They call methods in another class so that the array is populated with the needed strings. It looks something like this:
```
string[] mCalls = {c.get1(), c.get2(), c.get3()};
```
I'm sure this situation could apply to any program. However, in my program the variables these methods return are initially set with the string `"Unchecked"` - thus filling this example array with Unchecked 3 times. As my program goes on and things are checked, the values of the string variables get changed within the class they're in. I've been simply re-calling the getter methods at appropriate times to change what's in my array, like this:
```
mCalls[0] = c.get1();
mCalls[1] = c.get2();
mCalls[2] = c.get3();
```
I don't really like this. It seems inevitable that one day I'll have to change something, and if that happens I will have to manually do the tedious work of changing all of the indexing throughout my program. If this happens to be the best way I'm fine with that, but I assume there are better ways. So, in any case, **is there a way** to "refresh" the values in an array that is set up like this? And if so, what is it? | 2016/03/30 | [
"https://Stackoverflow.com/questions/36313122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6046887/"
] | You want something like this:
```
public string[] MCalls
{
get
{
return new string[]{c.get1(), c.get2(), c.get3()};
}
private set;
}
```
and then use MCalls as if it is a regular variable whenever you want to access the arrays | You could change your array to contain functions instead of strings like this:
```
Func<string>[] mCalls = { c.get1, c.get2, c.get3...};
```
And then use it this way:
```
string c2 = mCalls[1]();
```
But note that this way *every* access is a method call. I'm not sure what you are really trying to achieve, there may be better overall designs than this approach. |
36,313,122 | In C#, I have a string array that I have written full full of "getter" method calls. They call methods in another class so that the array is populated with the needed strings. It looks something like this:
```
string[] mCalls = {c.get1(), c.get2(), c.get3()};
```
I'm sure this situation could apply to any program. However, in my program the variables these methods return are initially set with the string `"Unchecked"` - thus filling this example array with Unchecked 3 times. As my program goes on and things are checked, the values of the string variables get changed within the class they're in. I've been simply re-calling the getter methods at appropriate times to change what's in my array, like this:
```
mCalls[0] = c.get1();
mCalls[1] = c.get2();
mCalls[2] = c.get3();
```
I don't really like this. It seems inevitable that one day I'll have to change something, and if that happens I will have to manually do the tedious work of changing all of the indexing throughout my program. If this happens to be the best way I'm fine with that, but I assume there are better ways. So, in any case, **is there a way** to "refresh" the values in an array that is set up like this? And if so, what is it? | 2016/03/30 | [
"https://Stackoverflow.com/questions/36313122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6046887/"
] | You could change your array to contain functions instead of strings like this:
```
Func<string>[] mCalls = { c.get1, c.get2, c.get3...};
```
And then use it this way:
```
string c2 = mCalls[1]();
```
But note that this way *every* access is a method call. I'm not sure what you are really trying to achieve, there may be better overall designs than this approach. | What you could do is loop thorugh with reflection and get all methods from the class and from here you can get a list of method names. With this list you can assign to an array or run the methods by name or whatever. You can also filter the list to get your specific method names only:
```
var methodNames = typeof(MyClass).GetMethods(BindingFlags.Public | BindingFlags.Static)
.Select(x => x.Name)
.Distinct()
.OrderBy(x => x);
```
To call the methods:
```
foreach(var method in methodNames)
{
typeof(MyClass).GetMethod(method).Invoke(t, new[] { "world" });
}
``` |
36,313,122 | In C#, I have a string array that I have written full full of "getter" method calls. They call methods in another class so that the array is populated with the needed strings. It looks something like this:
```
string[] mCalls = {c.get1(), c.get2(), c.get3()};
```
I'm sure this situation could apply to any program. However, in my program the variables these methods return are initially set with the string `"Unchecked"` - thus filling this example array with Unchecked 3 times. As my program goes on and things are checked, the values of the string variables get changed within the class they're in. I've been simply re-calling the getter methods at appropriate times to change what's in my array, like this:
```
mCalls[0] = c.get1();
mCalls[1] = c.get2();
mCalls[2] = c.get3();
```
I don't really like this. It seems inevitable that one day I'll have to change something, and if that happens I will have to manually do the tedious work of changing all of the indexing throughout my program. If this happens to be the best way I'm fine with that, but I assume there are better ways. So, in any case, **is there a way** to "refresh" the values in an array that is set up like this? And if so, what is it? | 2016/03/30 | [
"https://Stackoverflow.com/questions/36313122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6046887/"
] | You want something like this:
```
public string[] MCalls
{
get
{
return new string[]{c.get1(), c.get2(), c.get3()};
}
private set;
}
```
and then use MCalls as if it is a regular variable whenever you want to access the arrays | What you could do is loop thorugh with reflection and get all methods from the class and from here you can get a list of method names. With this list you can assign to an array or run the methods by name or whatever. You can also filter the list to get your specific method names only:
```
var methodNames = typeof(MyClass).GetMethods(BindingFlags.Public | BindingFlags.Static)
.Select(x => x.Name)
.Distinct()
.OrderBy(x => x);
```
To call the methods:
```
foreach(var method in methodNames)
{
typeof(MyClass).GetMethod(method).Invoke(t, new[] { "world" });
}
``` |
303,702 | I've two identical 5V akku packs and need a 10V Power supply.
So is it possible to connect these two akku packs in series to reach this or are there any critical issues, that can occur?
Thank you! | 2017/05/06 | [
"https://electronics.stackexchange.com/questions/303702",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/148337/"
] | You would not be connecting two Li-ion batteries in series. Li-ion batteries have a 3.6V output not 5V.
Whether they are in series is less of an issue than the current draw. You should be fine as long as you do not discharge the batteries too fast. That should not be an issue because li-ion batteries are very regulated, must pass safety standard tests, and there is likely a current limit on the output.
Many inexpensive off brand li-ion battery packs are not li-ion but NiMH. If the battery packs were shipped UPS, FedEx, or any way other than strictly ground, they are likely not Li-ion. UPS and FedEx will not ship Li-ion batteries or battery packs unless they are packaged with a device that uses the batteries. | There shouldn't be problem as long as batteries provide same voltage. If one battery in chain is weak, that would stress it, would cause unexpected voltage and current drop. Thus you should not connect batteries of different capacity or "age" for that reason, because one would discharge at different rate. Large "chains" of packs may heat too much, providing reason to failure.
But you shouldn't not probably connect "regulated" battery packs (and 5V-6V packs may come in this way) this way, they include electronics that may not work with that setup. IF it is rated at unusual nominal voltage it's either a lie, or there is voltage converter inside pack |
1,125,084 | How can I make a visitor's browser go fullscreen using JavaScript, in a way that works with IE, Firefox and Opera? | 2009/07/14 | [
"https://Stackoverflow.com/questions/1125084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/63898/"
] | Simple example from: <http://www.longtailvideo.com/blog/26517/using-the-browsers-new-html5-fullscreen-capabilities/>
```
<script type="text/javascript">
function goFullscreen(id) {
// Get the element that we want to take into fullscreen mode
var element = document.getElementById(id);
// These function will not exist in the browsers that don't support fullscreen mode yet,
// so we'll have to check to see if they're available before calling them.
if (element.mozRequestFullScreen) {
// This is how to go into fullscren mode in Firefox
// Note the "moz" prefix, which is short for Mozilla.
element.mozRequestFullScreen();
} else if (element.webkitRequestFullScreen) {
// This is how to go into fullscreen mode in Chrome and Safari
// Both of those browsers are based on the Webkit project, hence the same prefix.
element.webkitRequestFullScreen();
}
// Hooray, now we're in fullscreen mode!
}
</script>
<img class="video_player" src="image.jpg" id="player"></img>
<button onclick="goFullscreen('player'); return false">Click Me To Go Fullscreen! (For real)</button>
``` | ```
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h2>Fullscreen with JavaScript</h2>
<p>Click on the button to open the video in fullscreen mode.</p>
<button onclick="openFullscreen();">Open Video in Fullscreen Mode</button>
<p><strong>Tip:</strong> Press the "Esc" key to exit full screen.</p>
<video width="100%" controls id="myvideo">
<source src="rain.mp4" type="video/mp4">
<source src="rain.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
<script>
var elem = document.getElementById("myvideo");
function openFullscreen() {
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.webkitRequestFullscreen) { /* Safari */
elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) { /* IE11 */
elem.msRequestFullscreen();
}
}
</script>
<p>Note: Internet Explorer 10 and earlier versions do not support the msRequestFullscreen() method.</p>
</body>
</html>
```
Source:<https://www.w3schools.com/howto/howto_js_fullscreen.asp> |
1,125,084 | How can I make a visitor's browser go fullscreen using JavaScript, in a way that works with IE, Firefox and Opera? | 2009/07/14 | [
"https://Stackoverflow.com/questions/1125084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/63898/"
] | Try this script
```
<script language="JavaScript">
function fullScreen(theURL) {
window.open(theURL, '', 'fullscreen=yes, scrollbars=auto' );
}
</script>
```
For calling from script use this code,
```
window.fullScreen('fullscreen.jsp');
```
or with hyperlink use this
```
<a href="javascript:void(0);" onclick="fullScreen('fullscreen.jsp');">
Open in Full Screen Window</a>
``` | `function fs(){plr.requestFullscreen();document.exitFullscreen()};` or `function fs(){(plr.offsetWidth==360)?plr.requestFullscreen():document.exitFullscreen()}`
```
<!DOCTYPE html><html><head>
<style>
body{background:#000}
#plr{position:relative;background:#fff;width:360px}
#vd{width:100%;background:grey}
button{width:48px;height:48px;border:0;background:grey}
</style>
</head><body>
<div id="plr">
<video id="vd" src="video.mp4"></video>
<button onclick="(plr.offsetWidth==360)?plr.requestFullscreen():document.exitFullscreen()">fs</button>
<button onclick="plr.requestFullscreen();document.exitFullscreen()">fs2</button>
</div>
</body></html>
``` |
1,125,084 | How can I make a visitor's browser go fullscreen using JavaScript, in a way that works with IE, Firefox and Opera? | 2009/07/14 | [
"https://Stackoverflow.com/questions/1125084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/63898/"
] | Try [screenfull.js](https://github.com/sindresorhus/screenfull.js). It's a nice cross-browser solution that should work for Opera browser as well.
>
> Simple wrapper for cross-browser usage of the JavaScript Fullscreen API, which lets you bring the page or any element into fullscreen. Smoothens out the browser implementation differences, so you don't have to.
>
>
>
[Demo](https://sindresorhus.com/screenfull.js/). | `function fs(){plr.requestFullscreen();document.exitFullscreen()};` or `function fs(){(plr.offsetWidth==360)?plr.requestFullscreen():document.exitFullscreen()}`
```
<!DOCTYPE html><html><head>
<style>
body{background:#000}
#plr{position:relative;background:#fff;width:360px}
#vd{width:100%;background:grey}
button{width:48px;height:48px;border:0;background:grey}
</style>
</head><body>
<div id="plr">
<video id="vd" src="video.mp4"></video>
<button onclick="(plr.offsetWidth==360)?plr.requestFullscreen():document.exitFullscreen()">fs</button>
<button onclick="plr.requestFullscreen();document.exitFullscreen()">fs2</button>
</div>
</body></html>
``` |
1,125,084 | How can I make a visitor's browser go fullscreen using JavaScript, in a way that works with IE, Firefox and Opera? | 2009/07/14 | [
"https://Stackoverflow.com/questions/1125084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/63898/"
] | **This will works to show your window in full screen**
***Note:*** *For this to work, you need Query from <http://code.jquery.com/jquery-2.1.1.min.js>*
Or make have javascript link like this.
```
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<div id="demo-element">
<span>Full Screen Mode Disabled</span>
<button id="go-button">Enable Full Screen</button>
</div>
<script>
function GoInFullscreen(element) {
if(element.requestFullscreen)
element.requestFullscreen();
else if(element.mozRequestFullScreen)
element.mozRequestFullScreen();
else if(element.webkitRequestFullscreen)
element.webkitRequestFullscreen();
else if(element.msRequestFullscreen)
element.msRequestFullscreen();
}
function GoOutFullscreen() {
if(document.exitFullscreen)
document.exitFullscreen();
else if(document.mozCancelFullScreen)
document.mozCancelFullScreen();
else if(document.webkitExitFullscreen)
document.webkitExitFullscreen();
else if(document.msExitFullscreen)
document.msExitFullscreen();
}
function IsFullScreenCurrently() {
var full_screen_element = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement || null;
if(full_screen_element === null)
return false;
else
return true;
}
$("#go-button").on('click', function() {
if(IsFullScreenCurrently())
GoOutFullscreen();
else
GoInFullscreen($("#demo-element").get(0));
});
$(document).on('fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange', function() {
if(IsFullScreenCurrently()) {
$("#demo-element span").text('Full Screen Mode Enabled');
$("#go-button").text('Disable Full Screen');
}
else {
$("#demo-element span").text('Full Screen Mode Disabled');
$("#go-button").text('Enable Full Screen');
}
});</script>
``` | Try this script
```
<script language="JavaScript">
function fullScreen(theURL) {
window.open(theURL, '', 'fullscreen=yes, scrollbars=auto' );
}
</script>
```
For calling from script use this code,
```
window.fullScreen('fullscreen.jsp');
```
or with hyperlink use this
```
<a href="javascript:void(0);" onclick="fullScreen('fullscreen.jsp');">
Open in Full Screen Window</a>
``` |
1,125,084 | How can I make a visitor's browser go fullscreen using JavaScript, in a way that works with IE, Firefox and Opera? | 2009/07/14 | [
"https://Stackoverflow.com/questions/1125084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/63898/"
] | Try [screenfull.js](https://github.com/sindresorhus/screenfull.js). It's a nice cross-browser solution that should work for Opera browser as well.
>
> Simple wrapper for cross-browser usage of the JavaScript Fullscreen API, which lets you bring the page or any element into fullscreen. Smoothens out the browser implementation differences, so you don't have to.
>
>
>
[Demo](https://sindresorhus.com/screenfull.js/). | Can you Try:
```html
<script type="text/javascript">
function go_full_screen(){
var elem = document.documentElement;
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
}
}
</script>
<a href="#" onClick="go_full_screen();">Full Screen / Compress Screen</a>
``` |
1,125,084 | How can I make a visitor's browser go fullscreen using JavaScript, in a way that works with IE, Firefox and Opera? | 2009/07/14 | [
"https://Stackoverflow.com/questions/1125084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/63898/"
] | Simple example from: <http://www.longtailvideo.com/blog/26517/using-the-browsers-new-html5-fullscreen-capabilities/>
```
<script type="text/javascript">
function goFullscreen(id) {
// Get the element that we want to take into fullscreen mode
var element = document.getElementById(id);
// These function will not exist in the browsers that don't support fullscreen mode yet,
// so we'll have to check to see if they're available before calling them.
if (element.mozRequestFullScreen) {
// This is how to go into fullscren mode in Firefox
// Note the "moz" prefix, which is short for Mozilla.
element.mozRequestFullScreen();
} else if (element.webkitRequestFullScreen) {
// This is how to go into fullscreen mode in Chrome and Safari
// Both of those browsers are based on the Webkit project, hence the same prefix.
element.webkitRequestFullScreen();
}
// Hooray, now we're in fullscreen mode!
}
</script>
<img class="video_player" src="image.jpg" id="player"></img>
<button onclick="goFullscreen('player'); return false">Click Me To Go Fullscreen! (For real)</button>
``` | Now that the full screen APIs are more widespread and appear to be maturing, why not try [Screenfull.js](https://sindresorhus.com/screenfull.js/)? I used it for the first time yesterday and today our app goes truly full screen in (almost) all browsers!
Be sure to couple it with the `:fullscreen` pseudo-class in CSS. See <https://www.sitepoint.com/use-html5-full-screen-api/> for more. |
1,125,084 | How can I make a visitor's browser go fullscreen using JavaScript, in a way that works with IE, Firefox and Opera? | 2009/07/14 | [
"https://Stackoverflow.com/questions/1125084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/63898/"
] | In newer browsers such as Chrome 15, Firefox 10, Safari 5.1, IE 10 this is possible. It's also possible for older IE's via ActiveX depending on their browser settings.
Here's how to do it:
```
function requestFullScreen(element) {
// Supports most browsers and their versions.
var requestMethod = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullScreen;
if (requestMethod) { // Native full screen.
requestMethod.call(element);
} else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
}
var elem = document.body; // Make the body go full screen.
requestFullScreen(elem);
```
The user obviously needs to accept the fullscreen request first, and there is not possible to trigger this automatically on pageload, it needs to be triggered by a user (eg. a button)
Read more: <https://developer.mozilla.org/en/DOM/Using_full-screen_mode> | In Firefox 10, you can make the current page go fullscreen (real fullscreen with no window chrome) using this javascript:
```
window.fullScreen = true;
``` |
1,125,084 | How can I make a visitor's browser go fullscreen using JavaScript, in a way that works with IE, Firefox and Opera? | 2009/07/14 | [
"https://Stackoverflow.com/questions/1125084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/63898/"
] | In newer browsers such as Chrome 15, Firefox 10, Safari 5.1, IE 10 this is possible. It's also possible for older IE's via ActiveX depending on their browser settings.
Here's how to do it:
```
function requestFullScreen(element) {
// Supports most browsers and their versions.
var requestMethod = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullScreen;
if (requestMethod) { // Native full screen.
requestMethod.call(element);
} else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
}
var elem = document.body; // Make the body go full screen.
requestFullScreen(elem);
```
The user obviously needs to accept the fullscreen request first, and there is not possible to trigger this automatically on pageload, it needs to be triggered by a user (eg. a button)
Read more: <https://developer.mozilla.org/en/DOM/Using_full-screen_mode> | **This will works to show your window in full screen**
***Note:*** *For this to work, you need Query from <http://code.jquery.com/jquery-2.1.1.min.js>*
Or make have javascript link like this.
```
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<div id="demo-element">
<span>Full Screen Mode Disabled</span>
<button id="go-button">Enable Full Screen</button>
</div>
<script>
function GoInFullscreen(element) {
if(element.requestFullscreen)
element.requestFullscreen();
else if(element.mozRequestFullScreen)
element.mozRequestFullScreen();
else if(element.webkitRequestFullscreen)
element.webkitRequestFullscreen();
else if(element.msRequestFullscreen)
element.msRequestFullscreen();
}
function GoOutFullscreen() {
if(document.exitFullscreen)
document.exitFullscreen();
else if(document.mozCancelFullScreen)
document.mozCancelFullScreen();
else if(document.webkitExitFullscreen)
document.webkitExitFullscreen();
else if(document.msExitFullscreen)
document.msExitFullscreen();
}
function IsFullScreenCurrently() {
var full_screen_element = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement || null;
if(full_screen_element === null)
return false;
else
return true;
}
$("#go-button").on('click', function() {
if(IsFullScreenCurrently())
GoOutFullscreen();
else
GoInFullscreen($("#demo-element").get(0));
});
$(document).on('fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange', function() {
if(IsFullScreenCurrently()) {
$("#demo-element span").text('Full Screen Mode Enabled');
$("#go-button").text('Disable Full Screen');
}
else {
$("#demo-element span").text('Full Screen Mode Disabled');
$("#go-button").text('Enable Full Screen');
}
});</script>
``` |
1,125,084 | How can I make a visitor's browser go fullscreen using JavaScript, in a way that works with IE, Firefox and Opera? | 2009/07/14 | [
"https://Stackoverflow.com/questions/1125084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/63898/"
] | Here is a complete solution to get in and out of full screen mode (aka cancel, exit, escape)
```
function cancelFullScreen() {
var el = document;
var requestMethod = el.cancelFullScreen||el.webkitCancelFullScreen||el.mozCancelFullScreen||el.exitFullscreen||el.webkitExitFullscreen;
if (requestMethod) { // cancel full screen.
requestMethod.call(el);
} else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
}
function requestFullScreen(el) {
// Supports most browsers and their versions.
var requestMethod = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullscreen;
if (requestMethod) { // Native full screen.
requestMethod.call(el);
} else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
return false
}
function toggleFullScreen(el) {
if (!el) {
el = document.body; // Make the body go full screen.
}
var isInFullScreen = (document.fullScreenElement && document.fullScreenElement !== null) || (document.mozFullScreen || document.webkitIsFullScreen);
if (isInFullScreen) {
cancelFullScreen();
} else {
requestFullScreen(el);
}
return false;
}
``` | Can you Try:
```html
<script type="text/javascript">
function go_full_screen(){
var elem = document.documentElement;
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
}
}
</script>
<a href="#" onClick="go_full_screen();">Full Screen / Compress Screen</a>
``` |
1,125,084 | How can I make a visitor's browser go fullscreen using JavaScript, in a way that works with IE, Firefox and Opera? | 2009/07/14 | [
"https://Stackoverflow.com/questions/1125084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/63898/"
] | Luckily for unsuspecting web users this cannot be done with just javascript. You would need to write browser specific plugins, if they didn't already exist, and then somehow get people to download them. The closest you can get is a maximized window with no tool or navigation bars but users will still be able to see the url.
`window.open('<http://www.web-page.com>', 'title' , 'type=fullWindow, fullscreen, scrollbars=yes');">`
This is generally considered bad practice though as it removes a lot of browser functionality from the user. | ```
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h2>Fullscreen with JavaScript</h2>
<p>Click on the button to open the video in fullscreen mode.</p>
<button onclick="openFullscreen();">Open Video in Fullscreen Mode</button>
<p><strong>Tip:</strong> Press the "Esc" key to exit full screen.</p>
<video width="100%" controls id="myvideo">
<source src="rain.mp4" type="video/mp4">
<source src="rain.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
<script>
var elem = document.getElementById("myvideo");
function openFullscreen() {
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.webkitRequestFullscreen) { /* Safari */
elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) { /* IE11 */
elem.msRequestFullscreen();
}
}
</script>
<p>Note: Internet Explorer 10 and earlier versions do not support the msRequestFullscreen() method.</p>
</body>
</html>
```
Source:<https://www.w3schools.com/howto/howto_js_fullscreen.asp> |
11,239,937 | I am doing an e-learning application using CakePHP.
The problem is that I need to use the word "class" in the Controller so I can get a class link <http://www.site.com/class/>
Is there a way to use the word "class" or not?
I am currently using classroom (http://www.site.com/classroom) but the word itself is long.
Thanks. | 2012/06/28 | [
"https://Stackoverflow.com/questions/11239937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1386587/"
] | I wouldn't recommend it. Check out <http://www.php.net/manual/en/reserved.keywords.php>
>
> You cannot use any of the following words as constants, class names, function or method names. Using them as variable names is generally OK, but could lead to confusion.
>
>
>
Pick a different name, like 'rooms', or leave it as classrooms. Or use Cake's routing. | You cannot have a controller named `class` because that's a PHP restriction, but you can use [routing](http://book.cakephp.org/2.0/en/development/routing.html#connecting-routes) to make the URL `/class` correspond to a controller that has any name you like. |
68,008,678 | In my understanding, a select value will set default value in 2 ways:
1. Check if "selected" attribute for any option
2. Else place first option as selected
```
<select name="gender">
<option>Select Gender</option>
<option value="1">Male</option>
<option value="2">Female</option>
<option value="3">Other</option>
</select>
```
Is there any way through which I can find out by which step(above mentioned) is the default value set for this select | 2021/06/16 | [
"https://Stackoverflow.com/questions/68008678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14023365/"
] | Your issue likely comes from this line:
```
(...args) => event.execute(...args, client)
```
Which means basically "take all of the parameters and pass them to `event.execute`" so you are passing an undetermined amount of parameters (depending on the event type) and the `client` is not guaranteed to be the second one as you expect.
To provide some more details, the Discord client can send multiple different types of events, and every type of event provides a different amount of parameters in the callback. In other words by writing this: `(...args) => event.execute(...args,client)` you are retrieving an unknown amount of parameters, and passing them all to the `event.execute` function, so the position of the `client` parameter could vary, and it's not necessarily the second one as you expect in the function signature: `async execute(message, client) {`
You could either retrieve only the first parameter if you don't need others, like this:
```
client.once(event.name, arg => event.execute(arg, client));
```
And if you absolutely need all of the parameters, pass the client as first so it never moves, like this:
```
client.once(event.name, (...args) => event.execute(client, ...args));
```
Also adapt the `execute` signature:
```
async execute(client, ...args) {
``` | ```
module.exports = {
name: "eg",
description: "not ready",
category: "test",
execute(message, args, client){
const channel = client.channels.cache.get('853031094054944798');
channel.send('test');
}
}
```
it was the addition of args, before client that fixed it.
so in this example:
```
const { prefix } = require("../config.json");
module.exports = {
name: "report",
description: "This command allows you to report a user for smurfing.",
catefory: "misc",
usage: "To report a player, do $report <discord name> <reason>",
async execute(message, args, client) {
const args = message.content.slice(1).trim().split(/ +/);
const offender = message.mentions.users.first();
if (args.length < 2 || !offender.username) {
return message.reply('Please mention the user you want to report and specify a reason.');
}
const reason = args.slice(2).join(' ');
client.channels.cache.get('xxxxx').send(offender);
message.reply("You reported"${offender} for reason: ${reason}`);
}
}
```
It would be this. |
14,505,405 | I know that it is not recommended to block in the `receive` method of an actor, but I believe it can be done (as long as it is not done in too many actors at once).
[This post](http://letitcrash.com/post/29773618510/an-akka-2-terminator) suggests blocking in `preStart` as one way to solve a problem, so presumably blocking in `preStart` is safe.
However, I tried to block in `preRestart` (not `preStart`) and everything seemed to just hang - no more messages were logged as received.
Also, in cases where it is not safe to block, what is a safe alternative? | 2013/01/24 | [
"https://Stackoverflow.com/questions/14505405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/495796/"
] | try to remove the transaction-type="RESOURCE\_LOCAL"
works on my machine without this code | Good luck for your graded exercise, try code underneath ;)
```
public class PersistenceManager {
private static final EntityManagerFactory emf;
private static final ThreadLocal<EntityManager> threadLocal;
private static final Logger logger;
static {
emf = Persistence.createEntityManagerFactory("SupLink");
threadLocal = new ThreadLocal<EntityManager>();
logger = Logger.getLogger("SupLink");
logger.setLevel(Level.ALL);
}
public static EntityManager getEntityManager() {
EntityManager manager = threadLocal.get();
if (manager == null || !manager.isOpen()) {
manager = emf.createEntityManager();
threadLocal.set(manager);
}
return manager;
}
public static void closeEntityManager() {
EntityManager em = threadLocal.get();
threadLocal.set(null);
if (em != null)
em.close();
}
public static void beginTransaction() {
getEntityManager().getTransaction().begin();
}
public static void commit() {
getEntityManager().getTransaction().commit();
}
public static void rollback() {
getEntityManager().getTransaction().rollback();
}
public static Query createQuery(String query) {
return getEntityManager().createQuery(query);
}
public static void log(String info, Level level, Throwable ex) {
logger.log(level, info, ex);
}
}
``` |
20,130,986 | one part of my form is an input-hidden-field:
```
<input type="hidden" name="dump" id="dump" value="">
```
in this hidden-field an array is saved,
now i wanted to ask you which is the best way to check if this array is empty or does the array contain value´s ?
here is what i did:
```
if($_POST["dump"] == "") {
$arr = json_decode($_POST["dump"], true);
if(count($arr) == 0) {
echo "no value´s";
$url = "";
header("Location:".$url);
exit();
}
}
```
what do you think of it? are there any other, maybe more secure way´s to do this?
greetings!! | 2013/11/21 | [
"https://Stackoverflow.com/questions/20130986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2999787/"
] | ```
$dump = $_POST['dump'];
if (!empty($dump)) {
$arr = json_decode($dump, true);
if (!empty($arr)) {
// data is correct
}//add else
}//add else
```
`empty()` will only be false (in this case) if `$arr` is an array with at least one element. Also it will be true if `json_decode` fails (will return "NULL"). You can never trust user input so should always check for its correctness! | Consider using [PHP empty() function](http://php.net/manual/en/function.empty.php)
**PHP.net Reports:**
>
> Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
>
>
> The following things are considered to be empty:
>
>
> "" (an empty string)
>
>
> 0 (0 as an integer)
>
>
> 0.0 (0 as a float)
>
>
> "0" (0 as a string)
>
>
> NULL
>
>
> FALSE
>
>
> array() (an empty array)
>
>
> $var; (a variable declared, but without a value)
>
>
>
It checks for lot of cases in which a var can be empty or not.
So you may want to use
```
if(empty($var)){
// Yes, really empty
} else {
// Not empty at all
}
``` |
20,130,986 | one part of my form is an input-hidden-field:
```
<input type="hidden" name="dump" id="dump" value="">
```
in this hidden-field an array is saved,
now i wanted to ask you which is the best way to check if this array is empty or does the array contain value´s ?
here is what i did:
```
if($_POST["dump"] == "") {
$arr = json_decode($_POST["dump"], true);
if(count($arr) == 0) {
echo "no value´s";
$url = "";
header("Location:".$url);
exit();
}
}
```
what do you think of it? are there any other, maybe more secure way´s to do this?
greetings!! | 2013/11/21 | [
"https://Stackoverflow.com/questions/20130986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2999787/"
] | Consider using [PHP empty() function](http://php.net/manual/en/function.empty.php)
**PHP.net Reports:**
>
> Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
>
>
> The following things are considered to be empty:
>
>
> "" (an empty string)
>
>
> 0 (0 as an integer)
>
>
> 0.0 (0 as a float)
>
>
> "0" (0 as a string)
>
>
> NULL
>
>
> FALSE
>
>
> array() (an empty array)
>
>
> $var; (a variable declared, but without a value)
>
>
>
It checks for lot of cases in which a var can be empty or not.
So you may want to use
```
if(empty($var)){
// Yes, really empty
} else {
// Not empty at all
}
``` | ok this works fine, is it ok? :
```
if(empty($_POST["dump"])) {
$arr = json_decode($_POST["dump"], true);
if(count($arr) == 0) {
$url = "http://test80948.test-account.com/tweetmilliono/test.php";
header("Location:".$url);
exit();
}
}
``` |
20,130,986 | one part of my form is an input-hidden-field:
```
<input type="hidden" name="dump" id="dump" value="">
```
in this hidden-field an array is saved,
now i wanted to ask you which is the best way to check if this array is empty or does the array contain value´s ?
here is what i did:
```
if($_POST["dump"] == "") {
$arr = json_decode($_POST["dump"], true);
if(count($arr) == 0) {
echo "no value´s";
$url = "";
header("Location:".$url);
exit();
}
}
```
what do you think of it? are there any other, maybe more secure way´s to do this?
greetings!! | 2013/11/21 | [
"https://Stackoverflow.com/questions/20130986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2999787/"
] | ```
$dump = $_POST['dump'];
if (!empty($dump)) {
$arr = json_decode($dump, true);
if (!empty($arr)) {
// data is correct
}//add else
}//add else
```
`empty()` will only be false (in this case) if `$arr` is an array with at least one element. Also it will be true if `json_decode` fails (will return "NULL"). You can never trust user input so should always check for its correctness! | ok this works fine, is it ok? :
```
if(empty($_POST["dump"])) {
$arr = json_decode($_POST["dump"], true);
if(count($arr) == 0) {
$url = "http://test80948.test-account.com/tweetmilliono/test.php";
header("Location:".$url);
exit();
}
}
``` |
2,431,725 | Let $X\sim U([1,2])$ and $Y=\frac{1}{X}$
How do I calculate the mean of Y?
I know that
$$f(x)=\begin{cases}1
& \text{ if } 1\leq x\leq 2 \\
0& \text{ otherwise }
\end{cases}$$
Does that mean that
$$f(y)=\begin{cases}1
& \text{ if } 1\leq \frac{1}{y}\leq 2 \Leftrightarrow \frac{1}{2}\leq y\leq 1\\
0& \text{ otherwise }
\end{cases}$$
if so then the mean value should be:
$$\int\_{1/2}^{1}y=\int\_{1/2}^{1}\frac{1}{x} dx$$
Is this correct? | 2017/09/16 | [
"https://math.stackexchange.com/questions/2431725",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/481273/"
] | By the [Law of the unconscious statistician](https://en.wikipedia.org/wiki/Law_of_the_unconscious_statistician),
$$
\mathbb{E}[Y] = \mathbb{E}\left[\frac{1}{X}\right] = \int\_\mathbb{R} \frac{1}{x} f\_X(x)dx
= \int\_1^2 \frac{1}{x} dx = \ln 2
$$
since $f\_X(x) = \begin{cases}1 &\text{ if } 1\leq x\leq 2\\0& \text {otherwise.}\end{cases}$ | Use the transformation formula
$$p(Y)=p(X)\left|\frac{dX}{dY}\right|=\frac{1}{Y^2}$$
where $Y \in [\frac{1}{2},1]$
So
$$E[Y]=\int\_{1/2}^1 Y\frac{1}{Y^2}dY=\int\_{1/2}^1\frac{1}{Y}dY=\ln1-\ln\frac{1}{2}=\ln 2$$ |
31,603,398 | How can I get the email of a user from the facebook LoginButton widget?
I am getting null. The App Id I am using is correct. I can also get the correct name, but the email is missing. I do have permissions.
This is my code:
```
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;
// ...
public class MainActivity extends FragmentActivity {
// ...
@Override
public void onCreate(Bundle savedInstanceState) {
//
LoginButton loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
@Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
userName.setText("Hello, " + user.getName());
Toast.makeText(getApplicationContext(),
"User Name is , " + user.getName(), Toast.LENGTH_LONG)
.show();
Toast.makeText(getApplicationContext(),
"Email Id is , " + user.getProperty("email") , Toast.LENGTH_LONG)
.show();
} else {
userName.setText("You are not logged");
}
}
});
}
// ...
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions","email","basic_info");
public void requestPermissions() {
Session s = Session.getActiveSession();
if (s != null)
s.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSIONS));
}
``` | 2015/07/24 | [
"https://Stackoverflow.com/questions/31603398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4823878/"
] | ```
public class Login extends ActionBarActivity {
private CallbackManager callbackManager;
String emailid, gender, bday, username;
private LoginButton loginButton;
ProfilePictureView profilePictureView;
TextView info;
private AccessTokenTracker accessTokenTracker;
private ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.login);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays
.asList("public_profile, email, user_birthday, user_friends"));
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
new fblogin().execute(loginResult.getAccessToken());
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException e) {
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
class fblogin extends AsyncTask<AccessToken, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("wait.");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(AccessToken... params) {
GraphRequest request = GraphRequest.newMeRequest(params[0],
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object,
GraphResponse response) {
Log.v("LoginActivity", response.toString());
try {
username = object.getString("first_name");
emailid = object.getString("email");
gender = object.getString("gender");
bday = object.getString("birthday");
} catch (JSONException e) {
// TODO Auto-generated catch
// block
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields",
"id,first_name,email,gender,birthday");
request.setParameters(parameters);
request.executeAndWait();
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
```
This method work in Async manner.
Its Done . !! | You can fetch user email by sending `Request.newMeRequest` request. For this you need `UiLifecycleHelper` callback
`UiLifecycleHelper fbUiHelper = new UiLifecycleHelper(this, fbUiHelperCallback);`
```
private Session.StatusCallback fbUiHelperCallback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
getUserData(session, state);
}
private void getUserData(Session session, SessionState state) {
if (state.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
if (response != null) {
String name = user.getName();
// If you asked for email permission
String gender = (String) user.getProperty("gender");
String email = (String) user.getProperty("email");
}
}
}).executeAsync();
}
}
``` |
167,110 | With pretty much every circuit in a home needing one of the two types of protection (AFCI or GFCI), why don't all new homes have combination breakers installed just to be safe? Would it hurt anything using both types of protections for every breaker? I know that based on code we technically don't NEED both types of protection, but is it necessarily a bad thing to have?
Of course this wouldn't apply to circuits that have exemptions such as dedicated circuits for an appliance. | 2019/06/12 | [
"https://diy.stackexchange.com/questions/167110",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/45053/"
] | Sure, go for it
---------------
There's no basic problem with what you propose. Feel free to put CAFCIs in all breaker positions.
You may have a problem finding AFCIs larger than 20/30 amps, and you may have trouble finding 2-pole AFCIs in some cases. In this instance, for equivalent protection where AFCI is not mandated, simply run those circuits in metal conduit, e.g. EMT/THHN wire. This will protect the wire, not the appliances. | AFCI breakers (which NEC now requires on new houses) make a lot of sense. Issues with wires going bad are pretty rare and there's not too many things outside that that can trip one. The likelihood of a nuisance AFCI trip is fairly low.
AFCIs also protect against hidden dangers. Arcing events can happen in hidden locations (like junction boxes) and you might not realize it until the fire department figures out what burned down your house.
GFCIs, however, are much more prone to nuisance trips. Imagine you dropped your hair dryer in a sink. Most GFCIs are next to the point where a grounding event can happen (i.e. inside an outlet). This makes them easy to diagnose and reset. If that GFCI is on the breaker, however, that may not be obvious at all.
GFCI might also be on something you don't want to be subject to nuisance trips. A kitchen refrigerator might get its own circuit, but what about a freezer or mini-fridge?
The final nail in the coffin here is cost. You're going to add a lot of cost to mitigate the small chance that somewhere not already covered by GFCI requirements is going to experience a grounding event. |
23,362 | Your program must take as input a line of characters, like this:
```
@+.0
```
And output the characters sorted by how dark they are, like this:
```
.+0@
```
Requirements:
* You must use a monospaced font for darkness detection.
* You must find out how many pixels each character takes up. You must actually draw the character and count pixels, i.e. you can't just hardcode pixel amounts.
+ As a more concrete rule: if you switched fonts, your program should still work. Furthermore, your program should be able to switch fonts by simply changing a variable or value or string in the code.
* If you use antialiasing, you must count pixels as percentages of a fully black pixel. For example, an `rgb(32, 32, 32)` pixel will count as 1/8 of a full pixel. Disregard this rule if your characters are not antialiased.
* After counting pixels, you must sort the characters by the amount of pixels, and output them in order.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win. | 2014/03/07 | [
"https://codegolf.stackexchange.com/questions/23362",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/3808/"
] | Java, 584
=========
Wow... This was not a good language to do this in.
```
import java.awt.geom.*;import java.util.*;class F{static void n(final String f,List<Character> s){Collections.sort(s,new Comparator<Character>(){public int compare(Character a,Character b){return d(f,""+a) - d(f,""+b);}});}static int d(String f,String s){int i=0;PathIterator p=new java.awt.Font(f,0,12).createGlyphVector(((java.awt.Graphics2D)new java.awt.image.BufferedImage(8,8,2).getGraphics()).getFontRenderContext(),s).getGlyphOutline(0).getPathIterator(AffineTransform.getRotateInstance(0.0, 0.0));while(!p.isDone()){i+=p.currentSegment(new double[99])/2;p.next();}return i;}}
```
Usage:
```
import java.awt.geom.*;
import java.util.*;
public class F {
public static void main(String[]args){
List<Character> s = new ArrayList<Character>(0);
s.add('@');
s.add('+');
s.add('.');
s.add('0');
n("Calibri", s);
System.out.println(s);
}
static void n(final String f,List<Character> s){
Collections.sort(s,new Comparator<Character>(){
public int compare(Character a,Character b){
return d(f,""+a) - d(f,""+b);
}
});
}
static int d(String f,String s){
int i=0;
PathIterator p=new java.awt.Font(f,0,12).createGlyphVector(((java.awt.Graphics2D)new java.awt.image.BufferedImage(8,8,2).getGraphics()).getFontRenderContext(),s).getGlyphOutline(0).getPathIterator(AffineTransform.getRotateInstance(0.0, 0.0));
while(!p.isDone()){
i+=p.currentSegment(new double[99])/2;
p.next();
}
return i;
}
}
```
This setup results in:
```
[., +, 0, @]
```
---
The only line here that needs explanation:
```
PathIterator p=new java.awt.Font(f,0,12).createGlyphVector(((java.awt.Graphics2D)new java.awt.image.BufferedImage(8,8,2).getGraphics()).getFontRenderContext(),s).getGlyphOutline(0).getPathIterator(AffineTransform.getRotateInstance(0.0, 0.0));
```
* Initialize the 12pt font object with the passed font.
* Create a new BufferedImage obejct to create a Graphics2D object linked to a GraphicsContext.
* Get the font rendering context of the 2D graphics context for the string s.
* Get the first glyph (only glyph) in the string.
* Get the path iterator (list of points).
Then this final piece brings it together...
```
while(!p.isDone()){
i+=p.currentSegment(new double[99])/2;
p.next();
}
```
By iterating through all points and summing count of points. This density information is passed back up to the comparator and is used for sorting. | PHP - 485
=========
Demo:
```
$ php pcg-23362.php "@+.0"
.+0@
```
Code:
```
<?php $f='x.ttf';$d=array();foreach(str_split($argv[1]) as$_){$B=imagettfbbox(50,0,$f,$_);$w=abs($B[4]-$B[0]);$h=abs($B[5]-$B[1]);$im=imagecreate($w,$h);imagecolorallocate($im,255,255,255);imagettftext($im,50,0,0,$h-$B[1],imagecolorallocate($im,0,0,0),$f,$_);$b=$w*$h;for($x=0;$x<$w;$x++)for($y=0;$y<$h;$y++){$z=imagecolorsforindex($im,imagecolorat($im,$x,$y));$color=$z['red']*$z['green']*$z['blue'];$b-=$color/0x1000000;}$d[$_]=$b / ($w * $h);}asort($d);echo implode(array_keys($d));
``` |
23,362 | Your program must take as input a line of characters, like this:
```
@+.0
```
And output the characters sorted by how dark they are, like this:
```
.+0@
```
Requirements:
* You must use a monospaced font for darkness detection.
* You must find out how many pixels each character takes up. You must actually draw the character and count pixels, i.e. you can't just hardcode pixel amounts.
+ As a more concrete rule: if you switched fonts, your program should still work. Furthermore, your program should be able to switch fonts by simply changing a variable or value or string in the code.
* If you use antialiasing, you must count pixels as percentages of a fully black pixel. For example, an `rgb(32, 32, 32)` pixel will count as 1/8 of a full pixel. Disregard this rule if your characters are not antialiased.
* After counting pixels, you must sort the characters by the amount of pixels, and output them in order.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win. | 2014/03/07 | [
"https://codegolf.stackexchange.com/questions/23362",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/3808/"
] | Mathematica, 112 110 108 bytes
------------------------------
This can still likely be golfed further. Assumes the string is in variable s.
And now uses a correct syntax to sort one list by another list.
Lucky test cases -> "Oh yeah, that works" -> *Facepalm*
Thanks for the sharp eyes, David Carraher.
**Update:** Replaced OCR A with Menlo because I realized that on OSX the OCR A font family name is actually OCR A Std. So I was sorting a default font instead of the real deal. Menlo is also monospaced with the same byte count, so no net gain or loss.
I've put up a [hosted CDF export of the notebook](http://www.jonathanvanmatre.com/blog/mathematica-notebooks/), so you can see the code in action if you wish. I'm still figuring out how to add some interactivity to web-hosted CDFs, so for now it's just static.
```m
c=Characters@s;Last/@Sort[Transpose@{Total[1-#&/@ImageData@Rasterize@Style[#,FontFamily->"Menlo"],3]&/@c,c}]
```
Output for `s = FromCharacterCode /@ Range[33, 135];` with "Courier"

Output for same, but with FontFamily "Monospace":

Note that the final results are shown in MM's internal font, not in the font being sorted. Hence, you see the differences in the font chosen reflected in the sort. The CDF link shows both, though, for the completists.
Ungolfed code:
```m
s = FromCharacterCode /@ Range[33, 135];
c = Characters@s;
Last /@ Sort[
Transpose@{Total[1 - # & /@
ImageData@Rasterize@Style[#, FontFamily -> "Menlo"], 3] & /@ c, c}]
``` | Javascript + Canvas and Browser DOM (280 237 235 bytes)
=======================================================
*Updated version with suggetions from Fors and toothbrush in comments:*
```
function m(x){a=document.createElement('canvas').getContext('2d');a.font='9px Monaco';a.fillText(x,y=i=0,20);for(;i<3600;)y+=a.getImageData(0,0,30,30).data[i++];return y}alert(s.split('').sort(function(a,b){return m(a)-m(b)}).join(''))
```
More readable version:
```
// Scoring function - Calculates darkness for single character
function m(x) {
a = document.createElement('canvas').getContext('2d');
a.font = '9px Monaco';
a.fillText(x, y = i = 0, 20);
for (; i < 3600;) y += a.getImageData(0, 0, 30, 30).data[i++];
return y
}
// Assume input is in variable s and alert as output. Comparison function now expression.
alert(s.split('').sort(function (a, b) {
return m(a) - m(b)
}).join(''))
```
Can maybe be golfed more.
I'm new to this site, so I am unsure how input is normally read for Javascript answers. I assume input is contained in a variable named `s`. If this is not OK, I will update the answer and the char count.
[JSFiddle of updated version.](http://jsfiddle.net/waxwing/ABXEU/4/)
[JSFiddle of first version](http://jsfiddle.net/waxwing/ABXEU/). |
23,362 | Your program must take as input a line of characters, like this:
```
@+.0
```
And output the characters sorted by how dark they are, like this:
```
.+0@
```
Requirements:
* You must use a monospaced font for darkness detection.
* You must find out how many pixels each character takes up. You must actually draw the character and count pixels, i.e. you can't just hardcode pixel amounts.
+ As a more concrete rule: if you switched fonts, your program should still work. Furthermore, your program should be able to switch fonts by simply changing a variable or value or string in the code.
* If you use antialiasing, you must count pixels as percentages of a fully black pixel. For example, an `rgb(32, 32, 32)` pixel will count as 1/8 of a full pixel. Disregard this rule if your characters are not antialiased.
* After counting pixels, you must sort the characters by the amount of pixels, and output them in order.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win. | 2014/03/07 | [
"https://codegolf.stackexchange.com/questions/23362",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/3808/"
] | Mathematica, 112 110 108 bytes
------------------------------
This can still likely be golfed further. Assumes the string is in variable s.
And now uses a correct syntax to sort one list by another list.
Lucky test cases -> "Oh yeah, that works" -> *Facepalm*
Thanks for the sharp eyes, David Carraher.
**Update:** Replaced OCR A with Menlo because I realized that on OSX the OCR A font family name is actually OCR A Std. So I was sorting a default font instead of the real deal. Menlo is also monospaced with the same byte count, so no net gain or loss.
I've put up a [hosted CDF export of the notebook](http://www.jonathanvanmatre.com/blog/mathematica-notebooks/), so you can see the code in action if you wish. I'm still figuring out how to add some interactivity to web-hosted CDFs, so for now it's just static.
```m
c=Characters@s;Last/@Sort[Transpose@{Total[1-#&/@ImageData@Rasterize@Style[#,FontFamily->"Menlo"],3]&/@c,c}]
```
Output for `s = FromCharacterCode /@ Range[33, 135];` with "Courier"

Output for same, but with FontFamily "Monospace":

Note that the final results are shown in MM's internal font, not in the font being sorted. Hence, you see the differences in the font chosen reflected in the sort. The CDF link shows both, though, for the completists.
Ungolfed code:
```m
s = FromCharacterCode /@ Range[33, 135];
c = Characters@s;
Last /@ Sort[
Transpose@{Total[1 - # & /@
ImageData@Rasterize@Style[#, FontFamily -> "Menlo"], 3] & /@ c, c}]
``` | Postscript, 381
---------------
Here's something completely different, just for fun. As most fonts are vector anyway, 'counting pixels' is a little odd, isn't it. Calculating glyph shape area, while being correct way, is not that easy. An alternative can be scanning a rectangle and counting 'hits' when a point is inside a glyph shape, and Postscript has operators for this kind of checks. Though, true, scanning and insideness-testing is just a weird way of counting pixels.
```
(%stdin)(r)file token pop/Courier 99 selectfont[1 index length{0}repeat]0 1 99{0 1 99{0 1 5 index length 1 sub{newpath 9 19 moveto 3 copy 7 index exch 1 getinterval false charpath infill{3 index exch 2 copy get 1 add put}{pop}ifelse}for pop}for pop}for 0 1 99 dup mul{0 1 3 index length 1 sub{dup 3 index exch get 2 index eq{3 index exch 1 getinterval print}{pop}ifelse}for pop}for
```
.
```
(%stdin) (r) file token pop
/Courier 99 selectfont
%/DejaVuSansMono 99 selectfont
%/UbuntuMono-Regular 99 selectfont
[ 1 index length {0} repeat ] % str []
0 1 99 {
0 1 99 {
0 1 5 index length 1 sub {
newpath
9 19 moveto
3 copy % str [] n m i n m i
7 index exch % str [] n m i n m str i
1 getinterval % str [] n m i n m s
false charpath % str [] n m i n m
infill % str [] n m i bool
{3 index exch 2 copy get 1 add put} {pop} ifelse
} for
pop
} for
pop
} for
% un-comment next line to print number of 'hits' for each glyph
%
% dup {=} forall
%
% next is 'lazy sort'
0 1 99 dup mul { % str [] i
0 1 3 index length 1 sub { % str [] i j
dup 3 index exch % str [] i j [] j
get 2 index eq % str [] i j bool
{3 index exch 1 getinterval print} {pop} ifelse
} for
pop
} for
()=
```
And here are results for 3 different fonts (selection of which can be un-commented, above):
```
$ echo '(.-?@AByz01)' | gs -q -dBATCH d.ps
.-?1z0yA@B
$ echo '(.-?@AByz01)' | gs -q -dBATCH d.ps
.-?z1yA0B@
$ echo '(.-?@AByz01)' | gs -q -dBATCH d.ps
.-?1zyA0B@
``` |
23,362 | Your program must take as input a line of characters, like this:
```
@+.0
```
And output the characters sorted by how dark they are, like this:
```
.+0@
```
Requirements:
* You must use a monospaced font for darkness detection.
* You must find out how many pixels each character takes up. You must actually draw the character and count pixels, i.e. you can't just hardcode pixel amounts.
+ As a more concrete rule: if you switched fonts, your program should still work. Furthermore, your program should be able to switch fonts by simply changing a variable or value or string in the code.
* If you use antialiasing, you must count pixels as percentages of a fully black pixel. For example, an `rgb(32, 32, 32)` pixel will count as 1/8 of a full pixel. Disregard this rule if your characters are not antialiased.
* After counting pixels, you must sort the characters by the amount of pixels, and output them in order.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win. | 2014/03/07 | [
"https://codegolf.stackexchange.com/questions/23362",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/3808/"
] | Java - ~~468 450~~ 444
----------------------
```java
public static void main(String[]a){class c implements Comparable<c>{char d;c(char e){d=e;}public int compareTo(c o){return e(d)>e(o.d)?1:-1;}int e(char f){int a=0,x,y;BufferedImage img=new BufferedImage(99,99,1);img.getGraphics().drawString(""+f,9,80);for(y=0;y<99;y++)for(x=0;x<99;x++)a+=img.getRGB(x,y);return a;}}c[]s=new c[a[0].length()];int i=0;for(char d:a[0].toCharArray())s[i++]=new c(d);Arrays.sort(s);for(c d:s)System.out.print(d.d);}
```
`@+.0abcdefghijklmnopqrstuvwxyz`
->
`.irl+jcvtfxyzsuonkheaqpdb0wgm@`
Ungolfed:
```java
public static void main(String[] a) {
a = new String[]{"@+.0abcdefghijklmnopqrstuvwxyz"};
class c implements Comparable<c> {
char d;
c(char e) {
d = e;
}
@Override
public int compareTo(c o) {
return e(d) > e(o.d)? 1 : -1;
}
int e(char f) {
int a = 0, x, y;
BufferedImage img = new BufferedImage(99, 99, 1);
img.getGraphics().drawString("" + f, 9, 80);
for (y = 0; y < 99; y++)
for (x = 0; x < 99; x++)
a += img.getRGB(x, y);
return a;
}
}
c[] s = new c[a[0].length()];
int i = 0;
for (char d : a[0].toCharArray())
s[i++] = new c(d);
Arrays.sort(s);
for (c d : s)
System.out.print(d.d);
}
``` | ### R, 195 characters
```
A=strsplit(scan(,""),"")[[1]];cat(A[order(sapply(A,function(x){png('a',a='none',fa='monospace');frame();text(0,0,x);dev.off();sum(apply(png::readPNG('a'),c(1,2),function(x)any(x!=1)))}))],sep="")
```
Indented with comments:
```r
A=strsplit(scan(,""),"")[[1]] #Take characters as strings and split into single chars
cat(A[order(sapply(A,function(x){ #Apply the following function to each char and order accordingly
png('a',a='none',fa='monospace'); #Open empty png without antialiasing and with monospace font
frame(); #create empty plot
text(0,0,x); #add the char as text to the plot
dev.off(); #close png device
sum(apply(png::readPNG('a'), #read it back as rbga 3d matrix
c(1,2), #check every layer (R, G, B, A)
function(x)any(x!=1))) #if any are not 1, send TRUE
}))], #Sum all TRUEs
sep="") #Prints to output
```
Example:
```
> A=strsplit(scan(,""),"")[[1]];cat(A[order(sapply(A,function(x){png('a',a='none',fa='monospace');frame();text(0,0,x);dev.off();sum(apply(png::readPNG('a'),c(1,2),function(x)any(x!=1)))}))],sep="")
1: @+.0
2:
Read 1 item
.+0@
> A=strsplit(scan(,""),"")[[1]];cat(A[order(sapply(A,function(x){png('a',a='none',fa='monospace');frame();text(0,0,x);dev.off();sum(apply(png::readPNG('a'),c(1,2),function(x)any(x!=1)))}))],sep="")
1: 1234567890
2:
Read 1 item
1723450689
```
The gestion of fonts in R plots being platform-dependent, I cannot guarantee that it works on PC, but it does on a Mac (OS X 10.7.5, R 2.14.2). |
23,362 | Your program must take as input a line of characters, like this:
```
@+.0
```
And output the characters sorted by how dark they are, like this:
```
.+0@
```
Requirements:
* You must use a monospaced font for darkness detection.
* You must find out how many pixels each character takes up. You must actually draw the character and count pixels, i.e. you can't just hardcode pixel amounts.
+ As a more concrete rule: if you switched fonts, your program should still work. Furthermore, your program should be able to switch fonts by simply changing a variable or value or string in the code.
* If you use antialiasing, you must count pixels as percentages of a fully black pixel. For example, an `rgb(32, 32, 32)` pixel will count as 1/8 of a full pixel. Disregard this rule if your characters are not antialiased.
* After counting pixels, you must sort the characters by the amount of pixels, and output them in order.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win. | 2014/03/07 | [
"https://codegolf.stackexchange.com/questions/23362",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/3808/"
] | Mathematica, 112 110 108 bytes
------------------------------
This can still likely be golfed further. Assumes the string is in variable s.
And now uses a correct syntax to sort one list by another list.
Lucky test cases -> "Oh yeah, that works" -> *Facepalm*
Thanks for the sharp eyes, David Carraher.
**Update:** Replaced OCR A with Menlo because I realized that on OSX the OCR A font family name is actually OCR A Std. So I was sorting a default font instead of the real deal. Menlo is also monospaced with the same byte count, so no net gain or loss.
I've put up a [hosted CDF export of the notebook](http://www.jonathanvanmatre.com/blog/mathematica-notebooks/), so you can see the code in action if you wish. I'm still figuring out how to add some interactivity to web-hosted CDFs, so for now it's just static.
```m
c=Characters@s;Last/@Sort[Transpose@{Total[1-#&/@ImageData@Rasterize@Style[#,FontFamily->"Menlo"],3]&/@c,c}]
```
Output for `s = FromCharacterCode /@ Range[33, 135];` with "Courier"

Output for same, but with FontFamily "Monospace":

Note that the final results are shown in MM's internal font, not in the font being sorted. Hence, you see the differences in the font chosen reflected in the sort. The CDF link shows both, though, for the completists.
Ungolfed code:
```m
s = FromCharacterCode /@ Range[33, 135];
c = Characters@s;
Last /@ Sort[
Transpose@{Total[1 - # & /@
ImageData@Rasterize@Style[#, FontFamily -> "Menlo"], 3] & /@ c, c}]
``` | PHP, 298 characters
===================
I've added a few line breaks so you can see it in all its hideousness:
```
<?php
$s=@$_GET[s];$a=array();$v=imagecreate(16,16);$f='imagecolorallocate';
$f($v,0,0,0);for($i=0;$i<strlen($s);$i++){$c=$f($v,$i,0,1);
imagechar($v,5,2,$n=0,$s[$i],$c);for($y=16;$y--;)
for($x=16;$x--;)$n+=($c==imagecolorat($v,$x,$y));
$a[]=ord($s[$i])+($n<<8);}sort($a);foreach($a as $v)echo chr($v);
```
This code uses the GD fonts that come built-in with PHP. The second argument of `imagechar()` selects the font (numbers from 1 to 5 are valid).
**Example:**
```
Input: !@#$%^&*-=WEIX,./'
Output: '-.,^=!/*IE%X#$&@W
```
If you insert the following on top of the code shown above, then you'll be able to supply the list of characters in your web browser.
```
<?php
define("FONT_SIZE",5);
if(@$_SERVER['PATH_INFO']=='/a.png') {
$s = $_GET['s'];
$im = imagecreate(strlen($s)*(FONT_SIZE+4)+4,FONT_SIZE+12);
imagecolorallocate($im,255,255,128);
$c = imagecolorallocate($im,0,0,0);
imagestring($im,FONT_SIZE,2,0,$s,$c);
header("Content-Type: image/png");
imagepng($im);
imagedestroy($im);
exit();
}
$me = $_SERVER['PHP_SELF'];
$t1 = $img = "";
if ($t1=htmlspecialchars(@$_GET['s'])) {
$t2=urlencode($_GET['s']);
$img="<p><img src=\"$me/a.png?s=$t2\" /></p>";
}
echo <<<END_HTML
<html>
<body>
$img
<form action="$me" method="get">
<input type="text" name="s" size="40" value="$t1" />
<input type="submit" value="Go" />
</form>
END_HTML;
if(!isset($_GET['s'])) exit();
?>
``` |
23,362 | Your program must take as input a line of characters, like this:
```
@+.0
```
And output the characters sorted by how dark they are, like this:
```
.+0@
```
Requirements:
* You must use a monospaced font for darkness detection.
* You must find out how many pixels each character takes up. You must actually draw the character and count pixels, i.e. you can't just hardcode pixel amounts.
+ As a more concrete rule: if you switched fonts, your program should still work. Furthermore, your program should be able to switch fonts by simply changing a variable or value or string in the code.
* If you use antialiasing, you must count pixels as percentages of a fully black pixel. For example, an `rgb(32, 32, 32)` pixel will count as 1/8 of a full pixel. Disregard this rule if your characters are not antialiased.
* After counting pixels, you must sort the characters by the amount of pixels, and output them in order.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win. | 2014/03/07 | [
"https://codegolf.stackexchange.com/questions/23362",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/3808/"
] | ### R, 195 characters
```
A=strsplit(scan(,""),"")[[1]];cat(A[order(sapply(A,function(x){png('a',a='none',fa='monospace');frame();text(0,0,x);dev.off();sum(apply(png::readPNG('a'),c(1,2),function(x)any(x!=1)))}))],sep="")
```
Indented with comments:
```r
A=strsplit(scan(,""),"")[[1]] #Take characters as strings and split into single chars
cat(A[order(sapply(A,function(x){ #Apply the following function to each char and order accordingly
png('a',a='none',fa='monospace'); #Open empty png without antialiasing and with monospace font
frame(); #create empty plot
text(0,0,x); #add the char as text to the plot
dev.off(); #close png device
sum(apply(png::readPNG('a'), #read it back as rbga 3d matrix
c(1,2), #check every layer (R, G, B, A)
function(x)any(x!=1))) #if any are not 1, send TRUE
}))], #Sum all TRUEs
sep="") #Prints to output
```
Example:
```
> A=strsplit(scan(,""),"")[[1]];cat(A[order(sapply(A,function(x){png('a',a='none',fa='monospace');frame();text(0,0,x);dev.off();sum(apply(png::readPNG('a'),c(1,2),function(x)any(x!=1)))}))],sep="")
1: @+.0
2:
Read 1 item
.+0@
> A=strsplit(scan(,""),"")[[1]];cat(A[order(sapply(A,function(x){png('a',a='none',fa='monospace');frame();text(0,0,x);dev.off();sum(apply(png::readPNG('a'),c(1,2),function(x)any(x!=1)))}))],sep="")
1: 1234567890
2:
Read 1 item
1723450689
```
The gestion of fonts in R plots being platform-dependent, I cannot guarantee that it works on PC, but it does on a Mac (OS X 10.7.5, R 2.14.2). | PHP - 485
=========
Demo:
```
$ php pcg-23362.php "@+.0"
.+0@
```
Code:
```
<?php $f='x.ttf';$d=array();foreach(str_split($argv[1]) as$_){$B=imagettfbbox(50,0,$f,$_);$w=abs($B[4]-$B[0]);$h=abs($B[5]-$B[1]);$im=imagecreate($w,$h);imagecolorallocate($im,255,255,255);imagettftext($im,50,0,0,$h-$B[1],imagecolorallocate($im,0,0,0),$f,$_);$b=$w*$h;for($x=0;$x<$w;$x++)for($y=0;$y<$h;$y++){$z=imagecolorsforindex($im,imagecolorat($im,$x,$y));$color=$z['red']*$z['green']*$z['blue'];$b-=$color/0x1000000;}$d[$_]=$b / ($w * $h);}asort($d);echo implode(array_keys($d));
``` |
23,362 | Your program must take as input a line of characters, like this:
```
@+.0
```
And output the characters sorted by how dark they are, like this:
```
.+0@
```
Requirements:
* You must use a monospaced font for darkness detection.
* You must find out how many pixels each character takes up. You must actually draw the character and count pixels, i.e. you can't just hardcode pixel amounts.
+ As a more concrete rule: if you switched fonts, your program should still work. Furthermore, your program should be able to switch fonts by simply changing a variable or value or string in the code.
* If you use antialiasing, you must count pixels as percentages of a fully black pixel. For example, an `rgb(32, 32, 32)` pixel will count as 1/8 of a full pixel. Disregard this rule if your characters are not antialiased.
* After counting pixels, you must sort the characters by the amount of pixels, and output them in order.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win. | 2014/03/07 | [
"https://codegolf.stackexchange.com/questions/23362",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/3808/"
] | PHP, 298 characters
===================
I've added a few line breaks so you can see it in all its hideousness:
```
<?php
$s=@$_GET[s];$a=array();$v=imagecreate(16,16);$f='imagecolorallocate';
$f($v,0,0,0);for($i=0;$i<strlen($s);$i++){$c=$f($v,$i,0,1);
imagechar($v,5,2,$n=0,$s[$i],$c);for($y=16;$y--;)
for($x=16;$x--;)$n+=($c==imagecolorat($v,$x,$y));
$a[]=ord($s[$i])+($n<<8);}sort($a);foreach($a as $v)echo chr($v);
```
This code uses the GD fonts that come built-in with PHP. The second argument of `imagechar()` selects the font (numbers from 1 to 5 are valid).
**Example:**
```
Input: !@#$%^&*-=WEIX,./'
Output: '-.,^=!/*IE%X#$&@W
```
If you insert the following on top of the code shown above, then you'll be able to supply the list of characters in your web browser.
```
<?php
define("FONT_SIZE",5);
if(@$_SERVER['PATH_INFO']=='/a.png') {
$s = $_GET['s'];
$im = imagecreate(strlen($s)*(FONT_SIZE+4)+4,FONT_SIZE+12);
imagecolorallocate($im,255,255,128);
$c = imagecolorallocate($im,0,0,0);
imagestring($im,FONT_SIZE,2,0,$s,$c);
header("Content-Type: image/png");
imagepng($im);
imagedestroy($im);
exit();
}
$me = $_SERVER['PHP_SELF'];
$t1 = $img = "";
if ($t1=htmlspecialchars(@$_GET['s'])) {
$t2=urlencode($_GET['s']);
$img="<p><img src=\"$me/a.png?s=$t2\" /></p>";
}
echo <<<END_HTML
<html>
<body>
$img
<form action="$me" method="get">
<input type="text" name="s" size="40" value="$t1" />
<input type="submit" value="Go" />
</form>
END_HTML;
if(!isset($_GET['s'])) exit();
?>
``` | ### R, 195 characters
```
A=strsplit(scan(,""),"")[[1]];cat(A[order(sapply(A,function(x){png('a',a='none',fa='monospace');frame();text(0,0,x);dev.off();sum(apply(png::readPNG('a'),c(1,2),function(x)any(x!=1)))}))],sep="")
```
Indented with comments:
```r
A=strsplit(scan(,""),"")[[1]] #Take characters as strings and split into single chars
cat(A[order(sapply(A,function(x){ #Apply the following function to each char and order accordingly
png('a',a='none',fa='monospace'); #Open empty png without antialiasing and with monospace font
frame(); #create empty plot
text(0,0,x); #add the char as text to the plot
dev.off(); #close png device
sum(apply(png::readPNG('a'), #read it back as rbga 3d matrix
c(1,2), #check every layer (R, G, B, A)
function(x)any(x!=1))) #if any are not 1, send TRUE
}))], #Sum all TRUEs
sep="") #Prints to output
```
Example:
```
> A=strsplit(scan(,""),"")[[1]];cat(A[order(sapply(A,function(x){png('a',a='none',fa='monospace');frame();text(0,0,x);dev.off();sum(apply(png::readPNG('a'),c(1,2),function(x)any(x!=1)))}))],sep="")
1: @+.0
2:
Read 1 item
.+0@
> A=strsplit(scan(,""),"")[[1]];cat(A[order(sapply(A,function(x){png('a',a='none',fa='monospace');frame();text(0,0,x);dev.off();sum(apply(png::readPNG('a'),c(1,2),function(x)any(x!=1)))}))],sep="")
1: 1234567890
2:
Read 1 item
1723450689
```
The gestion of fonts in R plots being platform-dependent, I cannot guarantee that it works on PC, but it does on a Mac (OS X 10.7.5, R 2.14.2). |
23,362 | Your program must take as input a line of characters, like this:
```
@+.0
```
And output the characters sorted by how dark they are, like this:
```
.+0@
```
Requirements:
* You must use a monospaced font for darkness detection.
* You must find out how many pixels each character takes up. You must actually draw the character and count pixels, i.e. you can't just hardcode pixel amounts.
+ As a more concrete rule: if you switched fonts, your program should still work. Furthermore, your program should be able to switch fonts by simply changing a variable or value or string in the code.
* If you use antialiasing, you must count pixels as percentages of a fully black pixel. For example, an `rgb(32, 32, 32)` pixel will count as 1/8 of a full pixel. Disregard this rule if your characters are not antialiased.
* After counting pixels, you must sort the characters by the amount of pixels, and output them in order.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win. | 2014/03/07 | [
"https://codegolf.stackexchange.com/questions/23362",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/3808/"
] | Java - ~~468 450~~ 444
----------------------
```java
public static void main(String[]a){class c implements Comparable<c>{char d;c(char e){d=e;}public int compareTo(c o){return e(d)>e(o.d)?1:-1;}int e(char f){int a=0,x,y;BufferedImage img=new BufferedImage(99,99,1);img.getGraphics().drawString(""+f,9,80);for(y=0;y<99;y++)for(x=0;x<99;x++)a+=img.getRGB(x,y);return a;}}c[]s=new c[a[0].length()];int i=0;for(char d:a[0].toCharArray())s[i++]=new c(d);Arrays.sort(s);for(c d:s)System.out.print(d.d);}
```
`@+.0abcdefghijklmnopqrstuvwxyz`
->
`.irl+jcvtfxyzsuonkheaqpdb0wgm@`
Ungolfed:
```java
public static void main(String[] a) {
a = new String[]{"@+.0abcdefghijklmnopqrstuvwxyz"};
class c implements Comparable<c> {
char d;
c(char e) {
d = e;
}
@Override
public int compareTo(c o) {
return e(d) > e(o.d)? 1 : -1;
}
int e(char f) {
int a = 0, x, y;
BufferedImage img = new BufferedImage(99, 99, 1);
img.getGraphics().drawString("" + f, 9, 80);
for (y = 0; y < 99; y++)
for (x = 0; x < 99; x++)
a += img.getRGB(x, y);
return a;
}
}
c[] s = new c[a[0].length()];
int i = 0;
for (char d : a[0].toCharArray())
s[i++] = new c(d);
Arrays.sort(s);
for (c d : s)
System.out.print(d.d);
}
``` | PHP - 485
=========
Demo:
```
$ php pcg-23362.php "@+.0"
.+0@
```
Code:
```
<?php $f='x.ttf';$d=array();foreach(str_split($argv[1]) as$_){$B=imagettfbbox(50,0,$f,$_);$w=abs($B[4]-$B[0]);$h=abs($B[5]-$B[1]);$im=imagecreate($w,$h);imagecolorallocate($im,255,255,255);imagettftext($im,50,0,0,$h-$B[1],imagecolorallocate($im,0,0,0),$f,$_);$b=$w*$h;for($x=0;$x<$w;$x++)for($y=0;$y<$h;$y++){$z=imagecolorsforindex($im,imagecolorat($im,$x,$y));$color=$z['red']*$z['green']*$z['blue'];$b-=$color/0x1000000;}$d[$_]=$b / ($w * $h);}asort($d);echo implode(array_keys($d));
``` |
23,362 | Your program must take as input a line of characters, like this:
```
@+.0
```
And output the characters sorted by how dark they are, like this:
```
.+0@
```
Requirements:
* You must use a monospaced font for darkness detection.
* You must find out how many pixels each character takes up. You must actually draw the character and count pixels, i.e. you can't just hardcode pixel amounts.
+ As a more concrete rule: if you switched fonts, your program should still work. Furthermore, your program should be able to switch fonts by simply changing a variable or value or string in the code.
* If you use antialiasing, you must count pixels as percentages of a fully black pixel. For example, an `rgb(32, 32, 32)` pixel will count as 1/8 of a full pixel. Disregard this rule if your characters are not antialiased.
* After counting pixels, you must sort the characters by the amount of pixels, and output them in order.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win. | 2014/03/07 | [
"https://codegolf.stackexchange.com/questions/23362",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/3808/"
] | QBasic, 259 bytes
-----------------
```
SCREEN 1
DIM a(255)
FOR i = 32 TO 255
CLS
PRINT CHR$(i);
FOR p = 0 TO 64
a(i) = a(i) + POINT(p MOD 8, p \ 8)
NEXT p
NEXT i
FOR p = 0 TO 96
FOR i = 32 TO 255
IF a(i) = p THEN PRINT CHR$(i);
NEXT i
NEXT p
```
I did this for fun, so it's technically non-compliant to the rules in one way. It doesn't take a list of characters, but instead prints all characters from 32-255 and uses that instead. If you really want to see a version which complies with this rule, please tell me.
It also fails another technicality: "Furthermore, your program should be able to switch fonts by simply changing a variable or value or string in the code." There is no easy way to do this from within QBasic. However, the program will of course work fine with any codepage of your choosing.
Lastly, I could squeeze away a few characters (mostly whitespace that the QBasic IDE helpfully inserts,) but it's probably not worth it since this answer stands no chance of winning anyway.
 | Java, 584
=========
Wow... This was not a good language to do this in.
```
import java.awt.geom.*;import java.util.*;class F{static void n(final String f,List<Character> s){Collections.sort(s,new Comparator<Character>(){public int compare(Character a,Character b){return d(f,""+a) - d(f,""+b);}});}static int d(String f,String s){int i=0;PathIterator p=new java.awt.Font(f,0,12).createGlyphVector(((java.awt.Graphics2D)new java.awt.image.BufferedImage(8,8,2).getGraphics()).getFontRenderContext(),s).getGlyphOutline(0).getPathIterator(AffineTransform.getRotateInstance(0.0, 0.0));while(!p.isDone()){i+=p.currentSegment(new double[99])/2;p.next();}return i;}}
```
Usage:
```
import java.awt.geom.*;
import java.util.*;
public class F {
public static void main(String[]args){
List<Character> s = new ArrayList<Character>(0);
s.add('@');
s.add('+');
s.add('.');
s.add('0');
n("Calibri", s);
System.out.println(s);
}
static void n(final String f,List<Character> s){
Collections.sort(s,new Comparator<Character>(){
public int compare(Character a,Character b){
return d(f,""+a) - d(f,""+b);
}
});
}
static int d(String f,String s){
int i=0;
PathIterator p=new java.awt.Font(f,0,12).createGlyphVector(((java.awt.Graphics2D)new java.awt.image.BufferedImage(8,8,2).getGraphics()).getFontRenderContext(),s).getGlyphOutline(0).getPathIterator(AffineTransform.getRotateInstance(0.0, 0.0));
while(!p.isDone()){
i+=p.currentSegment(new double[99])/2;
p.next();
}
return i;
}
}
```
This setup results in:
```
[., +, 0, @]
```
---
The only line here that needs explanation:
```
PathIterator p=new java.awt.Font(f,0,12).createGlyphVector(((java.awt.Graphics2D)new java.awt.image.BufferedImage(8,8,2).getGraphics()).getFontRenderContext(),s).getGlyphOutline(0).getPathIterator(AffineTransform.getRotateInstance(0.0, 0.0));
```
* Initialize the 12pt font object with the passed font.
* Create a new BufferedImage obejct to create a Graphics2D object linked to a GraphicsContext.
* Get the font rendering context of the 2D graphics context for the string s.
* Get the first glyph (only glyph) in the string.
* Get the path iterator (list of points).
Then this final piece brings it together...
```
while(!p.isDone()){
i+=p.currentSegment(new double[99])/2;
p.next();
}
```
By iterating through all points and summing count of points. This density information is passed back up to the comparator and is used for sorting. |
23,362 | Your program must take as input a line of characters, like this:
```
@+.0
```
And output the characters sorted by how dark they are, like this:
```
.+0@
```
Requirements:
* You must use a monospaced font for darkness detection.
* You must find out how many pixels each character takes up. You must actually draw the character and count pixels, i.e. you can't just hardcode pixel amounts.
+ As a more concrete rule: if you switched fonts, your program should still work. Furthermore, your program should be able to switch fonts by simply changing a variable or value or string in the code.
* If you use antialiasing, you must count pixels as percentages of a fully black pixel. For example, an `rgb(32, 32, 32)` pixel will count as 1/8 of a full pixel. Disregard this rule if your characters are not antialiased.
* After counting pixels, you must sort the characters by the amount of pixels, and output them in order.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win. | 2014/03/07 | [
"https://codegolf.stackexchange.com/questions/23362",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/3808/"
] | [GTB](http://timtechsoftware.com/gtb "GTB")
-------------------------------------------
This has code to be the second hardest code I've ever written for a calculator. No hard-coded pixel values, it actually draws the text on a graph and loops to count each pixel.
```
0→I`_%I<l?_T;1,1,s;_,I,1
C;pT;{0,1,2,3,4,5},{0,1,2}→L1(I
0→I%I<l?_T;1,C;L1(I)>L1,I
```
**Input**
```
,O.i
```
**Output**
```
.,iO
``` | PHP - 485
=========
Demo:
```
$ php pcg-23362.php "@+.0"
.+0@
```
Code:
```
<?php $f='x.ttf';$d=array();foreach(str_split($argv[1]) as$_){$B=imagettfbbox(50,0,$f,$_);$w=abs($B[4]-$B[0]);$h=abs($B[5]-$B[1]);$im=imagecreate($w,$h);imagecolorallocate($im,255,255,255);imagettftext($im,50,0,0,$h-$B[1],imagecolorallocate($im,0,0,0),$f,$_);$b=$w*$h;for($x=0;$x<$w;$x++)for($y=0;$y<$h;$y++){$z=imagecolorsforindex($im,imagecolorat($im,$x,$y));$color=$z['red']*$z['green']*$z['blue'];$b-=$color/0x1000000;}$d[$_]=$b / ($w * $h);}asort($d);echo implode(array_keys($d));
``` |
13,931,720 | I want to add two picture slider at same page by JavaScript only. But only one slider is working and another is static.
Here is my code so far what I got from a website.
```
<script type="text/javascript">
window.onload = function() {
var rotator = document.getElementById("rotator");
var images = rotator.getElementsByTagName("img");
for (var i = 1; i < images.length; i++) {
images[i].style.display = "none";
}
var counter = 1;
setInterval(function() {
for (var i = 0; i < images.length; i++) {
images[i].style.display = "none";
}
images[counter].style.display = "block";
counter++;
if (counter == images.length) {
counter = 0;
}
}, 3000);
};
</script>
```
```
<div id="rotator">
<img height="250px" width="200px" src="images/claim/1.jpg" alt="" />
<img height="250px" width="200px" src="images/claim/2.jpg" alt="" />
<img height="250px" width="200px" src="images/claim/3.jpg" alt="" />
</div>
``` | 2012/12/18 | [
"https://Stackoverflow.com/questions/13931720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765171/"
] | I have managed to resolve this issue using the following code mentioned in [this SO post](https://stackoverflow.com/questions/6033638/an-object-with-the-same-key-already-exists-in-the-objectstatemanager-the-object) which shows how to save only the new values:
```
db.Entry(activeCitizen).CurrentValues.SetValues(citizenDetails.ActiveCitizen);
```
Note, I experienced the error: "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key"
[This SO post](https://stackoverflow.com/questions/7221349/an-object-with-the-same-key-already-exists-in-the-objectstatemanager-except) helped me overcome that issue.
The final code was therefore:
```
var currentCitizen = db.ActiveCitizen.Find(citizenDetails.ActiveCitizen.ID);
db.Entry(currentCitizen).CurrentValues.SetValues(citizenDetails.ActiveCitizen);
db.SaveChanges();
``` | Try This
```
[HttpPost]
public ActionResult Edit(CitizenEntryViewModel citizenDetails)
{
ActiveCitizen activeCitizen = db.ActiveCitizen.SingleOrDefault(m => m.ID == citizenDetails.ActiveCitizen.ID);
if (activeCitizen != null)
{
UpdateModel(activeCitizen);
db.SaveChanges();
}
``` |
57,123,043 | Im working with Microsoft Dynamics 365 Business Central. (ERP Software).
Im attempting to create build agents on my local server to set up Continious Integration with my projects.
On the buildserver i am running Docker Enterprise on Windows 2019.
When i spin up my dockeragent to facilitate the builds im experiencing an issue.
The dockeragent is asked by my CI flow to spin up another docker container called navcontainerhelper which is basically a docker container that contains the Business Central environment to build my application on.
However the navcontainerhelper doesnt know the docker commands since it doesnt include docker.
Ive researched and found that mounting the docker socket with -v is the way to do this however i cant seem to get that working.
When i create the agent i am using the following command:
```
docker run -v /var/run/docker.sock:/var/run/docker.sock -ti dockeragent:latest -e AZP_URL=<My azure url> -e AZP_TOKEN=<my azure token) -e AZP_AGENT_NAME=<my builder agent name>
```
when i attempt to execute this i get the following command which leads me to the mentioned conclusion.
```
docker : C:\Program Files\docker\docker.exe: Error response from daemon: invalid volume specification: '/var/run/docker.sock:/var/run/docker.sock'.
At C:\dockeragent\StartAgents.ps1:1 char:1
+ docker run -v /var/run/docker.sock:/var/run/docker.sock -ti dockerage ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (C:\Program File...n/docker.sock'.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
See 'C:\Program Files\docker\docker.exe run --help'.
```
Could someone give me a pointer as to what i am doing wrong?
I have changed the script to use the named pipes instead for windows. it now mounts like this:
```
docker run -e AZP_URL=<My azure url> -e AZP_TOKEN=<my azure token) -e AZP_AGENT_NAME=<my builder agent name> -v \\.\pipe\docker_engine:\\.\pipe\docker_engine dockeragent:latest
```
However the container still refuses to recognize my docker command:
```
New-NavContainer : The term 'docker' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\azp\agent\_work\***\s\scripts\Create-Container.ps***:36 char:***
+ New-NavContainer @parameters `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (docker:String) [New-NavContainer], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException,New-NavContainer
PowerShell exited with code '***'.
```
Any pointers would be greatly appreciated! | 2019/07/20 | [
"https://Stackoverflow.com/questions/57123043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1053445/"
] | in this case the answer was to use the named pipes like so:
```
-v \.\pipe\docker_engine:\\.\pipe\docker_engine
```
and to install the docker client into the container so it can talk to the docker engine | I was having trouble with the install, so I used one of the docker provided windows images from [docker hub](https://hub.docker.com/_/docker) as my base image instead of a microsoft one. Followed the remained of the microsoft [instructions](https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/docker?view=azure-devops). Started the container with the below command and everything worked smoothly.
```
`docker run --env-file agent.env -v \\.\pipe\docker_engine:\\.\pipe\docker_engine --name dockeragent dockeragent:latest`
``` |
46,490,229 | I'd like to know whether it is possible to get the "original id" of an object as the result of the query. Whenever I make a request to the server, it returns the node "global identifier", something like `U29saWNpdGFjYW9UeXBlOjEzNTkxOA==` .
The query is similar to this one:
```
{
allPatients(active: true) {
edges {
cursor
node {
id
state
name
}
}
}
```
and the return is:
```
{
"data": {
"edges": [
{
"cursor": "YXJyYXljb25uZWN0aW9uOjA=",
"node": {
"id": "U29saWNpdGFjYW9UeXBlOjEzNTkxOA==",
"state": "ARI",
"name": "Brad"
}
}
]
}
}
```
How can I get the "original" id of the object at the database level (e.g. '112') instead of that node unique identifier?
ps.: I am using graphene-python and Relay on the server side. | 2017/09/29 | [
"https://Stackoverflow.com/questions/46490229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2500462/"
] | Overriding default to\_global\_id method in Node object worked out for me:
```
class CustomNode(graphene.Node):
class Meta:
name = 'Node'
@staticmethod
def to_global_id(type, id):
return id
class ExampleType(DjangoObjectType):
class Meta:
model = Example
interfaces = (CustomNode,)
``` | First option, remove relay.Node as interface of your objectNode declaration.
Second option, use custom resolve\_id fonction to return id original value.
Example
```
class objectNode(djangoObjectType):
.... Meta ....
id = graphene.Int(source="id")
def resolve_id("commons args ...."):
return self.id
```
Hope it helps |
46,490,229 | I'd like to know whether it is possible to get the "original id" of an object as the result of the query. Whenever I make a request to the server, it returns the node "global identifier", something like `U29saWNpdGFjYW9UeXBlOjEzNTkxOA==` .
The query is similar to this one:
```
{
allPatients(active: true) {
edges {
cursor
node {
id
state
name
}
}
}
```
and the return is:
```
{
"data": {
"edges": [
{
"cursor": "YXJyYXljb25uZWN0aW9uOjA=",
"node": {
"id": "U29saWNpdGFjYW9UeXBlOjEzNTkxOA==",
"state": "ARI",
"name": "Brad"
}
}
]
}
}
```
How can I get the "original" id of the object at the database level (e.g. '112') instead of that node unique identifier?
ps.: I am using graphene-python and Relay on the server side. | 2017/09/29 | [
"https://Stackoverflow.com/questions/46490229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2500462/"
] | Overriding default to\_global\_id method in Node object worked out for me:
```
class CustomNode(graphene.Node):
class Meta:
name = 'Node'
@staticmethod
def to_global_id(type, id):
return id
class ExampleType(DjangoObjectType):
class Meta:
model = Example
interfaces = (CustomNode,)
``` | To expand on the top answer and for those using SQLAlchemy Object Types, this worked for me:
```
class CustomNode(graphene.Node):
class Meta:
name = 'myNode'
@staticmethod
def to_global_id(type, id):
return id
class ExampleType(SQLAlchemyObjectType):
class Meta:
model = Example
interfaces = (CustomNode, )
```
If you have other ObjectTypes using relay.Node as the interface, you will need to use a unique name under your `CustomNode`. Otherwise you will get and assertion error. |
46,490,229 | I'd like to know whether it is possible to get the "original id" of an object as the result of the query. Whenever I make a request to the server, it returns the node "global identifier", something like `U29saWNpdGFjYW9UeXBlOjEzNTkxOA==` .
The query is similar to this one:
```
{
allPatients(active: true) {
edges {
cursor
node {
id
state
name
}
}
}
```
and the return is:
```
{
"data": {
"edges": [
{
"cursor": "YXJyYXljb25uZWN0aW9uOjA=",
"node": {
"id": "U29saWNpdGFjYW9UeXBlOjEzNTkxOA==",
"state": "ARI",
"name": "Brad"
}
}
]
}
}
```
How can I get the "original" id of the object at the database level (e.g. '112') instead of that node unique identifier?
ps.: I am using graphene-python and Relay on the server side. | 2017/09/29 | [
"https://Stackoverflow.com/questions/46490229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2500462/"
] | Overriding default to\_global\_id method in Node object worked out for me:
```
class CustomNode(graphene.Node):
class Meta:
name = 'Node'
@staticmethod
def to_global_id(type, id):
return id
class ExampleType(DjangoObjectType):
class Meta:
model = Example
interfaces = (CustomNode,)
``` | With this you can retrive the real id in database:
```
def get_real_id(node_id: str):
_, product_id_real = relay.Node.from_global_id(global_id=node_id)
return product_id_real
``` |
22,496,913 | I have used EditText in my application, the problem is the entered text is not aligned properly, check it out my screen shot for what exactly my issue is.

My EditText XML file is
```
<EditText
android:id="@+id/signupFullName"
android:layout_width="179dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/updatedprofieledit"
android:ems="10"
android:hint="@string/enterfullanme"
android:inputType="textPersonName"
android:paddingLeft="10dip"
android:singleLine="true" >
<requestFocus />
</EditText>
```
Kindly help me to clear this issue, have tried with some EditText Specification but no luck.
Thanks | 2014/03/19 | [
"https://Stackoverflow.com/questions/22496913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1621926/"
] | add this line into your edit text
```
android:padding="5dp"
``` | use this
```
android:paddingRight="10dip"
``` |
22,496,913 | I have used EditText in my application, the problem is the entered text is not aligned properly, check it out my screen shot for what exactly my issue is.

My EditText XML file is
```
<EditText
android:id="@+id/signupFullName"
android:layout_width="179dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/updatedprofieledit"
android:ems="10"
android:hint="@string/enterfullanme"
android:inputType="textPersonName"
android:paddingLeft="10dip"
android:singleLine="true" >
<requestFocus />
</EditText>
```
Kindly help me to clear this issue, have tried with some EditText Specification but no luck.
Thanks | 2014/03/19 | [
"https://Stackoverflow.com/questions/22496913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1621926/"
] | It appears that your background image is smaller than your hard-coded width. Adding padding reserves some "unused room" at the end of your EditText. It would be better if you converted your background image to a 9-patch image so that it could resize automatically. | add this line into your edit text
```
android:padding="5dp"
``` |
22,496,913 | I have used EditText in my application, the problem is the entered text is not aligned properly, check it out my screen shot for what exactly my issue is.

My EditText XML file is
```
<EditText
android:id="@+id/signupFullName"
android:layout_width="179dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/updatedprofieledit"
android:ems="10"
android:hint="@string/enterfullanme"
android:inputType="textPersonName"
android:paddingLeft="10dip"
android:singleLine="true" >
<requestFocus />
</EditText>
```
Kindly help me to clear this issue, have tried with some EditText Specification but no luck.
Thanks | 2014/03/19 | [
"https://Stackoverflow.com/questions/22496913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1621926/"
] | It appears that your background image is smaller than your hard-coded width. Adding padding reserves some "unused room" at the end of your EditText. It would be better if you converted your background image to a 9-patch image so that it could resize automatically. | use this
```
android:paddingRight="10dip"
``` |
16,028,705 | On page 321 of *Real World Haskell*
There are these codes,
...
```
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
newtype AInt = A { unA::Int }
deriving (Show, Eq, Num)
instance Monoid AInt where
mempty = 0
```
My confusion is why it is
```
mempty = 0
```
but not
```
mempty = A 0
```
?
---
I also noticed that both
```
ghci> 0 :: AInt
```
and
```
ghci> A 0 :: AInt
```
give me the same response
```
A { unA = 0 }
```
Would someone please tell me what is the difference between theses two? | 2013/04/16 | [
"https://Stackoverflow.com/questions/16028705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1391960/"
] | The trick here is with the `GeneralizedNewtypeDeriving` extension. In particular, this lets us derive *any* class for a `newtype` as long as the underlying type is an instance. All this does is copy over the instance from the old type to the new type.
In this particular case, `AInt` derives `Num`. This means that `AInt` is an instance of `Num` using the same code as `Int` (with everything wrapped in `A` constructors as appropriate). This includes `Int`'s `fromInteger` function.
The `fromInteger` function is defined in terms of `Int`'s `fromInteger`, looking something like this:
```
fromInteger i = A (fromInteger i)
```
Since `0` is polymorphic--it has the type `0 :: Num a => a`--it's a valid constant for *any* type in `Num`. Thanks to the newtype deriving, this includes `AInt`, using the `fromInteger` function above. This means there is really no difference between `0 :: AInt` an `A 0 :: AInt`. | Numeric literals like `0` are overloaded and have the type `0 :: Num a => a`, which means that they can be any type for which there is a `Num` instance, depending on the context. This happens via the `fromInteger` function in the `Num` type class, so when you type `0` it is treated as if you'd written `fromInteger 0`.
By using `GeneralizedNewtypeDeriving`, GHC has (effectively1) written a `Num` instance for your class looking something like this:
```
instance Num AInt where
fromInteger n = A (fromInteger n)
...
```
So when you write `0 :: AInt`, this expands to `fromInteger 0 :: AInt` which is (by the definition above) equal to `A (fromInteger 0)` which is the same as if you had written `A 0`.
1 `GeneralizedNewtypeDeriving` doesn't actually write a new intance. It just performs the necessary casts to use the existing one. |
386,675 | Let $A\_j,j\in\mathbb Z^+$ be finite sets with at least two distinct elements.
How to show that $\prod\_{j=1}^\infty A\_j$ is uncountable? | 2013/05/09 | [
"https://math.stackexchange.com/questions/386675",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/52197/"
] | **Hint:**
Replace each $A\_j$ by $B\_j=\{0,\ldots,n-1\}$, where $n=|A\_j|$, using the axiom of choice. Now we have:
$$\left|\prod\_{j\in\Bbb N}\{0,1\}\right|\leq\left|\prod\_{j\in\Bbb N}B\_j\right|=\left|\prod\_{j\in\Bbb N}A\_j\right|.$$
You can bound this from the right by the product of copies of $\Bbb N$ and calculate the exact cardinality too. I am leaving the details for you.
Do note, the axiom of choice is essential and it is consistent that there are families of finite sets whose product is empty, and thus countable. | Identify a subset of each set with {0,1} using AC, and map the corresponding subset of the product onto binary expansions of reals in the interval [0,1], hence uncountable. |
19,091,013 | I have make virtual subdomain in my code.like below
```
RewriteCond %{HTTP_HOST} ^(.*)\.mysitename\.com
RewriteRule ^(.*)$ agent.php?asitename=%1 [L,NC,QSA]
```
it works fine, but it did not work for pages like
```
RewriteCond %{HTTP_HOST} ^(.*)\.mysitename\.com
RewriteRule ^(.*)/ag_buy.html ag_buy.php?sitename=%1&page=buy [L,NC,QSA]
```
it redirect all pages top agent.php, but it should only redirect home page to agent.php, for other pages it should work like ag\_buy.html to ag\_buy.php
and so on.........
please guide me on htaccess how can i make this possible. | 2013/09/30 | [
"https://Stackoverflow.com/questions/19091013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2341915/"
] | HuwD,
A good resource might be my [module template installation video](http://www.dotnetnuclear.com/articles/tabid/88/ID/11/MVP-Module-Development-Template-Installation-Configuration-Troubleshooting.aspx) which gives good information on setting up your development environment and debugging issues (regardless of the template you use). Check out between 1:30 and 5:00 minutes for the environment setup, and after 19 minutes some of the troubleshooting.
A couple common problems I see Visual Studio doing is creating an unwanted virtual directory on the DesktopModules folder and/or creating an unwanted web.config in the module's root.
Another good resource is [Dnnhero.com](http://dnnhero.com). In the development section there is a series on DNN7 environment and template setup. | You may want to give a try a free module called [Users Importer](http://usersimporter.codeplex.com/) - A bit old but worth a try.
Here is a paid alternative: [Bulk User Manager](http://store.dnnsoftware.com/home/product-details/bulk-user-manager-v33?r=73311e2a326b411fbbb4) |
19,091,013 | I have make virtual subdomain in my code.like below
```
RewriteCond %{HTTP_HOST} ^(.*)\.mysitename\.com
RewriteRule ^(.*)$ agent.php?asitename=%1 [L,NC,QSA]
```
it works fine, but it did not work for pages like
```
RewriteCond %{HTTP_HOST} ^(.*)\.mysitename\.com
RewriteRule ^(.*)/ag_buy.html ag_buy.php?sitename=%1&page=buy [L,NC,QSA]
```
it redirect all pages top agent.php, but it should only redirect home page to agent.php, for other pages it should work like ag\_buy.html to ag\_buy.php
and so on.........
please guide me on htaccess how can i make this possible. | 2013/09/30 | [
"https://Stackoverflow.com/questions/19091013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2341915/"
] | This is a common problem with my VS templates, though not for everyone, and it doesn't happen all the time. It stems from Visual Studio, so it shouldn't ever be a problem on your production servers, unless you upload source and try to compile there, than it might be an issue. | You may want to give a try a free module called [Users Importer](http://usersimporter.codeplex.com/) - A bit old but worth a try.
Here is a paid alternative: [Bulk User Manager](http://store.dnnsoftware.com/home/product-details/bulk-user-manager-v33?r=73311e2a326b411fbbb4) |
19,091,013 | I have make virtual subdomain in my code.like below
```
RewriteCond %{HTTP_HOST} ^(.*)\.mysitename\.com
RewriteRule ^(.*)$ agent.php?asitename=%1 [L,NC,QSA]
```
it works fine, but it did not work for pages like
```
RewriteCond %{HTTP_HOST} ^(.*)\.mysitename\.com
RewriteRule ^(.*)/ag_buy.html ag_buy.php?sitename=%1&page=buy [L,NC,QSA]
```
it redirect all pages top agent.php, but it should only redirect home page to agent.php, for other pages it should work like ag\_buy.html to ag\_buy.php
and so on.........
please guide me on htaccess how can i make this possible. | 2013/09/30 | [
"https://Stackoverflow.com/questions/19091013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2341915/"
] | This is a common problem with my VS templates, though not for everyone, and it doesn't happen all the time. It stems from Visual Studio, so it shouldn't ever be a problem on your production servers, unless you upload source and try to compile there, than it might be an issue. | HuwD,
A good resource might be my [module template installation video](http://www.dotnetnuclear.com/articles/tabid/88/ID/11/MVP-Module-Development-Template-Installation-Configuration-Troubleshooting.aspx) which gives good information on setting up your development environment and debugging issues (regardless of the template you use). Check out between 1:30 and 5:00 minutes for the environment setup, and after 19 minutes some of the troubleshooting.
A couple common problems I see Visual Studio doing is creating an unwanted virtual directory on the DesktopModules folder and/or creating an unwanted web.config in the module's root.
Another good resource is [Dnnhero.com](http://dnnhero.com). In the development section there is a series on DNN7 environment and template setup. |
18,747,504 | I am trying to get list of **WebApplication** in a Given Server.
***Get-SpWebapplication*** retrieves all the WebApplication in the Current machine.
I need to get the list of WebApplication in a particual server.
How to Do it.
Please help me with this. | 2013/09/11 | [
"https://Stackoverflow.com/questions/18747504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2654209/"
] | To get a list of all SharePoint Web Apps, use the following:
```
Get-SPWebApplication | Select DisplayName, Url
``` | Go to **"C:\windows\system32\inetsrv"** folder
and try this:
**.\appcmd list wp** |
9,286,927 | I am trying to find some text in my document that only appears in "Heading 1" styles. So far, no avail.
**Sample Code:**
```
With ThisDocument.Range.Find
.Text = "The Heading"
.Style = "Heading 1" 'Does not work
.Execute
If .Found Then Debug.Print "Found"
End With
```
Just a note, it keeps stopping at the table of contents.
Edit: fixed the mispelt 'if' statement | 2012/02/15 | [
"https://Stackoverflow.com/questions/9286927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/718341/"
] | Your code looks good to me. My best guess is that the 'Heading 1' style exists in your table of contents?
The code below should continue the find, finding all occurrences:
```
Dim blnFound As Boolean
With ThisDocument.Range.Find
.Text = "The Heading"
.Style = "Heading 1"
Do
blnFound = .Execute
If blnFound Then
Debug.Print "Found"
Else
Exit Do
End If
Loop
End With
```
I hope this helps. | I found this question on Google and the code in the question did not work for me. I have made the following changes to fix it:
* I changed `Selection.Find.Style = "Heading 1"` to an object.
* I changed the code to grab the boolean result of the search from `.Execute` rather than `.Found`
I hope this helps some other Googlers.
```
With ThisDocument.Range.Find
.Text = "The Heading"
.Style = ActiveDocument.Styles("Heading 1")
Dim SearchSuccessful As Boolean
SearchSuccessful = .Execute
If SearchSuccessful Then
' code
Else
' code
End If
End With
``` |
9,286,927 | I am trying to find some text in my document that only appears in "Heading 1" styles. So far, no avail.
**Sample Code:**
```
With ThisDocument.Range.Find
.Text = "The Heading"
.Style = "Heading 1" 'Does not work
.Execute
If .Found Then Debug.Print "Found"
End With
```
Just a note, it keeps stopping at the table of contents.
Edit: fixed the mispelt 'if' statement | 2012/02/15 | [
"https://Stackoverflow.com/questions/9286927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/718341/"
] | Your code looks good to me. My best guess is that the 'Heading 1' style exists in your table of contents?
The code below should continue the find, finding all occurrences:
```
Dim blnFound As Boolean
With ThisDocument.Range.Find
.Text = "The Heading"
.Style = "Heading 1"
Do
blnFound = .Execute
If blnFound Then
Debug.Print "Found"
Else
Exit Do
End If
Loop
End With
```
I hope this helps. | The reason I think it is not working is because you have to set the
```
.format = true
```
flag, and you *may* have to specify the style via the .Styles method:
```
With ThisDocument.Range.Find
.Text = "The Heading"
.Format = true <<< -------- Tells Word to look for a special formatting
.Style = ThisDocument.Styles("Heading 1")
Do
blnFound = .Execute
If blnFound Then
Debug.Print "Found"
Else
Exit Do
End If
Loop
End With
``` |
23,278,279 | Here is my jfiddle: <http://jsfiddle.net/D3zyt/8/>
html:
```
<div class="board">
<table id="mastermind_table_one">
<td></td>
<td></td>
<td></td>
<td></td>
</table>
<table id="mastermind_table_two">
<td></td>
<td></td>
<td></td>
<td></td>
</table>
<table id="mastermind_table_three">
<td></td>
<td></td>
<td></td>
<td></td>
</table>
```
You'll notice in the html that I have three tables. Is there a way when I click "next\_round", the background colors change for the next table and not the current (hardcoded) table? | 2014/04/24 | [
"https://Stackoverflow.com/questions/23278279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3007294/"
] | This does it by storing the current table in a variable and using `.next()` to find the next table:
[Fiddle](http://jsfiddle.net/rK3LA/)
```
var current;
$('.next_round').click(function() {
if(typeof current == 'undefined' || current.next('table').length == 0){
current = $('.board table').first();
} else {
current = current.next('table');
}
$(current).find('td').each(function() {
$(this).css("background-color", setRandomColor);
});
});
``` | Something like this helps?
```
var tables = $('.board table');
var currentTable = 0;
$('.next_round').click(function() {
var table = tables[currentTable];
table.find('td').each(function() {
$(this).css("background-color", setRandomColor);
});
currentTable++;
if(currentTable > tables.length){
currentTable = 0;
}
}
``` |
23,278,279 | Here is my jfiddle: <http://jsfiddle.net/D3zyt/8/>
html:
```
<div class="board">
<table id="mastermind_table_one">
<td></td>
<td></td>
<td></td>
<td></td>
</table>
<table id="mastermind_table_two">
<td></td>
<td></td>
<td></td>
<td></td>
</table>
<table id="mastermind_table_three">
<td></td>
<td></td>
<td></td>
<td></td>
</table>
```
You'll notice in the html that I have three tables. Is there a way when I click "next\_round", the background colors change for the next table and not the current (hardcoded) table? | 2014/04/24 | [
"https://Stackoverflow.com/questions/23278279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3007294/"
] | This does it by storing the current table in a variable and using `.next()` to find the next table:
[Fiddle](http://jsfiddle.net/rK3LA/)
```
var current;
$('.next_round').click(function() {
if(typeof current == 'undefined' || current.next('table').length == 0){
current = $('.board table').first();
} else {
current = current.next('table');
}
$(current).find('td').each(function() {
$(this).css("background-color", setRandomColor);
});
});
``` | **Note: this post contains a bad practice, I left it maybe someone could learn from it, read the comment**
just use one table like:
```
<table id="mastermind_table_three">
<td></td>
<td></td>
<td></td>
<td></td>
</table>
```
and then add a button `<button onclick="nextRound(this)` />
with the function as:
```
function nextRound(that) {
that.i = that.i ? (that.i + 1) : 1;
$('table').removeClass("mastermind_table_" + that.i - 1);
$('table').addClass("mastermind_table_" + that.i);
}
``` |
23,278,279 | Here is my jfiddle: <http://jsfiddle.net/D3zyt/8/>
html:
```
<div class="board">
<table id="mastermind_table_one">
<td></td>
<td></td>
<td></td>
<td></td>
</table>
<table id="mastermind_table_two">
<td></td>
<td></td>
<td></td>
<td></td>
</table>
<table id="mastermind_table_three">
<td></td>
<td></td>
<td></td>
<td></td>
</table>
```
You'll notice in the html that I have three tables. Is there a way when I click "next\_round", the background colors change for the next table and not the current (hardcoded) table? | 2014/04/24 | [
"https://Stackoverflow.com/questions/23278279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3007294/"
] | This does it by storing the current table in a variable and using `.next()` to find the next table:
[Fiddle](http://jsfiddle.net/rK3LA/)
```
var current;
$('.next_round').click(function() {
if(typeof current == 'undefined' || current.next('table').length == 0){
current = $('.board table').first();
} else {
current = current.next('table');
}
$(current).find('td').each(function() {
$(this).css("background-color", setRandomColor);
});
});
``` | This is a solution that implements event data in jquery.
And here is a fiddle: <http://jsfiddle.net/D3zyt/10/>
```
var randomColor = ["red", "blue", "green", "#9CBA7F", "yellow", "#BF5FFF"];
function setRandomColor() {
return randomColor[Math.floor(Math.random() * randomColor.length)];
}
$('.next_round').on("click", {i: 0}, function(e) {
var selectorFragment = ["one","two","three"]
$('#mastermind_table_'+selectorFragment[e.data.i]).each(function() {
$(this).find('td').each(function() {
$(this).css("background-color", setRandomColor);
})
})
e.data.i += 1
if (e.data.i === 3) e.data.i = 0
})
```
However, restructuring your html would probably make for an easier solution later down the road ;) |
1,267,071 | I'm creating an intranet asp.net mvc application that everyone in the company should have access to. I need to run the website impersonated for database access etc., but I want to know who each user is.
When I look at `Page.User.Identity.Name` it's blank. Is it possible to get the user's windows account name even though the site is running impersonated?
**Edit:**
Here's a little more info. I have a site in IIS 6 running with anonymous access enabled. The site is running under a system account that has access to the database (because all of the employees do not have access to the database).
My web.config has `<authentication mode="Windows" />` and `<identity impersonate="true"/>`
My goal is that the users won't have to log in - that fact that they are logged into our network (and the fact that the site is not on an external IP) is enough authentication. I would just like to know who the user is in order to track changes they make, etc. | 2009/08/12 | [
"https://Stackoverflow.com/questions/1267071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34720/"
] | try this
```
System.Security.Principal.WindowsIdentity.GetCurrent().Name
```
It should return a string with the users login name | Unless this functionality has changed under the MVC framework, and I don't think it has, Page.User.Identity.Name should still work. Sounds like your site is set up to allow anonymous authentication. If so, try disabling it. |
1,267,071 | I'm creating an intranet asp.net mvc application that everyone in the company should have access to. I need to run the website impersonated for database access etc., but I want to know who each user is.
When I look at `Page.User.Identity.Name` it's blank. Is it possible to get the user's windows account name even though the site is running impersonated?
**Edit:**
Here's a little more info. I have a site in IIS 6 running with anonymous access enabled. The site is running under a system account that has access to the database (because all of the employees do not have access to the database).
My web.config has `<authentication mode="Windows" />` and `<identity impersonate="true"/>`
My goal is that the users won't have to log in - that fact that they are logged into our network (and the fact that the site is not on an external IP) is enough authentication. I would just like to know who the user is in order to track changes they make, etc. | 2009/08/12 | [
"https://Stackoverflow.com/questions/1267071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34720/"
] | With `<authentication mode="Windows"/>` in your application and Anonymous access enabled in IIS, you will see the following results:
```
System.Environment.UserName: Computer Name
Page.User.Identity.Name: Blank
System.Security.Principal.WindowsIdentity.GetCurrent().Name: Computer Name
```
With `<authentication mode="Windows"/>` in your application, and ‘Anonymous access’ disabled and only ‘Integrated Windows Authentication’ in IIS, you will see the following results:
```
System.Environment.UserName: ASPNET (user account used to run ASP.NET service)
Page.User.Identity.Name: Domain\ Windows Account Name
System.Security.Principal.WindowsIdentity.GetCurrent().Name: Computer Name\ASPNET
```
With `<authentication mode="Windows"/>` and `<identity impersonate ="true"/>` in your application, and ‘Anonymous access’ disabled and only ‘Integrated Windows Authentication’ in IIS, you will see the following results:
```
System.Environment.UserName: Windows Account Name
Page.User.Identity.Name: Domain\ Windows Account Name
System.Security.Principal.WindowsIdentity.GetCurrent().Name: Domain\ Windows Account Name
``` | try this
```
System.Security.Principal.WindowsIdentity.GetCurrent().Name
```
It should return a string with the users login name |
1,267,071 | I'm creating an intranet asp.net mvc application that everyone in the company should have access to. I need to run the website impersonated for database access etc., but I want to know who each user is.
When I look at `Page.User.Identity.Name` it's blank. Is it possible to get the user's windows account name even though the site is running impersonated?
**Edit:**
Here's a little more info. I have a site in IIS 6 running with anonymous access enabled. The site is running under a system account that has access to the database (because all of the employees do not have access to the database).
My web.config has `<authentication mode="Windows" />` and `<identity impersonate="true"/>`
My goal is that the users won't have to log in - that fact that they are logged into our network (and the fact that the site is not on an external IP) is enough authentication. I would just like to know who the user is in order to track changes they make, etc. | 2009/08/12 | [
"https://Stackoverflow.com/questions/1267071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34720/"
] | try this
```
System.Security.Principal.WindowsIdentity.GetCurrent().Name
```
It should return a string with the users login name | I just wanted to post my fix, because no one else had said anything about it.
I was having the same issue when I published the site to the server, but not on my local. All the settings were the same. However, in IIS the "Default Website" had never been turned off. It was running and intercepting traffic, even though there was no site associated with it. Anonymous Authentication was turned on in the default, but turned off in my website running under port 80. It didn't seem to matter that my site had it turned off... since the default was turned on it was turned on for all traffic to port 80.
Disabling the default web fixed the issue. Also changing the port to 8080 works.
I hope this helps someone. |
1,267,071 | I'm creating an intranet asp.net mvc application that everyone in the company should have access to. I need to run the website impersonated for database access etc., but I want to know who each user is.
When I look at `Page.User.Identity.Name` it's blank. Is it possible to get the user's windows account name even though the site is running impersonated?
**Edit:**
Here's a little more info. I have a site in IIS 6 running with anonymous access enabled. The site is running under a system account that has access to the database (because all of the employees do not have access to the database).
My web.config has `<authentication mode="Windows" />` and `<identity impersonate="true"/>`
My goal is that the users won't have to log in - that fact that they are logged into our network (and the fact that the site is not on an external IP) is enough authentication. I would just like to know who the user is in order to track changes they make, etc. | 2009/08/12 | [
"https://Stackoverflow.com/questions/1267071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34720/"
] | With `<authentication mode="Windows"/>` in your application and Anonymous access enabled in IIS, you will see the following results:
```
System.Environment.UserName: Computer Name
Page.User.Identity.Name: Blank
System.Security.Principal.WindowsIdentity.GetCurrent().Name: Computer Name
```
With `<authentication mode="Windows"/>` in your application, and ‘Anonymous access’ disabled and only ‘Integrated Windows Authentication’ in IIS, you will see the following results:
```
System.Environment.UserName: ASPNET (user account used to run ASP.NET service)
Page.User.Identity.Name: Domain\ Windows Account Name
System.Security.Principal.WindowsIdentity.GetCurrent().Name: Computer Name\ASPNET
```
With `<authentication mode="Windows"/>` and `<identity impersonate ="true"/>` in your application, and ‘Anonymous access’ disabled and only ‘Integrated Windows Authentication’ in IIS, you will see the following results:
```
System.Environment.UserName: Windows Account Name
Page.User.Identity.Name: Domain\ Windows Account Name
System.Security.Principal.WindowsIdentity.GetCurrent().Name: Domain\ Windows Account Name
``` | Unless this functionality has changed under the MVC framework, and I don't think it has, Page.User.Identity.Name should still work. Sounds like your site is set up to allow anonymous authentication. If so, try disabling it. |
1,267,071 | I'm creating an intranet asp.net mvc application that everyone in the company should have access to. I need to run the website impersonated for database access etc., but I want to know who each user is.
When I look at `Page.User.Identity.Name` it's blank. Is it possible to get the user's windows account name even though the site is running impersonated?
**Edit:**
Here's a little more info. I have a site in IIS 6 running with anonymous access enabled. The site is running under a system account that has access to the database (because all of the employees do not have access to the database).
My web.config has `<authentication mode="Windows" />` and `<identity impersonate="true"/>`
My goal is that the users won't have to log in - that fact that they are logged into our network (and the fact that the site is not on an external IP) is enough authentication. I would just like to know who the user is in order to track changes they make, etc. | 2009/08/12 | [
"https://Stackoverflow.com/questions/1267071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34720/"
] | I just wanted to post my fix, because no one else had said anything about it.
I was having the same issue when I published the site to the server, but not on my local. All the settings were the same. However, in IIS the "Default Website" had never been turned off. It was running and intercepting traffic, even though there was no site associated with it. Anonymous Authentication was turned on in the default, but turned off in my website running under port 80. It didn't seem to matter that my site had it turned off... since the default was turned on it was turned on for all traffic to port 80.
Disabling the default web fixed the issue. Also changing the port to 8080 works.
I hope this helps someone. | Unless this functionality has changed under the MVC framework, and I don't think it has, Page.User.Identity.Name should still work. Sounds like your site is set up to allow anonymous authentication. If so, try disabling it. |
1,267,071 | I'm creating an intranet asp.net mvc application that everyone in the company should have access to. I need to run the website impersonated for database access etc., but I want to know who each user is.
When I look at `Page.User.Identity.Name` it's blank. Is it possible to get the user's windows account name even though the site is running impersonated?
**Edit:**
Here's a little more info. I have a site in IIS 6 running with anonymous access enabled. The site is running under a system account that has access to the database (because all of the employees do not have access to the database).
My web.config has `<authentication mode="Windows" />` and `<identity impersonate="true"/>`
My goal is that the users won't have to log in - that fact that they are logged into our network (and the fact that the site is not on an external IP) is enough authentication. I would just like to know who the user is in order to track changes they make, etc. | 2009/08/12 | [
"https://Stackoverflow.com/questions/1267071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34720/"
] | With `<authentication mode="Windows"/>` in your application and Anonymous access enabled in IIS, you will see the following results:
```
System.Environment.UserName: Computer Name
Page.User.Identity.Name: Blank
System.Security.Principal.WindowsIdentity.GetCurrent().Name: Computer Name
```
With `<authentication mode="Windows"/>` in your application, and ‘Anonymous access’ disabled and only ‘Integrated Windows Authentication’ in IIS, you will see the following results:
```
System.Environment.UserName: ASPNET (user account used to run ASP.NET service)
Page.User.Identity.Name: Domain\ Windows Account Name
System.Security.Principal.WindowsIdentity.GetCurrent().Name: Computer Name\ASPNET
```
With `<authentication mode="Windows"/>` and `<identity impersonate ="true"/>` in your application, and ‘Anonymous access’ disabled and only ‘Integrated Windows Authentication’ in IIS, you will see the following results:
```
System.Environment.UserName: Windows Account Name
Page.User.Identity.Name: Domain\ Windows Account Name
System.Security.Principal.WindowsIdentity.GetCurrent().Name: Domain\ Windows Account Name
``` | I just wanted to post my fix, because no one else had said anything about it.
I was having the same issue when I published the site to the server, but not on my local. All the settings were the same. However, in IIS the "Default Website" had never been turned off. It was running and intercepting traffic, even though there was no site associated with it. Anonymous Authentication was turned on in the default, but turned off in my website running under port 80. It didn't seem to matter that my site had it turned off... since the default was turned on it was turned on for all traffic to port 80.
Disabling the default web fixed the issue. Also changing the port to 8080 works.
I hope this helps someone. |
17,204,714 | * Why, in this query, is the final 'WHERE' clause needed to limit duplicates?
* The first LEFT JOIN is linking programs to entities on a UID
* The first INNER JOIN is linking programs to a subquery that gets statistics for those programs, by linking on a UID
* The subquery (that gets the StatsForDistributorClubs subset) is doing a grouping on UID columns
* So, I would've thought that this would all be joining unique records anyway so we shouldn't get row duplicates
* So why the need to limit based on the final WHERE by ensuring the 'program' is linked to the 'entity'?
(irrelevant parts of query omitted for clarity)
```
SELECT LmiEntity.[DisplayName]
,StatsForDistributorClubs.*
FROM [Program]
LEFT JOIN
LMIEntityProgram
ON LMIEntityProgram.ProgramUid = Program.ProgramUid
INNER JOIN
(
SELECT e.LmiEntityUid,
sp.ProgramUid,
SUM(attendeecount) [Total attendance],
FROM LMIEntity e,
Timetable t,
TimetableOccurrence [to],
ScheduledProgramOccurrence spo,
ScheduledProgram sp
WHERE
t.LicenseeUid = e.lmientityUid
AND [to].TimetableOccurrenceUid = spo.TimetableOccurrenceUid
AND sp.ScheduledProgramUid = spo.ScheduledProgramUid
GROUP BY e.lmientityUid, sp.ProgramUid
) AS StatsForDistributorClubs
ON Program.ProgramUid = StatsForDistributorClubs.ProgramUid
INNER JOIN LmiEntity
ON LmiEntity.LmiEntityUid = StatsForDistributorClubs.LmiEntityUid
LEFT OUTER JOIN Region
ON Region.RegionId = LMIEntity.RegionId
WHERE (
[Program].LicenseeUid = LmiEntity.LmiEntityUid
OR
[LMIEntityProgram].LMIEntityUid = LmiEntity.LmiEntityUid
)
``` | 2013/06/20 | [
"https://Stackoverflow.com/questions/17204714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1549918/"
] | As far as I understand you are trying to delete from the txt file. I would suggest `sed -i` for that. You should see required lines deleted in `${file}.mod` with your command
```
sed -i '/Entrust/d' $file
``` | As has been noted, your file contains `Entrust`, yet you are searching for `Entrusted`
```sh
sed '/Entrust/d'
``` |
17,204,714 | * Why, in this query, is the final 'WHERE' clause needed to limit duplicates?
* The first LEFT JOIN is linking programs to entities on a UID
* The first INNER JOIN is linking programs to a subquery that gets statistics for those programs, by linking on a UID
* The subquery (that gets the StatsForDistributorClubs subset) is doing a grouping on UID columns
* So, I would've thought that this would all be joining unique records anyway so we shouldn't get row duplicates
* So why the need to limit based on the final WHERE by ensuring the 'program' is linked to the 'entity'?
(irrelevant parts of query omitted for clarity)
```
SELECT LmiEntity.[DisplayName]
,StatsForDistributorClubs.*
FROM [Program]
LEFT JOIN
LMIEntityProgram
ON LMIEntityProgram.ProgramUid = Program.ProgramUid
INNER JOIN
(
SELECT e.LmiEntityUid,
sp.ProgramUid,
SUM(attendeecount) [Total attendance],
FROM LMIEntity e,
Timetable t,
TimetableOccurrence [to],
ScheduledProgramOccurrence spo,
ScheduledProgram sp
WHERE
t.LicenseeUid = e.lmientityUid
AND [to].TimetableOccurrenceUid = spo.TimetableOccurrenceUid
AND sp.ScheduledProgramUid = spo.ScheduledProgramUid
GROUP BY e.lmientityUid, sp.ProgramUid
) AS StatsForDistributorClubs
ON Program.ProgramUid = StatsForDistributorClubs.ProgramUid
INNER JOIN LmiEntity
ON LmiEntity.LmiEntityUid = StatsForDistributorClubs.LmiEntityUid
LEFT OUTER JOIN Region
ON Region.RegionId = LMIEntity.RegionId
WHERE (
[Program].LicenseeUid = LmiEntity.LmiEntityUid
OR
[LMIEntityProgram].LMIEntityUid = LmiEntity.LmiEntityUid
)
``` | 2013/06/20 | [
"https://Stackoverflow.com/questions/17204714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1549918/"
] | You can try:
[sed](/questions/tagged/sed "show questions tagged 'sed'")
```
sed -n '/Entrust/!p' $file > ${file}.mod
```
**or**
```
sed '/Entrust/d' $file > ${file}.mod
```
[awk](/questions/tagged/awk "show questions tagged 'awk'")
```
awk '!/Entrust/' $file > ${file}.mod
``` | As has been noted, your file contains `Entrust`, yet you are searching for `Entrusted`
```sh
sed '/Entrust/d'
``` |
17,204,714 | * Why, in this query, is the final 'WHERE' clause needed to limit duplicates?
* The first LEFT JOIN is linking programs to entities on a UID
* The first INNER JOIN is linking programs to a subquery that gets statistics for those programs, by linking on a UID
* The subquery (that gets the StatsForDistributorClubs subset) is doing a grouping on UID columns
* So, I would've thought that this would all be joining unique records anyway so we shouldn't get row duplicates
* So why the need to limit based on the final WHERE by ensuring the 'program' is linked to the 'entity'?
(irrelevant parts of query omitted for clarity)
```
SELECT LmiEntity.[DisplayName]
,StatsForDistributorClubs.*
FROM [Program]
LEFT JOIN
LMIEntityProgram
ON LMIEntityProgram.ProgramUid = Program.ProgramUid
INNER JOIN
(
SELECT e.LmiEntityUid,
sp.ProgramUid,
SUM(attendeecount) [Total attendance],
FROM LMIEntity e,
Timetable t,
TimetableOccurrence [to],
ScheduledProgramOccurrence spo,
ScheduledProgram sp
WHERE
t.LicenseeUid = e.lmientityUid
AND [to].TimetableOccurrenceUid = spo.TimetableOccurrenceUid
AND sp.ScheduledProgramUid = spo.ScheduledProgramUid
GROUP BY e.lmientityUid, sp.ProgramUid
) AS StatsForDistributorClubs
ON Program.ProgramUid = StatsForDistributorClubs.ProgramUid
INNER JOIN LmiEntity
ON LmiEntity.LmiEntityUid = StatsForDistributorClubs.LmiEntityUid
LEFT OUTER JOIN Region
ON Region.RegionId = LMIEntity.RegionId
WHERE (
[Program].LicenseeUid = LmiEntity.LmiEntityUid
OR
[LMIEntityProgram].LMIEntityUid = LmiEntity.LmiEntityUid
)
``` | 2013/06/20 | [
"https://Stackoverflow.com/questions/17204714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1549918/"
] | As far as I understand you are trying to delete from the txt file. I would suggest `sed -i` for that. You should see required lines deleted in `${file}.mod` with your command
```
sed -i '/Entrust/d' $file
``` | ```
sed -i 's/<content>This document has been digitally signed with external signatures using Entrust PKI</content>/#<content>This document has been digitally signed with external signatures using Entrust PKI</content>/g' $filename
```
This is the way you can comment the line that will not be noticed/read by the script. |
17,204,714 | * Why, in this query, is the final 'WHERE' clause needed to limit duplicates?
* The first LEFT JOIN is linking programs to entities on a UID
* The first INNER JOIN is linking programs to a subquery that gets statistics for those programs, by linking on a UID
* The subquery (that gets the StatsForDistributorClubs subset) is doing a grouping on UID columns
* So, I would've thought that this would all be joining unique records anyway so we shouldn't get row duplicates
* So why the need to limit based on the final WHERE by ensuring the 'program' is linked to the 'entity'?
(irrelevant parts of query omitted for clarity)
```
SELECT LmiEntity.[DisplayName]
,StatsForDistributorClubs.*
FROM [Program]
LEFT JOIN
LMIEntityProgram
ON LMIEntityProgram.ProgramUid = Program.ProgramUid
INNER JOIN
(
SELECT e.LmiEntityUid,
sp.ProgramUid,
SUM(attendeecount) [Total attendance],
FROM LMIEntity e,
Timetable t,
TimetableOccurrence [to],
ScheduledProgramOccurrence spo,
ScheduledProgram sp
WHERE
t.LicenseeUid = e.lmientityUid
AND [to].TimetableOccurrenceUid = spo.TimetableOccurrenceUid
AND sp.ScheduledProgramUid = spo.ScheduledProgramUid
GROUP BY e.lmientityUid, sp.ProgramUid
) AS StatsForDistributorClubs
ON Program.ProgramUid = StatsForDistributorClubs.ProgramUid
INNER JOIN LmiEntity
ON LmiEntity.LmiEntityUid = StatsForDistributorClubs.LmiEntityUid
LEFT OUTER JOIN Region
ON Region.RegionId = LMIEntity.RegionId
WHERE (
[Program].LicenseeUid = LmiEntity.LmiEntityUid
OR
[LMIEntityProgram].LMIEntityUid = LmiEntity.LmiEntityUid
)
``` | 2013/06/20 | [
"https://Stackoverflow.com/questions/17204714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1549918/"
] | As far as I understand you are trying to delete from the txt file. I would suggest `sed -i` for that. You should see required lines deleted in `${file}.mod` with your command
```
sed -i '/Entrust/d' $file
``` | ```
perl -lne 'print unless(/\bEntrust\b/)' your_file.txt > your_file.mod
``` |
17,204,714 | * Why, in this query, is the final 'WHERE' clause needed to limit duplicates?
* The first LEFT JOIN is linking programs to entities on a UID
* The first INNER JOIN is linking programs to a subquery that gets statistics for those programs, by linking on a UID
* The subquery (that gets the StatsForDistributorClubs subset) is doing a grouping on UID columns
* So, I would've thought that this would all be joining unique records anyway so we shouldn't get row duplicates
* So why the need to limit based on the final WHERE by ensuring the 'program' is linked to the 'entity'?
(irrelevant parts of query omitted for clarity)
```
SELECT LmiEntity.[DisplayName]
,StatsForDistributorClubs.*
FROM [Program]
LEFT JOIN
LMIEntityProgram
ON LMIEntityProgram.ProgramUid = Program.ProgramUid
INNER JOIN
(
SELECT e.LmiEntityUid,
sp.ProgramUid,
SUM(attendeecount) [Total attendance],
FROM LMIEntity e,
Timetable t,
TimetableOccurrence [to],
ScheduledProgramOccurrence spo,
ScheduledProgram sp
WHERE
t.LicenseeUid = e.lmientityUid
AND [to].TimetableOccurrenceUid = spo.TimetableOccurrenceUid
AND sp.ScheduledProgramUid = spo.ScheduledProgramUid
GROUP BY e.lmientityUid, sp.ProgramUid
) AS StatsForDistributorClubs
ON Program.ProgramUid = StatsForDistributorClubs.ProgramUid
INNER JOIN LmiEntity
ON LmiEntity.LmiEntityUid = StatsForDistributorClubs.LmiEntityUid
LEFT OUTER JOIN Region
ON Region.RegionId = LMIEntity.RegionId
WHERE (
[Program].LicenseeUid = LmiEntity.LmiEntityUid
OR
[LMIEntityProgram].LMIEntityUid = LmiEntity.LmiEntityUid
)
``` | 2013/06/20 | [
"https://Stackoverflow.com/questions/17204714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1549918/"
] | As far as I understand you are trying to delete from the txt file. I would suggest `sed -i` for that. You should see required lines deleted in `${file}.mod` with your command
```
sed -i '/Entrust/d' $file
``` | To search text outside XML-style tags, use the command below;
```
sed '/^\([^<]*\(<[^<>]*>\)*\)*Entrust/d'
```
Here is an example;
```
$ cat tmp.txt
some content 2.
some content with Entrust.
<tag type='Entrust'/>
<tag>Entrust</tag>
$ sed '/^\([^<]*\(<[^<>]*>\)*\)*Entrust/d' tmp.txt
some content 2.
<tag type='Entrust'/>
```
Note that this expression does not handle a tag which contains line-breaks. |
17,204,714 | * Why, in this query, is the final 'WHERE' clause needed to limit duplicates?
* The first LEFT JOIN is linking programs to entities on a UID
* The first INNER JOIN is linking programs to a subquery that gets statistics for those programs, by linking on a UID
* The subquery (that gets the StatsForDistributorClubs subset) is doing a grouping on UID columns
* So, I would've thought that this would all be joining unique records anyway so we shouldn't get row duplicates
* So why the need to limit based on the final WHERE by ensuring the 'program' is linked to the 'entity'?
(irrelevant parts of query omitted for clarity)
```
SELECT LmiEntity.[DisplayName]
,StatsForDistributorClubs.*
FROM [Program]
LEFT JOIN
LMIEntityProgram
ON LMIEntityProgram.ProgramUid = Program.ProgramUid
INNER JOIN
(
SELECT e.LmiEntityUid,
sp.ProgramUid,
SUM(attendeecount) [Total attendance],
FROM LMIEntity e,
Timetable t,
TimetableOccurrence [to],
ScheduledProgramOccurrence spo,
ScheduledProgram sp
WHERE
t.LicenseeUid = e.lmientityUid
AND [to].TimetableOccurrenceUid = spo.TimetableOccurrenceUid
AND sp.ScheduledProgramUid = spo.ScheduledProgramUid
GROUP BY e.lmientityUid, sp.ProgramUid
) AS StatsForDistributorClubs
ON Program.ProgramUid = StatsForDistributorClubs.ProgramUid
INNER JOIN LmiEntity
ON LmiEntity.LmiEntityUid = StatsForDistributorClubs.LmiEntityUid
LEFT OUTER JOIN Region
ON Region.RegionId = LMIEntity.RegionId
WHERE (
[Program].LicenseeUid = LmiEntity.LmiEntityUid
OR
[LMIEntityProgram].LMIEntityUid = LmiEntity.LmiEntityUid
)
``` | 2013/06/20 | [
"https://Stackoverflow.com/questions/17204714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1549918/"
] | As far as I understand you are trying to delete from the txt file. I would suggest `sed -i` for that. You should see required lines deleted in `${file}.mod` with your command
```
sed -i '/Entrust/d' $file
``` | You can try:
[sed](/questions/tagged/sed "show questions tagged 'sed'")
```
sed -n '/Entrust/!p' $file > ${file}.mod
```
**or**
```
sed '/Entrust/d' $file > ${file}.mod
```
[awk](/questions/tagged/awk "show questions tagged 'awk'")
```
awk '!/Entrust/' $file > ${file}.mod
``` |
17,204,714 | * Why, in this query, is the final 'WHERE' clause needed to limit duplicates?
* The first LEFT JOIN is linking programs to entities on a UID
* The first INNER JOIN is linking programs to a subquery that gets statistics for those programs, by linking on a UID
* The subquery (that gets the StatsForDistributorClubs subset) is doing a grouping on UID columns
* So, I would've thought that this would all be joining unique records anyway so we shouldn't get row duplicates
* So why the need to limit based on the final WHERE by ensuring the 'program' is linked to the 'entity'?
(irrelevant parts of query omitted for clarity)
```
SELECT LmiEntity.[DisplayName]
,StatsForDistributorClubs.*
FROM [Program]
LEFT JOIN
LMIEntityProgram
ON LMIEntityProgram.ProgramUid = Program.ProgramUid
INNER JOIN
(
SELECT e.LmiEntityUid,
sp.ProgramUid,
SUM(attendeecount) [Total attendance],
FROM LMIEntity e,
Timetable t,
TimetableOccurrence [to],
ScheduledProgramOccurrence spo,
ScheduledProgram sp
WHERE
t.LicenseeUid = e.lmientityUid
AND [to].TimetableOccurrenceUid = spo.TimetableOccurrenceUid
AND sp.ScheduledProgramUid = spo.ScheduledProgramUid
GROUP BY e.lmientityUid, sp.ProgramUid
) AS StatsForDistributorClubs
ON Program.ProgramUid = StatsForDistributorClubs.ProgramUid
INNER JOIN LmiEntity
ON LmiEntity.LmiEntityUid = StatsForDistributorClubs.LmiEntityUid
LEFT OUTER JOIN Region
ON Region.RegionId = LMIEntity.RegionId
WHERE (
[Program].LicenseeUid = LmiEntity.LmiEntityUid
OR
[LMIEntityProgram].LMIEntityUid = LmiEntity.LmiEntityUid
)
``` | 2013/06/20 | [
"https://Stackoverflow.com/questions/17204714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1549918/"
] | You can try:
[sed](/questions/tagged/sed "show questions tagged 'sed'")
```
sed -n '/Entrust/!p' $file > ${file}.mod
```
**or**
```
sed '/Entrust/d' $file > ${file}.mod
```
[awk](/questions/tagged/awk "show questions tagged 'awk'")
```
awk '!/Entrust/' $file > ${file}.mod
``` | ```
sed -i 's/<content>This document has been digitally signed with external signatures using Entrust PKI</content>/#<content>This document has been digitally signed with external signatures using Entrust PKI</content>/g' $filename
```
This is the way you can comment the line that will not be noticed/read by the script. |
17,204,714 | * Why, in this query, is the final 'WHERE' clause needed to limit duplicates?
* The first LEFT JOIN is linking programs to entities on a UID
* The first INNER JOIN is linking programs to a subquery that gets statistics for those programs, by linking on a UID
* The subquery (that gets the StatsForDistributorClubs subset) is doing a grouping on UID columns
* So, I would've thought that this would all be joining unique records anyway so we shouldn't get row duplicates
* So why the need to limit based on the final WHERE by ensuring the 'program' is linked to the 'entity'?
(irrelevant parts of query omitted for clarity)
```
SELECT LmiEntity.[DisplayName]
,StatsForDistributorClubs.*
FROM [Program]
LEFT JOIN
LMIEntityProgram
ON LMIEntityProgram.ProgramUid = Program.ProgramUid
INNER JOIN
(
SELECT e.LmiEntityUid,
sp.ProgramUid,
SUM(attendeecount) [Total attendance],
FROM LMIEntity e,
Timetable t,
TimetableOccurrence [to],
ScheduledProgramOccurrence spo,
ScheduledProgram sp
WHERE
t.LicenseeUid = e.lmientityUid
AND [to].TimetableOccurrenceUid = spo.TimetableOccurrenceUid
AND sp.ScheduledProgramUid = spo.ScheduledProgramUid
GROUP BY e.lmientityUid, sp.ProgramUid
) AS StatsForDistributorClubs
ON Program.ProgramUid = StatsForDistributorClubs.ProgramUid
INNER JOIN LmiEntity
ON LmiEntity.LmiEntityUid = StatsForDistributorClubs.LmiEntityUid
LEFT OUTER JOIN Region
ON Region.RegionId = LMIEntity.RegionId
WHERE (
[Program].LicenseeUid = LmiEntity.LmiEntityUid
OR
[LMIEntityProgram].LMIEntityUid = LmiEntity.LmiEntityUid
)
``` | 2013/06/20 | [
"https://Stackoverflow.com/questions/17204714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1549918/"
] | You can try:
[sed](/questions/tagged/sed "show questions tagged 'sed'")
```
sed -n '/Entrust/!p' $file > ${file}.mod
```
**or**
```
sed '/Entrust/d' $file > ${file}.mod
```
[awk](/questions/tagged/awk "show questions tagged 'awk'")
```
awk '!/Entrust/' $file > ${file}.mod
``` | ```
perl -lne 'print unless(/\bEntrust\b/)' your_file.txt > your_file.mod
``` |
17,204,714 | * Why, in this query, is the final 'WHERE' clause needed to limit duplicates?
* The first LEFT JOIN is linking programs to entities on a UID
* The first INNER JOIN is linking programs to a subquery that gets statistics for those programs, by linking on a UID
* The subquery (that gets the StatsForDistributorClubs subset) is doing a grouping on UID columns
* So, I would've thought that this would all be joining unique records anyway so we shouldn't get row duplicates
* So why the need to limit based on the final WHERE by ensuring the 'program' is linked to the 'entity'?
(irrelevant parts of query omitted for clarity)
```
SELECT LmiEntity.[DisplayName]
,StatsForDistributorClubs.*
FROM [Program]
LEFT JOIN
LMIEntityProgram
ON LMIEntityProgram.ProgramUid = Program.ProgramUid
INNER JOIN
(
SELECT e.LmiEntityUid,
sp.ProgramUid,
SUM(attendeecount) [Total attendance],
FROM LMIEntity e,
Timetable t,
TimetableOccurrence [to],
ScheduledProgramOccurrence spo,
ScheduledProgram sp
WHERE
t.LicenseeUid = e.lmientityUid
AND [to].TimetableOccurrenceUid = spo.TimetableOccurrenceUid
AND sp.ScheduledProgramUid = spo.ScheduledProgramUid
GROUP BY e.lmientityUid, sp.ProgramUid
) AS StatsForDistributorClubs
ON Program.ProgramUid = StatsForDistributorClubs.ProgramUid
INNER JOIN LmiEntity
ON LmiEntity.LmiEntityUid = StatsForDistributorClubs.LmiEntityUid
LEFT OUTER JOIN Region
ON Region.RegionId = LMIEntity.RegionId
WHERE (
[Program].LicenseeUid = LmiEntity.LmiEntityUid
OR
[LMIEntityProgram].LMIEntityUid = LmiEntity.LmiEntityUid
)
``` | 2013/06/20 | [
"https://Stackoverflow.com/questions/17204714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1549918/"
] | You can try:
[sed](/questions/tagged/sed "show questions tagged 'sed'")
```
sed -n '/Entrust/!p' $file > ${file}.mod
```
**or**
```
sed '/Entrust/d' $file > ${file}.mod
```
[awk](/questions/tagged/awk "show questions tagged 'awk'")
```
awk '!/Entrust/' $file > ${file}.mod
``` | To search text outside XML-style tags, use the command below;
```
sed '/^\([^<]*\(<[^<>]*>\)*\)*Entrust/d'
```
Here is an example;
```
$ cat tmp.txt
some content 2.
some content with Entrust.
<tag type='Entrust'/>
<tag>Entrust</tag>
$ sed '/^\([^<]*\(<[^<>]*>\)*\)*Entrust/d' tmp.txt
some content 2.
<tag type='Entrust'/>
```
Note that this expression does not handle a tag which contains line-breaks. |
226,599 | Using the following code, I make a simple graph that is exported to pdf:
```
format = AxesStyle -> {{Thickness[.01], Arrowheads[{0.0, 0.05}]}, { Arrowheads[{0.0, 0.05}]} }
graph = ListLinePlot[Table[{t, 2*t}, {t, 0, 100}], format, AspectRatio -> .2]
Export[StringJoin[NotebookDirectory[], "\\ext.pdf"], graph];
```
When I look at the graph, it cuts of the end of one of the arrows:
[](https://i.stack.imgur.com/lVJwa.png)
The y axis is ok - but the x axis is not. The end of the arrow has been clipped. It seems to be related to increasing the thickness of the axis.
For what its worth, the in-notebook display of the graph has complete arrows. It is only the exported version that is clipped.
I want both axes thick, and I want the whole arrow, and I want it in PDF. How to do this?
Please note that it didn't have this problem in Mathematica 11.3; it is only after I upgraded that this problem has arisen. I'm using 12.1
Edit: The reason I want it in pdf is not because I like the file format, but because I want it in a vector graphic that works with Latex. The output should have the resolution of a high quality vector graphic, without the arrow chopped. | 2020/07/27 | [
"https://mathematica.stackexchange.com/questions/226599",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/22432/"
] | The cut off in the head of the arrow appeared due to the assigned thickness of the axes, to check this we can change the position of the arrow and examine it closely as follow:
```
format = AxesStyle -> {{Thickness[0.02],
Arrowheads[{{0.09, 0.8}}]}, {Arrowheads[{0.0, 0.05}]}};
graph = ListLinePlot[Table[{t, 2*t}, {t, 0, 100}], format,
AspectRatio -> .2]
Export[StringJoin[NotebookDirectory[], "\\ext.pdf"], graph];
```
[](https://i.stack.imgur.com/rK0gw.png)
I used a pdf editor to check the head of the arrow, and this cut off is increased with increasing the thickness of the axes. So, the simple solution is to avoid assign specific thickness and instead impose it like this-:)
```
format = AxesStyle -> {{Arrowheads[{0.0, 0.05}]}, {Arrowheads[{0.0,
0.05}]}};
graph = ListLinePlot[{Table[{t, 0}, {t, -3, 100}],
Table[{t, 2*t}, {t, 0, 100}]}, format, AspectRatio -> .2,
PlotStyle -> {Directive[Gray, Thickness[0.01]], Blue}]
Export[StringJoin[NotebookDirectory[], "\\ext.pdf"], graph];
```
[](https://i.stack.imgur.com/FjnX8.png) | Add a little padding in a `Show` and export it as SVG. If you look at the SVG it's still broken. But then reimport it using `ResourceFunction["SVGImport"]`, then export it back out again as PDF. This seems to magically work and the PDF has the full arrow ... don't ask me why though:
```
svgi = ResourceFunction["SVGImport"]
format = AxesStyle -> {{Thickness[.01], Arrowheads[{0.0, 0.05}]}, {Arrowheads[{0.0, 0.05}]}}
graph = ListLinePlot[Table[{t, 2*t}, {t, 0, 100}], format, AspectRatio -> .2]
Export["ext.svg", Show[graph, PlotRangePadding -> {Automatic, 2}]];
result = svgi["ext.svg"]
Export["ext1.pdf", Show[result, PlotRangePadding -> {Automatic, 2}]]
``` |
226,599 | Using the following code, I make a simple graph that is exported to pdf:
```
format = AxesStyle -> {{Thickness[.01], Arrowheads[{0.0, 0.05}]}, { Arrowheads[{0.0, 0.05}]} }
graph = ListLinePlot[Table[{t, 2*t}, {t, 0, 100}], format, AspectRatio -> .2]
Export[StringJoin[NotebookDirectory[], "\\ext.pdf"], graph];
```
When I look at the graph, it cuts of the end of one of the arrows:
[](https://i.stack.imgur.com/lVJwa.png)
The y axis is ok - but the x axis is not. The end of the arrow has been clipped. It seems to be related to increasing the thickness of the axis.
For what its worth, the in-notebook display of the graph has complete arrows. It is only the exported version that is clipped.
I want both axes thick, and I want the whole arrow, and I want it in PDF. How to do this?
Please note that it didn't have this problem in Mathematica 11.3; it is only after I upgraded that this problem has arisen. I'm using 12.1
Edit: The reason I want it in pdf is not because I like the file format, but because I want it in a vector graphic that works with Latex. The output should have the resolution of a high quality vector graphic, without the arrow chopped. | 2020/07/27 | [
"https://mathematica.stackexchange.com/questions/226599",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/22432/"
] | Add a little padding in a `Show` and export it as SVG. If you look at the SVG it's still broken. But then reimport it using `ResourceFunction["SVGImport"]`, then export it back out again as PDF. This seems to magically work and the PDF has the full arrow ... don't ask me why though:
```
svgi = ResourceFunction["SVGImport"]
format = AxesStyle -> {{Thickness[.01], Arrowheads[{0.0, 0.05}]}, {Arrowheads[{0.0, 0.05}]}}
graph = ListLinePlot[Table[{t, 2*t}, {t, 0, 100}], format, AspectRatio -> .2]
Export["ext.svg", Show[graph, PlotRangePadding -> {Automatic, 2}]];
result = svgi["ext.svg"]
Export["ext1.pdf", Show[result, PlotRangePadding -> {Automatic, 2}]]
``` | [Export to PDF - scaling grids of plots and text size](https://mathematica.stackexchange.com/questions/2475/export-to-pdf-scaling-grids-of-plots-and-text-size) should answer this question already.
```
lots = GraphicsGrid[
Table[With[{a = RandomInteger[{1, 17}],
b = RandomInteger[{1, 17}]},
ParametricPlot[Sin[t^2] {Cos[a t], Sin[b t]}, {t, 0, 2 \[Pi]},
PlotRange -> {{-1, 1}, {-1, 1}}, Frame -> True,
ImageSize -> Scaled[1]]], {15}, {7}]];
Export["lots.pdf", lots]
```
The main problem is to use the right font. Mathematica is publication-ready, but are all the other programs especially for publication-ready for their task. The main problem is to determine the operating system one is on.
Otherwise, the Mathematica documentation is genial: [PDF](http://reference.wolfram.com/language/ref/format/PDF.html).
You are to work publication-ready responsible to match the fonts. That is true on all operating systems and everywhere. So match the font Mathematica uses in the graphics to the ones available to the pdf display program set on the local machine.
[`Scaled`](http://reference.wolfram.com/language/ref/Scaled.html) is really nice built-in otherwise.
There are features like pdf font embedding.
Another workaround is to export the graphics to SVG and convert the svg externally to pdf.
[SVG](http://reference.wolfram.com/language/ref/format/SVG.html) is mightier in Mathematica.
```
ExportString[Graphics[{Red, Disk[]}], "SVG"]
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" \
xmlns:xlink="http://www.w3.org/1999/xlink" width="360pt" \
height="359pt" viewBox="0 0 360 359" version="1.1">
<g id="surface79">
<path style=" \
stroke:none;fill-rule:evenodd;fill:rgb(99.998474%,0%,0%);fill-opacity:\
1;" d="M 351.820312 179.210938 C 351.820312 133.511719 333.664062 \
89.679688 301.347656 57.363281 C 269.03125 25.046875 225.203125 \
6.894531 179.5 6.894531 C 133.796875 6.894531 89.96875 25.046875 \
57.652344 57.363281 C 25.335938 89.679688 7.179688 133.511719 \
7.179688 179.210938 C 7.179688 224.914062 25.335938 268.746094 \
57.652344 301.0625 C 89.96875 333.378906 133.796875 351.53125 179.5 \
351.53125 C 225.203125 351.53125 269.03125 333.378906 301.347656 \
301.0625 C 333.664062 268.746094 351.820312 224.914062 351.820312 \
179.210938 Z M 351.820312 179.210938 "/>
</g>
</svg>
```
You can inspect the output to SVG in Mathematica.
```
format = AxesStyle -> {{Thickness[.01],
Arrowheads[{0.0, 0.05}]}, {Arrowheads[{0.0, 0.05}]}}
graph = ListLinePlot[Table[{t, 2*t}, {t, 0, 100}], format,
AspectRatio -> .2]
ExportString[
ListLinePlot[Table[{t, 2*t}, {t, 0, 100}], format,
AspectRatio -> .2], "SVG"]
```
[](https://i.stack.imgur.com/PMRis.png)
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" width="360pt"
height="88pt" viewBox="0 0 360 88" version="1.1">
<path style="fill:none;stroke-width:1.6;stroke-linecap:square;stroke-
linejoin:miter;stroke:rgb(36.84082%,50.67749%,70.979309%);stroke-
opacity:1;stroke-miterlimit:3.25;" d="M 94 83.515625 L 100.609375
82.234375 L 103.910156 81.59375 L 113.824219 79.671875 L 117.128906
79.035156 L 120.433594 78.394531 L 123.734375 77.753906 L 136.953125
75.191406 L 140.253906 74.550781 L 143.558594 73.910156 L 146.863281
73.273438 L 153.472656 71.992188 L 156.773438 71.351562 L 169.992188
68.789062 L 173.296875 68.152344 L 176.597656 67.511719 L 189.816406
64.949219 L 193.117188 64.308594 L 196.421875 63.667969 L 199.726562
63.03125 L 206.335938 61.75 L 209.636719 61.109375 L 222.855469
58.546875 L 226.160156 57.910156 L 229.460938 57.269531 L 242.679688
54.707031 L 245.980469 54.066406 L 249.285156 53.425781 L 252.589844
52.789062 L 259.199219 51.507812 L 262.5 50.867188 L 275.71875
48.304688 L 279.023438 47.667969 L 282.324219 47.027344 L 295.542969
44.464844 L 298.84375 43.824219 L 302.148438 43.183594 L 305.453125
42.546875 L 315.367188 40.625 L 318.667969 39.984375 L 328.582031
38.0625 L 331.886719 37.425781 L 335.1875 36.785156 L 348.40625
34.222656 L 351.707031 33.582031 L 355.011719 32.941406 L 358.316406
32.304688 L 368.230469 30.382812 L 371.53125 29.742188 L 381.445312
27.820312 L 384.75 27.183594 L 388.050781 26.542969 L 401.269531
23.980469 L 404.570312 23.339844 L 407.875 22.699219 L 411.179688
22.0625 L 421.09375 20.140625 L 424.394531 19.5 "
transform="matrix(1,0,0,1,-74,-13)"/>
<path style="fill:none;stroke-width:3.441624;stroke-linecap:butt;
stroke-linejoin:miter;stroke:rgb(0%,0%,0%);stroke-opacity:1;stroke-
miterlimit:3.25;" d="M 87.117188 83.515625 L 415.660156 83.515625 "
transform="matrix(1,0,0,1,-74,-13)"/>
<path style="fill:none;stroke-width:0.03;stroke-linecap:square;stroke-
linejoin:miter;stroke:rgb(0%,0%,0%);stroke-opacity:1;stroke-
miterlimit:3.25;" d="M 87.117188 83.515625 Z M 87.117188 83.515625 "
transform="matrix(1,0,0,1,-74,-13)"/>
<path style="fill:none;stroke-width:1;stroke-linecap:butt;stroke-
linejoin:miter;stroke:rgb(0%,0%,0%);stroke-opacity:1;stroke-
miterlimit:3.25;" d="M 94 84.890625 L 94 31.679688 "
transform="matrix(1,0,0,1,-74,-13)"/>
<path style="fill:none;stroke-width:0.03;stroke-linecap:square;stroke-
linejoin:miter;stroke:rgb(0%,0%,0%);stroke-opacity:1;stroke-
miterlimit:3.25;" d="M 94 84.890625 Z M 94 84.890625 "
transform="matrix(1,0,0,1,-74,-13)"/>
<path style="fill-rule:nonzero;fill:rgb(0%,0%,0%);fill-opacity:1;
stroke-width:0.03;stroke-linecap:square;stroke-linejoin:miter;stroke:
rgb(0%,0%,0%);stroke-opacity:1;stroke-miterlimit:3.25;" d="M
89.472656 33.265625 L 89.988281 33.015625 L 91.222656 32.460938 L
91.964844 32.167969 L 92.714844 31.914062 L 93.414062 31.738281 L 94
31.679688 L 94.53125 31.738281 L 95.21875 31.914062 L 95.996094
32.167969 L 96.785156 32.460938 L 98.136719 33.015625 L 98.710938
33.265625 L 94 16.058594 Z M 89.472656 33.265625 "
transform="matrix(1,0,0,1,-74,-13)"/>
And correct smaller deviation from the intent by hand after some experience is accumulated.
Converting SVG to PDf is safe since both standards are compatible. SVG is subset of the HTML5 language specification and therefore on the internet high level most advanced standard. PDF is only supported up to version 1.5 by Mathematica. There is already 1.7 published. The Adobe Systems version PDF 1.7 is the basis for this ISO 32000 edition as the newest valid standard since 2008, so very aged. SVG is too part of XML specification for example used by Word or OpenOffice.
Both pdf and svg can be viewed in the browser.
[](https://i.stack.imgur.com/IuzGE.png)
svg can be imported in many pdf editors as well. Compared to all Rasterizers this remain vector grafics and can be enlarged as the rest of an pdf without pixelation and other image distorsions. This is the official Adobe page for SVG: [enter link description here](https://www.adobe.com/devnet/svg.html). SCG is open source and complete part of Mathematica.
A tip is drag the output of the graphics input into the second field of the [`Export`](https://reference.wolfram.com/language/ref/Export.html) built-in for best results. |
226,599 | Using the following code, I make a simple graph that is exported to pdf:
```
format = AxesStyle -> {{Thickness[.01], Arrowheads[{0.0, 0.05}]}, { Arrowheads[{0.0, 0.05}]} }
graph = ListLinePlot[Table[{t, 2*t}, {t, 0, 100}], format, AspectRatio -> .2]
Export[StringJoin[NotebookDirectory[], "\\ext.pdf"], graph];
```
When I look at the graph, it cuts of the end of one of the arrows:
[](https://i.stack.imgur.com/lVJwa.png)
The y axis is ok - but the x axis is not. The end of the arrow has been clipped. It seems to be related to increasing the thickness of the axis.
For what its worth, the in-notebook display of the graph has complete arrows. It is only the exported version that is clipped.
I want both axes thick, and I want the whole arrow, and I want it in PDF. How to do this?
Please note that it didn't have this problem in Mathematica 11.3; it is only after I upgraded that this problem has arisen. I'm using 12.1
Edit: The reason I want it in pdf is not because I like the file format, but because I want it in a vector graphic that works with Latex. The output should have the resolution of a high quality vector graphic, without the arrow chopped. | 2020/07/27 | [
"https://mathematica.stackexchange.com/questions/226599",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/22432/"
] | The cut off in the head of the arrow appeared due to the assigned thickness of the axes, to check this we can change the position of the arrow and examine it closely as follow:
```
format = AxesStyle -> {{Thickness[0.02],
Arrowheads[{{0.09, 0.8}}]}, {Arrowheads[{0.0, 0.05}]}};
graph = ListLinePlot[Table[{t, 2*t}, {t, 0, 100}], format,
AspectRatio -> .2]
Export[StringJoin[NotebookDirectory[], "\\ext.pdf"], graph];
```
[](https://i.stack.imgur.com/rK0gw.png)
I used a pdf editor to check the head of the arrow, and this cut off is increased with increasing the thickness of the axes. So, the simple solution is to avoid assign specific thickness and instead impose it like this-:)
```
format = AxesStyle -> {{Arrowheads[{0.0, 0.05}]}, {Arrowheads[{0.0,
0.05}]}};
graph = ListLinePlot[{Table[{t, 0}, {t, -3, 100}],
Table[{t, 2*t}, {t, 0, 100}]}, format, AspectRatio -> .2,
PlotStyle -> {Directive[Gray, Thickness[0.01]], Blue}]
Export[StringJoin[NotebookDirectory[], "\\ext.pdf"], graph];
```
[](https://i.stack.imgur.com/FjnX8.png) | [Export to PDF - scaling grids of plots and text size](https://mathematica.stackexchange.com/questions/2475/export-to-pdf-scaling-grids-of-plots-and-text-size) should answer this question already.
```
lots = GraphicsGrid[
Table[With[{a = RandomInteger[{1, 17}],
b = RandomInteger[{1, 17}]},
ParametricPlot[Sin[t^2] {Cos[a t], Sin[b t]}, {t, 0, 2 \[Pi]},
PlotRange -> {{-1, 1}, {-1, 1}}, Frame -> True,
ImageSize -> Scaled[1]]], {15}, {7}]];
Export["lots.pdf", lots]
```
The main problem is to use the right font. Mathematica is publication-ready, but are all the other programs especially for publication-ready for their task. The main problem is to determine the operating system one is on.
Otherwise, the Mathematica documentation is genial: [PDF](http://reference.wolfram.com/language/ref/format/PDF.html).
You are to work publication-ready responsible to match the fonts. That is true on all operating systems and everywhere. So match the font Mathematica uses in the graphics to the ones available to the pdf display program set on the local machine.
[`Scaled`](http://reference.wolfram.com/language/ref/Scaled.html) is really nice built-in otherwise.
There are features like pdf font embedding.
Another workaround is to export the graphics to SVG and convert the svg externally to pdf.
[SVG](http://reference.wolfram.com/language/ref/format/SVG.html) is mightier in Mathematica.
```
ExportString[Graphics[{Red, Disk[]}], "SVG"]
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" \
xmlns:xlink="http://www.w3.org/1999/xlink" width="360pt" \
height="359pt" viewBox="0 0 360 359" version="1.1">
<g id="surface79">
<path style=" \
stroke:none;fill-rule:evenodd;fill:rgb(99.998474%,0%,0%);fill-opacity:\
1;" d="M 351.820312 179.210938 C 351.820312 133.511719 333.664062 \
89.679688 301.347656 57.363281 C 269.03125 25.046875 225.203125 \
6.894531 179.5 6.894531 C 133.796875 6.894531 89.96875 25.046875 \
57.652344 57.363281 C 25.335938 89.679688 7.179688 133.511719 \
7.179688 179.210938 C 7.179688 224.914062 25.335938 268.746094 \
57.652344 301.0625 C 89.96875 333.378906 133.796875 351.53125 179.5 \
351.53125 C 225.203125 351.53125 269.03125 333.378906 301.347656 \
301.0625 C 333.664062 268.746094 351.820312 224.914062 351.820312 \
179.210938 Z M 351.820312 179.210938 "/>
</g>
</svg>
```
You can inspect the output to SVG in Mathematica.
```
format = AxesStyle -> {{Thickness[.01],
Arrowheads[{0.0, 0.05}]}, {Arrowheads[{0.0, 0.05}]}}
graph = ListLinePlot[Table[{t, 2*t}, {t, 0, 100}], format,
AspectRatio -> .2]
ExportString[
ListLinePlot[Table[{t, 2*t}, {t, 0, 100}], format,
AspectRatio -> .2], "SVG"]
```
[](https://i.stack.imgur.com/PMRis.png)
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" width="360pt"
height="88pt" viewBox="0 0 360 88" version="1.1">
<path style="fill:none;stroke-width:1.6;stroke-linecap:square;stroke-
linejoin:miter;stroke:rgb(36.84082%,50.67749%,70.979309%);stroke-
opacity:1;stroke-miterlimit:3.25;" d="M 94 83.515625 L 100.609375
82.234375 L 103.910156 81.59375 L 113.824219 79.671875 L 117.128906
79.035156 L 120.433594 78.394531 L 123.734375 77.753906 L 136.953125
75.191406 L 140.253906 74.550781 L 143.558594 73.910156 L 146.863281
73.273438 L 153.472656 71.992188 L 156.773438 71.351562 L 169.992188
68.789062 L 173.296875 68.152344 L 176.597656 67.511719 L 189.816406
64.949219 L 193.117188 64.308594 L 196.421875 63.667969 L 199.726562
63.03125 L 206.335938 61.75 L 209.636719 61.109375 L 222.855469
58.546875 L 226.160156 57.910156 L 229.460938 57.269531 L 242.679688
54.707031 L 245.980469 54.066406 L 249.285156 53.425781 L 252.589844
52.789062 L 259.199219 51.507812 L 262.5 50.867188 L 275.71875
48.304688 L 279.023438 47.667969 L 282.324219 47.027344 L 295.542969
44.464844 L 298.84375 43.824219 L 302.148438 43.183594 L 305.453125
42.546875 L 315.367188 40.625 L 318.667969 39.984375 L 328.582031
38.0625 L 331.886719 37.425781 L 335.1875 36.785156 L 348.40625
34.222656 L 351.707031 33.582031 L 355.011719 32.941406 L 358.316406
32.304688 L 368.230469 30.382812 L 371.53125 29.742188 L 381.445312
27.820312 L 384.75 27.183594 L 388.050781 26.542969 L 401.269531
23.980469 L 404.570312 23.339844 L 407.875 22.699219 L 411.179688
22.0625 L 421.09375 20.140625 L 424.394531 19.5 "
transform="matrix(1,0,0,1,-74,-13)"/>
<path style="fill:none;stroke-width:3.441624;stroke-linecap:butt;
stroke-linejoin:miter;stroke:rgb(0%,0%,0%);stroke-opacity:1;stroke-
miterlimit:3.25;" d="M 87.117188 83.515625 L 415.660156 83.515625 "
transform="matrix(1,0,0,1,-74,-13)"/>
<path style="fill:none;stroke-width:0.03;stroke-linecap:square;stroke-
linejoin:miter;stroke:rgb(0%,0%,0%);stroke-opacity:1;stroke-
miterlimit:3.25;" d="M 87.117188 83.515625 Z M 87.117188 83.515625 "
transform="matrix(1,0,0,1,-74,-13)"/>
<path style="fill:none;stroke-width:1;stroke-linecap:butt;stroke-
linejoin:miter;stroke:rgb(0%,0%,0%);stroke-opacity:1;stroke-
miterlimit:3.25;" d="M 94 84.890625 L 94 31.679688 "
transform="matrix(1,0,0,1,-74,-13)"/>
<path style="fill:none;stroke-width:0.03;stroke-linecap:square;stroke-
linejoin:miter;stroke:rgb(0%,0%,0%);stroke-opacity:1;stroke-
miterlimit:3.25;" d="M 94 84.890625 Z M 94 84.890625 "
transform="matrix(1,0,0,1,-74,-13)"/>
<path style="fill-rule:nonzero;fill:rgb(0%,0%,0%);fill-opacity:1;
stroke-width:0.03;stroke-linecap:square;stroke-linejoin:miter;stroke:
rgb(0%,0%,0%);stroke-opacity:1;stroke-miterlimit:3.25;" d="M
89.472656 33.265625 L 89.988281 33.015625 L 91.222656 32.460938 L
91.964844 32.167969 L 92.714844 31.914062 L 93.414062 31.738281 L 94
31.679688 L 94.53125 31.738281 L 95.21875 31.914062 L 95.996094
32.167969 L 96.785156 32.460938 L 98.136719 33.015625 L 98.710938
33.265625 L 94 16.058594 Z M 89.472656 33.265625 "
transform="matrix(1,0,0,1,-74,-13)"/>
And correct smaller deviation from the intent by hand after some experience is accumulated.
Converting SVG to PDf is safe since both standards are compatible. SVG is subset of the HTML5 language specification and therefore on the internet high level most advanced standard. PDF is only supported up to version 1.5 by Mathematica. There is already 1.7 published. The Adobe Systems version PDF 1.7 is the basis for this ISO 32000 edition as the newest valid standard since 2008, so very aged. SVG is too part of XML specification for example used by Word or OpenOffice.
Both pdf and svg can be viewed in the browser.
[](https://i.stack.imgur.com/IuzGE.png)
svg can be imported in many pdf editors as well. Compared to all Rasterizers this remain vector grafics and can be enlarged as the rest of an pdf without pixelation and other image distorsions. This is the official Adobe page for SVG: [enter link description here](https://www.adobe.com/devnet/svg.html). SCG is open source and complete part of Mathematica.
A tip is drag the output of the graphics input into the second field of the [`Export`](https://reference.wolfram.com/language/ref/Export.html) built-in for best results. |
56,783,408 | How to have pass the value of a selected tableView to a public variable that can be accessed by multiple ViewControllers? Currently, in didSelectRowAt, I define the row selected as `portfolio` doing `let portfolio = structure[indexPath.row]` Now how can I save this value to perhaps some sort of variable that makes it avalible to multiple view controller?
I don't just mean pushing the value to whichever view controller is being presented when the cell is pressed, I need it be available to view controller past the .pushViewController.
In the past I tried using userdefaults, but this is not appropriate for values that are constantly changing and are not permanen.
```
import UIKit
class ScheduledCell: UITableViewCell {
@IBOutlet weak var ETALabel: UILabel!
@IBOutlet weak var cellStructure: UIView!
@IBOutlet weak var scheduledLabel: UILabel!
@IBOutlet weak var testingCell: UILabel!
@IBOutlet weak var pickupLabel: UILabel!
@IBOutlet weak var deliveryLabel: UILabel!
@IBOutlet weak var stopLabel: UILabel!
@IBOutlet weak var topBar: UIView!
}
class ToCustomerTableViewController: UITableViewController, UIGestureRecognizerDelegate {
var typeValue = String()
var driverName = UserDefaults.standard.string(forKey: "name")!
var structure = [AlreadyScheduledStructure]()
override func viewDidLoad() {
super.viewDidLoad()
fetchJSON()
//Disable delay in button tap
self.tableView.delaysContentTouches = false
tableView.tableFooterView = UIView()
}
private func fetchJSON() {
guard let url = URL(string: "https://example.com/example/example"),
let value = driverName.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = "driverName=\(value)".data(using: .utf8)
URLSession.shared.dataTask(with: request) { data, _, error in
guard let data = data else { return }
do {
self.structure = try JSONDecoder().decode([AlreadyScheduledStructure].self,from:data)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch {
print(error)
}
}.resume()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return structure.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "scheduledID", for: indexPath) as! ScheduledCell
let portfolio = structure[indexPath.row]
cell.stopLabel.text = "Stop \(portfolio.stop_sequence)"
cell.testingCell.text = portfolio.customer
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let portfolio = structure[indexPath.row]
let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "scheduledDelivery")
print(portfolio.customer)
controller.navigationItem.title = navTitle
navigationController?.pushViewController(controller, animated: true)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200.0
}
}
``` | 2019/06/27 | [
"https://Stackoverflow.com/questions/56783408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can use a function to pass an optional Value inside an `extension`, try the following:
From what I understood you want to pass values from your `viewController` and be able to get it from any other `viewController`..
```
extension UIViewController {
func passData(row: Int?) -> Int? {
var myValue = Int()
if row != nil {
myValue = row!
}
return myValue
}
}
```
in this `function` you can Pass the value you want and also retrieve it.
to pass data into the `function` simply use this :
```
passData(row: indexPath.row)
```
and if you want to retrieve the value of it from another `viewController` use this:
```
let myValue = passData(row: nil)
```
this way you could get the Data you pass from another `viewController`..
if that didn't work for you I'd suggest you use `UserDefaults` ..
I hope this could solve your problem. | You can use NSNotificationCenter and post value after selection and every subscribed controller will received a new value. For more info read this [NSNotificationCenter addObserver in Swift](https://stackoverflow.com/questions/24049020/nsnotificationcenter-addobserver-in-swift) |
292,332 | I was reading a question on Stack Overflow, and noticed that in the right side there was an empty ad, which consisted only of clouds over a blue sky:

It seemed curious to me that there were no info in the ad: no logo, no text, just a sky full of clouds. So I checked the source of the component, and noticed that it was not an image, but a group of DIVs, and the clouds where drawed using dots and CSS styles.

Just by mere curiosity, why is this ad empty, and instead of an image, it is an elaborated composite made of divs and text? | 2015/05/04 | [
"https://meta.stackoverflow.com/questions/292332",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/806975/"
] | While I like @Mitchell Carroll's answer, that is incorrect. The clouds are due to an ad tag being implemented improperly.
The error is fixed, so you will no longer see any [happy clouds](https://www.youtube.com/watch?v=raXanYjTF18). | It's likely the result of someone who is very well versed in HTML and CSS, and also believes that SO deserves to run without ads. Instead of just straight donating to SO, they bought up an ad in order to contribute to SO's development and upkeep, while also preventing an amount of real (possibly invasive and annoying) ads from showing up on people's screens. |
62,071,886 | maybe one of you can help me. I've written a feature in javascript that adds underlining to all "a" selectors. The function is called with the "onclick" attribute. I would like to reverse the effect, i.e. remove the underscore at second click on the same button. The question is how to do it ?
HTML code:
```
<button type="button" class="underlineLinks" id="underlineLinks" onclick="underlineLinks()">Click</button>
```
JS code:
```
function underlineLinks() {
const links = document.querySelectorAll("a");
links.forEach(a => a.style.textDecoration = "underline");
}
``` | 2020/05/28 | [
"https://Stackoverflow.com/questions/62071886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12267943/"
] | You can create a CSS class with the decoration underline
```
.class
{
text-decoration: underline
}
```
and use toggle in the JS.
Toggle will add the class if it isn't applied to your link and remove the class if it is applied to your link
```
function underlineLinks() {
const links = document.querySelectorAll("a");
links.forEach(a => a.classList.toggle("class"));
}
```
<https://jsfiddle.net/u4sxfdy5/> | you could do this
```
function getUnderLineLinksSetter() {
let areLinksUnderlines = false;
return () => {
const links = document.querySelectorAll('a');
areLinksUnderlines = !areLinksUnderlines;
links.forEach(a => {
if (areLinksUnderlines) {
a.style.textDecoration = 'initial';
} else {
a.style.textDecoration = 'underline';
}
});
};
}
```
and then use the following html
```
<button type="button" class="underlineLinks" id="underlineLinks" onclick="getUnderLineLinksSetter()()">Click</button>
```
Its better to add event listeners from code and not using html inline functions by that i mean instead of setting the on click using html, you set it using javascript like this
```
// put this code inside a load event in the page so you make sure the button is in the dom
function getUnderLineLinksSetter() {
let areLinksUnderlines = false;
return () => {
const links = document.querySelectorAll('a');
areLinksUnderlines = !areLinksUnderlines;
links.forEach(a => {
if (areLinksUnderlines) {
a.style.textDecoration = 'initial';
} else {
a.style.textDecoration = 'underline';
}
});
};
}
document.getElementById('underlineLinks').addEventLisetner('click', getUnderLineLinksSetter())
```
And then remove the onclick from html
```
<button type="button" class="underlineLinks" id="underlineLinks">Click</button>
``` |
62,071,886 | maybe one of you can help me. I've written a feature in javascript that adds underlining to all "a" selectors. The function is called with the "onclick" attribute. I would like to reverse the effect, i.e. remove the underscore at second click on the same button. The question is how to do it ?
HTML code:
```
<button type="button" class="underlineLinks" id="underlineLinks" onclick="underlineLinks()">Click</button>
```
JS code:
```
function underlineLinks() {
const links = document.querySelectorAll("a");
links.forEach(a => a.style.textDecoration = "underline");
}
``` | 2020/05/28 | [
"https://Stackoverflow.com/questions/62071886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12267943/"
] | You can create a CSS class with the decoration underline
```
.class
{
text-decoration: underline
}
```
and use toggle in the JS.
Toggle will add the class if it isn't applied to your link and remove the class if it is applied to your link
```
function underlineLinks() {
const links = document.querySelectorAll("a");
links.forEach(a => a.classList.toggle("class"));
}
```
<https://jsfiddle.net/u4sxfdy5/> | ```
function underlineLinks() {
const links = document.querySelectorAll("a");
var toChange = "underline"
if(links[0].style.textDecoration != "underline")) toChange = "none"
links.forEach(a => a.style.textDecoration = toChange);
}
```
Probably there is an easier way but idk, I shoot my shot |
6,160 | *Acabar com o problema* ou *acabar o problema*? Qual está correto? Têm os mesmos significados?
Pelo o que eu percebi, *acabar com o problema* significa ’terminar o problema’. | 2019/08/28 | [
"https://portuguese.stackexchange.com/questions/6160",
"https://portuguese.stackexchange.com",
"https://portuguese.stackexchange.com/users/2747/"
] | *Acabar com qualquer coisa* é por-lhe termo, extingui-la; *acabar alguma coisa* é terminá-la, concluí-la.
A forma correta depende portanto do contexto. Se estou a resolver um problema de matemática, quando o terminar terei *acabado o problema*.
Se o problema é, por exemplo, um cano roto, ao resolver o problema terei *acabado **com** o problema*. | Imagine o seguinte! Há um encanamento quebrado que vaza água constantemente. Para "terminar o problema" você tenta tampar o buraco, com as mãos ou de alguma outra forma. Porém para "acabar com o problema" você apenas tranca o registro. Então, "acabar com o problema" é ir até a fonte de origem do problema e dar um fim a ele. Já "terminar o problema" é como uma solução temporária, não impedindo que aquele problema volte a acontecer. |
287,181 | I have a gigantic list of files on a text files. This list is passed to tar, like this:
cat list.txt | xargs tar rvf archive.tar --ignore-failed-read
The problem is that some files that are on the list don't exist anymore. So tar keeps saying "Cannot stat: No such file or directory...".
I have no problems with that, however when some of these messages appear, tar hungs, and wait some minutes to resume the actions, making the backup very slow.
Any ideas on how I can filter only the existing files to tar?
Regards | 2011/07/05 | [
"https://serverfault.com/questions/287181",
"https://serverfault.com",
"https://serverfault.com/users/48713/"
] | How big is the list and how many files are gone? Can you filter the missing files?
```
% cat list.txt
foo/bar
foo/baz
foo/fred
foo/wilma
betty
% for file in `cat list.txt`; do [ -f $file ] && echo $file; done | xargs tar rvf archive.tar
foo/bar
foo/fred
betty
% tar tvf archive.tar
-rw-r--r-- scott/scott 0 2011-07-05 10:25 foo/bar
-rw-r--r-- scott/scott 0 2011-07-05 10:25 foo/fred
-rw-r--r-- scott/scott 0 2011-07-05 10:25 betty
%
``` | I don't know if it's the best way, but I've found out that using the parameter `-T`, tar will be much happier.
`tar rvf archive.tar --ignore-failed-read -T filelist.txt` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.