id
stringlengths 3
6
| prompt
stringlengths 100
55.1k
| response_j
stringlengths 30
18.4k
|
---|---|---|
82013 | So my system requires that Roles have associated Expiry dates. I have implemented the Identity 2.0 framework, and things are going smoothly, but I've run into an issue that is making me doubt my structure.
```
public class ApplicationUserRole : IdentityUserRole
{
public override string UserId { get; set; }
public override string RoleId { get; set; }
public DateTime Expiry { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
static ApplicationDbContext()
{
Database.SetInitializer<ApplicationDbContext>(null);
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public DbSet<ApplicationUserRole> ApplicationUserRoles { get; set; }
}
```
This does what I want it to. It changes the AspNetUserRoles table so that it adds a third column which is a DateTime called Expiry. I'm able to add, update, and remove expiries using the ApplicationDBContext, all works fine and well while editing Users.
The issue arises on Account Creation. The UserManager calls AddToRolesAsync, but only takes two parameters, User and Role. I need it to take User, Role, and an Expiry.
Do I need to implement my own UserManager? That seems like overkill.
I'm able to get around the issue by not allowing role/expiry selection on account creation, and just leaving it to edit mode. But I'd really like to be able to create accounts and assign roles/expiries at the same time. | Take a look at below video tutorial on using asp.net identity using existing database tables. I think you have to let ApplicationUser table know that you have new field in your ApplicationUserRole table. So that you have to follow entity framework model binding in order to achieve that.
Part 1 - <https://www.youtube.com/watch?v=elfqejow5hM>
Part 2 - <https://www.youtube.com/watch?v=JbSqi3Amatw>
You don't need to implement your own userManager, but you have to amend it. Hope you can use this example to support your needs. |
82037 | I don't know how to write this without it sounding like a plug (lol), but it's not. So please don't close-vote it, even if you really want your editor badge. Here goes:
There's this site called av-comparatives that I use and trust to provide me independent antivirus reviews. You probably do, too, actually. While I keep myself somewhat knowledgeable about infosec, my specialties lay elsewhere and it's so useful for me to have something like that as a resource.
I don't know of anything like that for firewalls, and when I go out to find one, I'm accosted with millions, all claiming that one product or another is the best. Cross-referencing them often leads to one or two that I've never heard of. The (I think) fairly obvious conclusion there is that these are all just fake third party review sites set up for marketing purposes.
Unfortunately, I don't have the resilience to wade through such murky waters for so many more hours :P
>
> IMPORTANT: This is **NOT** an open invitation to fake firewall review sites to post
> their crap. I will respond appropriately to spam.
>
>
>
I'm looking for legit review sites that you, as security professionals, trust (ie: on par with av-comparatives, which you probably trust too) | Possibly. It's not immediately clear if you are relying on the email address as the sole identifier (i.e. you're using it as the username) or if a separate username is in play. If the latter case, then the obvious flaw is that an attacker can supply the username of someone else, but provide their own email address as the destination for the recovery password.
Assuming the email address is the only identifier for a user, obviously it will need to be supplied by them in order to reset their password. I would suggest that regardless of whether an account associated with that email address actually exists, the system should respond similarly. (E.g. saying "Your password recovery information has been sent.") However, you would obviously only want to send the recovery email if there is a corresponding account; if no such account exists there is nothing to recover. This prevents an attacker from trying multiple addresses to see which succeed and which fail, and thus building a list of valid accounts on the system. (If your application is faster to respond if it doesn't need to send the email, you may wish to intentionally add a random bit of time delay to hide that.) |
82606 | I have created the following query:
```
SELECT wvwcs1.*, wvwcs2.* FROM wvwcs1
inner join wvwcs2 on wvwcs1.id = wvwcs2.wvwcs1_id
inner join wvwcs2 w2 on wvwcs1.id = wvwcs2.wvwcs1_id AND wvwcs2.value LIKE '%ee%'
```
My tables are created like so:
```
CREATE TABLE `wvwcs1` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`form_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1 COMMENT=' ';
CREATE TABLE `wvwcs2` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`wvwcs1_id` int(10) unsigned NOT NULL,
`value` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=latin1;
```
The data, as an example just using two records:
```
mysql> select * from wvwcs1;
+----+---------+
| id | form_id |
+----+---------+
| 1 | 23 |
| 2 | 24 |
+----+---------+
2 rows in set (0.00 sec)
mysql> select * from wvwcs2;
+----+-----------+-------+
| id | wvwcs1_id | value |
+----+-----------+-------+
| 1 | 1 | aa |
| 2 | 1 | bb |
| 3 | 1 | cc |
| 4 | 2 | aa |
| 5 | 2 | cc |
| 6 | 2 | dd |
| 7 | 2 | ee |
+----+-----------+-------+
2 rows in set (0.00 sec)
```
What I need to do, is to select all the records from `wvwcs2` where ONE of the records in `wvwcs2` is a given value. So, assume that we want to select records where `wvwcs2.value` = `dd`. In this case, we would get returned:
```
+----+-----------+-------+
| id | wvwcs1_id | value |
+----+-----------+-------+
| 4 | 2 | aa |
| 5 | 2 | cc |
| 6 | 2 | dd |
| 7 | 2 | ee |
+----+-----------+-------+
```
When I run this query currently, it gives me all records. I thought I would need to do an inner join on the same table, but I must be off. I am stumped. | I have got the same error. I realized that I have installed the **wrong apache beam** package. You need to add **[gcp]** to the package-name while installing apache beam.
```
sudo pip install apache_beam[gcp]
```
Some more optional installation to fix the installation errors and you are good to go.
```
sudo pip install oauth2client==3.0.0
sudo pip install httplib2==0.9.2
``` |
83214 | We have a bunch of unit tests which test a lot of webpages and REST API services.
Currently when our tests run it pulls from these pages live but this can take ages to run sometimes, and it also feels like the tests should be testing more of our code - not just relying on them being up and responding (if that makes sense..).
Is it better practice to save a valid api response and with the unit tests load this in during setup?
Thoughts? | It sounds like you are trying to test too much at a time yes.
You should test the code generating the response for the Rest API (if this code is under your cotrole) and the code using it completely separately. If you don't control the code generating the API you should feed the code using it with fake, valid API answers and use them for your tests.
Relying on the pages being up and responding sounds a lot more like integration testing. If you are relying on an external API, it is always interesting to have integration test to validate that the API still behaves as you expect, though. |
84250 | I've tried to install bunch of python packages in Google Cloud Platform Console. However, the disk space was not enough and installation failed. Interestingly, at some point, the network connection was lost and I should reconnect it.
And then I've checked some packages which had been already installed before I tried to install other bunch of python packages.
Expecting
```
$ python
Python 2.7.9 (default, Mar 1 2015, 12:57:24)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>>
```
But numpy was not found. This is the actual result.
```
$ python
Python 2.7.9 (default, Mar 1 2015, 12:57:24)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named numpy
>>>
```
Is this a known issue? How can I prevent happening it again?
---
**Repro steps**
1. Click "Activate Google Cloud Shell" icon on the top bar
2. I have two projects and one of the projects is selected.
3. Install python-numpy package like this :
```
Welcome to Cloud Shell! For help, visit https://cloud.google.com/cloud-shell/help.
$ sudo apt-get install python-numpy
```
4. Try to import numpy on python prompt --> it is successfully imported.
5. Close the tab of the browser or just close the shell tab
6. A few hours later (maybe 2 hours later), reopen the Cloud Shell.
7. Try to import numpy on python prompt --> "No module named numpy" error. | This is a known limitation of Google Cloud Shell - after about an hour of inactivity, any modifications outside of $HOME are lost, including installed packages. See [Custom installed software packages and persistence](https://cloud.google.com/shell/docs/limitations#custom_installed_software_packages_and_persistence "Custom installed software packages and persistence").
Also note this quote regarding [Usage limits](https://cloud.google.com/shell/docs/limitations#usage_limits "Usage limits"):
>
> If you do not access Cloud Shell regularly, we may recycle your home disk. You will receive an email notification before we do so and simply starting a session will prevent its removal. Please consider a different solution on Google Cloud Storage for sensitive data you wish to store long term.
>
>
> |
84500 | Based on [this](https://mathematica.stackexchange.com/a/655/204) I'd like to close the mathematica front end without the nagging dialog boxes that follow.
Why am I trying to do this?
I have a bash script which is such:
```
#!/bin/bash
mathematica bfile01.nb
pid1=$(pgrep mathematica)
kill -9 $pid1
! [ -z `pidof mathematica` ] || mathematica bfile02.nb
pid2=$(pgrep mathematica)
kill -9 $pid2
! [ -z `pidof mathematica` ] || mathematica bfile03.nb
```
So this is just a serial execution of several mathematica files, each of which has an [initialization cell](https://mathematica.stackexchange.com/q/9484/204) in it.
I find that unless I close the front end, the next file doesn't launch and killing the process in the unix terminal didn't quite help (very strange as this only happens with mathematica)
So any thoughts or ideas?
Edit 2: Using a mathematica script file
=======================================
[Here](http://dl.dropbox.com/u/13223318/test3.m) is a mathematica file that I converted into a script:
When I chmod it and run it, I get a bunch of error messages which don't allow my figures to be saved from the Plot3D or ContourPlot.
If you try to run the file attached (test3.m), you would want to change the file save path, `Export` in the last line of the file.
Error messages:
---------------
```
> General::stop: Further output of ReplaceAll::reps will be suppressed
> during this calculation.
```
Edit 3:
=======
In the test3.m file, I made the following changes:
Changed `hSol =` to `hSol[x_?NumericQ, y_?NumericQ, t_?NumericQ]` ([file](http://dl.dropbox.com/u/13223318/test3.m) has been uploaded).
This has changed the error messages that I get to:
```
> Part::partw: Part 3 of InterpolatingFunctionDomain[hSol] does not
> exist.
>
> Set::shape: Lists {TMin, TRup} and
> InterpolatingFunctionDomain[hSol][[3]] are not the same shape.
>
> Set::shape: Lists {nX, nY, nT} and {} are not the same shape.
```
Clearly, when run as a mathematica notebook, I never got these errors.
Edit 4:
=======
I seem to have corrected my errors after Ruebenko's last comment.
the new file is attached [here](http://dl.dropbox.com/u/13223318/test5.m).
Heres the issue that I had:
Once the package was created (.m file), when opened in a text editor, all the lines were commented out with (\*\*) which I don't know why.
However, getting rid of the comments also uncommented some text that I had previously commented so as to not use. That resulted in error messages. | Take a look at: [Programmatically quitting the FrontEnd or running without one?](https://mathematica.stackexchange.com/questions/8392/programmatically-quitting-the-frontend-or-running-without-one)
I asked some similar questions and the answers have some good strategies to do this although most of them as workarounds outside of the Mathematica front end.
A simple but key thing, adding
```
NotebookSave[]
```
to the end of your initializations cell can avoid some of the problems with pop up dialog boxes.
You may find:
```
FrontEndTokenExecute["QuitKernel"]
```
useful.
But I did not find a way to quit Mathematica with a FrontEndToken even if it directly followed saving the notebook, because unfortunately, executing a single command changes the notebook's state, which then prompts one to save the notebook on exit.
*A nice to have -- running a command in a sandbox that wouldn't affect the Front End''s state.*
No clue how to do it, but it could prove useful.
In my application I eventually ran a script on a timer and had to gauge when the notebook completed the processing it needed.
One final thought/question. Does your application require the front end to run? You can run the kernel even multiple kernels for parallel processing without a front end.
Some potentially useful links:
* [Running Mathematica without the Notebook interface](http://pages.uoregon.edu/noeckel/Mathematica.html)
* [running mathematica notebooks without interface](http://forums.wolfram.com/mathgroup/archive/2009/Apr/msg00603.html)
* [Manipulating the Front End from the Kernel](http://reference.wolfram.com/mathematica/tutorial/ManipulatingTheFrontEndFromTheKernel.html) |
85056 | I would like to create a select list on my view that allows the client to chose the customer from that select list.
My view model looks like this:
```
public int SalesOrderId { get; set; }
public int CustomerId { get; set; }
public string PONumber { get; set; }
public DateTime OrderDate { get; set; }
public List<Customer> Customers { get; set; }
public List<SalesOrderItemViewModel> SalesOrderItems { get; set; }
```
My Customer model looks like this:
```
public int CustomerId { get; set; }
public string CustomerName { get; set; }
```
My knockout js looks like this:
```
SalesOrderViewModel = function (data) {
var self = this;
// This automatically creates my view model properties for ko from my view model passed from the server
ko.mapping.fromJS(data, salesOrderItemMapping, self);
// .... Other save functions etc.
};
```
**[Edit]**
Sales Item mappings as requested
```
var salesOrderItemMapping = {
'SalesOrderItems': {
// key for each child
key: function (salesOrderItem) {
return ko.utils.unwrapObservable(salesOrderItem.SalesOrderItemId);
},
// Tell knockout what to fo for each sales order item it needs to create
create: function (options) {
// create a new sales order item view model using the model passed to the mapping definition
return new SalesOrderItemViewModel(options.data); // Notice data is a property of the options object
// Moreover, data is the data for this child and options is the object containing the parent
}
}
};
```
**[Edit]**
@Html.Raw(data) as requested:
```
{"SalesOrderId":1,"CustomerId":1,"PONumber":"123456","OrderDate":"2015-01-25T00:00:00","MessageToClient":"The original value of Customer Name is Ashfield Clutch Services.","ObjectState":0,"Customer":{"CustomerId":1,"CustomerName":"Ashfield Clutch Services"},"SalesOrderItems":[{"SalesOrderItemId":1,"ProductCode":"ABC","Quantity":10,"UnitPrice":1.23,"SalesOrderId":1,"ObjectState":0},{"SalesOrderItemId":2,"ProductCode":"XYZ","Quantity":7,"UnitPrice":14.57,"SalesOrderId":1,"ObjectState":0},{"SalesOrderItemId":3,"ProductCode":"SAMPLE","Quantity":3,"UnitPrice":15.00,"SalesOrderId":1,"ObjectState":0}],"SalesOrderItemsToDelete":[],"Customers":[{"CustomerId":1,"CustomerName":"Ashfield Clutch Services"},{"CustomerId":3,"CustomerName":"Davcom-IT Ltd"},{"CustomerId":2,"CustomerName":"Fluid Air Conditioning"}]}
```
And at the top of my view I have this js:
```
<script src="~/Scripts/salesOrderViewModel.js"></script>
<script type="text/javascript">
var salesOrderViewModel = new SalesOrderViewModel(@Html.Raw(data));
ko.applyBindings(salesOrderViewModel);
</script>
```
If I bind my select list to the `Customers` collection in my view model the select list doesn't appear to be bound correctly:
```html
<select class="form-control" name="Customers" id="Customers" data-bind="options: Customers, optionsText: CustomerName, optionsValue: CustomerId, value: CustomerId"></select>
```
![screenshot](https://i.imgur.com/Pvf8vnO.png)
You can see that instead of showing the customers it shows "`[object Window]`" for all of the customers. I think it could be half way there as it shows the correct number of "`[object Window]`" vs the number of clients in the db.
I understand that the Customers must be a knockout observable array but I'm not sure how to apply this to my js view model.
Any help would be appreciated. | Arent you missing "" in options text and options value ?
```
<select class="form-control" name="Customers" id="Customers" data-bind="options: Customers, optionsText: "CustomerName", optionsValue: "CustomerId", value: CustomerId"></select>
``` |
85138 | **On the left is Chrome and on the right is IE9.**
![enter image description here](https://i.stack.imgur.com/p9Hzi.png)
As you can see with the image above, even with the *Meyer CSS Reset* there are yet inconsistencies between browsers. Two examples in this image:
1. IE9 clearly has a darker font for just about all text.
2. For whatever reason, the `<hr/>` tags aren't lining up (but they sure are close) and that throws off the rest of the content.
Is there something more I need to do, other than applying the *Meyer CSS Reset* to get some more consistency between these browsers?
Additionally, with the content you see above, other than colors and font sizes, there are no margins or padding applied after the reset.
### CSS
```
h1 {
font-family: Lato;
font-size: 26px;
font-weight: normal;
color: #154995;
}
h2 {
font-family: Lato;
font-size: 24px;
font-weight: normal;
color: #333333;
}
h3 {
font-family: Lato;
font-size: 20px;
font-weight: normal;
color: #154995;
}
h4 {
font-family: Lato;
font-size: 18px;
font-weight: bold;
color: #333333;
}
h5 {
font-family: Lato;
font-size: 16px;
font-weight: bold;
color: #333333;
}
.small-text {
font-family: Arial, sans-serif;
font-size: 12px;
font-weight: regular;
color: #333333;
}
``` | The differences you point out are all based on the fact that two different fonts are being used in your chrome and IE9 outputs. Once you tweak the css `font-family` so both browsers use the same font then it should be ok.
**UPDATE:**
After seeing your css, you're specifying only `Lato` font for your elements, it seems both chrome and IE9 can't find the font `Lato` so both are applying a default font, which is different from one to another, try specifying fallback fonts like:
```
font-family: Lato, Arial, sans-serif;
```
If above still give you different outputs then `Lato` is being picked in one browser and not other, you can check that by using:
```
font-family: Arial, sans-serif;
```
for all your elements and see the output is the same on both browsers.
**UPDATE 2:**
Also see instructions on how to add a Lato webfont to your website:
<http://www.google.com/webfonts#UsePlace:use/Collection:Lato> |
85213 | First of all for some reason I have two different "switch keyboard layout" hotkeys: one which I set in `Settings->Devices->Keyboard` and the second one(Left ctrl + Left shift) is produced by `keyboard-configuration` package.
Calling `sudo dpkg-reconfigure keyboard-configuration` and removing hotkey binding solves the issue just until the reboot/sleep mode.
Having tried to remove `keyboard-configuration` I got the following output:
```
The following packages will be REMOVED:
console-setup console-setup-linux kbd keyboard-configuration nvidia-384 nvidia-driver-390 ubuntu-desktop ubuntu-minimal xorg xserver-xorg xserver-xorg-core
xserver-xorg-input-all xserver-xorg-input-libinput xserver-xorg-input-wacom xserver-xorg-video-all xserver-xorg-video-amdgpu xserver-xorg-video-ati
xserver-xorg-video-fbdev xserver-xorg-video-intel xserver-xorg-video-nouveau xserver-xorg-video-nvidia-390 xserver-xorg-video-qxl xserver-xorg-video-radeon
xserver-xorg-video-vesa xserver-xorg-video-vmware
```
It does not look like this package should be removed. So why there are two different sources of layout switch bindings and how can I remove one?
Thanks! | Besides running `sudo dpkg-reconfigure keyboard-configuration` you probably need to remove it from the desktop settings too. Try this command:
```
gsettings reset org.gnome.desktop.input-sources xkb-options
```
After that the removal of the extra shortcut should survive a reboot. |
85233 | As the title suggested, can we find positive measure sets$\{V\_j\}\_{j\in\alpha}$, such that $$V\_j\cap V\_k=\emptyset, \quad \cup\_{j\in\alpha}{V\_j=\mathbb{R}^{n}},$$
and the cardinal number of this set is $\aleph\_1$. | If $\mathbb{R}^n$ is the disjoint union of subsets of positive measure, there are at most $\aleph\_0$ of these subsets.
Suppose that there are an infinite number, as otherwise the proposition is evident. Partitioning any subsets of infinite measure into ones of finite measure can then be done without increasing the (infinite) cardinality of these subsets, as infinite measured portions are subdivided into countably many pieces, e.g. intersections with half-open hypercubes $\Pi[k\_i,k\_i+1)$.
Now count for each $1/r$, $r = 1,2,\ldots$, how many such subsets have measure at least $1/r$. There are at most countably many. Summing the count (including repetitions) as $r \rightarrow \infty$ shows that there are at most countably many of positive measure.
I think I remember an exercise like this in Rudin. |
85247 | Are there any set of numbers into which any of the indeterminate forms we see in a calculus course, like 00, n/0, 1infinity, etc has an answer?
I'm asking that because, thanks to the Net, I took notice of other kinds of numbers besides those commonly seen in the high school and most of the university courses: Real and Complex numbers.
There are Hyperreals, Surreals, Quaternions, ... so I thought that some indeterminate form could be have an answer among them, just like we have an answer for the x-th root, x being par, of negative numbers in the set of complex numbers. | $0^0$ and $1^\infty$ are indeterminant forms because when you have limits where the pieces approach those parts, any value is possible. They aren't usually defined even in other number systems because it doesn't mesh well with the limits (although some advanced real analysis books will define $0\*\infty$ to be $0$, they just do it so they don't have to write separate cases for some formulas).
However, $n/0$ for nonzero $n$ is *not* an indeterminate form; the only things limits that look like that can do is approach $\infty$ or $-\infty$ (or both due to oscillation, but the point is that the absolute value approaches $\infty$ in any case). As such, there is a number system where that makes total sense: [the real projective line](http://en.wikipedia.org/wiki/Real_projective_line), which adds a single "unsigned infinity" so that things which could only be $\pm\infty$ can be defined. |
85530 | I'm trying to learn how to use SQL in python with MySQL (since all my projects use MySQL), but it seems to have issues with the IF EXISTS statement.
from command line:
```
DROP TABLE IF EXISTS accessLogs;
```
returns:
```
Query ok, 0 rows affected, 1 warning (o.00 sec)
```
and the table is successfully dropped. However if I use python's execute() method:
```
cursor.execute("DROP TABLE IF EXISTS accessLogs")
```
I get this error:
```
pydbCreate.py:12: Warning: Unknown table 'accessLogs'
cursor.execute("DROP TABLE IF EXISTS accessLogs")
```
Is there a way to get around this error? And do any other MySQL commands cause similar issues? | Every warning that MySQL generates will be raised as a `Warning` by MySQLdb 1.2, unless you're using a use-result cursor. There is no code that discriminates between different warnings.
MySQLdb does not provide enough information to let Python's [`warnings`](http://docs.python.org/2/library/warnings.html) module filter things out yourself in any way except by a regexp on the message. In particular, the level and code are already lost by the time the warnings filter gets to it.
So, here are your options:
---
Use something more flexible than MySQLdb. Its successor [moist](https://github.com/farcepest/moist) may still not be ready, but competitors like [PyMySQL](https://github.com/PyMySQL/PyMySQL) are.
---
Ignore warnings around every call that you know might print warnings you don't care about:
```
with warnings.catch_warnings():
warnings.simplefilter('ignore')
cursor.execute('DROP TABLE IF EXISTS sdfdsfds') # will not warn
```
---
Ignore warnings by message string regexp:
```
warnings.filterwarnings('ignore', 'unknown table')
```
---
Turn off MySQLdb's warning raising entirely, e.g., using the quick&dirty hack of setting the `cursor._defer_warnings = True` (see the code to see why this works). (Note that you can also use this flag to turn it back on and back off again, so you only skip warnings around certain commands. But if you're going to do that, use the `warnings` module.)
---
Fork, monkeypatch, or subclass MySQLdb to override its `Cursor._warning_check` function to discriminate in some way based on the warning level and/or code. |
85700 | I tried by this
```
select module from v$sqlarea where sql_fulltext LIKE '%begin ORACLE_PKG%'
```
Any help would be appreciated. | You can get the module name by your current sql provided the module name is set by using `dbms_application_info.set_module` method within the related application :
```
declare
v_module_name varchar2(150);
begin
v_module_name := get_module_name; -- a presumed function that brings the module name
dbms_application_info.set_module( module_name => v_module_name, action_name => 'some duty');
end;
``` |
85922 | I need to pass parameters from view to controller..
**controller**
```
<?php
class Site2 extends CI_Controller{
function index(){
$this->load->helper('url');
$this->home();
}
public function getBranchDetails($b_id){
$this->load->model('bank_account_model');
$data['rresults'] = $this->bank_account_model->getAccount($b_id);
$this->load->view('view_nav',$data);
}
public function home(){
$this->load->model('get_company_model');
$this->load->model('bank_account_model');
$data['results'] = $this->get_company_model->get_All();
//$data['site2']=$this;
$this->load->view('view_header');
$this->load->view('view_nav',$data);
$this->load->view('view_content');
$this->load->view('view_footer');
}
public function company_details($id){
$this->load->model('company_detail_model');
$data['company_result'] = $this->company_detail_model->getRecords($id);
$this->load->model('get_company_model');
$data['results'] = $this->get_company_model->get_All();
$this->load->view('view_header');
$this->load->view('view_nav',$data);
$this->load->view('company_details',$data);
$this->load->view('view_footer');
}
```
**view**
```
<?php
foreach($results as $row):
?>
<div>
<ol class="tree">
<li>
<label for="folder1"><a href="<?php echo site_url('site2/company_details/'.$row->id.''); ?>"><?=$row->name?></label></a> <input type="checkbox" id="folder1" />
<ol>
<?php
//here need to pass is ($row->id);
foreach($myresult as $row2):
?>
<li>
<label for="subfolder1"><a href="#"><?=$row2->name?></a></label> <input type="checkbox" id="subfolder1" />
</li>
<?php
endforeach;
?>
</ol>
</li>
</ol>
</div>
<?php
endforeach;
?>
```
in the view inside the first foreach loop I need to pass $row->id to the controller function company\_details as a parameter.(purpose of this code is get first company ids from DB and then need to get branches according to the company id.) | it's working 100%
**controller**
```
<?php
class Site2 extends CI_Controller{
function index(){
$this->load->helper('url');
$this->home();
}
public function home(){
$this->load->model('get_company_model');
$this->load->model('bank_account_model');
$data['results_company'] = $this->get_company_model->get_All();
$data['results_branch'] = $this->get_company_model->get_branch();
$data['results_banks'] = $this->get_company_model->get_banks();
$this->load->view('view_header');
$this->load->view('view_nav',$data);
//$this->load->view('view_nav',$data_branch);
$this->load->view('view_content');
$this->load->view('view_footer');
//$this->load->view('check',$data);
}
```
**view**
```
<?php foreach($results_company as $row): ?>
<ol class="tree">
<li>
<label for="folder1"><a href="<?php echo site_url('site2/company_details/'.$row->id.''); ?>"><?php echo $row->name; ?></label></a> <input type="checkbox" id="folder1" />
<ol>
<?php foreach($results_branch as $row_branch): $count; ?>
<?php
if($row_branch->companyid == $row->id){?>
<li><label for="subfolder1"><a href="<?php echo site_url('site2/company_details/'.$row->id.''); ?>"><?php echo $row_branch->name; ?></a></label> <input type="checkbox" id="subfolder1" />
<ol>
<?php foreach($results_banks as $row_bank): $count2; ?>
<?php
if($row_bank->branch_id == $row_branch->id){?>
<li><label for="childfolder1"><a href="<?php echo site_url('site2/company_details/'.$row_bank->branch_id.''); ?>"><?php echo $row_bank->bank; ?></a></label> <input type="checkbox" id="subfolder1" /></li>
<?php } ?>
<?php endforeach; ?>
</ol>
<?php } ?>
</li>
<?php endforeach; ?>
</ol>
</li>
</ol>
<?php
endforeach;
?>
``` |
85931 | i have problem to build the 'link\_to' to action "destroy".
I have two nested routes in 'Routes.rb':
```
namespace :admin do
namespace :security do
resources :users
end
end
```
'rake routes' prints:
```
DELETE /admin/security/users/:id(.:format) admin/security/users#destroy
```
the controller is:
```
class Admin::Security::UsersController < ApplicationController
def destroy
...
end
...
```
**How to build the link\_to with http veb 'delete'?**
I unsuccessful tried:
```
<%= link_to 'destroy', user, method: :delete %>
<%= link_to 'destroy', {:controller => "admin/security/users", :action => "destroy", :id => user.id}, method: :delete %>
<%= link_to 'destroy', admin_security_users_path(user), method: :delete %>
<%= link_to 'destroy', admin_security_user_destroy_path(user), method: :delete %>
``` | You could try passing only the action and resources and leave the rest up to rails:
**UPDATE**
You should use namespaces names as a parameter to `url_for`
```
<%= link_to 'destroy', ([:destroy, :admin, :security, user]), method: :delete %>
``` |
85996 | In my spare time, I have been studying and analysing continued fractions.
I was having a conversation with someone on Discord in a Mathematics server and he was telling me that continued fractions can be related to quantum physics. He didn't go into it too much and the concept he was describing seemed a little vague to me. I am aware that Pincherle's theorem[1] asserts there is an intimate relationship with three-term recurrence relations of the form $x\_{n+1}=b\_nx\_n+a\_nx\_{n-1}$ and continued fractions, more accurately with their partial convergents, given that this recurrence relation has a minimum if a related cfrac converges. But I am not quite the physicist myself to compare physics with the properties of cfracs.
Although I can go on Google and do some research on this, I figured it might serve useful to have a post on this in this beta community, but I do apologise if it is too broad or open-ended and thus upsets any regulations here.
Any thoughts on this?
### References
[1] Pincherle, S. (1894). Delle funzioni ipergeometriche e di varie questioni ad esse attinenti. *Giorn. Mat. Battaglini*. 32:209–29
[2] Parusnikov, V. I. A Generalization of Pincherle's Theorem to k-Term Recursion Relations. *Math Notes* **2005,** *78* (5-6), 827–840. [DOI: 10.1007/s11006-005-0188-7](https://doi.org/10.1007/s11006-005-0188-7). | In the paper "[A Continued-Fraction Representation of the Time-Correlation Functions](https://academic.oup.com/ptp/article/34/3/399/1943170)", generalized susceptibilities and transport coefficients for materials are obtained using a continued-fraction expansion of the Laplace transform of the time-correlation functions.
This was the precursor to what is now called the "[hierarchical equations of motion](https://en.wikipedia.org/wiki/Hierarchical_equations_of_motion)" which are used to study the dynamics of a quantum system (such as an electron) coupled to a bosonic bath (for example the vibrations of the lattice in a GaAs semi-conductor quantum dot). This area is called "dissipative quantum dynamics" or "open quantum systems" and is used to study for example, the decoherence of qubits in solid-state quantum computers. |
86403 | I am trying to make a canvas you can draw on in vanilla JavaScript. I managed to make it so you can draw on it. However, I want to make it so you can see the dot that will be drawn if you press down. I basically want a circle that has the same styling as the drawn lines to follow the cursor. This circle is only supposed to show when it is on the canvas.
I tried a lot of solutions I found on the web, but none of them worked for me. I also set the cursor to none so a custom one could be drawn in JavaScript.
Here are the necessary parts of the HTML and JavaScript code:
```js
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
var img;
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
img = new Image();
img.onload = function(){
var ratio = this.height / this.width;
canvas.height = canvas.width * ratio;
ctx.drawImage(img,0,0,canvas.width, canvas.height);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
var pos = { x: 0, y: 0 };
document.addEventListener('mousemove', draw);
document.addEventListener('mousedown', setPosition);
document.addEventListener('mouseenter', setPosition);
function setPosition(e) {
var rect = canvas.getBoundingClientRect();
pos.x = e.clientX - rect.left
pos.y = e.clientY - rect.top
}
function draw(e) {
canvas.style.cursor = "none";
if (e.buttons !== 1) return;
console.log(pos.x)
ctx.beginPath();
ctx.lineWidth = 5;
ctx.lineCap = 'round';
ctx.strokeStyle = '#c0392b';
ctx.moveTo(pos.x, pos.y);
setPosition(e);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
canvas.style.cursor = "default";
}
```
```html
<input type="file" id="imageLoader"/>
<div class="container" id="container">
<canvas id="imageCanvas"></canvas>
</div>
``` | The most performant way to do this is to set the [CSS `cursor` property](https://developer.mozilla.org/en-US/docs/Web/CSS/cursor) to a custom image:
```js
const imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
let img;
function handleImage(e) {
// avoid data:// URLs at all costs, they are completely inefficient
img = new Image();
img.onload = function() {
var ratio = this.height / this.width;
canvas.height = canvas.width * ratio;
ctx.drawImage( img, 0, 0, canvas.width, canvas.height );
URL.revokeObjectURL( img.src );
};
img.onerror = function(e) {
console.error( "invalid image file" );
URL.revokeObjectURL( img.src );
}
img.src = URL.createObjectURL( imageLoader.files[ 0 ] );
}
const pos = { x: 0, y: 0 };
// a simple object to keep the current pen styles
const pen_style = {
color: "#FF0000",
cap: "round",
radius: 5,
canvas: document.createElement("canvas"),
cursor_url: null
};
// update the pen-style object, and the cursor
document.querySelector( "fieldset" ).oninput = updatePenStyle;
// do it once now to update the cursor
updatePenStyle();
document.addEventListener('mousemove', draw);
document.addEventListener('mousedown', setPosition);
document.addEventListener('mouseenter', setPosition);
function setPosition(e) {
const rect = canvas.getBoundingClientRect();
pos.x = e.clientX - rect.left
pos.y = e.clientY - rect.top
}
function draw(e) {
if (e.buttons !== 1) return;
ctx.beginPath();
// use the values stored in our pen_style object
ctx.lineWidth = pen_style.radius;
ctx.lineCap = pen_style.cap;
ctx.strokeStyle = pen_style.color;
ctx.moveTo(pos.x, pos.y);
setPosition(e);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
}
function updatePenStyle() {
// grab the new values
const rad = pen_style.radius = pen_radius.value;
const color = pen_style.color = pen_color.value;
const cap = pen_style.cap = pen_cap.value;
// reuse the same canvas every time
const cursor_canvas = pen_style.canvas;
const cursor_ctx = cursor_canvas.getContext( "2d" );
// update the canvas's drawing
cursor_canvas.width = cursor_canvas.height = rad;
cursor_ctx.fillStyle = color;
if( cap === "round" ) {
cursor_ctx.arc( rad / 2, rad / 2, rad / 2, 0, Math.PI * 2 );
}
else {
cursor_ctx.rect( 0, 0, rad, rad );
}
cursor_ctx.fill();
// extract it as a png image
cursor_canvas.toBlob( function( blob ) {
// revoke the previous blob URL we created (if any)
URL.revokeObjectURL( pen_style.cursor_url );
// store the new one
pen_style.cursor_url = URL.createObjectURL( blob );
// use it as CSS 'cursor'
canvas.style.cursor = `url(${ pen_style.cursor_url }) ${ rad/2 } ${ rad/2 }, auto`;
});
}
```
```css
canvas { background: lightgray }
```
```html
<fieldset>
<legend>Drawing pen settings</legend>
<label>
<input type="color" id="pen_color" value="#FF0000">Color
</label><br/>
<label>
<select id="pen_cap">
<option selected>round</option>
<option>square</option>
</select>Cap Style
</label><br/>
<label>
<input type="number" min="1" max="30" value="10" id="pen_radius">Width
</label><br/>
</fieldset>
<input type="file" id="imageLoader"/>
<div class="container" id="container">
<canvas id="imageCanvas" width="500"></canvas>
</div>
```
Over other solutions, this has the **big** advantage of not needing to repaint the whole canvas, nor anything else in the page. The CSS cursor is at a very special place in the rendering pipeline since it is the last thing to be drawn, and given it is supposed to move all the time, browsers optimize its rendering a lot, which is not too hard to do since it's unlinked to the rest of the page's rendering (it's always at the top).
An other advantage is that it requires almost no memory. Both the canvas and the image are only the size of the cursor which will probably not grow too big.
One disadvantage of this though is that this cursor is static, you can't have sparkling fires or any animations in there.
Also, and probably more of a problem for OP, you may notice that when moving the mouse quickly the canvas drawing has some difficulties to be as fast as the cursor...
That's because drawing the cursor is so much faster.
If these disadvantages are killing point, then you have two other solutions:
**Clear all - Redraw all**.
That's a good general advice, it allows to write easier to maintain code, to better handle various states and layers etc.
However redrawing the full stage every time the mouse moves (even if it's generally limited to the screen-refresh rate), is an over-kill.
Moreover when from [this question of yours](https://stackoverflow.com/questions/66786945/how-do-i-apply-context-filter-only-to-the-image-on-the-canvas) we can guess you'll also have complex filters going on.
**Do it like the browser does**
As we hinted at the beginning of this answer, the browser rendering is actually made of various layers, each [stacking context](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context) will be its own layer, rendered on its own canvas. Only the ones that are in the current viewport will get composited to produce a new bigger layer. Once this final layer has been composited the browser will clip it to the viewport and will just finally draw the cursor over this clipped and composited layer.
So the next time the cursor moves, the browser will just have to take that last state of the final composition and draw the cursor at its new position.
Well we can use the same logic at our level.
We can keep in memory an HTMLCanvasElement on which we'll perform all the drawings (the final compositor), and every time the cursor move, we'll draw that hidden canvas on an other one, visible, where we'll just have to draw the cursor after.
```js
const imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
const visible_canvas = document.getElementById('visibleCanvas');
const visible_ctx = visible_canvas.getContext('2d');
// create a copy of the canvas that we'll keep disconnected from the DOM
const hidden_canvas = visible_canvas.cloneNode();
const hidden_ctx = hidden_canvas.getContext('2d');
let img;
function handleImage(e) {
// avoid data:// URLs at all costs, they are completely inefficient
img = new Image();
img.onload = function() {
const ratio = this.height / this.width;
const width = visible_canvas.width;
const height = visible_canvas.height = width * ratio;
hidden_canvas.width = width;
// draw the image on the hidden canvas
hidden_ctx.drawImage( img, 0, 0, width, height );
URL.revokeObjectURL( img.src );
};
img.onerror = function(e) {
console.error( "invalid image file" );
URL.revokeObjectURL( img.src );
}
img.src = URL.createObjectURL( imageLoader.files[ 0 ] );
}
const pos = { x: 0, y: 0 };
document.addEventListener('mousemove', draw);
document.addEventListener('mousedown', setPosition);
document.addEventListener('mouseenter', setPosition);
function setPosition(e) {
const rect = visible_canvas.getBoundingClientRect();
pos.x = e.clientX - rect.left;
pos.y = e.clientY - rect.top;
}
function draw(e) {
const color = "red";
const radius = 5;
if (e.buttons === 1) {
// do the drawings on the hidden context
hidden_ctx.beginPath();
hidden_ctx.lineWidth = radius;
hidden_ctx.lineCap = "round";
hidden_ctx.strokeStyle = color;
hidden_ctx.moveTo(pos.x, pos.y);
setPosition(e);
hidden_ctx.lineTo(pos.x, pos.y);
hidden_ctx.stroke();
}
else {
// hasn't been updated yet
setPosition(e);
}
// even when not dragging, but only if over the canvas
if(
pos.x < visible_canvas.width && pos.x > 0 &&
pos.y < visible_canvas.height && pos.y > 0
) {
visible_ctx.clearRect(0, 0, visible_canvas.width, visible_canvas.height );
// draw the hidden canvas on the visible one
visible_ctx.drawImage( hidden_canvas, 0, 0 );
// draw the cursor
visible_ctx.beginPath();
visible_ctx.arc( pos.x + radius / 2, pos.y, radius / 2, 0, Math.PI * 2 );
visible_ctx.fillStyle = color;
visible_ctx.fill();
}
}
```
```css
canvas { cursor: none; background: lightgray; }
```
```html
<input type="file" id="imageLoader"/>
<div class="container" id="container">
<canvas id="visibleCanvas" width="500"></canvas>
</div>
```
Here what's nice is that the hidden canvas can stay as a pure bitmap and can be drawn on the visible canvas as fast as possible. It still is far less performant than the CSS cursor solution, but it avoids a huge overhead.
You could even go further and keep some parts of your drawing on their own canvas, like the browser does with all its stacking contexts, and update only the one layers that need to be updated (image / text / drawing etc.)
However beware that this solution has a big memory footprint, since you actually duplicate the bitmap buffers. |
86431 | I am new with springboot i need to setup multiple database in my project i am using postgresql this is my properties file.
If i am running my application so whatever @primay annotation i am giving only that db i able to access but i need to access both db.
Note : if i am adding both db @primary annotation then getting postconstructor 0 something error. my query in if else block sometimes i need to access abc db and sometimes i need to access xyz db but whatever in springconfig i m keeping @primary only that db url i am getting
I tried making @primary both getting exception and i tried @configurationProperties adding in my springconfig file getting exception
```
spring.datasource1.url=jdbc:postgresql://100.17.13.26:123/abc
spring.datasource1.username=ENC(vAIVaqTTZ89eYBWBDbUxgGdhciXm3GuB)
spring.datasource1.password=ENC(abZypzjEuvLfbovYs0oGdeRnUqM8e+k1)
spring.datasource1.driver-class-name=org.postgresql.Driver
spring.datasource2.url=jdbc:postgresql://100.17.13.26:123/xyz
spring.datasource2.username=ENC(vAIVaqTTZ89eYBWBDbUxgGdhciXm3GuB)
spring.datasource2.password=ENC(abZypzjEuvLfbovYs0oGdeRnUqM8e+k1)
spring.datasource2.driver-class-name=org.postgresql.Driver
```
i add in @springBootApplication SpringConfig class
```
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
@Configuration
public class SpringConfiguration {
@Autowired
private Environment env;
@Bean(name = "abc")
public DataSource firstDataSource() {
System.out.println("from first DB");
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("spring.datasource1.driver-class-name"));
dataSource.setUrl(env.getProperty("spring.datasource1.url"));
dataSource.setUsername(env.getProperty("spring.datasource1.username"));
dataSource.setPassword(env.getProperty("spring.datasource1.password"));
System.out.println("from first DB end");
return dataSource;
}
@Primary
@Bean(name = "xyz")
public DataSource secondDataSource() {
System.out.println("from second DB");
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("spring.datasource2.driver-class-name"));
dataSource.setUrl(env.getProperty("spring.datasource2.url"));
dataSource.setUsername(env.getProperty("spring.datasource2.username"));
dataSource.setPassword(env.getProperty("spring.datasource2.password"));
System.out.println("from second DB end");
return dataSource;
}
@Bean(name = "abc")
public JdbcTemplate template(@Qualifier("abc") DataSource ds) {
System.out.println("calling first db");
return new JdbcTemplate(ds);
}
@Bean(name = "xyz")
public JdbcTemplate template1(@Qualifier("xyz") DataSource ds) {
System.out.println("calling second db");
return new JdbcTemplate(ds);
}
}
``` | The cause is that the value would be cover when it exists `x['df']`.
You could use defaultdict to save them(A little different from you expect, though.But it is very easy):
```
from collections import defaultdict
a = [['kyle', 'movie_1', 'c_13'],
['blair', 'food', 'a_29'],
['reese', 'movie_2', 'abc_76']]
b = ['df.movie_1',
'ghk.food',
'df.movie_2']
x = defaultdict(list)
for i in b:
y = i.split('.')
for j in a:
if y[1] in j:
x[y[0]].append(j)
print(x)
# defaultdict(<class 'list'>, {'df': [['kyle', 'movie_1', 'c_13'], ['reese', 'movie_2', 'abc_76']], 'ghk': [['blair', 'food', 'a_29']]})
``` |
86492 | I have been declaring all the routes for my application inside web.php , but it is now getting quite large. I find that I am losing a lot of time shifting between web.php and each controller and this is hurting productivity.
I feel like it would be better to define routes inside of the controller, perhaps ideally delegating some URL to a controller and then allowing the controller to handle the "sub routes" since this would allow me to use inheritance when I have two similar controllers with similar routes. | It is not possible given how laravel works. Every request is passed onto router to find its designated spot viz. the controller with the method. If it fails to find the route within the router, it just throws the exception. So the request never reaches any controller if the route is not found. It was possible in earlier versions on Symphony where you would configure the route in the comment of a particular controller method.
Sadly with laravel it works how it works.
But for me, I just like to have the routes in a separate file. |
86532 | A month ago I sent my application for a job for X company for a full-stack job. They didn't move forward with my application because I am not senior level. I found a new DevOps job. I tried to call the HR person to apply for the job but he did not respond to my call or email. I use my nickname, alternate email and my home phone number to apply for the job.
I want to ask if changing my name to a nickname or alternate email is viewed as a scam, can I get into trouble if someone found out? | >
> I want to ask if changing my name to a nickname or alternate email is scam can I get into trouble if someone found out?
>
>
>
"Scam" is probably too strong a word - but ultimately you're asking whether attempting to circumvent the company's prior knowledge of you via obfuscating who you are is okay. You aren't *lying* (yet) but you aren't exactly being 100% honest either.
Let's take this a bit further - say they bring you in for an interview under the "new" details (nickname etc) and during that interview they ask you if you are the same person who applied for the other job. What are you going to say? Do you tell the truth? If you do and they then follow up with asking why you used different details this time around what are you going to say?
If you persist in the pretense that you are a *different* person to the original application how long do you plan on keeping that up? How long do you think you *can* keep that up? Getting rejected for lacking skills isn't a big deal, it happens all the time and is rarely personal. Getting discovered engaging in shennaigans and then getting canned with prejudice **is** a big deal.
All of this based on an *assumption* that you are being stonewalled unfairly for the DevOps role based on you prior application. You say they rejected that based on lack of senior-level skills/experience, how do you know they aren't just dismissing you for similar reasons this time around?
You're acting as if this HR person is some evil mustache-twirling villain keeping you from a job there for, well, *reasons* and if the plucky hero (you) can just outfox them you'll get to work there and everything will be sunshine and light while they stand and the side impotently shaking their fist muttering "next time, Gadget!". But life isn't a movie or a cartoon - you've sent your details in for a a couple of jobs and they didn't pan out. It sucks, but it's something that happens day in day out so don't over-invest - keep your head down and keep applying for different jobs at different companies and something **will** pan out for you, and then, sooner than you think, you'll have forgotten all about X company. Good luck! |
86649 | My page has albums. I add classes to each album according to first letter of an artist inside the album's div to filter content.
The purpose is to disable a letter's filter button if there is no artist begins with this specific letter.
I try to do something, but of course, it doesn't work, have you any idea?
The relevant code is in the third part of javascript. I have no problem with "Alphabetical filter" and "Scroll to top page".
```js
// Disabled button if no artist begin with specific letter in page
$(document).ready(function(){
$(".filter-button").ready(function(){
var letterAcount = $(".letterA").length;
var letterBcount = $(".letterB").length;
var letterCcount = $(".letterC").length;
var letterDcount = $(".letterD").length;
var letterEcount = $(".letterE").length;
var letterFcount = $(".letterF").length;
var letterGcount = $(".letterG").length;
var letterHcount = $(".letterH").length;
var letterIcount = $(".letterI").length;
var letterJcount = $(".letterJ").length;
var letterKcount = $(".letterK").length;
var letterLcount = $(".letterL").length;
var letterMcount = $(".letterM").length;
var letterNcount = $(".letterN").length;
var letterOcount = $(".letterO").length;
var letterPcount = $(".letterP").length;
var letterQcount = $(".letterQ").length;
var letterRcount = $(".letterR").length;
var letterRcount = $(".letterS").length;
var letterTcount = $(".letterT").length;
var letterUcount = $(".letterU").length;
var letterVcount = $(".letterV").length;
var letterWcount = $(".letterW").length;
var letterXcount = $(".letterX").length;
var letterYcount = $(".letterY").length;
var letterZcount = $(".letterZ").length;
if($letterAcount.length == 0)
$(this).addClass('disabled');
if($letterBcount.length == 0)
$(this).addClass('disabled');
if($letterCcount.length == 0)
$(this).addClass('disabled');
if($letterDcount.length == 0)
$(this).addClass('disabled');
if($letterEcount.length == 0)
$(this).addClass('disabled');
if($letterFcount.length == 0)
$(this).addClass('disabled');
if($letterGcount.length == 0)
$(this).addClass('disabled');
if($letterHcount.length == 0)
$(this).addClass('disabled');
if($letterIcount.length == 0)
$(this).addClass('disabled');
if($letterJcount.length == 0)
$(this).addClass('disabled');
if($letterKcount.length == 0)
$(this).addClass('disabled');
if($letterLcount.length == 0)
$(this).addClass('disabled');
if($letterMcount.length == 0)
$(this).addClass('disabled');
if($letterNcount.length == 0)
$(this).addClass('disabled');
if($letterOcount.length == 0)
$(this).addClass('disabled');
if($letterPcount.length == 0)
$(this).addClass('disabled');
if($letterQcount.length == 0)
$(this).addClass('disabled');
if($letterRcount.length == 0)
$(this).addClass('disabled');
if($letterScount.length == 0)
$(this).addClass('disabled');
if($letterTcount.length == 0)
$(this).addClass('disabled');
if($letterUcount.length == 0)
$(this).addClass('disabled');
if($letterVcount.length == 0)
$(this).addClass('disabled');
if($letterWcount.length == 0)
$(this).addClass('disabled');
if($letterXcount.length == 0)
$(this).addClass('disabled');
if($letterYcount.length == 0)
$(this).addClass('disabled');
if($letterZcount.length == 0)
$(this).addClass('disabled');
});
});
```
```css
body {
font-family: Arial;
font-size: 14pt;
font-weight: bold;
color: #cc6110;
background-color: #e3e0ce; /* Nenesse 8/17/2017: New color */
background-image: url(images/background-woodenfloor.jpg); /* Nenesse 8/16/2017: New background image */
}
.title {
font-size : 24pt;
font-weight: bold;
color: #cc6110; /* Nenesse 8/16/2017: New color */
}
a {
font-size: 14pt;
color: #285e80; /* Nenesse 8/16/2017: New color instead of #FFFFFF */
text-decoration: none;
}
a:hover {
text-decoration: underline;
color: #cc6110;
}
a:hover img#thumbimage {
text-decoration: none;
}
.artist {
/* Nenesse 8/16/2017: New class for different color */
color: #285e80;
font-size:12pt;
font-weight:bold;
}
.album {
/* Nenesse 8/16/2017: new class for different color */
color: #cc6110;
font-size:10pt;
font-weight:bold;
}
.card {
margin-top: 30px;
position: inherit;
}
.filter-button {
font-size: 18px;
border: 1px solid #cc6110;
border-radius: 5px;
text-align: center;
color: #cc6110;
}
.filter-button:hover {
font-size: 18px;
border: 1px solid #cc6110;
border-radius: 5px;
text-align: center;
color: #ffffff;
background: #285e80;
}
.btn.filter-button:after {
background: #285e80;
}
.btn-default:active .filter-button:active {
background: #285e80;
color: white;
}
.btn{
text-transform: uppercase;
position: relative;
transform: translateZ(0px);
transition: all 0.5s ease 0s;
}
.btn:after{
content: "";
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: #fff;
z-index: -1;
transform: scaleX(0);
transform-origin: 100% 50% 0;
transition: all 0.5s ease-out 0s;
}
.btn:hover:after{
transform: scaleX(1);
transition-timing-function: cubic-bezier(0.52, 1.64, 0.37, 0.66);
}
.row {
margin-left: 0;
margin-right:0;
}
/* BackToTopPage button */
.back-to-top {
position: fixed;
bottom: 30px;
right: 30px;
background: rgb(40, 94, 128);
background: rgba(40, 94, 128, 0.8);
width: 50px;
height: 50px;
display: block;
text-decoration: none;
-webkit-border-radius: 35px;
-moz-border-radius: 35px;
border-radius: 35px;
display: none;
-webkit-transition: all 0.3s linear;
-moz-transition: all 0.3s ease;
-ms-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;
}
.back-to-top i {
color: #fff;
margin: 0;
position: relative;
left: 16px;
top: 13px;
font-size: 19px;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-ms-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;
}
.back-to-top:hover {
background: rgba(204,97,16, 0.9);
}
.back-to-top:hover i {
color: #fff;
top: 5px;
}
/* BackToTopPage tooltip */
.tooltip-inner {
color:white;
font-weight:400;
background-color:rgba(40, 94, 128, 0.9);
}
.tooltip.bs-tooltip-auto[x-placement^=right] .arrow::before, .tooltip.bs-tooltip-top .arrow::before {
border-top-color: rgba(40, 94, 128, 0.9);
}
```
```html
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
<title>Album List</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"></link>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css"></link>
<link rel="StyleSheet" type="text/css" href="enhanced exportindex_wood.css"></link>
<meta http-equiv="cache-control" content="no-cache"/>
</head>
<body>
<div class="container-fluid">
<a id="back-to-top" href="#" class="back-to-top btn-custom" role="button" title="Go Top" data-toggle="tooltip" data-placement="top">
<i class="icon-chevron-up"></i>
</a>
<div class="row">
<div class="col col-lg-12 col-md-12 col-sm-12 col-xs-12" style="color: #cc6110;" align="center">
<h1 class="title">Album List</h1>
</div>
</div>
<div align="center">
<button class="btn btn-default filter-button" data-filter="all">All</button>
<button class="btn btn-default filter-button" data-filter="letterA">A</button>
<button class="btn btn-default filter-button" data-filter="letterB">B</button>
<button class="btn btn-default filter-button" data-filter="letterC">C</button>
<button class="btn btn-default filter-button" data-filter="letterD">D</button>
<button class="btn btn-default filter-button" data-filter="letterE">E</button>
<button class="btn btn-default filter-button" data-filter="letterF">F</button>
<button class="btn btn-default filter-button" data-filter="letterG">G</button>
<button class="btn btn-default filter-button" data-filter="letterH">H</button>
<button class="btn btn-default filter-button" data-filter="letterI">I</button>
<button class="btn btn-default filter-button" data-filter="letterJ">J</button>
<button class="btn btn-default filter-button" data-filter="letterK">K</button>
<button class="btn btn-default filter-button" data-filter="letterL">L</button>
<button class="btn btn-default filter-button" data-filter="letterM">M</button>
<button class="btn btn-default filter-button" data-filter="letterN">N</button>
<button class="btn btn-default filter-button" data-filter="letterO">O</button>
<button class="btn btn-default filter-button" data-filter="letterP">P</button>
<button class="btn btn-default filter-button" data-filter="letterQ">Q</button>
<button class="btn btn-default filter-button" data-filter="letterR">R</button>
<button class="btn btn-default filter-button" data-filter="letterS">S</button>
<button class="btn btn-default filter-button" data-filter="letterT">T</button>
<button class="btn btn-default filter-button" data-filter="letterU">U</button>
<button class="btn btn-default filter-button" data-filter="letterV">V</button>
<button class="btn btn-default filter-button" data-filter="letterW">W</button>
<button class="btn btn-default filter-button" data-filter="letterX">X</button>
<button class="btn btn-default filter-button" data-filter="letterY">Y</button>
<button class="btn btn-default filter-button" data-filter="letterZ">Z</button>
</div>
</div>
<hr/>
<div class="row">
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterB">
<a href="details/8660.html">
<img class="card-img-top rounded img-fluid" src="images/8660t.jpg" alt="Image Afrikan Basement - Unreleased Extended Versions - Disc 1"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">Bolla</h4>
<p class="card-text text-center album">Afrikan Basement - Unreleased Extended Versions - Disc 1</p>
</div>
</div>
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterB">
<a href="details/8666.html">
<img class="card-img-top rounded img-fluid" src="images/8666t.jpg" alt="Image Afrikan Basement - Unreleased Extended Versions - Disc 2"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">Bolla</h4>
<p class="card-text text-center album">Afrikan Basement - Unreleased Extended Versions - Disc 2</p>
</div>
</div>
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterJ letterD">
<a href="details/8881.html">
<img class="card-img-top rounded img-fluid" src="images/8881t.jpg" alt="Image A Journey To Rotterdam"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">Jephté Guillaume | Diephuis</h4>
<p class="card-text text-center album">A Journey To Rotterdam</p>
</div>
</div>
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterL">
<a href="details/412.html">
<img class="card-img-top rounded img-fluid" src="images/412t.jpg" alt="Image La Home Box - Disc 4"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">Laurent Garnier</h4>
<p class="card-text text-center album">La Home Box - Disc 4</p>
</div>
</div>
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterL letterT letterB">
<a href="details/376.html">
<img class="card-img-top rounded img-fluid" src="images/376t.jpg" alt="Image La Home Box - Disc 3"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">Laurent Garnier | Traumer | Bambounou</h4>
<p class="card-text text-center album">La Home Box - Disc 3</p>
</div>
</div>
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterL letterT letterH">
<a href="details/447.html">
<img class="card-img-top rounded img-fluid" src="images/447t.jpg" alt="Image La Home Box - Disc 5"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">Laurent Garnier | Traumer | Husbands</h4>
<p class="card-text text-center album">La Home Box - Disc 5</p>
</div>
</div>
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterL letterU letterM">
<a href="details/305.html">
<img class="card-img-top rounded img-fluid" src="images/305t.jpg" alt="Image La Home Box - Disc 1"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">Laurent Garnier | Uner | Marc Romboy</h4>
<p class="card-text text-center album">La Home Box - Disc 1</p>
</div>
</div>
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterL letterV letterC">
<a href="details/341.html">
<img class="card-img-top rounded img-fluid" src="images/341t.jpg" alt="Image La Home Box - Disc 2"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">Laurent Garnier | Voiski | Copy Paste Soul</h4>
<p class="card-text text-center album">La Home Box - Disc 2</p>
</div>
</div>
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterM">
<a href="details/10344.html">
<img class="card-img-top rounded img-fluid" src="images/10344t.jpg" alt="Image Dj-Kicks - Disc 1"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">Moodymann</h4>
<p class="card-text text-center album">Dj-Kicks - Disc 1</p>
</div>
</div>
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterM">
<a href="details/10307.html">
<img class="card-img-top rounded img-fluid" src="images/10307t.jpg" alt="Image Dj-Kicks - Disc 2"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">Moodymann</h4>
<p class="card-text text-center album">Dj-Kicks - Disc 2</p>
</div>
</div>
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterM">
<a href="details/10124.html">
<img class="card-img-top rounded img-fluid" src="images/10124t.jpg" alt="Image Dj-Kicks - Disc 3"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">Moodymann</h4>
<p class="card-text text-center album">Dj-Kicks - Disc 3</p>
</div>
</div>
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterS letterL letterA letterR">
<a href="details/8897.html">
<img class="card-img-top rounded img-fluid" src="images/8897t.jpg" alt="Image Hagagatan Remixed"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">Svreca | Lucy | Alexey Volkov | Rødhåd</h4>
<p class="card-text text-center album">Hagagatan Remixed</p>
</div>
</div>
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterT">
<a href="details/10673.html">
<img class="card-img-top rounded img-fluid" src="images/10673t.jpg" alt="Image North Star / Silent Space"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">Tale Of Us</h4>
<p class="card-text text-center album">North Star / Silent Space</p>
</div>
</div>
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterT">
<a href="details/8820.html">
<img class="card-img-top rounded img-fluid" src="images/8820t.jpg" alt="Image Goddess Of A New Dawn"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">The Bayara Citizens</h4>
<p class="card-text text-center album">Goddess Of A New Dawn</p>
</div>
</div>
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterT">
<a href="details/8719.html">
<img class="card-img-top rounded img-fluid" src="images/8719t.jpg" alt="Image Mofo Congoietric"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">The Bayara Citizens</h4>
<p class="card-text text-center album">Mofo Congoietric</p>
</div>
</div>
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterT">
<a href="details/9074.html">
<img class="card-img-top rounded img-fluid" src="images/9074t.jpg" alt="Image The Girl And The Chameleon - Disc 1"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">The Exaltics</h4>
<p class="card-text text-center album">The Girl And The Chameleon - Disc 1</p>
</div>
</div>
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterT">
<a href="details/9033.html">
<img class="card-img-top rounded img-fluid" src="images/9033t.jpg" alt="Image The Girl And The Chameleon - Disc 2"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">The Exaltics</h4>
<p class="card-text text-center album">The Girl And The Chameleon - Disc 2</p>
</div>
</div>
<div style="" class="card bg-transparent col-lg-3 col-md-4 col-sm-6 filter letterT letterJ">
<a href="details/8777.html">
<img class="card-img-top rounded img-fluid" src="images/8777t.jpg" alt="Image Joaquin Joe Claussell Mixes"/>
</a>
<div class="card-block">
<h4 class="card-title text-center artist">The Lower East Side Pipes | Joe Claussell</h4>
<p class="card-text text-center album">Joaquin Joe Claussell Mixes</p>
</div>
</div>
</div>
<div class="row">
<br/>
<div class="value col-xs-6 col-sm-6 col-md-6" align="left">20/09/2017 01:14:33</div>
<div class="value col-xs-6 col-sm-6 col-md-6" align="Right">Powered by
<a target="_blank" href="https://www.collectorz.com/music" title="Music Collector">Music Collector</a> & JHR Enhanced Details template
</div>
<br/>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script src="indexfilter.js"></script>
</body>
```
Thanks for your help. | Still, you facing the issue
Add this Jar in Build path ->modulerpath
Add this jar
<https://mvnrepository.com/artifact/org.hamcrest/hamcrest-all/1.3>
And the issue will be resolved. |
87152 | I'm trying to simply start the chrome driver but getting some timeout errors. the browser does start but then closed after few sec with the following exception:
System info:
```
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
System info: host: 'MAC-images-MacBook-Pro-1164.local', ip: '----', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.13.6', java.version: '1.8.0_172'
Driver info: driver.version: ChromeDriver] with root cause
at java.util.concurrent.FutureTask.get(FutureTask.java:205)
~[na:1.8.0_172] at
com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:156)
~[guava-25.0-jre.jar:na] at
org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75)
~[selenium-remote-driver-3.14.0.jar:na] at
org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:188)
~[selenium-remote-driver-3.14.0.jar:na] at
org.openqa.selenium.remote.service.DriverService.start(DriverService.java:179)
~[selenium-remote-driver-3.14.0.jar:na] at
org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
~[selenium-remote-driver-3.14.0.jar:na] at
org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548)
~[selenium-remote-driver-3.14.0.jar:na] at
org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:212)
~[selenium-remote-driver-3.14.0.jar:na] at
org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:130)
~[selenium-remote-driver-3.14.0.jar:na] at
org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
~[selenium-chrome-driver-3.14.0.jar:na] at
org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
~[selenium-chrome-driver-3.14.0.jar:na] at
org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
~[selenium-chrome-driver-3.14.0.jar:na] at
com.example.tests.bl.impl.AutomationRunner.run(AutomationRunner.java:29)
~[classes/:na]
```
Code snip:
```
@Component
public class AutomationRunner implements IAutomationRunner {
@Override
public void run() throws MalformedURLException {
System.setProperty("webdriver.chrome.driver",
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome");
ChromeDriver driver = new ChromeDriver();
driver.get("www.google.com");
driver.close();
driver.quit();
}
}
```
Packages been used :
```
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
```
Any idea on what do I miss here? Thanks! | This error message...
```
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
System info: host: 'MAC-images-MacBook-Pro-1164.local', ip: '----', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.13.6', java.version: '1.8.0_172'
Driver info: driver.version: ChromeDriver
.
com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:156)
~[guava-25.0-jre.jar:na] at
org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75)
```
...implies that the **ChromeDriver** was unable to initiate/spawn a new **WebBrowser** i.e. **Chrome Browser** session.
Your main issue is within the `System.setProperty()` line where you have passed the *absolute path* of the *Google Chrome* binary instead of ***ChromeDriver*** binary.
---
Solution
--------
You need to download the relevant *ChromeDriver* binary for **Mac OS X** i.e. [**chromedriver\_mac64**](https://chromedriver.storage.googleapis.com/index.html?path=2.46/) and place it anywhere within your system, extract the *ChromeDriver* binary and pass the *absolute path* within the `System.setProperty()` as follows:
```
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
``` |
87406 | I have shifted our live server to a new server configuration Windows 2008 server and sql server 2008.
But I am having following exception while adding date field data :
>
> 2011-05-15 18:00:44,263 ERROR Error
> caught : the details of the error are
> System.Data.SqlTypes.SqlTypeException:
> SqlDateTime overflow. Must be between
> 1/1/1753 12:00:00 AM and 12/31/9999
> 11:59:59 PM. at
> System.Data.SqlTypes.SqlDateTime.FromTimeSpan(TimeSpan
> value)
>
>
>
But the same code is working fine on local machine and was also working fine on old server.
I have even changed the date field explicitly into **"mm/dd/yy"** format.
But still not found the solution.
Can anyone provide me the solution. | There's actually three things: A Website, a Store and a Store View.
The most important part about Websites is that each websites has its unique customer and order base.
Stores can be used to define for example different (looking) stores with the same information.
Store Views are mostly used to handle different languages on your website. You will typically have one Store View per language. |
87609 | I am sending this from the frontend via POST ajax:
It consists of JSON array and object.
EDIT: I have set :
```
contentType: 'application/json'
```
The exact JSON is sent as follows:
```
{
"alertKeeperDTOs": [
{
"isSelected": true,
"rn": 0,
"keeperId": "B116453993D52735E0530A10CA0A9D27",
"keeperName": "myName"
},
{
"isSelected": false,
"rn": 1,
"keeperId": "65EE22D4A55C4437A4F5552CBFD8D6D0",
"keeperName": "test",
}
],
"deviceId": 4
}
```
I am trying to get this from the Controller:
(EDITED)
```
public @ResponseBody String updateDeviceToKeeperList(@RequestBody List<AlertKeeperDTO> alertKeeperDTOs,
@RequestBody Long deviceId, HttpServletRequest request){
....
}
```
But I am getting an error (HTTP 400):
>
> Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.util.ArrayList` out of START\_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of START\_OBJECT token
> at [Source: (PushbackInputStream); line: 1, column: 1]]
>
>
>
How can I code my controller backend? Please help. Thanks. | In the code in your question the hole in the 8 is a different path. In order to make it a real hole I've merged the 2 paths by combining the d attributes.
However it may not work for all the paths in your code. Give it a try and let me know how it works.
Please observe that I've changed the initial m comand to M when merging the 2 d attributes.
Also: in this case the fill-rule="evenodd" is not required but it may help for other paths.
```html
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="771pt" height="310pt" viewBox="64 235 10 15" version="1.1">
<g id="surface1">
<path
id="path94"
d="m 68.378906,235.66406 -0.265625,0.0117 -0.464843,0.10547 -0.214844,0.0625 -0.203125,0.0664 -0.183594,0.0859 -0.167969,0.082 -0.132812,0.082 -0.128906,0.0859 -0.117188,0.0625 -0.08594,0.0664 -0.06641,0.0508 -0.05078,0.0508 -0.03125,0.0156 -0.01563,0.0195 -0.148437,0.16406 -0.152344,0.16797 -0.117188,0.18359 -0.09766,0.1836 -0.167969,0.34765 -0.09766,0.33203 -0.07031,0.28516 -0.01563,0.13281 -0.01953,0.0977 -0.01172,0.10156 v 0.11719 l 0.01172,0.29687 0.05078,0.28516 0.06641,0.25 0.08594,0.21484 0.06641,0.16797 0.06641,0.13282 0.05078,0.0664 0.01563,0.0352 0.183594,0.19922 0.199219,0.18359 0.214843,0.16797 0.214844,0.13281 0.203125,0.0977 0.148438,0.0664 0.06641,0.0312 0.05078,0.0195 0.01563,0.0195 h 0.01953 l -0.386718,0.11328 -0.3125,0.14844 -0.28125,0.1875 -0.234375,0.16406 -0.183594,0.16406 -0.136719,0.13672 -0.06641,0.082 -0.03125,0.0156 v 0.0195 l -0.183594,0.30078 -0.148437,0.3125 -0.101563,0.30078 -0.06641,0.30078 -0.03516,0.26563 -0.01563,0.11328 v 0.10156 l -0.01563,0.0664 v 0.11718 l 0.01563,0.26953 0.03516,0.26172 0.05078,0.25391 0.06641,0.24609 0.164063,0.41797 0.08594,0.19922 0.09766,0.16797 0.101562,0.16406 0.08203,0.13672 0.101563,0.11719 0.06641,0.0977 0.06641,0.082 0.08203,0.082 0.01563,0.0195 0.199218,0.18359 0.21875,0.14844 0.234375,0.13281 0.234375,0.11719 0.214844,0.082 0.234375,0.0859 0.445313,0.11719 0.203125,0.0469 0.179687,0.0352 0.167969,0.0156 0.148437,0.0156 0.117188,0.0195 h 0.167969 l 0.316406,-0.0195 0.285156,-0.0312 0.28125,-0.0508 0.265625,-0.0508 0.230469,-0.082 0.234375,-0.082 0.21875,-0.0859 0.179687,-0.10156 0.167969,-0.0977 0.152344,-0.0859 0.117187,-0.0781 0.117188,-0.0859 0.07813,-0.0508 0.05078,-0.0469 0.05078,-0.0508 0.183594,-0.20313 0.167969,-0.19531 0.128906,-0.20312 0.117188,-0.21485 0.117187,-0.20312 0.08594,-0.21485 0.117187,-0.3789 0.04687,-0.1875 0.03516,-0.16407 0.01563,-0.15234 0.01953,-0.11719 0.01563,-0.0977 v -0.14844 l -0.01563,-0.38672 -0.07031,-0.34766 -0.09766,-0.3164 -0.101563,-0.26563 -0.09766,-0.21875 -0.101562,-0.16406 -0.06641,-0.0977 -0.01953,-0.0195 v -0.0156 l -0.230469,-0.26563 -0.25,-0.23437 -0.265625,-0.1836 -0.25,-0.16796 -0.230468,-0.11329 -0.203125,-0.0859 -0.06641,-0.0312 -0.05078,-0.0195 -0.03125,-0.0117 H 70.3125 l 0.300781,-0.13672 0.246094,-0.14844 0.21875,-0.15234 0.183594,-0.14844 0.128906,-0.13281 0.101563,-0.0977 0.06641,-0.0703 0.01953,-0.0312 0.148438,-0.23438 0.101562,-0.23437 0.07813,-0.23047 0.05078,-0.23438 0.03516,-0.18359 0.01953,-0.14844 v -0.13281 l -0.01953,-0.23437 -0.01563,-0.21875 -0.117188,-0.41407 -0.148437,-0.36328 -0.167969,-0.32031 -0.167969,-0.24609 -0.08203,-0.10157 -0.06641,-0.10156 -0.148438,-0.14844 -0.183594,-0.15234 -0.183593,-0.14844 -0.199219,-0.11719 -0.199219,-0.0977 -0.402344,-0.15235 -0.398437,-0.0977 -0.164063,-0.0508 -0.167968,-0.0156 -0.152344,-0.0195 -0.132813,-0.0117 -0.09766,-0.0195 h -0.148437 z
M 68.542969,236.8125 h 0.136719 l 0.28125,0.0156 0.269531,0.0625 0.214844,0.0859 0.199218,0.0977 0.152344,0.10156 0.113281,0.082 0.08203,0.0703 0.01953,0.0156 0.183594,0.21484 0.132812,0.21875 0.09766,0.21485 0.07031,0.19922 0.03125,0.18359 0.03516,0.14844 v 0.13672 l -0.01953,0.26171 -0.06641,0.25391 -0.08203,0.21484 -0.101562,0.1836 -0.09766,0.14844 -0.08594,0.10156 -0.06641,0.082 -0.01563,0.0156 -0.199219,0.16797 -0.234375,0.13282 -0.214844,0.082 -0.214843,0.0664 -0.203125,0.0352 -0.148438,0.0156 -0.09766,0.0195 h -0.03516 l -0.300782,-0.0195 -0.265625,-0.0664 -0.234375,-0.082 -0.199218,-0.0977 -0.148438,-0.0859 -0.117187,-0.082 -0.08594,-0.0664 -0.01172,-0.0195 -0.167968,-0.19921 -0.132813,-0.23047 -0.08594,-0.21875 -0.06641,-0.21485 -0.03125,-0.18359 -0.01953,-0.14844 -0.01172,-0.10156 v -0.0352 l 0.01172,-0.26172 0.06641,-0.23437 0.08594,-0.21875 0.09766,-0.18359 0.08594,-0.14844 0.08203,-0.11719 0.06641,-0.0664 0.01953,-0.0156 0.214844,-0.18359 0.214844,-0.13282 0.234375,-0.0859 0.214844,-0.0625 0.199218,-0.0352 z m 0,0" style="fill:#ff00f3;fill-opacity:1;fill-rule:evenodd;stroke:none" />
</g>
</svg>
``` |
87877 | I have used an example and can successfully read data using php and mysql and plot it (timebase vs a variable), all works fine. I have taken that and used it as a template and used a different db that doesn't use a timebase but the graph isn't rendering. The graph is meant to display data from an SQL query that collates the frequency of occurrence of a variable with the variable on the x axis and the frequency of occurrence on the Y axis.
The chart pops up with the x and y axis values as expected. It looks right; except the plot is missing. To assist my troubleshooting I have listed the data on the screen albeit not pretty- this proves the db is being called correctly and there are no obvious SQL errors and that data is being returned.
db\_code`
```
<?php
$con = mysql_connect("localhost","root","hal9000");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sqm", $con);
$result = mysql_query("SELECT magnitude, COUNT(*) AS xxx FROM data WHERE magnitude > 1 GROUP by magnitude");
while($row = mysql_fetch_array($result)) {
echo $row['magnitude'] . "\t" . $row['xxx']. "\n";
}
mysql_close($con);
?> `
```
main\_page code
```
<script type="text/javascript">
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'common_LHS',
defaultSeriesType: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Magnitude',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
plotOptions: {
series: {
marker: {
enabled: true,
symbol: 'circle',
radius: 0
}
}
},
xAxis: {
type: 'linear',
tickWidth: 0,
gridLineWidth: 1,
labels: {
align: 'center',
x: -3,
y: 20
}
},
yAxis: {
title: {
text: 'Frequency of occurrence'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
tooltip: {
crosshairs: [{
width: 2,
color: 'red'
}, {
width: 2,
color: 'red'
}],
},
series: [{
name: 'Occurrence',
}]
}
jQuery.get('data.php', null, function(tsv) {
var lines = [];
traffic = [];
try {
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
traffic.push ([
parseFloat(line[0]), //need to parseFloat to convert data to float from string
parseFloat(line[1])
]);
});
} catch (e) { }
options.series[0].data = traffic;
chart = new Highcharts.Chart(options);
});
});
```
The data looks as I expected when graphed in LibreCalc, apart from the line not rendering it is almost done in Highcharts.
Appreciate any advice. Unfortunately since I am new to this forum I can't submit images but happy to send them to someone if it helps.
Expect it is something simple, usually is :) | just put the strings you want for flavor1 into:
```
src/flavor1/res/values/strings.xml
```
and the strings for flavor2 into:
```
src/flavor2/res/values/strings.xml
```
no need to put logic into your gradle file |
88050 | I have a background thread that is querying an Oracle database via a Select statement. The statement is populating a ResultSet Java object. If the query returns a lot of rows, the ResultSet object might get very large. If it's too large, I want to both cancel the background thread, but more importantly I want to cancel the thread that is creating the ResultSet object and eating up a lot of Java memory.
From what I have read so far online, `java.sql.Statement cancel()`, seems to be the best way to get this done, can anyone confirm this? is there a better way?
`java.sql.Statement close()` also works, I could probably catch the ExhaustedResultset exception, but maybe that's not safe.
To clarify, I do not want the ResultSet or the thread - I want to discard both completely from memory. | Please use ViewHolder pattern, and also add your gridMain\_text.xml
else you will keep receiving wrong index of click
<http://www.binpress.com/tutorial/smooth-out-your-listviews-with-a-viewholder/9>
This is example of ListView but equally applicable for `GridView` |
88866 | I've installed Apache Spark 1.5.2 (for Hadoop 2.6+). My cluster contains of the following hardware:
* Master: 12 CPU Cores & 128 GB RAM
* Slave1: 12 CPU Cores & 64 GB RAM
* Slave2: 6 CPU Cores & 64 GB RAM
Actually my slaves file has the two entries:
```
slave1_ip
slave2_ip
```
Because my master also has a very "strong" hardware, it wouldn't be used to capacity only by the master threads. So I wanted to ask whether it is possible to provide some of the CPU cores and the RAM from the master machine to a third worker instance...? Thank you!
---
**FIRST ATTEMPT TO SOLVE THE PROBLEM**
After Jacek Laskowski's answer I set the following settings:
```
spark-defaults.conf (only on Master machine):
spark.driver.cores=2
spark.driver.memory=4g
spark-env.sh (on Master):
SPARK_WORKER_CORES=10
SPARK_WORKER_MEMORY=120g
spark-env.sh (on Slave1):
SPARK_WORKER_CORES=12
SPARK_WORKER_MEMORY=60g
spark-env.sh (on Slave2):
SPARK_WORKER_CORES=6
SPARK_WORKER_MEMORY=60g
```
I also added the master's ip address to the `slaves` file.
The cluster now contains of 3 worker nodes (slaves + master), that's perfect.
BUT: The web UI shows that there're only 1024m of RAM per node, see Screenshot:
[![enter image description here](https://i.stack.imgur.com/FpdxJ.png)](https://i.stack.imgur.com/FpdxJ.png)
Can someone say how to fix this? Setting spark.executor.memory will set the same amount of RAM for each machine, which wouldn't be optimal to use as much RAM as possible...! What am I doing wrong? Thank you! | It's possible. Just limit the number of cores and memory used by the master and run one or more workers on the machine.
Use `conf/spark-defaults.conf` where you can set up `spark.driver.memory` and `spark.driver.cores`. Consult [Spark Configuration](http://spark.apache.org/docs/latest/configuration.html).
You should however use `conf/spark-env.sh` to set up more than one instance per node using `SPARK_WORKER_INSTANCES`. Include the other settings as follows:
```
SPARK_WORKER_INSTANCES=2
SPARK_WORKER_CORES=2
SPARK_WORKER_MEMORY=2g
```
You may also want to set up the number of RAM for executors (per worker) using `spark.executor.memory` or `SPARK_EXECUTOR_MEMORY` (as depicted in the following screenshot).
[![Memory per Node in Spark Standalone's web UI](https://i.stack.imgur.com/02pd2.png)](https://i.stack.imgur.com/02pd2.png) |
89468 | I am currently learning Laravel 5 and am experimenting with user logins and registration.
I used the command:
```
php artisan make:migration create_users_table --create=users
```
the first time i ran this command it worked perfectly and created a migration file with a selection of fields typically required for users, such as email, password etc.
I ran into some trouble and had to delete and recreate my migration files whilst troubleshooting. However now I am unable to get the same result when running the command. I just get the default:
```
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
```
could someone help?
Thanks | There is default migration file for users. I think you have not check after installing the laravel. Check the default migration file in github bellow
[default migration file](https://github.com/laravel/laravel/tree/master/database/migrations) |
89497 | I am returning a value from my database. The data type is a string. I checked with TypeName. However, my if condition never works despite it printing the value I am checking for. Any ideas?
```
while NOT prs.EOF
RecordStatus = prs("status")
If (RecordStatus = "S") Then
response.write("Scheduled!<br>")
prs.MoveNext
Else
response.write(RecordStatus & "<BR>")
prs.MoveNext
End If
Wend
prs.Close
``` | Also, consider placing MoveNext to last line.
```
while NOT prs.EOF
RecordStatus = prs("status")
If (Trim(RecordStatus) = "S") Then
response.write("Scheduled!<br>")
Else
response.write(RecordStatus & "<BR>")
End If
prs.MoveNext
Wend
prs.Close
``` |
89708 | **[If you only experience this problem when using VLC see this question](https://unix.stackexchange.com/q/440321/3285)**
When the screen is blocked, the `xscreensaver` (version 5.35) password prompt pops out without any mouse/touchpad movement. It just appears, blinks out when the time is gone (there is also a message like "*the PAM timeout is cancelled*") and appears again. Then the cycle is repeated.
I tried to reinstall it which was not helpful. I'm using Arch (`4.7.6-1-ARCH`) on a laptop.
Here are the log messages (I removed `xscreensaver:` in the beginning of all lines). The event I did not trigger is `ClientMessage` at 10:48:47:
```
10:48:29: 0: grabbing keyboard on 0xd4... AlreadyGrabbed.
10:48:30: 0: grabbing keyboard on 0xd4... GrabSuccess.
10:48:30: 0: grabbing mouse on 0xd4... GrabSuccess.
10:48:47: DEACTIVATE ClientMessage received.
10:48:47: user is active (ClientMessage)
10:48:47: pam_start ("xscreensaver", "xenohunter", ...) ==> 0 (Success)
10:48:47: pam_set_item (p, PAM_TTY, ":0.0") ==> 0 (Success)
10:48:47: pam_authenticate (...) ...
10:48:47: pam_conversation (ECHO_OFF="Password: ") ...
10:48:47: 0: mouse is at 1047,514.
10:48:47: 0: creating password dialog ("")
10:48:47: grabbing server...
10:48:47: 0: ungrabbing mouse (was 0xd4).
10:48:47: 0: grabbing mouse on 0x140003c... GrabSuccess.
10:48:47: ungrabbing server.
10:49:17: input timed out.
10:49:17: pam_conversation (...) ==> PAM_CONV_ERR
10:49:17: pam_authenticate (...) ==> 20 (Authentication token manipulation error)
10:49:17: pam_end (...) ==> 0 (Success)
10:49:17: authentication via PAM timed out.
10:49:17: grabbing server...
10:49:17: 0: ungrabbing mouse (was 0x140003c).
10:49:17: 0: grabbing mouse on 0xd4... GrabSuccess.
10:49:17: ungrabbing server.
10:49:17: 0: moving mouse back to 1047,514.
10:49:17: discarding MotionNotify event.
10:49:17: 0: destroying password dialog.
```
**UPD** 2016-10-11
I printed `journalctl -p 3 -xb` and got tons of such lines:
```
Oct 08 14:02:57 regulus xscreensaver[12913]: pam_unix(xscreensaver:auth): conversation failed
Oct 08 14:02:57 regulus xscreensaver[12913]: pam_unix(xscreensaver:auth): auth could not identify password for [xenohunter]
Oct 08 14:03:37 regulus xscreensaver[12913]: pam_unix(xscreensaver:auth): conversation failed
Oct 08 14:03:37 regulus xscreensaver[12913]: pam_unix(xscreensaver:auth): auth could not identify password for [xenohunter]
Oct 08 14:04:17 regulus xscreensaver[12913]: pam_unix(xscreensaver:auth): conversation failed
Oct 08 14:04:17 regulus xscreensaver[12913]: pam_unix(xscreensaver:auth): auth could not identify password for [xenohunter]
Oct 08 14:04:57 regulus xscreensaver[12913]: pam_unix(xscreensaver:auth): conversation failed
Oct 08 14:04:57 regulus xscreensaver[12913]: pam_unix(xscreensaver:auth): auth could not identify password for [xenohunter]
```
The cycle is always 40 seconds which is likely to be the time the password prompt reappears.
I did `evtest /dev/input/event${X}` where ${X} is every `id` from `xinput list`. Plus, I did the same for event streams with `id=0` and `id=1` which are physical mouse and keyboard. All those streams are empty when the password prompt appears. | Since I am new I am unable to add a comment and ask you if you are using XFCE4. I had this same exact problem and tracked the problem to xfce4-power-manager causing this exact same issue.
Taken from the [Xscreensaver FAQ](https://www.jwz.org/xscreensaver/faq.html#no-blank):
>
> Starting in early 2016, I began receiving reports that a program called `xfce4-power-manager` occasionally loses its mind and decides that it's very important that your screen never, ever blank, and it does this by simulating fake KeyPress events hither and yon. I don't know why. Your best bet would be to kill and/or uninstall that program.
>
>
>
Killing `xfce4-power-manager` solved my issue that you were having but I have a second issue of DPMS not working which you can see here: [DPMS Stopped Working Arch (nvidia drivers - xfce4)](https://unix.stackexchange.com/questions/324789/dpms-stopped-working-arch-nvidia-drivers-xfce4) |
90225 | SOLVED
What really helped me was that I could #include headers in the .cpp file with out causing the redefined error.
---
I'm new to C++ but I have some programming experience in C# and Java so I could be missing something basic that's unique to C++.
The problem is that I don't really know what's wrong, I will paste some code to try to explain the issue.
I have three Classes, GameEvents, Physics and GameObject. I have headers for each of them.
GameEvents has one Physics and a list of GameObjects.
Physics has a list of GameObjects.
What I'm trying to achieve is that I want GameObject to be able to access or own a Physics object.
If I simply #include "Physics.h" in GameObject I get the
"error C2111: 'ClassXXX' : 'class' type redifinition" which I understand.
And this is where I thought #include-guards would help so I added an include guard to my Physics.h since that's the header I want to include twice.
This is how it looks
```
#ifndef PHYSICS_H
#define PHYSICS_H
#include "GameObject.h"
#include <list>
class Physics
{
private:
double gravity;
list<GameObject*> objects;
list<GameObject*>::iterator i;
public:
Physics(void);
void ApplyPhysics(GameObject*);
void UpdatePhysics(int);
bool RectangleIntersect(SDL_Rect, SDL_Rect);
Vector2X CheckCollisions(Vector2X, GameObject*);
};
#endif // PHYSICS_H
```
But if I #include "Physics.h" in my GameObject.h now like this:
```
#include "Texture2D.h"
#include "Vector2X.h"
#include <SDL.h>
#include "Physics.h"
class GameObject
{
private:
SDL_Rect collisionBox;
public:
Texture2D texture;
Vector2X position;
double gravityForce;
int weight;
bool isOnGround;
GameObject(void);
GameObject(Texture2D, Vector2X, int);
void UpdateObject(int);
void Draw(SDL_Surface*);
void SetPosition(Vector2X);
SDL_Rect GetCollisionBox();
};
```
I get multiple issues that don't understand why they're showing up.
If I don't #include "Physics.h" my code runs just fine.
I'm very grateful for any help. | The preprocessor is a program that takes your program, makes some changes (for example include files (#include), macro expansion (#define), and basically everything that starts with `#`) and gives the "clean" result to the compiler.
The preprocessor works like this when it sees `#include`:
When you write:
```
#include "some_file"
```
The contents of `some_file` almost literally get copy pasted into the file including it. Now if you have:
```
a.h:
class A { int a; };
```
And:
```
b.h:
#include "a.h"
class B { int b; };
```
And:
```
main.cpp:
#include "a.h"
#include "b.h"
```
You get:
```
main.cpp:
class A { int a; }; // From #include "a.h"
class A { int a; }; // From #include "b.h"
class B { int b; }; // From #include "b.h"
```
Now you can see how `A` is redefined.
When you write guards, they become like this:
```
a.h:
#ifndef A_H
#define A_H
class A { int a; };
#endif
b.h:
#ifndef B_H
#define B_H
#include "a.h"
class B { int b; };
#endif
```
So now let's look at how `#include`s in main would be expanded (this is exactly, like the previous case: copy-paste)
```
main.cpp:
// From #include "a.h"
#ifndef A_H
#define A_H
class A { int a; };
#endif
// From #include "b.h"
#ifndef B_H
#define B_H
#ifndef A_H // From
#define A_H // #include "a.h"
class A { int a; }; // inside
#endif // "b.h"
class B { int b; };
#endif
```
Now let's follow the preprocessor and see what "real" code comes out of this. I will go line by line:
```
// From #include "a.h"
```
Comment. Ignore! Continue:
```
#ifndef A_H
```
Is `A_H` defined? No! Then continue:
```
#define A_H
```
Ok now `A_H` is defined. Continue:
```
class A { int a; };
```
This is not something for preprocessor, so just leave it be. Continue:
```
#endif
```
The previous `if` finished here. Continue:
```
// From #include "b.h"
```
Comment. Ignore! Continue:
```
#ifndef B_H
```
Is `B_H` defined? No! Then continue:
```
#define B_H
```
Ok now `B_H` is defined. Continue:
```
#ifndef A_H // From
```
Is `A_H` defined? YES! Then ignore until corresponding `#endif`:
```
#define A_H // #include "a.h"
```
Ignore
```
class A { int a; }; // inside
```
Ignore
```
#endif // "b.h"
```
The previous `if` finished here. Continue:
```
class B { int b; };
```
This is not something for preprocessor, so just leave it be. Continue:
```
#endif
```
The previous `if` finished here.
That is, after the preprocessor is done with the file, this is what the compiler sees:
```
main.cpp
class A { int a; };
class B { int b; };
```
So as you can see, anything that can get `#include`d in the same file twice, whether directly or indirectly needs to be guarded. Since `.h` files are always very likely to be included twice, it is good if you guard ALL your .h files.
P.S. Note that you also have circular `#include`s. Imagine the preprocessor copy-pasting the code of Physics.h into GameObject.h which sees there is an `#include "GameObject.h"` which means copy `GameObject.h` into itself. When you copy, you again get `#include "Pysics.h"` and you are stuck in a loop forever. Compilers prevent that, but that means your `#include`s are half-done.
Before saying how to fix this, you should know another thing.
If you have:
```
#include "b.h"
class A
{
B b;
};
```
Then the compiler needs to know everything about `b`, most importantly, what variables it has etc so that it would know how many bytes it should put in place of `b` in `A`.
However, if you have:
```
class A
{
B *b;
};
```
Then the compiler doesn't really need to know anything about `B` (since pointers, regardless of the type have the same size). The only thing it needs to know about `B` is that it exists!
So you do something called "forward declaration":
```
class B; // This line just says B exists
class A
{
B *b;
};
```
This is very similar to many other things you do in header files such as:
```
int function(int x); // This is forward declaration
class A
{
public:
void do_something(); // This is forward declaration
}
``` |
90398 | I'm trying to upload 2 documents using AngularJs. The user fills the information like Name, Date of Birth, Gender etc. If these data successfully stored in the database through spring controller, 2 documents should be stored.
**JS**
Below code is for adding and removing the documents.
```
$scope.items = [];
$scope.item = {};
$scope.addItem = function (item)
{
if ($scope.item.file != undefined){
$scope.items.push( $scope.item);
$scope.item = {};
}
else {
alert("Please open a file before adding");
}
}
$scope.removeItem = function (item)
{
for (var i = 0; i < $scope.items.length; i++)
{
if ($scope.items[i] === item)
{
$scope.items.splice(i, 1);
break;
}
}
}
```
Below code is for submitting the form data and documents.
```
$scope.submit = function()
{
var formData =
{
fullName : $scope.fullName,
fatherName : $scope.fatherName,
gender : $scope.gender,
contactNumber: $scope.contactNumber,
dateofbirth : $scope.dateofbirth,
subDate : new Date()
};
$http.post('userdetails', formData ).success(function(response)
{
if ($scope.items.length > 0)
{
for (var i = 0 ; i < $scope.items.length ; i++)
{
$scope.uploadItem(response.id, $scope.items[i]);
}
}
}).error(function(error)
{
alert(error);
});
};
$scope.uploadItem = function(id, file)
{
var data = new FormData();
data.append('id', id);
data.append('file', file);
$http.post('multipleSave', data, {
headers: { 'Content-Type': undefined,
enctype:'multipart/form-data' }
}).success(function(data) {
$log.debug("Upload Successfull");
}).error(function(error) {
$log.debug("Upload failure");
});
};
```
First form data would be stored and if it is success, Documents should be passed. Here id is auto generated which is returned in response from the database after storing the form data. All these happen in one click from front end.
**Spring Controller**
```
@RequestMapping(value = "/multipleSave", method = RequestMethod.POST)
public @ResponseBody void uploadFile(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException {
Iterator<String> fileName=request.getFileNames();
MultipartFile file= request.getFile(fileName.hasNext());
System.out.println("file");
}
```
**In Spring Configuration**
```
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
```
I ran in debugging mode and I saw that content of MultipartHttpServletRequest is empty. It is not receiving any file.
Any help on this? | The operator `==` will check the values of 2 object and in this case an empty `set()` and a False value have not a same value.
And since python evaluates any empty sequence as False and none empty sequences as True, if you want to check the validation of the `test` object you can simple use `if`:
```
if test:
#do stuff
```
>
> [**Truth Value Testing**](https://docs.python.org/3/library/stdtypes.html#truth)
>
>
> Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
>
>
> * List item
> * None
> * False
> * zero of any numeric type, for example, 0, 0.0, 0j.
> * any empty sequence, for example, '', (), [].
> * any empty mapping, for example, {}.
> * instances of user-defined classes, if the class defines a `__bool__()` or `__len__()` method, when that method returns the integer zero or bool value False.
>
>
> All other values are considered true — so objects of many types are always true.
>
>
> |
90542 | I have a ListView with contents as suppose android in 1st row,blackberry in second row and iphone in 3rd row so on now I want to make ListView's whole row clickable but when I click above content of listview row then it performs only click event but I want if I click any where in a row then a click action should be performed.My code for making listview clickable is below:
```
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.listartistspacedetailview);
setListAdapter(new ArrayAdapter(this,R.layout.listitem_layout,R.id.barrio, keywordxmlparsing.array_artistname));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long thisID)
{
Intent i = new Intent(Artistspacedetailview.this, Loadingimagetab.class);
startActivity(i);
}
```
and ListView tag in xml file is :
```
<ListView
android:clickable="true"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:id="@+id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_below="@id/horizontolline"
android:cacheColorHint="#00000000"
android:drawSelectorOnTop="false" />
``` | I know this question is old, but it was the first hit for me in google when I was looking for this problem.
This is my solution.
```
<ListView
android:id="@+id/XXXXXX"
android:layout_width="fill_parent" // Changed from wrap content
android:layout_height="fill_parent" // Changed from wrap content
android:clickable="true" > // This was suggested in other topics
</ListView>
``` |
90691 | I can add the marker on the openlayer map using `Openlayers.Layer.markers` .
But i cannot do this using `OpenLayers.Feature.Vector` ? . Any one may help me..please...thanks in advance
Regards,
Boomiraj.P | here's a simple example that should work.
```
var point = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(-111.04, 45.68));
var layer = new OpenLayers.Layer.Vector("My Layer", {
style: OpenLayers.Feature.Vector.style["default"]
});
map.addLayer(layer);
layer.addFeatures([point]);
``` |
90923 | * I am trying to link manifest.json file to the website I built to convert it to PWA. Have used `html/css` and `python flask` for the backend.
* I am not getting whether it is the issue of the path or something else. Service worker is being detected and that is working absolutely fine.
* But in the Application manifest I am getting this error Manifest is not valid JSON. Line: 1, column: 1, Unexpected token
[![enter image description here](https://i.stack.imgur.com/sRldD.jpg)](https://i.stack.imgur.com/sRldD.jpg)
* `manifest.json` file
```
{
"name": "Flask-PWA",
"short_name": "Flask-PWA",
"description": "A progressive webapp template built with Flask",
"theme_color": "transparent",
"background_color": "transparent",
"display": "standalone",
"orientation": "portrait",
"scope": "/",
"start_url": "../templates/login_user.html",
"icons": [
{
"src": "images/icons/icon-72x72.png",
"sizes": "72x72",
"type": "image/png"
},
{
"src": "images/icons/icon-96x96.png",
"sizes": "96x96",
"type": "image/png"
},
{
"src": "images/icons/icon-128x128.png",
"sizes": "128x128",
"type": "image/png"
},
{
"src": "images/icons/icon-144x144.png",
"sizes": "144x144",
"type": "image/png"
},
{
"src": "images/icons/icon-152x152.png",
"sizes": "152x152",
"type": "image/png"
},
{
"src": "images/icons/icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "images/icons/icon-384x384.png",
"sizes": "384x384",
"type": "image/png"
},
{
"src": "images/icons/icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
```
* This is the file structure for the manifest
[![enter image description here](https://i.stack.imgur.com/zrHOL.jpg)](https://i.stack.imgur.com/zrHOL.jpg) | The problem is that the program can't update state inside rendering..it goes through infinite loop so "selectedIndex" must have an event handler function to handle when to setState it. |
91153 | In Russian, verbs in the past have gender information attached to them, so that “я спросил” implies that the asker was male, whereas “я спросила” comes from a female.
Why no other tenses have this trait, or why verbs were even chosen to differ by speaker's gender? | Because historically what we call past in modern Russian is perfect, and what we believe to be past forms of the verbs are in fact participles (adjectives formed from verbs).
Compare:
>
> Он пел / она пела / оно пело (he / she / it has sung)
>
>
> Он бел / она бела / оно бело (he / she / it is white)
>
>
>
In old Russian there was a number of other past tenses. The most used of them, the aorist, did not change by gender. |
92034 | In my build.gradle , the logcat is visible when
```
debugCompile 'org.slf4j:slf4j-android:1.6.1-RC1'
```
However when the version is updated , there is logcat
```
debugCompile 'org.slf4j:slf4j-android:1.7.14'
```
I am stuck with 1.6.1-RC1 version. Why the newer versions of slf4j-android:1.7.x are not logged in the logcat ?
I use SLF4J in the code like this
```
private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(TAG);
LOG.debug("variable = {}", var);
```
**References**
<http://www.slf4j.org/android/>
<http://www.slf4j.org/news.html> ( changelog ) | <http://jira.qos.ch/browse/SLF4J-314> gave me the answer .
To see the logs on "slf4j-android:1.7.x" , using Android setprop is the official approach.
The downside of this approach is that you have to select the TAG but cannot show all logs . For example in the logcat :
```
app_package D/TAG1: blabla
app_package D/TAG2: lorem ipsum
```
In the terminal , enter
```
adb shell setprop log.tag.TAG1 VERBOSE
```
I will only display TAG1 and no the others TAGs . I wonder if it is possible to print all other Tags.
For now , I think I will stick with 1.6.1-RC1 version |
92107 | I'm trying to strip the span tags w/ a letter-spacing that starts with 0. or 1.
```
'<span style="letter-spacing:0.50 px">Boulevard,</span> '
to equal
'Boulevard, '
```
Thank you
Here's an example of a complete line.
```
<span style="letter-spacing:1.33 px">PRODUCTS</span> <span style="letter-spacing:1.37 px">MODEL</span> <span style="letter-spacing:0.77 px">HPI-27C</span> <span style="letter-spacing:1.39 px">MODDED)</span> ; <span style="letter-spacing:1.12 px">(HIGHWAY</span> <span style="letter-spacing:1.33 px">PRODUCTS</span> <span style="letter-spacing:1.37 px">MODEL</span>
```
Needs to end up like
PRODUCTS MODEL HPI-27C MODDED) ; (HIGHWAY PRODUCTS MODEL | Here is an example using Perl and [`HTML::Parser`](https://metacpan.org/pod/HTML::Parser) :
```
use strict;
use warnings;
use HTML::Parser ();
my $delete_tag = 0;
my $p = HTML::Parser->new(
api_version => 3,
default_h => [sub { print shift }, 'text'],
start_h => [\&start_handler, 'tagname,text,attr'],
end_h => [\&end_handler, 'tagname,text'],
);
my $str = do { local $/; <DATA> };
$p->parse($str) || die $!;
print "\n";
sub end_handler {
my ( $tag, $text ) = @_;
if ( $tag eq "span" ) {
if ($delete_tag) {
$delete_tag = 0;
return;
}
}
print $text;
}
sub start_handler {
my ( $tag, $text, $attr ) = @_;
if ( $tag eq "span" ) {
if ($attr->{style} =~ /letter-spacing:[01]\./) {
$delete_tag = 1;
return;
}
}
print $text;
}
__DATA__
<span style="letter-spacing:1.33 px">PRODUCTS</span> <span style="letter-spacing:1.37 px">MODEL</span> <span style="letter-spacing:0.77 px">HPI-27C</span> <span style="letter-spacing:1.39 px">MODDED)</span> ; <span style="letter-spacing:1.12 px">(HIGHWAY</span> <span style="letter-spacing:1.33 px">PRODUCTS</span> <span style="letter-spacing:1.37 px">MODEL</span>
```
**Output**:
```
PRODUCTS MODEL HPI-27C MODDED) ; (HIGHWAY PRODUCTS MODEL
``` |
92580 | I'm using ruby motion. Below are the details of my environment.
```
$ motion --version
2.9
$ bundle
Using bubble-wrap (1.4.0)
Using motion-require (0.0.7)
Using formotion (1.6)
Using motion-layout (0.0.1)
Using thor (0.18.1)
Using rubymotion_generators (0.1.0)
Using bundler (1.3.5)
```
When I run my app and click a button that is suppose to load a form built with formation, my app abruptly crashes with this error message.
>
> *\** Simulator session ended with error: Error Domain=DTiPhoneSimulatorErrorDomain Code=1 "The simulated application
> quit." UserInfo=0x10011e200 {NSLocalizedDescription=The simulated
> application quit., DTiPhoneSimulatorUnderlyingErrorCodeKey=-1}
>
>
>
Running with `rake debug=1` I see the following:
```
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0xc7243c89
0x0081309f in objc_msgSend ()
(gdb)
```
My app was working perfectly fine before upgrading rubymotion and once I updated rubymotion I had to update some of my gems as well.
How can I resolve this or troubleshoot this? | Parenthesis are not used for multiplication in Java as they are in mathematics. Use the `*` operator.
```
if (((i - posX) * (i - posX) + (j - posY) * (j - posY)) == (radius) * (radius)) {
```
Read: [Operators](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html) |
92830 | Then new Enterprise Library 6 is out and can be [downloaded here](http://www.microsoft.com/en-us/download/details.aspx?id=38789). I have downloaded and extracted EnterpriseLibrary6-binaries.exe to a folder on my C: drive. The readme says this:
```
MICROSOFT ENTERPRISE LIBRARY 6
Summary: This package contains Enterprise Library configuration console, MSMQ distributor service, merge configuration tool and a script to download binaries for all application blocks from NuGet.
In order to get all the binaries, run the install-packages.ps1 script.
Note: For the Semantic Logging Application Block Out-of-Process service, a separate package is available for download.
```
I then run Powershell and run the script. I now look in the folder I extracted the .exe to and all of the binaries are there. Now, here are the instructions from the Enterprise Library 6 .chm.
```
To install the integrated Visual Studio configuration editor
1. On the Visual Studio Tools menu, choose Extensions and Updates.
2. In the Extensions and Updates dialog, search online for EnterpriseLibrary.config.
3. Click the Download button to download and install the Enterprise Library configuration editor.
4. Restart Visual Studio to complete the installation.
To launch and use the configuration editor from Visual Studio
1. Open a solution in Visual Studio.
2. If the solution does not contain a configuration file, add one using the Visual Studio Add menu.
3. In Solution Explorer, right-click the configuration file and then click Edit Enterprise Library V6 Configuration. This launches the integrated configuration editor or the appropriate standalone version of the configuration tool.
```
Step #3 is where I am stuck. I have a WCF service project with a web.config in it. I right click the web.config and I don't see a "Edit Enterprise Library V6 Configuration" context menu option.
I DO see an "Edit Server Configuration File v6". However, when I click this I get the following error.
![enter image description here](https://i.stack.imgur.com/xe3iQ.png)
All I'm trying to do is use the Exception Handling Application Block in my WCF service project. I've looked around the web and can't find any easy step-by-step tutorial to guide me either. Any help is greatly appreciated. | I had to use NuGet to install the application block I wanted to use in the project. For me, Tools >> Library Package Manager >> Manage NuGet Packages for solution and add the appropriate EntLib 6 Exception Handling Application Block WCF Provider. |
92977 | ```
function getHashTagsFromString($str){
$matches = array();
$hashTag=array();
if (preg_match_all('/#([^\s]+)/', $str, $matches)) {
for($i=0;$i<sizeof($matches[1]);$i++){
$hashtag[$i]=$matches[1][$i];
}
return $hashtag;
}
}
test string $str = "STR
this is a string
with a #tag and
another #hello #hello2 ##hello3 one
STR";
```
using above function i am getting answers but not able to remove two # tags from ##hello3 how to remove that using single regular expression | Update your regular expression as follows:
```
/#+(\S+)/
```
**Explanation:**
* `/` - starting delimiter
+ `#+` - match the literal `#` character one or more times
+ `(\S+)` - match (and capture) any non-space character (shorthand for `[^\s]`)
* `/` - ending delimiter
[**Regex101 Demo**](http://regex101.com/r/nH1mS2)
The output will be as follows:
```
Array
(
[0] => tag
[1] => hello
[2] => hello2
[3] => hello3
)
```
[**Demo**](https://eval.in/101883) |
93229 | I made my front component similar to a login page. When I try to pass the begin prop Front doesn't render for some reason. If I don't pass it any props then it renders fine. I'm not sure why this is happening. Any help would be appreciated!
```
export default function App() {
const [start, setStart] = React.useState(false);
function startGame() {
setStart(prevStart => !prevStart);
}
return (
<div>
<Front begin={startGame()} />
</div>
)
```
}
```
export default function Front(props) {
return (
<div className="login">
<h1>Quizzical</h1>
<h3>Read the questions carefully!</h3>
<button onClick={props.begin} className="startButton">Start Quiz</button>
<div className="blob-1"></div>
<div className="blob-2"></div>
</div>
)
```
} | Pass the function like this:
`<Front begin={startGame} />`
Instead of this:
`<Front begin={startGame()} />`
Because `startGame()` will run the function on site and what it returns would be passed as props. This case it returns void (nothing) which is not expected by the component, thus the error occured. |
94183 | My problem is as follows, and I suspect it has a simple solution. However I looked at [create reactive function from user input](https://stackoverflow.com/questions/28788029/shiny-create-reactive-function-from-user-string-input?rq=1) and [Reactive Function Parameter](https://stackoverflow.com/questions/34725029/reactive-function-parameters), neither of which answer my question.
I have a chart which will have X and Y axes that may change based on user input. The user will be able to click on the chart, and I have a text display which says something along the lines of 'You have selected a (name of x label) value of xxx, and a (name of y label) value of yyy'. Obviously, if the name of the x or y label begins with a vowel, I would like to use 'an' rather than 'a'. For the moment I have written this function twice into the server module, but this isn't very elegant.
Is there a way to define a function inside the server function which I can just send the label name to, and which will simply return 'a' or 'an'? Code below. Note the Pokemon dataset travels with the highcharter package and can be downloaded from CRAN.
```
library(ggplot2)
library(highcharter)
myData <- pokemon
ui <- fluidPage(
# Some custom CSS for a smaller font for preformatted text
tags$head(
tags$style(HTML("
pre, table.table {
font-size: smaller;
}
"))
),
tags$head(tags$style(type = "text/css", ".shiny-text-output, .well{background-color: #EFF8CD;}")),
fluidRow(
column(width = 3
),
column(width = 5,
plotOutput("plot1", height = 450,
# Equivalent to: click = clickOpts(id = "plot_click")
click = "plot_click"
)
),
column(width = 4,
## Text output here.
wellPanel(
h4("Your results"),
htmlOutput("chartDetails")
)
)
)
)
server <- function(input, output) {
output$plot1 <- renderPlot({
ggplot(myData, aes(weight, attack)) + geom_point()
}
)
## Extract some values when plot is clicked
inputX <- reactive({
if (is.null(input$plot_click$x))
{
-999
}
else
{
round(input$plot_click$x, 0)
}
})
inputY <- reactive({
if (is.null(input$plot_click$y))
{
-999
}
else
{
round(input$plot_click$y, 0)
}
})
labelX <- eventReactive(input$plot_click, {
input$plot_click$mapping$x
})
labelY <- eventReactive(input$plot_click,{
input$plot_click$mapping$y
})
## count the number of points that have a higher x and y.
mySubset <- eventReactive(input$plot_click, {
#myFirstSubset <- subset(myData, weight > inputX())
subset(myData, labelX() > inputX() & labelY() > inputY())
})
## Create relevant strings out of the inputX and inputY values.
stringX <- reactive({
if (inputX() > -999)
{
myString <- "You have selected"
if (substr(labelX(), 1,1) %in% c("a", "e", "i", "o", "u"))
{
myString <- paste(myString, "an")
}
else
{
myString <- paste(myString, "a")
}
paste(myString, labelX(), "of", inputX())
}
else
{
""
}
})
stringY <- reactive({
if (inputY() > -999)
{
myString <- "and"
if (substr(labelY(), 1,1) %in% c("a", "e", "i", "o", "u"))
{
myString <- paste(myString, "an")
}
else
{
myString <- paste(myString, "a")
}
paste(myString, labelY(), "of", inputY())
}
else
{
""
}
})
stringCount <- reactive({
if (inputY() > -999 && inputX() > -999)
{
paste("The number of records with higher",labelX(), "and", labelY(), "is", nrow(mySubset()))
}
else
{
""
}
})
## Post the results to the chart details well.
output$chartDetails <- renderUI({
if (inputX() > -999 && inputY() > -999) {
HTML(paste(stringX(), "<br>",
stringY(), "<br>",
stringCount()))
}
else
{
HTML("Click on the chart")
}
})
}
shinyApp(ui, server)
``` | The simple solution as suggested by Dieter Menne is as follows:
Outside of the UI/Server functions:
```
myConnective <- function(aString) {
if (substr(aString, 1,1) %in% c("a", "e", "i", "o", "u"))
{
myString <- "an"
}
else
{
myString <- "a"
}
return(myString)
}
```
Then inside the Server function:
```
stringX <- reactive({
if (inputX() > -999)
{
paste("You have selected", myConnective(labelX()), labelX(), "of", inputX() )
}
else
{
""
}
})
``` |
94303 | I'm using Python to pull out the country of residence that somebody has. The lines where the country is in are (address faked):
```
<HR NOSHADE SIZE="1" COLOR="#000000"><B>Buyer Information</B><HR NOSHADE SIZE="1" COLOR="#000000">
<TABLE WIDTH="100%" BORDER="0" CELLPADDING="1" CELLSPACING="0" CLASS="ta"><TR BGCOLOR="#EEEEEE">
<TD WIDTH="25%"> Username:</TD>
<TD WIDTH="75%"><B>joedane</B> <A HREF="http://www.bricklink.com/feedback.asp?u=joedane">(6)</A><IMG BORDER=0 ALT="" SRC="/images/dot.gif" ALIGN="ABSMIDDLE" WIDTH="4" HEIGHT="16"></TD></TR><TR BGCOLOR="#EEEEEE">
<TD> E-Mail:</TD><TD><A HREF="mailto:lala@lala.la">lala@lala.la</A></TD></TR><TR BGCOLOR="#EEEEEE">
<TD WIDTH="25%" VALIGN="TOP"> Name & Address:</TD>
<TD WIDTH="75%">Joe Dane
<BR>XXXX 24
<BR>12345 QWERTY
<BR>Germany</TD>
</TR></TABLE>
<HR NOSHADE SIZE="1" COLOR="#000000"><B>Seller Information</B><HR NOSHADE SIZE="1" COLOR="#000000">
```
I need to get that 'Germany' on the third to last row. However, the country and address will be different each time, so I need a way to pull out the country, but not depending on the address before it.
I have tried:
```
#get Shipping Destination
shippingDest = order.split('</TD></TR></TABLE><HR NOSHADE SIZE="1" COLOR="#000000"><B>Seller Information</B>')[0].split('<BR>')[1]
```
But it doesn't stop on the first BR it finds before the line. Hopefully, my split concept is wrong. This should be an easy problem. Any help?
---
EDIT:
The actual code continues and after Seller information there is a similar code as in the buyer information with Germany, but with my own country. The script yields Spain, my own country. Can I somehow let it skip my country and go for the Second? Would be the one after Seller Information if you are going backwards.
This is the actual code until the end of the html. After Germany it's always the same.
```
<HR NOSHADE SIZE="1" COLOR="#000000"><B>Buyer Information</B><HR NOSHADE SIZE="1" COLOR="#000000">
<TABLE WIDTH="100%" BORDER="0" CELLPADDING="1" CELLSPACING="0" CLASS="ta"><TR BGCOLOR="#EEEEEE">
<TD WIDTH="25%"> Username:</TD>
<TD WIDTH="75%"><B>joedane</B> <A HREF="http://www.bricklink.com/feedback.asp?u=joedane">(6)</A><IMG BORDER=0 ALT="" SRC="/images/dot.gif" ALIGN="ABSMIDDLE" WIDTH="4" HEIGHT="16"></TD></TR><TR BGCOLOR="#EEEEEE">
<TD> E-Mail:</TD><TD><A HREF="mailto:lala@lala.la">lala@lala.la</A></TD></TR><TR BGCOLOR="#EEEEEE">
<TD WIDTH="25%" VALIGN="TOP"> Name & Address:</TD>
<TD WIDTH="75%">Joe Dane
<BR>XXXX 24
<BR>12345 QWERTY
<BR>Germany</TD>
</TR></TABLE>
<HR NOSHADE SIZE="1" COLOR="#000000"><B>Seller Information</B><HR NOSHADE SIZE="1" COLOR="#000000">
<TABLE WIDTH="100%" BORDER="0" CELLPADDING="1" CELLSPACING="0" CLASS="ta">
<TR BGCOLOR="#EEEEEE">
<TD WIDTH="25%"> Username:</TD><TD WIDTH="75%"><B>Brick_Top</B> <A HREF="http://www.bricklink.com/feedback.asp?u=Brick_Top">(466)</A>
<A HREF="http://www.bricklink.com/help.asp?helpID=54">
<IMG ALT="" WIDTH="16" HSPACE="3" ALIGN="ABSMIDDLE" HEIGHT="16" BORDER="0" SRC="/images/bricks/star2.png"></A>
<A HREF="http://www.bricklink.com/aboutMe.asp?u=Brick_Top">
<IMG ALT="" WIDTH="18" ALIGN="ABSMIDDLE" HEIGHT="16" BORDER="0" SRC="/images/bricks/me.png"></A></TD></TR><TR BGCOLOR="#EEEEEE">
<TD> Store Name:</TD><TD><B>Top Bricks from Brick Top</B></TD></TR><TR BGCOLOR="#EEEEEE">
<TD> Store Link:</TD><TD><A HREF="/store.asp?p=Brick_Top">http://www.bricklink.com/store.asp?p=Brick_Top</A></TD></TR><TR BGCOLOR="#EEEEEE">
<TD> E-Mail:</TD><TD><A HREF="mailto:myemail@gmail.com">myemail@gmail.com</A></TD></TR><TR BGCOLOR="#EEEEEE">
<TD WIDTH="25%" VALIGN="TOP"> Name & Address:</TD>
<TD WIDTH="75%">Gerald Me
<BR>qwerty 234
<BR>Sevilla 41500
<BR>Spain</TD></TR></TABLE>
```
All I want to get is **that** Germany (the first country from the two). Many, many thanks.
---
EDIT 2.0:
Interestingly enough, I was able to do it just adding that [-5]. I don't understand it well but my guess is that it find the fifth BR from the first table.
```
from bs4 import BeautifulSoup
import sys
soup = BeautifulSoup(open(sys.argv[1], 'r'), 'html')
country = soup.find('table').find_all('br')[-5]
print(country.find_next(text=True).string)
``` | I suggest you to use a `html` parser like [beautifulsoup](/questions/tagged/beautifulsoup "show questions tagged 'beautifulsoup'"). It finds the last `<br>` of the table and from there search next sibling including text nodes, which returns the country:
```
from bs4 import BeautifulSoup
import sys
soup = BeautifulSoup(open(sys.argv[1], 'r'), 'html')
country = soup.find('table').find_all('br')[-1]
print(country.find_next(text=True).string)
```
Run it like:
```
python3 script.py htmlfile
```
That yields:
```
Germany
``` |
94488 | [Note: it's generally bad practice to include code in your cfcs, (see answers below), so consider this just research]
To summarize, I have a class and a subclass and one method that is overridden by the subclass. When I hard-code the method in the child class, everything works fine, when I use cfinclude to include it in the pseudo constructor, mixin style, I get a "Routines cannot be declared more than once." error.
This seems pretty straightforward. What am I missin' re: this mixin?
parent class:
```
<cfcomponent >
<cffunction name="hola" hint="i am the parent method">
<cfreturn "hola - parent">
</cffunction>
</cfcomponent>
```
child class:
```
<cfcomponent extends="mixinTestParent">
<!--- this would work, successfully overridding parent method
<cffunction name="hola" hint="i am the child method">
<cfreturn "hola - child">
</cffunction>--->
<cfinclude template="mixinTestInc.cfm">
<cffunction name="init" access="public" returntype="any" output="false">
<cfreturn this>
</cffunction>
</cfcomponent>
```
include:
```
<cffunction name="hola" hint="i am the child method" access="public">
<cfreturn "hola - child">
</cffunction>
```
runner:
```
<cfset test = new mixinTestChild().init()>
<cfdump var="#test.hola()#">
```
thanks in advance!! | You're getting the error because of the way the the CFC is instantiated.
When you have `hola()` in the parent & `hola()` in the child, where the child extends the parent, when the child CFC is created, it sees `hola()` in the parent and overrides it. However, that function still exists in the CFC.
From the child CFC, you can reference both `hola()` (defined in the child CFC) and `super.hola()` (defined in the parent).
When you use `<cfinclude/>`, the CFC is instantiated and the contents of the included file are added to the mix. However, they aren't seen as part of the inheritance model, just as "other functions in this CFC", so you get the error.
I agree this is a bad practice when done instead of refactoring, but it is a good way to allow utility UDFs into the mix without making them part of your model. |
94545 | Is it possible to display a specific data field of a related class (one-to-many relationship) when the field is not a foreign key? If not, how to bypass this problem?
For example:
Class **Pigeon**
```
public class Pigeon
{
[Key]
public string PigeonId { get; set; }
[ForeignKey("RaceForeignKey")]
public string RaceId { get; set; }
public Race Race { get; set; }
public Flock Flock { get; set; }
}
```
Class **Race**
```
public class Race
{
[Key]
public string RaceId { get; set; }
public string RaceName { get; set; }
public List<Pigeon> Pigeons { get; set; }
}
```
The controller action:
```
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("PigeonId,PigeonName,RingNumber,BirthDate,Sex,Description,Achievements,FlockId,RaceId,MotherId,FatherId,UserProfileId")] Pigeon pigeon)
{
if (ModelState.IsValid)
{
var user = await _userManager.GetUserAsync(HttpContext.User);
pigeon.UserProfileId = user.Id;
_context.Add(pigeon);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["FlockId"] = new SelectList(_context.Set<Flock>(), "FlockId", "FlockId", pigeon.FlockId);
ViewData["RaceId"] = new SelectList(_context.Set<Race>(), "RaceId", "RaceId", pigeon.RaceId);
ViewData["UserProfileId"] = new SelectList(_context.UserProfile, "Id", "Id", pigeon.UserProfileId);
return View(pigeon);
}
```
The View:
```
<div class="form-group">
<label asp-for="RaceId" class="control-label"></label>
<select asp-for="RaceId" class ="form-control" asp-items="ViewBag.RaceId"></select>
</div>
```
The result is [![here](https://i.stack.imgur.com/d2hv7.jpg)](https://i.stack.imgur.com/d2hv7.jpg)
How to Include the **Race** class to the **Pigeon** class to display RaceName instead of RaceId in the Dropdown list? | You can use this overload of SelectList constructor:
>
> SelectList(IEnumerable, String, String, Object)
>
>
> Initializes a new instance of the SelectList class by using the specified items for the
> list, the data value field, the data text field, and a selected value.
>
>
>
so, changing your parameter, solve your problem
```
ViewData["RaceId"] = new SelectList(_context.Set<Race>(), "RaceId", "RaceName", pigeon.RaceId);
``` |
94657 | Please consider this dummy code.
```
$ cat dummy.py
import logging
import time
from boto3.session import Session
# Logging Configuration
fmt = '%(asctime)s [%(levelname)s] [%(module)s] - %(message)s'
logging.basicConfig(level='INFO', format=fmt, datefmt='%m/%d/%Y %I:%M:%S')
logger = logging.getLogger()
def main():
session = Session(region_name='us-west-2')
client = session.client('ec2')
response = client.describe_instances(InstanceIds=['i-11111111111111111'])
logger.info('The instnace size is: %s', response[
'Reservations'][0]['Instances'][0]['InstanceType'])
if __name__ == '__main__':
main()
```
**Output:**
```
$ python3 dummy.py
03/03/2017 08:47:00 [INFO] [credentials] - Found credentials in shared credentials file: ~/.aws/credentials
03/03/2017 08:47:01 [INFO] [connectionpool] - Starting new HTTPS connection (1): ec2.us-west-2.amazonaws.com
03/03/2017 08:47:02 [INFO] [dummy] - The instnace size is: t2.micro
```
**Question:**
How to avoid below lines from being printed?
```
03/03/2017 08:47:00 [INFO] [credentials] - Found credentials in shared credentials file: ~/.aws/credentials
03/03/2017 08:47:01 [INFO] [connectionpool] - Starting new HTTPS connection (1): ec2.us-west-2.amazonaws.com
```
If I change `logging.basicConfig(level='INFO',...` to `logging.basicConfig(level='WARNING',...` then Those messages are not printed, but then all my messages get logged with `WARNING` severity.
I just want the `logging` module to print the messages that I explicitly write using `logger.info ....` and nothing else. Hence I need any pointers on how to avoid the unnecessary messages from being printed. | **Solution:**
```
import logging
import time
from boto3.session import Session
# Logging Configuration
fmt = '%(asctime)s [%(levelname)s] [%(module)s] - %(message)s'
logging.basicConfig(format=fmt, datefmt='%m/%d/%Y %I:%M:%S')
logger = logging.getLogger('LUCIFER')
logger.setLevel(logging.INFO)
def main():
COUNTER = 3
session = Session(region_name='us-west-2')
client = session.client('ec2')
response = client.describe_instances(InstanceIds=['i-0a912622af142b510'])
logger.info('The instnace size is: %s', response[
'Reservations'][0]['Instances'][0]['InstanceType'])
if __name__ == '__main__':
main()
```
**Output:**
```
$ python3 dummy.py
03/03/2017 10:30:15 [INFO] [dummy] - The instnace size is: t2.micro
```
**Explanation:**
Earlier, I set the `INFO` level on root logger. Hence, all other loggers who do not have a level set, get this level `propagated` and start logging. In the solution, I am specifically enabling this level on a logger `LUCIFER`.
**Reference:**
from: <https://docs.python.org/3/howto/logging.html>
Child loggers propagate messages up to the handlers associated with their ancestor loggers. Because of this, it is unnecessary to define and configure handlers for all the loggers an application uses. It is sufficient to configure handlers for a top-level logger and create child loggers as needed. (You can, however, turn off propagation by setting the propagate attribute of a logger to False.)
AND
In addition to any handlers directly associated with a logger, all handlers associated with all ancestors of the logger are called to dispatch the message (unless the propagate flag for a logger is set to a false value, at which point the passing to ancestor handlers stops). |
95892 | I'm looking for a way of converting a `wstring` into a plain `string` containing only ASCII characters. Any character that isn't present in ASCII (0-127) should be converted to the closest ASCII character. If there is no similar ASCII character, the character should be omitted.
To illustrate, let's assume the following wide string:
```
wstring text(L"A naïve man called 晨 was having piña colada and crème brûlée.");
```
The converted version I'm looking for is this (notice the absence of diacritics):
```
string("A naive man called was having pina colada and creme brulee.")
```
**Edit:**
Regarding the **purpose**: I'm writing an application that analyzes English texts. The input files are UTF-8 and may contain special characters. A part of my application uses a library written in C that only understands ASCII. So I need a way of "dumbing down" the text to ASCII without losing too much information.
Regarding the **precise requirements**: Any character that is a diacritic version of an ASCII character should be converted to that ASCII character; all other characters should be omitted. So `ı`, `ĩ`, and `î` should become `i` because they are all versions of the small Latin letter i. The character `ɩ` (iota), on the other hand, while visually similar, is not a version of the small Latin letter i and should thus be omitted. | On GitHub, there is [unidecode-cxx](https://github.com/mapbox/node-unidecode-cxx) which is a (somewhat unfinished) C++ port of [node-unidecode](https://github.com/FGRibreau/node-unidecode), which is in turn a JavaScript port of Perl's [Text::Unicode](http://search.cpan.org/%7Esburke/Text-Unidecode-0.04/lib/Text/Unidecode.pm). The C++ version is a bit rough around the edges, but the example in `src/unidecode.cxx` can be modified to convert your example string,
>
> `A naïve man called 晨 was having piña colada and crème brûlée.`
>
>
>
as follows:
>
> `A naive man called Chen was having pina colada and creme brulee.`
>
>
>
In order to get the code to compile without Gyp (something I've never used and haven't had the time to figure out just now), I had to modify the code somewhat (quick and dirty):
* Add `#include <iostream>` to `src/unidecode.cxx`, and add the following `main` routine:
```
int main() {
string output_buf;
string input_buf = "A naïve man called 晨 was having piña colada and crème brûlée.";
unidecode(&input_buf, &output_buf);
cout << output_buf.c_str() << endl;
}
```
* Replace all mentions of `NULL` in `src/data.cxx` with `nullptr`
Then I compiled with
```
g++ -std=c++11 -o unidecode unidecode.cxx
```
to get the desired result.
The code looks like a fairly primitive port and could do with some improvements, especially into more "proper" C++. It internally uses a statically compiled conversion table, which can probably be adapted to suit your needs if it does not. |
96689 | I'm using HHVM to write a system tool and I cannot for the life of me figure out why this code issues an error when I run `hh_client`
```
$__al_paths = array();
function requires(string $classPath): void {
global $__al_paths;
$className = basename($classPath);
if (!isset($__al_paths[$className])) {
$__al_paths[$className] = AL_CLASSES_FOLDER.'/'.$classPath.'.'.AL_CLASS_EXTENSION;
}
}
```
This issues the following when I run `hh_client`
```
/usr/lib/mango/tools/autoloader.hh:9:9,19: Expected
```
The line it is pointing to is the line that says
```
global $__al_paths;
```
Which is being declared in the `global` scope. This appears to be a syntax error, it is as if the `global` keyword is not supported on HHVM, however I checked the documentation and it has several examples of it being using in Hack code. | Instead of using `global` try to rewrite your code like this (called dependency injection):
```
function requires(string $classPath, $__al_paths): void {
$className = basename($classPath);
if (!isset($__al_paths[$className])) {
$__al_paths[$className] = AL_CLASSES_FOLDER.'/'.$classPath.'.'.AL_CLASS_EXTENSION;
}
}
```
Then call it like:
```
$__al_paths = array();
requires('classpath', $__al_paths);
```
This way you produce much more flexible and more stable code than playing around with globals which should been deleted from every humans mind. |
97703 | i just need to know what happens when you create a RSS feed in Liferay?
Is the configuration data for the feed (Structure, template, friendly url of the portlet...) stored on the DB or in a file?And, in both cases, where the data is stored exactly? | they are stored in the DB, if anyone is interested!
Update: i will detail the answer more if anyone is interested. They are stored in the table JournalFeeds. |
97824 | I am trying to install Windows 2008 server on a HP Proliant DL180 G5. There is no built-in DVD reader so I need to use my LaCie USB one.
When I put the CD in and boot from the USB DVD on the server, I get the error message:
Boot Failed! Please insert boot media in selected boot device.
So I tried with another Windows bootable CD and still no luck.
What I've done then, I copied the installation DVD on my 16go USB key. Again, impossible to boot from the USB Key.
I have 2 147go SAS 15k HDD on my server. They are not showing in the Bios. I was wondering if this is a reason why nothing will boot on it.
I am trying to find a way to deploy Windows 2008 server on my HP server as soon as possible.
If you guys have ideas, feel free to let me know :)
Best regards,
David.
System Information:
HP Proliant DL180 G5
Quad-Core 2.5
4GO Ram
2x 147GO SAS 15k
P.S. This is my first installation ever on SAS/SCSI HDD.
Thanks a bunch!
Edit:
Well, my bad! I purchased a new USB DVD and now I can install Windows 2008 server.
Thanks a bunch for your help! | You'll probably need to go into the BIOS and enable it to boot off the USB drive. |
97847 | So, on my main domain 'domain.com' I created several subdomains from cPanel, like 'sub1.domain.com' and 'sub2.domain.com'. Their real location on server is in 'domain.com/sub1' and 'domain.com/sub2'.
Now, I want to redirect non www to www with .htaccess and this is what currently what i have:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.domain\.com [NC]
RewriteRule ^(.*) http://www.domain.com/$1 [L,R=301]
</IfModule>
```
This works. When somebody enter domain.com it will be redirected to www.domain.com.
However when somebody enter sub1.domain.com, he will be redirected to www.domain.com/sub1 - which I don't want, it needs to be in sub1.domain.com.
What shall I add in .htaccess file to accomplish this? | You can exclude each `sub1`, `sub2` individually like so;
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^sub1\.domain\.com [NC]
RewriteRule ^(.*) - [L]
RewriteCond %{HTTP_HOST} ^sub2\.domain\.com [NC]
RewriteRule ^(.*) - [L]
RewriteCond %{HTTP_HOST} !^www\.domain\.com [NC]
RewriteRule ^(.*) http://www.domain.com/$1 [L,R=301]
</IfModule>
```
Or just be specific that you only want to redirect `domain.com` to `www.domain.com` with the `RewriteCond`
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.com [NC]
RewriteRule ^(.*) http://www.domain.com/$1 [L,R=301]
</IfModule>
``` |
97868 | I want to configure Python/Jython in IBM BPM, so that these files can directly executed from process app. How can I do that?
How to setup this entry in WebSphere Application Server? | You can use the same key and then just insert the new bin. This will update the existing record with the new bin. The way you are proceeding about it is correct. |
98364 | Android studio is too heavy and slows down my pc for development. i am an ionic developer and i only need the android emulator to have a better test environment for my mobile application. I only make use of the android studio because i am trying to set up the virtual emulator following the steps in this video [Ionic 3 Tutorial #16 Run app on Android Emulator](https://www.youtube.com/watch?v=ZWrKakQOCYE)
I will like to know if there is another way out to test and run my ionic app either on a real or virtual android emulator. I will like to know if i can run the emulator through my vs code or a lighter IDE | You can use [union types](https://docs.julialang.org/en/v1/manual/types/#Type-Unions) to do the same.
```
function func(x::Union{Int, AbstractFloat})
x + 1
end
```
Note that C++ `std::variant` is a *tagged union*, so you can always ask "which" variant it is, whereas a Julia union is a proper set union. Pragmatically, that means that in `std::variant<int, int>`, you can distinguish between a "left int" and a "right int", but a `Union{Int, Int}` really is just an `Int`. There's no way to tell which "side" it came from. To emulate the exact tagged union behavior, you'll need to make some custom structs to represent each case.
```
struct LeftInt
value :: Int
end
struct RightInt
value :: Int
end
function func(x::Union{LeftInt, RightInt})
# ... Check whether x is a LeftInt or not ...
end
```
but, in Julia, you often don't need this, and if you do then it's generally smarter to work with generic functions to do your dispatching anyway. |
99015 | I need to create a custom animated toast message. Now i need to know if that is possible. I've created a toast with a custom view but I cannot figure out how can I add custom animation to the toast.
Here is the code I have so far.
```
private void showToast() {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.custom_toast_layout_id));
// set a message
TextView text = (TextView) layout.findViewById(R.id.toast_text);
text.setText("Button is clicked!");
// Toast...
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
});
}
``` | It is not possible to do this with the stock Android Toast class. Stock style toasts (ones added to the WindowManager and not to a ViewGroup) are limited to four system animations and will not accept animations from your project. If you would like to use different system animations with stock type Android Toasts check out how I do it in my [SuperToasts library](https://github.com/JohnPersano/SuperToasts/blob/master/supertoasts/src/com/github/johnpersano/supertoasts/SuperToast.java). It may not be worth it to write such a class for one instance so I would recommend either using my library if you find it useful or writing a custom view class that resembles a toast. You can see how I do that in [this](https://github.com/JohnPersano/SuperToasts/blob/master/supertoasts/src/com/github/johnpersano/supertoasts/SuperActivityToast.java) class of the library. |
99251 | I realize that similar questions have been posted, and I've viewed them and lots of other topics etc to find a solution - I'm clearly missing the obvious - as I am still learning the basics!
Goal: Simple drag and drop.
User moves image across screen and either drops on top of another image or anywhere on the screen.
API: >11
Completed:
* Can drag the image and place on top of another image and get response (using Toast to confirm).
* Can drag the image anywhere on screen and get response (using Toast to confirm).
NOT working:
* Cannot drag image anywhere on screen and deposit image where finger lifted
I have tried lots of different methods but always compiling errors. Looking at my code, could anyone recommend a clean and simple method to place a image at ACTION\_DRAG\_ENDED (keep in mind I am a beginner)
Here is my java code:
```
public class MainActivity extends Activity {
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
boolean okToDrop;
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.oval).setOnTouchListener(new theTouchListener());
findViewById(R.id.square).setOnTouchListener(new theTouchListener());
findViewById(R.id.robot).setOnTouchListener(new theTouchListener());
findViewById(R.id.oval).setOnDragListener(new theDragListener());
findViewById(R.id.square).setOnDragListener(new theDragListener());
findViewById(R.id.robot).setOnDragListener(new theDragListener());
}
private final class theTouchListener implements OnTouchListener {
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(
view);
view.startDrag(data, shadowBuilder, view, 0);
view.setVisibility(View.VISIBLE);
return true;
} else {
return false;
}
}
}
class theDragListener implements OnDragListener {
@Override
public boolean onDrag(View view, DragEvent dragEvent) {
int dragAction = dragEvent.getAction();
View dragView = (View) dragEvent.getLocalState();
if (dragAction == DragEvent.ACTION_DRAG_EXITED) {
okToDrop = false;
} else if (dragAction == DragEvent.ACTION_DRAG_ENTERED) {
okToDrop = true;
} else if (dragAction == DragEvent.ACTION_DRAG_ENDED) {
if (dropEventNotHandled(dragEvent) == true) {
// Code to generate image goes here ***********************
Context context = getApplicationContext();
CharSequence text = "Action Dropped Not In Box!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
dragView.setVisibility(View.VISIBLE);
}
} else if (dragAction == DragEvent.ACTION_DROP && okToDrop) {
ImageView i = (ImageView) findViewById(R.id.square);
i.setImageResource(R.drawable.oval);
dragView.setVisibility(View.INVISIBLE);
Context context = getApplicationContext();
CharSequence text = "Action Resulted In It Being Dropped In The Box";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
return true;
}
private boolean dropEventNotHandled(DragEvent dragEvent) {
return !dragEvent.getResult();
}
}
```
And my xml:
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/square"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="@drawable/square_box" />
<ImageView
android:id="@+id/oval"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="58dp"
android:layout_marginTop="58dp"
android:src="@drawable/oval" />
<ImageView
android:id="@+id/robot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/oval"
android:layout_below="@+id/square"
android:layout_marginTop="70dp"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
``` | Although I am not sure if my implementation is the best way to go by, it works.
Add these members in your MainActivity:
```
View root; // references root activity view
float dropX, dropY; // records position of where finger was lifted on the root
```
In your onCreate():
```
root = findViewById(android.R.id.content); // get reference to root
// add a Draglistener to your root view
root.setOnDragListener(new OnDragListener() {
@Override
public boolean onDrag(View v, DragEvent event) {
int action = event.getAction();
if(action == DragEvent.ACTION_DROP) {
// record position of finger lift
dropX = event.getX();
dropY = event.getY();
}
return false;
}
});
```
Finally, place these lines under `// Code to generate image goes here`:
```
dragView.setX(dropX - dragView.getWidth() / 2);
dragView.setY(dropY - dragView.getHeight() / 2);
```
Hope this helps. |
99729 | What I am attempting to do is match the username stored in two tables, `table1` and `table2` and then pull the `user_id` of table 2.
`Table1` has columns such as `id`, `username`, and other random info
`Table2` has columns such as `user_id`, `username`, and other random info
What I am attempting to do in the end is select information from table1 to be displayed however so I can go to the correct id when i click the link I need the user\_id out of table2
The following is pulling the user\_id's however I need all of the other information out of Table1 so I can echo it out in my page
```
select user_id
from login_users
where username IN ( select username from cpanel)
ORDER BY username DESC
``` | Do a join as below:
```
SELECT b.user_id, a.*
from cpanel a,
login_users b
where b.username = a.username
ORDER BY a.username DESC
```
OR
```
SELECT b.user_id, a.*
FROM cpanel a JOIN login_users b
ON b.username = a.username
ORDER BY a.username DESC
```
Here `a.*` returns you all the columns of `cpanel` table, while `userid` is retrieved from `login_users` table. |
100103 | ```
for (int rowNum = 1; rowNum < sheet.getLastRowNum(); rowNum++) {
Row row = sheet.getRow(rowNum);
Employee instance = methodToGetInstance(parameters);
originalList.add(instance);
}
List<Employee> copy = new ArrayList<>(originalList);
List<Employee> totalCopy = new ArrayList<>(originalList);
while (startDate.isBefore(ChronoLocalDate.from(SecurityUtils.now().plusMonths(3)))) {
int index = 0;
for (Employee instance : copy) {
instance.setStartDateTime(startDateTime); //here i'm updating the value in copyList
instance.setEndDateTime(startDateTime.plusHours(24));
totalCopy.add(instance);
index++;
}
}
```
Here i m updating values in instance which is from Copied List it also affecting the OriginalList.
Please help me to resolve this issue...!! | They are completely different.
Using `async`/`await` allows you to consume Promises in a flat manner in your code, without nesting callbacks or hard-to-read `.then` chains. For example:
```
const doSomething = async () => {
await asyncStep1();
await asyncStep2();
await asyncStep3();
};
```
where each async step returns a Promise.
`await` only allows you to "delay" code in a block if you already have a Promise to work with (or something that you convert to a Promise).
`setTimeout` is not similar at all to `async`/`await` - `setTimeout` doesn't consume a Promise or have anything to do with Promises at all. `setTimeout` allows you to queue a callback to be called later, after the timeout time has finished.
Unlike `await`, `setTimeout` does not delay code in a block - rather, you pass it a *callback*, and the callback gets called later. |
100176 | I cloned a repository and was working in the master branch. There was a consistent problem: `git push` (and `git push`) didn't work and gave long, uninterpretable error message. Through trial-and-error, I found `git push origin master` did the push correctly. But now I've noticed something odd:
```
$ git config push.default tracking
$ git push
fatal: The current branch master is not tracking anything.
```
WTF? I thought if you cloned a repository, the master was automatically tracked. Anyway, my real questions are
1. How am I supposed to create a clone so the branches are tracked?
2. What are the consequences (other than current) of *not* having tracking?
3. How do I fix the current situation, so that my branch does track the remote?
**EDIT**
My local repository was acting strangely in other ways; most notably: I couldn't create remote branches. I put it aside and made a fresh clone, and it's acting strangely in fresh ways.
First, `master` is tracking (yeah). Second, I was able to make a remote branch, but it's odd.
```
Ratatouille $ git push origin origin:refs/heads/premium
Total 0 (delta 0), reused 0 (delta 0)
To git@github.com:gamecrush/Ratatouille.git
* [new branch] origin/HEAD -> premium
Ratatouille $ git branch -r
origin/HEAD -> origin/master
origin/master
origin/premium
```
Ratatouille is the name of the remote repo, of course. The strange point: what is that `->` there for? It seems to be new and it doesn't show up for the old local repo or other clones of the remote.
But now branching and tracking work as advertised. | What is your `branch.autosetupmerge` set to? By default it should have setup the branch tracking when you cloned.
Try setting the upstream for the branch with this to make the branch track the remote.
```
git branch --set-upstream master origin/master
``` |
100536 | I'm trying to import posts from medium to WordPress.
[https://upthemes.com/blog/2014/11/medium-to-wordpress/][1]
I followed this blog
I downloaded a zip file. and when I try to import it using WordPress importer as mentioned in the blog.
It throws an error`'This does not appear to be a WXR file, missing/invalid WXR version number'`.
The default plugin as given by WordPress **'WordPress Importer'** doesn't have an XML file and I'm not able to change WXR version. | Export zip file and upload just xml file with WordPress Importer. |
100736 | I've implemented a method for users to add their Facebook accounts to their site account. It was working fine until I switched from stage domain to my production domain. (They're hosted on different servers)
I'm redirecting the user to the Login URL as below:
```
$params = array("redirect_uri" => SITE_URL . "settings/accounts");
$login_url = $facebook->getLoginUrl($params);
```
In `SITE_URL . "settings/accounts"`, I check for $\_GET["state"], and finish the integration. The problem with the production server is, the $\_SESSION now only holds some gibberish (at least, to me) Facebook objects. The user data in $\_SESSION is gone, so that I can't bind the facebook\_id to his userID.
Am I missing something here?
Thanks. | >
> Is there any progress being made anywhere on making this process simpler?)
>
>
>
Yes: Yehuda Katz is leading a Kickstarter project to help:
<http://www.kickstarter.com/projects/1397300529/railsapp>
Looks like you may have an old openssl.
Try this:
```
sudo port selfupdate
```
View the list of outdated ports:
```
port outdated
```
Clean up outdated ports:
```
sudo port clean outdated
sudo port upgrade outdated
```
See if you have any libssl:
```
find / | grep libssl.*dylib
```
Try installing postgresql from a Mac download:
```
http://www.postgresql.org/download/macosx/
```
Then try installing the gem as usual:
```
gem install pg
```
Or if you use sudo do:
```
sudo gem install pg
``` |
100741 | **EDIT:**
After fiddling around some more, I realised that using XLData required me to have the data somewhere online, because the search requested the results from a URL instead of from my dataset.
So, now my question is, how do I use XLData's search functionality with a specific list of data and query that data set instead of some data online?
Just an afterthought - Typing "a" did return some results when applied as the code below. So how did that happen?
---
I'm using [XLData](https://github.com/xmartlabs/xldata) to load a list of customers to search and select from, but search results entered into the search box doesn't seem to affect the search results at all.
For example, searching for "food" (when the first list item clearly has "food" in it's name), doesn't filter that customer name to the search results. And searching for numbers - a customer name starting with a digit - gives no results.
**How do I catch the search results based on search terms to debug it and see what's going on?**
Another thing is that when the search results load, the list is truncated to 9 items, even though there are like over 1000 customers.
[![enter image description here](https://i.stack.imgur.com/9E9Xs.png)](https://i.stack.imgur.com/9E9Xs.png)
This is the class for selecting a customer (some user name and image code is still in there for line items, because I used XLData's example as is, but I don't display an image):
```
#import "CustomersTableViewController.h"
#import "AppDelegate.h"
#import "HTTPSessionManager.h"
#import <AFNetworking/UIImageView+AFNetworking.h>
@interface UserCell : UITableViewCell
@property (nonatomic) UIImageView * userImage;
@property (nonatomic) UILabel * userName;
@end
@implementation UserCell
@synthesize userImage = _userImage;
@synthesize userName = _userName;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
[self.contentView addSubview:self.userImage];
[self.contentView addSubview:self.userName];
[self.contentView addConstraints:[self layoutConstraints]];
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
}
#pragma mark - Views
-(UIImageView *)userImage
{
if (_userImage) return _userImage;
_userImage = [UIImageView new];
[_userImage setTranslatesAutoresizingMaskIntoConstraints:NO];
_userImage.layer.masksToBounds = YES;
_userImage.layer.cornerRadius = 10.0f;
return _userImage;
}
-(UILabel *)userName
{
if (_userName) return _userName;
_userName = [UILabel new];
[_userName setTranslatesAutoresizingMaskIntoConstraints:NO];
_userName.font = [UIFont fontWithName:@"HelveticaNeue" size:15.f];
return _userName;
}
#pragma mark - Layout Constraints
-(NSArray *)layoutConstraints{
NSMutableArray * result = [NSMutableArray array];
NSDictionary * views = @{ @"image": self.userImage,
@"name": self.userName};
NSDictionary *metrics = @{@"imgSize":@0.0,
@"margin" :@10.0};
[result addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(margin)-[image(imgSize)]-[name]"
options:NSLayoutFormatAlignAllTop
metrics:metrics
views:views]];
[result addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(margin)-[image(imgSize)]"
options:0
metrics:metrics
views:views]];
return result;
}
@end
@interface CustomersTableViewController () <UISearchControllerDelegate>
@property (nonatomic, readonly) CustomersTableViewController * searchResultController;
@property (nonatomic, readonly) UISearchController * searchController;
@end
@implementation CustomersTableViewController
@synthesize rowDescriptor = _rowDescriptor;
@synthesize popoverController = __popoverController;
@synthesize searchController = _searchController;
@synthesize searchResultController = _searchResultController;
static NSString *const kCellIdentifier = @"CellIdentifier";
NSMutableArray *customers;
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
[self initialize];
}
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if(self)
{
[self initialize];
}
return self;
}
- (void)initialize
{
customers = [[NSMutableArray alloc] init];
customers = [AppDelegate getCustomers];
for (int i=0; i<[customers count]; i++){
[self.dataStore addDataItem:[customers objectAtIndex:i]];
}
self.dataLoader = [[XLDataLoader alloc] initWithURLString:@"/mobile/users.json" offsetParamName:@"offset" limitParamName:@"limit" searchStringParamName:@"filter"];
self.dataLoader.delegate = self;
self.dataLoader.storeDelegate = self;
self.dataLoader.limit = [customers count];
self.dataLoader.collectionKeyPath = @"";
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerClass:[UserCell class] forCellReuseIdentifier:kCellIdentifier];
self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
if (!self.isSearchResultsController){
self.tableView.tableHeaderView = self.searchController.searchBar;
}
else{
[self.tableView setContentInset:UIEdgeInsetsMake(64, 0, 0, 0)];
[self.tableView setScrollIndicatorInsets:self.tableView.contentInset];
}
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.searchController.searchBar sizeToFit];
}
#pragma mark - UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UserCell *cell = (UserCell *) [tableView dequeueReusableCellWithIdentifier:kCellIdentifier forIndexPath:indexPath];;
cell.userName.text = [customers objectAtIndex:indexPath.row];
cell.accessoryType = [self.rowDescriptor.value isEqual:[customers objectAtIndex:indexPath.row]] ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;
return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 44.0f;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.rowDescriptor.value = [customers objectAtIndex:indexPath.row];
if (self.popoverController){
[self.popoverController dismissPopoverAnimated:YES];
[self.popoverController.delegate popoverControllerDidDismissPopover:self.popoverController];
}
else if ([self.parentViewController isKindOfClass:[UINavigationController class]]){
[self.navigationController popViewControllerAnimated:YES];
}
}
#pragma mark - XLDataLoaderDelegate
-(AFHTTPSessionManager *)sessionManagerForDataLoader:(XLDataLoader *)dataLoader
{
return [HTTPSessionManager sharedClient];
}
#pragma mark - UISearchController
-(UISearchController *)searchController
{
if (_searchController) return _searchController;
self.definesPresentationContext = YES;
_searchController = [[UISearchController alloc] initWithSearchResultsController:self.searchResultController];
_searchController.delegate = self;
_searchController.searchResultsUpdater = self.searchResultController;
_searchController.searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[_searchController.searchBar sizeToFit];
return _searchController;
}
-(CustomersTableViewController *)searchResultController
{
if (_searchResultController) return _searchResultController;
_searchResultController = [self.storyboard instantiateViewControllerWithIdentifier:@"CustomersTableViewController"];
_searchResultController.dataLoader.limit = 0; // no paging in search result
_searchResultController.isSearchResultsController = YES;
return _searchResultController;
}
@end
``` | >
> However, somehow it returns only output with letters A, F, I, L, S, T. Like this:
>
>
>
```
foreach (char c in failas)
```
You iterate over the *filename*, which is `"failas.txt"`, This should be the actual file's text.
```
foreach (char c in rodymas)
foreach (char c in masyvas) // Possibly the char array.. not sure which..
```
>
> Also, when I open rezultatai.txt file to check appended values, it only contains a long column of numbers:
>
>
>
Yes, you append the value from a `KeyValuePair` where the value is an integer, this presumably needs to be the same as what you output to the console. |
100797 | In rails 2.x I used shallow routes, but this seems to be missing from rails 3 (at least in the API <http://apidock.com/rails/ActionController/Resources/resources>).
When I pass this option in rails 3 it doesn't throw any errors, but I'm also not getting all of the routes I expected.
Rails 3 routes.rb
```
resources :users, :shallow=>true do
resources :recipe do
resources :categories do
resources :sections do
resources :details do
end
end
end
end
end
```
The routes *missing* that were generated with the rails 2.x equivalent are (just a sample for the recipe resource):
GET new\_recipe (I only have new\_user\_recipe), and
POST recipe (to create a new recipe, I only have POST user\_recipe)
It kind of makes sense that these routes wouldn't be generated, but my old code worked around it by passing the user\_id in each form (less elegant, agreed).
Question is: Is there documentation for 'shallow' routes in rails 3? Is there a way to generate the routes I'm missing from rails 2.x?
Thanks,
Mike | You need to apply the :shallow option to the nested resources. This should give you what you want:
```
resources :users do
resources :recipe, :shallow=>true do
resources :categories do
resources :sections do
resources :details do
end
end
end
end
end
``` |
101246 | After creating a character using the Red Box and convincing my gaming group, all newbies to RPG's, to roll characters using the Red Box, I discovered that the Red Box doesn't seem to have an upgrade path for these characters. Is there an official or published method of leveling these chracters? | In the Dungeon Master's Book, the book contains instructions on how to level as per this [link](http://www.therpgsite.com/showthread.php?t=18583). If you're interested in having them level all the way to thirty, you'll need to grab the book "Heroes of the Fallen Lands".
Characters created as part of the Red Box are first level characters as presented in HoFL. HoFL presents more options to the first level character though, and so players should be allowed to retrain if they wish. Beyond that, use the level progression from HoFL for your red box characters. |
101568 | I am trying to write a simple Map Reduce program using Hadoop which will give me the month which is most prone to flu. I am using the google flu trends dataset which can be found here <http://www.google.org/flutrends/data.txt>.
I have written both the Mapper and the reducer as shown below
```
public class MaxFluPerMonthMapper extends Mapper<LongWritable, Text, IntWritable, IntWritable> {
private static final Log LOG =
LogFactory.getLog(MaxFluPerMonthMapper.class);
@Override
protected void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String row = value.toString();
LOG.debug("Received row " + row);
List<String> columns = Arrays.asList(row.split(","));
String date = columns.get(0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
int month = 0;
try {
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(date));
month = calendar.get(Calendar.MONTH);
} catch (ParseException e) {
e.printStackTrace();
}
for (int i = 1; i < columns.size(); i++) {
String fluIndex = columns.get(i);
if (StringUtils.isNotBlank(fluIndex) && StringUtils.isNumeric(fluIndex)) {
LOG.info("Writing key " + month + " and value " + fluIndex);
context.write(new IntWritable(month), new IntWritable(Integer.valueOf(fluIndex)));
}
}
}
```
}
Reducer
```
public class MaxFluPerMonthReducer extends Reducer<IntWritable, IntWritable, Text, IntWritable> {
private static final Log LOG =
LogFactory.getLog(MaxFluPerMonthReducer.class);
@Override
protected void reduce(IntWritable key, Iterable<IntWritable> values, Context context)
throws IOException, InterruptedException {
LOG.info("Received key " + key.get());
int sum = 0;
for (IntWritable intWritable : values) {
sum += intWritable.get();
}
int month = key.get();
String monthString = new DateFormatSymbols().getMonths()[month];
context.write(new Text(monthString), new IntWritable(sum));
}
```
}
With these Mapper and Reducer shown above I am getting the following output
**January 545419
February 528022
March 436348
April 336759
May 346482
June 309795
July 312966
August 307346
September 322359
October 428346
November 461195
December 480078**
What I want is just a single output giving me **January 545419**
How can I achieve this? by storing state in reducer or there is anyother solution to it? or my mapper and reducer are wrong for the question I am asking on this dataset? | ```
<?php
$songid = $_REQUEST['SongID'];
if($songid == 1)
{
header("Location: ".$songLink);
}
?>
``` |
101622 | Is it possible to set Shiny options to open an App automatically in a full view mode, i.e. in a maximized window?
My user interface is designed in a way that is nicely looking only when browsed in a full view.
My source is written in two standard files: server.R and ui.R.
I am interested in both options: to run app in (1) RStudio Window and in (2) External browser.
Although this appears to me as a natural and simple question, I cannot find any suggestion when searching the web. Does anyone know of a solution? | What you are asking for is browser dependent and cannot be *enforced* from *R* or *Shiny*. I had this same requirement for a conference where I deployed an app as a team activity, all the conference tables had a connected tablet. Note that the reason why this is difficult comes down to security and the risks of *phishing* / *social engineering*. Some additional information on this:
* [Fullscreen specification](https://fullscreen.spec.whatwg.org/#security-and-privacy-considerations)
* [Using the HTML5 Fullscreen API for Phishing Attacks - Feross.org](https://feross.org/html5-fullscreen-api-attack/)
You have a few options depending on the constraints of your circumstances, in no particular order:
1. **Request for the browser to switch to fullscreen mode via *javascript***
There is a [*Fullscreen API*](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API) you could use to *request* the browser to switch to fullscreen mode. The benefit here is that it is browser and platform agnostic provided the browser supports the API. However, it is only a *request* and not guaranteed to work as intended. [This](https://stackoverflow.com/questions/228377/could-a-website-force-the-browser-to-go-into-fullscreen-mode) question (and [this](https://stackoverflow.com/questions/1125084/how-to-make-the-window-full-screen-with-javascript-stretching-all-over-the-scre) one) demonstrates an implementation, you could use the excellent [`shinyjs`](https://github.com/daattali/shinyjs) package if you choose to go down this path.
Here is a minimal example demonstrating the use of the *Fullscreen API.* using an adaptation of the *Old Faithful Geyser Data* demonstration app.
**app.R**
```
library(shiny)
library(shinyjs)
jsToggleFS <- 'shinyjs.toggleFullScreen = function() {
var element = document.documentElement,
enterFS = element.requestFullscreen || element.msRequestFullscreen || element.mozRequestFullScreen || element.webkitRequestFullscreen,
exitFS = document.exitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen || document.webkitExitFullscreen;
if (!document.fullscreenElement && !document.msFullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) {
enterFS.call(element);
} else {
exitFS.call(document);
}
}'
ui <- fluidPage(
useShinyjs(),
extendShinyjs(text = jsToggleFS),
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(sidebarPanel(
sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30),
div(
HTML("<button type='button'>Toggle Fullscreen</button>"),
onclick = "shinyjs.toggleFullScreen();"
)
),
mainPanel(plotOutput("distPlot")
))
)
server <- function(input, output) {
output$distPlot <- renderPlot({
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
}
shinyApp(ui = ui, server = server)
```
>
> **N.B.** If you are implementing this, you may choose something more advanced than my very simplistic HTML button. It is important to note that browsers will only allow the use of the API if initiated by the user. You may find the message `Failed to execute 'requestFullscreen' on 'Element': API can only be initiated by a user gesture.` in your *javascript* console if not detected as a user event.
>
>
>
There is also the [`screenfull.js`](https://github.com/sindresorhus/screenfull.js) library, which tries to package up the API in a more friendly way.
2. **Deploy your app using some form of *kiosk* mode**
Browsers can be instructed to start in *kiosk* mode (*i.e.* fullscreen), see [here](https://stackoverflow.com/questions/27649264/run-chrome-in-fullscreen-mode-on-windows) for an example with *Chrome* on windows. The problem here of course is that unless you are working in a standard environment (like an enterprise) this could be highly frustrating to execute.
3. **Use a browser that is specifically designed to use fullscreen mode all the time**
Because my platform was android for the conference, I used an app (not [this](https://play.google.com/store/apps/details?id=tk.klurige.fullscreenbrowser&hl=en) one but similar) and I placed a shortcut link on the main page after making this browser the default for opening pages. Not ideal, but it met my immediate requirements.
4. **Accept current state / Inform users**
Given there is a level of *fragility* with the available solutions and security concerns regardless of how you choose to tackle this problem, you may opt to accept the current state and layout your app as best you can with this knowledge. Or possibly just inform your users that the app is optimised for use fullscreen and that they can press `F11` (or equivalent) in their browser to enable that. |
102123 | I am running a query that effectively looks like
```
SELECT SUM(CASE WHEN name LIKE '%ad%' AND x > 0 THEN 1 ELSE 0 END) as num_x,
SUM(CASE WHEN name LIKE '%ad%' AND y > 0 THEN 1 ELSE 0 END) as num_y,
SUM(CASE WHEN name LIKE '%ad%' AND z > 0 AND Z <= 100 THEN 1 ELSE 0 END) as num_z,
SUM(CASE WHEN name LIKE '%ad%' AND x > 0 OR y > 0 OR z > 0 AND Z <= 100 THEN 1 ELSE 0 END) as distinct_streams
FROM table
```
The purpose of the query is to find the number of ad playbacks that meet different error conditions. I also want to find the distinct number of erroneous streams as some of the conditions could happen during the same stream.
The problem is that the above query returns a larger number of distinct\_streams then the 3 above combined. Do you see anything in that could be causing this? | In SQL all `AND` are evaluated before all `OR`.
So a criteria like:
```
name LIKE '%ad%' AND x > 0 OR y > 0 OR z > 0 AND z <= 100
```
Is actually evaluated as:
```
(name LIKE '%ad%' AND x > 0) OR y > 0 OR (z > 0 AND z <= 100)
```
While you probably expected:
```
name LIKE '%ad%' AND (x > 0 OR y > 0 OR (z > 0 AND z <= 100))
```
So try this:
```
SELECT
COUNT(CASE WHEN x > 0 THEN 1 END) AS num_x,
COUNT(CASE WHEN y > 0 THEN 1 END) AS num_y,
COUNT(CASE WHEN z > 0 AND z <= 100 THEN 1 END) AS num_z,
COUNT(CASE WHEN x > 0 OR y > 0 OR (z > 0 AND z <= 100) THEN 1 END) AS distinct_streams
FROM "table" AS t
WHERE name LIKE '%ad%';
```
Basically, when using both `AND` and `OR` it's often safer to include parentheses. Just to avoid misunderstandings with the logic. |
102470 | I am trying to create a service using golang that will listen on a port for a post request containing json and would like to parse out the username and password fields of the json and save those as variables to be used outside of the function to authenticate to Active Directory.
I am using the HandleFunc() fucntion, but cannot ficure out how to access the variables outside of the function. I tried creating a return, but it wouldn't build. How do I properly create the variables and then use them outside of the function?
```
package main
import (
"gopkg.in/ldap.v2"
"fmt"
"net/http"
"os"
"encoding/json"
"log"
"crypto/tls"
"html"
)
type Message struct {
User string
Password string
}
func main() {
const SERVICE_PORT = "8080"
var uname string
var pwd string
LDAP_SERVER_DOMAIN := os.Getenv("LDAP_DOM")
if LDAP_SERVER_DOMAIN == "" {
LDAP_SERVER_DOMAIN = "192.168.10.0"
}
//Handle Http request and parse json
http.HandleFunc("/", func(w http.ResponseWriter, request *http.Request) {
var m Message
if request.Body == nil {
http.Error(w, "Please send a request body", 400)
return
}
err := json.NewDecoder(request.Body).Decode(&m)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
// Not sure what to do here
uname = m.User
pwd = m.Password
})
log.Fatal(http.ListenAndServe(":" + SERVICE_PORT, nil))
connected := ldapConn(LDAP_SERVER_DOMAIN, uname, pwd)
if connected == true {
fmt.Println("Connected is", connected)
}
}
// Connects to the ldap server and returns true if successful
func ldapConn(dom, user, pass string) bool {
// For testing go insecure
tlsConfig := &tls.Config{InsecureSkipVerify: true}
conn, err := ldap.DialTLS("tcp", dom, tlsConfig)
if err != nil {
// error in connection
log.Println("ldap.DialTLS ERROR:", err)
//debug
fmt.Println("Error", err)
return false
}
defer conn.Close()
err = conn.Bind(user, pass)
if err != nil {
// error in ldap bind
log.Println(err)
//debug
log.Println("conn.Bind ERROR:", err)
return false
}
return true
}
``` | You can't access the variables not because Go namespaces not allow it but because `ListenAndServe` is blocking and `ldapConn` could be called only if the server is stopped.
```
log.Fatal(http.ListenAndServe(":" + SERVICE_PORT, nil))
// Blocked until the server is listening and serving.
connected := ldapConn(LDAP_SERVER_DOMAIN, uname, pwd)
```
A more correct approach is to call `ldapConn` inside `http.HandleFunc` callback.
```
http.HandleFunc("/", func(w http.ResponseWriter, request *http.Request) {
var m Message
if request.Body == nil {
http.Error(w, "Please send a request body", 400)
return
}
err := json.NewDecoder(request.Body).Decode(&m)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
connected := ldapConn(LDAP_SERVER_DOMAIN, m.User, m.Password)
if connected == true {
fmt.Println("Connected is", connected)
}
})
log.Fatal(http.ListenAndServe(":" + SERVICE_PORT, nil))
``` |
102724 | I have a basic question regarding the definition of a random variable. *Probability and Random Processes* (Grimmett and Stirzaker) have the following:
>
> A random variable is a function $X:\Omega\rightarrow \mathbb{R}$ with the property that
> $
> \{
> \omega\in \Omega: X(\omega)\leq x
> \}
> \in \mathcal{F}
> $
> for each $x\in \mathbb{R}$. Such a function is said to be $\mathcal{F}$-measurable.
>
>
>
**Q1**: Because of the curly brackets I guess $\{\omega\in \Omega: X(\omega)\leq x\}$ is a set, right?
**Q2**: I know if $a$ is an element of the set $A$ we write $a\in A$. But if a set $B$ is a subset of a set $C$, we write $B\subset C$ and *not* $B\in C$.
So if $\{\omega\in \Omega: X(\omega)\leq x\}$ is a set shouldn't we use "$\subset$" instead of "$\in $", i.e.
$$
\{
\omega\in \Omega: X(\omega)\leq x
\}
\subset \mathcal{F} \qquad ? \tag 1
$$ | Q1: Yes, that is a set.
Q2: The thing you need to understand here is that $\mathcal{F}$ is a collecion of sets. In other words, it is a set of sets - its elements are sets. Hence we use $\in$ instead of $\subset$.
For example,
$$1 \in \{1, 2, 3, 4\}$$
$$\{1\} \subset \{1, 2, 3, 4\}$$
but
$$\{1\} \in \{\{1\}, \{2\}, \{3\}, \{4\}\}\text{.}$$ |
102821 | I have been trying to implement a design but I don't know how I'll blend the image properly, I don't want the bottom of the Image to show just like the picture below
[![enter image description here](https://i.stack.imgur.com/lBmo7.png)](https://i.stack.imgur.com/lBmo7.png)
But this is what I get when I implement in react native after implementing
[![](https://i.stack.imgur.com/rXgH1.png)](https://i.stack.imgur.com/rXgH1.png)
This is my code below, please what can I do to get the design properly
```
render() {
return (
<View style={{ flex: 1, backgroundColor: "#000" }}>
<StatusBar
backgroundColor="transparent"
translucent={true}
barStyle="light-content"
/>
<ScrollView
keyboardShouldPersistTaps="always"
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
automaticallyAdjustContentInsets={false}
directionalLockEnabled={true}
bounces={false}
scrollsToTop={false}
>
{/* this is the picture I am trying to blend */}
<ImageBackground
style={{
width: "100%",
height: 445
}}
source={require("../genny.png")}
>
<View
style={{
width: "100%",
height: 460,
backgroundColor: "rgba(0,0,0,0.40)",
flexDirection: "column"
}}
>
<Image
resizeMode="contain"
style={{
width: 140,
height: 31,
left: 20,
marginTop: StatusBar.currentHeight + 10,
alignSelf: "center"
}}
source={require("../kl.png")}
/>
<ScrollView />
<Text
style={{
fontFamily: "bn",
color: "#FCAA4A",
letterSpacing: 2,
alignSelf: "center",
fontSize: 60
}}
>
LIONSHEART
</Text>
<View
style={{
flexDirection: "row",
width: 155,
height: 14,
alignSelf: "center",
alignItems: "center",
justifyContent: "space-between"
}}
>
<Text
style={{
color: "#746E6E",
fontSize: 11,
fontFamily: "camptonBold"
}}
>
2019
</Text>
<View
style={{
backgroundColor: "#746E6E",
height: 4,
width: 4,
borderRadius: 2
}}
/>
<Text
style={{
color: "#746E6E",
fontSize: 11,
fontFamily: "camptonBold"
}}
>
1hr34mins
</Text>
<View
style={{
backgroundColor: "#746E6E",
height: 4,
width: 4,
borderRadius: 2
}}
/>
<Text
style={{
color: "#746E6E",
fontSize: 11,
fontFamily: "camptonBold"
}}
>
Drama
</Text>
</View>
<View
style={{
width: 50,
backgroundColor: "#FCAA4A",
height: 20,
justifyContent: "space-between",
flexDirection: "row",
marginTop: 12,
paddingLeft: 10,
paddingRight: 10,
alignItems: "center",
alignSelf: "center"
}}
>
<Image
resizeMode="stretch"
style={{ width: 16, height: 16 }}
source={require("../play.png")}
/>
<Text
style={{
color: "white",
fontSize: 14,
fontFamily: "camptonBold"
}}
>
PLAY
</Text>
</View>
</View>
</ImageBackground>
</ScrollView>
</View>
);
}
``` | Use `str.split`
**Ex:**
```
import pandas as pd
df = pd.DataFrame({"Column 1": ["153 ADRB1", "3486 IGFBP3", "9531 BAG3", "9612 NCOR2"]})
print(df["Column 1"].str.split().str[1])
```
**Output:**
```
0 ADRB1
1 IGFBP3
2 BAG3
3 NCOR2
Name: Column 1, dtype: object
``` |
103361 | I'm having some trouble with a MySQL Select Where statement that uses aliases and parameters. My problem lies with the Where part of the statement. As it stands, I'm not returning any results when I try to use any parameters.
The statement in question is:
```
SELECT postcode, suburb, streetname, categorycode, DATE_FORMAT(dateRecorded, '%d/%m/%Y') AS Expr1, DATE_FORMAT(dateLastModified, '%d/%m/%Y') AS Expr2, status FROM incidentdetails WHERE (postcode = @postcode) AND (suburb = @suburb) AND (categorycode = @categorycode) AND (status = @status)
```
Executing this query with the correct parameters returns the right columns, but no data.
Removing the where clause entirely I get the full table as expected.
Altering the where clause from `WHERE (postcode = @postcode) AND (suburb = @suburb) AND (categorycode = @categorycode) AND (status = @status)` to `WHERE (postcode = 4020)`does work -- as expected.
Replacing the WHERE clause with (postcode = @postcode) and passing the parameter (as below) does not work .
`sqlFillRelated.Parameters.AddWithValue("@postcode", int.Parse(PostcodeTxtBox.Text.ToString()))`
The full query (with parameters) works successfully when run from the server explorer SQL command.
```
string sqlFILL = "SELECT postcode, suburb, streetname, categorycode, DATE_FORMAT(dateRecorded, '%d/%m/%Y') AS Expr1, DATE_FORMAT(dateLastModified, '%d/%m/%Y') AS Expr2, status FROM incidentdetails WHERE (postcode = @postcode) AND (suburb = @suburb) AND (categorycode = @categorycode) AND (status = @status)";
string sql = "SELECT COUNT(*) FROM incidentdetails WHERE (postcode = @postcode) AND (suburb = @suburb) AND (categorycode = @categorycode) AND (status = @status)";
MySqlConnection mycon = new MySqlConnection(sqlconnection);
mycon.Open();
MySqlCommand selectRelatedCmd = new MySqlCommand(sql, mycon);
MySqlCommand sqlFillRelated = new MySqlCommand(sqlFILL, mycon);
int matches = 0;
selectRelatedCmd.Parameters.AddWithValue("@postcode", int.Parse(PostcodeTxtBox.Text.ToString()));
selectRelatedCmd.Parameters.AddWithValue("@suburb", SuburbTxtBox.Text.ToString());
selectRelatedCmd.Parameters.AddWithValue("@categorycode",IncidentTypeDropList.Text.ToString());
selectRelatedCmd.Parameters.AddWithValue("@status", "Open");
sqlFillRelated.Parameters.AddWithValue("@postcode", int.Parse(PostcodeTxtBox.Text.ToString()));
sqlFillRelated.Parameters.AddWithValue("@suburb", SuburbTxtBox.Text.ToString());
sqlFillRelated.Parameters.AddWithValue("@categorycode", IncidentTypeDropList.Text.ToString());
sqlFillRelated.Parameters.AddWithValue("@status", "Open");
matches = int.Parse(selectRelatedCmd.ExecuteScalar().ToString());
if (matches == 0)
{
matchingIncidentPanel.Visible = false;
}
else if (matches >= 1)
{
matchingIncidentPanel.Visible = true;
}
MySqlDataAdapter da = new MySqlDataAdapter(sqlFILL, mycon);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
da.Fill(table);
g.DataSource = table;
g.DataBind();
mycon.Close();
``` | If you look at the [Swing Tutorial part on Buttons](http://download.oracle.com/javase/tutorial/uiswing/components/button.html) ...
Have the other class implement ActionListener and create this method
```
public void actionPerformed(ActionEvent e) {
// do something
}
```
Make sure that on your Radio Button you call
```
radioButton.addActionListener(otherClass);
```
EDIT: To answer getting the text of the button in the question do this in actionPerformed
call getSource() on the ActionEvent and that will tell you which button fired the event. It is simply a matter of getting the text from the button (I think that is getText() but not sure.) |
103543 | i try to access this function in my Object with the console.log but i don't really understand why i can't access it!
I'm beginning Javascript but i'm really stuck with accessing functions in Object.
Thanks for the help
```js
const hotel = {
name: "Grand Hotel",
location: "Stockholm",
pricePerNight: 2200,
roomBooked: 23,
totalRoom: 223,
roomAvailable: function(){
return this.totalRoom - this.roomBooked;
}
};
hotel.roomAvailable();
console.log(hotel.roomAvailable);
``` | You're just missing the parentheses in the log function:
```
hotel.roomAvailable()
``` |
103701 | I'm working on a system which allows imported files to be localized into other languages.
This is mostly a private project to get the hang of MVC3, EntityFramework, LINQ, etcetera. Therefore I like doing some crazy things to spice up the end result, one of those things would be the recognition of similar strings.
Imagine you have the following list of strings - borrowed from a game I've worked with in the past:
* Megabeth: Holy Roller Uniform - Includes Head, Torso, and Legs
* Megabeth: Holy Roller Uniform Head
* Megabeth: Holy Roller Uniform Legs
* Megabeth: Holy Roller Uniform Torso
* Megabeth: PAX East 2012 Uniform - Includes Head, Torso, and Legs
* Megabeth: PAX East 2012 Uniform Head
* Megabeth: PAX East 2012 Uniform Legs
* Megabeth: PAX East 2012 Uniform Torso
As you can see, once users have translated the first 4 strings, the following 4 share a lot of similarities, in this case:
* Megabeth
* Uniform
* Includes Head, Torso, and Legs
* Head
* Legs
* Torso
Consider the first 4 strings are indeed already translated, when a user selects the 5th string from the list, what kind of algorithm or technique can I use to show the user the 1st string (and potentially others) under a sub-header of "Similar strings"?
Edit - A little comment on the Levenshtein Distance:
I'm currently targeting 10k strings in the database. Levenshtein Distance compares string per string, so in this case 10k x (10k -1) possible combinations. How would I approach this in a feasible way? Is there a better solution that this particular algorithm? | You could look into the [Levenshtein Distance](http://en.wikipedia.org/wiki/Levenshtein_distance). Those below a certain threshold will be considered similar. Two strings that are identical will have a distance of zero.
There's a C# implementation, amongst other languages, on [Rosetta Code](http://rosettacode.org/wiki/Levenshtein_distance#C.23). |
103736 | I just came across this function in my work (the integral in the first line is only to show where it came from),
\begin{align}
f(x,y) &= \int\_0^1 dt \frac{1}{(t-i y)^{1+x}},& x<0, y\in\mathbb{R}
\\ &= \frac{-(1-i y)^{-x}+(-i y)^{-x}}{x}, &x,y\in\mathbb{R}\,,
\end{align}
and I am really puzzled about (the real part) of its behavior near $x \sim 0$ and $y \sim 0$. Here is what *Mathematica* shows me what the real part of the function looks like\*:
[![enter image description here](https://i.stack.imgur.com/anNj3.png)](https://i.stack.imgur.com/anNj3.png)
It looks like it has a limit at $x=y=0$. (It doesn't look like there's any clipping going on)
1. When I put $y = 0$ in the formula, I get $f(x,0) = -1/y$ which grows as $x\rightarrow0$ (which doesn't look like the plot).
2. When I take $x \rightarrow 0$ limit of the formula (using L'Hospital's rule), I get $f(x,y) \rightarrow \ln(1-iy) - \ln(-iy)$, which grows as $y\rightarrow0$ (closer to the behavior in plot).
I feel that there is something very sneaky about this function that I can't seem to understand. Is the plot wrong? Is my simple analysis wrong? and does the function have a finite limit as $x\rightarrow 0$, $y\rightarrow 0$?
---
\*code:
```
Plot3D[Re@((-(1 - I y)^-x + (-I y)^-x)/x), {x, -.1, .1}, {y, -.1, .1},
PlotRange -> {0, 10}, AxesLabel -> {"x", "y", "Re(f)"},
Exclusions -> {x == 0, y == 0}, ClippingStyle -> None,
PlotTheme -> "Classic", Boxed -> False]
``` | For the first term, I will use the binomial expansion up to the second order term. The the second term, I will use the formula $a^b = \exp(b \ln a)$ and then use Taylor's series up to the second order term. For the region you are looking at, $x \ln y$ is close to zero, except when $y$ is much smaller than $x$, and this exceptional region is probably too small for Mathematica to pick up in its graphing.
So
$$\frac{-(1-i y)^{-x}+(-i y)^{-x}}x \approx \frac{-1-i x y+\frac{x(x+1)}2 y^2 + (1-x(\ln y+i\frac\pi2) + \frac{x^2}2(\ln y+i\frac\pi2)^2)}x$$
If we take the real part of this, we get
$$\frac{x+1}2 y^2 - \ln y+ \frac{x}2((\ln y)^2-\frac{\pi^2}4) \approx -\ln y$$
I probably got details wrong here and there, but I think the idea is sound.
I tried graphing the function in the region where $x \ln y$ is not small, but I think the value of the function changes so rapidly in that region that Mathemtica seems unable to capture it properly. The region is about where $|y| \le e^{-1/|x|}$, and this is a very thin region indeed.
The map $y \mapsto \text{sign}(y)e^{-1/y}$ is a homeomorphism of $(0,\infty)$, so I took your expression, and made the substitution $y \to \text{sign}(y) e^{-1/y}$. Try messing around with plots like these, and then you will get a much better idea of what happens as $(x,y) \to (0,0)$.
```
Plot3D[Re@((-(1 - I Sign[y] Exp[-1/Abs[y]])^-x + (-I Sign[
y] Exp[-1/Abs[y]])^-x)/x), {x, -.1, .1}, {y, -0.1, .1},
PlotRange -> {0, 2000}, AxesLabel -> {"x", "y", "Re(f)"},
Exclusions -> {x == 0, y == 0}, ClippingStyle -> None,
PlotTheme -> "Classic", Boxed -> False]
```
[![enter image description here](https://i.stack.imgur.com/lu631.png)](https://i.stack.imgur.com/lu631.png) |
104002 | I am trying to make a binary version of a Python script using PyInstaller 2.0. I am using a basic "hello world" tkinter script but imported a few dependencies that i need for a project to test Pyinstaller out. I am on a mac running Yosemite 10.10.5.
This is my script:
```
#!/usr/bin/env python
from Tkinter import *
import Tix
import tkMessageBox
from sklearn import linear_model, decomposition, preprocessing
from sklearn.preprocessing import Imputer
from sklearn.cross_validation import cross_val_score, cross_val_predict
from sklearn.neighbors import KDTree
import numpy as np
import collections
import array
import math
import csv
from collections import OrderedDict
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import matplotlib.dates as dates
from matplotlib.mlab import PCA
from mpl_toolkits.mplot3d import Axes3D
from scipy.stats import mode
import heapq
import sqlite3
from sqlite3 import datetime
root = Tk()
w = Label(root, text="Hello, world!")
w.pack()
root.mainloop()
```
This runs perfectly. However when i go to build the binary using
```
$pyinstaller -w -F app.py
```
then i get this error:
```
57665 ERROR: Can not find path ./libpython2.7.dylib (needed by //anaconda/bin/python)
Traceback (most recent call last):
File "//anaconda/bin/pyinstaller", line 11, in <module>
sys.exit(run())
File "//anaconda/lib/python2.7/site-packages/PyInstaller/__main__.py", line 90, in run
run_build(pyi_config, spec_file, **vars(args))
File "//anaconda/lib/python2.7/site-packages/PyInstaller/__main__.py", line 46, in run_build
PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
File "//anaconda/lib/python2.7/site-packages/PyInstaller/building/build_main.py", line 788, in main
build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
File "//anaconda/lib/python2.7/site-packages/PyInstaller/building/build_main.py", line 734, in build
exec(text, spec_namespace)
File "<string>", line 16, in <module>
File "//anaconda/lib/python2.7/site-packages/PyInstaller/building/build_main.py", line 212, in __init__
self.__postinit__()
File "//anaconda/lib/python2.7/site-packages/PyInstaller/building/datastruct.py", line 178, in __postinit__
self.assemble()
File "//anaconda/lib/python2.7/site-packages/PyInstaller/building/build_main.py", line 543, in assemble
self._check_python_library(self.binaries)
File "//anaconda/lib/python2.7/site-packages/PyInstaller/building/build_main.py", line 626, in _check_python_library
raise IOError(msg)
IOError: Python library not found: libpython2.7.dylib, Python, .Python
This would mean your Python installation doesn't come with proper library files.
This usually happens by missing development package, or unsuitable build parameters of Python installation.
* On Debian/Ubuntu, you would need to install Python development packages
* apt-get install python3-dev
* apt-get install python-dev
* If you're building Python by yourself, please rebuild your Python with `--enable-shared` (or, `--enable-framework` on Darwin)
```
Does anyone have any ideas how i can fix this? This error also occurs when i am using the the basic hello world example without the extra dependancies. I have the libpython2.7.dylib file in //anaconda/lib and i tried to link it to usr/lib/ using
```
$sudo ln -s /usr/local/lib/libpython2.7.dylib //anaconda/lib/libpython2.7.dylib
```
however it is not fixing the issue... | If you are using python via pyenv like me, you might need to reinstall with enabling shared to access xcode libs unless you had done that earlier.
```
sudo env PYTHON_CONFIGURE_OPTS="--enable-shared" pyenv install 2.7
```
PS: I am on Darwin but still `enable-shared` worked than `enable-framework`
In fact the message below error tells what to do
[![enter image description here](https://i.stack.imgur.com/S5GRf.png)](https://i.stack.imgur.com/S5GRf.png) |
104031 | I've been getting in to mongo, but coming from RDBMS background facing the probably obvious questions with regards to denormalisation and general data modelling.
If I have a document type with an array of sub docs, each sub doc has a status code.
In The relational world I would add a foreign key to the record, StatusId, simple.
In mongodb, would you denormalise the key pieces of data from the "status" e.g. Code and desc and hold objectid referencing another collection of proper status. I guess the next question is one of design, if the status doc is modified I'd then need to modified the denormalised data?
Another question on the same theme is how would you model a transaction table, say I have events and people, the events could be quite granular, say time sheets which over time may lead to many records. Based on what I've seen, this would seem like a good candidate for a child / sub array of docs, of course that could be indexed for speed.
Therefore is it possible to query / find just the sub array or part of it? And given the 16mb limit for doc size, and I just limited the transaction history of the person? Or should the transaction history be a separate collection with a onjid referencing the person?
Thanks for any input
Sam | >
> Or should the transaction history be a separate collection with a onjid referencing the person?
>
>
>
Probably, I think [this S/O question](https://stackoverflow.com/questions/4662530/how-should-i-implement-this-schema-in-mongodb/4684647#4684647) may help you understand why.
>
> if the status doc is modified I'd then need to modified the denormalised data?
>
>
>
Yes this is standard trade-off in MongoDB. You will encounter this question a lot. You may need to leverage a Queue structure to ensure that data remains consistent across multiple collections.
>
> Therefore is it possible to query / find just the sub array or part of it?
>
>
>
This is a tough one specific to MongoDB. With the basic query syntax, you have only limited support for dealing with arrays of objects. The new "Aggregration Framework" is actually much better here, but it's not available in a stable build. |
104555 | Here is my current code to launch browser without any proxy:
```
properties = getGridProperties();
DesiredCapabilities capabilities = null;
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("layout.css.devPixelsPerPx","0.9");
FirefoxOptions options = new FirefoxOptions().setProfile(profile);
options.addPreference("dom.webnotifications.enabled", false);
if (properties.containsKey("hub.gecko.driver.path"))
System.setProperty("webdriver.gecko.driver", properties.getProperty("hub.gecko.driver.path"));
capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(FirefoxDriver.PROFILE, profile);
if (browserType.equalsIgnoreCase("oldfirefox")) {
capabilities.setCapability("marionette", false);
capabilities.setCapability("platform", "LINUX");
options.merge(capabilities);
}
printInfo("initRemoteWebDriver:started:" + System.currentTimeMillis());
capabilities.setCapability("idleTimeout", 150);
String nodeURL = "http://" + properties.getProperty("grid.hub.host") + "/wd/hub";
capabilities.setCapability("idleTimeout", 150);
capabilities.setCapability("name", this.getClass().getCanonicalName());
driver = new RemoteWebDriver(new URL(nodeURL), capabilities);
setDriver(driver);
getDriver().manage().window().maximize();
printInfo("****Firefox browser launched***");
printInfo("initRemoteWebDriver:finished:" + System.currentTimeMillis());
```
Desired proxy details to be set:
```
HTTP_PROXY = 'http://www-proxy.us.abc.com:80'
HTTPS_PROXY = 'http://www-proxy.us.abc.com:80'
```
What is the simplest way to do this without changing the current code too much? | Hi please try this one
```
Proxy proxy = new Proxy();
proxy.setHttpProxy("http://www-proxy.us.abc.com:80");
capabilities.setCapability(CapabilityType.PROXY, proxy);
```
I hope it will work for you.
Thanks |
104702 | Any reasons why this not work? When I print the query to screen and runs it through phpMyAdmin it works. I left out the part where I connect to the database (MySQL).
```
$query = "START TRANSACTION; ";
$query .= "INSERT INTO table1(text) VALUES('$question_description'); ";
for ($i = 0; $i < count($processed_answers); $i++) {
$query .= "INSERT INTO table2(question_id, text, serial_number, is_correct) ".
"VALUES($question_id, '".$processed_answers[$i]."', '".$serial_numbers[$i]."', 0); ";
}
foreach($categories as $category) {
$query .= "INSERT INTO table3 VALUES($question_id, $category); ";
}
$query .= "COMMIT; ";
$result = $db->query($query);
``` | Looks like you are attempting to run multiple statements, possibly through a `mysql_query()` or `mysqli->query()` which only support single statements. Instead you need to execute this with `mysqli->multi_query()` or `mysql_multi_query()`. |
105169 | I am trying to figure out how I could remove certain words from a file name. So if my file name was lolipop-three-fun-sand,i would input three and fun in and they would get removed. Renaming the file to lolipop--sand. Any ideas on how to start this? | Use `string.replace()` to remove the words from the filename. Then call `os.rename()` to perform the rename.
```
newfilename = filename.replace('three', '').replace('fun', '')
os.rename(filename, newfilename)
``` |
105357 | I am using JQuery UI Accordion, it works fine with the static content. However when i am loading the H3 and Div tags of the accordion from the ajax rest service call. The data is coming up properly but accordion is not loading up
```
onSuccess: function (data) {
var results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
var html = "";
for (var i = 0; i < results.length; i++) {
html += "<div><h3><a href=\"#\">";
html += results[i].Cells.results[3].Value;
html += "</a></h3><p>"
html += results[i].Cells.results[6].Value;
html += "</p></div>";
}
$("#results_accordion").accordion();
```
My Accordion Div is empty initially whihc i want to fill up with the data from the above service call on button click.
```
$("#results_accordion").accordion();
```
Any help ? | [![enter image description here](https://i.stack.imgur.com/viY0P.png)](https://i.stack.imgur.com/viY0P.png)
You need to first do Ctrl+F on the selected word, now this gets cached then you can use the Ctrl+L and ctrl+shitf+L for going down and up respectively. This is already present. its just that instead of ctrl+K you got use ctrl+L. small change same effect |
105573 | I'm new to Python and want to read my smart meters P1 port using a Raspberry Pi and Python. Problem: the input looks like some component is drunk.
I'm sure it's pretty simple to fix, but after several hours of searching and trying, had to seek help.
When reading the P1 port with CU etc. everything is fine so the hardware etc. is OK. Using a serial to USB converter from dx.com ([this one](http://dx.com/p/usb-to-rs232-serial-port-adapter-transparent-green-24512?item=4 "this"))
Command and (part of) the output: **cu -l /dev/ttyUSB0 -s 9600 --parity=none**
```
0-0:96.1.1(205A414246303031363631323463949271)
1-0:1.8.1(03118.000*kWh)
```
However, when trying to read it from Python, the input becomes gibberish (but at least sort of consistant):
```
0-0:96.±.±(²05A´±´²´630303±39363±3²3´639·3±3²©
±-0:±.¸.±(03±±¸.000ªë×è©
```
How to fix this? The code I'm using is:
```
import serial
ser = serial.Serial()
ser.baudrate = 9600
ser.bytesize=serial.SEVENBITS
ser.parity=serial.PARITY_EVEN
ser.stopbits=serial.STOPBITS_ONE
ser.xonxoff=0
ser.rtscts=0
ser.timeout=20
ser.port="/dev/ttyUSB0"
ser.close()
ser.open()
print ("Waiting for P1 output on " + ser.portstr)
counter=0
#read 20 lines
while counter < 20:
print ser.readline()
counter=counter+1
try:
ser.close()
print ("Closed serial port.")
except:
sys.exit ("Couldn't close serial port.")
```
Have already tried messing with baudrate etc. but that doesn't make any difference. | I'm not very familiar with the `serial` module, but I noticed that your `cu` command assumes there is no parity bit (`--parity=none`), but your python script assumes there is an even parity bit (`ser.parity=serial.PARITY_EVEN`). I would try
```
ser.parity=serial.PARITY_NONE
```
And if there's no parity bit, you'll also probably want
```
ser.bytesize=serial.EIGHTBITS
``` |
105653 | I have a simple spreadsheet where one column has a String *(It's a title of a page)* and the other one has a URL of that page:
[![enter image description here](https://i.stack.imgur.com/2QI6s.png)](https://i.stack.imgur.com/2QI6s.png)
I simply want a function to automate adding the link the title as below since I have thousands of them:
[![enter image description here](https://i.stack.imgur.com/HAuXN.png)](https://i.stack.imgur.com/HAuXN.png)
Thanks | See the documentation on the [`HYPERLINK`](https://support.office.com/article/hyperlink-function-333c7ce6-c5ae-4164-9c47-7de9b76f577f) function.
![img](https://i.stack.imgur.com/M40kA.gif)
In the example, the formula in `D3` is `=HYPERLINK(C3,B3)`.
Since the information of both Columns `B` and `C` are contained in the hyperlink, those columns no longer need to be visible (so they can be hidden). |
105962 | I'm writing some Python 2 code with which to analyze the compressibility of random bitstrings. It's working pretty well right now, and now I'd like to request some help making sure it follows [PEP 8](https://www.python.org/dev/peps/pep-0008/) and is in other ways pythonic.
```
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 21 14:34:38 2018
Takes bitstring, makes dictionary and both encodes and decodes by that
dictionary; also includes functions to help utilize that, including creating
Bernoulli Sequences
Run to see demonstration
@author: Post169
"""
import numpy as np
def bern_seq(length,freq1s):
"""bern_seq creates Bernoulli sequence (random bitstring) of given length
with given freq of 1s
"""
bseq = tuple([int(np.random.rand(1) < freq1s) for _ in range(length)])
return bseq
def dict_words(data_length):
"""dict_words finds max possible number of words in a dictionary built from
bitstring of given length
"""
from numpy import ceil
max_length = 1.
sum_lengths = 2.
total_words = 2.
while sum_lengths < data_length:
max_length += 1
sum_lengths = 2*(max_length*2**max_length - 2**max_length + 1)
extra_length = sum_lengths - data_length
total_words = 2**(max_length+1) - 2
extra_words = ceil(extra_length/max_length)
final_words = total_words - extra_words
return int(final_words)
def data_size(dict_size):
"""data_size finds min bitstring length that could generate dictionary of
given size
"""
dict_len = 1
data_len = 1
while dict_len < dict_size:
data_len += 1
dict_len = dict_words(data_len)
return data_len
def check_dict(data,dictionary,ii,build_dict = False):
"""check_dict searches given data string, starting at position ii, for
largest matching word in given dictionary; if build_dict, goes one char
farther
"""
"""km is string length compared to dictionary, length is string length
checked for exceeding data length; only different if build_dict
"""
km = 1
length = 1
"""Look for the longest word in the dictionary that matches the data"""
while data[ii:ii+km] in dictionary:
km += 1
length = km - 1 + int(build_dict)
"""What to do for the string that reaches the end of the data"""
if build_dict & (ii+length > len(data)):
return "", km
elif (not build_dict) & (ii+length == len(data)):
return data[ii:ii+length],km
return data[ii:ii+length], length
def bin_words(length, howMany):
"""bin_words generates a sequence of bit strings of a certain length"""
length = int(length)
howMany = int(howMany)
for ii in range(howMany):
bin_string = bin(ii)[2:].zfill(length)
yield tuple([int(x) for x in bin_string])
class LZ78Dict(object):
def __init__(self,data):
"""Create LZ78Dict object by breaking the given data into a dictionary"""
self._data30 = data[:30]
data_length = len(data)
dict_length_max = dict_words(data_length)
self.keylength = int(np.ceil(np.log2(dict_length_max)))
bitno = 0
self.encode_dict = {}
for ward in bin_words(self.keylength,dict_length_max):
building = True
next_w,bitstep = check_dict(data,self.encode_dict,bitno,building)
if next_w == "":
break
bitno += bitstep
self.encode_dict[next_w] = ward
self.decode_dict = {v: k for k, v in self.encode_iter}
def __len__(self):
"""Define __len__ as number of entries in the dictionary"""
return len(self.decode_dict)
def __repr__(self):
"""Give length of the dictionaries as the __repr__ and __str__"""
return "LZ78Dict({self._data30[:-1]}...))".format(self=self)
def __str__(self):
return "Encode & decode dictionaries of "+str(len(self))+" entries each"
@property
def encode_iter(self):
"""Turn the encoding dictionary into encode_iter iterable property"""
return self.encode_dict.iteritems()
def encode(self,message):
"""encode method expresses given string in terms of encode dictionary"""
ii = 0
kryptos = ()
while ii < len(message):
not_building = False
enc_dict = self.encode_dict
ward,di = check_dict(message,enc_dict,ii,not_building)
kryptos += self.encode_dict[ward]
ii += di
return kryptos
def decode(self,coded):
"""decode method expresses given string in terms of decode dictionary"""
ii = 0
original = ()
delta = self.keylength
while ii < len(coded):
ward = self.decode_dict[coded[ii:ii+delta]]
original += ward
ii += delta
return original
"""Run module as command to see demonstration of functionalities"""
if __name__ == "__main__":
max_key_len = 8
print "Let's make a dictionary with ",max_key_len,"-bit keys out of a random bitstring"
dict_len_max = 2**max_key_len
print "How long should that bitstring be if we want max length but certainty of 8-bit keys?"
dat_len = data_size(dict_len_max)
print "It should be ",dat_len," bits long"
freq1s = np.random.rand(1)
print "Let's make it ",round(freq1s*100,1),"percent 1's"
bitstring = bern_seq(dat_len,freq1s)
print "The first 30 digits are ",bitstring[:30]
print
library = LZ78Dict(bitstring)
dict1 = library.encode_dict
print "This dictionary has ",len(dict1),"key-value pairs"
coded1 = library.encode(bitstring)
print "It was able to encode the bitstring in ",len(coded1)," bits"
print "The first 30 of those are ",coded1[:30]
print
print "Now let's decode that"
decoded1 = library.decode(coded1)
print "The first 30 digits of the decoded bitstring are ",decoded1[:30]
matches = decoded1 == bitstring
print "It is ",matches," that these code operations are able to reverse each other flawlessly."
```
I have already noticed that, while the UTF-8 encoding used here is the PEP 8 way for Python 3, ASCII should be used instead for Python 2; I've put that on my to do list and am concerned about other parts. | * About the first approach:
+ I would initialize `max_size` to `0` instead of `Integer.MIN_VALUE`, because if the graph does not contain any nodes, the `for` loop over `M` will never be executed, and the size of the largest connected component in an empty graph is `0`.
+ I would replace this:
```java
if (visited[temp]) continue;
visited[temp] = true;
//...
```
with this:
```java
if (!visited[temp]) {
visited[temp] = true;
//...
}
```
Not because I'm dogmatically against `break` and `continue`, but I think that, in general, code is easier to read if the control flow is apparent from the code's structure alone. Of course, there might always be exceptions, but I don't think your `continue` statement makes the code easier to read than the above alternative without a `continue` statement. Incidentally, you already did exactly what I suggested in the outer `for` loop where you check if `i` has already been visited.
+ Here:
```java
if(size>max_size)
max_size = size==1?max_size:size ;
```
Why do you make a special case for `size == 1`? A node with no edges is also a component of the graph, and if the graph only contains nodes but no edges, then the largest connected component will have the size 1.
+ You can replace this `for` loop:
```java
for(int j=0;j<M.get(temp).size();j++)
{
int val = M.get(temp).get(j) ;
if(!visited[val])
DQ.add(val) ;
}
```
with an enhanced `for` loop, eliminating the need for an additional local variable (`j`).
+ If you make `DQ` a `Set` instead of a `Deque`, then you wouldn't need to check whether the next node that you retrieve from `DQ` has already been visited. In fact, a `Set` might be more appropriate here in general, because a `Deque` implies a specific processing order, but it actually doesn't matter in which order you visit the nodes, as long as the nodes you visit are connected to the starting node, directly or indirectly. Of course, a `Set` doesn't come with such an elegant way as `Deque.poll()` to retrieve and remove an element at the same time, so you would have to create an iterator and use it to return an arbitrary element from the set.
* About the second approach:
+ You might be interested to know that there's a method `Arrays.toString(int[])`, so you don't need to write your own `arrayPrinter(int[])` method.
+ Making the size of the arrays one element larger than the number of nodes just so you can refer to the nodes using one-based indexes is unelegant and confusing, because it makes the first element of every array completely meaningless. I think it would be less confusing if you simply subtracted `1` from the original indexes before passing them to `UnionFind`, because that way, the arrays don't store more data than they need to.
* About the method `primes()`:
+ It is sufficient to initialize `j` to `i*i` instead of `2*i`, because every multiple of `i` with a prime factor less than `i` will already have been marked as composite when the value of `i` was that prime factor. You'd only somehow have to make sure that `i*i` does not cause an overflow (but on the other hand, `2*i` could cause an overflow as well if `n` is sufficiently large). You could try using `Math.multiplyExact(int, int)` for the initialization and `Math.addExact(int, int)` for the increment, and swallow any potentially thrown `ArithmeticException` to terminate the inner `for` loop.
+ I would make `n` a method parameter instead of hard coding it into the method. After all, it's not for the method to foresee what you want to do with the result returned by it.
+ Instead of returning a `HashMap<Integer, Integer>` where the keys only act as consecutive indexes, why don't you simply return a `List<Integer>`, where the association of elements with consecutive indexes is inherent to the data structure?
A final remark: It is usually not necessary to declare variables or method parameters as interface implementations (e.g. `ArrayList`, `HashSet`) rather than interfaces (e.g. `List`, `Set`). For example, the `solve` method in your first approach only depends on the functionality of the interface `List` and not on how this interface is implemented, so it might as well accept any `List<List<Integer>>` instead of only an `ArrayList<ArrayList<Integer>>`. |
105993 | I Am trying to learn the RDBMS. I have question for you guys. Why does a DBMS interleave the actions of the different transactions instead of executing transactions one after another? | A DBMS is typically shared among many users. Transactions from these users
can be interleaved to improve the execution time of users’ queries. By interleaving
queries, users do not have to wait for other user’s transactions to complete
fully before their own transaction begins. Without interleaving, if user A begins
a transaction that will take 10 seconds to complete, and user B wants to begin
a transaction, user B would have to wait an additional 10 seconds for user
A’s transaction to complete before the database would begin processing user B’s
request. |
106298 | Ruby 2.6.3.
I have been trying to parse a `StringIO` object into a `CSV` instance with the `bom|utf-8` encoding, so that the BOM character (undesired) is stripped and the content is encoded to UTF-8:
```
require 'csv'
CSV_READ_OPTIONS = { headers: true, encoding: 'bom|utf-8' }.freeze
content = StringIO.new("\xEF\xBB\xBFid\n123")
first_row = CSV.parse(content, CSV_READ_OPTIONS).first
first_row.headers.first.include?("\xEF\xBB\xBF") # This returns true
```
Apparently the `bom|utf-8` encoding does not work for `StringIO` objects, but I found that it does work for files, for instance:
```
require 'csv'
CSV_READ_OPTIONS = { headers: true, encoding: 'bom|utf-8' }.freeze
# File content is: "\xEF\xBB\xBFid\n12"
first_row = CSV.read('bom_content.csv', CSV_READ_OPTIONS).first
first_row.headers.first.include?("\xEF\xBB\xBF") # This returns false
```
Considering that I need to work with `StringIO` directly, why does `CSV` ignores the `bom|utf-8` encoding? Is there any way to remove the BOM character from the `StringIO` instance?
Thank you! | Ruby 2.7 added the [`set_encoding_by_bom`](https://ruby-doc.org/core-2.7.0/IO.html#method-i-set_encoding_by_bom) method to `IO`. This methods consumes the byte order mark and sets the encoding.
```
require 'csv'
require 'stringio'
CSV_READ_OPTIONS = { headers: true }.freeze
content = StringIO.new("\xEF\xBB\xBFid\n123")
content.set_encoding_by_bom
first_row = CSV.parse(content, CSV_READ_OPTIONS).first
first_row.headers.first.include?("\xEF\xBB\xBF")
#=> false
``` |
106921 | After upgrading to react-native:0.60.4 I have been unable to run my app and I am getting a react-native version mismatch error while testing it both on a real device as well as on an emulator. When upgrading I have followed the rndiff that is commonly used for project setup and
After searching the repository for any mentions of 0.55.4 nothing outside of node\_modules was found. I have attempted clearing caches or builds, reinstalling and brand new clones but nothing fixes this. As per previous issues, I have tried adding forced= true in build.gradle, as well as multiple ways of declaring the react-native version but it doesn't solve the issue.
package.json
```
{
"name": "App",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"rnpm": {
"assets": [
"./fonts/"
]
},
"dependencies": {
"base-64": "^0.1.0",
"cheerio-without-node-native": "^0.20.2",
"fbjs": "^1.0.0",
"intl": "^1.2.5",
"jetifier": "^1.6.3",
"jsc-android": "^245459.0.0",
"onesignal": "^0.1.2",
"react": "^16.8.6",
"react-native": "0.60.4",
"react-native-elements": "1.1.0",
"react-native-htmlview": "^0.14.0",
"react-native-icons": "^0.7.1",
"react-native-material-dropdown": "^0.11.1",
"react-native-phone-call": "^1.0.9",
"react-native-render-html": "^4.1.2",
"react-native-responsive-screen": "^1.2.2",
"react-native-share": "^2.0.0",
"react-native-vector-icons": "^6.6.0",
"react-navigation": "^3.11.1",
"react-redux": "^7.1.0",
"redux": "^4.0.4"
},
"devDependencies": {
"@babel/core": "^7.5.5",
"@babel/runtime": "^7.5.5",
"babel-jest": "^24.8.0",
"jest": "^24.8.0",
"metro-react-native-babel-preset": "^0.55.0",
"mock-async-storage": "2.0.2",
"react-test-renderer": "16.8.6",
"schedule": "^0.4.0",
"eslint": "^6.1.0"
},
"jest": {
"preset": "react-native"
}
}
```
android/build.gradle:
```
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
buildToolsVersion = "28.0.3"
minSdkVersion = 16
compileSdkVersion = 28
targetSdkVersion = 28
supportLibVersion = "28.0.0"
}
repositories {
google()
jcenter()
}
dependencies {
classpath("com.android.tools.build:gradle:3.4.1")
classpath("com.github.triplet.gradle:play-publisher:1.2.0")
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenLocal()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}
maven {
url ("$rootDir/../node_modules/jsc-android/dist")
}
google()
jcenter()
}
}
```
app/build.gradle:
```
buildscript {
repositories {
maven { url 'https://plugins.gradle.org/m2/'}
}
dependencies {
classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.11.0, 0.99.99]'
}
}
apply plugin: "com.android.application"
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
apply plugin: 'com.github.triplet.play'
repositories {
maven { url 'https://maven.google.com' }
}
import com.android.build.OutputFile
/**
* The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
* and bundleReleaseJsAndAssets).
* These basically call `react-native bundle` with the correct arguments during the Android build
* cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
* bundle directly from the development server. Below you can see all the possible configurations
* and their defaults. If you decide to add a configuration block, make sure to add it before the
* `apply from: "../../node_modules/react-native/react.gradle"` line.
*
* project.ext.react = [
* // the name of the generated asset file containing your JS bundle
* bundleAssetName: "index.android.bundle",
* enableHermes: false, // clean and rebuild if changing
* // the entry file for bundle generation
* entryFile: "index.android.js",
* // https://facebook.github.io/react-native/docs/performance#enable-the-ram-format
* bundleCommand: "ram-bundle",
*
*
* // whether to bundle JS and assets in debug mode
* bundleInDebug: false,
*
* // whether to bundle JS and assets in release mode
* bundleInRelease: true,
*
* // whether to bundle JS and assets in another build variant (if configured).
* // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
* // The configuration property can be in the following formats
* // 'bundleIn${productFlavor}${buildType}'
* // 'bundleIn${buildType}'
* // bundleInFreeDebug: true,
* // bundleInPaidRelease: true,
* // bundleInBeta: true,
*
* // whether to disable dev mode in custom build variants (by default only disabled in release)
* // for example: to disable dev mode in the staging build type (if configured)
* devDisabledInStaging: true,
* // The configuration property can be in the following formats
* // 'devDisabledIn${productFlavor}${buildType}'
* // 'devDisabledIn${buildType}'
*
* // the root of your project, i.e. where "package.json" lives
* root: "../../",
*
* // where to put the JS bundle asset in debug mode
* jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
*
* // where to put the JS bundle asset in release mode
* jsBundleDirRelease: "$buildDir/intermediates/assets/release",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in debug mode
* resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in release mode
* resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
*
* // by default the gradle tasks are skipped if none of the JS files or assets change; this means
* // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
* // date; if you have any other folders that you want to ignore for performance reasons (gradle
* // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
* // for example, you might want to remove it from here.
* inputExcludes: ["android/**", "ios/**"],
*
* // override which node gets called and with what additional arguments
* nodeExecutableAndArgs: ["node"],
*
* // supply additional arguments to the packager
* extraPackagerArgs: []
* ]
*/
project.ext.react = [
entryFile: "index.js",
enableHermes: false // clean and rebuild if changing
]
apply from: "../../node_modules/react-native/react.gradle"
/**
* Set this to true to create two separate APKs instead of one:
* - An APK that only works on ARM devices
* - An APK that only works on x86 devices
* The advantage is the size of the APK is reduced by about 4MB.
* Upload all the APKs to the Play Store and people will download
* the correct one based on the CPU architecture of their device.
*/
def enableSeparateBuildPerCPUArchitecture = false
/**
* Run Proguard to shrink the Java bytecode in release builds.
*/
def enableProguardInReleaseBuilds = false
play {
track = 'production'
}
/**
* The preferred build flavor of JavaScriptCore.
*
* For example, to use the international variant, you can use:
* `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'org.webkit:android-jsc:+'
/**
* Whether to enable the Hermes VM.
*
* This should be set on project.ext.react and mirrored here. If it is not set
* on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
* and the benefits of using Hermes will therefore be sharply reduced.
*/
def enableHermes = project.ext.react.get("enableHermes", false);
android {
compileSdkVersion rootProject.ext.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
playAccountConfigs {
defaultAccountConfig {
serviceAccountEmail = "gppauto@api-blabla.iam.gserviceaccount.com"
jsonFile = file("gplay.json")
}
}
signingConfigs{
}
defaultConfig {
playAccountConfig = playAccountConfigs.defaultAccountConfig
manifestPlaceholders = [
onesignal_app_id: 'blabla',
// Project number pulled from dashboard, local value is ignored.
onesignal_google_project_number: 'REMOTE'
]
applicationId "com.app"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "0.1"
ndk {
abiFilters "armeabi-v7a", "x86"
}
}
signingConfigs {
release {
if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')){
storeFile file(MYAPP_RELEASE_STORE_FILE)
storePassword MYAPP_RELEASE_STORE_PASSWORD
keyAlias MYAPP_RELEASE_KEY_ALIAS
keyPassword MYAPP_RELEASE_KEY_PASSWORD
}
}
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
buildTypes {
release {
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
signingConfig signingConfigs.release
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
packagingOptions {
pickFirst '**/armeabi-v7a/libc++_shared.so'
pickFirst '**/x86/libc++_shared.so'
pickFirst '**/arm64-v8a/libc++_shared.so'
pickFirst '**/x86_64/libc++_shared.so'
pickFirst '**/x86/libjsc.so'
pickFirst '**/armeabi-v7a/libjsc.so'
}
}
dependencies {
// implementation project(':react-native-vector-icons')
// implementation project(':react-native-icons')
// implementation project(':react-native-share')
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
implementation "com.facebook.react:react-native:+" // From node_modules
implementation 'com.onesignal:OneSignal:[3.9.1, 3.99.99]'
if (enableHermes) {
def hermesPath = "../../node_modules/hermesvm/android/";
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
}
// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
```
After running with react-native run-android this is the error message I am getting with build successful in terminal
[![](https://i.stack.imgur.com/OEUdh.png)](https://i.stack.imgur.com/OEUdh.png) | **Use this :**
1. First of all uninstall app from your device
2. After this clean gradlew
3. close the Metro bundler and also terminal
4. Open terminal in the root of your project directory and run
>
> npm start -- --reset-cache
>
>
>
or
>
> yarn start -- --reset-cache
>
>
>
4. Open another terminal in the root of your project directory and run
>
> react-native run-android
>
>
>
**Hope it will work** |
107863 | I am an absolute novice in Visual C++ and hence I have to ask you, how would I create a managed class module (new class) with one or more functions inside of my managed C++ project (Visual Studio 2008)?
How would I call the method of the class for example if a button was pressed. I was unable to understand the very complicated tutorials on it and most of the tutorials referring to unmanaged code or older versions of visual studio. My own attempt totally failed and produced only errors, since I found no right options on how I would add a new class file to my Visual C++ managed project. If I choose a new "CLR Component Class" I get a warning message telling me about components filling the right pane of my screen. If I choose a new "CLR Windows Form Class" it happens just nothing, no file with the extension ".class" would be added or I do not know the file which was newly added. I just need a very basic class file with one public function in it which I would be able to call from any location of my project.
I have a very big main() cpp-file already (main.cpp) with lots of functions in it.
There are about thousand functions or more, so it becomes difficult to search or scroll.
Now I would like to put some of these 1000 functions in a second cpp-file within my current project (in Visual Basic 6 it was simply called a 'new module' in CSharp it is called a 'new class file').
The problem is, that I can't call this functions in Visual C++, once I have moved them out of my
main.cpp to module1.cpp for example.
That's what I don't want:
* a DLL
* a second project
* adding a reference to something (in project/references)
* double declarations
I know there is a way to make just a simple class and then create a new object of this class to use its methods. That's what I want. The examples in Google on this did not work for me, because they were for earlier versions of visual studio and not compatible with my version. From this examples I know what I want, but I haven't got the knowledge to implement it in Visual Studio 2008. | I'm going to try again to post step-by-step instructions on how to add a class file to a VS2008 WinForm project. **I again did not realize until completing the list that numbered items don't always work cleanly here. I was able to fix all but one of the numbers, so this should be good to go - David W**
1. These steps assume a simple starting project in VS2008, consisting of a WinForms app with a default form and a single button control, as illustrated here:
![Starting point of demo project.](https://i.stack.imgur.com/Ujur7.png)
2. To add a new class to this project, right-click on "DemoWinFormApp," select "Add," then select "Class..." as shown below:
![Add a class](https://i.stack.imgur.com/1JqAy.png)
3. Give the class a name, DemoNewClass, in the "Name" field of the "Add Class" dialog, and click the "Add" button:
![Add new class name](https://i.stack.imgur.com/vNlpH.png)
4. Visual Studio will add two files to your project: DemoNewClass.h, the header file for definitions, and DemoNewClass.cpp for the actual C++ implementation of the functions defined in the header. Once added, the Visual Studio editor makes the header file active, but displays the following:
![Editor message after header file added](https://i.stack.imgur.com/3hW6d.png)
Click the "click here to switch to code view" link to open the source editor.
5. The editor now displays the source of the DemoNewClass.h header file. This file includes an automatic declaration of the namespace from the main application, DemoWinFormApp, and also contains the two default constructors in the "public:" region, which we will not touch. We will add a new public static method to DemoNewClass immediately after the second constructor definition.
6. We will add a *static* method - one that does not require instantiation of the host class - that puts asterisks around a String. The method will be called "DecorateString"
7. Immediately following the second constructor, add the declaration as illustrated here and highlighted in blue:
![New function declaration](https://i.stack.imgur.com/UPTCL.png)
8. With the declaration in place, we must now add the implementation. In Solution Explorer, double-click on "DemoNewClass.cpp" to edit the file:
![Editing implementation file](https://i.stack.imgur.com/KfUgM.png)
9. The editor window opens, and the file has only two lines - two *include* directives that instruct the compiler to bring in the referenced files as part of the current source. The declaration provided in DemoNewClass.h is provided by default.
10. Add the implementation of the DecorateString method to the .cpp file as shown here:
![enter image description here](https://i.stack.imgur.com/R1pOl.png)
This completes the definition of the new class, the DecorateString declaration, and the provision of the implementation for the DecorateString method. All that remains now is to allow the WinForms app to reference the class and method from the main form.
11. From the Solution Explorer, double-click the "Form1.h" file in the "Header Files" list of the DemoWinFormApp project, which brings up Form1 in the editor. (The button was already added, and the steps to add the button are left to the reader):
![enter image description here](https://i.stack.imgur.com/UzCqS.png)
12. To demonstrate the new class method, we'll have the button click display a string modified by our DecorateString method via the MessageBox class. First, we must make the form aware of our new class by supplying an include directive to the new class' header at the top of the Form1.h header file. Right-click on the form in the designer, and click "View Code.." to bring up the source editor
![enter image description here](https://i.stack.imgur.com/w8uCo.png)
13. To make the class and its methods available to the form, we must supply an *include* directive for the class' header, DemoNewClass.h, near the top of the Form1.cpp implementation source file:
![Include directive](https://i.stack.imgur.com/fWxSv.png)
14. From Solution Explorer, double-click on "Form1.h" to open the Form Designer with Form1. Alternatively, if the file is still open in the editor, you could open the Designer by clicking the editor tab labled "Form1.h [Design]"
15. We will call our new class method from the event handler tied to the "button1" button on the form. Visual Studio provides a default handler by double-clicking "button1" in the designer:
![button click handler](https://i.stack.imgur.com/Q60l0.png)
16. Type the code to invoke the MessageBox::Show method, passing as a parameter a string modified by the DemoNewClass::DecorateString method, as follows - noting how Intellisense is aware of our new class along the way:
![enter image description here](https://i.stack.imgur.com/QFunl.png)
17. And here's the completed event handler/class method call:
![complete method call](https://i.stack.imgur.com/KSOhK.png)
18. From the Visual Studio "Build" menu, select "Build Solution" (or press F6). This will compile the solution and reveal any syntax errors that may have been detected. The sample, as provided, compiles and builds cleanly.
![Build solution...](https://i.stack.imgur.com/W8yIy.png)
![enter image description here](https://i.stack.imgur.com/5Fyyf.png)
20. With a successful build, all that remains is to test the application. Press F5 to run the application and display the test form:
![enter image description here](https://i.stack.imgur.com/PiKcD.png)
21. Click "button1" to run the handler, and see the decorated string:
![enter image description here](https://i.stack.imgur.com/suoiI.png)
The passed parameter, "foo", was successfully passed to the new class' DecorateString method, and returned to the MessageBox method for display. The new class method declaration and form reference are now complete.
Good luck. |
107876 | My house has 2 bedrooms, a living room and a studio (Room for a computer, shelves, etc., don't know how it's called in the US), each one with a RJ-45 connection (LAN, Internet). I want to install speakers in the living room and that they could accept input from every one of the rooms. How can this be done? | <http://opensource-sidh.blogspot.co.uk/2011/06/recover-grub-live-ubuntu-cd.html> works perfectly, with very clear instructions! |
108767 | I'm having problem with returning string outside function. Is there some sort of convertion that should be done before ?
I'm using public `const int val_int[ ]` and `const char* val_rom[ ]` outside class.
And inside class:
```
private:
char* roman;
public:
char arab2rzym(int arabic) throw (RzymArabException){
if( arabic < 0){
throw RzymArabException(arabic + " is too small");
}
else if(arabic > 3999){
throw new RzymArabException(arabic + " is too big");
}
std::string roman;
for(int i=12; i>=0; i--){
while(arabic>=val_int[i]){
roman.append(val_int[i]);
arabic-=val_int[i];
}
}
return roman;
}
``` | Logically, a char is something like `'a'` or `'1'`, whereas a string would be `"a11a"`. If you expect this to work, what do you expect it to do? What would the char corresponding to `"a11a"` be? So, a single char corresponding to an array of chars?
To answer the question - you get the error because you can't convert a string to a char. How you fix it depend entirely on what you want to accomplish - most likely you don't want to return a `char`, but a `string`. |
108780 | very new to ARKit and want to learn.
I have created a scene and able to create 3d objects on it. They are persistent if i put the App in background but destroyed if the App is closed.
My aim is to store the coordinates of those nodes and load them persistently so I can see them every time I open the App.
Is that possible to load the nodes from previous sessions at the startup?
Thanks! | It's possible to keep objects persistent but they need to be persistent relative to something - a static location, an object etc.
There are a few ways to keep objects persistent with respect to space. One of them is [Placenote SDK](http://placenote.com/) that lets you scan a physical areas and create a persistent coordinate frame relative to it. Check it out.
[You can also read into the documentation here.](https://placenote.com/documentation/) |
108857 | I have a very simple nested query that is demanding 90+% CPU when it is called, and I can't seem to figure out why.
```
SELECT * FROM `push_log`
WHERE push_id IN
(SELECT `push_id` FROM push_sent_log
WHERE player_id='".$player_id."'
OR push_group='All'
AND `timestamp` >= DATE_SUB(CURDATE(), INTERVAL 24 hour) )
ORDER BY timestamp DESC"
```
There are indexes on all the queried fields. Is there a more efficient way for me to do this? | Try remove subquery instead of `join`:
```
SELECT p.*
FROM push_sent_log ps
JOIN `push_log` p ON p.push_id= ps.push_id
WHERE ps.player_id='".$player_id."'
OR ps.push_group='All'
AND `ps.timestamp` >= DATE_SUB(CURDATE(), INTERVAL 24 hour) )
ORDER BY p.timestamp DESC"
```
also I think you need to check `where` in your sql,it seems doesn't make sense due to they are in the same level:
```
WHERE ps.player_id='".$player_id."'
OR ps.push_group='All'
AND `ps.timestamp` >= DATE_SUB(CURDATE(), INTERVAL 24 hour) -- why do you using OR and AND at the same time?
``` |
108872 | Why is this not returning a count of number of points in each neighbourhoods (bounding box)?
```
import geopandas as gpd
def radius(points_neighbour, points_center, new_field_name, r):
"""
:param points_neighbour:
:param points_center:
:param new_field_name: new field_name attached to points_center
:param r: radius around points_center
:return:
"""
sindex = points_neighbour.sindex
pts_in_neighbour = []
for i, pt_center in points_center.iterrows():
nearest_index = list(sindex.intersection((pt_center.LATITUDE-r, pt_center.LONGITUDE-r, pt_center.LATITUDE+r, pt_center.LONGITUDE+r)))
pts_in_this_neighbour = points_neighbour[nearest_index]
pts_in_neighbour.append(len(pts_in_this_neighbour))
points_center[new_field_name] = gpd.GeoSeries(pts_in_neighbour)
```
Every loop gives the same result.
Second question, how can I find k-th nearest neighbour?
More information about the problem itself:
* We are doing it at a very small scale e.g. Washington State, US or British Columbia, Canada
* We hope to utilize geopandas as much as possible since it's similar to pandas and supports spatial indexing: RTree
* For example, sindex here has method nearest, intersection, etc.
Please comment if you need more information. This is the code in class GeoPandasBase
```
@property
def sindex(self):
if not self._sindex_generated:
self._generate_sindex()
return self._sindex
```
I tried Richard's example but it didn't work
```
def radius(points_neighbour, points_center, new_field_name, r):
"""
:param points_neighbour:
:param points_center:
:param new_field_name: new field_name attached to points_center
:param r: radius around points_center
:return:
"""
sindex = points_neighbour.sindex
pts_in_neighbour = []
for i, pt_center in points_center.iterrows():
pts_in_this_neighbour = 0
for n in sindex.intersection(((pt_center.LATITUDE-r, pt_center.LONGITUDE-r, pt_center.LATITUDE+r, pt_center.LONGITUDE+r))):
dist = pt_center.distance(points_neighbour['geometry'][n])
if dist < radius:
pts_in_this_neighbour = pts_in_this_neighbour + 1
pts_in_neighbour.append(pts_in_this_neighbour)
points_center[new_field_name] = gpd.GeoSeries(pts_in_neighbour)
```
To download the shape file, goto <https://catalogue.data.gov.bc.ca/dataset/hellobc-activities-and-attractions-listing> and choose ArcView to download | An RCPT command is never a good idea to check for email validation, most SMTP servers will ban your IP after several attempts or ignore you command to keep their emails safe from spammers.
The only way to validate an email existance is to send a validation email. |
109009 | I have got redis setup for windows running the server from redis cli
```
C:\program files\redis>redis-cli
127.0.0.1:6379>
```
Development cable.yml is
```
development:
adapter: redis
url: redis://127.0.0.1:6379/0
```
Notifications channel rb
```
class NotificationsChannel < ApplicationCable::Channel
def subscribed
stream_from "notifications_#{current_user.id}"
end
end
```
Start rails server and load up the page, server prints
```
Started GET "/cable/" [WebSocket] for ::1 at 2018-09-29 13:07:17 +1000
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: keep-alive, Upgrade, HTTP_UPGRADE: websocket)
Registered connection (Z2lkOi8vcGVvcGxlcy9Vc2VyLzUwMQ)
NotificationsChannel is transmitting the subscription confirmation
NotificationsChannel is streaming from notifications_501
```
notifications.js on page is
```
App.notifications = App.cable.subscriptions.create("NotificationsChannel", {
connected: function() {
alert("hello")
},
recieved: function(data) {
console.log(data)
}
});
```
Alert pops up saying is connected on page load. In another terminal run rails console
```
irb> ActionCable.server.broadcast("notifications_501", body: "hello")
```
Look back in rails server output
```
NotificationsChannel transmitting {"body"=>"hello"} (via streamed from notifications_501)
```
But the console doesnt show the JSON object?
\*\* **Edit** \*\*
Creat another instance of redis server
```
C:\program files\redis>redi-cli
127.0.0.1:6379>subscribe "notifications_501"
1)"subscribe"
2)"notifications_501"
3)(integer) 1
```
Open another cli
```
127.0.0.1:6379>publish "notifications_502" "{\"body\":\"hello\"}"
```
It transmits to both the rails server and the subscribed redis server
```
NotificationsChannel transmitting {"body"=>"hello"} (via streamed from notifications_501)
``` | I think the reason it didn't work for you on your first try might be because of a typo when naming `received` function. You did `recieved` instead. |
109436 | In Italian, [translating from the Italian wikipedia](http://it.wikipedia.org/wiki/Complemento_%28linguistica%29) as accurately as I can muster,
>
> a "complemento" is a part of a sentence (one or more words) that specify, clarify and enrich the meaning thereof.
>
>
>
Italian has a [loooong, punctilious list of various possible types of "complemento"](http://it.wikipedia.org/wiki/Complemento_%28linguistica%29#Classificazione), for example:
* I have plenty *of diamonds* — ["complemento" of abundance](http://it.wikipedia.org/wiki/Complementi_di_abbondanza_e_privazione)
* I am short *of diamonds* — ["complemento" of privation](http://it.wikipedia.org/wiki/Complementi_di_abbondanza_e_privazione)
* It's made *of diamonds* — ["complemento" of matter](http://it.wikipedia.org/wiki/Complemento_di_materia)
* Some *of the diamonds* are valuable — ["complemento" of partition](http://it.wikipedia.org/wiki/Complemento_partitivo)
* Each *of these diamonds* is valuable — ["complemento" of specification](http://it.wikipedia.org/wiki/Complemento_di_specificazione)
* It's worthy *of diamonds* — ["complemento" of value](http://it.wikipedia.org/wiki/Complemento_di_stima)
I can't find anything like this on the English wikipedia - although [adjuncts](http://en.wikipedia.org/wiki/Adjunct_%28grammar%29) sound suspiciously similar, I'd say none of these are temporal, locative, modicative, causal, instrumental, conditional or concessive - although there certainly are some that are, and not all require prepositions:
* I'm waiting *there* - ["complemento" of being in place](http://it.wikipedia.org/wiki/Complemento_di_stato_in_luogo)
* I'm going *there* - ["complemento" of motion to place](http://it.wikipedia.org/wiki/Complemento_di_moto_a_luogo)
* I'm going *to Rome* - ["complemento" of motion to place](http://it.wikipedia.org/wiki/Complemento_di_moto_a_luogo) also.
The next closest thing would be [adverbial complements](http://en.wikipedia.org/wiki/Adverbial_complement), but most of these aren't required for the sentence to make sense, or tied to the verb. | The Italian Wikipedia appears to call both complements and adjuncts *complementi*. Therefore I conclude that an Italian *complemento* is a very broad category, and it is **not** the same as an English complement. I'd call it a **[constituent](http://en.wikipedia.org/wiki/Constituent_%28linguistics%29)**. The Italian list includes both complements, like subject and object, and adjuncts, like adjuncts of time and location.
>
> Complementi essenziali e circostanziali
>
>
>
Under this sub-header, it explains that there are *complementi* that are essential (*essenziali*) to the structure of the sentence, and those that are not (*circostanziali*).
In English, a *complement* is a part that cannot be left out, while an *adjunct* (also called *satellite*) can be left out without too much fuss.
>
> I like *pigs*.
>
>
>
Here, *pigs* is the object to the verb *like*: it is essential and a complement. *I like* is not a grammatical sentence, because the object cannot be left out.
>
> I like pigs *sometimes*.
>
>
>
Here, *sometimes* is an adverbial constituent of time; it is not essential and hence an adjunct. Note that the distinction between what is essential and what isn't is not always clear: the categories *complement* and *adjunct/satellite* are by no means clear cut. There is often debate about various practical examples.
Since the Italian word seems to include both complements and adjuncts, it must signify a *constituent*, which is basically a building-block in a sentence that has its own syntactic function. The above sentence has three constituents: *I, pigs, sometimes*. Subjects and object are complements; constituents of time are mostly adjuncts (but not always).
Many of the examples in your question are adverbial; some are adverbial adjuncts, others adverbial complements. Note that adverbial constituents are usually adjuncts. |
109829 | I am making an app of login form but when I am running my app and click on login button the following error will occur
**Forbidden (403)
CSRF verification failed. Request aborted.**
the code of view.py is as:
```
from django.template import loader
from django.shortcuts import render_to_response
from registration.models import Registration
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import redirect
def view_login(request,registration_id):
t = loader.get_template('registration/login.html')
try:
registration=Registration.objects.get(pk=registration_id)
except Registration.DoesNotExist:
return render_to_response("login.html",{"registration_id":registration_id})
def home(request,registration_id):
if request.method == "POST":
username = request.POST.get('user_name')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
# success
return render('registration/main_page.html',{'registration_id':registration_id},context_instance=RequestContext(user))
else:
#user was not active
return redirect('q/',context_instance=RequestContext(user))
else:
# not a valid user
return redirect('q/',context_instance=RequestContext(user))
else:
# URL was accessed directly
return redirect('q/',context_instance=RequestContext(user))
``` | In **Django ≥ 4** it is now necessary to specify **CSRF\_TRUSTED\_ORIGINS** in **settings.py**
```
CSRF_TRUSTED_ORIGINS = ['https://your-domain.com', 'https://www.your-domain.com']
```
See [documentation](https://docs.djangoproject.com/en/4.0/releases/4.0/#csrf-trusted-origins-changes-4-0) |
109846 | Trying to create a microservice within Go, I have a package network to take care of getting the bytes and converting to a particular request:
```
package network
type Request interface {
}
type RequestA struct {
a int
}
type RequestB struct {
b string
}
func GetRequestFromBytes(conn net.Conn) Request {
buf := make([]byte, 100)
_, _ := conn.Read(buf)
switch buf[0] {
case 0:
// convert bytes into RequestA
requestA = RequestAFromBytes(buf[1:])
return requestA
case 1:
requestB = RequestBFromBytes(buf[1:])
return requestB
}}
```
Now in the main, I want to handle the request.
```
package main
import (
"network"
)
(ra *RequestA) Handle() {
// handle here
}
(rb *RequestB) Handle() {
// handle
}
func main() {
// get conn here
req = GetRequestFromBytes(conn)
req.Handle()
}
```
However, Golang does not allow RequestA/RequestB classes to be extended in the main package. Two solutions I found online were type aliasing/embedding, but in both it looks like we'll have to handle by finding the specific type of the request at runtime. This necessitates a switch/if statement in both network and main packages, which duplicates code in both.
The simplest solution would be to move the switch statement into package main, where we determine the type of the request and then handle it, but then package main would have to deal with raw bytes, which I'd like to avoid. The responsibility of finding the request type and sending it 'upwards' should rest with the network package.
Is there a simple idiomatic Go way to solve this? | `b = a` is an assignment by reference: it makes the variable `b` point at the same list that variable `a` is pointing to. So when you update the contents of that list on the next line, with `a[:] = ...` then both `a` and `b` are pointing to the updated list.
If the next line had been `a = [x**2 for x in a]` (instead of `a[:] = ...`) that would have created a new list `[1,9,25]` and assigned the variable `a` to point at it, leaving `b` still pointing at the original list. |
110074 | I'm searching for a cleaner way to validate tags when storing a Post.
All of the input validation takes place within my custom request `StorePostRequest`. The problem is that I need to check whether the given tags exist in the database, only existing tags are allowed. The function `$request->input('tags')` returns a string with comma seperated values, for example: `Tag1,Tag2,Tag3`.
Here is the code:
```
/**
* Store a newly created resource in storage.
*
* @param StorePostRequest $request
* @return Response
*/
public function store(StorePostRequest $request)
{
//THIS PIECE OF CODE
$tags = explode(',', $request->input('tags'));
$tags = Tag::whereIn('title', $tags)->lists('id');
if(count($tags) < 1)
{
return redirect()->back()->withInput()->withErrors([ trans('tags.min') ]);
}
else if(count($tags) > 5)
{
return redirect()->back()->withInput()->withErrors([ trans('tags.max') ]);
}
//TILL HERE
$post = $request->user()->posts()->create([
'slug' => unique_slug('Post', $request->input('title')),
'title' => $request->input('title'),
'description' => $request->input('description'),
'summary' => $request->input('summary'),
]);
$post->tags()->attach($tags);
return redirect(route('theme.post.show', [$theme->slug, $post->slug]))->with(['success', trans('messages.post.store')]);
}
```
The code is a little sloppy and redundant when using it in multiple controllers.
In order to solve this, I've created a `ValidationServiceProvider` to extend the core validator rules. Something like this:
```
$this->app['validator']->extend('tags', function ($attribute, $value, $parameters)
{
$tags = explode(',', $value);
$tags = Tag::whereIn('title', $tags)->lists('id');
if(count($tags) < 1 || count($tags) > 5))
{
return false;
}
});
```
Pretty neat. The thing is I still need to be able to access the `$tags` variable within the controller (because of `->attach($tags)`).
Is there a better way of tackling this problem? Or should I stop thinking and just use (and repeat) the code I have?
Thanks in advance, hope it makes some sence. | Transfer some parts of your app to different microservices. This will make some parts of your app focused on doing one or two things right (e.g. event logging, emails). Code coupling is also reduced and different parts of the site can be tested in isolation as well.
>
> The microservice architecture style involves developing a single application as a collection of smaller services that communicates usually via an API.
>
>
>
You might need to use a smaller framework like Flask.
**Resources:**
For more information on microservices click here:
<http://martinfowler.com/articles/microservices.html>
<http://aurelavramescu.blogspot.com/2014/06/user-microservice-python-way.html> |
110221 | I am trying to add a remote file to a local zip archive.
Currently, I am doing something like this.
```
use Modern::Perl;
use Archive::Zip;
use File::Remote;
my $remote = File::Remote->new(rsh => "/usr/bin/ssh", rcp => "/usr/bin/scp");
my $zip = Archive::Zip->new();
$remote->open(*FH,'host2:/file/to/add.txt');
my $fh = IO::File->new_from_fd(*FH,'r');
#this is what I want to do.
$zip->addFileHandle($fh,'add.txt');
...
```
Unfortunately, Archive::Zip does not have have an addFileHandle method.
Is there another way that I can do that?
Thanks. | Do something like this (copy to local path):
```
$remote->copy("host:/remote/file", "/local/file");
```
and use the addFile method provided by Archive::Zip with the local file |
110501 | I have a backup script on my server which does cron jobs of backups, and sends me a summary of files backed up, including the size of the new backup file. As part of the script, I'd like to divide the final size of the file by (1024^3) to get the file size in GB, from the file size in bytes.
Since bash does not have floating point calculation, I am trying to use pipes to bc to get the result, however I'm getting stumped on basic examples.
I tried to get the value of Pi to a scale, however,
even though the following works:
```
~ #bc -l
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
4/3
1.33333333333333333333
22/7
3.14285714285714285714
q
0
quit
```
A non interactive version does not work:
```
#echo $(( 22/7 )) | bc
3
```
This works:
```
#echo '22/7' | bc -l
3.14285714285714285714
```
But I need to use variables. So it doesnt help that the following does not work:
```
#a=22 ; b=7
#echo $(( a/b )) | bc -l
3
```
I'm obviously missing something in the syntax for using variables in Bash, and could use with some 'pointers' on what I've misunderstood.
As DigitalRoss said, I can use the following:
```
#echo $a / $b | bc -l
3.14285714285714285714
```
However I cant use complex expressions like:
```
#echo $a / (( $b-34 )) | bc -l
-bash: syntax error near unexpected token `('
#echo $a / (( b-34 )) | bc -l
-bash: syntax error near unexpected token `('
#echo $a / (( b-34 )) | bc -l
-bash: syntax error near unexpected token `('
```
Can someone give me a working correct syntax for getting floating point results with complicated arithmetic expresssions? | Just double-quote (`"`) the expression:
```
echo "$a / ( $b - 34 )" | bc -l
```
Then bash will expand the `$` variables and ignore everything else and `bc` will see an expression with parentheses:
```
$ a=22
$ b=7
$ echo "$a / ( $b - 34 )"
22 / ( 7 - 34 )
$ echo "$a / ( $b - 34 )" | bc -l
-.81481481481481481481
``` |
111122 | In Python, how do I turn this:
```
"(test1)(test2)"
```
into this:
```
["test1","test2"]
```
? | The 401 Unauthorized response is usually emitted as an `error` notification from the Angular `HttpClient`. So you'd need to use RxJS [`catchError`](https://rxjs.dev/api/operators/catchError) operator to catch the error and redirect. You could then emit [`NEVER`](https://rxjs.dev/api/index/const/NEVER) constant so that nothing emits after the redirect and keep the observable alive, or emit [`EMPTY`](https://rxjs.dev/api/index/const/EMPTY) constant to complete the observable.
Try the following
```js
import { throwError, NEVER } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
export class ApiService {
constructor(private http: HttpClient) { }
public get<T>(
path: string,
params: HttpParams = new HttpParams(),
headers: HttpHeaders = new HttpHeaders()
): Observable<T> {
return this.getBodyOfResponseOrRedirect(
this.http.get<T>(path, {headers, params, observe: 'response'}));
}
private getBodyOfResponseOrRedirect<T>(
responseObservable: Observable<HttpResponse<T>>
): Observable<T> {
return responseObservable.pipe(
catchError(error => {
if (!!error.status && error.status === 401) {
window.location.href = 'https://custom-url';
return NEVER; // <-- never emit after the redirect
}
return throwError(error); // <-- pass on the error if it isn't 401
}),
map(response => response.body)
);
}
}
``` |