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 |
|---|---|---|---|---|---|
1,735 | The bardic lore skill always left me baffled. I never had clear the terms of such skill. A bard can roll a bard lore throw to know some abstruse information. The fact is that the throw is bound to a specific need or question, and it can very well be that the bard knows nothing about one topic, and a lot of a very related topic, as beautifully depicted in [The Gamers 2](http://www.youtube.com/watch?v=90wFS7cDQCg&feature=related&t=8m14s).
What is the real meaning of the bardic lore skill, in game terms ? | 2010/08/29 | [
"https://rpg.stackexchange.com/questions/1735",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/113/"
] | Original celtic bards were actually historians. All of celtic tradition was oral, so someone had to remeber it and pass it on. The poetry and music were only added to make it easier to remember. We can imagine the D&D Bard as a kind of wandering historian-in-training. He already knows some of the songs/stories, but has a long way to go - as he gains experience, he learns more and more of them. But he isn't performing what we would call a scientific reaserch - he is wandering the land, collecting pieces of lore and legend.
So, for example, he may know that a vampire can be killed by putting a stake through his heart, beacause he knows "The Song of Barabarus, the Mighty Vampire Slayer", but he doesn't need to know that the same vampire is weak to light, since it isn't mentioned in this song. He would need to know "The Legend of Saint Carnus and the Dark Beast" - which, while technically covering the same topic, is about a completly different person from completly different land, and thus not a part of "a pack". For someone which aproperiate scholary knowledge, this two facts are tied together as a part of vampire lore. For bards, those are separate things, tied to specific places, clans and stories. | Bardic lore is a real life skill. Heck, a lot of people possess it. It's just having information about something that given your background, learning, or skill set you generally wouldn't be expected to know. Just being well read and having general knowledge of a host of different skills, professions, situations, histories is basically all Bardic lore is. They've read a bunch of books, or talked with a bunch of people, or heard songs from long standing oral traditions talking about places, people or items from bygone ages and by checking for it, they might remember hearing at least a little bit about it, though full knowledge of something pretty rare. |
7,901,373 | Is there a way to tell Python about additional `site-packages` locations without modifying existing scripts?
On my CentOS 5.5 server I have a Python 2.7 installation that is installed in `/opt/python2.7.2` and there is a `site-packages` folder at `/opt/python2.7.2/lib/python2.7/site-packages`.
The reason for this is that I didn't want to disturb the existing Python 2.4 install that shipped with the 5.5 distribution.
However a third party Python application also added a `site-packages` folder at: `/usr/local/lib/python2.7/site-packages` and installed itself at that location.
This is partly my fault because I didn't tweak the `PREFIX` in the application's `Makefile` before installing, however there's not much I can do about it now.
I know that I can do this:
```
import sys; sys.path.insert(0, "/usr/local/lib/python2.7/site-packages")
```
However it would involve me tracking down every script and adding the above which is not ideal should there be updates in the future.
To get around this I created a symbolic link in `/opt/python2.7.2/lib/python2.7/site-packages` to the location of this third party application:
```
ln -sf /usr/local/lib/python2.7/site-packages/theapp /opt/python2.7.2/lib/python2.7/site-packages/theapp
```
This appears to work fine but I'm wondering if there's a better way? | 2011/10/26 | [
"https://Stackoverflow.com/questions/7901373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419/"
] | You can use the [Site-specific configuration hook](http://docs.python.org/library/site.html).
>
> "A path configuration file is a file whose name has the form `name.pth` and exists in one of the four directories mentioned above; its contents are additional items (one per line) to be added to `sys.path`."
>
>
>
In your case, you should be able to achieve what you want by simply dropping in a `.pth` file containing the path of the directory to include:
```
[root@home]$ echo "/usr/local/lib/python2.7/site-packages/" > /opt/python2.7.2/lib/python2.7/site-packages/usrlocal.pth
``` | You could replace the python executable with a wrapper script which appends your added installpath to PYTHONPATH. But this is a kludge.
But I'd try to fix the installation of the add-on so that it properly goes into the site-packages dir. |
73,400,532 | I have two screens. **Approve List** and **Approve Detail**. When data approved in Approve Detail, page navigate to Approve List. Then approved data should disapear from FLatList. How to remove FlatList item when data approved? or how to re render FlatList when data change? Here is my code:
Approve List:
```
const Approve = ({ navigation }) => {
const [rekomendasi, setRekomendasi] = useState({})
// other code
const getRekomendasi = async (token, bagian) => {
try {
const response = await sippApi.get(`/penjaminan?bagian=${bagian}`, {
headers: {
Auth: token
}
});
setRekomendasi(response.data.data)
console.log(rekomendasi)
} catch (error) {
console.log(error)
}
}
useEffect(() => {
getToken();
getUserData()
getRekomendasi(token, userData.bagian);
}, [setToken, setUserData, rekomendasi]); // if I pass rekomendasi here, make infinite loop on api request
return (
<FlatList
onRefresh={() => onRefresh()}
refreshing={isFetching}
removeClippedSubviews
style={{ marginTop: 2 }}
data={rekomendasi}
keyExtractor={rekom => rekom.penjaminan.nomor_rekomendasi}
renderItem={({ item }) => {
return (
<TouchableOpacity onPress={() => navigation.navigate("ApproveDetail", { id: item.penjaminan.nomor_rekomendasi, bagian: userData.bagian })}>
<ApproveList
plafond={item.value}
kantor={item.nama_kantor}
nomor_rekomendasi={item.nomor_rekomendasi}
produk={item.skim}
/>
</TouchableOpacity>
)
}}
showsHorizontalScrollIndicator={false}
/>
)
}
```
If I pass value on second argument on UseEffect, it cause infinite loop on API request. If not, my FlatList cant re render when data change. What should I do?
Thanks for help | 2022/08/18 | [
"https://Stackoverflow.com/questions/73400532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3169003/"
] | Using `sed`, this will change all null values to `BLANK` and strings with consecutive spaces between the values to change the space to `_` after the delimiter `:`
```
$ sed -E ':a;s/^([^ ]*: +)([^ ]*) +/\1\2_/;ta;s/: +?$/: BLANK/' input_file
servername: tesing1001
os: Unix
bu: BLANK
aid: 132
location: anywhere
environment: dev-stg
application: ABCD_testing_space
city: kk
``` | Maybe this will help you.
I replace all spaces with an \_
After that i replace all ":\_" with ": "
```
foo=${str// /_}
echo $foo
echo ${foo/:_/: }
``` |
73,400,532 | I have two screens. **Approve List** and **Approve Detail**. When data approved in Approve Detail, page navigate to Approve List. Then approved data should disapear from FLatList. How to remove FlatList item when data approved? or how to re render FlatList when data change? Here is my code:
Approve List:
```
const Approve = ({ navigation }) => {
const [rekomendasi, setRekomendasi] = useState({})
// other code
const getRekomendasi = async (token, bagian) => {
try {
const response = await sippApi.get(`/penjaminan?bagian=${bagian}`, {
headers: {
Auth: token
}
});
setRekomendasi(response.data.data)
console.log(rekomendasi)
} catch (error) {
console.log(error)
}
}
useEffect(() => {
getToken();
getUserData()
getRekomendasi(token, userData.bagian);
}, [setToken, setUserData, rekomendasi]); // if I pass rekomendasi here, make infinite loop on api request
return (
<FlatList
onRefresh={() => onRefresh()}
refreshing={isFetching}
removeClippedSubviews
style={{ marginTop: 2 }}
data={rekomendasi}
keyExtractor={rekom => rekom.penjaminan.nomor_rekomendasi}
renderItem={({ item }) => {
return (
<TouchableOpacity onPress={() => navigation.navigate("ApproveDetail", { id: item.penjaminan.nomor_rekomendasi, bagian: userData.bagian })}>
<ApproveList
plafond={item.value}
kantor={item.nama_kantor}
nomor_rekomendasi={item.nomor_rekomendasi}
produk={item.skim}
/>
</TouchableOpacity>
)
}}
showsHorizontalScrollIndicator={false}
/>
)
}
```
If I pass value on second argument on UseEffect, it cause infinite loop on API request. If not, my FlatList cant re render when data change. What should I do?
Thanks for help | 2022/08/18 | [
"https://Stackoverflow.com/questions/73400532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3169003/"
] | Using `sed`, this will change all null values to `BLANK` and strings with consecutive spaces between the values to change the space to `_` after the delimiter `:`
```
$ sed -E ':a;s/^([^ ]*: +)([^ ]*) +/\1\2_/;ta;s/: +?$/: BLANK/' input_file
servername: tesing1001
os: Unix
bu: BLANK
aid: 132
location: anywhere
environment: dev-stg
application: ABCD_testing_space
city: kk
``` | Using awk (gawk in particular):
```
awk -F ': ' '/^application/ { gsub(" ","_",$2) } /^bu/ { gsub("","BLANK",$2)}1' file
Set the field delimiter to ": " and then where the line starts with "application", use awks, gsub function to replace all instances of " " with "_" in the second field. With lines starting with bu, replace "" with "BLANK" in the second field
```
This will output the amendments to the screen, to write the data back to the file, use a temporary file and so:
```
awk -F ': ' '/^application/ { gsub(" ","_",$2) } /^bu/ { gsub("","BLANK",$2)}1' file > file.tmp && cp -f file.tmp file
``` |
73,400,532 | I have two screens. **Approve List** and **Approve Detail**. When data approved in Approve Detail, page navigate to Approve List. Then approved data should disapear from FLatList. How to remove FlatList item when data approved? or how to re render FlatList when data change? Here is my code:
Approve List:
```
const Approve = ({ navigation }) => {
const [rekomendasi, setRekomendasi] = useState({})
// other code
const getRekomendasi = async (token, bagian) => {
try {
const response = await sippApi.get(`/penjaminan?bagian=${bagian}`, {
headers: {
Auth: token
}
});
setRekomendasi(response.data.data)
console.log(rekomendasi)
} catch (error) {
console.log(error)
}
}
useEffect(() => {
getToken();
getUserData()
getRekomendasi(token, userData.bagian);
}, [setToken, setUserData, rekomendasi]); // if I pass rekomendasi here, make infinite loop on api request
return (
<FlatList
onRefresh={() => onRefresh()}
refreshing={isFetching}
removeClippedSubviews
style={{ marginTop: 2 }}
data={rekomendasi}
keyExtractor={rekom => rekom.penjaminan.nomor_rekomendasi}
renderItem={({ item }) => {
return (
<TouchableOpacity onPress={() => navigation.navigate("ApproveDetail", { id: item.penjaminan.nomor_rekomendasi, bagian: userData.bagian })}>
<ApproveList
plafond={item.value}
kantor={item.nama_kantor}
nomor_rekomendasi={item.nomor_rekomendasi}
produk={item.skim}
/>
</TouchableOpacity>
)
}}
showsHorizontalScrollIndicator={false}
/>
)
}
```
If I pass value on second argument on UseEffect, it cause infinite loop on API request. If not, my FlatList cant re render when data change. What should I do?
Thanks for help | 2022/08/18 | [
"https://Stackoverflow.com/questions/73400532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3169003/"
] | Using `sed`, this will change all null values to `BLANK` and strings with consecutive spaces between the values to change the space to `_` after the delimiter `:`
```
$ sed -E ':a;s/^([^ ]*: +)([^ ]*) +/\1\2_/;ta;s/: +?$/: BLANK/' input_file
servername: tesing1001
os: Unix
bu: BLANK
aid: 132
location: anywhere
environment: dev-stg
application: ABCD_testing_space
city: kk
``` | Using **awk** you could set the FS *(Field Separator)* to a colon followed by optional spaces, and the OFS *(Ouput Field Separator)* to `:`
Using a pattern, you could match if the line starts with non whitespace chars followed by `:` and then optional spaces only.
If that is the case, print out the first field with the OFS and "BLANK" and move to the *next* line as there is nothing to substitute on this line.
For all the other lines, replace `" "` with `_`
```
awk '
BEGIN{
FS=":[[:space:]]*";
OFS=": "
}
/^[^[:space:]]*:[[:space:]]*$/{
print $1 OFS "BLANK"
next
}
{
gsub(" ","_", $2)
}1
' file
```
Output
```
servername: tesing1001
os: Unix
bu: BLANK
aid: 132
location: anywhere
environment: dev-stg
application: ABCD_testing_space
city: kk
```
---
With **gnu awk** you might also match the whole line using a pattern and 2 capture groups, and do the replacement based on the value of capture group 2.
```
awk '
match($0, /^([^[:blank:]]+:[[:blank:]]*)(.+)?$/, a) {
if (a[2] != "") {
print a[1] gensub(" ", "_", "g", a[2])
next
}
print a[1] "BLANK"
}
' file
``` |
47,508,179 | When I return base or custom object from `SxcApiController` everything work OK,
but If I try to return:
"`HttpResponseMessage`", Something like:
```
return Request.CreateResponse(HttpStatusCode.BadRequest, new { Message = "ERROR : " + ex.Message } );
```
I get error:
>
> 'System.Net.Http.HttpResponseMessage' is defined in an assembly that
> is not referenced. You must add a reference to assembly
> 'System.Net.Http, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a'.",
>
>
>
How can I fix this? How to add additional reference to api controller?
I already add : "`using System.Net.Http;`" in api controller but this is not the problem...
== Added =============================
I found this code inside 2sxc.csproj file:
```xml
<Reference Include="System.Net.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
<Reference Include="System.Net.Http.Formatting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
```
And there is Version=2.0.0.0
Can this be a problem?
== Complete controller =================================
```
using System;
using System.Net.Http;
using System.Web.Http;
using DotNetNuke.Data;
using DotNetNuke.Web.Api;
using DotNetNuke.Security;
using ToSic.SexyContent.WebApi;
public class InstallController : SxcApiController
{
[HttpGet]
[AllowAnonymous]
//[DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.Host)]
//[ValidateAntiForgeryToken]
public object DbTablesCreate()
{
var result = new { P1 = "test1", P2 = "test2" } ;
try
{
// Some code I want to protect...
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, result);
//return new { Message = "Returned error with status code OK" };
}
return Request.CreateResponse(HttpStatusCode.OK, result);
//return new { Message = "Returned ok with status code OK" };
}
}
```
Complete result : 500 Internal Server Error
>
> { "Message": "2sxc Api Controller Finder: Error while selecting /
> compiling a controller for the request. Pls check the event-log and
> the code. See the inner exception for more details.",
> "ExceptionMessage":
> "c:\websites\dev.lea-d.si\Portals\0\2sxc\nnApp\api\InstallController.cs(23):
> error CS0012: The type 'System.Net.Http.HttpRequestMessage' is defined
> in an assembly that is not referenced. You must add a reference to
> assembly 'System.Net.Http, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a'.", "ExceptionType":
> "System.Web.HttpCompileException", "StackTrace": " at
> System.Web.Compilation.AssemblyBuilder.Compile() at
> System.Web.Compilation.BuildProvidersCompiler.PerformBuild() at
> System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath
> virtualPath) at
> System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath
> virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean
> allowBuildInPrecompile, Boolean throwIfNotFound, Boolean
> ensureIsUpToDate) at
> System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext
> context, VirtualPath virtualPath, Boolean noBuild, Boolean
> allowCrossApp, Boolean allowBuildInPrecompile, Boolean
> throwIfNotFound, Boolean ensureIsUpToDate) at
> System.Web.Compilation.BuildManager.GetVPathBuildResult(HttpContext
> context, VirtualPath virtualPath, Boolean noBuild, Boolean
> allowCrossApp, Boolean allowBuildInPrecompile, Boolean
> ensureIsUpToDate) at
> System.Web.Compilation.BuildManager.GetCompiledAssembly(String
> virtualPath) at
> ToSic.SexyContent.WebApi.AppApiControllerSelector.SelectController(HttpRequestMessage
> request) in
> C:\Projects\2SexyContent\Web\DesktopModules\ToSIC\_SexyContent\Sxc
> WebApi\AppApiControllerSelector.cs:line 77" }
>
>
>
============== Solution1 ================
I copy the
*System.Net.Http.dll*
to Bin folder of site and then also add:
```
using System.Net;
using System.Net.Http;
```
Now stuf work | 2017/11/27 | [
"https://Stackoverflow.com/questions/47508179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6334086/"
] | I copy the file:
System.Net.Http.dll
to Bin folder of the site and then also add:
```
using System.Net;
using System.Net.Http;
```
Now stuff work | As the error message stated, you needed to add the requested `dll` to the site. The framework searches the `bin` directory of the site for the necessary references in order to operate correctly.
Also assuming that the controller is derived from `ApiController` you can try the following using a different syntax
```
[HttpGet]
[AllowAnonymous]
//[DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.Host)]
//[ValidateAntiForgeryToken]
public IHttpActionResult DbTablesCreate() {
var result = new { P1 = "test1", P2 = "test2" } ;
try {
//...code removed for brevity
} catch (Exception ex) {
return Content(HttpStatusCode.BadRequest, result);
}
return OK(result);
}
``` |
63,129,476 | RDBMS: MariaDB 10.1.44
My database structure is as follows :
```
CREATE TABLE product
(
id int primary key auto_increment,
name varchar(255),
is_pack tinyint(1)
);
CREATE TABLE cart
(
id int primary key auto_increment
);
CREATE TABLE cart_item
(
id int primary key auto_increment,
id_cart int not null,
id_product int not null,
quantity int not null default 0
);
CREATE TABLE product_pack
(
id int primary key auto_increment,
id_pack int not null,
id_product int not null,
quantity int not null default 0
);
alter table cart_item
add constraint cart_item_cart_fk
foreign key (id_cart) references cart (id);
alter table cart_item
add constraint cart_item_product_fk
foreign key (id_product) references product (id);
alter table product_pack
add constraint product_pack_pack_fk
foreign key (id_pack) references product (id);
alter table cart_item
add constraint product_pack_product_fk
foreign key (id_product) references product (id);
INSERT INTO product (name, is_pack) VALUES ('Product 1', 0);
INSERT INTO product (name, is_pack) VALUES ('Product 2', 0);
INSERT INTO product (name, is_pack) VALUES ('Product 3', 0);
INSERT INTO product (name, is_pack) VALUES ('Product pack 1', 1);
INSERT INTO cart () VALUES ();
-- My cart contains 1x Product 1, 2x Product 3 and 2x Product pack 1
INSERT INTO cart_item (id_cart, id_product, quantity) VALUES (1, 1, 1);
INSERT INTO cart_item (id_cart, id_product, quantity) VALUES (1, 3, 2);
INSERT INTO cart_item (id_cart, id_product, quantity) VALUES (1, 4, 2);
-- Product pack 1 "contains" 2x Product 1 plus 2x Product 2
INSERT INTO product_pack (id_pack, id_product, quantity) VALUES (4, 1, 2);
INSERT INTO product_pack (id_pack, id_product, quantity) VALUES (4, 2, 2);
```
[DB Fiddle MCRE](https://www.db-fiddle.com/f/tCyeYhK7GgbAnUePs6KUL/0)
---
I have a table `cart_items` which represents an association n..n between `cart` and `products`. Selecting those cart items is trivial, but I face a problem. I implemented product packs, which are "meta-products" not visible by the user and contains some other products, in a defined quantity, and I can't find how to select the sum of the quantities of each non-pack product in my cart.
E.G
I have a pack `Pack 1` that contains 2x `Product 1` and 2x `Product 2` - Let's say I have 1x `Product 1`, 2x `Product 3` and 2x `Pack 1` in my cart. Then I want my query to return :
```
----------------------
product | quantity |
Product 1 | 5 |
Product 2 | 4 |
Product 3 | 2 |
----------------------
```
I tried `JOINING` ON my product pack table as I could :
```
SELECT (CASE WHEN p.is_pack = 0 THEN p.id ELSE pp.id END) as id
, (CASE WHEN p.is_pack = 0 THEN p.name ELSE cp.name END) as name
, (CASE WHEN p.is_pack = 0 THEN ci.quantity ELSE pp.quantity * ci.quantity END) as quantity
FROM cart_item ci
JOIN product p
ON ci.id_product = p.id
LEFT
JOIN product_pack pp
ON pp.id_pack = p.id
LEFT
JOIN product cp
ON cp.id = pp.id_product
```
But of course I can not get one line per product and `SUM` without `GROUPING BY product.id` (can I ?) and I can't achieve this group. I get this error :
`Query Error: Error: ER_WRONG_FIELD_WITH_GROUP: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.p.is_pack' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by` | 2020/07/28 | [
"https://Stackoverflow.com/questions/63129476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10198980/"
] | Hi there its not the fault of the mat table you are making a table out of the same variable and each row has two way binding for the same variable this will result in the each row will have the same value.
In order to achive what you wanted please take a look at Angular Reactive formarrays.
Here is a pretty good tutorialhow to use formarrays
<https://netbasal.com/angular-reactive-forms-the-ultimate-guide-to-formarray-3adbe6b0b61a> | It should be `[(ngModel)]="AppRemarks"` since `name= "AppRemarks"` in your Input field |
63,129,476 | RDBMS: MariaDB 10.1.44
My database structure is as follows :
```
CREATE TABLE product
(
id int primary key auto_increment,
name varchar(255),
is_pack tinyint(1)
);
CREATE TABLE cart
(
id int primary key auto_increment
);
CREATE TABLE cart_item
(
id int primary key auto_increment,
id_cart int not null,
id_product int not null,
quantity int not null default 0
);
CREATE TABLE product_pack
(
id int primary key auto_increment,
id_pack int not null,
id_product int not null,
quantity int not null default 0
);
alter table cart_item
add constraint cart_item_cart_fk
foreign key (id_cart) references cart (id);
alter table cart_item
add constraint cart_item_product_fk
foreign key (id_product) references product (id);
alter table product_pack
add constraint product_pack_pack_fk
foreign key (id_pack) references product (id);
alter table cart_item
add constraint product_pack_product_fk
foreign key (id_product) references product (id);
INSERT INTO product (name, is_pack) VALUES ('Product 1', 0);
INSERT INTO product (name, is_pack) VALUES ('Product 2', 0);
INSERT INTO product (name, is_pack) VALUES ('Product 3', 0);
INSERT INTO product (name, is_pack) VALUES ('Product pack 1', 1);
INSERT INTO cart () VALUES ();
-- My cart contains 1x Product 1, 2x Product 3 and 2x Product pack 1
INSERT INTO cart_item (id_cart, id_product, quantity) VALUES (1, 1, 1);
INSERT INTO cart_item (id_cart, id_product, quantity) VALUES (1, 3, 2);
INSERT INTO cart_item (id_cart, id_product, quantity) VALUES (1, 4, 2);
-- Product pack 1 "contains" 2x Product 1 plus 2x Product 2
INSERT INTO product_pack (id_pack, id_product, quantity) VALUES (4, 1, 2);
INSERT INTO product_pack (id_pack, id_product, quantity) VALUES (4, 2, 2);
```
[DB Fiddle MCRE](https://www.db-fiddle.com/f/tCyeYhK7GgbAnUePs6KUL/0)
---
I have a table `cart_items` which represents an association n..n between `cart` and `products`. Selecting those cart items is trivial, but I face a problem. I implemented product packs, which are "meta-products" not visible by the user and contains some other products, in a defined quantity, and I can't find how to select the sum of the quantities of each non-pack product in my cart.
E.G
I have a pack `Pack 1` that contains 2x `Product 1` and 2x `Product 2` - Let's say I have 1x `Product 1`, 2x `Product 3` and 2x `Pack 1` in my cart. Then I want my query to return :
```
----------------------
product | quantity |
Product 1 | 5 |
Product 2 | 4 |
Product 3 | 2 |
----------------------
```
I tried `JOINING` ON my product pack table as I could :
```
SELECT (CASE WHEN p.is_pack = 0 THEN p.id ELSE pp.id END) as id
, (CASE WHEN p.is_pack = 0 THEN p.name ELSE cp.name END) as name
, (CASE WHEN p.is_pack = 0 THEN ci.quantity ELSE pp.quantity * ci.quantity END) as quantity
FROM cart_item ci
JOIN product p
ON ci.id_product = p.id
LEFT
JOIN product_pack pp
ON pp.id_pack = p.id
LEFT
JOIN product cp
ON cp.id = pp.id_product
```
But of course I can not get one line per product and `SUM` without `GROUPING BY product.id` (can I ?) and I can't achieve this group. I get this error :
`Query Error: Error: ER_WRONG_FIELD_WITH_GROUP: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.p.is_pack' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by` | 2020/07/28 | [
"https://Stackoverflow.com/questions/63129476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10198980/"
] | I ran into this as well! Ended up being the `name` attribute throwing things off. `name` is used to uniquely identify the control, so when you apply the same name to each attribute they all share the same identifier/key and get treated as one input.
This should solve your issue (left some code out for brevity):
```
<ng-container matColumnDef="Remarks">
<mat-header-cell *matHeaderCellDef>scheduled hours</mat-header-cell>
<mat-cell *matCellDef="let element; let i = index;">
<mat-form-field>
<input matInput [(ngModel)]="Remarks" name="AppRemarks{{ i }}">
</mat-form-field>
</mat-cell>
</ng-container>
``` | It should be `[(ngModel)]="AppRemarks"` since `name= "AppRemarks"` in your Input field |
33,333,159 | First of all I want to say that I have a website where I want to change the language without reloading the page. That is why I inserted buttons for EN and DE.
```
<button lang="de" class="btn btn-primary btn-sm language" >DE</button>
<button lang="en" class="btn btn-primary btn-sm language" >EN</button>
```
Furthermore my CSS looks like this:
```
html.en :lang(de) {
display: none;
}
html.de :lang(en) {
display: none;
}
```
And that is my JQuery script:
```
if ($("html").hasClass('de')) {
$('html').addClass('de');
}
else{
$('html').addClass('en');
}
$('.language').click(function(){
($('html').toggleClass('de en'));
});
```
And finally here is my html tag:
```
<html class="">
```
My Problem is that if I change the language on one page it automatically changes back if I click on a link to a new page. I know there is a problem with my JQuery if function. But I really do not know how to solve this.
Maybe with JQuery cookies? | 2015/10/25 | [
"https://Stackoverflow.com/questions/33333159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5460523/"
] | Yes - every page load will result in a new JavaScript scope. If you need to maintain any state between pages, you'll need to use cookies or keep something appended on to the URL between pages. (Even if using server-side components, a client-side identifier is typically required to keep a session ID for the server to relate back to.)
<https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API> may also be of interest. | An easy way you could do this on the client side is by using query strings. You can append a query string to the end of a url like this:
```
?lang=en
```
Then in your javascript you can parse out the query string and handle accordingly. While there are good libraries out there for parsing query strings ([like this](https://github.com/sindresorhus/query-string)), here is a very simple piece of JS that will grab the query string. This ONLY works if there is one query string though. If you plan on using more query string in the future, you will need to implement something better.
```
var language = location.search.replace(/^.*?\=/, '');
``` |
33,333,159 | First of all I want to say that I have a website where I want to change the language without reloading the page. That is why I inserted buttons for EN and DE.
```
<button lang="de" class="btn btn-primary btn-sm language" >DE</button>
<button lang="en" class="btn btn-primary btn-sm language" >EN</button>
```
Furthermore my CSS looks like this:
```
html.en :lang(de) {
display: none;
}
html.de :lang(en) {
display: none;
}
```
And that is my JQuery script:
```
if ($("html").hasClass('de')) {
$('html').addClass('de');
}
else{
$('html').addClass('en');
}
$('.language').click(function(){
($('html').toggleClass('de en'));
});
```
And finally here is my html tag:
```
<html class="">
```
My Problem is that if I change the language on one page it automatically changes back if I click on a link to a new page. I know there is a problem with my JQuery if function. But I really do not know how to solve this.
Maybe with JQuery cookies? | 2015/10/25 | [
"https://Stackoverflow.com/questions/33333159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5460523/"
] | Yes - every page load will result in a new JavaScript scope. If you need to maintain any state between pages, you'll need to use cookies or keep something appended on to the URL between pages. (Even if using server-side components, a client-side identifier is typically required to keep a session ID for the server to relate back to.)
<https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API> may also be of interest. | You can disable the buttons to prevent reload page since you don't need to reload this page
```
$('.language').click(function(e){
($('html').toggleClass('de en'));
e.preventDefault();
});
``` |
33,333,159 | First of all I want to say that I have a website where I want to change the language without reloading the page. That is why I inserted buttons for EN and DE.
```
<button lang="de" class="btn btn-primary btn-sm language" >DE</button>
<button lang="en" class="btn btn-primary btn-sm language" >EN</button>
```
Furthermore my CSS looks like this:
```
html.en :lang(de) {
display: none;
}
html.de :lang(en) {
display: none;
}
```
And that is my JQuery script:
```
if ($("html").hasClass('de')) {
$('html').addClass('de');
}
else{
$('html').addClass('en');
}
$('.language').click(function(){
($('html').toggleClass('de en'));
});
```
And finally here is my html tag:
```
<html class="">
```
My Problem is that if I change the language on one page it automatically changes back if I click on a link to a new page. I know there is a problem with my JQuery if function. But I really do not know how to solve this.
Maybe with JQuery cookies? | 2015/10/25 | [
"https://Stackoverflow.com/questions/33333159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5460523/"
] | To keep trace of the current locale, the best practice is to set it in the url, this approach allows the user to switch lang when he needs!!
If you're not able to keep the lang on the url you may consider the use of WebStorage...
Try something like this:
```js
var I18nService = (function($, storage) {
var STORAGE_KEY = 'MY_SITE_CURRENTLOCALE';
function I18nService() {
$(document).ready(function() {
this.setCurrent(this.current);
});
}
I18nService.prototype.available = ['en', 'de']
I18nService.prototype.current = (function() {
var res = this.available[0];
var previous = this.getStored();
if(previous) {
res = previous;
}
return res;
})();
I18nService.prototype.getStored = function() {
return storage.getItem(STORAGE_KEY);
};
I18nService.prototype.store = function() {
storage.setItem(STORAGE_KEY, this.current);
return this;
};
I18nService.prototype.setCurrent = function(newVal) {
this.current = newVal;
return this.store().updateClasses();
};
I18nService.prototype.getCurrent = function() {
return this.current;
};
I18nService.prototype.updateClasses = function() {
$('html').removeClass(this.available.join(' ')).addClass(this.current);
return this;
};
return new I18nService();
})(jQuery, window.localStorage.bind(window) /* or sessionStorage, dependes on what you need */);
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
``` | An easy way you could do this on the client side is by using query strings. You can append a query string to the end of a url like this:
```
?lang=en
```
Then in your javascript you can parse out the query string and handle accordingly. While there are good libraries out there for parsing query strings ([like this](https://github.com/sindresorhus/query-string)), here is a very simple piece of JS that will grab the query string. This ONLY works if there is one query string though. If you plan on using more query string in the future, you will need to implement something better.
```
var language = location.search.replace(/^.*?\=/, '');
``` |
33,333,159 | First of all I want to say that I have a website where I want to change the language without reloading the page. That is why I inserted buttons for EN and DE.
```
<button lang="de" class="btn btn-primary btn-sm language" >DE</button>
<button lang="en" class="btn btn-primary btn-sm language" >EN</button>
```
Furthermore my CSS looks like this:
```
html.en :lang(de) {
display: none;
}
html.de :lang(en) {
display: none;
}
```
And that is my JQuery script:
```
if ($("html").hasClass('de')) {
$('html').addClass('de');
}
else{
$('html').addClass('en');
}
$('.language').click(function(){
($('html').toggleClass('de en'));
});
```
And finally here is my html tag:
```
<html class="">
```
My Problem is that if I change the language on one page it automatically changes back if I click on a link to a new page. I know there is a problem with my JQuery if function. But I really do not know how to solve this.
Maybe with JQuery cookies? | 2015/10/25 | [
"https://Stackoverflow.com/questions/33333159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5460523/"
] | An easy way you could do this on the client side is by using query strings. You can append a query string to the end of a url like this:
```
?lang=en
```
Then in your javascript you can parse out the query string and handle accordingly. While there are good libraries out there for parsing query strings ([like this](https://github.com/sindresorhus/query-string)), here is a very simple piece of JS that will grab the query string. This ONLY works if there is one query string though. If you plan on using more query string in the future, you will need to implement something better.
```
var language = location.search.replace(/^.*?\=/, '');
``` | You can disable the buttons to prevent reload page since you don't need to reload this page
```
$('.language').click(function(e){
($('html').toggleClass('de en'));
e.preventDefault();
});
``` |
33,333,159 | First of all I want to say that I have a website where I want to change the language without reloading the page. That is why I inserted buttons for EN and DE.
```
<button lang="de" class="btn btn-primary btn-sm language" >DE</button>
<button lang="en" class="btn btn-primary btn-sm language" >EN</button>
```
Furthermore my CSS looks like this:
```
html.en :lang(de) {
display: none;
}
html.de :lang(en) {
display: none;
}
```
And that is my JQuery script:
```
if ($("html").hasClass('de')) {
$('html').addClass('de');
}
else{
$('html').addClass('en');
}
$('.language').click(function(){
($('html').toggleClass('de en'));
});
```
And finally here is my html tag:
```
<html class="">
```
My Problem is that if I change the language on one page it automatically changes back if I click on a link to a new page. I know there is a problem with my JQuery if function. But I really do not know how to solve this.
Maybe with JQuery cookies? | 2015/10/25 | [
"https://Stackoverflow.com/questions/33333159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5460523/"
] | To keep trace of the current locale, the best practice is to set it in the url, this approach allows the user to switch lang when he needs!!
If you're not able to keep the lang on the url you may consider the use of WebStorage...
Try something like this:
```js
var I18nService = (function($, storage) {
var STORAGE_KEY = 'MY_SITE_CURRENTLOCALE';
function I18nService() {
$(document).ready(function() {
this.setCurrent(this.current);
});
}
I18nService.prototype.available = ['en', 'de']
I18nService.prototype.current = (function() {
var res = this.available[0];
var previous = this.getStored();
if(previous) {
res = previous;
}
return res;
})();
I18nService.prototype.getStored = function() {
return storage.getItem(STORAGE_KEY);
};
I18nService.prototype.store = function() {
storage.setItem(STORAGE_KEY, this.current);
return this;
};
I18nService.prototype.setCurrent = function(newVal) {
this.current = newVal;
return this.store().updateClasses();
};
I18nService.prototype.getCurrent = function() {
return this.current;
};
I18nService.prototype.updateClasses = function() {
$('html').removeClass(this.available.join(' ')).addClass(this.current);
return this;
};
return new I18nService();
})(jQuery, window.localStorage.bind(window) /* or sessionStorage, dependes on what you need */);
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
``` | You can disable the buttons to prevent reload page since you don't need to reload this page
```
$('.language').click(function(e){
($('html').toggleClass('de en'));
e.preventDefault();
});
``` |
1,201,467 | To explain a little more, I have a file Sidebar.cs, and I have Sidebar.js, and Sidebar.css.
I would like to be able to make it Sidebar.cs, Sidebar.cs.js, and Sidebar.cs.css, and have the js and css file go "under" (as children of) the Sidebar.cs node in the treeview, just like what happens with .designer files and .aspx.cs files.
Is this possible to accomplish? | 2009/07/29 | [
"https://Stackoverflow.com/questions/1201467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3226/"
] | Open up the project file in a text editor or using the "edit project file" context menu (might be only part of an add-in I have). You can then use the DependentUpon XML tag to get the hierarchy. For example, this is how a Form and it's designer look:
```
<Compile Include="Views\SSWizardForm.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Views\SSWizardForm.designer.cs">
<DependentUpon>SSWizardForm.cs</DependentUpon>
</Compile>
```
Note the "DependentUpon" tag, meaning "make this a child of another file". | I haven't tried this myself, so take this with a pinch of salt, but this is what I infer by looking at projects I have to hand
Open the project file in notepad (or other preferred text editor), and the structure of a project file so it looks like
```
<Compile Include="whatever.cs">
<DependentUpon>whatever.else</DependentUpon>
</Compile>
<None Include="whatever.else" />
```
instead of
```
<Compile Include="whatever.cs" />
```
with as many `DependentUpon` clauses and `None` elements as needed |
128,588 | Whenever I open google voice typing, it plays a rising ding sound, then a falling ding sound when it stops.
This is very annoying to me. I have a rooted stock S5 on Lollipop. I searched for the sound file but couldn't locate it, it may be wrapped up in the apk file.
Is there a way to stop this irritating sound? If I install the Xposed Framework, will that help?
Edit: Someone has suggested turning the media volume down to zero. This will work, but is not appropriate for me, as I am using the language learning app duolingo while I am using voice typing. So I need the app to send out audio via the media channel, simultaneously with using voice typing. Coming at it from another angle, [I have asked if there is an alternative application which meets my requirements.](https://softwarerecs.stackexchange.com/questions/26522/offline-voice-typing-alternative-for-android)
**edit**
**Using app settings 1.15, you can mute voice typing by muting the Google app in Marshmallow (and maybe above). However, voice typing now mutes other audio ( regardless of its configuration on app settings) so I asked a question about it here**
[How do I stop voice typing from muting/pausing other playing media?](https://android.stackexchange.com/questions/193881/how-do-i-stop-voice-typing-from-muting-pausing-other-playing-media) | 2015/11/11 | [
"https://android.stackexchange.com/questions/128588",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/99196/"
] | I have a solution that may be useful ,if not for the OP I hope it will be useful as a reference for shutting the volume of a particular application OFF.
This method will mute all sounds coming from Google App but will not affect the other apps. It works on 4.1 up to Lollipop, but the questioner found that the App Settings Xposed module doesn't work on Marshmallow.
**Requirements :**
* Root access
* Xposed installer [Lollipop/Marshmallow](http://forum.xda-developers.com/showthread.php?t=3034811) / [kitkat and older](http://forum.xda-developers.com/xposed/xposed-installer-versions-changelog-t2714053) / [Stock lollipop Samsung Only](http://forum.xda-developers.com/xposed/unofficial-xposed-samsung-lollipop-t3113463) (!)
* App settings xposed Module get it from [here](http://repo.xposed.info/module/de.robv.android.xposed.mods.appsettings) (install apk on phone )
**Method :**
* make sure app settings is activated in `xposed installer` under "**modules**" reboot after activating for the first time.
* now open App settings and type `Google` in the search field.
* You will see in the list the `Google App` click on it.
* on the Activity Bar you will see a toggle button toggle it `ON`.
* A view with lots of settings will show up ,look at the bottom of the screen just above the permission button there is a check box that say "**Mute audio**" check it.
* now click on the save button in the right side of the activity bar and confirm the pop-up message.
* Now open the voice typing and enjoy the full silence :)
>
> (!) For Samsung devices under Lollipop Follow carefully the thread you must have a deodexed Rom.
>
>
> | Automation is my solution.
There are plenty of automation apps, but I use [MacroDroid](https://play.google.com/store/apps/details?id=com.arlosoft.macrodroid), since it is easy to learn (that's why I use it) and the behaviour can be easily customized to get the result you want. Besides,free version allows you to create up to 5 macros and so for the task at hand, free version suffices. I prefer automation as a first choice when I need to get something running the way I want rather than depend on an app.
MacroDroid uses macros to perform desired actions.
Macro for your requirement would look like this:
(I am **thankful to OP for testing** o on his Lollipop based device and confirming behaviour as expected, since my device runs on KitKat and Google has implemented API level changes differently in Lollipop)
### Main Macro (working as tested by OP)
### Trigger
Application Launched → Google
### Action
Volume Change → Configure
Here you get 7 options which can be chosen singly or in combination on a sliding scale from 0 to 100. Options are-
1. Alarm
2. Music
3. Notifications
4. Ringer
5. System Sounds
6. Voice Call
7. Bluetooth Voice
Choose ((2) Music and (5) System Sounds) and set them to 0 for **Lollipop**
Choose ((3) Notifications and (5) System Sounds) and set them to 0 for **KitKat**
( Reason for different selection is explained in Note below)
You can set the (6) Voice call level as desired ( select by testing voice
typing comfort level)
### Constraints
None
(Macro runs only when constraint is *true*, so here it runs always)
Save the macro and ensure it is enabled before testing
### Optional Macro (Awaiting OP to test)
(In case you need to change volume manually for voice typing, the "ding sound reappears, as reported by OP. This macro is to kill the "ding sound". This macro is not required if you are fine with the voice control level in the main macro and do not need to manually change voice typing volume)
### Trigger
Volume Button Pressed → Volume Up → Update Volume
(Followed by)
Volume Button Pressed → Volume Down → Update Volume
### Action and Constraints
Same as in the main macro
( Triggers work as logical *OR* and the action for muting the "ding sound" is triggered whenever the volume is manually increased or decreased for voice typing )
### Why this should work for everybody
1. My search hasn't shown an app or Xposed module that can do this ( not denying the possibility, though)
2. This macro **doesn't require root** unlike Xposed approach.
3. **Granular control on different Volume settings**. MacroDroid permits you to alter sounds, with a flexibility that is beyond what normally is available in ringer / volume sound control as this example illustrates. My Huawei Honor 6 has only 6 types of volume settings (which is more than some devices offer) but not Bluetooth, which can be controlled through a macro
4. **Customization**. You can set "modes", which are like global variables akin to setting profiles. As an example, you can set this macro to run while at home (by mapping cell towers of your home location) and have the "ding" sound active elsewhere. Possibilities for customization are pretty much as you wish
5. Last but not least, **it is free :-)**
### System Settings
1. Do not Greenify MacroDroid and exclude it from task killers, if you use them.
2. Enable MacroDroid in "Auto Protect"(Huawei phones) or "Stamina Mode" (Sony phones or "Power Nap" (Stamina Mode Xposed module for non Sony devices). Also, if you update to Marshmallow in the future, exclude MacroDroid from Doze. Refer this: [Is there a way to exclude an app from Doze?](https://android.stackexchange.com/questions/129074/is-there-a-way-to-exclude-an-app-from-doze/129075)
These features prevent app(s) to be active when the device is not awake, conserving battery. May not be pertinent to your phone but adding this as a general precaution.
3. Enable MacroDroid in accessibility settings and also allow it as device administrator in security settings.
4. For Lollipop, enable notification access from notification settings
### Note
Google Voice Recognition functionality that creates the "ding" sound was streamed as notification stream in KitKat. In Lollipop this is switched to music stream. Hence, in the macro, settings differ.
**Source**: <https://stackoverflow.com/questions/21701432/continues-speech-recognition-beep-sound-after-google-search-update> |
282,814 | I'm currently working on a science fair project, were I have to power a LED light bulb with potatoes. I can't find any websites that answer my 2 questions. Luckily I was able to find the answers to most of them. So i'll list them below and hopefully you can answer them.
1. How many volts does it take to power a 120 watt LED light.
2. How does a potato conduct electricity. | 2017/01/27 | [
"https://electronics.stackexchange.com/questions/282814",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/137231/"
] | What can you expect from a two potato (in series) battery voltage wise?
[](https://i.stack.imgur.com/1pv44.png)
The voltage depends on how far the metal electrodes are apart in the **electrochemical series**.
By connecting the potatoes **in series** you can increase the available voltage.
A three potato battery using zinc (or galvanised metal) and copper electrodes should easily light up a red LED.
[](https://i.stack.imgur.com/gKrk2.png) | 1. Depends on the LED, some are in the thirties.
2. By sticking two different types of metals into a potato, you are able to use the conductive materials and acids in the potato to create a flow of electrons from one metal to the other.
120w? You'd probably need hundreds of potatoes in order to even get it to dimly light up for a short time, and thousands if you want it to run at full power...
Either way, since potatoes aren't very good batteries, their current output is low enough so that even if the voltage is a bit over the LED'S max, the higher current draw feom the led will cause the voltage to drop until the led is consuming what it needs to consume, unless you have a lot of potatoes, then you might burn it. |
198,480 | I am trying to download the Ricci.m file from [this page](https://sites.math.washington.edu/~lee/Ricci/). The instructions say
>
> You'll need to download the source file Ricci.m and save it in a directory accessible to Mathematica...Once you've successfully transferred all the Ricci files to your system, start up Mathematica and load the Ricci package....
>
>
>
When I'm clicking on the Ricci.m file on the page though, a web page with lots of text opens. I don't quite know how to download/save it on my computer. Also, how do I know which directory is accessible to Mathematica? | 2019/05/16 | [
"https://mathematica.stackexchange.com/questions/198480",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/65635/"
] | >
> Also, how do I know which directory is accessible to Mathematica?
>
>
>
These directories can be listed by evaluating [`$Path`](https://reference.wolfram.com/language/ref/$Path.html).
The standard place to put packages is the directory opened by the command
```
SystemOpen@FileNameJoin[{$UserBaseDirectory, "Applications"}]
```
I suggest you put it there. | You have to use the right mousebutton, then choose save-as.
Then open this file, and evaluate it.
You have then all functions defined in the package available to use. Read the
```
(* comments sections; or text between brackets and asterixes as indicated *)
```
to find out how to use these functions. |
7,499,950 | I need to serialize a Transferable object to I can send it over an object data stream but during runtime I get the error java.io.NotSerializableException & I have no idea whats wrong. How do I fix this?
Here's the part of the code that is causing the error
```
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
System.out.println(contents);
//Initialiaze ObjectStreams
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//write objects
oos.writeObject(contents);
oos.close();
``` | 2011/09/21 | [
"https://Stackoverflow.com/questions/7499950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813852/"
] | It seems that your object have to implements both Transferable and Serializable.
Hope this code helps you
```
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//Initialiaze ObjectStreams
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
clipboard.setContents(new Plop(), null);
final Transferable contents = clipboard.getContents(null);
final Plop transferData = (Plop) contents.getTransferData(new DataFlavor(Plop.class, null));
oos.writeObject(transferData);
oos.close();
```
with a plop like:
```
static class Plop implements Transferable, Serializable{
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[0]; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean isDataFlavorSupported(final DataFlavor flavor) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Object getTransferData(final DataFlavor flavor) throws UnsupportedFlavorException, IOException {
return this;
}
}
``` | Your concrete class must implement the `Serializable` interface to be able to do so. |
7,499,950 | I need to serialize a Transferable object to I can send it over an object data stream but during runtime I get the error java.io.NotSerializableException & I have no idea whats wrong. How do I fix this?
Here's the part of the code that is causing the error
```
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
System.out.println(contents);
//Initialiaze ObjectStreams
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//write objects
oos.writeObject(contents);
oos.close();
``` | 2011/09/21 | [
"https://Stackoverflow.com/questions/7499950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813852/"
] | The vest way around this is to parse each data flavor into a serializable object of it's kind i.e. put string clipboard content into a string object | Your concrete class must implement the `Serializable` interface to be able to do so. |
7,499,950 | I need to serialize a Transferable object to I can send it over an object data stream but during runtime I get the error java.io.NotSerializableException & I have no idea whats wrong. How do I fix this?
Here's the part of the code that is causing the error
```
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
System.out.println(contents);
//Initialiaze ObjectStreams
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//write objects
oos.writeObject(contents);
oos.close();
``` | 2011/09/21 | [
"https://Stackoverflow.com/questions/7499950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813852/"
] | It seems that your object have to implements both Transferable and Serializable.
Hope this code helps you
```
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//Initialiaze ObjectStreams
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
clipboard.setContents(new Plop(), null);
final Transferable contents = clipboard.getContents(null);
final Plop transferData = (Plop) contents.getTransferData(new DataFlavor(Plop.class, null));
oos.writeObject(transferData);
oos.close();
```
with a plop like:
```
static class Plop implements Transferable, Serializable{
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[0]; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean isDataFlavorSupported(final DataFlavor flavor) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Object getTransferData(final DataFlavor flavor) throws UnsupportedFlavorException, IOException {
return this;
}
}
``` | ```
* Thrown when an instance is required to have a Serializable interface.
* The serialization runtime or the class of the instance can throw
* this exception. The argument should be the name of the class.
```
Hmm. Have you added to your object `implements Serializable` ?
UPD.
Also check that all fields are also serializable. If not - mark them as transient. |
7,499,950 | I need to serialize a Transferable object to I can send it over an object data stream but during runtime I get the error java.io.NotSerializableException & I have no idea whats wrong. How do I fix this?
Here's the part of the code that is causing the error
```
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
System.out.println(contents);
//Initialiaze ObjectStreams
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//write objects
oos.writeObject(contents);
oos.close();
``` | 2011/09/21 | [
"https://Stackoverflow.com/questions/7499950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813852/"
] | The vest way around this is to parse each data flavor into a serializable object of it's kind i.e. put string clipboard content into a string object | ```
* Thrown when an instance is required to have a Serializable interface.
* The serialization runtime or the class of the instance can throw
* this exception. The argument should be the name of the class.
```
Hmm. Have you added to your object `implements Serializable` ?
UPD.
Also check that all fields are also serializable. If not - mark them as transient. |
7,499,950 | I need to serialize a Transferable object to I can send it over an object data stream but during runtime I get the error java.io.NotSerializableException & I have no idea whats wrong. How do I fix this?
Here's the part of the code that is causing the error
```
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
System.out.println(contents);
//Initialiaze ObjectStreams
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//write objects
oos.writeObject(contents);
oos.close();
``` | 2011/09/21 | [
"https://Stackoverflow.com/questions/7499950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813852/"
] | The vest way around this is to parse each data flavor into a serializable object of it's kind i.e. put string clipboard content into a string object | It seems that your object have to implements both Transferable and Serializable.
Hope this code helps you
```
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//Initialiaze ObjectStreams
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
clipboard.setContents(new Plop(), null);
final Transferable contents = clipboard.getContents(null);
final Plop transferData = (Plop) contents.getTransferData(new DataFlavor(Plop.class, null));
oos.writeObject(transferData);
oos.close();
```
with a plop like:
```
static class Plop implements Transferable, Serializable{
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[0]; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean isDataFlavorSupported(final DataFlavor flavor) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Object getTransferData(final DataFlavor flavor) throws UnsupportedFlavorException, IOException {
return this;
}
}
``` |
11,338,827 | ```
NodeList nList2 = doc.getElementsByTagName("dep");
Map<String, List<Map<String, String>>> depMap = new HashMap<String, List<Map<String, String>>>();
for (int temp = 0; temp < nList2.getLength(); temp++) {
Element el = (Element)nList2.item(temp);
String type=el.getAttribute("type");
Node nNode = nList2.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
List<Map<String,String>> depList = new ArrayList<Map<String,String>>();
String governor = getTagValue("governor", eElement);
String dependent = getTagValue("dependent", eElement);
Map<String, String> govdepmap = new HashMap<String, String>();
govdepmap.put(governor, dependent);
depList.add(govdepmap);
List<Map<String,String>> flist = new ArrayList<Map<String,String>>();
flist.add(govdepmap);
depMap.put(type, flist);
}
}
```
I wrote this code but the problem is whenever the loop runs it replaces the List which was already stored in depMap. I want that it should append the new Map in the List retrieved from depMap and not replace it. | 2012/07/05 | [
"https://Stackoverflow.com/questions/11338827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1468694/"
] | so instead of creating new list in each iteration you need to get the list from map and `add()` items to that list
Change
```
List<Map<String,String>> flist = new ArrayList<Map<String,String>>();
```
to
```
List<Map<String,String>> flist = depMap.get(type);
if(flist == null){
List<Map<String,String>> flist = new ArrayList<Map<String,String>>();
}
``` | Move the initialization of `flist`, `govdepmap` and `depList` outside the for-loop. |
11,338,827 | ```
NodeList nList2 = doc.getElementsByTagName("dep");
Map<String, List<Map<String, String>>> depMap = new HashMap<String, List<Map<String, String>>>();
for (int temp = 0; temp < nList2.getLength(); temp++) {
Element el = (Element)nList2.item(temp);
String type=el.getAttribute("type");
Node nNode = nList2.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
List<Map<String,String>> depList = new ArrayList<Map<String,String>>();
String governor = getTagValue("governor", eElement);
String dependent = getTagValue("dependent", eElement);
Map<String, String> govdepmap = new HashMap<String, String>();
govdepmap.put(governor, dependent);
depList.add(govdepmap);
List<Map<String,String>> flist = new ArrayList<Map<String,String>>();
flist.add(govdepmap);
depMap.put(type, flist);
}
}
```
I wrote this code but the problem is whenever the loop runs it replaces the List which was already stored in depMap. I want that it should append the new Map in the List retrieved from depMap and not replace it. | 2012/07/05 | [
"https://Stackoverflow.com/questions/11338827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1468694/"
] | so instead of creating new list in each iteration you need to get the list from map and `add()` items to that list
Change
```
List<Map<String,String>> flist = new ArrayList<Map<String,String>>();
```
to
```
List<Map<String,String>> flist = depMap.get(type);
if(flist == null){
List<Map<String,String>> flist = new ArrayList<Map<String,String>>();
}
``` | Just change your code to following code.
```
NodeList nList2 = doc.getElementsByTagName("dep");
Map<String, List<Map<String, String>>> depMap = new HashMap<String, List<Map<String, String>>>();
List<Map<String,String>> flist = null;
for (int temp = 0; temp < nList2.getLength(); temp++) {
Element el = (Element)nList2.item(temp);
String type=el.getAttribute("type");
Node nNode = nList2.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
List<Map<String,String>> depList = new ArrayList<Map<String,String>>();
String governor = getTagValue("governor", eElement);
String dependent = getTagValue("dependent", eElement);
Map<String, String> govdepmap = new HashMap<String, String>();
govdepmap.put(governor, dependent);
depList.add(govdepmap);
if(flist == null){
flist = new ArrayList<Map<String,String>>();
}
flist.add(govdepmap);
depMap.put(type, depList);
}
}
``` |
69,601,473 | I'm having trouble doing my code since I'm learning from scratch I don't have any idea how I'm going to print out a reversed input from my array.
This is what I have so far:
```
import java.util.Scanner;
public class ReverseList {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] array = new int[10];
int num = 0;
int count = 0;
int total = 1;
loop:
for (count = 0; count <= 10; count++) {
System.out.print("Enter a number (999 to quit): ");
num = scan.nextInt();
if (num == 999) {
break loop;
}
if (count == 9) {
break loop;
}
array[count] = num;
total = count+1;
}
System.out.print("\n The list reversed is:" );
//List Reversed
}
}
```
And the application output should look similar to:
```
Enter a number (999 to quit): 19 <enter>
Enter a number (999 to quit): 44 <enter>
Enter a number (999 to quit): 25 <enter>
Enter a number (999 to quit): 16 <enter>
Enter a number (999 to quit): 999 <enter>
The list reversed is: 16 25 44 19
``` | 2021/10/17 | [
"https://Stackoverflow.com/questions/69601473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17165770/"
] | Dynamic variable name is not recommended, especially in this situation because you are directly taking the user input. But if you really want to implement it, `globals()` is one option:
```py
x = '123'
y = '456'
which = input('What do you want to see?: ') # x
print(globals()[which]) # 123
```
A better and more secure approach would be to use a dict:
```py
user_vars = {'x': '123', 'y': '456'}
which = input('What do you want to see?: ') # x
print(user_vars[which]) # 123
``` | `input()` can be used to fetch input from the command line.
```py
name = input("Your Name: ")
print("Hello there, " + name + "!")
``` |
69,601,473 | I'm having trouble doing my code since I'm learning from scratch I don't have any idea how I'm going to print out a reversed input from my array.
This is what I have so far:
```
import java.util.Scanner;
public class ReverseList {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] array = new int[10];
int num = 0;
int count = 0;
int total = 1;
loop:
for (count = 0; count <= 10; count++) {
System.out.print("Enter a number (999 to quit): ");
num = scan.nextInt();
if (num == 999) {
break loop;
}
if (count == 9) {
break loop;
}
array[count] = num;
total = count+1;
}
System.out.print("\n The list reversed is:" );
//List Reversed
}
}
```
And the application output should look similar to:
```
Enter a number (999 to quit): 19 <enter>
Enter a number (999 to quit): 44 <enter>
Enter a number (999 to quit): 25 <enter>
Enter a number (999 to quit): 16 <enter>
Enter a number (999 to quit): 999 <enter>
The list reversed is: 16 25 44 19
``` | 2021/10/17 | [
"https://Stackoverflow.com/questions/69601473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17165770/"
] | `input()` can be used to fetch input from the command line.
```py
name = input("Your Name: ")
print("Hello there, " + name + "!")
``` | You can make use of the dictionary in python as follows:
```
user_options = {'x': '123', 'y': '456', 'z': '789'}
entered_value = input('Please enter an input?: ') # could be x, y or z depending upon the dictionary
print(user_options[entered_value])
```
This should give you the number depending on if x,y, or z is entered |
69,601,473 | I'm having trouble doing my code since I'm learning from scratch I don't have any idea how I'm going to print out a reversed input from my array.
This is what I have so far:
```
import java.util.Scanner;
public class ReverseList {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] array = new int[10];
int num = 0;
int count = 0;
int total = 1;
loop:
for (count = 0; count <= 10; count++) {
System.out.print("Enter a number (999 to quit): ");
num = scan.nextInt();
if (num == 999) {
break loop;
}
if (count == 9) {
break loop;
}
array[count] = num;
total = count+1;
}
System.out.print("\n The list reversed is:" );
//List Reversed
}
}
```
And the application output should look similar to:
```
Enter a number (999 to quit): 19 <enter>
Enter a number (999 to quit): 44 <enter>
Enter a number (999 to quit): 25 <enter>
Enter a number (999 to quit): 16 <enter>
Enter a number (999 to quit): 999 <enter>
The list reversed is: 16 25 44 19
``` | 2021/10/17 | [
"https://Stackoverflow.com/questions/69601473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17165770/"
] | `input()` can be used to fetch input from the command line.
```py
name = input("Your Name: ")
print("Hello there, " + name + "!")
``` | You can also use `eval()`,
The `eval()` method parses the expression passed to this method and runs python expression (code) within the program.
```
x = '123'
try:
print(eval(input()))
except NameError:
print("Invalid variable name")
``` |
69,601,473 | I'm having trouble doing my code since I'm learning from scratch I don't have any idea how I'm going to print out a reversed input from my array.
This is what I have so far:
```
import java.util.Scanner;
public class ReverseList {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] array = new int[10];
int num = 0;
int count = 0;
int total = 1;
loop:
for (count = 0; count <= 10; count++) {
System.out.print("Enter a number (999 to quit): ");
num = scan.nextInt();
if (num == 999) {
break loop;
}
if (count == 9) {
break loop;
}
array[count] = num;
total = count+1;
}
System.out.print("\n The list reversed is:" );
//List Reversed
}
}
```
And the application output should look similar to:
```
Enter a number (999 to quit): 19 <enter>
Enter a number (999 to quit): 44 <enter>
Enter a number (999 to quit): 25 <enter>
Enter a number (999 to quit): 16 <enter>
Enter a number (999 to quit): 999 <enter>
The list reversed is: 16 25 44 19
``` | 2021/10/17 | [
"https://Stackoverflow.com/questions/69601473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17165770/"
] | Dynamic variable name is not recommended, especially in this situation because you are directly taking the user input. But if you really want to implement it, `globals()` is one option:
```py
x = '123'
y = '456'
which = input('What do you want to see?: ') # x
print(globals()[which]) # 123
```
A better and more secure approach would be to use a dict:
```py
user_vars = {'x': '123', 'y': '456'}
which = input('What do you want to see?: ') # x
print(user_vars[which]) # 123
``` | You can make use of the dictionary in python as follows:
```
user_options = {'x': '123', 'y': '456', 'z': '789'}
entered_value = input('Please enter an input?: ') # could be x, y or z depending upon the dictionary
print(user_options[entered_value])
```
This should give you the number depending on if x,y, or z is entered |
69,601,473 | I'm having trouble doing my code since I'm learning from scratch I don't have any idea how I'm going to print out a reversed input from my array.
This is what I have so far:
```
import java.util.Scanner;
public class ReverseList {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] array = new int[10];
int num = 0;
int count = 0;
int total = 1;
loop:
for (count = 0; count <= 10; count++) {
System.out.print("Enter a number (999 to quit): ");
num = scan.nextInt();
if (num == 999) {
break loop;
}
if (count == 9) {
break loop;
}
array[count] = num;
total = count+1;
}
System.out.print("\n The list reversed is:" );
//List Reversed
}
}
```
And the application output should look similar to:
```
Enter a number (999 to quit): 19 <enter>
Enter a number (999 to quit): 44 <enter>
Enter a number (999 to quit): 25 <enter>
Enter a number (999 to quit): 16 <enter>
Enter a number (999 to quit): 999 <enter>
The list reversed is: 16 25 44 19
``` | 2021/10/17 | [
"https://Stackoverflow.com/questions/69601473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17165770/"
] | Dynamic variable name is not recommended, especially in this situation because you are directly taking the user input. But if you really want to implement it, `globals()` is one option:
```py
x = '123'
y = '456'
which = input('What do you want to see?: ') # x
print(globals()[which]) # 123
```
A better and more secure approach would be to use a dict:
```py
user_vars = {'x': '123', 'y': '456'}
which = input('What do you want to see?: ') # x
print(user_vars[which]) # 123
``` | You can also use `eval()`,
The `eval()` method parses the expression passed to this method and runs python expression (code) within the program.
```
x = '123'
try:
print(eval(input()))
except NameError:
print("Invalid variable name")
``` |
3,369,802 | I would like to ask if someone could help me with the following equation.
\begin{equation}
x^4+ax^3+(a+b)x^2+2bx+b=0
\end{equation}
Could you first solve in general then $a=11$ and $b=28$.
I get it to this form but I stuck.
\begin{equation}
1+a\left(\frac{1}{x}+\frac{1}{x^2}\right)+b\left(\frac{1}{x^2}+\frac{1}{x^3}+\frac{1}{x^3}+\frac{1}{x^4}\right) = 0
\end{equation}
Thank you in advance. | 2019/09/25 | [
"https://math.stackexchange.com/questions/3369802",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | The polynomial equation for $(a, b)=(11,28)$ is given by
$$
x^4+11x^3+39x^2+56x+28=(x^2 + 7x + 7)(x + 2)^2=0.
$$
"How do we come up wit this layout"? By the rational root test, we find the factor $x-2$ twice, and dividing gives the factor $x^2+7x+7$. Hence the roots are $x=-2,-2,\frac{\sqrt{21}-7}{2},\frac{-\sqrt{21}-7}{2}$.
In general, the polynomial will not have any integral roots. A good example is the case $(a, b)=(1,1)$, where the polynomial
$$
x^4+x^3+2x^2+2x+1
$$
is irreducible over $\Bbb Q$. It has no real root at all. | You are almost there !
$$1+a\left(\frac{1}{x}+\frac{1}{x^2}\right)+b\left(\frac{1}{x^2}+\frac{1}{x^3}+\frac{1}{x^3}+\frac{1}{x^4}\right) = 0$$
$$1+a\left(\frac{x+1}{x^2}\right)+b\left(\frac{x+1}{x^3}+\frac{x+1}{x^4}\right) = 0$$
$$1+a\left(\frac{x+1}{x^2}\right)+b\left(\frac{x+1}{x^2}\right)^2 = 0$$ |
12,212,139 | I have to implement java based call routing engine which route calls based on the phone number prefix to the appropriate gateway.
Here my table (postgres) containing the prefixes:
```
CREATE TABLE call_routing (
prefix character varying(20) PRIMARY KEY NOT NULL,
carrier character varying(50) NOT NULL,
dialstring character varying(50) NOT NULL
)
```
Some sample data:
```
INSERT INTO call_routing values ('02','1','/sofia/gateway/gw1');
INSERT INTO call_routing values ('0221','1','/sofia/gateway/gw2');
INSERT INTO call_routing values ('0228','1','/sofia/gateway/gw3');
```
For example phone number 0221123456789 should be routed to gateway "/sofia/gateway/gw2", phone number 0211123456789 should be routed to "/sofia/gateway/gw1", etc.
Questions:
1. What will be the fastest approach with java / jdbc to query the best matching prefix.
2. Is it a better approach to read the table on application startup into java objects and do everything in java without db access on each call? | 2012/08/31 | [
"https://Stackoverflow.com/questions/12212139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905640/"
] | I'd personally cache the table, but you could get the best matching prefix by ordering by length (`number` is what you're searching for):
```
SELECT dialstring FROM call_routing WHERE strpos(number, prefix) = 1 ORDER BY length(prefix) DESC LIMIT 1;
``` | I am wondering about this. It seems like the biggest problem is the fact that you have catchalls (gw1 in your example).
```
SELECT dialstring from call_routing where number like prefix || '%'
ORDER BY length(prefix) DESC
LIMIT 1
```
Indexing this will be hard, but I guess the first question is, how many call prefixes are you tracking? |
12,212,139 | I have to implement java based call routing engine which route calls based on the phone number prefix to the appropriate gateway.
Here my table (postgres) containing the prefixes:
```
CREATE TABLE call_routing (
prefix character varying(20) PRIMARY KEY NOT NULL,
carrier character varying(50) NOT NULL,
dialstring character varying(50) NOT NULL
)
```
Some sample data:
```
INSERT INTO call_routing values ('02','1','/sofia/gateway/gw1');
INSERT INTO call_routing values ('0221','1','/sofia/gateway/gw2');
INSERT INTO call_routing values ('0228','1','/sofia/gateway/gw3');
```
For example phone number 0221123456789 should be routed to gateway "/sofia/gateway/gw2", phone number 0211123456789 should be routed to "/sofia/gateway/gw1", etc.
Questions:
1. What will be the fastest approach with java / jdbc to query the best matching prefix.
2. Is it a better approach to read the table on application startup into java objects and do everything in java without db access on each call? | 2012/08/31 | [
"https://Stackoverflow.com/questions/12212139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905640/"
] | **Get a better indexing**
By ordering directly on prefix, not length(prefix):
```
SELECT dialstring FROM call_routing
WHERE number like prefix || '%'
ORDER BY prefix DESC
LIMIT 1
```
Why?
Because the selected rows for a number `abcdef` will be prefixes. So will be numbers like:
a
ab
abc
abcd
So if you order them alphabetically it's enough to get a list from longest to shortest, and that's what you want.
Also you can get a stronger filter using:
`prefix between 'a' and 'abcde'`. All your prefixes will be alphabetically `>=` the shortest prefix and alphabetically `<=` the longest one.
So it could be expressed as:
```
SELECT dialstring FROM call_routing WHERE
prefix between substr(number, 1, 1) and number -- range filter (use index)
AND number like prefix || '%' -- only relevant data (normal filter)
ORDER BY prefix DESC -- index will work
LIMIT 1
```
And of course the index will be on column prefix.
**Cache all?**
Yes, please. :)
How many items do you have? If it's not a huge list, load it in memory.
Then you can have a TreeMap (if you want order by prefix) or a HashMap (if you prefer to find the longest prefix first and keep trying with one char less each time). Which one will be better? Depends on the number of prefixes that are in the range `a >> abcde` and don't match the `like` condition (`abbde` by example).
**If there are no a lot of entries**
You could use an array, sorted by prefix desc:
```
be
b
abcde
abbbc
abd
ab
```
For finding the good prefix do an `Arrays.binarySearch(T[], T key, Comparator<T>)` to find if your phone is in there (`abcde`). If it is... ok. If it's not you move forward until:
```
- you find a prefix (OK, this is the winner)
- it doesn't start with the same char (there are no prefix)
```
This way you are traversing the range `abcde >> a` and finding the first prefix (it is, the longest possible).
**The good one**
Is making a T-R-E-E (I'm not sure about the name). Make a tree where each node holds only a letter (number in your case).
```
0 // represents 0
->
2 // represents 02
-> 1 // represents 021
-> 3 // represents 023
->
4 // represents 04
```
So when you look for you longest prefix you try to get as deep as possible in your tree:
```
Node n = root;
for (char c: number) {
if ((child = n.hasChild(c)) != null)
{
prefix += c;
n = child;
}
else
break;
}
```
You just need a to create a
```
class Node
{
int digit;
Map<Integer, Node> childs = new HashMap<Integer, Node>(); // or a 10 bucket array :)
YourInfo info;
}
```
And for creating the structure:
```
findOrCreateNode(prefix).setInfo(info);
```
where findOrCreateNode is the same as before but when it doesn't found the node... creates it (`n.put(c, new Node(c))`). | I'd personally cache the table, but you could get the best matching prefix by ordering by length (`number` is what you're searching for):
```
SELECT dialstring FROM call_routing WHERE strpos(number, prefix) = 1 ORDER BY length(prefix) DESC LIMIT 1;
``` |
12,212,139 | I have to implement java based call routing engine which route calls based on the phone number prefix to the appropriate gateway.
Here my table (postgres) containing the prefixes:
```
CREATE TABLE call_routing (
prefix character varying(20) PRIMARY KEY NOT NULL,
carrier character varying(50) NOT NULL,
dialstring character varying(50) NOT NULL
)
```
Some sample data:
```
INSERT INTO call_routing values ('02','1','/sofia/gateway/gw1');
INSERT INTO call_routing values ('0221','1','/sofia/gateway/gw2');
INSERT INTO call_routing values ('0228','1','/sofia/gateway/gw3');
```
For example phone number 0221123456789 should be routed to gateway "/sofia/gateway/gw2", phone number 0211123456789 should be routed to "/sofia/gateway/gw1", etc.
Questions:
1. What will be the fastest approach with java / jdbc to query the best matching prefix.
2. Is it a better approach to read the table on application startup into java objects and do everything in java without db access on each call? | 2012/08/31 | [
"https://Stackoverflow.com/questions/12212139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905640/"
] | I'd personally cache the table, but you could get the best matching prefix by ordering by length (`number` is what you're searching for):
```
SELECT dialstring FROM call_routing WHERE strpos(number, prefix) = 1 ORDER BY length(prefix) DESC LIMIT 1;
``` | You may also look at this PostgreSQL module on github that is specifically meant to provide fast prefix matching for phone numbers:
<https://github.com/dimitri/prefix> |
12,212,139 | I have to implement java based call routing engine which route calls based on the phone number prefix to the appropriate gateway.
Here my table (postgres) containing the prefixes:
```
CREATE TABLE call_routing (
prefix character varying(20) PRIMARY KEY NOT NULL,
carrier character varying(50) NOT NULL,
dialstring character varying(50) NOT NULL
)
```
Some sample data:
```
INSERT INTO call_routing values ('02','1','/sofia/gateway/gw1');
INSERT INTO call_routing values ('0221','1','/sofia/gateway/gw2');
INSERT INTO call_routing values ('0228','1','/sofia/gateway/gw3');
```
For example phone number 0221123456789 should be routed to gateway "/sofia/gateway/gw2", phone number 0211123456789 should be routed to "/sofia/gateway/gw1", etc.
Questions:
1. What will be the fastest approach with java / jdbc to query the best matching prefix.
2. Is it a better approach to read the table on application startup into java objects and do everything in java without db access on each call? | 2012/08/31 | [
"https://Stackoverflow.com/questions/12212139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905640/"
] | **Get a better indexing**
By ordering directly on prefix, not length(prefix):
```
SELECT dialstring FROM call_routing
WHERE number like prefix || '%'
ORDER BY prefix DESC
LIMIT 1
```
Why?
Because the selected rows for a number `abcdef` will be prefixes. So will be numbers like:
a
ab
abc
abcd
So if you order them alphabetically it's enough to get a list from longest to shortest, and that's what you want.
Also you can get a stronger filter using:
`prefix between 'a' and 'abcde'`. All your prefixes will be alphabetically `>=` the shortest prefix and alphabetically `<=` the longest one.
So it could be expressed as:
```
SELECT dialstring FROM call_routing WHERE
prefix between substr(number, 1, 1) and number -- range filter (use index)
AND number like prefix || '%' -- only relevant data (normal filter)
ORDER BY prefix DESC -- index will work
LIMIT 1
```
And of course the index will be on column prefix.
**Cache all?**
Yes, please. :)
How many items do you have? If it's not a huge list, load it in memory.
Then you can have a TreeMap (if you want order by prefix) or a HashMap (if you prefer to find the longest prefix first and keep trying with one char less each time). Which one will be better? Depends on the number of prefixes that are in the range `a >> abcde` and don't match the `like` condition (`abbde` by example).
**If there are no a lot of entries**
You could use an array, sorted by prefix desc:
```
be
b
abcde
abbbc
abd
ab
```
For finding the good prefix do an `Arrays.binarySearch(T[], T key, Comparator<T>)` to find if your phone is in there (`abcde`). If it is... ok. If it's not you move forward until:
```
- you find a prefix (OK, this is the winner)
- it doesn't start with the same char (there are no prefix)
```
This way you are traversing the range `abcde >> a` and finding the first prefix (it is, the longest possible).
**The good one**
Is making a T-R-E-E (I'm not sure about the name). Make a tree where each node holds only a letter (number in your case).
```
0 // represents 0
->
2 // represents 02
-> 1 // represents 021
-> 3 // represents 023
->
4 // represents 04
```
So when you look for you longest prefix you try to get as deep as possible in your tree:
```
Node n = root;
for (char c: number) {
if ((child = n.hasChild(c)) != null)
{
prefix += c;
n = child;
}
else
break;
}
```
You just need a to create a
```
class Node
{
int digit;
Map<Integer, Node> childs = new HashMap<Integer, Node>(); // or a 10 bucket array :)
YourInfo info;
}
```
And for creating the structure:
```
findOrCreateNode(prefix).setInfo(info);
```
where findOrCreateNode is the same as before but when it doesn't found the node... creates it (`n.put(c, new Node(c))`). | I am wondering about this. It seems like the biggest problem is the fact that you have catchalls (gw1 in your example).
```
SELECT dialstring from call_routing where number like prefix || '%'
ORDER BY length(prefix) DESC
LIMIT 1
```
Indexing this will be hard, but I guess the first question is, how many call prefixes are you tracking? |
12,212,139 | I have to implement java based call routing engine which route calls based on the phone number prefix to the appropriate gateway.
Here my table (postgres) containing the prefixes:
```
CREATE TABLE call_routing (
prefix character varying(20) PRIMARY KEY NOT NULL,
carrier character varying(50) NOT NULL,
dialstring character varying(50) NOT NULL
)
```
Some sample data:
```
INSERT INTO call_routing values ('02','1','/sofia/gateway/gw1');
INSERT INTO call_routing values ('0221','1','/sofia/gateway/gw2');
INSERT INTO call_routing values ('0228','1','/sofia/gateway/gw3');
```
For example phone number 0221123456789 should be routed to gateway "/sofia/gateway/gw2", phone number 0211123456789 should be routed to "/sofia/gateway/gw1", etc.
Questions:
1. What will be the fastest approach with java / jdbc to query the best matching prefix.
2. Is it a better approach to read the table on application startup into java objects and do everything in java without db access on each call? | 2012/08/31 | [
"https://Stackoverflow.com/questions/12212139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905640/"
] | **Get a better indexing**
By ordering directly on prefix, not length(prefix):
```
SELECT dialstring FROM call_routing
WHERE number like prefix || '%'
ORDER BY prefix DESC
LIMIT 1
```
Why?
Because the selected rows for a number `abcdef` will be prefixes. So will be numbers like:
a
ab
abc
abcd
So if you order them alphabetically it's enough to get a list from longest to shortest, and that's what you want.
Also you can get a stronger filter using:
`prefix between 'a' and 'abcde'`. All your prefixes will be alphabetically `>=` the shortest prefix and alphabetically `<=` the longest one.
So it could be expressed as:
```
SELECT dialstring FROM call_routing WHERE
prefix between substr(number, 1, 1) and number -- range filter (use index)
AND number like prefix || '%' -- only relevant data (normal filter)
ORDER BY prefix DESC -- index will work
LIMIT 1
```
And of course the index will be on column prefix.
**Cache all?**
Yes, please. :)
How many items do you have? If it's not a huge list, load it in memory.
Then you can have a TreeMap (if you want order by prefix) or a HashMap (if you prefer to find the longest prefix first and keep trying with one char less each time). Which one will be better? Depends on the number of prefixes that are in the range `a >> abcde` and don't match the `like` condition (`abbde` by example).
**If there are no a lot of entries**
You could use an array, sorted by prefix desc:
```
be
b
abcde
abbbc
abd
ab
```
For finding the good prefix do an `Arrays.binarySearch(T[], T key, Comparator<T>)` to find if your phone is in there (`abcde`). If it is... ok. If it's not you move forward until:
```
- you find a prefix (OK, this is the winner)
- it doesn't start with the same char (there are no prefix)
```
This way you are traversing the range `abcde >> a` and finding the first prefix (it is, the longest possible).
**The good one**
Is making a T-R-E-E (I'm not sure about the name). Make a tree where each node holds only a letter (number in your case).
```
0 // represents 0
->
2 // represents 02
-> 1 // represents 021
-> 3 // represents 023
->
4 // represents 04
```
So when you look for you longest prefix you try to get as deep as possible in your tree:
```
Node n = root;
for (char c: number) {
if ((child = n.hasChild(c)) != null)
{
prefix += c;
n = child;
}
else
break;
}
```
You just need a to create a
```
class Node
{
int digit;
Map<Integer, Node> childs = new HashMap<Integer, Node>(); // or a 10 bucket array :)
YourInfo info;
}
```
And for creating the structure:
```
findOrCreateNode(prefix).setInfo(info);
```
where findOrCreateNode is the same as before but when it doesn't found the node... creates it (`n.put(c, new Node(c))`). | You may also look at this PostgreSQL module on github that is specifically meant to provide fast prefix matching for phone numbers:
<https://github.com/dimitri/prefix> |
12,835,677 | Suppose I have a method like this
```
Calculator calc;
public void testMethod(){
-----
----
Calc.add(1,2);
-----
-------
}
```
Now I want print Calculator.add at the end of the function, i.e i want to print the classname.printname at the end of the function. The printing should be generic enough that I can use the same for other methods as well. How to achieve this goal.
Thanks in advance | 2012/10/11 | [
"https://Stackoverflow.com/questions/12835677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650521/"
] | ```
private static final int CLIENT_CODE_STACK_INDEX;
static {
// Finds out the index of "this code" in the returned stack trace - funny but it differs in JDK 1.5 and 1.6
int i = 0;
for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
i++;
if (ste.getClassName().equals(Resource.class.getName())) {
break;
}
}
CLIENT_CODE_STACK_INDEX = i;
}
public static String getCurrentMethodName() {
return Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX].getMethodName();
}
public static String getCallerMethodName() {
return Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX+1].getMethodName();
}
``` | user Calculator.getClass().getName());for finding name of class and Calculator.getMethod();
or use System.out.println( "I was called by " + e.getStackTrace()[1].getClassName() +
"." +
e.getStackTrace()[1].getMethodName() +
"()!" ); |
12,835,677 | Suppose I have a method like this
```
Calculator calc;
public void testMethod(){
-----
----
Calc.add(1,2);
-----
-------
}
```
Now I want print Calculator.add at the end of the function, i.e i want to print the classname.printname at the end of the function. The printing should be generic enough that I can use the same for other methods as well. How to achieve this goal.
Thanks in advance | 2012/10/11 | [
"https://Stackoverflow.com/questions/12835677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650521/"
] | As the very simplest approach, remember you can always call `this.getClass().getName()`:
```
class SimpleCalculator {
public int add(int a, int b) {
System.out.println(this.getClass().getName() +
" - adding " + a + " and " + b);
return a + b;
}
}
```
---
Another common approach is to use a logging library like [Log4J](http://www.tutorialspoint.com/log4j/index.htm).
* [Log4J API](http://logging.apache.org/log4j/1.2/apidocs/)
The class you'd be using is [Logger](http://logging.apache.org/log4j/1.2/apidocs/)
You configure *Log4J* to write to a certain file.
Each class declares a *Logger object* that prints messages to a file.
Each message begins with the name of the class that generated the message.
```
class SimpleCalculator {
Logger calcLogger = Logger.getLogger(SimpleCalculator.class);
public int add(int a, int b) {
calcLogger.debug("add - adding " + a + " and " + b);
return a + b;
}
}
```
... or you could use a method like @urir suggests.
... or you could get crazy and use [AOP](http://en.wikipedia.org/wiki/Aspect-oriented_programming). | user Calculator.getClass().getName());for finding name of class and Calculator.getMethod();
or use System.out.println( "I was called by " + e.getStackTrace()[1].getClassName() +
"." +
e.getStackTrace()[1].getMethodName() +
"()!" ); |
2,917,973 | There is already a [question](https://math.stackexchange.com/questions/724556/abbotts-exercise-6-2-14-convergent-subsequences-for-bounded-sequences-of-fu) regarding exercise 6.2.14 from Stephen Abbott's Understanding Analysis in this site. But it does not answer my question. The Question is posed below, and my question below it.
[](https://i.stack.imgur.com/JT9z2.png)
My question is what exactly the notation $f\_{1,k}$ means ?. From what I understand from the question, $f\_{1,k}$ means a subsequence of $f\_n$ evaluated at the point $x\_1$ i.e. the first index indicated the data point at which the functions are evaluated and second index $k$ simply means that it is a subsequence i.e. $k \subseteq [n]$. So in effect, $f\_{1,k}$ is always evaluated at $x\_1$. Then what exactly $f\_{1,k}(x\_2)$ means ?. | 2018/09/15 | [
"https://math.stackexchange.com/questions/2917973",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/79342/"
] | First to prove that the polynomial is irreducible you can use the Eisenstein criterion for $p=2$.
For the second part you can notice that the roots are $\pm\sqrt{2\pm\sqrt{2}}$. To prove that the $\mathbb{Q}(\alpha)$ is the splitting field you can use the fact that $\pm \frac{\sqrt{2}}{\alpha}$ is a root of the polynomial. Indeed:
$$\left(\pm\frac{\sqrt{2}}{\alpha}\right)^4 - 4\left(\pm\frac{\sqrt{2}}{\alpha}\right)^2 + 2 = \frac{4}{\alpha^4} - \frac{8}{\alpha^2} + 2 = \frac{2}{\alpha^4}(2 - 4\alpha^2 + \alpha^4) = 0$$
Now obviously $\sqrt{2} = \alpha^2 - 2 \in \mathbb{Q}(\alpha)$ and so $\pm\frac{\sqrt{2}}{\alpha} \in \mathbb{Q}(\alpha)$. Thus the roots are $\pm \alpha, \pm \frac{\sqrt{2}}{\alpha}$ (make sure to prove that in fact the 4 distinct roots) and as they are all in $\mathbb{Q}(\alpha)$ we have proven the claim. | As noted by @Stefan4024, the polynomial $f(x) = x^4-4x^2+2$ is irreducible so it is the minimal polynomial of $\alpha$.
Notice that
$$f(x) = (x^4-4x^2+4)- 2 = (x^2-2)^2- 2$$
so the roots are $\sqrt{2+\sqrt2}, -\sqrt{2+\sqrt2}, \sqrt{2-\sqrt2},-\sqrt{2-\sqrt2}$.
Now clearly $-\sqrt{2+\sqrt2} = -\alpha \in \mathbb{Q}(\alpha)$.
Also notice that $\sqrt{2} = \alpha^2-2 \in \mathbb{Q}(\alpha)$ so $$\sqrt{2-\sqrt2} = \frac{\sqrt{2}}{\sqrt{2+\sqrt{2}}} = \frac{\alpha^2-2}{\alpha} \in \mathbb{Q}(\alpha)$$
and then also $-\sqrt{2-\sqrt2} \in \mathbb{Q}(\alpha)$.
We conclude that $\mathbb{Q}(\alpha)$ is the splitting field of $f(x)$ over $\mathbb{Q}$. |
17,709,246 | I have what I hope is a quick question. Haven't found working code for this, and I'm at a little bit of a loss.
I'm working with an old database on SQL Server 2005. It has a dynamic questionnaire (or a thousand, actually... long story), and each question can have the answer stored as either a smallint or as ntext.
The current "answers" table is as follows:
```
AnswerID (PK, int, not null)
EvalID (int, null)
QuestionID (int, null)
NumericAnswer (smallint, null)
TextAnswer (ntext, null)
```
(Yes, I know `ntext` is deprecated. It's an old table.)
This table now has over 300,000 records in it, and is getting really large. So I'm looking for more efficient ways to store the data, and decided to do a little experiment with moving everything to a single sql\_variant field (currently, each row can have data in just one of the two answer columns, not both).
So I made another table, called `AnswersTest`:
```
AnswerID (PK, int, not null)
EvalID (int, null)
QuestionID (int, null)
AnswerGiven (sql_variant, null)
```
... and I'm now trying to get all of the existing data from `Answers` to `AnswersTest`, preferably in their original order... so I'm running an insert query, and it's not working. I've tried both the following:
```
INSERT INTO AnswersTest (EvalID, QuestionID, AnswerGiven)
SELECT EvalID, QuestionID, ISNULL(NumericAnswer,TextAnswer) AS AnswerGiven FROM Answers ORDER BY AnswerID
```
...and
```
INSERT INTO AnswersTest (EvalID, QuestionID, AnswerGiven)
SELECT EvalID, QuestionID, CONVERT(ntext,CASE WHEN NumericAnswer IS NULL THEN TextAnswer ELSE NumericAnswer END) AS AnswerGiven FROM Answers ORDER BY AnswerID
```
In both cases, I get the following:
`Operand type clash: ntext is incompatible with smallint`
I know there must be a simple answer to this... I'm just drawing a blank (it's been a couple of months since I've had to do anything much with TSQL), and I can't find a working answer through searching. Please help. :)
EDIT: Found an answer through trial and error...
The answer may not have been the best one (and it may jump through some unnecessary hoops), but it's a one-time query and it works. :)
```
INSERT INTO AnswersTest (EvalID, QuestionID, AnswerGiven)
SELECT EvalID, QuestionID, CASE WHEN CONVERT(sql_variant,NumericAnswer) IS NULL THEN CONVERT(sql_variant,CONVERT(varchar(8000),TextAnswer)) ELSE CONVERT(sql_variant,NumericAnswer) END AS AnswerGiven FROM Answers ORDER BY AnswerID
```
(Note: I tried `varchar(max)`, but that wasn't allowed. The answers weren't all that long, though... nobody writes essays in these surveys... so I just changed it to `varchar(8000)`, and that worked).
Thanks for reading, and sorry to take up your time! :) | 2013/07/17 | [
"https://Stackoverflow.com/questions/17709246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592948/"
] | Faced Similar Error when I accidentally gave string values to column defined as int.
Please rearrange the values and Table fields in the insert statement
For ex
```
Insert into Table (int,string) values (string,int)
```
will not work and generate the error as stated above. So re arrange it in respective manner.
```
Insert into Table (int,string) values (int,string)
``` | This [link](https://stackoverflow.com/questions/2133946/nvarcharmax-vs-ntext) describes the difference between ntext and nvarchar(max). Is does mention that the ntext is being deprecated. It also talk about the nvarchar(max) being stored within your table making the queries faster. You might want to try using the variation of separate fields of numericanswer and textanswer and see where it gets you from a performance perspective. |
8,696 | Are there word elements, including suffixes, from Old English or other languages that have been linked to their ancient deities and the people that served them, to which these elements are still in use today in the evolution of their language? e.g.:
Jehovah/Jesus Christ a.k.a. Cristos; Christus derived to: Christian; Christianity; Christen; Christendom; Christening; Christhood; Christmas; Christadelphinian & Anti-Christ to name a few. The suffix 'ist' has been applied to many modern English words over the centuries. Have other deities produced this kind of impact upon society?
I hope this clarifies better what I am asking for the sake of the academic community. | 2014/07/31 | [
"https://linguistics.stackexchange.com/questions/8696",
"https://linguistics.stackexchange.com",
"https://linguistics.stackexchange.com/users/3689/"
] | I assumed the question implied words other than the days of the week,
interesting because different but "functionally" related deities have
named them such as Frigg in English for Friday, and Venus in French
for vendredi.
I guess it also excluded the names of planets and other bodies of the
solar system, which are direct reuses. However some of them produced
derived word. For example **martian**, originally intended to denote the
inhabitants of planet Mars, has become common enough to be sometimes
used to just mean extra-terrestrial being.
You have many words, often adjectives, with a meaning related to
characteristics or attributes of the gods, for example:
**venereal**: having to do with physical love, mostly used in medical context.
**aphrodisiac**: substance that increases sexual desire, from the
Greek goddes Aphrodite
**martial**: related to fight and army, from Mars, Roman god of war.
**jovial**: from the Roman god Iupiter (genitive Iovis)
**bacchanal**: a crazed party with drunken revelry
**cereal**: and all derived words, from Ceres, Roman goddess of agriculture.
**volcano**: and all derived words, from Vulcan, the name of a god of fire in Roman mythology.
**vulcanize**: and all derived words, from Vulcan, the name of a god
of fire in Roman mythology
**hermetic**: from Hermes, via the vocabulary of alchemy.
The names of many chemical element s derive from names of ancient
gods:
**Cerium**: named after the asteroid Ceres, named itself after the Roman
goddess;
**Copernicium** named after Copernicus, western god of astronomy;
**Helium**: named after the greek Helios, the sun or sun-god;
**Iridium**: named after the greek Iris, goddess of rainbows;
**Mercury**: named after the Roman god Mercury;
**Neptunium**: named after the planet Neptune, named itself after the Roman god;
**Palladium**: named after the asteroid Ceres,named itself after the Greek
goddess Pallas Athena;
**Plutonium**: Named after Pluto, named itself after the Roman god Pluto;
**Uranium**: after the planet Uranus, itself named for the greek god Ouranos;
**Vanadium**: from Vanadís, one of the names of the Vanr goddess Freyja in
Norse mythology;
and a few others to be found in the [list of chemical element name etymologies](http://en.wikipedia.org/wiki/List_of_chemical_element_name_etymologies)
And to end this list, which is certainly far from complete, one word
referring to two gods, one male and one female: **Hermaphrodite**. | **Days of week** may be a good example of what you are looking for.
In many IE languages, names of those are derived from ancient deities representing individual planets.
>
> *In most Indian languages, the word for **Sunday** is Ravivāra or Adityavāra or its derived forms — vāra meaning day, Aditya and Ravi both being a style (manner of address) for Surya, the chief solar **deity** and one of the Adityas.* — [Wikipedia](http://en.wikipedia.org/wiki/Sunday#Etymology)
>
>
> *In many Languages of India, the word for **Monday** is derived from Sanskrit Somavāra. Soma is another name of the Moon **god** in Hinduism.* — [Wikipedia](http://en.wikipedia.org/wiki/Monday#Etymology)
>
>
> |
60,258,123 | I am trying to integrate payment gateway on my website. There are three courses each having different prices. I am passing the value of the amount and package to `form.php` and i have made the input fields to readonly but the user can still change the amount in inspect element and make it 0 and pass on the value and get the course for free. How can i stop user from changing the value? or is there any other way to pass the value? or encrypt it and then decrypt it again?
here is my code `index.php`
```
<div id="outer">
<div class="box">
<h4>Rs. 9,900/-</h4>
<ul>
<li>2-Days Classroom Training</li>
<li>E-Learning Course</li>
</ul>
<form action="form.php" method="post">
<input type="hidden" name="amount" value="9900" readonly="readonly">
<input type="hidden" name="package" value="basic" readonly="readonly">
<input type="submit" name="BUY NOW" value="BUY NOW">
</form>
</div>
<div class="box">
<h4>Rs. 11,900/-</h4>
<ul>
<li>4-Days Classroom Training</li>
<li>E-Learning Course</li>
</ul>
<form action="form.php" method="post">
<input type="hidden" name="amount" value="11900" readonly="readonly">
<input type="hidden" name="package" value="standard" readonly="readonly">
<input type="submit" name="BUY NOW" value="BUY NOW">
</form>
</div>
<div class="box">
<h4>Rs. 14,900/-</h4>
<ul>
<li>4-Days Classroom Training</li>
<li>E-Learning Course</li>
<li>5 Hours Personal Session With The Trainer</li>
</ul>
<form action="form.php" method="post">
<input type="hidden" name="amount" value="14900" readonly="readonly">
<input type="hidden" name="package" value="pro" readonly="readonly">
<input type="submit" name="BUY NOW" value="BUY NOW">
</form>
</div>
</div>
```
`form.php`
```
<body>
<?php
if (isset($_POST['amount']) && isset($_POST['package'])) {
$amount = $_POST['amount'];
$package = $_POST['package'];
}
?>
<div>
<table>
<form name="postForm" action="form_process.php" method="POST" >
<tr><td>txnid</td><td><input type="text" name="txnid" readonly="readonly" value="<?php echo $txnid=time().rand(1000,99999); ?>" /></td></tr>
<tr><td>amount</td><td><input type="text" name="amount" readonly="readonly" value="<?php echo $amount; ?>" /></td></tr>
<tr><td>firstname</td><td><input type="text" name="firstname" value="" /></td></tr>
<tr><td>email</td><td><input type="text" name="email" value="" /></td></tr>
<tr><td>phone</td><td><input type="text" name="phone" value="" /></td></tr>
<tr><td>Package</td><td><input type="text" name="productinfo" readonly="readonly" value="<?php echo $package; ?>"/></td></tr>
<tr><td colspan="3"><input type="hidden" name="service_provider" value="payu_paisa" size="64" /></td></tr>
<tr><td><input type="hidden" name="surl" value="http://localhost/payment/success.php" size="64" readonly="readonly" /></td></tr>
<tr><td><input type="hidden" name="furl" value="http://localhost/payment/failure.php" size="64" readonly="readonly" /></td></tr>
<tr><td><input type="submit" /></td><td><input type="reset" /></td></tr>
</form>
</table>
</div>
</body>
```
`form_process.php`
```
<script>
function submitForm() {
var postForm = document.forms.postForm;
postForm.submit();
}
</script>
</head>
<?php
if(!isset($_POST['firstname'])){header("location: form.php");}
// Change the Merchant key here as provided by Payumoney
$MERCHANT_KEY = "*******";
// Change the Merchant Salt as provided by Payumoney
$SALT = "********";
$firstname =$_POST['firstname'];
$email =$_POST['email'];
$phone =$_POST['phone'];
$productinfo =$_POST['productinfo'];
$service_provider =$_POST['service_provider'];
$amount =$_POST['amount'];
$txnid =$_POST['txnid'];
$productinfo =$_POST['productinfo'];
$surl =$_POST['surl'];
$furl =$_POST['furl'];
//$ =$_POST[''];
$hashseq=$MERCHANT_KEY.'|'.$txnid.'|'.$amount.'|'.$productinfo.'|'.$firstname.'|'.$email.'|||||||||||'.$SALT;
$hash =strtolower(hash("sha512", $hashseq));
?>
<body onload="submitForm();">
<div>
<h2>Payment Gateway Testing Sample</h2>
<table>
<tr><td>Transaction Id</td><td><strong><?php echo $_POST['txnid']; ?></strong></td><td>Amount: </td><td><strong>Rs. <?php echo $_POST['amount']; ?></strong></td>
</table>
<div >
<p>In this page we will genrate hash and send it to payumoney.</p>
<br>
<p>Please be patient. this process might take some time,<br />please do not hit refresh or browser back button or close this window</p>
</div>
</div>
<div>
<form name="postForm" action="https://sandboxsecure.payu.in/_payment" method="POST" >
<input type="hidden" name="key" value="<?php echo $MERCHANT_KEY; ?>" />
<input type="hidden" name="hash" value="<?php echo $hash; ?>"/>
<input type="hidden" name="txnid" value="<?php echo $_POST['txnid']; ?>" />
<input type="hidden" name="amount" value="<?php echo $_POST['amount']; ?>" />
<input type="hidden" name="firstname" value="<?php echo $_POST['firstname']; ?>" />
<input type="hidden" name="email" value="<?php echo $_POST['email']; ?>" />
<input type="hidden" name="phone" value="<?php echo $_POST['phone']; ?>" />
<input type="hidden" name="productinfo" value="<?php echo $_POST['productinfo']; ?>" />
<input type="hidden" name="service_provider" value="payu_paisa" size="64" />
<input type="hidden" name="surl" value="<?php echo $_POST['surl']; ?>" />
<input type="hidden" name="furl" value="<?php echo $_POST['furl']; ?>" />
</form>
</div>
</body>
```
`success.php`
```
<body>
<script>var time = 5;
setInterval(function() {
var seconds = time % 60;
var minutes = (time - seconds) / 60;
if (seconds.toString().length == 1) {
seconds = "0" + seconds;
}
if (minutes.toString().length == 1) {
minutes = "0" + minutes;
}
document.getElementById("time").innerHTML = minutes + ":" + seconds;
time--;
if (time == 0) {
window.location.href = "index.php";
}
}, 1000);
</script>
<div>
<h2>Payment Success</h2>
</div>
<div>
<?php
if(isset($_POST['status'])){
if($_POST['status']=="success"){
echo "<p>Payment Done Successfully.<br>Details Are Below.</p>";
echo "<p>Txn Id: ".$_POST['txnid']."</p>";
echo "<p>Name: ".$_POST['firstname']."</p>";
echo "<p>Email: ".$_POST['email']."</p>";
echo "<p>Amount: ".$_POST['amount']."</p>";
echo "<p>Phone No: ".$_POST['phone']."</p>";
echo "<p>Product Info: ".$_POST['productinfo']."</p>";
echo "<p>encryptedPaymentId: ".$_POST['encryptedPaymentId']."</p>";
}
}
?>
</div>
<div>Redirecting to home page in <span id="time"></span></div>
``` | 2020/02/17 | [
"https://Stackoverflow.com/questions/60258123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12849804/"
] | Never let the user send the price. Each course has an ID. Let's assume this:
* course 1, has ID = 1, price = 499, name = 2-Days Classroom Training
* course 2, has ID = 2, price = 999, name = 4-Days Classroom Training
On your payment page, inside `<forms>` send only `course_id = X`.
On the PHP script which receives the request you know that `course_id = X` has `price = Y`... This is the price you will charge.
```
// index.php
<form action="form.php" method="post">
<input type="hidden" name="course_id" value="1" readonly="readonly">
<label>
2-days learning course
</label>
<input type="submit" name="BUY NOW" value="BUY NOW">
</form>
//form.php
if (isset($_POST['course_id']){
if ($_POST['course_id'] == 1){
$amount = 499;
}
} else {
echo 'invalid request'; exit();
}
``` | Check the value of the field, if its zero, just kill the execution of the code, send the user back to the form and print a warning...
Or you could use JavaScript to validate the amount onClick and double check after submission.
***It's a jungle out there!!!*** |
60,258,123 | I am trying to integrate payment gateway on my website. There are three courses each having different prices. I am passing the value of the amount and package to `form.php` and i have made the input fields to readonly but the user can still change the amount in inspect element and make it 0 and pass on the value and get the course for free. How can i stop user from changing the value? or is there any other way to pass the value? or encrypt it and then decrypt it again?
here is my code `index.php`
```
<div id="outer">
<div class="box">
<h4>Rs. 9,900/-</h4>
<ul>
<li>2-Days Classroom Training</li>
<li>E-Learning Course</li>
</ul>
<form action="form.php" method="post">
<input type="hidden" name="amount" value="9900" readonly="readonly">
<input type="hidden" name="package" value="basic" readonly="readonly">
<input type="submit" name="BUY NOW" value="BUY NOW">
</form>
</div>
<div class="box">
<h4>Rs. 11,900/-</h4>
<ul>
<li>4-Days Classroom Training</li>
<li>E-Learning Course</li>
</ul>
<form action="form.php" method="post">
<input type="hidden" name="amount" value="11900" readonly="readonly">
<input type="hidden" name="package" value="standard" readonly="readonly">
<input type="submit" name="BUY NOW" value="BUY NOW">
</form>
</div>
<div class="box">
<h4>Rs. 14,900/-</h4>
<ul>
<li>4-Days Classroom Training</li>
<li>E-Learning Course</li>
<li>5 Hours Personal Session With The Trainer</li>
</ul>
<form action="form.php" method="post">
<input type="hidden" name="amount" value="14900" readonly="readonly">
<input type="hidden" name="package" value="pro" readonly="readonly">
<input type="submit" name="BUY NOW" value="BUY NOW">
</form>
</div>
</div>
```
`form.php`
```
<body>
<?php
if (isset($_POST['amount']) && isset($_POST['package'])) {
$amount = $_POST['amount'];
$package = $_POST['package'];
}
?>
<div>
<table>
<form name="postForm" action="form_process.php" method="POST" >
<tr><td>txnid</td><td><input type="text" name="txnid" readonly="readonly" value="<?php echo $txnid=time().rand(1000,99999); ?>" /></td></tr>
<tr><td>amount</td><td><input type="text" name="amount" readonly="readonly" value="<?php echo $amount; ?>" /></td></tr>
<tr><td>firstname</td><td><input type="text" name="firstname" value="" /></td></tr>
<tr><td>email</td><td><input type="text" name="email" value="" /></td></tr>
<tr><td>phone</td><td><input type="text" name="phone" value="" /></td></tr>
<tr><td>Package</td><td><input type="text" name="productinfo" readonly="readonly" value="<?php echo $package; ?>"/></td></tr>
<tr><td colspan="3"><input type="hidden" name="service_provider" value="payu_paisa" size="64" /></td></tr>
<tr><td><input type="hidden" name="surl" value="http://localhost/payment/success.php" size="64" readonly="readonly" /></td></tr>
<tr><td><input type="hidden" name="furl" value="http://localhost/payment/failure.php" size="64" readonly="readonly" /></td></tr>
<tr><td><input type="submit" /></td><td><input type="reset" /></td></tr>
</form>
</table>
</div>
</body>
```
`form_process.php`
```
<script>
function submitForm() {
var postForm = document.forms.postForm;
postForm.submit();
}
</script>
</head>
<?php
if(!isset($_POST['firstname'])){header("location: form.php");}
// Change the Merchant key here as provided by Payumoney
$MERCHANT_KEY = "*******";
// Change the Merchant Salt as provided by Payumoney
$SALT = "********";
$firstname =$_POST['firstname'];
$email =$_POST['email'];
$phone =$_POST['phone'];
$productinfo =$_POST['productinfo'];
$service_provider =$_POST['service_provider'];
$amount =$_POST['amount'];
$txnid =$_POST['txnid'];
$productinfo =$_POST['productinfo'];
$surl =$_POST['surl'];
$furl =$_POST['furl'];
//$ =$_POST[''];
$hashseq=$MERCHANT_KEY.'|'.$txnid.'|'.$amount.'|'.$productinfo.'|'.$firstname.'|'.$email.'|||||||||||'.$SALT;
$hash =strtolower(hash("sha512", $hashseq));
?>
<body onload="submitForm();">
<div>
<h2>Payment Gateway Testing Sample</h2>
<table>
<tr><td>Transaction Id</td><td><strong><?php echo $_POST['txnid']; ?></strong></td><td>Amount: </td><td><strong>Rs. <?php echo $_POST['amount']; ?></strong></td>
</table>
<div >
<p>In this page we will genrate hash and send it to payumoney.</p>
<br>
<p>Please be patient. this process might take some time,<br />please do not hit refresh or browser back button or close this window</p>
</div>
</div>
<div>
<form name="postForm" action="https://sandboxsecure.payu.in/_payment" method="POST" >
<input type="hidden" name="key" value="<?php echo $MERCHANT_KEY; ?>" />
<input type="hidden" name="hash" value="<?php echo $hash; ?>"/>
<input type="hidden" name="txnid" value="<?php echo $_POST['txnid']; ?>" />
<input type="hidden" name="amount" value="<?php echo $_POST['amount']; ?>" />
<input type="hidden" name="firstname" value="<?php echo $_POST['firstname']; ?>" />
<input type="hidden" name="email" value="<?php echo $_POST['email']; ?>" />
<input type="hidden" name="phone" value="<?php echo $_POST['phone']; ?>" />
<input type="hidden" name="productinfo" value="<?php echo $_POST['productinfo']; ?>" />
<input type="hidden" name="service_provider" value="payu_paisa" size="64" />
<input type="hidden" name="surl" value="<?php echo $_POST['surl']; ?>" />
<input type="hidden" name="furl" value="<?php echo $_POST['furl']; ?>" />
</form>
</div>
</body>
```
`success.php`
```
<body>
<script>var time = 5;
setInterval(function() {
var seconds = time % 60;
var minutes = (time - seconds) / 60;
if (seconds.toString().length == 1) {
seconds = "0" + seconds;
}
if (minutes.toString().length == 1) {
minutes = "0" + minutes;
}
document.getElementById("time").innerHTML = minutes + ":" + seconds;
time--;
if (time == 0) {
window.location.href = "index.php";
}
}, 1000);
</script>
<div>
<h2>Payment Success</h2>
</div>
<div>
<?php
if(isset($_POST['status'])){
if($_POST['status']=="success"){
echo "<p>Payment Done Successfully.<br>Details Are Below.</p>";
echo "<p>Txn Id: ".$_POST['txnid']."</p>";
echo "<p>Name: ".$_POST['firstname']."</p>";
echo "<p>Email: ".$_POST['email']."</p>";
echo "<p>Amount: ".$_POST['amount']."</p>";
echo "<p>Phone No: ".$_POST['phone']."</p>";
echo "<p>Product Info: ".$_POST['productinfo']."</p>";
echo "<p>encryptedPaymentId: ".$_POST['encryptedPaymentId']."</p>";
}
}
?>
</div>
<div>Redirecting to home page in <span id="time"></span></div>
``` | 2020/02/17 | [
"https://Stackoverflow.com/questions/60258123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12849804/"
] | U can do one thing to avoid the trap is that just make a session variable for the amount value and then fetch the session variable in the next page and then send the session variable for the amount element(mandatory) along with the others field which are encrypted/decrypted by the payment gateway. | Check the value of the field, if its zero, just kill the execution of the code, send the user back to the form and print a warning...
Or you could use JavaScript to validate the amount onClick and double check after submission.
***It's a jungle out there!!!*** |
60,258,123 | I am trying to integrate payment gateway on my website. There are three courses each having different prices. I am passing the value of the amount and package to `form.php` and i have made the input fields to readonly but the user can still change the amount in inspect element and make it 0 and pass on the value and get the course for free. How can i stop user from changing the value? or is there any other way to pass the value? or encrypt it and then decrypt it again?
here is my code `index.php`
```
<div id="outer">
<div class="box">
<h4>Rs. 9,900/-</h4>
<ul>
<li>2-Days Classroom Training</li>
<li>E-Learning Course</li>
</ul>
<form action="form.php" method="post">
<input type="hidden" name="amount" value="9900" readonly="readonly">
<input type="hidden" name="package" value="basic" readonly="readonly">
<input type="submit" name="BUY NOW" value="BUY NOW">
</form>
</div>
<div class="box">
<h4>Rs. 11,900/-</h4>
<ul>
<li>4-Days Classroom Training</li>
<li>E-Learning Course</li>
</ul>
<form action="form.php" method="post">
<input type="hidden" name="amount" value="11900" readonly="readonly">
<input type="hidden" name="package" value="standard" readonly="readonly">
<input type="submit" name="BUY NOW" value="BUY NOW">
</form>
</div>
<div class="box">
<h4>Rs. 14,900/-</h4>
<ul>
<li>4-Days Classroom Training</li>
<li>E-Learning Course</li>
<li>5 Hours Personal Session With The Trainer</li>
</ul>
<form action="form.php" method="post">
<input type="hidden" name="amount" value="14900" readonly="readonly">
<input type="hidden" name="package" value="pro" readonly="readonly">
<input type="submit" name="BUY NOW" value="BUY NOW">
</form>
</div>
</div>
```
`form.php`
```
<body>
<?php
if (isset($_POST['amount']) && isset($_POST['package'])) {
$amount = $_POST['amount'];
$package = $_POST['package'];
}
?>
<div>
<table>
<form name="postForm" action="form_process.php" method="POST" >
<tr><td>txnid</td><td><input type="text" name="txnid" readonly="readonly" value="<?php echo $txnid=time().rand(1000,99999); ?>" /></td></tr>
<tr><td>amount</td><td><input type="text" name="amount" readonly="readonly" value="<?php echo $amount; ?>" /></td></tr>
<tr><td>firstname</td><td><input type="text" name="firstname" value="" /></td></tr>
<tr><td>email</td><td><input type="text" name="email" value="" /></td></tr>
<tr><td>phone</td><td><input type="text" name="phone" value="" /></td></tr>
<tr><td>Package</td><td><input type="text" name="productinfo" readonly="readonly" value="<?php echo $package; ?>"/></td></tr>
<tr><td colspan="3"><input type="hidden" name="service_provider" value="payu_paisa" size="64" /></td></tr>
<tr><td><input type="hidden" name="surl" value="http://localhost/payment/success.php" size="64" readonly="readonly" /></td></tr>
<tr><td><input type="hidden" name="furl" value="http://localhost/payment/failure.php" size="64" readonly="readonly" /></td></tr>
<tr><td><input type="submit" /></td><td><input type="reset" /></td></tr>
</form>
</table>
</div>
</body>
```
`form_process.php`
```
<script>
function submitForm() {
var postForm = document.forms.postForm;
postForm.submit();
}
</script>
</head>
<?php
if(!isset($_POST['firstname'])){header("location: form.php");}
// Change the Merchant key here as provided by Payumoney
$MERCHANT_KEY = "*******";
// Change the Merchant Salt as provided by Payumoney
$SALT = "********";
$firstname =$_POST['firstname'];
$email =$_POST['email'];
$phone =$_POST['phone'];
$productinfo =$_POST['productinfo'];
$service_provider =$_POST['service_provider'];
$amount =$_POST['amount'];
$txnid =$_POST['txnid'];
$productinfo =$_POST['productinfo'];
$surl =$_POST['surl'];
$furl =$_POST['furl'];
//$ =$_POST[''];
$hashseq=$MERCHANT_KEY.'|'.$txnid.'|'.$amount.'|'.$productinfo.'|'.$firstname.'|'.$email.'|||||||||||'.$SALT;
$hash =strtolower(hash("sha512", $hashseq));
?>
<body onload="submitForm();">
<div>
<h2>Payment Gateway Testing Sample</h2>
<table>
<tr><td>Transaction Id</td><td><strong><?php echo $_POST['txnid']; ?></strong></td><td>Amount: </td><td><strong>Rs. <?php echo $_POST['amount']; ?></strong></td>
</table>
<div >
<p>In this page we will genrate hash and send it to payumoney.</p>
<br>
<p>Please be patient. this process might take some time,<br />please do not hit refresh or browser back button or close this window</p>
</div>
</div>
<div>
<form name="postForm" action="https://sandboxsecure.payu.in/_payment" method="POST" >
<input type="hidden" name="key" value="<?php echo $MERCHANT_KEY; ?>" />
<input type="hidden" name="hash" value="<?php echo $hash; ?>"/>
<input type="hidden" name="txnid" value="<?php echo $_POST['txnid']; ?>" />
<input type="hidden" name="amount" value="<?php echo $_POST['amount']; ?>" />
<input type="hidden" name="firstname" value="<?php echo $_POST['firstname']; ?>" />
<input type="hidden" name="email" value="<?php echo $_POST['email']; ?>" />
<input type="hidden" name="phone" value="<?php echo $_POST['phone']; ?>" />
<input type="hidden" name="productinfo" value="<?php echo $_POST['productinfo']; ?>" />
<input type="hidden" name="service_provider" value="payu_paisa" size="64" />
<input type="hidden" name="surl" value="<?php echo $_POST['surl']; ?>" />
<input type="hidden" name="furl" value="<?php echo $_POST['furl']; ?>" />
</form>
</div>
</body>
```
`success.php`
```
<body>
<script>var time = 5;
setInterval(function() {
var seconds = time % 60;
var minutes = (time - seconds) / 60;
if (seconds.toString().length == 1) {
seconds = "0" + seconds;
}
if (minutes.toString().length == 1) {
minutes = "0" + minutes;
}
document.getElementById("time").innerHTML = minutes + ":" + seconds;
time--;
if (time == 0) {
window.location.href = "index.php";
}
}, 1000);
</script>
<div>
<h2>Payment Success</h2>
</div>
<div>
<?php
if(isset($_POST['status'])){
if($_POST['status']=="success"){
echo "<p>Payment Done Successfully.<br>Details Are Below.</p>";
echo "<p>Txn Id: ".$_POST['txnid']."</p>";
echo "<p>Name: ".$_POST['firstname']."</p>";
echo "<p>Email: ".$_POST['email']."</p>";
echo "<p>Amount: ".$_POST['amount']."</p>";
echo "<p>Phone No: ".$_POST['phone']."</p>";
echo "<p>Product Info: ".$_POST['productinfo']."</p>";
echo "<p>encryptedPaymentId: ".$_POST['encryptedPaymentId']."</p>";
}
}
?>
</div>
<div>Redirecting to home page in <span id="time"></span></div>
``` | 2020/02/17 | [
"https://Stackoverflow.com/questions/60258123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12849804/"
] | Never let the user send the price. Each course has an ID. Let's assume this:
* course 1, has ID = 1, price = 499, name = 2-Days Classroom Training
* course 2, has ID = 2, price = 999, name = 4-Days Classroom Training
On your payment page, inside `<forms>` send only `course_id = X`.
On the PHP script which receives the request you know that `course_id = X` has `price = Y`... This is the price you will charge.
```
// index.php
<form action="form.php" method="post">
<input type="hidden" name="course_id" value="1" readonly="readonly">
<label>
2-days learning course
</label>
<input type="submit" name="BUY NOW" value="BUY NOW">
</form>
//form.php
if (isset($_POST['course_id']){
if ($_POST['course_id'] == 1){
$amount = 499;
}
} else {
echo 'invalid request'; exit();
}
``` | U can do one thing to avoid the trap is that just make a session variable for the amount value and then fetch the session variable in the next page and then send the session variable for the amount element(mandatory) along with the others field which are encrypted/decrypted by the payment gateway. |
33,169 | Does using a semicolon to join two clauses form a coordinate construction with two clauses coordinated and is it the same as with "and" and are such sentences interchangeable ? And can we omit words(ellipsis/gapping) as we did with coordinate structure ?
>
> In 2000 there were seven cases; in 1999, five.
>
> In 2000 there were seven cases and in 1999, five.
>
>
> | 2014/09/10 | [
"https://ell.stackexchange.com/questions/33169",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/9862/"
] | >
> In 2000 there were seven cases; in 1999, five.
>
>
>
Yes, this can be considered coordination. Specifically, it's **asyndetic** coordination, meaning that there is no overt coordinator such as *and* present.
Yes, both of your examples have the same meaning. As you suggest, the first sentence is an example of **gapping** with the existential *there were* omitted from the second coordinate:
>
> In 2000 there were seven cases; in 1999, ~~there were~~ five ~~cases~~.
>
>
>
We can find a similar example in *The Cambridge Grammar of the English Language*, p.1744:
>
> Some of the immigrants went to small farms in the Midwest; others, to large Eastern cities.
>
>
>
This is explicitly labeled as an example of asyndetic coordination with gapping and a semicolon.
In most but not all cases gapping is equivalent to a non-gapped version:
>
> In 2000 there were seven cases; in 1999, ~~there were~~ five ~~cases~~.
>
> In 2000 there were seven cases; in 1999, there were five ~~cases~~.
>
>
>
These examples are interchangeable. | The rule I know of is summed up as:
>
> "a semicolon should be used to separate two independent clauses (or complete sentences) that are closely related in meaning."
>
>
>
*Technically*, **"In 1999, five"** cannot stand as a complete sentence. **"In 1999, there were five cases"** can. You can also build a sentence diagram for **"In 1999, there were five"** (although it makes me a bit uneasy standing alone).
But *in practice* your first sentence wouldn't be misunderstood. That pattern is used frequently. It's most often qualified somehow to show the point you are trying to make with the contrast. Dramatic pauses are usually used when spoken:
>
> In 2000 there were seven cases; [{...beat...}](http://en.wikipedia.org/wiki/Beat_(filmmaking)) in 1999, [{...beat...}](http://en.wikipedia.org/wiki/Beat_(filmmaking)) **only** five.
>
>
>
British journalists would say it exactly like this, and you would write it down using a semicolon.
Putting the "and" in doesn't have correct grammar, yet doesn't offer the same leeway. Perhaps because the spoken form is awkward: if you put `and` after the beat you've waited too long, while if you put it before the beat it leaves people hanging in an awkward way.
>
> In 2000 there were seven cases and in 1999, five.
>
>
>
...so that form should be avoided. |
31,351,626 | I have look at many web sites and many pages on Stackoverflow, but none of them has solved my problem yet. Simply, I have a `hyperlink` and I want to retrieve an image from database via `Ajax` call and then display it on `FancyBox` popup. I also tried many different combinations of `Javascript` and `Controller` action methods, but have not managed so display the downloaded file properly. Could you please have a look at my code and give a working example containing all the necessary methods in `View` and in `Controller`? On the other hand, it would be better to open a dialog for the other file types (i.e. excel, pdf) while opening `FancyBox` for image files.
**View:**
```
<a onclick="downloadFile(@Model.ID);">@Model.FileName</a>
function downloadFile(id) {
$.ajax({
url: "/Issue/RenderImage?ID=" + id,
async: true,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
$('#fancybox-inner').html('<img height="200" width="250" src="data:image/png;base64,' + response + '" />');
}
});
}
```
**Controller:** There is no problem regarding to the method in the Controller and it returns the image properly.
```
[HttpPost]
public virtual JsonResult RenderImage(int id)
{
string str = System.Convert.ToBase64String(repository.FileAttachments.FirstOrDefault(p => p.ID == id).FileData, 0, repository.FileAttachments.FirstOrDefault(p => p.ID == id).FileData.Length);
return Json(new { Image = str, JsonRequestBehavior.AllowGet });
}
``` | 2015/07/10 | [
"https://Stackoverflow.com/questions/31351626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/836018/"
] | Better try
```
success: function (response) {
$.fancybox({
content: '<img height="200" width="250" src="data:image/png;base64,' + response + '" />',
type: "html"
});
}
```
I wonder why you trying to load the content inside a fancybox container when you don't show any code where you already opened it. Anyways, it's always better to launch a new fancybox with the new content (from ajax response)
Of course, this will work if the ajax call is returning the correct response for your `<img>` tag, but that I cannot tell. | This should work. Looks like image is stored as JSON. If so, I think you should convert it back to Base64 before sending it to the browser. See <http://mobile.cs.fsu.edu/converting-images-to-json-objects/>
```
function downloadFile(id) {
$('#fancybox-inner').html('<img height="200" width="250" src="/Issue/RenderImage?ID='+id+'" />');
}
``` |
28,710 | I understand that he had four major projects come out in 2005 - all of which got nominated for major awards, so I understand why he did not do Goblet of Fire. However, was there any particular reason ever given by him or the directors/producers/etc involved, why he did not return for 5-8? | 2012/12/31 | [
"https://scifi.stackexchange.com/questions/28710",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/10926/"
] | John Williams [was asked back](http://en.wikipedia.org/wiki/John_williams#Film_and_television_scoring) to score *Harry Potter and the Deathly Hallows - Part 2* by director David Yates; however, Williams's schedule and Yates's schedule "did not align" -- Yates would have had to have provided Williams with a raw cut of *Deathly Hallows - Part 2* much sooner than was feasible if he were to compose the music for the film. The [John Williams Fan Network](http://www.jwfan.com/forums/index.php?showtopic=8947) (I'm unsure of the quality of this source) cites either a lack of time on Williams's part, or the director wanting someone local to the production, as possible reasons behind why Williams did not go on to score *Goblet of Fire* after the first three films. Fans at the [*Film Score Monthly*](http://www.filmscoremonthly.com/board/posts.cfm?threadID=65574&forumID=1&archive=0) forums seem to lend credence to these possibilities.
Clearly, The Powers That Be secured the rights to, for example, [*Lumos! Hedwig's Theme* YouTube 1:42 **(SFW)**](http://www.youtube.com/watch?v=md7O1Ve8K7M), which is the main *Harry Potter* theme, which would allow them permission for any subsequent composer to incorporate *Hedwig's Theme* into future *Potter* scores as needed. Indeed, *Hedwig's Theme* is heard in all eight *Potter* films in one incarnation or another.
In *Harry Potter and the Goblet of Fire*, *Hedwig's Theme* can be heard in the opening credits. In *Order of the Phoenix*, it can also be heard in the opening credits. In *Deathly Hallows - Part 2*, the second part of *Hedwig's Theme*, which corresponds with the opening credits of *Chamber of Secrets*, is heard at the *19 Years Later* scene, which is the last scene of all the *Harry Potter* movies. Offhand I can't pinpoint off the top of my head where exactly Williams's work is used in *Half-Blood Prince* or *Deathly Hallows - Part 1*, but according to John Williams's Wikipedia page, it was indeed used.
As an aside, [here YouTube 4:56 **(SFW)**](http://www.youtube.com/watch?v=GTXBLyp7_Dw) is a clip of the London Symphony Orchestra performing *Hedwig's Theme* for the Proms for the BBC, which is pretty cool because it shows which instrument plays each part of the theme. I hadn't known before, and **GorchestopherH** pointed out to me, that the instrument that plays the opening measures of *Hedwig's Theme* -- the bell-like instrument -- is something called a [celeste or celesta](http://en.wikipedia.org/wiki/Celesta), which is grouped in the keyboard family although it's technically a percussion instrument (**TangoOversway** pointed this out to me; originally I had said it was not a percussion instrument. It's an idiophone.). "Celesta" or "celeste" means "heavenly" in French. | He had already passed the torch.
Many creative people are like that - once they have to let go of something or move on, they would rather not go back to revisit old works. The other side to it is something a bit like courtesy. Once you've turned it over to someone else, let them have it - don't grab it back.
In terms of consistency, once a producer of a film series has moved on from using one person in a work (whether they're a composer, director, or actor), it's a step down from what might be called "total unity" and it makes sense, once you change direction, to not go back. (Unless the new direction is a disaster - such as with *On Her Majesty's Secret Service* in the 007 series. It did lousy at the box office, and they went back to Sean Connery as Bond, and ened up with what's generally considered one of the worst Bond films ever made (*Diamonds are Forever*) and knew they'd have to move on anyway.) |
28,710 | I understand that he had four major projects come out in 2005 - all of which got nominated for major awards, so I understand why he did not do Goblet of Fire. However, was there any particular reason ever given by him or the directors/producers/etc involved, why he did not return for 5-8? | 2012/12/31 | [
"https://scifi.stackexchange.com/questions/28710",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/10926/"
] | He had already passed the torch.
Many creative people are like that - once they have to let go of something or move on, they would rather not go back to revisit old works. The other side to it is something a bit like courtesy. Once you've turned it over to someone else, let them have it - don't grab it back.
In terms of consistency, once a producer of a film series has moved on from using one person in a work (whether they're a composer, director, or actor), it's a step down from what might be called "total unity" and it makes sense, once you change direction, to not go back. (Unless the new direction is a disaster - such as with *On Her Majesty's Secret Service* in the 007 series. It did lousy at the box office, and they went back to Sean Connery as Bond, and ened up with what's generally considered one of the worst Bond films ever made (*Diamonds are Forever*) and knew they'd have to move on anyway.) | One of the main reasons why John Williams never came back to Compose for Goblet of Fire was due to his involvement of 'Revenge of the Sith - Episode III' that same year. Thus, his scheduling made it nearly impossible to compose both films at the same time, so Williams generously acknowledged Mike Newell (the director) to use one of his longtime friends and brilliant composer Patrick Doyle, whom went on to compose the film in his honor, using samples of motifs from John throughout the score. In terms of his being asked back or to leave, Warner Brothers and the producers themselves were upset to Williams leaving the project due to scheduling conflicts, yet never insisted Williams to be let go due to his "style". The stylistic choice for *his* music made the tone absolutely set for the films. Had John stayed on for all 8 (presumably 7, if they had at the time), I think the musical score would still have worked brilliantly, since Williams is known for keeping things fresh and unique, with a hint of familiarity to counter-balance it all out, like what he recently did for *Star Wars: The Force Awakens*. The fact that the series garnished new composers for almost each movie made the scores distinct from one another, complementing the scope, subtly, and tone of the individual films with said scores. |
28,710 | I understand that he had four major projects come out in 2005 - all of which got nominated for major awards, so I understand why he did not do Goblet of Fire. However, was there any particular reason ever given by him or the directors/producers/etc involved, why he did not return for 5-8? | 2012/12/31 | [
"https://scifi.stackexchange.com/questions/28710",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/10926/"
] | John Williams [was asked back](http://en.wikipedia.org/wiki/John_williams#Film_and_television_scoring) to score *Harry Potter and the Deathly Hallows - Part 2* by director David Yates; however, Williams's schedule and Yates's schedule "did not align" -- Yates would have had to have provided Williams with a raw cut of *Deathly Hallows - Part 2* much sooner than was feasible if he were to compose the music for the film. The [John Williams Fan Network](http://www.jwfan.com/forums/index.php?showtopic=8947) (I'm unsure of the quality of this source) cites either a lack of time on Williams's part, or the director wanting someone local to the production, as possible reasons behind why Williams did not go on to score *Goblet of Fire* after the first three films. Fans at the [*Film Score Monthly*](http://www.filmscoremonthly.com/board/posts.cfm?threadID=65574&forumID=1&archive=0) forums seem to lend credence to these possibilities.
Clearly, The Powers That Be secured the rights to, for example, [*Lumos! Hedwig's Theme* YouTube 1:42 **(SFW)**](http://www.youtube.com/watch?v=md7O1Ve8K7M), which is the main *Harry Potter* theme, which would allow them permission for any subsequent composer to incorporate *Hedwig's Theme* into future *Potter* scores as needed. Indeed, *Hedwig's Theme* is heard in all eight *Potter* films in one incarnation or another.
In *Harry Potter and the Goblet of Fire*, *Hedwig's Theme* can be heard in the opening credits. In *Order of the Phoenix*, it can also be heard in the opening credits. In *Deathly Hallows - Part 2*, the second part of *Hedwig's Theme*, which corresponds with the opening credits of *Chamber of Secrets*, is heard at the *19 Years Later* scene, which is the last scene of all the *Harry Potter* movies. Offhand I can't pinpoint off the top of my head where exactly Williams's work is used in *Half-Blood Prince* or *Deathly Hallows - Part 1*, but according to John Williams's Wikipedia page, it was indeed used.
As an aside, [here YouTube 4:56 **(SFW)**](http://www.youtube.com/watch?v=GTXBLyp7_Dw) is a clip of the London Symphony Orchestra performing *Hedwig's Theme* for the Proms for the BBC, which is pretty cool because it shows which instrument plays each part of the theme. I hadn't known before, and **GorchestopherH** pointed out to me, that the instrument that plays the opening measures of *Hedwig's Theme* -- the bell-like instrument -- is something called a [celeste or celesta](http://en.wikipedia.org/wiki/Celesta), which is grouped in the keyboard family although it's technically a percussion instrument (**TangoOversway** pointed this out to me; originally I had said it was not a percussion instrument. It's an idiophone.). "Celesta" or "celeste" means "heavenly" in French. | One of the main reasons why John Williams never came back to Compose for Goblet of Fire was due to his involvement of 'Revenge of the Sith - Episode III' that same year. Thus, his scheduling made it nearly impossible to compose both films at the same time, so Williams generously acknowledged Mike Newell (the director) to use one of his longtime friends and brilliant composer Patrick Doyle, whom went on to compose the film in his honor, using samples of motifs from John throughout the score. In terms of his being asked back or to leave, Warner Brothers and the producers themselves were upset to Williams leaving the project due to scheduling conflicts, yet never insisted Williams to be let go due to his "style". The stylistic choice for *his* music made the tone absolutely set for the films. Had John stayed on for all 8 (presumably 7, if they had at the time), I think the musical score would still have worked brilliantly, since Williams is known for keeping things fresh and unique, with a hint of familiarity to counter-balance it all out, like what he recently did for *Star Wars: The Force Awakens*. The fact that the series garnished new composers for almost each movie made the scores distinct from one another, complementing the scope, subtly, and tone of the individual films with said scores. |
1,443,231 | java & keytool install paths:
```
C:\Users\foobar>where java
C:\Program Files\Java\jdk1.8.0_211\bin\java.exe
C:\Users\foobar>where keytool
C:\Program Files\Java\jdk1.8.0_211\bin\keytool.exe
```
As it's the only `cacerts` file in the `Java` directory, I assume this is the default:
```
"C:\Program Files\Java\jdk1.8.0_211\jre\lib\security\cacerts"
```
`keytool` output - WITH path to specific `cacerts` keystore file:
```
C:\Users\foobar>keytool -list -keystore "C:\Program Files\Java\jdk1.8.0_211\jre\lib\security\cacerts"
Enter keystore password:
Keystore type: jks
Keystore provider: SUN
Your keystore contains 98 entries
verisignclass2g2ca [jdk], Aug 25, 2016, trustedCertEntry,
Certificate fingerprint (SHA1): C9:B4:1C:EA:F2:9D:95:B6:CC:A0:08:1B:67:EC:9D:B3:EA:C4:47:76
digicertassuredidg3 [jdk], Aug 25, 2016, trustedCertEntry,
Certificate fingerprint (SHA1): 00:F4:9F:DC:0F:48:2C:AB:30:89:F5:17:A2:4F:9A:48:C6:C9:F8:A2
...
...
...
verisignuniversalrootca [jdk], Aug 25, 2016, trustedCertEntry,
Certificate fingerprint (SHA1): 36:30:A5:FB:87:3B:0F:A7:7B:B7:0D:54:79:CA:35:66:87:72:30:4D
```
`keytool` output - WITHOUT path to specific `cacerts` keystore file:
```
C:\Users\foobar>keytool -list
Enter keystore password:
Keystore type: jks
Keystore provider: SUN
Your keystore contains 0 entries
```
Why are the `keytool` outputs not the same?
When a specific keystore is NOT defined, which `cacerts` file is being used/referenced? | 2019/05/31 | [
"https://superuser.com/questions/1443231",
"https://superuser.com",
"https://superuser.com/users/1043627/"
] | It turns out that my .env file is incorrect. You should not put ',' separator between the variables. | If its a react app be sure you're in the client directory and that you're not trying to run you react app in server directory...as it won't give you error but address issues |
46,626,862 | I have another question posted where my query would not return the results into my sealresult Label. So I figured to ask it in a different way because I still cannot figure this out. I have the following code, it runs perfectly when the button "Search" is clicked and returns the query result. However, I have a textBox with an Id of receiptbox and I want to enable an user to input text and that be placed into the query to gather the result into the sealresult Label. How do I accomplish this? I want user input where it says RE00007544 from a textbox labeled receiptbox.
```
protected void receiptbox_TextChanged(object sender, EventArgs e)
{
}
protected void sealresultquery_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void searchbutton_Click(object sender, EventArgs e)
{
sealresult.Text = "";
string connString = @"Data Source=SQL;Initial Catalog=mydatabase;User ID=admin;Password=******";
string query = "Select seal1 from dbo.RECEIPTHEADER where receipt = 'RE00007544'";
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm = new SqlCommand(query, conn);
using (conn)
{
try
{
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
while(reader.Read())
{
sealresult.Text += reader[0].ToString();
}
reader.Close();
}
catch(Exception ex)
{
querystatus.Text = ex.Message;
}
}
}
``` | 2017/10/08 | [
"https://Stackoverflow.com/questions/46626862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7958874/"
] | ```
vector<int> numbers;
// some code here to add values to the numbers array
int maxStreak = 0;
int counter = 0;
int previousNumber;
int currentNumber;
for (int i= 1; i < numbers.size(); i++)
{
previousNumber = numbers[i - 1];
currentNumber = numbers[i];
if (abs(currentNumber - previousNumber) <= 10) {
counter++;
maxStreak = (counter > maxStreak) ? counter : maxStreak;
}
else {
counter = 0;
}
}
cout << maxStreak;
```
---
Here is how it works:
1. *maxStreak* stores the highest number of streak.
2. *counter* stores the number of current streak.
3. The loop starts reading from the second element of the array and compares each number in the array with the its previous number.
4. If the difference between the two numbers is equal to or less than 10, *counter* increments and *maxStreak* will be updated appropriately.
5. If the difference between the two numbers is not equal to or less than 10, *counter* will be reset to 0. | Remember `start` index of potential run (initially 0)
Start loop from the second index and check **every** pair `(i++)`
Calculate **absolute** value of difference (AD) of `A[i]` and `A[i-1]`
If AD is **too large**, run is over, so find whether run length `(i-start)` is longer than previous (`maxlen`)
Check run length after loop end again |
53,847,803 | Similar to [Clojure recur with multi-arity](https://stackoverflow.com/questions/49546574/clojure-recur-with-multi-arity) I'd like recur with a different arity. But in my case, I define the function via a let, as I want to use another value from the let (`file-list`) without passing it:
```
(let [file-list (drive/list-files! google-drive-credentials google-drive-folder-id)
download-file (fn
([name]
(download-file ; <-- attempt to recur
name
(fn []
(throw
(ex-info
(str name " not found on Google Drive"))))))
([name not-found-fn]
(if-let [file (->> file-list
(filter #(= (:original-filename %)
name))
first)]
(drive/download-file! google-drive-credentials file)
(not-found-fn))))]
;; #
)
```
I get this error: `Exception in thread "main" java.lang.RuntimeException: Unable to resolve symbol: download-file in this context` | 2018/12/19 | [
"https://Stackoverflow.com/questions/53847803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/362378/"
] | You can give a local name to the `fn`:
```
(let [download-file (fn download-file
([name] (download-file name (fn ...))))
```
you could also use [`letfn`](https://clojuredocs.org/clojure.core/letfn):
```
(letfn [(download-file
([name] (download-file name (fn ...)))
([name not-found-fn] ...)])
``` | In order to make more readable exception error messages, I often append `-fn` to the inner function name, like so:
```
(let [download-file (fn download-file-fn [name] ...) ]
<use download-file> ...)
``` |
71,124 | Once I asked my friend 'how's the summer treating you?', he replied 'It's been good because it's been bad.'
What does it mean? Good or bad? | 2012/06/15 | [
"https://english.stackexchange.com/questions/71124",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/22352/"
] | Just my guess: Low heat tolerance + bad (cold) weather = good summer. | It really depends on what country, where the emphasis was in the sentence, what your friend's sense of humor is like...
In other words, it means absolutely nothing to me. If I were sitting with someone who said it, I would have to guess based on everything *other* than the words. |
71,124 | Once I asked my friend 'how's the summer treating you?', he replied 'It's been good because it's been bad.'
What does it mean? Good or bad? | 2012/06/15 | [
"https://english.stackexchange.com/questions/71124",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/22352/"
] | It sounds like your friend was referring to a [***silver lining***](http://www.wordnik.com/words/silver%20lining) of some sort. It may have been weather-related, as SF. guessed, or it could have been a host of other things.
For example, If he was a student, it might mean:
>
> This term, my professors are really giving me a lot of work!1 But at least I'm learning a lot.2
>
>
>
If he was a business owner, it could mean:
>
> I've been so busy with my business that I haven't had any time off!2 But at least business is good.1
>
>
>
or even:
>
> Business has been off, so I don't have much work coming in2 – but at least I've been able to enjoy the summer!1
>
>
>
So, without any more context, there's really no way to know for sure exactly what he meant.
---
In the quotes above 1this is "bad", and 2this is "good". Hence, *It's been good,*2 *because it's been bad.*1 | It really depends on what country, where the emphasis was in the sentence, what your friend's sense of humor is like...
In other words, it means absolutely nothing to me. If I were sitting with someone who said it, I would have to guess based on everything *other* than the words. |
71,124 | Once I asked my friend 'how's the summer treating you?', he replied 'It's been good because it's been bad.'
What does it mean? Good or bad? | 2012/06/15 | [
"https://english.stackexchange.com/questions/71124",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/22352/"
] | It sounds like your friend was referring to a [***silver lining***](http://www.wordnik.com/words/silver%20lining) of some sort. It may have been weather-related, as SF. guessed, or it could have been a host of other things.
For example, If he was a student, it might mean:
>
> This term, my professors are really giving me a lot of work!1 But at least I'm learning a lot.2
>
>
>
If he was a business owner, it could mean:
>
> I've been so busy with my business that I haven't had any time off!2 But at least business is good.1
>
>
>
or even:
>
> Business has been off, so I don't have much work coming in2 – but at least I've been able to enjoy the summer!1
>
>
>
So, without any more context, there's really no way to know for sure exactly what he meant.
---
In the quotes above 1this is "bad", and 2this is "good". Hence, *It's been good,*2 *because it's been bad.*1 | Just my guess: Low heat tolerance + bad (cold) weather = good summer. |
18,969,798 | Essentially, I'm trying to find a good way to attach more views to a Router without creating a custom Router. **What's a good way to accomplish this?**
Here is something sort of equivalent to what I'm trying to accomplish. Variable names have been changed and the example method I want to introduce is extremely simplified for the sake of this question.
Router:
```
router = routers.SimpleRouter(trailing_slash=False)
router.register(r'myobjects', MyObjectViewSet, base_name='myobjects')
urlpatterns = router.urls
```
ViewSet
```
class MyObjectsViewSet(viewsets.ViewSet):
""" Provides API Methods to manage MyObjects. """
def list(self, request):
""" Returns a list of MyObjects. """
data = get_list_of_myobjects()
return Response(data)
def retrieve(self, request, pk):
""" Returns a single MyObject. """
data = fetch_my_object(pk)
return Response(data)
def destroy(self, request, pk):
""" Deletes a single MyObject. """
fetch_my_object_and_delete(pk)
return Response()
```
One example of another method type I need to include. (There are many of these):
```
def get_locations(self, request):
""" Returns a list of location objects somehow related to MyObject """
locations = calculate_something()
return Response(locations)
```
The end-result is that the following URL would work correctly and be implemented 'cleanly'.
```
GET example.com/myobjects/123/locations
``` | 2013/09/23 | [
"https://Stackoverflow.com/questions/18969798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485900/"
] | You define method like you do now, but you need to use the same url as method name and add link decorator, so for
```
/myobjects/123/locations/
```
You add method like this
```
@link(permission_classes=[...])
def locations(self, request, pk=None):
...
```
and router will pick it automatically. | From [Routing to extra methods on a ViewSet](https://groups.google.com/forum/#!msg/django-rest-framework/naTNAxw4jws/nue_fhS5vI4J):
>
> I think you may need to route the method by hand, i.e. The Old-Fashioned Way™.
>
>
> First pull the method out as a separate view:
>
>
>
> ```
> set_password_view = UserViewSet.as_view({'post': 'set_password'})
>
> ```
>
> (or such)
>
>
> Then assign your URL:
>
>
>
> ```
> url(r'^users/username_available/$', set_password_view, name-=...)
>
> ```
>
> (Or such)
>
>
>
There's a [related question on SO](https://stackoverflow.com/q/18194603/4794). |
18,969,798 | Essentially, I'm trying to find a good way to attach more views to a Router without creating a custom Router. **What's a good way to accomplish this?**
Here is something sort of equivalent to what I'm trying to accomplish. Variable names have been changed and the example method I want to introduce is extremely simplified for the sake of this question.
Router:
```
router = routers.SimpleRouter(trailing_slash=False)
router.register(r'myobjects', MyObjectViewSet, base_name='myobjects')
urlpatterns = router.urls
```
ViewSet
```
class MyObjectsViewSet(viewsets.ViewSet):
""" Provides API Methods to manage MyObjects. """
def list(self, request):
""" Returns a list of MyObjects. """
data = get_list_of_myobjects()
return Response(data)
def retrieve(self, request, pk):
""" Returns a single MyObject. """
data = fetch_my_object(pk)
return Response(data)
def destroy(self, request, pk):
""" Deletes a single MyObject. """
fetch_my_object_and_delete(pk)
return Response()
```
One example of another method type I need to include. (There are many of these):
```
def get_locations(self, request):
""" Returns a list of location objects somehow related to MyObject """
locations = calculate_something()
return Response(locations)
```
The end-result is that the following URL would work correctly and be implemented 'cleanly'.
```
GET example.com/myobjects/123/locations
``` | 2013/09/23 | [
"https://Stackoverflow.com/questions/18969798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485900/"
] | The [answer given by mariodev](https://stackoverflow.com/a/18970651/3216056) above is correct, as long as you're only looking to make `GET` requests.
If you want to `POST` to a function you're appending to a ViewSet, you need to use the `action` decorator:
```
from rest_framework.decorators import action, link
from rest_framework.response import Response
class MyObjectsViewSet(viewsets.ViewSet):
# For GET Requests
@link()
def get_locations(self, request):
""" Returns a list of location objects somehow related to MyObject """
locations = calculate_something()
return Response(locations)
# For POST Requests
@action()
def update_location(self, request, pk):
""" Updates the object identified by the pk """
location = self.get_object()
location.field = update_location_field() # your custom code
location.save()
# ...create a serializer and return with updated data...
```
Then you would `POST` to a URL formatted like:
`/myobjects/123/update_location/`
<http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing> has more information if you're interested! | You define method like you do now, but you need to use the same url as method name and add link decorator, so for
```
/myobjects/123/locations/
```
You add method like this
```
@link(permission_classes=[...])
def locations(self, request, pk=None):
...
```
and router will pick it automatically. |
18,969,798 | Essentially, I'm trying to find a good way to attach more views to a Router without creating a custom Router. **What's a good way to accomplish this?**
Here is something sort of equivalent to what I'm trying to accomplish. Variable names have been changed and the example method I want to introduce is extremely simplified for the sake of this question.
Router:
```
router = routers.SimpleRouter(trailing_slash=False)
router.register(r'myobjects', MyObjectViewSet, base_name='myobjects')
urlpatterns = router.urls
```
ViewSet
```
class MyObjectsViewSet(viewsets.ViewSet):
""" Provides API Methods to manage MyObjects. """
def list(self, request):
""" Returns a list of MyObjects. """
data = get_list_of_myobjects()
return Response(data)
def retrieve(self, request, pk):
""" Returns a single MyObject. """
data = fetch_my_object(pk)
return Response(data)
def destroy(self, request, pk):
""" Deletes a single MyObject. """
fetch_my_object_and_delete(pk)
return Response()
```
One example of another method type I need to include. (There are many of these):
```
def get_locations(self, request):
""" Returns a list of location objects somehow related to MyObject """
locations = calculate_something()
return Response(locations)
```
The end-result is that the following URL would work correctly and be implemented 'cleanly'.
```
GET example.com/myobjects/123/locations
``` | 2013/09/23 | [
"https://Stackoverflow.com/questions/18969798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485900/"
] | You can now do this with the list\_route and detail\_route decorators: <http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing>
For example:
```
from rest_framework.decorators import list_route
from rest_framework.response import Response
...
class MyObjectsViewSet(viewsets.ViewSet):
...
@list_route()
def locations(self, request):
queryset = get_locations()
serializer = LocationSerializer(queryset, many=True)
return Response(serializer.data)
``` | You define method like you do now, but you need to use the same url as method name and add link decorator, so for
```
/myobjects/123/locations/
```
You add method like this
```
@link(permission_classes=[...])
def locations(self, request, pk=None):
...
```
and router will pick it automatically. |
18,969,798 | Essentially, I'm trying to find a good way to attach more views to a Router without creating a custom Router. **What's a good way to accomplish this?**
Here is something sort of equivalent to what I'm trying to accomplish. Variable names have been changed and the example method I want to introduce is extremely simplified for the sake of this question.
Router:
```
router = routers.SimpleRouter(trailing_slash=False)
router.register(r'myobjects', MyObjectViewSet, base_name='myobjects')
urlpatterns = router.urls
```
ViewSet
```
class MyObjectsViewSet(viewsets.ViewSet):
""" Provides API Methods to manage MyObjects. """
def list(self, request):
""" Returns a list of MyObjects. """
data = get_list_of_myobjects()
return Response(data)
def retrieve(self, request, pk):
""" Returns a single MyObject. """
data = fetch_my_object(pk)
return Response(data)
def destroy(self, request, pk):
""" Deletes a single MyObject. """
fetch_my_object_and_delete(pk)
return Response()
```
One example of another method type I need to include. (There are many of these):
```
def get_locations(self, request):
""" Returns a list of location objects somehow related to MyObject """
locations = calculate_something()
return Response(locations)
```
The end-result is that the following URL would work correctly and be implemented 'cleanly'.
```
GET example.com/myobjects/123/locations
``` | 2013/09/23 | [
"https://Stackoverflow.com/questions/18969798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485900/"
] | You define method like you do now, but you need to use the same url as method name and add link decorator, so for
```
/myobjects/123/locations/
```
You add method like this
```
@link(permission_classes=[...])
def locations(self, request, pk=None):
...
```
and router will pick it automatically. | If you want to extend a viewset with a view that is or should not directly be written inside your viewset, you can write a “wrapper” action to pass the data through.
For example, with class based views:
```py
from somewhere import YourExternalClassView
class SomeViewSet(viewsets.ReadOnlyModelViewSet):
# ...
@action(detail=True)
def your_action(self, request, pk):
return YourExternalClassView.as_view()(request, pk=pk)
```
How does it work?
-----------------
On class based views, the `as_view` method returns a view function, to which we will pass the data we received from the action. The view will then hand over to process further.
For non-class based view, the views can be called/wrapped directly without `.as_view(...)(...)`. |
18,969,798 | Essentially, I'm trying to find a good way to attach more views to a Router without creating a custom Router. **What's a good way to accomplish this?**
Here is something sort of equivalent to what I'm trying to accomplish. Variable names have been changed and the example method I want to introduce is extremely simplified for the sake of this question.
Router:
```
router = routers.SimpleRouter(trailing_slash=False)
router.register(r'myobjects', MyObjectViewSet, base_name='myobjects')
urlpatterns = router.urls
```
ViewSet
```
class MyObjectsViewSet(viewsets.ViewSet):
""" Provides API Methods to manage MyObjects. """
def list(self, request):
""" Returns a list of MyObjects. """
data = get_list_of_myobjects()
return Response(data)
def retrieve(self, request, pk):
""" Returns a single MyObject. """
data = fetch_my_object(pk)
return Response(data)
def destroy(self, request, pk):
""" Deletes a single MyObject. """
fetch_my_object_and_delete(pk)
return Response()
```
One example of another method type I need to include. (There are many of these):
```
def get_locations(self, request):
""" Returns a list of location objects somehow related to MyObject """
locations = calculate_something()
return Response(locations)
```
The end-result is that the following URL would work correctly and be implemented 'cleanly'.
```
GET example.com/myobjects/123/locations
``` | 2013/09/23 | [
"https://Stackoverflow.com/questions/18969798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485900/"
] | The [answer given by mariodev](https://stackoverflow.com/a/18970651/3216056) above is correct, as long as you're only looking to make `GET` requests.
If you want to `POST` to a function you're appending to a ViewSet, you need to use the `action` decorator:
```
from rest_framework.decorators import action, link
from rest_framework.response import Response
class MyObjectsViewSet(viewsets.ViewSet):
# For GET Requests
@link()
def get_locations(self, request):
""" Returns a list of location objects somehow related to MyObject """
locations = calculate_something()
return Response(locations)
# For POST Requests
@action()
def update_location(self, request, pk):
""" Updates the object identified by the pk """
location = self.get_object()
location.field = update_location_field() # your custom code
location.save()
# ...create a serializer and return with updated data...
```
Then you would `POST` to a URL formatted like:
`/myobjects/123/update_location/`
<http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing> has more information if you're interested! | From [Routing to extra methods on a ViewSet](https://groups.google.com/forum/#!msg/django-rest-framework/naTNAxw4jws/nue_fhS5vI4J):
>
> I think you may need to route the method by hand, i.e. The Old-Fashioned Way™.
>
>
> First pull the method out as a separate view:
>
>
>
> ```
> set_password_view = UserViewSet.as_view({'post': 'set_password'})
>
> ```
>
> (or such)
>
>
> Then assign your URL:
>
>
>
> ```
> url(r'^users/username_available/$', set_password_view, name-=...)
>
> ```
>
> (Or such)
>
>
>
There's a [related question on SO](https://stackoverflow.com/q/18194603/4794). |
18,969,798 | Essentially, I'm trying to find a good way to attach more views to a Router without creating a custom Router. **What's a good way to accomplish this?**
Here is something sort of equivalent to what I'm trying to accomplish. Variable names have been changed and the example method I want to introduce is extremely simplified for the sake of this question.
Router:
```
router = routers.SimpleRouter(trailing_slash=False)
router.register(r'myobjects', MyObjectViewSet, base_name='myobjects')
urlpatterns = router.urls
```
ViewSet
```
class MyObjectsViewSet(viewsets.ViewSet):
""" Provides API Methods to manage MyObjects. """
def list(self, request):
""" Returns a list of MyObjects. """
data = get_list_of_myobjects()
return Response(data)
def retrieve(self, request, pk):
""" Returns a single MyObject. """
data = fetch_my_object(pk)
return Response(data)
def destroy(self, request, pk):
""" Deletes a single MyObject. """
fetch_my_object_and_delete(pk)
return Response()
```
One example of another method type I need to include. (There are many of these):
```
def get_locations(self, request):
""" Returns a list of location objects somehow related to MyObject """
locations = calculate_something()
return Response(locations)
```
The end-result is that the following URL would work correctly and be implemented 'cleanly'.
```
GET example.com/myobjects/123/locations
``` | 2013/09/23 | [
"https://Stackoverflow.com/questions/18969798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485900/"
] | You can now do this with the list\_route and detail\_route decorators: <http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing>
For example:
```
from rest_framework.decorators import list_route
from rest_framework.response import Response
...
class MyObjectsViewSet(viewsets.ViewSet):
...
@list_route()
def locations(self, request):
queryset = get_locations()
serializer = LocationSerializer(queryset, many=True)
return Response(serializer.data)
``` | From [Routing to extra methods on a ViewSet](https://groups.google.com/forum/#!msg/django-rest-framework/naTNAxw4jws/nue_fhS5vI4J):
>
> I think you may need to route the method by hand, i.e. The Old-Fashioned Way™.
>
>
> First pull the method out as a separate view:
>
>
>
> ```
> set_password_view = UserViewSet.as_view({'post': 'set_password'})
>
> ```
>
> (or such)
>
>
> Then assign your URL:
>
>
>
> ```
> url(r'^users/username_available/$', set_password_view, name-=...)
>
> ```
>
> (Or such)
>
>
>
There's a [related question on SO](https://stackoverflow.com/q/18194603/4794). |
18,969,798 | Essentially, I'm trying to find a good way to attach more views to a Router without creating a custom Router. **What's a good way to accomplish this?**
Here is something sort of equivalent to what I'm trying to accomplish. Variable names have been changed and the example method I want to introduce is extremely simplified for the sake of this question.
Router:
```
router = routers.SimpleRouter(trailing_slash=False)
router.register(r'myobjects', MyObjectViewSet, base_name='myobjects')
urlpatterns = router.urls
```
ViewSet
```
class MyObjectsViewSet(viewsets.ViewSet):
""" Provides API Methods to manage MyObjects. """
def list(self, request):
""" Returns a list of MyObjects. """
data = get_list_of_myobjects()
return Response(data)
def retrieve(self, request, pk):
""" Returns a single MyObject. """
data = fetch_my_object(pk)
return Response(data)
def destroy(self, request, pk):
""" Deletes a single MyObject. """
fetch_my_object_and_delete(pk)
return Response()
```
One example of another method type I need to include. (There are many of these):
```
def get_locations(self, request):
""" Returns a list of location objects somehow related to MyObject """
locations = calculate_something()
return Response(locations)
```
The end-result is that the following URL would work correctly and be implemented 'cleanly'.
```
GET example.com/myobjects/123/locations
``` | 2013/09/23 | [
"https://Stackoverflow.com/questions/18969798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485900/"
] | From [Routing to extra methods on a ViewSet](https://groups.google.com/forum/#!msg/django-rest-framework/naTNAxw4jws/nue_fhS5vI4J):
>
> I think you may need to route the method by hand, i.e. The Old-Fashioned Way™.
>
>
> First pull the method out as a separate view:
>
>
>
> ```
> set_password_view = UserViewSet.as_view({'post': 'set_password'})
>
> ```
>
> (or such)
>
>
> Then assign your URL:
>
>
>
> ```
> url(r'^users/username_available/$', set_password_view, name-=...)
>
> ```
>
> (Or such)
>
>
>
There's a [related question on SO](https://stackoverflow.com/q/18194603/4794). | If you want to extend a viewset with a view that is or should not directly be written inside your viewset, you can write a “wrapper” action to pass the data through.
For example, with class based views:
```py
from somewhere import YourExternalClassView
class SomeViewSet(viewsets.ReadOnlyModelViewSet):
# ...
@action(detail=True)
def your_action(self, request, pk):
return YourExternalClassView.as_view()(request, pk=pk)
```
How does it work?
-----------------
On class based views, the `as_view` method returns a view function, to which we will pass the data we received from the action. The view will then hand over to process further.
For non-class based view, the views can be called/wrapped directly without `.as_view(...)(...)`. |
18,969,798 | Essentially, I'm trying to find a good way to attach more views to a Router without creating a custom Router. **What's a good way to accomplish this?**
Here is something sort of equivalent to what I'm trying to accomplish. Variable names have been changed and the example method I want to introduce is extremely simplified for the sake of this question.
Router:
```
router = routers.SimpleRouter(trailing_slash=False)
router.register(r'myobjects', MyObjectViewSet, base_name='myobjects')
urlpatterns = router.urls
```
ViewSet
```
class MyObjectsViewSet(viewsets.ViewSet):
""" Provides API Methods to manage MyObjects. """
def list(self, request):
""" Returns a list of MyObjects. """
data = get_list_of_myobjects()
return Response(data)
def retrieve(self, request, pk):
""" Returns a single MyObject. """
data = fetch_my_object(pk)
return Response(data)
def destroy(self, request, pk):
""" Deletes a single MyObject. """
fetch_my_object_and_delete(pk)
return Response()
```
One example of another method type I need to include. (There are many of these):
```
def get_locations(self, request):
""" Returns a list of location objects somehow related to MyObject """
locations = calculate_something()
return Response(locations)
```
The end-result is that the following URL would work correctly and be implemented 'cleanly'.
```
GET example.com/myobjects/123/locations
``` | 2013/09/23 | [
"https://Stackoverflow.com/questions/18969798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485900/"
] | The [answer given by mariodev](https://stackoverflow.com/a/18970651/3216056) above is correct, as long as you're only looking to make `GET` requests.
If you want to `POST` to a function you're appending to a ViewSet, you need to use the `action` decorator:
```
from rest_framework.decorators import action, link
from rest_framework.response import Response
class MyObjectsViewSet(viewsets.ViewSet):
# For GET Requests
@link()
def get_locations(self, request):
""" Returns a list of location objects somehow related to MyObject """
locations = calculate_something()
return Response(locations)
# For POST Requests
@action()
def update_location(self, request, pk):
""" Updates the object identified by the pk """
location = self.get_object()
location.field = update_location_field() # your custom code
location.save()
# ...create a serializer and return with updated data...
```
Then you would `POST` to a URL formatted like:
`/myobjects/123/update_location/`
<http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing> has more information if you're interested! | You can now do this with the list\_route and detail\_route decorators: <http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing>
For example:
```
from rest_framework.decorators import list_route
from rest_framework.response import Response
...
class MyObjectsViewSet(viewsets.ViewSet):
...
@list_route()
def locations(self, request):
queryset = get_locations()
serializer = LocationSerializer(queryset, many=True)
return Response(serializer.data)
``` |
18,969,798 | Essentially, I'm trying to find a good way to attach more views to a Router without creating a custom Router. **What's a good way to accomplish this?**
Here is something sort of equivalent to what I'm trying to accomplish. Variable names have been changed and the example method I want to introduce is extremely simplified for the sake of this question.
Router:
```
router = routers.SimpleRouter(trailing_slash=False)
router.register(r'myobjects', MyObjectViewSet, base_name='myobjects')
urlpatterns = router.urls
```
ViewSet
```
class MyObjectsViewSet(viewsets.ViewSet):
""" Provides API Methods to manage MyObjects. """
def list(self, request):
""" Returns a list of MyObjects. """
data = get_list_of_myobjects()
return Response(data)
def retrieve(self, request, pk):
""" Returns a single MyObject. """
data = fetch_my_object(pk)
return Response(data)
def destroy(self, request, pk):
""" Deletes a single MyObject. """
fetch_my_object_and_delete(pk)
return Response()
```
One example of another method type I need to include. (There are many of these):
```
def get_locations(self, request):
""" Returns a list of location objects somehow related to MyObject """
locations = calculate_something()
return Response(locations)
```
The end-result is that the following URL would work correctly and be implemented 'cleanly'.
```
GET example.com/myobjects/123/locations
``` | 2013/09/23 | [
"https://Stackoverflow.com/questions/18969798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485900/"
] | The [answer given by mariodev](https://stackoverflow.com/a/18970651/3216056) above is correct, as long as you're only looking to make `GET` requests.
If you want to `POST` to a function you're appending to a ViewSet, you need to use the `action` decorator:
```
from rest_framework.decorators import action, link
from rest_framework.response import Response
class MyObjectsViewSet(viewsets.ViewSet):
# For GET Requests
@link()
def get_locations(self, request):
""" Returns a list of location objects somehow related to MyObject """
locations = calculate_something()
return Response(locations)
# For POST Requests
@action()
def update_location(self, request, pk):
""" Updates the object identified by the pk """
location = self.get_object()
location.field = update_location_field() # your custom code
location.save()
# ...create a serializer and return with updated data...
```
Then you would `POST` to a URL formatted like:
`/myobjects/123/update_location/`
<http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing> has more information if you're interested! | If you want to extend a viewset with a view that is or should not directly be written inside your viewset, you can write a “wrapper” action to pass the data through.
For example, with class based views:
```py
from somewhere import YourExternalClassView
class SomeViewSet(viewsets.ReadOnlyModelViewSet):
# ...
@action(detail=True)
def your_action(self, request, pk):
return YourExternalClassView.as_view()(request, pk=pk)
```
How does it work?
-----------------
On class based views, the `as_view` method returns a view function, to which we will pass the data we received from the action. The view will then hand over to process further.
For non-class based view, the views can be called/wrapped directly without `.as_view(...)(...)`. |
18,969,798 | Essentially, I'm trying to find a good way to attach more views to a Router without creating a custom Router. **What's a good way to accomplish this?**
Here is something sort of equivalent to what I'm trying to accomplish. Variable names have been changed and the example method I want to introduce is extremely simplified for the sake of this question.
Router:
```
router = routers.SimpleRouter(trailing_slash=False)
router.register(r'myobjects', MyObjectViewSet, base_name='myobjects')
urlpatterns = router.urls
```
ViewSet
```
class MyObjectsViewSet(viewsets.ViewSet):
""" Provides API Methods to manage MyObjects. """
def list(self, request):
""" Returns a list of MyObjects. """
data = get_list_of_myobjects()
return Response(data)
def retrieve(self, request, pk):
""" Returns a single MyObject. """
data = fetch_my_object(pk)
return Response(data)
def destroy(self, request, pk):
""" Deletes a single MyObject. """
fetch_my_object_and_delete(pk)
return Response()
```
One example of another method type I need to include. (There are many of these):
```
def get_locations(self, request):
""" Returns a list of location objects somehow related to MyObject """
locations = calculate_something()
return Response(locations)
```
The end-result is that the following URL would work correctly and be implemented 'cleanly'.
```
GET example.com/myobjects/123/locations
``` | 2013/09/23 | [
"https://Stackoverflow.com/questions/18969798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485900/"
] | You can now do this with the list\_route and detail\_route decorators: <http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing>
For example:
```
from rest_framework.decorators import list_route
from rest_framework.response import Response
...
class MyObjectsViewSet(viewsets.ViewSet):
...
@list_route()
def locations(self, request):
queryset = get_locations()
serializer = LocationSerializer(queryset, many=True)
return Response(serializer.data)
``` | If you want to extend a viewset with a view that is or should not directly be written inside your viewset, you can write a “wrapper” action to pass the data through.
For example, with class based views:
```py
from somewhere import YourExternalClassView
class SomeViewSet(viewsets.ReadOnlyModelViewSet):
# ...
@action(detail=True)
def your_action(self, request, pk):
return YourExternalClassView.as_view()(request, pk=pk)
```
How does it work?
-----------------
On class based views, the `as_view` method returns a view function, to which we will pass the data we received from the action. The view will then hand over to process further.
For non-class based view, the views can be called/wrapped directly without `.as_view(...)(...)`. |
34,904,191 | Is there a way of passing a function to another function and then executing it?
```
functionCaller(functionToBeCalled());
``` | 2016/01/20 | [
"https://Stackoverflow.com/questions/34904191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5058429/"
] | Double.MIN\_VALUE:
A constant holding the smallest positive nonzero value of type double.
Double.MAX\_VALUE:
A constant holding the largest positive finite value of type double.
You can check here for more details: <https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html> | For `double highest = Double.MIN_VALUE;`, instead use `-Double.MAX_VALUE`. Note the '-' sign.
And for :
```
if (num > highest)
{
highest = num;
}
```
Use:
```
highest = Math.max(highest, num)
lowest = Math.min(lowest, num)
``` |
65,557,020 | I learned I can use [:hover:after](https://stackoverflow.com/a/13234028/667903) so I tried it myself, however it is not working:
```css
.img-shadow img:hover:after {
-webkit-box-shadow: inset 10px 10px 10px 0px rgba(0,0,0,0.75);
-moz-box-shadow: inset 10px 10px 10px 0px rgba(0,0,0,0.75);
box-shadow: inset 10px 10px 10px 0px rgba(0,0,0,0.75);
}
```
```html
<div class="wpb_single_image wpb_content_element vc_align_left img-shadow">
<figure class="wpb_wrapper vc_figure">
<a href="#"><img width="100%" height="auto" src="http://dev.watmar.com.au/wp-content/uploads/2020/10/Power_generation.jpg"></a>
</figure>
</div>
``` | 2021/01/04 | [
"https://Stackoverflow.com/questions/65557020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/667903/"
] | By default, `dotnet publish` publishes the entire application for running on the current operating system. When that does not match where you intend to run the application you can specify the runtime to publish for with `-r|--runtime`.
Something like this should work: `dotnet publish -r linux-x64` | A 403 error would lie somewhere in the IIS/web server configuration. Look at the config file or the IIS settings. |
27,726,430 | ```
pyg = 'ay'
original = raw_input('Enter a word:')
word = original.lower()
first = word[0]
if len(original) > 0 and original.isalpha():
print original
else:
print 'empty'
new_word = word[1:]
print new_word + first + pyg
```
^ the above code is something I've tried on codeacademy as Im at a beginners level.I'm supposed to set new\_word equal to the slice from the 1st index all the way to the end of new\_word using [1:len(new\_word)] to do this. So if I entered 'hart', it should print 'arthay'.
It won't let me proceed onto the next level until I set new\_word equal to the slice as well.
I'm confused as to how to go about doing this. Any help would be appreciated. Thanks! | 2014/12/31 | [
"https://Stackoverflow.com/questions/27726430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4117165/"
] | For Android API 21 and above, just use:
```
Os.symlink(originalFilePath,symLinkFilePath);
``` | There is no public API to do this. You can however use some dirty reflection to create your symbolic link. I just tested the following code and it worked for me:
```
// static factory method to transfer a file from assets to package files directory
AssetUtils.transferAsset(this, "test.png");
// The file that was transferred
File file = new File(getFilesDir(), "test.png");
// The file that I want as my symlink
File symlink = new File(getFilesDir(), "symlink.png");
// do some dirty reflection to create the symbolic link
try {
final Class<?> libcore = Class.forName("libcore.io.Libcore");
final Field fOs = libcore.getDeclaredField("os");
fOs.setAccessible(true);
final Object os = fOs.get(null);
final Method method = os.getClass().getMethod("symlink", String.class, String.class);
method.invoke(os, file.getAbsolutePath(), symlink.getAbsolutePath());
} catch (Exception e) {
// TODO handle the exception
}
```
A quick Google search showed this answer if you don't want to use reflection: <http://androidwarzone.blogspot.com/2012/03/creating-symbolic-links-on-android-from.html> |
57,782 | Mathematica won't change a number's BaseForm recursively:
```
63969 // BaseForm[#, 16] & // BaseForm[#, 8] & // BaseForm[#, 2] &
```
Well, I inspected former answers, most of them treated formatting problems, but none of the anwers given treated the nestable aspect. Maybe I'm wrong, and I risk a duplicate.
(1) I would like to have a nestable function which allows constructs of the form
```
63969 // base@16 // base@8 // base@2
```
This feature might be adopted advantageously within iterative functions : NestList, FoldList, ...
---
Edit1
-----
To explain my interest for seamless changes of baseforms
```
2 ArcCot[GoldenRatio^2^^1111] == ArcCot[2^^1010101010]
2^^1010101010 // BaseForm[#, 4] &
```

---
Edit2
-----
I tried myself another approch, but it has an disadvantage: `HoldForm` isn't respected
```
ClearAll@base
base[b_] := Function[# // ReplaceAll[#, BaseForm[x_, _] :> BaseForm[x, 10]] & //
ToString // ToExpression // BaseForm[#, b] &]
testsuite = {5555, BaseForm[5555, 8], HoldForm@Plus[5000, 555],5*BaseForm[1111, 2]}
base@10 /@ testsuite
``` | 2014/08/20 | [
"https://mathematica.stackexchange.com/questions/57782",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/16373/"
] | There is a useful attribute, `NHoldFirst` whose purpose is to protect the function from exactly that. So setting:
```
SetAttributes[a, NHoldFirst];
```
and then evaluating the integral works the way you want:
```
Integrate[(a[1] + x)^2, {x, 1., 2.}]
(*2.33333 + 3. a[1] + 1. a[1]^2*)
```
The relevant example from the documentation cites "indexed" functions that are otherwise evaluated numerically (spherical harmonics, elliptic etc) but whose first argument needs to stay an integer.
As per Michael E2's comment, if you want to protect more than just the first of your function's arguments from `N` then `NHoldAll` is the attribute you need. | First, I did not get same result as your answer. I got numerical values in all terms.
```
int = Integrate[(a[1] + x)^2, {x, 1., b}]
```
MMA 9:
```
(* -0.333333 + 0.333333 b^3 - 1. a[1.] + 1. b^2 a[1.] - 1. a[1.]^2 +
1. b a[1.]^2 + 5.55112*10^-17 a[1.]^3 *)
```
MMA 10:
```
(*-0.333333 (1. + a[1.])^3 + 0.333333 (b + a[1.])^3*)
```
(Note: if you expand result from MMA 10, the last term in result of MMA 9 vanish)
in both cases if I use Rationalize, here is what I got:
```
Rationalize[int]
```
MMA 9
```
(*-0.333333 + b^3/3 - 1. a[1] + b^2 a[1] - 1. a[1]^2 + b a[1]^2 +
5.55112*10^-17 a[1]^3*)
```
MMA 10:
```
(*-(1/3) (1 + a[1])^3 + 1/3 (b + a[1])^3*)
```
(Note: quit interesting to see that MMA 10 can give more accurate and compact form result as compare to MMA 9) |
10,439,948 | i have this testing code which am working with ..
i have a module called `ms` and and another one called `test`
the `test` controller code is :
```
<?php
class Test extends MX_Controller {
public function __construct()
{
parent::__construct();
$this->template->title($this->config->item('site_name','app'));
}
public function index()
{
$this->template->build('index');
}
}
```
and the code inside `ms` is :
```
<?php
//ms module
class Msrofi extends MX_Controller {
public function __construct()
{
parent::__construct();
$this->template->title($this->config->item('site_name','app'));
}
public function index()
{
$t = Modules::run('test/test/index');
var_dump($t);
$this->template->build('index_message');
}
}
```
the problem is that the build function inside `test` is trying to find the `index` view file inside the `ms` views folder not the `test` views folder ..
i checked the `$this->_module` and it gave me the `ms` module name ..
any one know how to fix that ?? | 2012/05/03 | [
"https://Stackoverflow.com/questions/10439948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013493/"
] | Since the `test` module is being called in the context of the `ms` one, `$this->template->build()` is looking for a view file in the `ms` module. The same way you can load models and libraries cross-module, you would have to do this for your view path as well:
```
class Test extends MX_Controller {
public function index()
{
// This path works only from the "test" module
// $this->template->build('index');
// This path works from any module
$this->template->build('test/index');
}
}
```
It's a little annoying maybe to have to explicitly call the module path in the module itself, but cross-module dependency defeat some of the goals of modularity in the first place.
A quick aside: `Modules::run()` output not returned, but directly echoed, so you can't assign it to a variable or `print_r`/`var_dump` it without using an output buffer:
```
ob_start();
Modules::run('test/test/index');
$t = ob_get_clean();
var_dump($t);
``` | You can try to change the module.php the run method
The following example is I have to use the fix solution:
1. Open the third\_party/MX/Modules.php
2. Near 75 lines to find
$buffer = ob\_get\_clean();
3. Increase in its following:
if($output === NULL && $buffer === ''){
$output = CI::$APP->output->get\_output();
}
At this time, it should be able to work properly... |
4,106,035 | Let $A\_1, \dots , A\_n$ be commutative unitary Rings and $A = \prod\_{i=1}^{n} A\_i$.
Then every prime Ideal $\frak{p}$ $\subset A$ is of the form $\pi\_i^{-1}(\frak{p}\_i)$ where $\pi\_i: A \to A\_i$ are the canonical projections and $\frak{p\_i}$ $\subset A\_i$ is prime.
I know that every Ideal in $A$ is a direct product of Ideals in the $A\_i$, so we have $\frak{p}$ $= \frak{a}\_i \times \dots \times \frak{a}\_n$ for some Ideals $\frak{a}\_i$ $\subset A\_i$. They are also prime since $\frak{p}$ is prime. Now, since the $\pi\_i$ are surjective $\pi\_i(\frak{p})$ $\subset A\_i$ is prime as well. Then we have $\pi\_i^{-1}(\pi\_i(\frak{p})) \supset \frak{p}$. Now I don't know how to finish the proof.
Hints and/or improvements are greatly appreciated! | 2021/04/17 | [
"https://math.stackexchange.com/questions/4106035",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/697395/"
] | You can derive the proof from the following facts:
1. An ideal $\mathfrak{a} \subseteq A$ is prime iff $A/\mathfrak{a}$ is an integral domain.
2. There is an isomorphism of rings $(\prod\_i A\_i) / (\prod\_i \mathfrak{a}\_i) \cong \prod\_i A\_i / \mathfrak{a\_i}$
3. A product $\prod\_i A\_i$ is an integral domain iff $A\_i=0$ for all indices $i$ except for exactly one index $j$, and for this index $A\_j$ is an integral domain. | Assume $\mathfrak a\_i\neq A\_i,\mathfrak a\_j\neq A\_j$ for $i\neq j.$ Then $1\_i\in A\_i\setminus \mathfrak a\_i$ and $1\_j\in A\_j\setminus \mathfrak a\_j.$
Define $a=(a\_k)\_{k=1}^n,b=(b\_k)\_{k=1}^n\in A$ as:
$$a\_k=\begin{cases}0&k\neq i\\
1\_i&k=i
\end{cases}$$
$$b\_k=\begin{cases}0&k\neq j\\
1\_j&k=j
\end{cases}$$
Then $ab=0\in\mathfrak p,$ but neither $a$ nor $b$ is in $\mathfrak p,$ so $\mathfrak p$ is not prime.
So if $\mathfrak p=\prod \mathfrak a\_i$ is a prime ideal, then $\mathfrak a\_i=A\_i$ must be true for all but one $i.$ |
3,922,083 | Is there any Applescript available that sends either an URL or array of images as attachment of the mail through Mac Office 2011? | 2010/10/13 | [
"https://Stackoverflow.com/questions/3922083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/474228/"
] | Also see:
MS Outlook 2011 sp1 V14.1.0 changes the apple script dictionary..
<http://www.officeformachelp.com/2011/04/microsoft-updates-applescript-dictionary-for-outlook-2011-sp1/>
also:
run send all -- forces mail in out box to be sent right now | Seeing as how Office 2011 is very new, I'd be surprised you'll find ready-made code to use outside of an example script given with Office. [This is where the Dictionary comes in; the Dictionary tells you everything that an application responds to, what objects can be manipulated, etc.](https://stackoverflow.com/questions/3430313/determining-what-applescript-commands-an-application-responds-to) When scripting an application for the first time, the Dictionary will always be the first thing you look at.
What you are asking doesn't seem like it would be too hard figure out even for someone who is new to Applescript.
**UPDATE:** Here is *teh codez* for Entourage 2008. I would imagine that v2011 wouldn't stray too much from this because it is very straightforward:
```
tell application "Microsoft Entourage"
set newMessage to make new outgoing message with properties {subject:"New Outgoing Message Subject", recipient:"email@domain.com", content:"Message Body", attachment:{pathToFile1, pathToFile2}}
end tell
--> RESULT: A new message appears in the Outbox with the content placed
``` |
169,712 | I'm writing a package which, among other things, gives abbreviations for `\mathbb`, as follows:
```
\newcommand{\A}{\mathbb A}
\def\B{\mathbb B}
\def\C{\mathbb C}
\newcommand{\D}{\mathbb D}
\newcommand{\E}{\mathbb E}
\newcommand{\F}{\mathbb F}
\def\G{\mathbb G}
\def\H{\mathbb H}
\newcommand{\I}{\mathbb I}
\newcommand{\J}{\mathbb J}
\newcommand{\K}{\mathbb K}
\def\L{\mathbb L}
\def\M{\mathbb M}
\newcommand{\N}{\mathbb N}
\def\O{\mathbb O}
\def\P{\mathbb P}
\newcommand{\Q}{\mathbb Q}
\newcommand{\R}{\mathbb R}
\def\S{\mathbb S}
\def\T{\mathbb T}
\def\U{\mathbb U}
\newcommand{\V}{\mathbb V}
\newcommand{\W}{\mathbb W}
\newcommand{\X}{\mathbb X}
\newcommand{\Y}{\mathbb Y}
\newcommand{\Z}{\mathbb Z}
\DeclareSymbolFont{bbold}{U}{bbold}{m}{n}
\DeclareSymbolFontAlphabet{\bb}{bbold}
```
The reason for the `\def`-`\newcommand` oscillation is that I have seen some of those commands are not always defined, so choosing `\newcommand` would give problems in some cases while `\renewcommand` would in others, while `\def` bypasses this by not checking if the commands are defined or not. The strange thing which this question is about is that removing the braces from the `\def`s (e.g. in `\def\B{\mathbb B}` removing those around `\mathbb B`, and similarly from all the other `\def` commands) seems to cause problems. For example, removing them all except those of `\B` and `\C` causes:
```
./mworks.sty:844: LaTeX Error: \mathbb allowed only in math mode.
See LaTeX manual or LaTeX Companion for explanation.
Type G <return> for immediate help.
...
1.844 \newcommand{\I}{\mathbb
I}
?
```
Why does that happen? | 2014/04/05 | [
"https://tex.stackexchange.com/questions/169712",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/42315/"
] | You have probably discovered why it's very strongly discouraged to redefine kernel commands with `\def`.
For instance, `\H` is defined to give the “hungarian umlaut” accent; so, if you are talking about Erdős in your document, you'll get a puzzling error, even if you seem not to be using `\H`. Actually when `\usepackage[utf8]{inputenc}` is in force, LaTeX translates `Erdős` into `Erd\H{o}s`. Can you see the problem?
***Don't redefine kernel commands*** unless you know precisely what you're doing. If `\newcommand` can't be used, you *must* check what the command means and, if it turns out to be a command for typesetting accents or similar things, *don't* redefine it.
It's also particularly bad is adding those commands in a package, even if it's for personal usage. If you pass it to your buddies, they'll start to use it and maybe include it in something they submit elsewhere. As Barbara Beeton observes in a comment,
>
> if a package like this gets submitted with a manuscript to a publisher, it can become very expensive to correct, and may result in rejection of the manuscript.
>
>
>
I should add that she is a great expert (*the* expert, perhaps) in copy editing for journals and books at the AMS.
You can try saying
```
\def\box#1{\fbox{#1}}
```
and see what happens.
Of course, the syntax
```
\def{\A}{\mathbb A}
```
is invalid: while `\newcommand{\A}{...}` is good, *no brace* can follow `\def`. Irremediably wrong is also
```
\def\B \mathbb B
```
which makes really no sense. By the way, the preferred syntax would be `\mathbb{B}` with braces that clearly delimit what `\mathbb` is applied to. | As the posted code doesn't generate the error shown, I'll modify it so it does.
This *complete* document demonstrates the error.
```
\RequirePackage{amsfonts}
\newcommand{\A}{\mathbb A}
\def\B{\mathbb B}
\def\C{\mathbb C}
\newcommand{\D}{\mathbb D}
\newcommand{\E}{\mathbb E}
\newcommand{\F}{\mathbb F}
\def\G{\mathbb G}
\def\H \mathbb H
\newcommand{\I}{\mathbb I}
\stop
```
it produces
```
$ pdflatex er11
This is pdfTeX, Version 3.1415926-2.5-1.40.14 (TeX Live 2013)
restricted \write18 enabled.
entering extended mode
(./er11.tex
LaTeX2e <2011/06/27>
Babel <3.9j> and hyphenation patterns for 54 languages loaded.
(/usr/local/texlive/2013/texmf-dist/tex/latex/amsfonts/amsfonts.sty)
! LaTeX Error: \mathbb allowed only in math mode.
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.10 \newcommand{\I}{\mathbb
I}
?
```
the immediate fix is to make it like the code posted in the question, or as egreg notes, better don't use one-letter commands and over-write LaTeX internals. |
67,255 | 
If it means watched, then I saw the check box is over there even though I selected unwatched column.
Does it mean downloaded? There is no tool tips and it's kind of silly to have 2 columns expressing the same thing.
The checkbox may means downloaded. What about the circle to the left of the checkboxes? | 2012/10/13 | [
"https://apple.stackexchange.com/questions/67255",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/23343/"
] | The checkbox is a tool for downloaded items to specify if you want that specific item to sync to your device. There is a setting in your iTunes device list to sync only checked items in iTunes:

If you have that setting turned on, unchecking any song or video will tell iTunes not to sync that item to your device during the next sync.
The circle is a progress indicator for downloaded items:
* A **filled circle** indicates that the item is **unplayed**.
* A **half circle** indicates that the item is **partially played**.
* **No circle** indicates that the item has been **played to completion**. | Check box is for you to check when you have completed a lesson. The circles gradually fill up as you complete the lesson. |
67,255 | 
If it means watched, then I saw the check box is over there even though I selected unwatched column.
Does it mean downloaded? There is no tool tips and it's kind of silly to have 2 columns expressing the same thing.
The checkbox may means downloaded. What about the circle to the left of the checkboxes? | 2012/10/13 | [
"https://apple.stackexchange.com/questions/67255",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/23343/"
] | The blue circle tells you how much of the media file your have played. A full circle means that it has never been played or has been marked as unplayed. A half circle means it has been partially played. No circle means it has been fully played.
As for the checkboxes, they are just for marking purposes and can have multiple functions. You can create a new playlist with the marked files, sync them to an iDevice, tell iTunes only to play marked files, etc.
Of course, a file you have not downloaded will not have a checkbox, as it does not exist on your computer. | Check box is for you to check when you have completed a lesson. The circles gradually fill up as you complete the lesson. |
67,255 | 
If it means watched, then I saw the check box is over there even though I selected unwatched column.
Does it mean downloaded? There is no tool tips and it's kind of silly to have 2 columns expressing the same thing.
The checkbox may means downloaded. What about the circle to the left of the checkboxes? | 2012/10/13 | [
"https://apple.stackexchange.com/questions/67255",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/23343/"
] | The checkbox is a tool for downloaded items to specify if you want that specific item to sync to your device. There is a setting in your iTunes device list to sync only checked items in iTunes:

If you have that setting turned on, unchecking any song or video will tell iTunes not to sync that item to your device during the next sync.
The circle is a progress indicator for downloaded items:
* A **filled circle** indicates that the item is **unplayed**.
* A **half circle** indicates that the item is **partially played**.
* **No circle** indicates that the item has been **played to completion**. | The blue circle tells you how much of the media file your have played. A full circle means that it has never been played or has been marked as unplayed. A half circle means it has been partially played. No circle means it has been fully played.
As for the checkboxes, they are just for marking purposes and can have multiple functions. You can create a new playlist with the marked files, sync them to an iDevice, tell iTunes only to play marked files, etc.
Of course, a file you have not downloaded will not have a checkbox, as it does not exist on your computer. |
43,196,636 | I have an example of a neural network with two layers. The first layer takes two arguments and has one output. The second should take one argument as result of the first layer and one additional argument. It should looks like this:
```
x1 x2 x3
\ / /
y1 /
\ /
y2
```
So, I'd created a model with two layers and tried to merge them but it returns an error: `The first layer in a Sequential model must get an "input_shape" or "batch_input_shape" argument.` on the line `result.add(merged)`.
Model:
```python
first = Sequential()
first.add(Dense(1, input_shape=(2,), activation='sigmoid'))
second = Sequential()
second.add(Dense(1, input_shape=(1,), activation='sigmoid'))
result = Sequential()
merged = Concatenate([first, second])
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
result.add(merged)
result.compile(optimizer=ada_grad, loss=_loss_tensor, metrics=['accuracy'])
``` | 2017/04/04 | [
"https://Stackoverflow.com/questions/43196636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/944000/"
] | You're getting the error because `result` defined as `Sequential()` is just a container for the model and you have not defined an input for it.
Given what you're trying to build set `result` to take the third input `x3`.
```python
first = Sequential()
first.add(Dense(1, input_shape=(2,), activation='sigmoid'))
second = Sequential()
second.add(Dense(1, input_shape=(1,), activation='sigmoid'))
third = Sequential()
# of course you must provide the input to result which will be your x3
third.add(Dense(1, input_shape=(1,), activation='sigmoid'))
# lets say you add a few more layers to first and second.
# concatenate them
merged = Concatenate([first, second])
# then concatenate the two outputs
result = Concatenate([merged, third])
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
result.compile(optimizer=ada_grad, loss='binary_crossentropy',
metrics=['accuracy'])
```
However, my preferred way of building a model that has this type of input structure would be to use the [functional api](https://keras.io/getting-started/functional-api-guide/).
Here is an implementation of your requirements to get you started:
```python
from keras.models import Model
from keras.layers import Concatenate, Dense, LSTM, Input, concatenate
from keras.optimizers import Adagrad
first_input = Input(shape=(2, ))
first_dense = Dense(1, )(first_input)
second_input = Input(shape=(2, ))
second_dense = Dense(1, )(second_input)
merge_one = concatenate([first_dense, second_dense])
third_input = Input(shape=(1, ))
merge_two = concatenate([merge_one, third_input])
model = Model(inputs=[first_input, second_input, third_input], outputs=merge_two)
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
model.compile(optimizer=ada_grad, loss='binary_crossentropy',
metrics=['accuracy'])
```
**To answer the question in the comments:**
1. How are result and merged connected? Assuming you mean how are they concatenated.
Concatenation works like this:
```python
a b c
a b c g h i a b c g h i
d e f j k l d e f j k l
```
i.e rows are just joined.
2. Now, `x1` is input to first, `x2` is input into second and `x3` input into third. | You can experiment with `model.summary()` (notice the concatenate\_XX (Concatenate) layer size)
```
# merge samples, two input must be same shape
inp1 = Input(shape=(10,32))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=0) # Merge data must same row column
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()
# merge row must same column size
inp1 = Input(shape=(20,10))
inp2 = Input(shape=(32,10))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()
# merge column must same row size
inp1 = Input(shape=(10,20))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()
```
You can view notebook here for detail:
<https://nbviewer.jupyter.org/github/anhhh11/DeepLearning/blob/master/Concanate_two_layer_keras.ipynb> |
43,196,636 | I have an example of a neural network with two layers. The first layer takes two arguments and has one output. The second should take one argument as result of the first layer and one additional argument. It should looks like this:
```
x1 x2 x3
\ / /
y1 /
\ /
y2
```
So, I'd created a model with two layers and tried to merge them but it returns an error: `The first layer in a Sequential model must get an "input_shape" or "batch_input_shape" argument.` on the line `result.add(merged)`.
Model:
```python
first = Sequential()
first.add(Dense(1, input_shape=(2,), activation='sigmoid'))
second = Sequential()
second.add(Dense(1, input_shape=(1,), activation='sigmoid'))
result = Sequential()
merged = Concatenate([first, second])
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
result.add(merged)
result.compile(optimizer=ada_grad, loss=_loss_tensor, metrics=['accuracy'])
``` | 2017/04/04 | [
"https://Stackoverflow.com/questions/43196636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/944000/"
] | You're getting the error because `result` defined as `Sequential()` is just a container for the model and you have not defined an input for it.
Given what you're trying to build set `result` to take the third input `x3`.
```python
first = Sequential()
first.add(Dense(1, input_shape=(2,), activation='sigmoid'))
second = Sequential()
second.add(Dense(1, input_shape=(1,), activation='sigmoid'))
third = Sequential()
# of course you must provide the input to result which will be your x3
third.add(Dense(1, input_shape=(1,), activation='sigmoid'))
# lets say you add a few more layers to first and second.
# concatenate them
merged = Concatenate([first, second])
# then concatenate the two outputs
result = Concatenate([merged, third])
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
result.compile(optimizer=ada_grad, loss='binary_crossentropy',
metrics=['accuracy'])
```
However, my preferred way of building a model that has this type of input structure would be to use the [functional api](https://keras.io/getting-started/functional-api-guide/).
Here is an implementation of your requirements to get you started:
```python
from keras.models import Model
from keras.layers import Concatenate, Dense, LSTM, Input, concatenate
from keras.optimizers import Adagrad
first_input = Input(shape=(2, ))
first_dense = Dense(1, )(first_input)
second_input = Input(shape=(2, ))
second_dense = Dense(1, )(second_input)
merge_one = concatenate([first_dense, second_dense])
third_input = Input(shape=(1, ))
merge_two = concatenate([merge_one, third_input])
model = Model(inputs=[first_input, second_input, third_input], outputs=merge_two)
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
model.compile(optimizer=ada_grad, loss='binary_crossentropy',
metrics=['accuracy'])
```
**To answer the question in the comments:**
1. How are result and merged connected? Assuming you mean how are they concatenated.
Concatenation works like this:
```python
a b c
a b c g h i a b c g h i
d e f j k l d e f j k l
```
i.e rows are just joined.
2. Now, `x1` is input to first, `x2` is input into second and `x3` input into third. | Adding to the above-accepted answer so that it helps those who are using `tensorflow 2.0`
```py
import tensorflow as tf
# some data
c1 = tf.constant([[1, 1, 1], [2, 2, 2]], dtype=tf.float32)
c2 = tf.constant([[2, 2, 2], [3, 3, 3]], dtype=tf.float32)
c3 = tf.constant([[3, 3, 3], [4, 4, 4]], dtype=tf.float32)
# bake layers x1, x2, x3
x1 = tf.keras.layers.Dense(10)(c1)
x2 = tf.keras.layers.Dense(10)(c2)
x3 = tf.keras.layers.Dense(10)(c3)
# merged layer y1
y1 = tf.keras.layers.Concatenate(axis=1)([x1, x2])
# merged layer y2
y2 = tf.keras.layers.Concatenate(axis=1)([y1, x3])
# print info
print("-"*30)
print("x1", x1.shape, "x2", x2.shape, "x3", x3.shape)
print("y1", y1.shape)
print("y2", y2.shape)
print("-"*30)
```
Result:
```
------------------------------
x1 (2, 10) x2 (2, 10) x3 (2, 10)
y1 (2, 20)
y2 (2, 30)
------------------------------
``` |
43,196,636 | I have an example of a neural network with two layers. The first layer takes two arguments and has one output. The second should take one argument as result of the first layer and one additional argument. It should looks like this:
```
x1 x2 x3
\ / /
y1 /
\ /
y2
```
So, I'd created a model with two layers and tried to merge them but it returns an error: `The first layer in a Sequential model must get an "input_shape" or "batch_input_shape" argument.` on the line `result.add(merged)`.
Model:
```python
first = Sequential()
first.add(Dense(1, input_shape=(2,), activation='sigmoid'))
second = Sequential()
second.add(Dense(1, input_shape=(1,), activation='sigmoid'))
result = Sequential()
merged = Concatenate([first, second])
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
result.add(merged)
result.compile(optimizer=ada_grad, loss=_loss_tensor, metrics=['accuracy'])
``` | 2017/04/04 | [
"https://Stackoverflow.com/questions/43196636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/944000/"
] | Adding to the above-accepted answer so that it helps those who are using `tensorflow 2.0`
```py
import tensorflow as tf
# some data
c1 = tf.constant([[1, 1, 1], [2, 2, 2]], dtype=tf.float32)
c2 = tf.constant([[2, 2, 2], [3, 3, 3]], dtype=tf.float32)
c3 = tf.constant([[3, 3, 3], [4, 4, 4]], dtype=tf.float32)
# bake layers x1, x2, x3
x1 = tf.keras.layers.Dense(10)(c1)
x2 = tf.keras.layers.Dense(10)(c2)
x3 = tf.keras.layers.Dense(10)(c3)
# merged layer y1
y1 = tf.keras.layers.Concatenate(axis=1)([x1, x2])
# merged layer y2
y2 = tf.keras.layers.Concatenate(axis=1)([y1, x3])
# print info
print("-"*30)
print("x1", x1.shape, "x2", x2.shape, "x3", x3.shape)
print("y1", y1.shape)
print("y2", y2.shape)
print("-"*30)
```
Result:
```
------------------------------
x1 (2, 10) x2 (2, 10) x3 (2, 10)
y1 (2, 20)
y2 (2, 30)
------------------------------
``` | You can experiment with `model.summary()` (notice the concatenate\_XX (Concatenate) layer size)
```
# merge samples, two input must be same shape
inp1 = Input(shape=(10,32))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=0) # Merge data must same row column
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()
# merge row must same column size
inp1 = Input(shape=(20,10))
inp2 = Input(shape=(32,10))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()
# merge column must same row size
inp1 = Input(shape=(10,20))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()
```
You can view notebook here for detail:
<https://nbviewer.jupyter.org/github/anhhh11/DeepLearning/blob/master/Concanate_two_layer_keras.ipynb> |
60,146,978 | `print('python'*5,sep=',')`
<https://i.stack.imgur.com/zB3HT.png>
How do I print it on a new line?
Ex: pythonpythonpythonppythonpython
But it's not using `'sep=','` option
so, how do I get it working ?
ex: python,python,python,.... | 2020/02/10 | [
"https://Stackoverflow.com/questions/60146978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870928/"
] | Try this way
```
print(*5*('python',), sep=',')
```
Output
>
> python,python,python,python,python
>
>
>
You have to add the ',' to let the separator know what to separate, otherwise it will think there's only one word. | There are a number of ways to do so. Try
```
'python, ' * 5
```
or
```
print(*['python']*5,sep=',')
```
or
```
', '.join(['python'] * 5)
```
`sep` is an argument of `print()` function and not a string formatter. It puts the separator when print's work is done. |
41,252,208 | I'd like to use an HTTP proxy (such as nginx) to cache large/expensive requests. These resources are identical for any *authorized* user, but their authentication/authorization needs to be checked by the backend on each request.
It sounds like something like `Cache-Control: public, max-age=0` along with the nginx directive `proxy_cache_revalidate on;` is the way to do this. The proxy can cache the request, but every subsequent request needs to do a conditional GET to the backend to ensure it's authorized before returning the cached resource. The backend then sends a 403 if the user is unauthorized, a 304 if the user is authorized and the cached resource isn't stale, or a 200 with the new resource if it has expired.
In nginx if `max-age=0` is set the request isn't cached at all. If `max-age=1` is set then if I wait 1 second after the initial request then nginx does perform the conditional GET request, however before 1 second it serves it directly from cache, which is obviously very bad for a resource that needs to be authenticated.
Is there a way to get nginx to cache the request but immediately require revalidating?
Note this *does* work correctly in Apache. Here are examples for both nginx and Apache, the first 2 with max-age=5, the last 2 with max-age=0:
```
# Apache with `Cache-Control: public, max-age=5`
$ while true; do curl -v http://localhost:4001/ >/dev/null 2>&1 | grep X-Cache; sleep 1; done
< X-Cache: MISS from 172.x.x.x
< X-Cache: HIT from 172.x.x.x
< X-Cache: HIT from 172.x.x.x
< X-Cache: HIT from 172.x.x.x
< X-Cache: HIT from 172.x.x.x
< X-Cache: REVALIDATE from 172.x.x.x
< X-Cache: HIT from 172.x.x.x
# nginx with `Cache-Control: public, max-age=5`
$ while true; do curl -v http://localhost:4000/ >/dev/null 2>&1 | grep X-Cache; sleep 1; done
< X-Cached: MISS
< X-Cached: HIT
< X-Cached: HIT
< X-Cached: HIT
< X-Cached: HIT
< X-Cached: HIT
< X-Cached: REVALIDATED
< X-Cached: HIT
< X-Cached: HIT
# Apache with `Cache-Control: public, max-age=0`
# THIS IS WHAT I WANT
$ while true; do curl -v http://localhost:4001/ >/dev/null 2>&1 | grep X-Cache; sleep 1; done
< X-Cache: MISS from 172.x.x.x
< X-Cache: REVALIDATE from 172.x.x.x
< X-Cache: REVALIDATE from 172.x.x.x
< X-Cache: REVALIDATE from 172.x.x.x
< X-Cache: REVALIDATE from 172.x.x.x
< X-Cache: REVALIDATE from 172.x.x.x
# nginx with `Cache-Control: public, max-age=0`
$ while true; do curl -v http://localhost:4000/ >/dev/null 2>&1 | grep X-Cache; sleep 1; done
< X-Cached: MISS
< X-Cached: MISS
< X-Cached: MISS
< X-Cached: MISS
< X-Cached: MISS
< X-Cached: MISS
```
As you can see in the first 2 examples the requests are able to be cached by both Apache and nginx, and Apache correctly caches even max-age=0 requests, but nginx does not. | 2016/12/20 | [
"https://Stackoverflow.com/questions/41252208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113/"
] | I would like to address the additional questions / concerns that have come up during the conversation since my original answer of simply using `X-Accel-Redirect` (and, if Apache-compatibility is desired, `X-Sendfile`, respectively).
The solution that you seek as "optimal" (without `X-Accel-Redirect`) is incorrect, for more than one reason:
1. All it takes is a request from an unauthenticated user for your cache to be wiped clean.
* If every other request is from an unauthenticated user, you effectively simply have no cache at all whatsoever.
* Anyone can make requests to the public URL of the resource to keep your cache wiped clean at all times.
2. If the files served are, in fact, static, then you're wasting extra memory, time, disc and vm/cache space for keeping more than one copy of each file.
3. If the content served is dynamic:
* Is it the same constant cost to perform authentication as resource generation? Then what do you actually gain by caching it when revalidation is always required? A constant factor less than 2x? You might as well not bother with caching simply to tick a checkmark, as real-world improvement would be rather negligible.
* Is it exponentially more expensive to generate the view than to perform authentication? Sounds like a good idea to cache the view, then, and serve it to tens of thousands of requests at peak time! But for that to happen successfully you better not have any unauthenticated users lurking around (as even a couple could cause significant and unpredictable expenses of having to regen the view).
4. What happens with the cache in various edge-case scenarios? What if the user is denied access, without the developer using appropriate code, and then that gets cached? What if the next administrator decides to tweak a setting or two, e.g., [`proxy_cache_use_stale`](http://nginx.org/r/proxy_cache_use_stale)? Suddenly, you have unauthenticated users receiving privy information. You're leaving all sorts of cache poisoning attack vectors around by needlessly joining together independent parts of your application.
5. I don't think it's technically correct to return `Cache-Control: public, max-age=0` for a page that requires authentication. I believe the correct response might be `must-revalidate` or `private` in place of `public`.
The nginx "deficiency" on the lack of support for immediate revalidation w/ `max-age=0` is by design (similarly to its lack of support for `.htaccess`).
As per the above points, it makes little sense to immediately require re-validation of a given resource, and it's simply an approach that doesn't scale, especially when you have a "ridiculous" amount of requests per second that must all be satisfied using minimal resources and under no uncertain terms.
If you require a web-server designed by a "committee", with backwards compatibility for every kitchen-sink application and every questionable part of any RFC, nginx is simply not the correct solution.
On the other hand, `X-Accel-Redirect` is really simple, foolproof and de-facto standard. It lets you separate content from access control in a very neat way. It's dead simple. It actually ensures that your content will be cached, instead of your cache be wiped out clean willy-nilly. It is *the* correct solution worth pursuing. Trying to avoid an "extra" request every 10K servings during the peek time, at the price of having only "one" request when no caching is needed in the first place, and effectively no cache when the 10K requests come by, is not the correct way to design scalable architectures. | I think your best bet would be to modify your backend with support of `X-Accel-Redirect`.
Its functionality is enabled by default, and is described in the documentation for [`proxy_ignore_headers`](http://nginx.org/r/proxy_ignore_headers):
>
> “X-Accel-Redirect” performs an internal redirect to the specified URI;
>
>
>
You would then cache said internal resource, and automatically return it for any user that has been authenticated.
As the redirect has to be [`internal`](http://nginx.org/r/internal), there would not be any other way for it to be accessed (e.g., without an internal redirect of some sort), so, as per your requirements, unauthorised users won't be able to access it, but it could still be cached just as any other [`location`](http://nginx.org/r/location). |
41,252,208 | I'd like to use an HTTP proxy (such as nginx) to cache large/expensive requests. These resources are identical for any *authorized* user, but their authentication/authorization needs to be checked by the backend on each request.
It sounds like something like `Cache-Control: public, max-age=0` along with the nginx directive `proxy_cache_revalidate on;` is the way to do this. The proxy can cache the request, but every subsequent request needs to do a conditional GET to the backend to ensure it's authorized before returning the cached resource. The backend then sends a 403 if the user is unauthorized, a 304 if the user is authorized and the cached resource isn't stale, or a 200 with the new resource if it has expired.
In nginx if `max-age=0` is set the request isn't cached at all. If `max-age=1` is set then if I wait 1 second after the initial request then nginx does perform the conditional GET request, however before 1 second it serves it directly from cache, which is obviously very bad for a resource that needs to be authenticated.
Is there a way to get nginx to cache the request but immediately require revalidating?
Note this *does* work correctly in Apache. Here are examples for both nginx and Apache, the first 2 with max-age=5, the last 2 with max-age=0:
```
# Apache with `Cache-Control: public, max-age=5`
$ while true; do curl -v http://localhost:4001/ >/dev/null 2>&1 | grep X-Cache; sleep 1; done
< X-Cache: MISS from 172.x.x.x
< X-Cache: HIT from 172.x.x.x
< X-Cache: HIT from 172.x.x.x
< X-Cache: HIT from 172.x.x.x
< X-Cache: HIT from 172.x.x.x
< X-Cache: REVALIDATE from 172.x.x.x
< X-Cache: HIT from 172.x.x.x
# nginx with `Cache-Control: public, max-age=5`
$ while true; do curl -v http://localhost:4000/ >/dev/null 2>&1 | grep X-Cache; sleep 1; done
< X-Cached: MISS
< X-Cached: HIT
< X-Cached: HIT
< X-Cached: HIT
< X-Cached: HIT
< X-Cached: HIT
< X-Cached: REVALIDATED
< X-Cached: HIT
< X-Cached: HIT
# Apache with `Cache-Control: public, max-age=0`
# THIS IS WHAT I WANT
$ while true; do curl -v http://localhost:4001/ >/dev/null 2>&1 | grep X-Cache; sleep 1; done
< X-Cache: MISS from 172.x.x.x
< X-Cache: REVALIDATE from 172.x.x.x
< X-Cache: REVALIDATE from 172.x.x.x
< X-Cache: REVALIDATE from 172.x.x.x
< X-Cache: REVALIDATE from 172.x.x.x
< X-Cache: REVALIDATE from 172.x.x.x
# nginx with `Cache-Control: public, max-age=0`
$ while true; do curl -v http://localhost:4000/ >/dev/null 2>&1 | grep X-Cache; sleep 1; done
< X-Cached: MISS
< X-Cached: MISS
< X-Cached: MISS
< X-Cached: MISS
< X-Cached: MISS
< X-Cached: MISS
```
As you can see in the first 2 examples the requests are able to be cached by both Apache and nginx, and Apache correctly caches even max-age=0 requests, but nginx does not. | 2016/12/20 | [
"https://Stackoverflow.com/questions/41252208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113/"
] | I would like to address the additional questions / concerns that have come up during the conversation since my original answer of simply using `X-Accel-Redirect` (and, if Apache-compatibility is desired, `X-Sendfile`, respectively).
The solution that you seek as "optimal" (without `X-Accel-Redirect`) is incorrect, for more than one reason:
1. All it takes is a request from an unauthenticated user for your cache to be wiped clean.
* If every other request is from an unauthenticated user, you effectively simply have no cache at all whatsoever.
* Anyone can make requests to the public URL of the resource to keep your cache wiped clean at all times.
2. If the files served are, in fact, static, then you're wasting extra memory, time, disc and vm/cache space for keeping more than one copy of each file.
3. If the content served is dynamic:
* Is it the same constant cost to perform authentication as resource generation? Then what do you actually gain by caching it when revalidation is always required? A constant factor less than 2x? You might as well not bother with caching simply to tick a checkmark, as real-world improvement would be rather negligible.
* Is it exponentially more expensive to generate the view than to perform authentication? Sounds like a good idea to cache the view, then, and serve it to tens of thousands of requests at peak time! But for that to happen successfully you better not have any unauthenticated users lurking around (as even a couple could cause significant and unpredictable expenses of having to regen the view).
4. What happens with the cache in various edge-case scenarios? What if the user is denied access, without the developer using appropriate code, and then that gets cached? What if the next administrator decides to tweak a setting or two, e.g., [`proxy_cache_use_stale`](http://nginx.org/r/proxy_cache_use_stale)? Suddenly, you have unauthenticated users receiving privy information. You're leaving all sorts of cache poisoning attack vectors around by needlessly joining together independent parts of your application.
5. I don't think it's technically correct to return `Cache-Control: public, max-age=0` for a page that requires authentication. I believe the correct response might be `must-revalidate` or `private` in place of `public`.
The nginx "deficiency" on the lack of support for immediate revalidation w/ `max-age=0` is by design (similarly to its lack of support for `.htaccess`).
As per the above points, it makes little sense to immediately require re-validation of a given resource, and it's simply an approach that doesn't scale, especially when you have a "ridiculous" amount of requests per second that must all be satisfied using minimal resources and under no uncertain terms.
If you require a web-server designed by a "committee", with backwards compatibility for every kitchen-sink application and every questionable part of any RFC, nginx is simply not the correct solution.
On the other hand, `X-Accel-Redirect` is really simple, foolproof and de-facto standard. It lets you separate content from access control in a very neat way. It's dead simple. It actually ensures that your content will be cached, instead of your cache be wiped out clean willy-nilly. It is *the* correct solution worth pursuing. Trying to avoid an "extra" request every 10K servings during the peek time, at the price of having only "one" request when no caching is needed in the first place, and effectively no cache when the 10K requests come by, is not the correct way to design scalable architectures. | If you are unable to modify the backend app as suggested or if the authentication is straightforward such as auth basic, an alternative approach would be to carry out the authentication in Nginx.
Implementing this auth process and defining the cache validity period would be all you would have to do and Nginx will take care of the rest as per the process flow below
**Nginx Process Flow as Pseudo Code:**
```
If (user = unauthorised) then
Nginx declines request;
else
if (cache = stale) then
Nginx gets resource from backend;
Nginx caches resource;
Nginx serves resource;
else
Nginx gets resource from cache;
Nginx serves resource;
end if
end if
```
Con is that depending on the auth type you have, you might need something like the Nginx Lua module to handle the logic.
EDIT
====
Seen the additional discussions and information given. Now, not fully knowing about how the backend app works but looking at the example config the user `anki-code` gave on GitHub which you commented on [HERE](https://github.com/metabase/metabase/issues/3966#issuecomment-267494668), the config below will avoid the issue you raised of backend app's authentication/authorization checks not being run for previously cached resources.
I assume the backend app returns a HTTP 403 code for unauthenticated users. I also assume that you have the Nginx Lua module in place since the GitHub config relies on this although I do note that the part you tested does not need that module.
Config:
```
server {
listen 80;
listen [::]:80;
server_name 127.0.0.1;
location / {
proxy_pass http://127.0.0.1:3000; # Metabase here
}
location ~ /api/card((?!/42/|/41/)/[0-9]*/)query {
access_by_lua_block {
-- HEAD request to a location excluded from caching to authenticate
res = ngx.location.capture( "/api/card/42/query", { method = ngx.HTTP_HEAD } )
if res.status = 403 then
return ngx.exit(ngx.HTTP_FORBIDDEN)
else
ngx.exec("@metabase")
end if
}
}
location @metabase {
# cache all cards data without card 42 and card 41 (they have realtime data)
if ($http_referer !~ /dash/){
#cache only cards on dashboard
set $no_cache 1;
}
proxy_no_cache $no_cache;
proxy_cache_bypass $no_cache;
proxy_pass http://127.0.0.1:3000;
proxy_cache_methods POST;
proxy_cache_valid 8h;
proxy_ignore_headers Cache-Control Expires;
proxy_cache cache_all;
proxy_cache_key "$request_uri|$request_body";
proxy_buffers 8 32k;
proxy_buffer_size 64k;
add_header X-MBCache $upstream_cache_status;
}
location ~ /api/card/\d+ {
proxy_pass http://127.0.0.1:3000;
if ($request_method ~ PUT) {
# when the card was edited reset the cache for this card
access_by_lua 'os.execute("find /var/cache/nginx -type f -exec grep -q \\"".. ngx.var.request_uri .."/\\" {} \\\; -delete ")';
add_header X-MBCache REMOVED;
}
}
}
```
With this, I'll expect that the test with **`$ curl 'http://localhost:3001/api/card/1/query'`** will run as follows:
### First Run (With Required Cookie)
1. Request Hits **`location ~ /api/card((?!/42/|/41/)/[0-9]*/)query`**
2. In Nginx Access Phase, a "HEAD" sub-request is issued to **`/api/card/42/query`**. This location is excluded from caching in the config given.
3. The backend app returns a non 403 etc response since the user is authenticated.
4. A sub-request is then issued to the **`@metabase`** named location block which handles the actual request and returns the content to the user.
### Second Run (Without Required Cookie)
1. Request Hits **`location ~ /api/card((?!/42/|/41/)/[0-9]*/)query`**
2. In Nginx Access Phase, a "HEAD" sub-request is issued to the backend at **`/api/card/42/query`**.
3. The backend app returns 403 Forbidden response since the user is not authenticated
4. The user's client gets a 403 Forbidden response.
Instead of **`/api/card/42/query`**, if resource intensive, you may be able to create a simple card query that will simply be used to do the auth.
Seems a straightforward way to go about it. The backend stays as it is without messing about with it and you configure your caching details in Nginx. |
41,376,266 | I am using python 2.7 and trying to **search folder not file**.
We have specific project number for every project and evry documents goes to project folder under any project. So , we have to search the project folder if it is exist or valid.
My script can find the specific folder but it takes long time (about 11 to 13 minutes to complete the process)
I would like to share my script work to have some better ideas.
```
import os
path=r"F:\Projekte"
def find_directory():
for root, dirs, files in os.walk(path):
for i in dirs:
if i=="A9901001":
print root
find_directory()
``` | 2016/12/29 | [
"https://Stackoverflow.com/questions/41376266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1764861/"
] | In order to include a global library, you have to add the jquery.js file in the `scripts` array from angular-cli.json:
```
"scripts": [
"../node_modules/jquery/dist/jquery.js"
]
```
After this, restart `ng serve` if it is already started. | If you use webPack and Typescript you can do something like this:
in your vendor.ts file import jquery:
```
/ RxJS.
import "rxjs";
// Angular 2.
import "@angular/common";
import "@angular/compiler";
import "@angular/core";
import "@angular/http";
import "@angular/platform-browser";
import "@angular/platform-browser-dynamic";
import "@angular/router";
// Reflect Metadata.
import "reflect-metadata";
// Other vendors for example jQuery, Lodash or Bootstrap
// You can import js, ts, css, sass, ...
import "jquery"; //<-- HERE IS JQUERY
import "bootstrap/dist/js/bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import "angular2-toaster/lib/toaster.css";
import "angular2-toaster/angular2-toaster";
import "ng2-slim-loading-bar";
import "ng2-slim-loading-bar/style.css";
import "ng2-modal";
import "ng2-bs3-modal/ng2-bs3-modal";
```
then in your webpack.dev.js use plug in to import it in every component without need to import it manually:
```
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var webpack = require("webpack");
var HtmlWebpackPlugin = require("html-webpack-plugin");
var CleanWebpackPlugin = require('clean-webpack-plugin');
var path = require('path');
module.exports = {
entry: {
"polyfills": "./polyfills.ts",
"vendor": "./vendor.ts",
"app": "./app/main.ts",
},
resolve: {
extensions: ['', '.ts', '.js', '.json', '.css', '.scss', '.html']
},
output: {
path: "./app_build",
filename: "js/[name]-[hash:8].bundle.js"
},
devtool: 'source-map',
module: {
loaders: [
{
loader: "babel-loader",
// Skip any files outside of your project's `src` directory
//include: [
// "app_build",
//],
exclude: [
path.resolve(__dirname, "node_modules")
],
// Only run `.js` and `.jsx` files through Babel
test: /\.js/,
// Options to configure babel with
query: {
plugins: ['transform-runtime', 'babel-plugin-transform-async-to-generator'],
presets: ['es2015', 'stage-0'],
}
},
{
test: /\.ts$/,
loader: "ts"
},
{
test: /\.html$/,
loader: "html"
},
//{
// test: /\.(png|jpg|gif|ico|woff|woff2|ttf|svg|eot)$/,
// loader: "file?name=assets/[name]-[hash:6].[ext]",
//},
{
test: /\.(png|jpg|gif|ico)$/,
//include: path.resolve(__dirname, "assets/img"),
loader: 'file?name=/assets/img/[name]-[hash:6].[ext]'
},
{
test: /\.(woff|woff2|eot|ttf|svg)$/,
// exclude: /node_modules/,
loader: 'file?name=/assets/fonts/[name].[ext]'
},
// Load css files which are required in vendor.ts
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css!sass')
},
]
},
plugins: [
new ExtractTextPlugin("css/[name]-[hash:8].bundle.css", { allChunks: true }),
new webpack.optimize.CommonsChunkPlugin({
name: ["app", "vendor", "polyfills"]
}),
new CleanWebpackPlugin(
[
"./app_build/js/",
"./app_build/css/",
"./app_build/assets/",
"./app_build/index.html"
]
),
// inject in index.html
new HtmlWebpackPlugin({
template: "./index.html",
inject: "body"
}),
// JQUERY PLUGIN HERE <-- !!! HERE IS PLUG IN
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery'
})
],
devServer: {
//contentBase: path.resolve(__dirname, "app_build/"),
historyApiFallback: true,
stats: "minimal"
}
};
```
Now everywhere in your code .ts you can use jquery like this:
```
import { Component, AfterViewInit, ElementRef } from '@angular/core';
@Component({
selector: 'about',
template: require('./about.component.html'),
styles: [String(require('./about.component.scss'))]
})
export default class AboutComponent implements AfterViewInit {
calendarElement: any;
constructor(private elementRef: ElementRef) { }
ngAfterViewInit() {
this.calendarElement = jQuery(this.elementRef.nativeElement);
}
}
``` |
41,376,266 | I am using python 2.7 and trying to **search folder not file**.
We have specific project number for every project and evry documents goes to project folder under any project. So , we have to search the project folder if it is exist or valid.
My script can find the specific folder but it takes long time (about 11 to 13 minutes to complete the process)
I would like to share my script work to have some better ideas.
```
import os
path=r"F:\Projekte"
def find_directory():
for root, dirs, files in os.walk(path):
for i in dirs:
if i=="A9901001":
print root
find_directory()
``` | 2016/12/29 | [
"https://Stackoverflow.com/questions/41376266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1764861/"
] | If you use webPack and Typescript you can do something like this:
in your vendor.ts file import jquery:
```
/ RxJS.
import "rxjs";
// Angular 2.
import "@angular/common";
import "@angular/compiler";
import "@angular/core";
import "@angular/http";
import "@angular/platform-browser";
import "@angular/platform-browser-dynamic";
import "@angular/router";
// Reflect Metadata.
import "reflect-metadata";
// Other vendors for example jQuery, Lodash or Bootstrap
// You can import js, ts, css, sass, ...
import "jquery"; //<-- HERE IS JQUERY
import "bootstrap/dist/js/bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import "angular2-toaster/lib/toaster.css";
import "angular2-toaster/angular2-toaster";
import "ng2-slim-loading-bar";
import "ng2-slim-loading-bar/style.css";
import "ng2-modal";
import "ng2-bs3-modal/ng2-bs3-modal";
```
then in your webpack.dev.js use plug in to import it in every component without need to import it manually:
```
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var webpack = require("webpack");
var HtmlWebpackPlugin = require("html-webpack-plugin");
var CleanWebpackPlugin = require('clean-webpack-plugin');
var path = require('path');
module.exports = {
entry: {
"polyfills": "./polyfills.ts",
"vendor": "./vendor.ts",
"app": "./app/main.ts",
},
resolve: {
extensions: ['', '.ts', '.js', '.json', '.css', '.scss', '.html']
},
output: {
path: "./app_build",
filename: "js/[name]-[hash:8].bundle.js"
},
devtool: 'source-map',
module: {
loaders: [
{
loader: "babel-loader",
// Skip any files outside of your project's `src` directory
//include: [
// "app_build",
//],
exclude: [
path.resolve(__dirname, "node_modules")
],
// Only run `.js` and `.jsx` files through Babel
test: /\.js/,
// Options to configure babel with
query: {
plugins: ['transform-runtime', 'babel-plugin-transform-async-to-generator'],
presets: ['es2015', 'stage-0'],
}
},
{
test: /\.ts$/,
loader: "ts"
},
{
test: /\.html$/,
loader: "html"
},
//{
// test: /\.(png|jpg|gif|ico|woff|woff2|ttf|svg|eot)$/,
// loader: "file?name=assets/[name]-[hash:6].[ext]",
//},
{
test: /\.(png|jpg|gif|ico)$/,
//include: path.resolve(__dirname, "assets/img"),
loader: 'file?name=/assets/img/[name]-[hash:6].[ext]'
},
{
test: /\.(woff|woff2|eot|ttf|svg)$/,
// exclude: /node_modules/,
loader: 'file?name=/assets/fonts/[name].[ext]'
},
// Load css files which are required in vendor.ts
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css!sass')
},
]
},
plugins: [
new ExtractTextPlugin("css/[name]-[hash:8].bundle.css", { allChunks: true }),
new webpack.optimize.CommonsChunkPlugin({
name: ["app", "vendor", "polyfills"]
}),
new CleanWebpackPlugin(
[
"./app_build/js/",
"./app_build/css/",
"./app_build/assets/",
"./app_build/index.html"
]
),
// inject in index.html
new HtmlWebpackPlugin({
template: "./index.html",
inject: "body"
}),
// JQUERY PLUGIN HERE <-- !!! HERE IS PLUG IN
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery'
})
],
devServer: {
//contentBase: path.resolve(__dirname, "app_build/"),
historyApiFallback: true,
stats: "minimal"
}
};
```
Now everywhere in your code .ts you can use jquery like this:
```
import { Component, AfterViewInit, ElementRef } from '@angular/core';
@Component({
selector: 'about',
template: require('./about.component.html'),
styles: [String(require('./about.component.scss'))]
})
export default class AboutComponent implements AfterViewInit {
calendarElement: any;
constructor(private elementRef: ElementRef) { }
ngAfterViewInit() {
this.calendarElement = jQuery(this.elementRef.nativeElement);
}
}
``` | I recommend to follow [Nikhil Shah](https://stackoverflow.com/a/41376442/1986423) suggestion in case of existing @type (like the case of jQuery)
However if you have library that export global variable (like jQuery) but does not have known @type file you can take a look at [my following answer](https://stackoverflow.com/a/42531719/1986423) |
41,376,266 | I am using python 2.7 and trying to **search folder not file**.
We have specific project number for every project and evry documents goes to project folder under any project. So , we have to search the project folder if it is exist or valid.
My script can find the specific folder but it takes long time (about 11 to 13 minutes to complete the process)
I would like to share my script work to have some better ideas.
```
import os
path=r"F:\Projekte"
def find_directory():
for root, dirs, files in os.walk(path):
for i in dirs:
if i=="A9901001":
print root
find_directory()
``` | 2016/12/29 | [
"https://Stackoverflow.com/questions/41376266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1764861/"
] | There is a new way to deal with *external libraries* using **@types**
In order to install/use **jquery**, you just need to install it in your project using
```
npm install --save @types/jquery
```
and then in **tsconfig.json**,under **types**, add its reference accordingly as shown,
**tsconfig.json**
```
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2015", "dom" ],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"types": [
"jquery", //<<<<-----add here
"hammerjs",
"node"
]
}
}
``` | I recommend to follow [Nikhil Shah](https://stackoverflow.com/a/41376442/1986423) suggestion in case of existing @type (like the case of jQuery)
However if you have library that export global variable (like jQuery) but does not have known @type file you can take a look at [my following answer](https://stackoverflow.com/a/42531719/1986423) |
41,376,266 | I am using python 2.7 and trying to **search folder not file**.
We have specific project number for every project and evry documents goes to project folder under any project. So , we have to search the project folder if it is exist or valid.
My script can find the specific folder but it takes long time (about 11 to 13 minutes to complete the process)
I would like to share my script work to have some better ideas.
```
import os
path=r"F:\Projekte"
def find_directory():
for root, dirs, files in os.walk(path):
for i in dirs:
if i=="A9901001":
print root
find_directory()
``` | 2016/12/29 | [
"https://Stackoverflow.com/questions/41376266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1764861/"
] | There is a new way to deal with *external libraries* using **@types**
In order to install/use **jquery**, you just need to install it in your project using
```
npm install --save @types/jquery
```
and then in **tsconfig.json**,under **types**, add its reference accordingly as shown,
**tsconfig.json**
```
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2015", "dom" ],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"types": [
"jquery", //<<<<-----add here
"hammerjs",
"node"
]
}
}
``` | If @tudorciotlos answer does not work for you (like in my case) try this extended way:
```
"scripts": [
{ "input": "../node_modules/jquery/dist/jquery.js", "bundleName": "renamed-script.js" }
]
```
```html
<script src="renamed-script.js"></script>
```
[Source here](https://github.com/angular/angular-cli/wiki/stories-global-scripts) |
41,376,266 | I am using python 2.7 and trying to **search folder not file**.
We have specific project number for every project and evry documents goes to project folder under any project. So , we have to search the project folder if it is exist or valid.
My script can find the specific folder but it takes long time (about 11 to 13 minutes to complete the process)
I would like to share my script work to have some better ideas.
```
import os
path=r"F:\Projekte"
def find_directory():
for root, dirs, files in os.walk(path):
for i in dirs:
if i=="A9901001":
print root
find_directory()
``` | 2016/12/29 | [
"https://Stackoverflow.com/questions/41376266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1764861/"
] | In order to include a global library, you have to add the jquery.js file in the `scripts` array from angular-cli.json:
```
"scripts": [
"../node_modules/jquery/dist/jquery.js"
]
```
After this, restart `ng serve` if it is already started. | There is a new way to deal with *external libraries* using **@types**
In order to install/use **jquery**, you just need to install it in your project using
```
npm install --save @types/jquery
```
and then in **tsconfig.json**,under **types**, add its reference accordingly as shown,
**tsconfig.json**
```
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2015", "dom" ],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"types": [
"jquery", //<<<<-----add here
"hammerjs",
"node"
]
}
}
``` |
41,376,266 | I am using python 2.7 and trying to **search folder not file**.
We have specific project number for every project and evry documents goes to project folder under any project. So , we have to search the project folder if it is exist or valid.
My script can find the specific folder but it takes long time (about 11 to 13 minutes to complete the process)
I would like to share my script work to have some better ideas.
```
import os
path=r"F:\Projekte"
def find_directory():
for root, dirs, files in os.walk(path):
for i in dirs:
if i=="A9901001":
print root
find_directory()
``` | 2016/12/29 | [
"https://Stackoverflow.com/questions/41376266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1764861/"
] | In order to include a global library, you have to add the jquery.js file in the `scripts` array from angular-cli.json:
```
"scripts": [
"../node_modules/jquery/dist/jquery.js"
]
```
After this, restart `ng serve` if it is already started. | If @tudorciotlos answer does not work for you (like in my case) try this extended way:
```
"scripts": [
{ "input": "../node_modules/jquery/dist/jquery.js", "bundleName": "renamed-script.js" }
]
```
```html
<script src="renamed-script.js"></script>
```
[Source here](https://github.com/angular/angular-cli/wiki/stories-global-scripts) |
41,376,266 | I am using python 2.7 and trying to **search folder not file**.
We have specific project number for every project and evry documents goes to project folder under any project. So , we have to search the project folder if it is exist or valid.
My script can find the specific folder but it takes long time (about 11 to 13 minutes to complete the process)
I would like to share my script work to have some better ideas.
```
import os
path=r"F:\Projekte"
def find_directory():
for root, dirs, files in os.walk(path):
for i in dirs:
if i=="A9901001":
print root
find_directory()
``` | 2016/12/29 | [
"https://Stackoverflow.com/questions/41376266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1764861/"
] | Firstly you don't need to put it in index.html instead put this entry in `angular-cli.json` file
Like this:
```
"scripts": [
"../node_modules/wow.js/dist/wow.js",
"../node_modules/jquery/dist/jquery.js",
"....Other Libs..."
]
```
Then make sure you have installed jQuery properly before use
Also check the root path while giving relative path in the angular-cli.json file | If @tudorciotlos answer does not work for you (like in my case) try this extended way:
```
"scripts": [
{ "input": "../node_modules/jquery/dist/jquery.js", "bundleName": "renamed-script.js" }
]
```
```html
<script src="renamed-script.js"></script>
```
[Source here](https://github.com/angular/angular-cli/wiki/stories-global-scripts) |
41,376,266 | I am using python 2.7 and trying to **search folder not file**.
We have specific project number for every project and evry documents goes to project folder under any project. So , we have to search the project folder if it is exist or valid.
My script can find the specific folder but it takes long time (about 11 to 13 minutes to complete the process)
I would like to share my script work to have some better ideas.
```
import os
path=r"F:\Projekte"
def find_directory():
for root, dirs, files in os.walk(path):
for i in dirs:
if i=="A9901001":
print root
find_directory()
``` | 2016/12/29 | [
"https://Stackoverflow.com/questions/41376266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1764861/"
] | There is a new way to deal with *external libraries* using **@types**
In order to install/use **jquery**, you just need to install it in your project using
```
npm install --save @types/jquery
```
and then in **tsconfig.json**,under **types**, add its reference accordingly as shown,
**tsconfig.json**
```
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2015", "dom" ],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"types": [
"jquery", //<<<<-----add here
"hammerjs",
"node"
]
}
}
``` | Firstly you don't need to put it in index.html instead put this entry in `angular-cli.json` file
Like this:
```
"scripts": [
"../node_modules/wow.js/dist/wow.js",
"../node_modules/jquery/dist/jquery.js",
"....Other Libs..."
]
```
Then make sure you have installed jQuery properly before use
Also check the root path while giving relative path in the angular-cli.json file |
41,376,266 | I am using python 2.7 and trying to **search folder not file**.
We have specific project number for every project and evry documents goes to project folder under any project. So , we have to search the project folder if it is exist or valid.
My script can find the specific folder but it takes long time (about 11 to 13 minutes to complete the process)
I would like to share my script work to have some better ideas.
```
import os
path=r"F:\Projekte"
def find_directory():
for root, dirs, files in os.walk(path):
for i in dirs:
if i=="A9901001":
print root
find_directory()
``` | 2016/12/29 | [
"https://Stackoverflow.com/questions/41376266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1764861/"
] | There is a new way to deal with *external libraries* using **@types**
In order to install/use **jquery**, you just need to install it in your project using
```
npm install --save @types/jquery
```
and then in **tsconfig.json**,under **types**, add its reference accordingly as shown,
**tsconfig.json**
```
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2015", "dom" ],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"types": [
"jquery", //<<<<-----add here
"hammerjs",
"node"
]
}
}
``` | If you use webPack and Typescript you can do something like this:
in your vendor.ts file import jquery:
```
/ RxJS.
import "rxjs";
// Angular 2.
import "@angular/common";
import "@angular/compiler";
import "@angular/core";
import "@angular/http";
import "@angular/platform-browser";
import "@angular/platform-browser-dynamic";
import "@angular/router";
// Reflect Metadata.
import "reflect-metadata";
// Other vendors for example jQuery, Lodash or Bootstrap
// You can import js, ts, css, sass, ...
import "jquery"; //<-- HERE IS JQUERY
import "bootstrap/dist/js/bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import "angular2-toaster/lib/toaster.css";
import "angular2-toaster/angular2-toaster";
import "ng2-slim-loading-bar";
import "ng2-slim-loading-bar/style.css";
import "ng2-modal";
import "ng2-bs3-modal/ng2-bs3-modal";
```
then in your webpack.dev.js use plug in to import it in every component without need to import it manually:
```
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var webpack = require("webpack");
var HtmlWebpackPlugin = require("html-webpack-plugin");
var CleanWebpackPlugin = require('clean-webpack-plugin');
var path = require('path');
module.exports = {
entry: {
"polyfills": "./polyfills.ts",
"vendor": "./vendor.ts",
"app": "./app/main.ts",
},
resolve: {
extensions: ['', '.ts', '.js', '.json', '.css', '.scss', '.html']
},
output: {
path: "./app_build",
filename: "js/[name]-[hash:8].bundle.js"
},
devtool: 'source-map',
module: {
loaders: [
{
loader: "babel-loader",
// Skip any files outside of your project's `src` directory
//include: [
// "app_build",
//],
exclude: [
path.resolve(__dirname, "node_modules")
],
// Only run `.js` and `.jsx` files through Babel
test: /\.js/,
// Options to configure babel with
query: {
plugins: ['transform-runtime', 'babel-plugin-transform-async-to-generator'],
presets: ['es2015', 'stage-0'],
}
},
{
test: /\.ts$/,
loader: "ts"
},
{
test: /\.html$/,
loader: "html"
},
//{
// test: /\.(png|jpg|gif|ico|woff|woff2|ttf|svg|eot)$/,
// loader: "file?name=assets/[name]-[hash:6].[ext]",
//},
{
test: /\.(png|jpg|gif|ico)$/,
//include: path.resolve(__dirname, "assets/img"),
loader: 'file?name=/assets/img/[name]-[hash:6].[ext]'
},
{
test: /\.(woff|woff2|eot|ttf|svg)$/,
// exclude: /node_modules/,
loader: 'file?name=/assets/fonts/[name].[ext]'
},
// Load css files which are required in vendor.ts
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css!sass')
},
]
},
plugins: [
new ExtractTextPlugin("css/[name]-[hash:8].bundle.css", { allChunks: true }),
new webpack.optimize.CommonsChunkPlugin({
name: ["app", "vendor", "polyfills"]
}),
new CleanWebpackPlugin(
[
"./app_build/js/",
"./app_build/css/",
"./app_build/assets/",
"./app_build/index.html"
]
),
// inject in index.html
new HtmlWebpackPlugin({
template: "./index.html",
inject: "body"
}),
// JQUERY PLUGIN HERE <-- !!! HERE IS PLUG IN
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery'
})
],
devServer: {
//contentBase: path.resolve(__dirname, "app_build/"),
historyApiFallback: true,
stats: "minimal"
}
};
```
Now everywhere in your code .ts you can use jquery like this:
```
import { Component, AfterViewInit, ElementRef } from '@angular/core';
@Component({
selector: 'about',
template: require('./about.component.html'),
styles: [String(require('./about.component.scss'))]
})
export default class AboutComponent implements AfterViewInit {
calendarElement: any;
constructor(private elementRef: ElementRef) { }
ngAfterViewInit() {
this.calendarElement = jQuery(this.elementRef.nativeElement);
}
}
``` |
41,376,266 | I am using python 2.7 and trying to **search folder not file**.
We have specific project number for every project and evry documents goes to project folder under any project. So , we have to search the project folder if it is exist or valid.
My script can find the specific folder but it takes long time (about 11 to 13 minutes to complete the process)
I would like to share my script work to have some better ideas.
```
import os
path=r"F:\Projekte"
def find_directory():
for root, dirs, files in os.walk(path):
for i in dirs:
if i=="A9901001":
print root
find_directory()
``` | 2016/12/29 | [
"https://Stackoverflow.com/questions/41376266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1764861/"
] | In order to include a global library, you have to add the jquery.js file in the `scripts` array from angular-cli.json:
```
"scripts": [
"../node_modules/jquery/dist/jquery.js"
]
```
After this, restart `ng serve` if it is already started. | I recommend to follow [Nikhil Shah](https://stackoverflow.com/a/41376442/1986423) suggestion in case of existing @type (like the case of jQuery)
However if you have library that export global variable (like jQuery) but does not have known @type file you can take a look at [my following answer](https://stackoverflow.com/a/42531719/1986423) |
30,972 | Is there anything similar on Windows what would achieve the same as the InputManager on OS X? | 2008/08/27 | [
"https://Stackoverflow.com/questions/30972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260/"
] | 1. Require SSL on the application
2. In a custom error page for the 403 redirect the browser to the incoming URL, changing http to https along the way.
Note: Keep port 80 open for this - or there won't be a server to listen for requests to redirect. | Is just not accepting any connections on port 80 an option? I'm a complete web server noob so I don't know if the server can operate without an unsecured listen port but if the server can operate only listen on port 443 that would seem to be simplest option.
Another option would be a redirect from the unsecure port to the secure one |
30,972 | Is there anything similar on Windows what would achieve the same as the InputManager on OS X? | 2008/08/27 | [
"https://Stackoverflow.com/questions/30972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260/"
] | Just to clarify Greg's point 1. IIS Manager > Site properties > Directory Security > Secure Communications > Require Secure Channel (SSL) | Is just not accepting any connections on port 80 an option? I'm a complete web server noob so I don't know if the server can operate without an unsecured listen port but if the server can operate only listen on port 443 that would seem to be simplest option.
Another option would be a redirect from the unsecure port to the secure one |
22,842,323 | I have spent the last 5 hours tracking down a bug where symlinked files have been relabelled as normal files (I don't know how!). I would like to add a verification step to my build script to ensure this doesn't happen again.
In the working environment I get this:
```
> ls -l
... [Info] ... File1.h -> ../../a/b/File1.h
... [Info] ... File2.h -> ../../a/b/File2.h
...
```
In the corrupted environment I get this:
```
> ls -l
... [Info] ... File1.h
... [Info] ... File2.h
...
```
How can I make a robust script to iterate though the files in a folder and ensure that each file is a symlink? | 2014/04/03 | [
"https://Stackoverflow.com/questions/22842323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296446/"
] | You can use the numpy.timedelta64 object to perform time delta calculations on a numpy.datetime64 object, see [Datetime and Timedelta Arithmetic](http://docs.scipy.org/doc/numpy/reference/arrays.datetime.html#datetime-and-timedelta-arithmetic/ "Datetime and Timedelta Arithmetic").
Since a year can be either 365 or 366 days, it is not possible to substract a year, but you could substract 365 days instead:
```
import numpy as np
np.datetime64('2014-12-31') - np.timedelta64(365,'D')
```
results in:
`numpy.datetime64('2013-12-31')` | How about:
```
import numpy as np
import pandas as pd
def numpy_date_add(vd_array,y_array):
ar=((vd_array.astype('M8[Y]') + np.timedelta64(1, 'Y') * \
y_array).astype('M8[M]')+ \
(vd_array.astype('M8[M]')- \
vd_array.astype('M8[Y]'))).astype('M8[D]')+ \
(vd_array.astype('M8[D]')-\
vd_array.astype('M8[M]'))
return ar
# usage
valDate=pd.datetime(2016,12,31)
per=[[0,3,'0-3Yr'],
[3,7,'3-7Yrs'],
[7,10,'7-10Yrs'],
[10,15,'10-15Yrs'],
[15,20,'15-20Yrs'],
[20,30,'20-30Yrs'],
[30,40,'30-40Yrs'],
[40,200,'> 40Yrs']]
pert=pd.DataFrame(per,columns=['start_period','end_period','mat_band'])
pert['valDate']=valDate
pert['startdate'] = numpy_date_add(pert.valDate.values,pert.start_period.values)
pert['enddate'] = numpy_date_add(pert.valDate.values,pert.end_period.values)
print(pert)
```
Is vector based pandas usage and I think it deals with leap years. |
65,946,960 | I wrote a replacement for VB's MsgBox to gain control over the screen location. In the Visual Studio environment it did exactly what I wanted. I converted it into a class library but Strings with embedded vbCrLf characters add a blank line and lose the five spaces inserted into the line for the indent.
I've tried doubling the width of MyLabel. The form got wider since it's predicated on MyLabel.Width but the extra line was still there. My lines of text and the label are built as follows:
```
'split the string on vbCrLf with some leading spaces on each line to indent the message
strLineArr = strMsg.Split(vbCrLf)
Dim intMaxLength As Integer = 0
Dim intIndex As Int16 = 0
Dim ctrLine As Int16 = 0
strMsg = vbCrLf & vbCrLf 'put some space at the top
For i = 0 To strLineArr.Length - 1
If strLineArr(i).Length > intMaxLength Then
intMaxLength = strLineArr(i).Length 'width of label is based on longest line
intIndex = i 'keep tack of which line
End If
strMsg = strMsg & Space(5) & strLineArr(i) & vbCrLf 'add five leading space for an indent
ctrLine += 1 'line counter for the height of the label
Next
'set up the label and message
Dim lblMsg As New Label()
lblMsg.Font = New Drawing.Font("Arial", 10, FontStyle.Regular)
lblMsg.Text = strLineArr(intIndex) & "cccccccccc" 'longest line; add 10 'c' spaces for margin
Dim g As Graphics = lblMsg.CreateGraphics()
lblMsg.Width = CInt(g.MeasureString(lblMsg.Text, lblMsg.Font).Width)
lblMsg.Height = CInt(g.MeasureString(lblMsg.Text, lblMsg.Font).Height) * (ctrLine + 3)
lblMsg.Text = strMsg
```
Using the string "Short Message" & vbCrLf & "Second row":
[](https://i.stack.imgur.com/Iq2Lz.png)
The left side is when the code is run within the Visual Studio environment; the right side is the same code executed from within the .dll.
Any thought on this would be appreciated. | 2021/01/28 | [
"https://Stackoverflow.com/questions/65946960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11582774/"
] | I think I see a likely culprit. This is a perfect example of why you should ALWAYS have `Option Strict On`. This line:
```vb
strLineArr = strMsg.Split(vbCrLf)
```
is trying to call a method that doesn't exist. `vbCrLf` is a `String` and there is no overload of the `Split` method that accepts a `String` parameter like that. If you had `Option Strict On`, the compiler would inform you of that fact and refuse to build the project until you fixed it. With `Option Strict Off`, the compiler makes a best guess at what you want to do.
What it decides is that you actually want to call the overload that accepts a `ParamArray` of `Char` values. To accomplish that, it simply uses the first character of your `String` and discards the rest. That means that you are splitting on carriage return characters only and all but the first of the substrings you create have an erroneous line feed as the first character.
You later try to reconstruct the original text by inserting line breaks between the substrings, which means that you actually end up with one carriage return and two line feeds between each pair of substrings. I don't know why the result is different depending on where the code is but the code is wrong no matter where it is getting the expected result is just a happy accident.
Basically, your code is terrible. Sorry, but that's just the way it is. Trying to control position by adding leading spaces to each line is just terrible. You should be either using a `Label` to display the text and letting the position of the control provide the spacing from the edge of the form or else using GDI+ to draw all the text exactly where you want it. What you're doing is a filthy hack and you should stop it.
If you really must keep doing what you're doing, the correct way to split a `String` on line breaks is with a different overload of `String.Split` that actually does accept `String` delimiters rather than `Char` delimiters. Firstly, set `Option Strict On` in this project's property pages and also set it `On` in the IDE options, so it is `On` by default for future projects. You may have to fix other errors if you're using late binding or implicit conversions elsewhere. Now, if you know for a fact that your `String` will always have the default line break for the current platform, do this:
```vb
strLineArr = strMsg.Split({Environment.NewLine}, StringSplitOptions.None)
```
If you don't know whether the line breaks will be Windows (CR-LF) or UNIX (LF) then you can do this:
```vb
strLineArr = strMsg.Split({ControlChars.CrLf, ControlChars.Lf}, StringSplitOptions.None)
```
The latter will preferentially split on the two characters together but will also split on lone line feeds.
If you really wanted to reconstruct the original text but with 5 spaces before each line, I'd suggest the following:
```vb
Dim spaces = New String(" "c, 5)
strMsg = spaces & String.Join(Environment.NewLine & spaces, strLineArr)
``` | This is not an answer to the question you asked but it requires a bit of code so I didn't want to post it as a comment. It is basically a different way of doing things such that your current question should become moot.
In a new WinForms project, I added a new form named `MessageForm` and I added a `Label` to it. I did not change any properties of the `Label`, which means that `AutoSize` was `True` and `Location` was {0,0}. I then added the following code:
```vb
Public Class MessageForm
Public Sub New(message As String)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Label1.Text = message
End Sub
Private Sub MessageForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ClientSize = Label1.Size
End Sub
End Class
```
I added a `TextBox` and a `Button` to my startup form and set `MultiLine` to `True` on the `TextBox`. I then added the following code:
```vb
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Call New MessageForm(TextBox1.Text).ShowDialog()
End Sub
End Class
```
When I ran my project, I was able to type any text into the `TextBox`, click the `Button` and have that text displayed in the new form exactly as you would expect. You would obviously make certain adjustments to make the form look better but I don't see why you can't implement the same principle. If you want space at the top then don't put line breaks in the text. Just leave some space between the top of the `Label` and the top of the form. Etc. |
12,009 | I need to use multiple instances of Tor with different IP addresses on each. I looked it up on google and found this [link](https://tor.stackexchange.com/questions/2006/how-to-run-multiple-tor-browsers-with-different-ips). So far I was able to make use of the "manual way" of editing everything and launching the instance. However there are a few problems I see using this method.
It takes a while to edit and launch each instance (5-10mins each)
After closing each instance, it doesn't work anymore. Hence, I have to redo each instance.
I also found in that link an answer where the guy made a "bash script." Correct me if I'm wrong, but this is for linux. Is there a way to do this in Windows? | 2016/07/03 | [
"https://tor.stackexchange.com/questions/12009",
"https://tor.stackexchange.com",
"https://tor.stackexchange.com/users/13490/"
] | When you are looking for configuration of Tor-daemon, you should take a look at this file:
```
tor-browser_en-US/Browser/TorBrowser/Data/Tor/torrc-defaults
```
I'm not on Windows, however, I can advice to you to find a correct `torrc` - config file which is used by Windows version. For example, push at one time `ctrl`+`tab`, in this manager try to change configuration to show you `full command name`, there you would find Tor-daemon process, not a TorBrowser process. So there are two processes:
* firefox --class Tor Browser -profile TorBrowser/Data/Browser/profile.default
* tor --defaults-torrc tor-browser\_en-US/Browser/TorBrowser/Data/Tor/torrc-defaults
When you done, try to read config file of Tor-daemon: `torrc-defaults`
On Linux system, it is contains next:
```
# torrc-defaults for Tor Browser
#
# This file is distributed with Tor Browser and should not be modified (it
# may be overwritten during the next Tor Browser update). To customize your
# Tor configuration, shut down Tor Browser and edit the torrc file.
#
# If non-zero, try to write to disk less frequently than we would otherwise.
AvoidDiskWrites 1
# Where to send logging messages. Format is minSeverity[-maxSeverity]
# (stderr|stdout|syslog|file FILENAME).
Log notice stdout
# Bind to this address to listen to connections from SOCKS-speaking
# applications.
SocksPort 9150 IPv6Traffic PreferIPv6 KeepAliveIsolateSOCKSAuth
ControlPort 9151
CookieAuthentication 1
## fteproxy configuration
ClientTransportPlugin fte exec ./TorBrowser/Tor/PluggableTransports/fteproxy.bin --managed
## obfs4proxy configuration
ClientTransportPlugin obfs2,obfs3,obfs4,scramblesuit exec ./TorBrowser/Tor/PluggableTransports/obfs4proxy
## meek configuration
ClientTransportPlugin meek exec ./TorBrowser/Tor/PluggableTransports/meek-client-torbrowser -- ./TorBrowser/Tor/PluggableTransports/meek-client
```
See, here `#` - it is a comment, so this line will not be handled by Tor-daemon.
Also, read the manual about this config file [here](https://www.torproject.org/docs/tor-manual.html.en).
Finally, there are only two TCP-ports used by TorBrowser's Tor-daemon by default:
* SocksPort 9150 IPv6Traffic PreferIPv6 KeepAliveIsolateSOCKSAuth
* ControlPort 9151
For each instance of TorBrowser you need to get different ports, because otherwise Tor-daemon can not bind itself on the network-subsystem, then it can not launch itself, then TorBrowser can not connect to Tor-Daemon.
Try to copy full directory of TorBrowser to separate place, edit exact `torrc`, be careful, there are many different torrc files by default, like default torrc from Tor-daemon packet, different debug torrc files, etc...
Thereafter, edit second instance by hands. Viola - you have Two different TorBrowser instance which are used two different Tor-daemons, which are binded on four different TCP-ports. | Windows can easily run Bash scripts - Windows 10 now has "Ubuntu subsystem", previous versions have "Services for Unix", there also a Cygwin, MinGW and even standalone builds of Bash+binutils for Windows, so you can obtain the package which will be best for you and *just run* your bash script on Windows. |
25,825 | I saw a comment by mpiktas that ["The sum of two independent t-distributed random variables is not t-distributed"](https://stats.stackexchange.com/questions/10856/what-is-the-distribution-of-the-difference-of-two-t-distributions). Is it then of any known distribution?
Actually, I am using piece-wise linear regression.
$E(y) = \beta\_0 + \beta\_1x + \beta\_2(x - break)\cdot d$
where
```
break = value of predictor x at the breakpoint
d = dummy variable = 1, if x > break; 0, otherwise
```
Effectively, the equation means:
$E(y) = \beta\_0 + \beta\_1x$ `if x > break`
$E(y) = (\beta\_0 – \beta\_2 \cdot break) + (\beta\_1+\beta\_2)x$ `otherwise`
And I want to know whether $x$ is a significant predictor. Couldn't find anything similar on the internet. Thus, I thought of:
1. calculating the p-value for $(\beta\_1+\beta\_2)$ to determine if $x$ is a significant predictor on the right of breakpoint (i.e. when `x > break`); and
2. using p-value for $\beta\_1$ to determine if $x$ is a significant predictor on the left of breakpoint (i.e. when `x =< break`). | 2012/04/04 | [
"https://stats.stackexchange.com/questions/25825",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/10356/"
] | These are called piecewise linear splines, you should be able to find some references on the internet also regarding different possible parametrizations (the coefficient of the second spline may represent the change in the slope from the preceding interval or it may represent the slope for the second interval).
Anyway, if you want to test against the null $H\_0: {\beta}\_{spline1} + {\beta}\_{spline2} = 0$ you can construct the significance test by hand (or, if you're using Stata, using the `test` postestimation command).
Fit your unrestricted model and then fit your restricted model under the constraint $\beta\_{spline1} + \beta\_{spline2} = 0$. At this point you can construct a $F$ test
$$
F\_{obs} = \frac{(SSE\_{restricted}-SSE\_{unrestricted})}{SSE\_{unrestricted}/(n-k\_{unrestricted}-1)}
$$
which under the null is distributed as a Snedecor's $F$ r.v. with $1$ and $n-k\_{unrestricted}-1$ degrees of freedom.
($n =$ # observations,
$k =$ # predictors) | Whuber,
Just to confirm. My equations are:
E(y) = beta0 + beta1x , if x > break
E(y) = (beta0 – beta2\*break) + (beta1+beta2)x , otherwise
Is it wrong to:
1) test the null hypothesis of beta1+beta2 = 0 to determine if x is a significant predictor on the left of breakpoint (i.e. when x =< break); and
2) use the p-value for beta1 to determine if x is a significant predictor on the left of breakpoint (i.e. when x =< break)? |
45,739,217 | I use laravel 5.3 framework and have a middleware to check for languages, redirects are correct and localization works, my question is, it is recommended to save selected language in a cookie? So I will be able to redirect the user every time to the selected language? Can it be also good for performance...
At the moment if I call `App::getLocale()` is get the right language.
I'm generally interested to know is this way correct what I do? | 2017/08/17 | [
"https://Stackoverflow.com/questions/45739217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2968642/"
] | I use this middleware to check/set the language in session for every request:
```
<?php
namespace App\Http\Middleware;
use App;
use Auth;
use Config;
use Session;
use Closure;
class SetLocale
{
public function handle($request, Closure $next)
{
// If the session doesn't have already a locale
if (!Session::has('locale')) {
// Set the logged in user language
if (Auth::check() && Auth::user()->lang->code) {
Session::put('locale', Auth::user()->lang->code);
} else {
// Else get the http header language and set it
$requestLanguage = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if (App\Lang::where('code', $requestLanguage)->exists()) {
Session::put('locale', $requestLanguage);
} else {
// If none of the above worked use the app deafult language
Session::put('locale', Config::get('app.locale'));
}
}
}
// Set the output locale as app locale
App::setLocale(Session::get('locale'));
return $next($request);
}
}
```
Hope this helps you. | For the simple one, you can try this code too..
```
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;
class SetLocale
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$default = config('app.locale');
// 2. retrieve selected locale if exist (otherwise return the default)
$locale = Session::get('locale', $default);
// 3. set the locale
App::setLocale($locale);
return $next($request);
}
}
``` |
13,707 | Using Twig, is it possible to strip out or replace a non-breaking space (` `)?
I've got a string variable `price` (returned from the [`currency`](https://craftcms.com/docs/templating/filters#currency) filter) that prints like this:
```
Nkr 100,00
```
What I'd like, is to strip the `Nkr ` part, so the string looks like this:
```
100,00
```
However, `{{ price|replace('Nkr ', '') }}` does nothing, as the `replace` filter doesn't appear to actually match the non-breaking space.
`{{ price|replace({'Nkr' : ''}) }}` strips out the `Nkr` part, but leaves the ` `; and I'm unable to remove it.
Here's what I tried already (after stripping the `Nkr` part):
```
{{ price|replace({' ' : ''}) }}
{{ price|raw|replace({' ' : ''}) }}
{{ price|striptags }}
{{ price|raw|striptags }}
{{ price|trim }}
{{ price|raw|trim }}
{{ price|replace({ '\u00a0' : '' }) }}
{{- price -}}
{% spaceless %}{{ price }}{% endspaceless %}
``` | 2016/02/16 | [
"https://craftcms.stackexchange.com/questions/13707",
"https://craftcms.stackexchange.com",
"https://craftcms.stackexchange.com/users/1098/"
] | You just think it is ` ` that get's returned from the filter, because that's how your developer tools display it, but in fact it is a *UTF-8 encoded* non-breaking space character. Have a look at the source code that is output and you won't see the ` `.
The filter gets the formatting pattern from the [app/framework/i18n/data/no.php](https://github.com/pixelandtonic/Craft-Release/blob/master/app/framework/i18n/data/no.php#L32) file. Everything in this file is UTF-8 encoded and the non-breaking space is no exception.
So how can we remove it? Copy-and-pasting doesn't always work, because it depends on the apps used. On Mac OS X 10.11 I was able to simply copy the string from the source code view in the Safari dev tools to Atom editor and it worked. I can also generate the character with `Alt`+`Space`. Copying the snippet into this answer doesn't work though, it somehow converts it to a normal space:
```
{{ price|replace('Nkr ') }}
```
**Important sidenote:**
Mac OS X users who are like me and sometimes accidentially enter a non-breaking space character into their source code and then go mad trying to fix the error, have a look at this Apple Stack Exchange post: [What's alt+spacebar character and how to disable it?](https://apple.stackexchange.com/questions/34672/whats-altspacebar-character-and-how-to-disable-it)
Atom editor users can install the [highlight-nbsp](https://atom.io/packages/highlight-nbsp) package. | Here's a different spin... Try removing everything that's **not numeric or comma**.
```
{{ price|replace('/[^0-9,]/', '') }}
``` |
13,707 | Using Twig, is it possible to strip out or replace a non-breaking space (` `)?
I've got a string variable `price` (returned from the [`currency`](https://craftcms.com/docs/templating/filters#currency) filter) that prints like this:
```
Nkr 100,00
```
What I'd like, is to strip the `Nkr ` part, so the string looks like this:
```
100,00
```
However, `{{ price|replace('Nkr ', '') }}` does nothing, as the `replace` filter doesn't appear to actually match the non-breaking space.
`{{ price|replace({'Nkr' : ''}) }}` strips out the `Nkr` part, but leaves the ` `; and I'm unable to remove it.
Here's what I tried already (after stripping the `Nkr` part):
```
{{ price|replace({' ' : ''}) }}
{{ price|raw|replace({' ' : ''}) }}
{{ price|striptags }}
{{ price|raw|striptags }}
{{ price|trim }}
{{ price|raw|trim }}
{{ price|replace({ '\u00a0' : '' }) }}
{{- price -}}
{% spaceless %}{{ price }}{% endspaceless %}
``` | 2016/02/16 | [
"https://craftcms.stackexchange.com/questions/13707",
"https://craftcms.stackexchange.com",
"https://craftcms.stackexchange.com/users/1098/"
] | Here's a different spin... Try removing everything that's **not numeric or comma**.
```
{{ price|replace('/[^0-9,]/', '') }}
``` | If you need to trim a non-breaking space which is the UTF-8 encoded non-breaking space character:
```
{{ value|trim(" \t\n\r\0\x0B\xC2\xA0") }}
```
This works because internally Twig uses the PHP `trim`, `ltrim`, and `rtrim functions`. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.