qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
14,692 |
I found this sentence on the internet:
>
> Seems like society **leveled itself out** once again.
>
>
>
What does *level out* mean here? I have looked up OALD, and it defines *level out/off* as:
>
> level off/out
>
> 1 to stop rising or falling and remain horizontal.
>
> *The plane levelled off at 1500 feet.*
>
> *After the long hill, the road levelled out.*
>
> 2 to stay at a steady level of development or progress after a period of sharp rises or falls.
>
> *Sales have levelled off after a period of rapid growth.*
>
>
>
However, I'm not quite sure whether either of them fits the context.
|
2013/12/20
|
[
"https://ell.stackexchange.com/questions/14692",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/1473/"
] |
(To)Level out stands for work on an area to make it even, smooth and free of indents, dents or dings.
Figuratively, if some person or group levels out, it comes ahead of its shortcomings, no more ups and downs, and it can have a smooth riding future.
|
415,877 |
I followed some advice I found here for a replacement for Disk Inventory X
[OSX disk space shows 200GB as "other"](https://apple.stackexchange.com/questions/388549/osx-disk-space-shows-200gb-as-other#answer-388581)
I installed the DaisyDisk app and it worked very well, however now my machine is constantly overheating and mds\_stores is consuming 99% of the cpu.
DaisyDisk does not appear in the Applications folder.
How do I uninstall it? Does anyone know? They don't have any information on their website. I should have been more careful.
<https://daisydiskapp.com/>
|
2021/03/16
|
[
"https://apple.stackexchange.com/questions/415877",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/131099/"
] |
You may want to reinstall it and use "[AppCleaner](http://freemacsoft.net/appcleaner/)" to properly remove it and all of its remnants.
|
12,421,312 |
I am getting error when using load data to insert the query .
```
"load data infile '/home/bharathi/out.txt' into table Summary"
```
This file is there in the location . But mysql throws the below error .
**ERROR 29 (HY000): File '/home/bharathi/out.txt' not found (Errcode: 13)**
```
show variables like 'data%';
+---------------+-----------------+
| Variable_name | Value |
+---------------+-----------------+
| datadir | /var/lib/mysql/ |
+---------------+-----------------+
```
Data Dir is pointing to root permissioned folder . I can't change this variable because it's readonly .
How can I do the load data infile operation ?
I tried changing file permissions , load data local infile . It wont work .
|
2012/09/14
|
[
"https://Stackoverflow.com/questions/12421312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1449101/"
] |
As documented under [`LOAD DATA INFILE` Syntax](http://dev.mysql.com/doc/en/load-data.html):
>
> For security reasons, when reading text files located on the server, the files must either reside in the database directory or be readable by all. Also, to use [`LOAD DATA INFILE`](http://dev.mysql.com/doc/en/load-data.html) on server files, you must have the [`FILE`](http://dev.mysql.com/doc/en/privileges-provided.html#priv_file) privilege. See [Section 6.2.1, “Privileges Provided by MySQL”](http://dev.mysql.com/doc/en/privileges-provided.html). For non-`LOCAL` load operations, if the [`secure_file_priv`](http://dev.mysql.com/doc/en/server-system-variables.html#sysvar_secure_file_priv) system variable is set to a nonempty directory name, the file to be loaded must be located in that directory.
>
>
>
You should therefore either:
* Ensure that your MySQL user has the `FILE` privilege and, assuming that the `secure_file_priv` system variable is not set:
+ make the file readable by all; or
+ move the file into the database directory.
* Or else, use the `LOCAL` keyword to have the file read by your client and transmitted to the server. However, note that:
>
> `LOCAL` works only if your server and your client both have been configured to permit it. For example, if [*`mysqld`*](http://dev.mysql.com/doc/en/mysqld.html) was started with [`--local-infile=0`](http://dev.mysql.com/doc/en/server-system-variables.html#sysvar_local_infile), `LOCAL` does not work. See [Section 6.1.6, “Security Issues with `LOAD DATA LOCAL`”](http://dev.mysql.com/doc/en/load-data-local.html).
>
>
>
|
117,931 |
I can add custom fields to the user registration form, if I add the fields to the user profile: admin/config/people/accounts/fields
There is a checkbox "Show on user registraion" which is inactive:

The checkbox only gets active if I check "Mandatory field", but some of the fields must not be mandatory. Is that a bug? Is there a workaround (without using module 'Profil2') ?
I'm using Drupal Core 7.28
|
2014/06/11
|
[
"https://drupal.stackexchange.com/questions/117931",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/17039/"
] |
I have never encountered such problem before. But since you have such problem then I think the best way is to write a hook\_form\_alter. And set the required field that you don't want as mandatory to false.
```
function mymodule_form_alter(&$form, $form_state, $form_id){
switch ($form_id) {
case 'registration_form_id':
$form['field_name']['und'][0]['value']['#required'] = FALSE;
break;
}
}
```
Hope this helps.
|
73,248,935 |
```
public Void traverseQuickestRoute(){ // Void return-type from interface
findShortCutThroughWoods()
.map(WoodsShortCut::getTerrainDifficulty)
.ifPresent(this::walkThroughForestPath) // return in this case
if(isBikePresent()){
return cycleQuickestRoute()
}
....
}
```
Is there a way to exit the method at the `ifPresent`?
In case it is not possible, for other people with similar use-cases: I see two alternatives
```
Optional<MappedRoute> woodsShortCut = findShortCutThroughWoods();
if(woodsShortCut.isPresent()){
TerrainDifficulty terrainDifficulty = woodsShortCut.get().getTerrainDifficulty();
return walkThroughForrestPath(terrainDifficulty);
}
```
This feels more ugly than it needs to be and combines if/else with functional programming.
A chain of `orElseGet(...)` throughout the method does not look as nice, but is also a possibility.
|
2022/08/05
|
[
"https://Stackoverflow.com/questions/73248935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2321414/"
] |
`return` is a control statement. Neither lambdas (arrow notation), nor method refs (`WoodsShortcut::getTerrainDifficulty`) support the idea of control statements that move control to outside of themselves.
Thus, the answer is a rather trivial: Nope.
You have to think of the stream 'pipeline' as the thing you're working on. So, the question could be said differently: Can I instead change this code so that I can modify how this one pipeline operation works (everything starting at `findShortCut()` to the semicolon at the end of all the method invokes you do on the stream/optional), and then make this one pipeline operation the whole method.
Thus, the answer is: **`orElseGet` is probably it.**
Disappointing, perhaps. 'functional' does not strike me as the right answer here. The problem is, there are things for/if/while loops can do that 'functional' cannot do. So, if you are faced with a problem that is simpler to tackle using 'a thing that for/if/while is good at but functional is bad at', then it is probably a better plan to just use for/if/while then.
One of the core things lambdas can't do are about the transparencies. Lambdas are non-transparant in regards to these 3:
* Checked exception throwing. `try { list.forEach(x -> throw new IOException()); } catch (IOException e) {}` isn't legal even though your human brain can trivially tell it should be fine.
* (Mutable) local variables. `int x = 5; list.forEach(y -> x += y);` does not work. Often there are ways around this (`list.mapToInt(Integer::intValue).sum()` in this example), but not always.
* Control flow. `list.forEach(y -> {if (y < 0) return y;});` does not work.
So, keep in mind, you really have only 2 options:
* Continually retrain yourself to not think in terms of such control flow. You find `orElseGet` 'not as nice'. I concur, but if you really want to blanket apply functional to as many places as you can possibly apply it, the whole notion of control flow out of a lambda needs not be your go-to plan, and you definitely can't keep thinking 'this code is not particularly nice because it would be simpler if I could control flow out', you're going to be depressed all day programming in this style. The day you never even think about it anymore is the day you have succeeded in retraining yourself to 'think more functional', so to speak.
* Stop thinking that 'functional is always better'. Given that there are so many situations where their downsides are so significant, perhaps it is not a good idea to pre-suppose that the lambda/methodref based solution must somehow be superior. Apply what seems correct. That should often be "Actually just a plain old for loop is fine. Better than fine; it's the right, most elegant1 answer here".
[1] "This code is elegant" is, of course, a non-falsifiable statement. It's like saying "The Mona Lisa is a pretty painting". You can't make a logical argument to prove this and it is insanity to try. "This code is elegant" boils down to saying "*I* think it is prettier", it cannot boil down to an objective fact. That also means in team situations there's no point in debating such things. Either everybody gets to decide what 'elegant' is (hold a poll, maybe?), or you install a dictator that decrees what elegance is. If you want to fix that and have meaningful debate, the term 'elegant' needs to be defined in terms of objective, falsifiable statements. I would posit that things like:
* in face of expectable future change requests, this style is easier to modify
* A casual glance at code leaves a first impression. Whichever style has the property that this first impression is accurate - is better (in other words, code that confuses or misleads the casual glancer is bad). Said even more differently: Code that really needs comments to avoid confusion is worse than code that is self-evident.
* this code looks familiar to a wide array of java programmers
* this code consists of fewer AST nodes (the more accurate from of 'fewer lines = better')
* this code has simpler semantic hierarchy (i.e. fewer indents)
Those are the kinds of things that should *define* 'elegance'. Under almost all of those definitions, 'an `if` statement' is as good or better in this specific case!
|
17,429,280 |
I want to detect the edges on the serial data signal (din). I have written the following code in VHDL which is running successfully but the edges are detected with one clock period delay i.e change output is generated with one clk\_50mhz period delay at each edge. Could anyone please help me to detect edges without delay. Thank you.
```
process (clk_50mhz)
begin
if clk_50mhz'event and clk_50mhz = '1' then
if (rst = '0') then
shift_reg <= (others => '0');
else
shift_reg(1) <= shift_reg(0);
shift_reg(0) <= din;
end if;
end if;
end process;
process (clk_50mhz)
begin
if clk_50mhz'event and clk_50mhz = '1' then
if rst = '0' then
change <= '0' ;
elsif(clk_enable_2mhz = '1') then
change <= shift_reg(0) xor shift_reg(1);
end if ;
end if ;
end process ;
```
When I changed my code to following I am able to detect the edges
```
process (clk_50mhz)
begin
if clk_50mhz'event and clk_50mhz = '1' then
if (RST = '0') then
shift_reg <= (others=>'0');
else
shift_reg(1) <= shift_reg(0);
shift_reg(0) <= din;
end if;
end if;
end process;
change <= shift_reg(1) xor din;
```
|
2013/07/02
|
[
"https://Stackoverflow.com/questions/17429280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2463272/"
] |
Here you go
```
library ieee;
use ieee.std_logic_1164.all;
entity double_edge_detector is
port (
clk_50mhz : in std_logic;
rst : in std_logic;
din : in std_logic;
change : out std_logic
);
end double_edge_detector;
architecture bhv of double_edge_detector is
signal din_delayed1 :std_logic;
begin
process(clk_50mhz)
begin
if rising_edge(clk_50mhz) then
if rst = '1' then
din_delayed1 <= '0';
else
din_delayed1 <= din;
end if;
end if;
end process;
change <= (din_delayed1 xor din); --rising or falling edge (0 -> 1 xor 1 -> 0)
end bhv;
```
|
43,979,701 |
In preview all good, but when I compiling, there is no image. If problem in source, so why it is showing in preview window?


```
<Grid>
<!-- Grid 4x3 -->
<Grid.RowDefinitions>
<RowDefinition Height="1*"></RowDefinition>
<RowDefinition Height="0.5*"></RowDefinition>
<RowDefinition Height="0.5*"></RowDefinition>
<RowDefinition Height="0.7*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.2*"></ColumnDefinition>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="0.2*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<!-- Controls -->
<!-- Row №1-->
<Image Grid.Row="0" Grid.Column="1" Source="pack://siteoforigin:,,,/Resources/logo.png"></Image>
<!-- Row №2-3 -->
<StackPanel Grid.Row="1" Grid.Column="1" Grid.RowSpan="2">
<Label Content="Вы заходите как..."></Label>
<ComboBox>
<ComboBoxItem Content="Клиент"></ComboBoxItem>
<ComboBoxItem Content="Сотрудник"></ComboBoxItem>
</ComboBox>
<Label Content="ID"></Label>
<TextBox></TextBox>
<Label Content="Пароль"></Label>
<PasswordBox></PasswordBox>
</StackPanel>
<!-- Row №4 -->
</Grid>
```
|
2017/05/15
|
[
"https://Stackoverflow.com/questions/43979701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6677766/"
] |
Seems that the image you specified is not copied to the output directory. You can resolve the issue in two ways:
1) In the property grid set Build Action to "None" and Copy to Output Directory to "Copy always" (you need to do this because the siteoforigin URI seeks the resource in the binary file location)
2) Set the Build Action property to "Resource" and use the `pack://application` absolute URI or the relative URI (like this: `<Image Source="Resources/logo.png"/>` )
|
47,148,128 |
this problem is driving me nuts. I have a test server and a live server. The test server is showing unicode characters retrieved from an Azure sql database correctly. While the live server running identical code accessing the same data is not showing them correctly.
The data in the database is:
Hallo ich heiße Pokémon! Ich würde gerne mal mit einem anderen Kämpfe!
The test servers shows
Hallo ich heiße Pokémon! Ich würde etc...
The live server, which is an Azure web service shows
Hallo ich hei�e Pok�mon! Ich w�rde gerne mal mit einem anderen K�mpfe
Same PHP code, Same database, Same browser, same db connection string,
different web servers, different results.
I do know Azure is running PHP 5.6 and the test server is running PHP 5.3
They are using sqlsrv\_connect
The data field is type varchar.
I tried using "CharacterSet" => "UTF-8" in the connection but this made no difference to the Azure server and screwed up the result on the test server.
I am out of ideas and leads.
|
2017/11/07
|
[
"https://Stackoverflow.com/questions/47148128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1556436/"
] |
Edit: After searching stackoverflow, here is a solution you maybe looking for: [MySQL - How to search for exact word match using LIKE?](https://stackoverflow.com/questions/5743177/mysql-how-to-search-for-exact-word-match-using-like)
What‘s you‘r searchquery exactly?
```
SELECT * FROM songs WHERE singers RLIKE '^Gallagher';
```
|
11,650,228 |
So I have situation when I need skip current test from test method body.
Simplest way is to write something like this in test method.
```
if (something) return;
```
But I have a lot complicated tests and I need a way to skip test from methods which I invoke in current test method body.
Is it possible?
|
2012/07/25
|
[
"https://Stackoverflow.com/questions/11650228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545920/"
] |
You should not skip test this way. Better do one of following things:
* mark test as ignored via `[Ignore]` attribute
* throw `NotImplementedException` from your test
* write `Assert.Fail()` (otherwise you can forget to complete this test)
* remove this test
Also keep in mind, that your tests should not contain conditional logic. Instead you should create two tests - separate test for each code path (with name, which describes what conditions you are testing). So, instead of writing:
```
[TestMethod]
public void TestFooBar()
{
// Assert foo
if (!bar)
return;
// Assert bar
}
```
Write two tests:
```
[TestMethod]
public void TestFoo()
{
// set bar == false
// Assert foo
}
[Ignore] // you can ignore this test
[TestMethod]
public void TestBar()
{
// set bar == true
// Assert bar
}
```
|
19,273,719 |
I have a single Crystal Report that I am trying to run via a web site using a Report Viewer and also (using the same .rpt) via a background process that would generate the report straight to a stream or file using the export options.
I am not using a database, but have created an xml schema file and am generating an xml data file to load into the report based on unique user data.
When I created the report I made an ADO.NET(XML) connection to design it and pointed it to my schema file (all within VS 2012).
At run time I use a .net DataSet object and use the ReadXmlSchema and ReadXml methods to get my report data and then just set the datasource of my ReportDocument object.
This all worked great in my web application using Report Viewer. Here is the working code:
```
ReportDocument report = new ReportDocument();
report.Load(reportPath);
DataSet reportData = new DataSet();
reportData.ReadXmlSchema("MySchema.xml");
reportData.ReadXml("SampleData1.xml");
report.SetDataSource(reportData);
CrystalReportViewer1.ReportSource = report;
```
My issue/question is how to run this programmatically with no Report Viewer and have it generate a PDF? Essentially the same code as above minus the Report Viewer piece and adding one of the Export options. I have a long running background process and would like to attach this report as a PDF to an email I generate.
I am able to use the same methodology as the web version, but when I get to the SetDataSource line and try to set it to my DataSet I receive and error saying 'Unknown Database Connection Error...' having to do with not using the SetDatabaseLogon method.
I am trying to understand what Crystal Reports expects in the way of the SetDatabaseLogon method when I am not connecting to a database. If it assumes my original ADO.NET(XML) connection in the .RPT file is a legitimate database connection, then what are the logon parameters? It's just a file. There is no username, password etc.
Is there a better way to do a straight to PDF from an existing Crystal Report without Report Viewer? I have looked at various links but found nothing that does not involve some kind of connection string. If I must use SetDatabaseLogin, what values will work when using XML files only?
Thanks for any information or links!
Edit: In looking at the "Unknown Database Connector Error" (not Connection as I stated earlier) I see that it is actually looking at the .RPT in my Temp folder and not in my Remote location where I thought I was loading it from. Maybe this is the problem?
|
2013/10/09
|
[
"https://Stackoverflow.com/questions/19273719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2564788/"
] |
Have you tried something like this:
```
Report.ExportToDisk(ExportFormatType.PortableDocFormat, Server.MapPath("Foldername/Reportname.pdf"));
```
|
28,492,909 |
I'm putting together a site which has a protected section where users must be logged in to access. I've done this in Laravel 4 without too much incident. However, for the life of me I cannot figure out why I can't get it to work in Laravel 5(L5).
In L5 middleware was/were introduced. This changes the route file to:
```
Route::get('foo/bar', ['middleware'=>'auth','FooController@index']);
Route::get('foo/bar/{id}', ['middleware'=>'auth','FooController@show']);
```
The route works fine as long as the middleware is not included.
When the route is accessed with the middleware however the result is not so much fun.
>
> Whoops, looks like something went wrong.
>
>
> ReflectionException in Route.php line 150:
>
>
> Function () does not exist
>
>
>
Any insight, help, and/or assistance is very appreciated. I've done the Google circuit and couldn't find anything relevant to my current plight. Thanks in advance.
|
2015/02/13
|
[
"https://Stackoverflow.com/questions/28492909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3265547/"
] |
you forgot the `uses` key :
```
Route::get('foo/bar/{id}', ['middleware'=>'auth', 'uses'=>'FooController@show']);
```
|
40,313,389 |
I am attempting to extract IP Address from a MySQL database using REGEX ina a SELECT statement. When i run the Query in the MySQL console it returns the expected results:
```
SELECT * FROM database.table WHERE field3 REGEXP '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$';
```
When I run the same query through a python script it returns results that are not IP Addresses.
```
query = ("SELECT * FROM database.table WHERE field3 REGEXP '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$';")
```
Where am I going wrong?
|
2016/10/28
|
[
"https://Stackoverflow.com/questions/40313389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6744297/"
] |
To answer how to add the `avx` flag into compiler options.
In your case the f77 complier is being picked `gfortran:f77: ./distance.f` < That is the key line.
You could try specifying `--f77flags=-mavx`
|
33,806,541 |
I got this homework assignment, cant figure it out.
I need to ask the user how many town names he wants to enter. For example 5.
Then, he enters the 5 town names.
Afterwards, we need to find the average length of the names and show him the names which have less letters than the average length. Thanks for your shared time :)
My code so far:
```
static void Main(string[] args)
{
int n;
Console.WriteLine("How many town names would you like to enter:");
n = int.Parse(Console.ReadLine());
string[] TownNames = new string[n];
Console.Clear();
Console.WriteLine("Enter {0} town names:", n);
for (int i = 0; i < n; i++)
{
Console.Write("Enter number {0}: ", i + 1);
TownNames[i] = Convert.ToString(Console.ReadLine());
}
Console.ReadKey(true);
}
static void Average(double[] TownNames, int n)
{
}
```
|
2015/11/19
|
[
"https://Stackoverflow.com/questions/33806541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5581685/"
] |
You replace the value each time in the loop, so the output is only the result of the last iteration: 4\*4.
Not exactly what calculation you want to do that will give you 24, but maybe you want to add the result to the previous value of y, or multiple it?
|
2,252,383 |
Suppose $(x\_n)$ is an increasing sequence of real numbers and not bounded above. Is it true that all its subsequences are not bounded above?
I think the statement is not true. We can have an increasing sequence such that it has multiple limit points. For example, we can have a sequence $x\_n=n$, but 'chop' by adding more terms such that it has $10$ and $11$ as limit points. Then we have two subsequences which are bounded above.
Question: Is my thinking process above correct? If yes, how should we obtain a closed for such a sequence?
|
2017/04/26
|
[
"https://math.stackexchange.com/questions/2252383",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/54398/"
] |
no, an increasing sequence only has only limit point, which is either $\infty$ if the sequence is unbounded or $\sup\_n x\_n$ if the sequence if bounded.
If $x\_n$ is an increasing sequence and $x\_n=10$ for infinitely many $n$, then necessarily $x\_n=10$ for all $n$ sufficiently large.
|
2,029,257 |
By considering the set $\{1,2,3,4\}$, one can easily come up with an [example](https://en.wikipedia.org/wiki/Pairwise_independence) (attributed to S. Bernstein) of pairwise independent but not independent random variables.
Counld anybody give an example with [continuous random variables](https://en.wikipedia.org/wiki/Probability_distribution#Continuous_probability_distribution)?
|
2016/11/24
|
[
"https://math.stackexchange.com/questions/2029257",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] |
Let $x,y,z'$ be normally distributed, with $0$ mean. Define $$z=\begin{cases} z' & xyz'\ge 0\\ -z' & xyz'<0\end{cases}$$
The resulting $x,y,z$ will always satisfy $xyz\ge 0$, but be pairwise independent.
|
31,670 |
I have an 8 year old son who refuses to use the restroom. He does #1 in toilet but not #2. This has been going on for less than a year, I'd say about 8 months now. Before that, his potty routine was normal. Out of nowhere he started refusing to go. I've asked him if there's any reason to why he doesn't use the toilet and he responds with "I don't know, there's no reason"
He stays with his grandfather every weekend and he does it there as well. He doesn't do it at school at all, I guess he waits till he's at home where he's most "comfortable" because he doesn't want "kids to smell him".
What can I do to make him use the restroom like he used to? I'm tired of having to wash his underwear as often as I do and having talks with him about the need of toilets.
|
2017/09/08
|
[
"https://parenting.stackexchange.com/questions/31670",
"https://parenting.stackexchange.com",
"https://parenting.stackexchange.com/users/29589/"
] |
>
> What can I do to make him use the restroom like he used to?
>
>
>
My son went through something similar when he was young, and in my case it was just a battle of wills. I said to him you need to **poopy in the potty**. I would repeat this phrase over and over again. I would sit with him in the bathroom until he did use the bath room. ( Not for hours on end, but 10 min ever hour or so )
The other part of this is I had him hand wash the majority of the mess every single time, be it on just his underwear, or his clothes.
Once he started falling back in line, I provided rewards for doing the right thing, such as allowing him to watch his TV show, or an extra sweet.
Be patient he will come around.
**NOTE:** In writing this answer, I am assuming that **medical conditions** have been eliminated. Have your doctor examine him if this is a concern.
|
51,415,248 |
I got two dictionaries and both of them have same keys ,i am trying to access the second dictionary using the key as input of first dictionary like below
```
Players = {0: "Quit",
1: "Player 1",
2: "Player 2",
3: "Player 3",
4: "Player 4",
5: "Player 5"
}
exits = {0: {"Q": 0},
1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
2: {"N": 5, "Q": 0},
3: {"W": 1, "Q": 0},
4: {"N": 1, "W": 2, "Q": 0},
5: {"W": 2, "S": 1, "Q": 0} }
avabilablePlayer =",".join(list(Players.values()))
print (avabilablePlayer)
direction = input("Available Players are " + avabilablePlayer + " ").upper()
if direction in exits:
dict_key=exits.get(direction)
print(dict_key)
```
The above code is not returning the values from the second dictionary, how to fix this without using any methods and functions?
|
2018/07/19
|
[
"https://Stackoverflow.com/questions/51415248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9775079/"
] |
Use `font-size: 0;` to `ul` and `font-size: 15px;` to `li`
```css
ul {
display: block;
columns: 2;
font-size: 0;
}
li {
border-top: 1px solid black;
list-style: none;
font-size: 15px;
}
```
```html
<ul>
<li>TEST 1</li>
<li>TEST 2</li>
<li>TEST 3</li>
<li>TEST 4</li>
<li>TEST 5</li>
<li>TEST 6</li>
<li>TEST 7</li>
<li>TEST 8</li>
</ul>
```
|
18,331,189 |
I have form like this:
```
<%= simple_form_for @category do |f| %>
<%= f.input :name %>
<%= f.input :description %>
<%= f.input :parent_id, collection: @board.subtree, include_blank: false %>
<%= f.button :submit %>
<% end %>
```
`@category` is instance of `Board` so this `:submit` tries to run `create` action from `BoardsController`. Instead of it, I'd like to run `create` action from `CategoriesController`.
How can I do this?
|
2013/08/20
|
[
"https://Stackoverflow.com/questions/18331189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1654940/"
] |
Just add the `url` option.
```
<%= simple_form_for @category, url: category_path(@category) do |f| %>
```
|
34,990,495 |
Is there a way to use an event to call a function when the JSON.Parse() has parsed all the objects from a file?
|
2016/01/25
|
[
"https://Stackoverflow.com/questions/34990495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5685815/"
] |
`JSON.parse` is synchronous. it returns the object corresponding to the given JSON text.
More about it from [mozilla](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)
now a good way of doing JSON.parse is shown below (inside a try-catch)
```
try {
var data = JSON.parse(string);
//data is the object,
//convert to object is completed here. you can call a function here passing created object
}
catch (err) {
//mark this error ?
}
```
Now there are discussions, about why `JSON.parse` is not async, like the [ONE HERE](https://www.reddit.com/r/javascript/comments/2uc7gv/its_2015_why_the_hell_is_jsonparse_synchronous/)
|
157,005 |
I have this tree shape artwork and i want to trim hole (which are spotted with black color). I tried with all the trim options, Did not work.
How can i trim. Any other way or option
[File](https://drive.google.com/file/d/1qjEp-3dyvqJSyAC8ivlnk8bKEl6zmx6F/view?usp=sharing)
[](https://i.stack.imgur.com/kT6CK.jpg)
|
2022/05/04
|
[
"https://graphicdesign.stackexchange.com/questions/157005",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/173783/"
] |
Assuming the circles are on top of everything else...
* Select all the circles
* Choose `Object > Compound Path > Make` from the menu. This forces Illustrator to see the circles as one, singular object, rather than a collection of objects.
* Change the **Fill** of the circles to be either 100C100M100Y100K or 0R0G0B, depending upon the color mode you are working in. (Yes, 100% of all inks in CMYK - it's for a *mask* not printed objects.)
* Select all the artwork (trees and circles)
* On the **Transparency Panel** (`Window > Transparency`) click the `Make Mask` button
* **Untick** the `Clip` button on the **Transparency Panel**
This will give you an **Opacity Mask** which will "punch" out the holes in the underlying artwork.
[](https://i.stack.imgur.com/yqLwC.png)
More on opacity masks...
* [Opacity Mask With Multiple Images (Illustrator CS5)](https://graphicdesign.stackexchange.com/questions/6436/opacity-mask-with-multiple-images-illustrator-cs5)
* [Using the Opacity Mask on Illustrator](https://graphicdesign.stackexchange.com/questions/126822/using-the-opacity-mask-on-illustrator)
* [Why doesn't my opacity mask fully hide my object?](https://graphicdesign.stackexchange.com/questions/64083/why-doesnt-my-opacity-mask-fully-hide-my-object)
* [Illustrator: Opacity Mask is not moving/resizing along with object it masks, if the masked object is a Mesh object](https://graphicdesign.stackexchange.com/questions/137123/illustrator-opacity-mask-is-not-moving-resizing-along-with-object-it-masks-if)
* [How to create a gradient opacity mask in Illustrator](https://graphicdesign.stackexchange.com/questions/71406/how-to-create-a-gradient-opacity-mask-in-illustrator)
* [Feather Clipping Mask in Adobe Illustrator](https://graphicdesign.stackexchange.com/questions/153943/feather-clipping-mask-in-adobe-illustrator)
* [illustrator cs6 when exporting to PDF and print - the black area of masks shown in a low opacity also in PDF preview](https://graphicdesign.stackexchange.com/questions/54367/illustrator-cs6-when-exporting-to-pdf-and-print-the-black-area-of-masks-shown)
|
91,269 |
I want to test a video IP core that reads a block of memory and writes to it again. The IP core is using the VFBC. My idea for testing was to write a core that looks like the VFBC, but just uses a simple 32Meg RAM as back-end.
It is allocated like this:
```
memory_size : NATURAL := ((2 * 2048) * 2048)
type memory_array is array (0 to (memory_size - 1)) of std_logic_vector(31 downto 0);
signal memory : memory_array;
```
ISim is crashing claiming that it needs more than 2 gig of ram, and questasim is allocating 12gig in the process of compilation for simulation.
**Note: I don't want to synthesize this. It is for simulation only!**
So the question is: how can I simulate such an RAM efficiently in VHDL?
|
2013/11/20
|
[
"https://electronics.stackexchange.com/questions/91269",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/25263/"
] |
If the memory you are simulating can fit into the ram of the workstation then using a fixed-size storage is the easiest to use. But as you have seen, signals are much more expensive compared to variables. This difference is related to the *discrete event simulation* model that VHDL is based on. A signal assignment schedules a transaction at a given point in time, but a variable assignment is strictly a sequential statement that execute in zero simulation time. The difference can be seen in the memory usage of the two different models. The results are obtained by running the example code below in Riviera PRO.
Memory allocation when using a signal for data storage:
```
Allocation: Simulator allocated 891567 kB (elbread=1023 elab2=890389 kernel=154 sdf=0)
```
Memory allocation when using a variable for data storage:
```
Allocation: Simulator allocated 39599 kB (elbread=1023 elab2=38421 kernel=154 sdf=0)
```
Example code
------------
```
library ieee;
use ieee.std_logic_1164.all;
use std.env;
entity memtest is
end;
architecture sim of memtest is
signal clk : std_logic := '0';
signal we : std_logic;
signal writedata, q : integer;
signal addr : natural;
-- Uncomment or comment to switch between variable or signal for memory storage.
--signal mem : integer_vector(0 to 2 * 2048**2-1);
begin
clk <= not clk after 10 ns;
-----------------------------------
stimulus :
-----------------------------------
process
begin
for n in 0 to 100 loop
wait until falling_edge(clk);
we <= '1' ;
writedata <= n;
addr <= n;
end loop;
env.stop;
end process;
-----------------------------------
memory :
-----------------------------------
process ( clk )
-- Uncomment or comment to switch between variable or signal for memory storage.
variable mem : integer_vector(0 to 2 * 2048**2-1);
begin
if rising_edge(clk) then
q <= mem(addr);
if we = '1' then
-- Remember to modify assignment operator when switching data storage.
mem(addr) := writedata;
end if;
end if;
end process;
end;
```
|
494,506 |
Are there any design patterns/methods/ways to remove nested if then else conditions/switch statements?
I remember coming across some methods used by the Google folks listed in a Google code blog post. Can’t seem to find it now though
|
2009/01/30
|
[
"https://Stackoverflow.com/questions/494506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22039/"
] |
You want to use a refactoring that replaces a conditional using a polymorphic class. For [example](http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html).
Or here's another [example](http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism)
Essentially the ideal is very simple you create an object heirarchy, and move the various behaviors into an overriden method. You will still need a method to create the right class but this can be done using a factory pattern.
Edit
====
Let me add that this is not a perfect solution in every case. As (I forgot your name sorry) pointed in my comments, some times this can be a pain especially if you have to create an object model just to do this. This refactoring excells if you have this:
```
function doWork(object x)
{
if (x is a type of Apple)
{
x.Eat();
} else if (x is a type of Orange)
{
x.Peel();
x.Eat();
}
}
```
Here you can refactor the switch into some new method that each fruit will handle.
Edit
====
As someone pointed out how do you create the right type to go into doWork, there are more ways to solve this problem then I could probally list so some basic ways. The first and most straight forward (and yes goes against the grain of this question) is a switch:
```
class FruitFactory
{
Fruit GetMeMoreFruit(typeOfFruit)
{
switch (typeOfFruit)
...
...
}
}
```
The nice thing about this approach is it's easy to write, and is usually the first method I use. While you still have a switch statement its isolated to one area of code and is very basic all it returns is a n object. If you only have a couple of objects and they;re not changing this works very well.
Other more compelx patterns you can look into is an [Abstract Factory](http://en.wikipedia.org/wiki/Abstract_factory_pattern). You could also dynamically create the Fruit if your platform supports it. You could also use something like the [Provider Pattern](http://en.wikipedia.org/wiki/Provider_pattern). Which essentially to me means you configure your object and then you have a factory which based on the configuration and a key you give the factory creates the right class dynamically.
|
38,116,133 |
I have a nodejs + expressjs app that needs to be converted to an android. A quick solution that we are thinking of is to use phonegap. The issue I am stuck with is all my files under view folder of the web app are ejs files.
When I try to upload my app to phonegap it says no index.html found in my .zip folder.
My question here is:
1. Should I separate the front end files from the node app? using html and pure js?
2. Is there a way I can render ejs files on to html files (something like import) so that I can convert existing web app into an android app?
3. Is there an option in phonegap to use ejs files instead of html files?
I am using <https://build.phonegap.com/> for converting the app. Someone please help as I am stuck with this for a long time.
|
2016/06/30
|
[
"https://Stackoverflow.com/questions/38116133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3467302/"
] |
As per our discussion discussion , below solution comes:-
1.Need to install `CURL` on your system by the command :-
```
sudo apt-get install php7.0-curl
```
2.Regarding second error i got this link:- [utf8\_(en|de)code removed from php7?](https://stackoverflow.com/questions/35701730/utf8-endecode-removed-from-php7)
It states that `utf8_encode/decode` is function related to `php xml extension` which you have to install your system by below command:-
```
sudo apt-get install php7.0-xml
```
***Important Note:-*** after install of these library packages ***restart*** your ***server*** so that ***changes will reflect***. Thanks.
|
59,444,161 |
I am getting really frustrated already. I have tried so many variations and searched for an answer in all existing stackoverflow questions, but it didn't help.
All I need is to get **ALL the text** (**without the @class name 'menu' or without the @id name 'menu'**)
I have tried already these commands:
```
//*[not(descendant-or-self::*[(contains(@id, 'menu')) or (contains(@class, 'menu'))])]/text()[normalize-space()]
```
But whatever I try, I always get back the **all the text even with the elements that I excluded**.
Ps: I am using Scrapy which uses XPATH 1.0
```html
<body>
<div id="top">
<div class="topHeader">
<div class="topHeaderContent">
<a class="headerLogo" href="/Site/Home.de.html"></a>
<a class="headerText" href="/Site/Home.de.html"></a>
<div id="menuSwitch"></div>
</div>
</div>
<div class="topContent">
<div id="menuWrapper">
<nav>
<ul class="" id="menu"><li class="firstChild"><a class="topItem" href="/Site/Home.de.html">Home</a> </li>
<li class="hasChild"><span class="topItem">Produkte</span><ul class=" menuItems"><li class=""><a href="/Site/Managed_Services.de.html">Managed Services</a> </li>
<li class=""><a href="/Site/DMB/Video.de.html">VideoServices</a> </li>
<li class=""><a href="/Site/DMB/Apps.de.html">Mobile Publishing</a> </li>
<li class=""><a href="/Site/Broadcasting.de.html">Broadcasting</a> </li>
<li class=""><a href="/Site/Content_Management.de.html">Content Management</a> </li>
</ul>
</li>
<li class="hasChild"><span class="topItem">Digital Media Base</span><ul class=" menuItems"><li class=""><a href="/Site.de.html">About DMB</a> </li>
<li class=""><a href="/Site/DMB/Quellen.de.html">Quellen</a> </li>
<li class=""><a href="/Site/DMB/Video.de.html">Video</a> </li>
<li class=""><a href="/Site/DMB/Apps.de.html">Apps</a> </li>
<li class=""><a href="/Site/DMB/Web.de.html">Web</a> </li>
<li class=""><a href="/Site/DMB/Archiv.de.html">Archiv</a> </li>
<li class=""><a href="/Site/DMB/Social_Media.de.html">Social Media</a> </li>
<li class=""><a href="/Site/DMB/statistik.de.html">Statistik</a> </li>
<li class=""><a href="/Site/DMB/Payment.de.html">Payment</a> </li>
</ul>
</li>
<li class="activeMenu "><a class="topItem" href="/Site/Karriere.de.html">Karriere</a> </li>
<li class="hasChild"><span class="topItem">Fake-IT</span><ul class=" menuItems"><li class=""><a href="/Site/About.de.html">About</a> </li>
<li class=""><a href="/Site/Management.de.html">Management</a> </li>
<li class=""><a href="/Site/Mission_Statement.de.html">Mission Statement</a> </li>
<li class=""><a href="/Site/Pressemeldungen.de.html">Pressemeldungen</a> </li>
<li class=""><a href="/Site/Referenzen.de.html">Kunden</a> </li>
</ul>
</li>
</ul>
</nav>
<div class="topSearch">
<div class="topSearch">
<form action="/Site/Suchergebnis.html" method="get">
<form action="/Site/Suchergebnis.html" method="get">
<input class="searchText" onblur="processSearch(this, "Suchbegriff", "blur")" onfocus="processSearch(this,"Suchbegriff")" type="text" value="Suchbegriff" name="searchTerm" id="searchTerm" />
<input class="searchSubmit" id="js_searchSubmit" type="submit" name="yt0" />
<div class="stopFloat">
</div>
</form>
</div>
</div>
</div>
</div>
<p> I want to have this text here! </p>
.
.
More elements
.
.
</div>
<p> I want to have this text here! </p>
.
.
More elements
.
.
</body>
```
**I always get this back:**
```
['Home',
'Produkte',
'Managed Services',
'VideoServices',
'Mobile Publishing',
'Broadcasting',
'Content Management',
'Digital Media Base',
'About DMB',
'Quellen',
'Video',
'Apps',
'Web',
'Archiv',
'Social Media',
'Statistik',
'Payment',
'Karriere',
'Fake-IT',
'About',
'Management',
'Mission Statement',
'Pressemeldungen',
'Kunden',
' I want to have this text here! ',
' I want to have this text here! ']
```
**But I need it like that:**
```
[' I want to have this text here! ',
' I want to have this text here! ']
```
|
2019/12/22
|
[
"https://Stackoverflow.com/questions/59444161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7513730/"
] |
This very convoluted xpath 1.0 expression works on your sample html. It would be somewhat simpler in xpath 2.0 and above. But try it on your actual code:
```
//*[not(descendant-or-self::*[contains(@class,'menu')])]
[not(descendant-or-self::*[contains(@id,'menu')])]
[not(ancestor-or-self::*[contains(@class,'menu')])]
[not(ancestor-or-self::*[contains(@id,'menu')])]//text()
```
|
60,140,614 |
So I have a wordlist containing 3 words:
```
Apple
Christmas Tree
Shopping Bag
```
And I know only certain characters in the word and the length of the word, for instance:
>
> *???i???as ?r??*
>
>
>
where the **?** means it's an unknown character and I want to type it into the console and get an output of ALL the words in the word list containing these characters in these places and with this amount of characters.
Is there any way I can achieve this? I want my program to function in the same way *<https://onelook.com/>* works.
|
2020/02/09
|
[
"https://Stackoverflow.com/questions/60140614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10123677/"
] |
You can turn your expression into a regex and try matching with that:
```
import re
words = [
'Apple',
'Christmas Tree',
'Shopping Bag'
]
match = '???i???as ?r??'
regex = '^' + match.replace('?', '.') + '$' # turn your expression into a proper regex
for word in words: # go through each word
if re.match(regex, word): # does the word match the regex?
print(word)
```
Output:
```
Christmas Tree
```
|
54,828,044 |
I'm trying to reference an object that I'm matching for.
```
import re
list = ["abc","b","c"]
if any(re.search(r"a",i) for i in list):
print("yes")
print(i)
```
This works, just not the last `print` command.
Is there any way to do what I'm trying do to here?
|
2019/02/22
|
[
"https://Stackoverflow.com/questions/54828044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9599075/"
] |
This solution will scale worse for *large arrays*, for such cases the other proposed answers will perform better.
---
Here's one way taking advantage of [`broadcasting`](https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html):
```
(coo[:,None] == targets).all(2).any(1)
# array([False, True, True, False])
```
---
**Details**
Check for every row in `coo` whether or not it matches another in `target` by direct comparisson having added a first axis to `coo` so it becomes broadcastable against `targets`:
```
(coo[:,None] == targets)
array([[[False, False],
[ True, False]],
[[False, False],
[ True, True]],
[[ True, True],
[False, False]],
[[False, False],
[False, True]]])
```
Then check which `ndarrays` along the second axis have [`all`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html) values to `True`:
```
(coo[:,None] == targets).all(2)
array([[False, False],
[False, True],
[ True, False],
[False, False]])
```
And finally use [`any`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.any.html) to check which rows have at least one `True`.
|
1,393,216 |
I have an strange problem.
This is Microsoft Office 365 under Windows 10 and I don't remember when, but every time I start the computer, Excel is opened with a blank workbook.
I looked at startup tab in task manager and it is not there.. I also saw in Settings -> Applications -> Startup and it is not there two.
Do you have an advice to avoid this?
Thanks
Jaime
---
Well I did just as you said to do unfortunately though now I **can't get past the windows log in screen because it disabled my fingerprint reader and my pin code**.
*Can you tell me how to set it back to a normal boot up so that I can log back into my computer please.*
|
2019/01/11
|
[
"https://superuser.com/questions/1393216",
"https://superuser.com",
"https://superuser.com/users/524721/"
] |
It turns out that this may be caused by a so-called feature of Microsoft.
Short answer:
Windows Settings->Accounts->Sign-In Options->Privacy->Off
Longer answer:
<https://answers.microsoft.com/en-us/msoffice/forum/all/microsoft-word-and-excel-2016-automatically-opens/8d5869df-0212-4f04-9fac-c7e99256a005>
|
42,909,258 |
In my TypeScript code I have 2 classes `ClassA` and `ClassB`:
```
export class ClassA {
name: string;
classB: ClassB;
getName(): string {
return this.name;
}
}
export class ClassB {
name: string;
getName(): string {
return this.name;
}
}
```
I try to parse a Json into a `ClassA` instance like this:
```
let classA: ClassA = Object.assign(new ClassA(), JSON.parse('{"name":"classA", "classB": {"name":"classB"}}'));
```
But only `ClassA` is instanciated, inside classB attribute is not.
I have the following result when I log objects:
```
console.log(classA); // ClassA {name: "classA", classB: Object}
console.log(classA.getName()); // classA
console.log(classA.classB); // Object {name: "classB"}
console.log(classA.classB.getName()); // EXCEPTION: classA.classB.getName is not a function
```
Is that possible to deeply parse a Json?
|
2017/03/20
|
[
"https://Stackoverflow.com/questions/42909258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4205751/"
] |
You can use `ismember` + indexing to do your task:
```
[idx1,idx2] = ismember(A(:,1:end-1), B(:,1:end-1), 'rows');
idx3 = ~ismember(B(:,1:end-1), A(:,1:end-1), 'rows');
C(idx1,:) = [A(idx1,:) B(idx2(idx1),end)];
C(~idx1,:) = [A(~idx1,:) zeros(sum(~idx1),1)];
C=[C;B(idx3,1:end-1) zeros(sum(idx3),1) B(idx3,end)];
```
|
58,140,603 |
How can i make single select statement that combine both Select statements on the basis of only common 'PO' and 'Style Number' column


|
2019/09/27
|
[
"https://Stackoverflow.com/questions/58140603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11571211/"
] |
[ASP.NET Core 3.0 not currently available for Azure App Service.](https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio#aspnet-core-30-not-currently-available-for-azure-app-service) [Microsoft Docs]
The [preview versions of .NET Core 3.0](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/azure-apps/index?view=aspnetcore-3.0&tabs=visual-studio#deploy-aspnet-core-preview-release-to-azure-app-service) [Microsoft Docs] are available on the Azure service.
|
22,098,456 |
I have in my MainPage() the following line of code:
```
string str = tbx1.Text;
```
Then I have a slider that changes this TextBox:
```
private void Slider_ValueChanged_1(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Slider slider1 = sender as Slider;
tbx1.Text = slider1.Value.ToString();
}
```
When I run the app the default value of `tbx1` is read in, and it can be changed with the slider. But how do I read in the new value of `tbx1` into `str`? It seems that only the default value is kept in `str`.
|
2014/02/28
|
[
"https://Stackoverflow.com/questions/22098456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1189952/"
] |
If string is accessable you can do the following
```
private void Slider_ValueChanged_1(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Slider slider1 = sender as Slider;
tbx1.Text = slider1.Value.ToString();
str = slider1.Value.ToString();
}
```
|
1,921,621 |
I have this problem for a long time, and can't find a solution.
I guess this might be something everybodys faced using Sphinx, but I cnanot get any
usefull information.
I have one index, and a delta.
I queried in a php module both indexes, and then show the results.
For each ID in the result, I create an object for the model, and dsiplay main data for
that model.
I delete one document from the database, phisically.
When I query the index, the ID for this deleted document is still there (in the sphinx
result set).
Maybe I can detect this by code, and avoid showing it, but the result set sphinx gaves me
as result is wrong. xxx total\_found, when really is xxx-1.
For example, Sphinx gaves me the first 20 results, but one of this 20 results doesn't
exists anymore, so I have to show only 19 results.
I re-index the main index once per day, and the delta index, each 5 minutes.
Is there a solution for this??
Thanks in advance!!
|
2009/12/17
|
[
"https://Stackoverflow.com/questions/1921621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170915/"
] |
What I've done in my Ruby Sphinx adapter, Thinking Sphinx, is to track when records are deleted, and update a boolean attribute for the records in the main index (I call it `sphinx_deleted`). Then, whenever I search, I filter on values where `sphinx_deleted` is 0. In the sql\_query configuration, I have the explicit attribute as follows:
```
SELECT fields, more_fields, 0 as sphinx_deleted FROM table
```
And of course there's the attribute definition as well.
```
sql_attr_bool = sphinx_deleted
```
Keep in mind that these updates to attributes (using the Sphinx API) are only stored in memory - the underlying index files aren't changed, so if you restart Sphinx, you'll lose this knowledge, unless you do a full index as well.
This is a bit of work, but it will ensure your result count and pagination will work neatly.
|
54,145,150 |
I am trying to automate a pretty trivial scenario where I have to get the text inside multiple `li` child elements of a `ul` elements and compare it against a given array. I am using Protractor with Cucumber JS and using `async/await` to manage promises.
My scenario HTML looks something like this
```
<div class="some-class">
<ul class="some-ul-class">
<li>
<span>Heading1: </span>
<span class="some-span-class> Value of Heading 1</span>
</li>
<li>
<span>Heading2: </span>
<span class="some-span-class> Value of Heading 2</span>
</li>
<li>
<span>Heading3: </span>
<span class="some-span-class> Value of Heading 3</span>
</li>
<li>
<span>Heading4: </span>
<span class="some-span-class> Value of Heading 4</span>
</li>
<li>
<span>Heading5: </span>
<span class="some-span-class> Value of Heading 5</span>
</li>
```
I need to get the values of the first span element i.e the `Heading1`, `Heading2` texts. I saw a lot of approaches in SO, but none of them have resulted in a solution. Most of the solutions do not have `async/await` implemented and if I try them, the code doesn't do what it is intended to do.
Examples I've referred : [Protractor Tests get Values of Table entries](https://stackoverflow.com/questions/34135713/protractor-tests-get-values-of-table-entries)
[Protractor : Read Table contents](https://stackoverflow.com/questions/29501976/protractor-read-table-contents)
If I try using the `map` function inside the `async` block, but that resulted in a `ECONNREFUSED` error, and hence has been suggested not to do so [here](https://github.com/angular/protractor/issues/4706).
Would appreciate if someone can guide me towards a solution on this one.
|
2019/01/11
|
[
"https://Stackoverflow.com/questions/54145150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1728790/"
] |
```js
(function ($) {
$.fn.formNavigation = function () {
$(this).each(function () {
// Events triggered on keydown (repeatable when holding the key)
$(this).find('input').on('keydown', function(e) {
// Vertical navigation using tab as OP wanted
if (e.which === 13 && !e.shiftKey) {
// navigate forward
if ($(this).closest('tr').next().find('input').length>0) {
// when there is another row below
e.preventDefault();
$(this).closest('tr').next().children().eq($(this).closest('td').index()).find('input').focus();
} else if ($(this).closest('tbody').find('tr:first').children().eq($(this).closest('td').index()+1).find('input').length>0) {
// when last row reached
e.preventDefault();
$(this).closest('tbody').find('tr:first').children().eq($(this).closest('td').index()+1).find('input').focus();
}
} else if (e.which === 13 && e.shiftKey) {
// navigate backward
if ($(this).closest('tr').prev().find('input').length>0) {
// when there is another row above
e.preventDefault();
$(this).closest('tr').prev().children().eq($(this).closest('td').index()).find('input').focus();
} else if ($(this).closest('tbody').find('tr:last').children().eq($(this).closest('td').index()-1).find('input').length>0) {
// when first row reached
e.preventDefault();
$(this).closest('tbody').find('tr:last').children().eq($(this).closest('td').index()-1).find('input').focus();
}
}
});
});
};
})(jQuery);
// usage
$('.gridexample').formNavigation();
```
```html
<!DOCTYPE html>
<html>
<body>
<table class="gridexample">
<tbody>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
</tbody>
<table>
<!-- jQuery needed for this solution -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
</body>
</html>
```
|
19,680 |
I mean through out the whole show cars are depicted almost exactly the same as cars from our time, except for the lack of wheels. You would think that people 1000 years more advanced than us would be able to come up with a new design.
|
2012/06/29
|
[
"https://scifi.stackexchange.com/questions/19680",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/7446/"
] |
I say it's nostalgia and marketing...As evidence for this I reference the existence of New New York, Mom's Friendly Robot Company ads and just human nature in general. For every viewpoint, you can use nostalgia to sell it! That, I believe, is the simple, unadorned reason that cars look the same in the year 3000.
|
926,116 |
I have a PC with one physical LAN adapter connecting to a VPN server. Is there a way i can setup a (virtual) gateway interface on that same LAN adapter in a way so the other devices on my network can use that as gateway and run their traffic through that and the VPN connection?
Most of my ifconfig:
```
enp0s21f5 Link encap:Ethernet HWaddr 4c:cc:6a:d5:94:96
inet addr:192.168.1.120 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::76e3:9399:187d:fdad/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
tun0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
inet addr:10.11.0.2 P-t-P:10.11.0.2 Mask:255.255.0.0
inet6 addr: fdda:d0d0:cafe:1197::1000/64 Scope:Global
inet6 addr: fe80::c9b:2e1b:882:1637/64 Scope:Link
UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1500 Metric:1
virbr0 Link encap:Ethernet HWaddr 00:00:00:00:00:00
inet addr:192.168.122.1 Bcast:192.168.122.255 Mask:255.255.255.0
UP BROADCAST MULTICAST MTU:1500 Metric:1
```
And here routing info:
```
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 10.11.0.1 0.0.0.0 UG 50 0 0 tun0
0.0.0.0 192.168.1.1 0.0.0.0 UG 100 0 0 enp0s21f5
10.11.0.0 0.0.0.0 255.255.0.0 U 50 0 0 tun0
89.238.176.34 192.168.1.1 255.255.255.255 UGH 100 0 0 enp0s21f5
169.254.0.0 0.0.0.0 255.255.0.0 U 1000 0 0 enp0s21f5
192.168.1.0 0.0.0.0 255.255.255.0 U 100 0 0 enp0s21f5
192.168.122.0 0.0.0.0 255.255.255.0 U 0 0 0 virbr0
```
|
2017/06/16
|
[
"https://askubuntu.com/questions/926116",
"https://askubuntu.com",
"https://askubuntu.com/users/701084/"
] |
Solution with `wifi adapter` and `hostapd` software:
`sudo apt-get install hostapd -y`
Configure `hostapd`
```
interface=wlan0
ssid=Your_WLAN
hw_mode=g # can be b/g/n
wpa=2
wpa_passphrase=PASS
wpa_key_mgmt=WPA-PSK WPA-EAP WPA-PSK-SHA256 WPA-EAP-SHA256
```
Edit `/etc/network/interfaces`
```
auto wlan0
iface wlan0 inet static
hostapd /etc/hostapd/hostapd.conf
address 192.168.0.1
netmask 255.255.255.0
```
Because your PC is router you need to enable forwarding to interfaces
* 1st way `echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf && sysctl
-p` # persistent mode
* 2nd - `echo 1 > /proc/sys/net/ip/ipv4/ip_forward`
To enable it on the boot and start it:
systemctl enable hostapd && systemctl start hostapd
Install `dnsmasq` as it will be both your dns and dhcp server.
`sudo apt install dnsmasq`
edit it's conf file: vi `/etc/dnsmasq.conf`
```
interface=lo,wlan0
no-dhcp-interface=lo
dhcp-range=192.168.0.2,192.168.0.254,255.255.255.0,12h
```
Iptables:
```
iptables -t nat -A POSTROUTING -o tun+ -j MASQUERADE
iptables -A FORWARD -i wlan+ -o tun+ -j ACCEPT
iptables -A FORWARD -o tun+ -j ACCEPT
iptables -A FORWARD -i tun+ -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i tun+ -j ACCEPT
```
Let me know if it works for you.
|
32,517,452 |
Can someone help me? I would like to do something like this on a textarea to set the maxlength attribute:
```
<!DOCTYPE html>
<html>
<head>
<style>
.democlass {
color: red;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<p>Click the button to create a "class" attribute with the value "democlass" and insert it to the H1 element above.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var h1 = document.getElementsByTagName("H1")[0];
var att = document.createAttribute("class");
att.value = "democlass";
h1.setAttributeNode(att);
}
</script>
</body>
</html>
```
My code is:
```
<!DOCTYPE html>
<html>
<head>
<style>
</head>
<body>
<textarea>Hello World</textarea>
<button onclick="myFunction()">change max length</button>
<script>
function myFunction() {
var text = document.getElementsByTagName("textarea");
var att = document.createAttribute("maxlength");
att.value = "100";
text.setAttributeNode(att);
}
</script>
</body>
</html>
```
And if I run the script by clicking the button the console says:
>
> Uncaught TypeError: h1.setAttribute is not a function.
>
>
>
Ps: i'm new at stackoverflow :)
|
2015/09/11
|
[
"https://Stackoverflow.com/questions/32517452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324123/"
] |
You have some errors in your code. Check out this simplified one:
[jsFiddle](http://jsfiddle.net/kmsdev/cmkhosx6/)
```
<h1>Hello World</h1>
<textarea rows="10" cols="40"></textarea><br />
<button onclick="myFunction()">change max length</button>
<script>
function myFunction() {
var text = document.getElementsByTagName("textarea")[0];
text.setAttribute("maxlength", 100);
}
</script>
```
|
47,318,912 |
I am being passed inconsistent data. The problem is the individual rows of `$data_array` are not consistently in the same sequence but each has a reliable "text:" preceding the value.
Each row contains about 120 elements of data. I only need 24 of those elements.
It's also possible one of the elements I need could be missing, such as "cost".
(I'm using php version 5.4)
-- Task:
Using $order\_array, create a new $data\_array\_new by reordering the data in each "row" into the same sequence as $order\_array.
If an elements is missing from a row insert "NA".
Once the elements are in the correct sequence the "text" is no longer required.
```
$order_array = array("price", "cost", "vol", "eps")
$data_array = Array (
$one = Array ("cost":43.40, "vol":44000, "eps":1.27, "price":65.00),
$two = Array ("eps":5.14, "price":33.14, "vol":657000),
$thr = Array ("vol":650000, "cost":66.67, "eps":1.33, "price":44.31),
);
```
The resulting ouput should appear with the data in this order: ("price", "cost", "vol", "eps")
```
$data_array_new = Array (
$one = Array (65.00,43.40,44000,1.27),
$two = Array (33.14,"NA",657000,5.14),
$thr = Array (44.31,66.67,650000,1.33),
);
```
|
2017/11/15
|
[
"https://Stackoverflow.com/questions/47318912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7174910/"
] |
Of course you can. Just create an interface for the Fragment, let's say `FragmentCallback`, with your desired callback method, `onButtonClick()` for instance. In the `onAttached()` of your Fragment, cast the Activity to your new interface and store it in a variable `private FragmentCallback callback;`. Each Activity using this Fragment must implement this callback interface. Then call the callbacks `onButtonClick()` method in your Fragments `onButtonClick()` method. That's it - a very common pattern.
|
22,720,603 |
I'm using `ng-repeat` to create an index of records within a Rails view, on this index I'm trying to implement a button to update a particular record. The problem is I need to pass the correct id through to the Rails controller. I'm getting an error when I attempt to pass the record id through with `'{{swim_record.id}}!'` , using string interpolation via Angular.
```
<tbody>
<tr ng-repeat='swim_record in SwimRecords | orderBy:predicate.value:reverse |
filter:search'>
<td>
<a ng-href='/swim_records/{{swim_record.id}}'>
{{swim_record.last_name}}
</a>
</td>
<td>{{swim_record.first_name}}</td>
<td class = 'hidden-xs'>{{swim_record.check_in | date:'MM/dd/yyyy @ h:mma'}}</td>
<th class = 'hidden-xs'>{{swim_record.lmsc}}</td>
<td>
<%= bootstrap_form_for Swimmer.find_by_id("{{swim_record.id }}!".to_i) do |f| %>
<%= f.hidden_field :last_name, value: "Hat" %>
<%= f.submit 'Check Out', class: "btn btn-danger" %>
<% end %>
</td>
</tr>
</tbody>
```
Any suggestions would be very much appreciated!
|
2014/03/28
|
[
"https://Stackoverflow.com/questions/22720603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3395126/"
] |
>
> Why is my function returning before the X,Y variables are set?
>
>
>
[Because JavaScript I/O is asynchronous](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call).
If you want to wait for two promises - you need to hook on the promise's completion. Luckily, promises make this super simple for you with `Promise.all` and `Promise.spread`.
```
Promise.all(getX(rows[0].id,con,mysql),getY(rows[0].id,con,mysql)).spread(function(x,y){
console.log(x,y);//should work;
});
```
|
41,185,122 |
I am making a complex algorithm in C# in which one step is to compare 2 very large lists of ranges and finding out the overlapping region. I have tried a lot of ways to find them, but m not sure if I am covering all possibilities. Also my algo on this step is taking too long with huge lists.
**Example:**
**range 1 = 1-400**
**range 2 = 200-600**
So when I want to check overlap between these two ranges I should get the answer = 200.
Because total 200 numbers are overlapping between these two ranges. So this is how I want the answer, I want the exact number of integers that are overlapping between two ranges.
**Example of Lists:**
List1 : 1-400, 401-800, 801-1200 and so on...
List2 : 10240-10276, 10420 10456, 11646-11682 and so on...
Now I have to compare each range of list1 with each range of list2, and find out if a certain range of list1 overlaps with any of the range of list2 and if yes then what is the overlapping answer? These are just sample values for the purposes of understanding.
I only need a simple and most efficient/fast formula to find out the overlap answer between 2 ranges. I can manage the rest of the loop algorithm.
**Example formula** :
```
var OverlappingValue = FindOverlapping(range1.StartValue, range1.EndValue,range2.StartValue, range2.EndValue);
```
and if the two ranges are not overlapping at all, then function must return 0.
PS: I didn't post my code because it's really complicated with a lot of conditions, I only need one simple formula.
|
2016/12/16
|
[
"https://Stackoverflow.com/questions/41185122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5305863/"
] |
If there is any overlapping range ; it must start from the max lower bound to the min upper bound so just use that "formula"
Then just get the number of item in that range by subtracting it's upper bound to it's lower one and add one (to be all inclusive)
Finally if that amount is negative it means that the range weren't overlapping so just get the max between that amount and 0 to handle that case
**Edit :** Oops C# not VB.Net
```
int FindOverlapping (int start1, int end1, int start2, int end2)
{
return Math.Max (0, Math.Min (end1, end2) - Math.Max (start1, start2) + 1);
}
```
|
8,725,594 |
At the moment I have:
```
//replace common characters
$search = array('&', '£', '$');
$replace = array('&', '£', '$');
$html= str_replace($search, $replace, $html);
```
The problem with this code is that if the & has been already converted it will try to convert it again. How would I make sure this doesn't happen?
|
2012/01/04
|
[
"https://Stackoverflow.com/questions/8725594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/560287/"
] |
I would use the built in functions that PHP has to escape HTML characters:
* [`htmlentities()`](http://php.net/manual/en/function.htmlentities.php)
* [`htmlspecialchars()`](http://www.php.net/manual/en/function.htmlspecialchars.php)
Rather than rolling my own as it is much easier. `htmlentities()` and `htmlspecialchars()` explicitly handle this with the `double_encode` parameter:
>
> When double\_encode is turned off PHP will not encode existing html
> entities. The default is to convert everything.
>
>
>
|
477,504 |
I got a local repository in `/var/www/html/centos/7` directory. In here, all rpm packages from centos are downloaded.
I will create a crontab for updating my local repository every 1 week or sth.
I want to learn that does `repocreate --update` do this? Or should I download all the packages from centos repo again?
If I should download the packages from centos repo, is there a way to skip the downloaded packages (they're in `/centos/7` directory as I mentioned) and download just the new (updated) packages from centos?
UPDATE
I have found the solution but it's not working for me. I created a new directory centos7/repo and download some files to check if the rsync --ignore-existing will work. But whenever I run the below command, I got an error
```
failed to connect to ftp.linux.org.tr (193.140.100.100): Connection timed out (110)
rsync: failed to connect to ftp.linux.org.tr (2001:a98:11::100): Network is unreachable (101)
rsync error: error in socket IO (code 10) at clientserver.c(125) [Receiver=3.1.2]
```
The command is:
```
rsync -avz --ignore-existing rsync://ftp.linux.org.tr/centos/7/os/x86_64/ /var/www/html/centos7/repo/
```
I tried other mirrors as well from <https://centos.org/download/mirrors/> (there are rsync location in this site as well). But none of them worked. Can anybody validate that rsync mirrors does work? Probably I can't go through firewall with port 873.
Is there anyway that I can use this rsync through port 80 or is there another way to accomplish this task? (I tried zsync but it needs a zsync file.)
|
2018/10/24
|
[
"https://unix.stackexchange.com/questions/477504",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/317026/"
] |
If you have problems with rsync, then you can use [reposync](https://linux.die.net/man/1/reposync). It is able to download all packages (or --newest-only| -n) from repo, configured in the system.
So final commands in script looks like:
```
/usr/bin/reposync --repoid=updates --download_path=/var/www/html/centos7/repo/updates --newest-only
/usr/bin/createrepo /var/www/html/centos7/repo/updates
```
|
62,325 |
What is the IUPAC name of *tert*-pentyl? I know that isopentyl is 2-methylpentane and neohexyl would be 2,2-methylhexane, but what about *tert*?
|
2016/11/08
|
[
"https://chemistry.stackexchange.com/questions/62325",
"https://chemistry.stackexchange.com",
"https://chemistry.stackexchange.com/users/33717/"
] |
There is a really nifty chart for this on the [pentyl group](https://en.wikipedia.org/wiki/Pentyl_group) page of Wikipedia:
>
> $$ \small
> \begin{array}{lcc}
> \hline
> \text{Name} & \text{Structure} & \text{IUPAC status} & \text{IUPAC recommendation} \\
> \hline
> n\text{-pentyl} & \ce{-(CH2)4CH3}\ & \text{} & \text{pentyl} \\
> tert\text{-pentyl} & \ce{-C(CH3)2CH2CH3} & \text{Allowed} & \text{1,1-dimethylpropyl} \\
> \text{neopentyl} & \ce{-CH2C(CH3)3} & \text{Allowed} & \text{2,2-dimethylpropyl} \\
> \text{isopentyl} & \ce{-CH2CH2CH(CH3)2} & \text{Allowed} & \text{3-methylbutyl} \\
> sec\text{-pentyl} & \ce{-CH(CH3)CH2CH2CH3} & & \text{1-methylbutyl, pentan-2-yl} \\
> 3\text{-pentyl} & \ce{-CH(C2CH3)2} & & \text{1-ethylpropyl, pentan-3-yl} \\
> \hline
> \end{array}
> $$
>
>
>
|
1,016,204 |
I have an existing project that I was working on, and I recently decided to update my iPhone SDK and updated to the latest 3.0 SDK.
I update my SDK and go to open my existing project. Sure enough, there are some problems including some certificate problems and so on. Anyway, google and I were able to solve most of them, but I haven't had any luck on what I hope to be the last of my problems.
When running my program in the simulator, I now get
>
> dyld: Library not loaded:
> /System/Library/Frameworks/UIKit.framework/UIKit
> Referenced from:
> /Developer/iGameLib/iGameLib/build/Debug-iphonesimulator/iGameLib.app/iGameLib Reason: image not found
>
>
>
Now, I discovered the UIKit has moved to
>
> /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0sdk/
> System/Library/FrameWorks/UIKit
>
>
>
and I have updated my target and project settings to point to that new framework location, but still when I build it, no luck.
I have also tried clearing out the simulator's applications and settings, still no luck.
The referencing .app is cleared when I run the "clean" menuitem, I have confirmed this, so clearly something in my project settings are still pointing to use the old UIKit location.
**Where should I be looking?**
I've gone as far as I can to help myself but I'm afraid I'm at a loss here. I don't see it under the target settings, or the project settings, or the plist, or any of the other files within my project.
|
2009/06/19
|
[
"https://Stackoverflow.com/questions/1016204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I was getting the same error
dyld: Library not loaded: /System/Library/Frameworks/UIKit.framework/UIKit
The solution on my case was simply quit Xcode and try again.
|
64,040,215 |
I made this code that creates a scatter chart and allows me to change the color of a node on the plot when I click/select it.
```
package com.jpc.javafx.charttest;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.ScatterChart;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class CreateChart extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
//-------Create Chart--------------
NumberAxis xAxis = new NumberAxis();
NumberAxis yAxis = new NumberAxis();
XYChart.Series<Number,Number> dataSeries1 = new XYChart.Series();
ScatterChart chart = new ScatterChart(xAxis,yAxis);
dataSeries1.getData().add(new XYChart.Data( 1, 567));
dataSeries1.getData().add(new XYChart.Data( 5, 612));
dataSeries1.getData().add(new XYChart.Data(10, 800));
chart.getData().add(dataSeries1);
//-----Select node and change color -----
for(final XYChart.Data<Number,Number> data : dataSeries1.getData()) {
data.getNode().setOnMouseClicked(e-> {
//dataSeries1.getNode().lookup(".chart-symbol").setStyle("-fx-background-color: red"); that does not work
data.getNode().setStyle("-fx-background-color: blue" );
});
}
VBox vbox = new VBox(chart);
Scene scene = new Scene(vbox, 400, 200);
primaryStage.setScene(scene);
primaryStage.setHeight(300);
primaryStage.setWidth(1200);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
```
The problem is that when I select another point the previous one stays blue. So I need to reset all the nodes to the default color before I change the selected point's color.
I tried to add this:
`dataSeries1.getNode().lookup(".chart-symbol").setStyle("-fx-background-color: red");`
but I get:
>
> Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
>
>
>
|
2020/09/24
|
[
"https://Stackoverflow.com/questions/64040215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14127900/"
] |
To summarize your requirement:
* a visual property of a chart-symbol should be marked on user interaction
* there should be only one such marked symbol
Sounds like a kind of selection mechanism - which is not supported for chart symbols out of the box, application code must take care of it. The task is
* keep track of the (last) selected symbol
* guarantee that at any time only a single symbol is selected
* keep the visual state of un/selected as needed
The most simple implementation for the logic (the first two bullets) would be to keep a reference to the current selected and update it on user interaction. An appropriate instrument for the latter would be a PseudoClass: can be defined in the css and de/activated along with the logic.
Code snippets (to be inserted into your example)
```
// Pseudo-class
private PseudoClass selected = PseudoClass.getPseudoClass("selected");
// selected logic
private Node selectedSymbol;
protected void setSelectedSymbol(Node symbol) {
if (selectedSymbol != null) {
selectedSymbol.pseudoClassStateChanged(selected, false);
}
selectedSymbol = symbol;
if (selectedSymbol != null) {
selectedSymbol.pseudoClassStateChanged(selected, true);
}
}
// event handler on every symbol
data.getNode().setOnXX(e -> setSelectedSymbol(data.getNode()));
```
css example, to be loaded via a style-sheet f.i.:
```
.chart-symbol:selected {
-fx-background-color: blue;
}
```
|
14,241,389 |
I am getting a "Specified cast is not valid" valid when doing only a release build from MSBuild 4.0. I tested this out in using a release build from Visual Studio 2012 and didn't get this issue. I also tested this out using a debug build from MSBuild 4.0 and didn't get this issue.
Exception: 
Code
```
public abstract class CachedSessionBase : ISessionObject
{
protected Dictionary<MethodBase, Object> _getAndSetCache = new Dictionary<MethodBase, object>();
protected TResult SetAndGet<TResult>(ObjectFactory factory, Func<TResult> func)
{
StackTrace stackTrace = new StackTrace();
var methodBase = stackTrace.GetFrame(1).GetMethod();
if (!_getAndSetCache.ContainsKey(methodBase))
{
_getAndSetCache[methodBase] = func.Invoke();
}
return (TResult)_getAndSetCache[methodBase];
}
```
The error is being thrown on this line
```
return (TResult)_getAndSetCache[methodBase];
```
|
2013/01/09
|
[
"https://Stackoverflow.com/questions/14241389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/463469/"
] |
It is likely that the call stack is different than what you are expecting it to be. Your method may be getting inlined, then `GetFrame(1)` is retrieving the caller's caller. When the value is retrieved from the dictionary, it is of a different type because it is for a different method.
You could try adding the attribute `[MethodImpl(MethodImplOptions.NoInlining]` to `SetAndGet` to prevent the inlining optimization for the method.
|
56,666,430 |
hi m trying to download db data in excel format,,, but when I click on download then it says: Call to undefined method Maatwebsite\Excel\Excel::create()
code of controller:
```
function excel()
{
$pdf_data = DB::table('importpdfs')->get()->toArray();
$pdf_array[] = array('Battery', 'No_of_questions_attempted', 'SAS', 'NPR', 'ST', 'GR');
foreach($pdf_data as $pdf)
{
$pdf_array[] = array(
'Battery' => $pdf->Battery,
'No_of_questions_attempted' => $pdf->No_of_questions_attempted,
'SAS' => $pdf->SAS,
'NPR' => $pdf->NPR,
'ST' => $pdf->ST,
'GR' => $pdf->GR
);
}
Excel::create('Pdf Data', function($excel) use ($pdf_array){
$excel->setTitle('Pdf Data');
$excel->sheet('Pdf Data', function($sheet) use ($pdf_array){
$sheet->fromArray($pdf_array, null, 'A1', false, false);
});
})->download('xlsx');
}
```
|
2019/06/19
|
[
"https://Stackoverflow.com/questions/56666430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10896655/"
] |
The create method was removed with `laravel-excel` version `3.0`.
From the [upgrade guide](https://docs.laravel-excel.com/3.1/getting-started/upgrade.html#upgrading-to-3-from-2-1):
>
> Excel::create() is removed and replaced by
> Excel::download/Excel::store($yourExport)
>
>
>
I would use the [quickstart guide](https://docs.laravel-excel.com/3.1/exports/) from their documentation.
|
238,223 |
I would like to create a view that uses aggregation on an entity to display the count and the sum by date. But it should be grouped by date only without time even the original date value has time values. I.e.
Entity:
processedTime | amount | value | ...
01/01/2017 08:00:00 | 10 | 1 | ...
01/01/2017 08:18:10 | 10 | 1 | ...
01/01/2017 10:00:00 | 10 | 1 | ...
01/02/2017 08:00:00 | 10 | 1 | ...
01/02/2017 09:30:00 | 10 | 1 | ...
...
the view should output
01/01/2017 | 30 | 3 | ...
01/02/2017 | 20 | 2 | ...
If I create a view with aggregation grouped by the date field, the view also evaluates the time and tries to group by the entire value of the date field. How can I group only by year, month and day without time?
|
2017/06/11
|
[
"https://drupal.stackexchange.com/questions/238223",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/76493/"
] |
@kiamlaluno described the technical details. This is the background why the `DependencySerializationTrait` was introduced:
This was the situation before:
>
> * Any class that receives injected dependencies (whether by
> constructor injection or setter injection) typically keeps a reference
> to its dependencies in class members. That's how dependency injection
> works.
> * Drupal being Drupal, it serializes stuff in several
> places:
> + Anything that is in a $form / $form\_state : the FormInterface object, but also any object whose methods are used by
> FAPI #callbacks ('#pre\_render' = array($some\_object,
> 'someSubmit')).
> + Anything that gets cached, stored in state(), or more generally in the k/v stores...
> * When an object is serialized, all the objects it references get serialized as well, and recursively, all the
> dependencies of those objects...
> * This leads to a
> serialization chain of hell: [#1909418] hit a case where serializing
> the form controller meant serializing the EntityManager -> the
> Container -> (among many other things) the DrupalKernel. This got
> fixed by making sure the kernel was serializable - which is just
> insane :-).
>
>
>
And this was the proposed solution:
>
> The answer for "DIC-friendly serialization" seems to be: * On
> serialize, do not serialize dependencies.
> * On unserialize,
> re-pull them from the container. Granted, this breaks mocking, but
> serialization/unserialization is not something you typically do in
> unit tests, so I don't see this as a real problem.
>
>
>
> How to do this might not be too simple though. Two approaches come to
> mind:
>
>
> 1. Classes that want to be "DIC-friendly serialized" need to
> implement an unserialize() method that hardcodes the services ids of
> its dependencies. That means doing something similar to the create()
> factory method that is currently used at instantiation time in a
> couple places in core (controllers, some plugins). Hardcoding service
> ids in more and more classes is not a joyful perspective, though.
> 2. Crazy idea:
> * Modify the DIC so that each time a service gets instantiated, the service id by which it got instantiated gets placed
> in a public \_\_serviceId (or something) property on the object.
> * Classes that want to be "DIC-friendly serialized" do:
>
> * On serialize() : foreach member, if (!empty($this->member->\_\_serviceId)) {just serialize the \_\_serviceId
> string instead of the whole object});
> * On unserialize() : $this->member = \Drupal::service($service\_id)
>
>
>
Quoted from [Injected dependencies and serialization hell](https://www.drupal.org/node/2004282)
|
3,178,361 |
Finding $$\int^{6}\_{0}x(x-1)(x-2)(x-3)(x-4)(x-6)dx$$
My progress so far
$$x(x-4)(x-6)(x-1)(x-2)(x-3)=\bigg(x^3-10x^2+24x\bigg)\bigg(x^3-6x^2+11x-6\bigg)$$
How can I find solution Help me
|
2019/04/07
|
[
"https://math.stackexchange.com/questions/3178361",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/661425/"
] |
Well, you can certainly proceed as you are now, and continue expanding until you get the polynomial into standard form, then integrate. We could go about it in a bit of a different way, though.
Let $f(x)=x(x-1)(x-2)(x-3)(x-4)(x-6).$ Then we have $$\int\_0^6f(x)dx=\int\_0^3f(x)dx+\int\_3^6f(x)dx,$$ and making the substitution $x\mapsto 6-x$ (so $3\mapsto 3,$ $6\mapsto 0,$ and $dx\mapsto-dx$) in the rightmost integral gets us
\begin{eqnarray}\int\_0^6f(x)dx &=& \int\_0^3f(x)dx-\int\_3^0f(6-x)dx\\ &=& \int\_0^3f(x)dx+\int\_0^3f(6-x)dx\\ &=& \int\_0^3\bigl(f(x)+f(6-x)\bigr)dx.\end{eqnarray}
Now, note that
\begin{eqnarray}f(6-x) &=& (6-x)(5-x)(4-x)(3-x)(2-x)(0-x)\\ &=& (-1)^6(x-6)(x-5)(x-4)(x-3)(x-2)(x-0)\\ &=& x(x-2)(x-3)(x-4)(x-5)(x-6),\end{eqnarray}
so that, remembering our difference of squares formula $(u+v)(u-v)=u^2-v^2,$ we can see that
\begin{eqnarray}f(x)+f(6-x) &=& x(x-2)(x-3)(x-4)(x-6)\bigl((x-1)+(x-5)\bigr)\\ &=& x(x-2)(x-3)(x-4)(x-6)(2x-6)\\ &=& 2x(x-2)(x-3)^2(x-4)(x-6)\\ &=& 2x(x-6)(x-2)(x-4)(x-3)^2\\ &=& 2\bigl((x-3)+3\bigr)\bigl((x-3)-3\bigr)\bigl((x-3)+1\bigr)\bigl((x-3)-1\bigr)(x-3)^2\\ &=& 2\left((x-3)^2-9\right)\left((x-3)^2-1\right)(x-3)^2\\ &=& 2\left((x-3)^4-10(x-3)^2+9\right)(x-3)^2\\ &=& 2\left((x-3)^6-10(x-3)^4+9(x-3)^2\right).\end{eqnarray}
Thus, we have $$\int\_0^6f(x)dx=2\int\_0^3\left((x-3)^6-10(x-3)^4+9(x-3)^2\right)dx,$$ and making the substitution $x\mapsto 3-x$ (so that $0\mapsto 3,$ $3\mapsto 0,$ and $x\mapsto-dx$) on the right-hand side, we get
\begin{eqnarray}f(6-x) &=& -2\int\_3^0\left((-x)^6-10(-x)^4+9(-x)^2\right)dx\\ &=& -2\int\_3^0\left(x^6-10x^4+9x^2\right)dx\\ &=& 2\int\_0^3\left(x^6-10x^4+9x^2\right)dx,\end{eqnarray}
which is a much nicer integral to evaluate. Still, that's a lot of work to go through just to avoid a few more polynomial expansions.
|
1,748,908 |
I am using sugarCRM at my localhost.
For no apparent reason firefox is viewing the page in Quirks mode (the login page). This is completely messing up the page, here is a sample of the data shown:
>
> ��������Z�n7�-}v�fd4��q�Z�·8�ڱa�-�
> f(�
> 5�rf��<�b���y�=��ftwRw�@"����m�<�2��^?}�
> -��Ӌ�s���w|�#��Wo����U��'���a�n�{2��f0f1�E��~K���
> fA\�$♞)�ioDU���]�U�;�$�`��krp@�XKE|I�p&k������C[rP��!��?�tH��9�j�p=
>
>
>
I thought this might be the server's fault (apache) but if I use Epiphany I can see the page perfectly. When I see the pages info, I see that the render mode is in quirks mode.
Is there any way to force it to use the Standards compliance mode?
I am on ubuntu 9.10 using Firefox 3.5 (I also tried 3.0.15, same thing happened) I disabled all the extension and I still got the same page. A friend tried viewing it with Chrome and the same thing happened :(
|
2009/11/17
|
[
"https://Stackoverflow.com/questions/1748908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8715/"
] |
To get Firefox to render a page in standards-compliant mode, add a DOCTYPE to your HTML. For example, if you're using HTML (as opposed to XHTML), use:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/DTD/strict.dtd">
```
You might find this Wikipedia link helpful - [triggering different rendering modes](http://en.wikipedia.org/wiki/Quirks_mode#Triggering_different_rendering_modes).
|
39,030,892 |
i have a big image that has a dimensions of 1920x1080, but my current canvas has only a size of 800x600.. scaling the image to the size of the background pixelates/reduces the quality of the image. even when exporting, the image quality is still low.. how do i prevent that from happening?
```
var background = 'image.jpg';
canvas.setBackgroundImage(background, canvas.renderAll.bind(canvas), {
width: canvas.width,
height: canvas.height,
originX: 'left',
originY: 'top'
});
```
|
2016/08/19
|
[
"https://Stackoverflow.com/questions/39030892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2091217/"
] |
I'm not sure fabric has a way to improve this. Doing big scaling can cause these kind of quality reductions. In our app we use a library called pica that is for resizing images down with high quality.
[pica repo here](https://github.com/nodeca/pica)
[pica demo here](http://nodeca.github.io/pica/demo/)
You could use this library to scale image image down before adding it to the canvas or maybe even when the canvas resizes.
|
2,030,910 |
I am sending a status code via the header function, such as `header('HTTP/1.1 403');`, and would like to in another area of my code detect what status code is to be sent (in particular if I have sent an error code of some nature). As has been mentioned [elsewhere](https://stackoverflow.com/questions/1798353/determine-the-http-status-that-will-be-sent-in-php), `headers_list()` does not return this particular item, and it's unclear to me if it actually counts as a header, as neither Firebug nor Fiddler2 treat it with the headers. So - how can a PHP script detect which status code is about to be sent to the browser?
I would rather not use a wrapper function (or object) around the header method, or otherwise set some global variable along with the sending of the status code. I'd also rather not call my code from itself using curl or the like, due to performance concerns. Please let me know what you think.
|
2010/01/08
|
[
"https://Stackoverflow.com/questions/2030910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118153/"
] |
Consider setting a constant:
```
define('HTTP_STATUS', 403);
```
and using the `defined` function later on:
```
if(defined('HTTP_STATUS') && HTTP_STATUS == 403) // ...or whatever you're looking to do
```
Actually peeking back at the headers themselves is kind of a hack in itself as it's simply too slow: you're dealing with strings and arrays and all sorts of other messy data. Set for yourself a simple constant: it's blazing fast, it does the same thing, and it doesn't create any "true" global variables.
|
696,208 |
learning QM and just have a few questions regarding normalizing wavefunctions.
1. Thus far, every initial wavefunction that we've normalized has had an undefined constant explicitly put out front (i.e., something like $\Psi (x,0) = A(a - x^{2})$, as an example) I was recently asked to normalize a wavefunction that didn't have any undetermined constant out front of the function involving x. Now it's okay for me to multiply the undefined constant, say $A$, to the wavefunction? Since, of course, the purpose of normalizing the wavefunction is finding a form such that the probability is 1 over all space.
2. If I'm given a complete wavefunction (i.e., a solution to the time dependent Schrodinger equation - $\Psi(x,t) = \psi(x)\phi(t)$ I can just perform the normalization at $t=0$ right? In other words, normalize the initial wavefunction $\Psi(x,0) = \psi(x)\phi(0)$. Since once a wavefunction is normalized, it remains normalized for all time, correct? Or do I need to perform the normalization at arbitrary time $t$ if given the complete wavefunction?
3. If I've just normalized a wavefunction and am determining the constant $A$ but have $|A|^{2}$ = $K$ where $K$ is just some constant then I necessarily have $A$ = $\pm\sqrt{K}$ but the problem makes no mention of the nature of the constant (i.e., doesn't say anything like "where $A,a,b,$ etc... are all positive real constants) then how am I to determine the sign of $A$? Does it even matter? I imagine it wouldn't in the verification of the normalization but it would change the sign of the wavefunction, so it must have some importance?
4. If I get a wavefunction such that $|\Psi(x,0)|^{2} = 1$ would that tell me that this wavefunction is non-normalizable? Since the integral doesn't converge.
|
2022/02/23
|
[
"https://physics.stackexchange.com/questions/696208",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/152819/"
] |
1. Yes. Normalizing the wavefunction means multiplying it by whatever constant you need to in order to make its norm equal to $1$.
2. Yes, because time evolution in quantum mechanics is *unitary* - in other words, you can write $\psi(t) = \hat U(t) \psi(0)$ for a unitary operator $\hat U(t)$ called the *propagator*, and $\Vert \hat U \psi\Vert = \Vert \psi\Vert $ for all unitary operators $\hat U$. Caveat: this is no longer true if you perform a measurement, in which case your wavefunction will undergo (non-unitary) projective evolution and you may need to renormalize afterward.
3. If $|A|^2 = K$, then $A=e^{i\theta} \sqrt{K}$ for any arbitrary phase angle $\theta\in[0,2\pi)$. You may make any choice you want, and it will not impact any physically meaningful predictions of the theory. Perhaps you could check to see whether multiplying the wave function by some $e^{i\theta}$ changes e.g. the probabilities of any measurement outcomes.
|
16,049,330 |
I am attempting to store css files inside database and call them in the most effective wa using PHP. I know I can include a style.php file and just do a query to get the data; however, not sure if that is the best way or not. I'd prefer to not have
```
<style>
#blah { }
#blah 2 { }
etc.
</style>
```
show up on every page. I am attempting to make this work similar to how a typical css file would work where it is just a link similar to the way it is below. I have read about people using
html page:
```
<link rel="stylesheet" type="text/css" href="style.php" />
```
style.php page:
```
header("Content-Type: text/css");
```
however, have also seen that that doesn't work well with IE.
So does anyone have any recommendations on how I can do this in the best way for all browsers?
|
2013/04/17
|
[
"https://Stackoverflow.com/questions/16049330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2200549/"
] |
I'd probably write a tiny wrapper class for each:
```
template <class T>
class read_only {
T volatile *addr;
public:
read_only(int address) : addr((T *)address) {}
operator T() volatile const { return *addr; }
};
template <class T>
class write_only {
T volatile *addr;
public:
write_only(int address) : addr ((T *)address) {}
// chaining not allowed since it's write only.
void operator=(T const &t) volatile { *addr = t; }
};
```
At least assuming your system has a reasonable compiler, I'd expect both of these to be optimized so the generated code was indistinguishable from using a raw pointer. Usage:
```
read_only<unsigned char> x(0x1234);
write_only<unsigned char> y(0x1235);
y = x + 1; // No problem
x = y; // won't compile
```
|
12,386,263 |
I am trying to build a very basic executable (Windows) using PySide. The following script runs properly in the interpreter (Python 2.7, PySide 1.1.2)
```
#!/usr/bin/python
import sys
sys.stdout = open("my_stdout.log", "w")
sys.stderr = open("my_stderr.log", "w")
import PySide.QtGui
from PySide.QtGui import QApplication
from PySide.QtGui import QMessageBox
# Create the application object
app = QApplication(sys.argv)
# Create a simple dialog box
msgBox = QMessageBox()
msgBox.setText("Hello World - using PySide version " + PySide.__version__)
msgBox.exec_()
```
I tried 3 methods (py2exe, pyinstaller and cx\_freeze) and all the 3 generated executables fail to execute. The two stdout/stderr files appear, so I found the first PySide import is making everything fail. (Unhandled exception/Access violation)
I analyzed the executable file with depends (<http://www.dependencywalker.com/>) and everything looks correctly linked.
Any idea?
|
2012/09/12
|
[
"https://Stackoverflow.com/questions/12386263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1595335/"
] |
You need to add the atexit module as an include. source: <http://qt-project.org/wiki/Packaging_PySide_applications_on_Windows>
(is also the case for Linux btw)
|
28,659,011 |
i have following problem in my javascript code.
I try to put my ajax response into a table.
All works fine.
But now i'v tried to show s porgressbar in one of the columns for each entry.
Dosen't work.
Here is the main piece of code which do the work:
```
[...]
,success:function(data) {
$("#table").empty();
$.each(data,function(index,Data) {
var process_result = Data.accuracyI;
var id = Data.UIDI;
if (Data.entire == 0) {
$("#entire").text("No succeed").css({
"color": "red",
"font-weight": "bold"
});
} else {
$("#entire").html(Data.EntireI).css({
"color": "green",
"font-weight": "bold"
});
$tr = $("<tr/>");
$tr.append($("<td/>").text(Data.lastNameI));
$tr.append($("<td/>").text(Data.firstNameI));
$tr.append($("<td/>").text(Data.aliasI));
$tr.append($("<td/>").text(Data.pepI));
$tr.append($("<td/>").text(Data.dobI));
$tr.append($("<td/>").text(Data.place_of_birthI));
$tr.append($("<td/>").text(Data.countriesI));
$tr.append($("<td/>").html("<div id='" + id + "'></div>"));
$tr.append($("<td/>").html(Data.PDFI));
$("#result").append($tr);
$(id).progressbar({
value: process_result
});
}
});
[...]
```
So here you can see the code.
My problem is that the progressbar in the column after 'Countries' is not showing for each entry - just for the first in the table.
Bizarrely if i change the 'div' Element to, for example the varibale process\_result, each entry of the table shows his own number correctly.
So what is the misstake i have to change?
Thnaks a lot.
|
2015/02/22
|
[
"https://Stackoverflow.com/questions/28659011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3625342/"
] |
```
var id = Data.UIDI;
[...]
$(id).progressbar({
value: process_result
});
```
the variable `id` should represent a selector. see [API](http://api.jqueryui.com/progressbar/)
solution
--------
```
$('#' + id).progressbar({
value: process_result
});
```
|
17,316,183 |
I want to start and stop service when device in action call, so i use TelephonyManager and my class extends flagment. i Tried this code
```
TelephonyManager tm = (TelephonyManager)getActivity().getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
private PhoneStateListener mPhoneListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
getActivity().stopService(new Intent(getActivity(),LockScreenService.class));
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
getActivity().stopService(new Intent(getActivity(),LockScreenService.class));
break;
case TelephonyManager.CALL_STATE_IDLE:
getActivity().startService(new Intent(getActivity(),LockScreenService.class));
break;
}
}
}
;
```
but it does not work. Please give me some advises. Thanks so much
|
2013/06/26
|
[
"https://Stackoverflow.com/questions/17316183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2503313/"
] |
Try this code:
```
telephonyManager = ( TelephonyManager )getActivity.getSystemService( Context.TELEPHONY_SERVICE );
imeistring = telephonyManager.getDeviceId();
```
|
693,174 |
I know its possible to integrate jQuery within Firefox addons, but are we able to manipulate (animate, move, adjust transparency, etc) XUL elements themselves?
From what I understand, the Firefox addon can use jQuery to manipulate HTML/DOM elements, but not sure about XUL elements.
|
2009/03/28
|
[
"https://Stackoverflow.com/questions/693174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84047/"
] |
XUL and HTML actually deal with opacity the exact same way, and it is jQuery that incorrectly detects what the browser can do. jQuery thinks it's in a different browser when it's living inside XUL, and so opacity effects are handled differently - by jQuery. Since it IS in Firefox, and it should deal with opacity normally, you can override this like so:
jQuery.support.opacity = true
Do this right after jQuery is loaded.
There is probably a whole category of similar fixes that can be post-applied to jQuery to make it behave better, but I haven't looked in to it.
|
59,534,983 |
I have the following code (full example):
```
import React, { useState, useEffect } from 'react';
import { SafeAreaView, View, Button, StyleSheet, Animated } from 'react-native';
import { PanGestureHandler, State } from 'react-native-gesture-handler';
const App = () => {
const [blocks, setBlocks] = useState([]);
const CreateBlockHandler = () => {
let array = blocks;
array.push({
x: new Animated.Value(0),
y: new Animated.Value(0)
});
setBlocks(array);
RenderBlocks();
};
const MoveBlockHandler = (index, event) => {
Animated.spring(blocks[index].x, { toValue: event.nativeEvent.x }).start();
Animated.spring(blocks[index].y, { toValue: event.nativeEvent.y }).start();
};
const RenderBlocks = () => {
return blocks.map((item, index) => {
return (
<PanGestureHandler key={index} onGestureEvent={event => MoveBlockHandler(index,event)}>
<Animated.View style={[styles.block, {
transform: [
{ translateX: item.x },
{ translateY: item.y }
]
}]} />
</PanGestureHandler>
)
});
};
return (
<SafeAreaView style={styles.container}>
<View style={styles.pancontainer}>
<RenderBlocks />
</View>
<Button title="Add block" onPress={CreateBlockHandler} />
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
pancontainer: {
width: '95%',
height:'75%',
borderWidth: 1,
borderColor: 'black'
},
block: {
width: 50,
height: 50,
backgroundColor: 'black'
}
});
export default App;
```
What does this code do? It's a big square, and a button below it. When I click on the button, a new black square (50x50) is made in the big square. I do this by creating a new array element (the array = blocks). This is done in the function **CreateBlockHandler**. This does not work correctly!
The function **MoveBlockHandler** makes the little squares movable. This works!
What does not work? When I create a new black square, the black square is not rendered on the screen. Only when I refresh, the square is rendered. The square is created through CreateBlockHandler, because when I do a console.log(blocks) in that function, I can see that a new array element is added.
How can I force this code to do a full re-render with all the array elements? I tried to wrap the render of the square in a separate function (**RenderBlocks**) and I'm calling this function every time a new square is made (last line in CreateBlockHandler). The function is called (I can check this with a console.log()) but no squares are rendered.
|
2019/12/30
|
[
"https://Stackoverflow.com/questions/59534983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12496104/"
] |
When you assign `blocks` to `array` the reference gete copied which mutates the state, so it doesn't re-render on `setState`.
```
const CreateBlockHandler = () => {
let array = [...blocks];
array.push({
x: new Animated.Value(0),
y: new Animated.Value(0)
});
setBlocks(array);
RenderBlocks
```
|
61,118,659 |
Tried extracting the href from:
```
<a lang="en" class="new class" href="/abc/stack.com"
tabindex="-1" data-type="itemTitles"><span><mark>Scott</mark>, CC042<br></span></a>
```
using `elems = driver.find_elements_by_css_selector(".new class [href]")` , but doesn't seem to work.
Also tried [Python Selenium - get href value](https://stackoverflow.com/questions/54862426/python-selenium-get-href-value), but it returned an empty list.
So I want to extract all the href elements of class = "new class" as mentioned above and append them in a list
Thanks!!
|
2020/04/09
|
[
"https://Stackoverflow.com/questions/61118659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13016237/"
] |
Use `.get_attribute('href')`.
`by_css_selector`:
```
elems = driver.find_elements_by_css_selector('.new.class')
for elem in elems:
print(elem.get_attribute('href'))
```
Or `by_xpath`:
```
elems = driver.find_elements_by_xpath('//a[@class="new class"]')
```
|
431,878 |
I have files with naming convention of this pattern:
```
bond_7.LEU.CA.1.dat
bond_7.LEU.CA.2.dat
bond_7.LEU.CA.3.dat
bond_12.ALA.CB.1.dat
bond_12.ALA.CB.2.dat
bond_12.ALA.CB.3.dat
...
```
I want to concatenate all files of the same group into a single one. For example:
```
cat bond_7.LEU.CA.*.dat > ../bondvalues/bond_7.LEU.CA.1_3.dat
```
There's large number of these files. How can achieve this with a bash script?
|
2012/06/02
|
[
"https://superuser.com/questions/431878",
"https://superuser.com",
"https://superuser.com/users/137717/"
] |
Assuming that the example you provide reflects all of your files the following should do the trick:
```
for f in *.1.dat
do
cat ${f%%1.dat}* > ${f%%1.dat}1_3.dat
done
```
This requires that each group contains a file with the .1.dat extension.
|
7,640,177 |
I'm defining a javascript object and setting its properties and methods like this:
```
function MyObject()
{
this.prop1 = 1;
this.prop2 = 2;
this.meth1=meth1;
}
function meth1()
{
// do soemthing
}
```
All is fine. My question is how can i have an object be a property of MyObject? I actually want an 'associative array' as a property something along these lines:
```
function MyObject()
{
this.obj['x'] = 'val1';
this.obj['y'= = 'val2';
this.prop1 = 1;
this.prop2 = 2;
this.meth1=meth1;
}
```
I have tried declaring obj in MyObject like this: `obj = new Object`; with no luck, obj is not being interpreted as a property.
Any clues as to what i'm doing wrong?
thanks
|
2011/10/03
|
[
"https://Stackoverflow.com/questions/7640177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/550116/"
] |
Do you mean:
```
function MyObject() {
this.obj = {'x': 'val1', 'y': 'val2'};
this.prop1 = 1;
this.prop2 = 2;
this.meth1=meth1;
}
```
?
Now you can say:
```
new MyObject().obj.x //`val1`
```
Alternative syntax:
```
this.obj = {};
this.obj.x = 'val1';
this.obj.y = 'val2';
```
|
64,491,157 |
I have a .NET Core Web API using ODATA. To support a legacy requirement, I'd like to change the default format of DateTime members to something like "yyyy-MM-dd HH:mm:ss", then be able to override the format on individual members. I understand this is different from JsonConverter and may require a custom ODATA serializer, but I am not sure how to do so.
|
2020/10/22
|
[
"https://Stackoverflow.com/questions/64491157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832058/"
] |
I found a good solution using [ODataPayloadValueConverter](https://learn.microsoft.com/en-us/dotnet/api/microsoft.odata.odatapayloadvalueconverter?view=odata-core-7.0). Below is the implementation for DateTime, but you could easily add other types as needed.
```
class MyPayloadValueConverter : ODataPayloadValueConverter
{
public override object ConvertToPayloadValue(object value, IEdmTypeReference edmTypeReference)
{
if (value is DateTime)
{
return String.Format("{0:yyyy-MM-dd HH:mm:ss}", value, CultureInfo.InvariantCulture);
}
else
{
return base.ConvertToPayloadValue(value, edmTypeReference);
}
}
public override object ConvertFromPayloadValue(object value, IEdmTypeReference edmTypeReference)
{
if (edmTypeReference.IsDate() && value is string)
{
return DateTime.Parse((string)value, CultureInfo.InvariantCulture);
}
else
{
return base.ConvertFromPayloadValue(value, edmTypeReference);
}
}
}
```
Wire up your converter in Startup.cs like this:
```
app.UseEndpoints(endpoints =>
{
...
endpoints.MapODataRoute("odata", "odata", action =>
{
action.AddService(Microsoft.OData.ServiceLifetime.Singleton, typeof(ODataPayloadValueConverter), pvc => new MyPayloadValueConverter());
});
});
```
|
41,764,618 |
```
$("selector").data("name", null);
console.log($("selector").data("name"));
```
This prints `undefined`.
Is there anyway to instantiate a `null` item in the jQuery data object of an element, not an undefined one?
|
2017/01/20
|
[
"https://Stackoverflow.com/questions/41764618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3380611/"
] |
Yes and Your code works fine, You should check if your `$("selector")` exists
|
5,019,360 |
I have made a webapp for my android phone where I can check the sales at my store when I'm not there.
I would like to have notifications on my phone whenever a sale is made.
What is the best way of doing this? Any existing android apps that I can configure to check a php-script every 2 minutes or something?
|
2011/02/16
|
[
"https://Stackoverflow.com/questions/5019360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348776/"
] |
Try using XMPP to send a message to yourself, which you can receive via gtalk on the phone. Alternatively, an email, SMS, etc.
|
44,285,434 |
I have a UserForm that has a textbox that is populated from the `=Now()` function. However the data I am tracking runs on a 3 shift schedule, so "3rd shift" will technically be entering their data on next day. I have adjusted for this using an if statement, but my problem is getting my textbox to update on the change of a combo box that allows you to select what shift you're entering for. I tried the DoEvents function at the suggestion from another helpsite, but it did not work. Thanks in advance!
`Private Sub date_txtb_Change()
If shift_cbox.Text = "Shift 1" Then
date_txtb.Text = Format(Now(), "MM/DD/YY") 'Current Date
DoEvents`
```
ElseIf shift_cbox.Text = "Shift 2" Then
date_txtb.Text = Format(Now(), "MM/DD/YY") 'Current Date
DoEvents
ElseIf shift_cbox.Text = "Shift 3" Then
date_txtb.Text = Format(Now() - 1, "MM/DD/YY") 'Current Date -1
DoEvents
Else
'do nothing'
End If
```
`End Sub`.
|
2017/05/31
|
[
"https://Stackoverflow.com/questions/44285434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7889757/"
] |
You are using the wrong object. Instead of `Private Sub date_txtb_Change()` you should use `Private Sub shift_cbox_Change()`.
|
5,507,754 |
I have an html form that sends data to .cgi page. Here is the html:
```
<HTML>
<BODY BGCOLOR="#FFFFFF">
<FORM METHOD="post" ACTION="test.cgi">
<B>Write to me below:</B><P>
<TEXTAREA NAME="feedback" ROWS=10 COLS=50></TEXTAREA><P>
<CENTER>
<INPUT TYPE=submit VALUE="SEND">
<INPUT TYPE=reset VALUE="CLEAR">
</CENTER>
</FORM>
</BODY>
</HTML>
```
Here is the perl script for test.cgi:
```
#!/usr/bin/perl
use utf8;
use encoding('utf8');
require Encode;
require CGI;
# The following accepts the data from the form and puts it in %FORM
if ($ENV{'REQUEST_METHOD'} eq 'POST') {
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
# The following generates the html for the page
print "Content-type: text/html\n\n";
print "<HTML>\n";
print "<HEAD>\n";
print "<TITLE>Thank You!</TITLE>\n";
print "</HEAD>\n";
print "<BODY BGCOLOR=#FFFFCC TEXT=#000000>\n";
print "<H1>Thank You!</H1>\n";
print "<P>\n";
print "<H3>Your feedback is greatly appreciated.</h3><BR>\n";
print "<P>\n<P>\n";
print "The user wrote:\n\n";
print "<P>\n";
# This is print statement A
print "$FORM{'feedback'}<br>\n";
$FORM{'feedback'}=~s/(\w)/ $1/g;
# This is print statement B
print "$FORM{'feedback'}\n";
print "</BODY>\n";
print "</HTML>\n";
exit(0);
}
```
This all works the way it's supposed to if the user enters English text. However, this will eventually be used in a product where the user will enter Chinese text. So here's an example of the problem. If the user enters "中文" into the form, then Print Statement A prints "中文." However, Print Statement B (which prints $value after the regex has been run) prints "&# 2 0 0 1 3;&# 2 5 9 9 1; ". What I want it to print however is "中 文". If you want to see this, go to <http://thedeandp.com/chinese/input.html> and try it yourself.
So basically, what I've figured out is that when perl reads in the form, it's just treating each byte as a character, so the regex adds a space between each byte. Chinese characters use unicode, so it's multiple bytes to a character. That means the regex breaks up the unicode with a space between the bytes, and that is what produces the output seen in Print Statement B. I've tried methods like $value = Encode::decode\_utf8($value) to get perl to treat it as unicode, but nothing has worked so far.
|
2011/03/31
|
[
"https://Stackoverflow.com/questions/5507754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686620/"
] |
That [CGI](http://search.cpan.org/perldoc?CGI) style could be improved while fixing your encoding decoding issue. Try this–
```
use strict;
use warnings;
use Encode;
use CGI ":standard";
use HTML::Entities;
print
header("text/html; charset=utf-8"),
start_html("Thank you!"),
h1("Thank You!"),
h3("Your feedback is greatly appreciated.");
if ( my $feedback = decode_utf8( param("feedback") ) )
{
print
p("The user wrote:"),
blockquote( encode_utf8( encode_entities($feedback) ) );
}
print end_html();
```
Proper encoding and decoding between octets/bytes and utf-8 is necessary to avoid surprises and allow the Perl to behave as you’d expect.
For example, you can drop this in–
```
h4("Which capitalizes as:"),
blockquote( encode_utf8( uc $feedback ) );
```
And see character conversions work like so: å™ç∂®r£ ➟ Å™Ç∂®R£
Update: added `encode_entities`. NEVER print user input back without escaping the HTML. Update to update: which actually will end up escaping the utf-8 depending on the setup (you can have it only escape ['"<>] for example)…
|
31,946,407 |
I have a C# application using Oracle database and Entity Framework 5. Oracle client is version 12c R1. My application uses database first approach. I'm trying to run the app using Visual Studio Enterprise 2015. When I access the edmx file and I try to update the model from the database, it gives me the following error:
>
> An exception of type 'System.ArgumentException' occurred while attempting to update from the database. The exception message is: 'Unable to convert runtime connection string to its design-time equivalent. The libraries required to enable Visual Studio to communicate with the database for design purposes (DDEX provider) are not installed for provider 'Oracle.DataAccess.Client'. Connection string: XXXXX.
>
>
>
This error does not occur when I use Visual Studio Ultimate 2013. Only on Visual Studio Enterprise 2015.
Is there any known incompatibility issue with the new one?
|
2015/08/11
|
[
"https://Stackoverflow.com/questions/31946407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4791851/"
] |
I believe it is because not yet out ODT version compatible with Visual Studio 2015. Wait or will have no choice for now?
[Oracle Developer Tools](http://www.oracle.com/technetwork/developer-tools/visual-studio/overview/index.html)
|
440,571 |
I'm trying to build some unit tests for testing my Rails helpers, but I can never remember how to access them. Annoying. Suggestions?
|
2009/01/13
|
[
"https://Stackoverflow.com/questions/440571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4322/"
] |
In rails 3 you can do this (and in fact it's what the generator creates):
```
require 'test_helper'
class YourHelperTest < ActionView::TestCase
test "should work" do
assert_equal "result", your_helper_method
end
end
```
And of course [the rspec variant by Matt Darby](https://stackoverflow.com/a/441298/1152564) works in rails 3 too
|
221,498 |
I’m building a Lightning component to edit html and need a robust WYSIWYG rich text editor (RTE) with “add link” feature and embed features. I really need the “add link” feature. When I search for RTE and Lightning I found and considered the following:
Trailblazer gives UI guidelines if you want to layout your own markup for a RTE but why reinvent the wheel when there are good plugins out there.
<http://lightningdesignsystem.com/components/rich-text-editor/>
The old ui:inputRichText is not supported when LockerService is activated:
So this leaves `<lightning:inputRichText />`. But this RTE lacks is deficient in both add link and image features.
```
<lightning:inputRichText value="{!v.body}" aura:id="iBody">
</lightning:inputRichText>
```
I’ve seen code that suggests you can add a button to let uses insert an image.
```
<lightning:inputRichText value="{!v.body}">
<lightning:insertImageButton/>
</lightning:inputRichText>
```
But this image uploader has a 1MB limit and has a terrible way of dealing with files that are too big. The user is told a serious error happened and they are asked to send a report into SF.
Is there some inner component that can be added to provide a Add Hyperlink feature?
Or, can we get the RTE that is used in Salesforce Lightning? Its the CKE editor and it’d be good enough. Is there a way to use this in our Lightning apps? I’ll guess that it might be imported as a static resource etc. Has anyone tried this and had success?
|
2018/06/14
|
[
"https://salesforce.stackexchange.com/questions/221498",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/2437/"
] |
I figured it out: if your Salesforce Instance has access to Einstein Bots, there will be an **Einstein Bots Settings** section under the **Chat Buttons** section in **Setup**.
[](https://i.stack.imgur.com/Ijq2Z.png)
If you leave **Einstein Bots Configuration** blank, then (curiously enough) the preview for Einstein Bot will redirect the user to a Live Agent.
To fix this issue, simply fill in **Einstein Bots Configuration** as I have done in the picture above.
|
16,765,085 |
How can I detect which UIButton has been tapped:
```
-(void) topScorer {
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
[button1 addTarget:self
action:@selector(buttonClicked:)
forControlEvents:UIControlEventTouchDown];
[button1 setTitle:@"Button1" forState:UIControlStateNormal];
button1.frame = CGRectMake(16, self.view.bounds.size.height*0.6, 60, 60);
UIImage *img1 = [UIImage imageNamed:@"img1.png"];
button1.layer.cornerRadius = 10;
button1.layer.masksToBounds = YES;
[button1 setImage:img1 forState:UIScrollViewDecelerationRateNormal];
button1.tag = 1;
[self.view addSubview:button1];
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self
action:@selector(buttonClicked:)
forControlEvents:UIControlEventTouchDown];
[button2 setTitle:@"Button2" forState:UIControlStateNormal];
button2.frame = CGRectMake(92, self.view.bounds.size.height*0.6, 60, 60);
UIImage *img2 = [UIImage imageNamed:@"img2.png"];
button2.layer.cornerRadius = 10;
button2.layer.masksToBounds = YES;
[button2 setImage:img2 forState:UIScrollViewDecelerationRateNormal];
button2.tag = 2;
[self.view addSubview:button2];
}
-(void) buttonClicked: (id)sender {
// How can I detect here which button is tapped?
// For Example, I want to do this:
// if button1 is pressed, do something
// if button 2 is pressed, do another thing
}
```
|
2013/05/27
|
[
"https://Stackoverflow.com/questions/16765085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1019442/"
] |
Cast your sender to a UIButton and compare the tag value.
```
UIButton *button = (UIButton *)sender;
if (button.tag == 1) {
} else {
}
```
|
22,691,075 |
This question is a part of my current problem, so let's start with the big picture.
I am trying to sort a dictionary by the values in descending order. My dictionary is 1-to-1 corresponding, such as:
>
> ('ID1':value1, 'ID2':value2, ......)
>
>
>
I followed [this thread](https://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value) and find my answer:
```
import operator
sorted_dict = sorted(original_dict.iteritems(), key = operator.itemgetter(1), reverse = True)
```
Then I tried to extract the keys in `sorted_dict` since I thought it is a `dictionary`. However, it turns out that `sorted_dict` is a `list`, thus has no `keys()` method.
In fact, the `sorted_dict` is organized as:
>
> [('ID1', value1), ('ID2', value2), .....] # a list composed of tuples
>
>
>
But what I need is a list of ids such as:
>
> ['ID1', 'ID2', ......]
>
>
>
So now, the problem turns to **How to extract variable in specific position for each of the tuples in a list?**
Any suggestions? Thanks.
|
2014/03/27
|
[
"https://Stackoverflow.com/questions/22691075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2633803/"
] |
You can do that using [list comprehension](http://www.secnetix.de/olli/Python/list_comprehensions.hawk) as follows:
```
>>> ids = [element[0] for element in sorted_dict]
>>> print ids
['ID1', 'ID2', 'ID3', ...]
```
This gets the first element of each `tuple` in the `sorted_dict` list of tuples
|
4,476,917 |
>
> **Possible Duplicate:**
>
> [How many data a list can hold at the maximum](https://stackoverflow.com/questions/3767979/how-many-data-a-list-can-hold-at-the-maximum)
>
>
>
What is the maximum number of elements a list can hold?
|
2010/12/18
|
[
"https://Stackoverflow.com/questions/4476917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/489718/"
] |
didnt get ya completely but to append a new tr to a specific tr you can use
```
$('#trUniqueId').append(
$('<tr/>').attr("id","newtrId")
);
```
|
130,462 |
I am doing some hands-on training with Kali linux and one of the exercise I came across was to make an exe file containing malicious payload(say to obtain reverse shell), send it to a victim and hope for the victim to download the exe file. If he/she downloads it, it is fairly easy after that.
Now this isn't tricky at all, assuming the fact that many users aren't aware of security. But in real world, to carry out this attack, there must be more hurdles that an attacker needs to cross for exploitation?
What are those security measures that stops attempt to exploit users? For example I can think of firewall which tries to detect malicious looking requests.
Please answer the question for both internal and external attacks.
|
2016/07/19
|
[
"https://security.stackexchange.com/questions/130462",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/110848/"
] |
There are a number of ways that people attempt to mitigate these attacks.
**External**
* Prevent spam filter from allowing MIME types frequently associated with malware (it's highly unlikely there is a business relevant reason to send .exe or .bat files for instance)
* Use Anti-Virus as .exe's can be detected even after several rounds of encoding. Preferably you'd want "behavioural based" anti-virus which block applications based on actions they attempt to take.
* Educate your staff on how to spot threats and what to do should they encounter them.
* If you're IT department is big enough and you want to pull your hair out figuring it out, software restriction policies can be implemented to only allow known .exe's from running
* Disable the ability for executables to run from the temp directory / directories
* Implement firewall egress filtering. Set up a proxy with deep packet inspection that intercepts SSL / TLS connections and blocks outbound traffic that seems suspicious.
**Internal**
* Do not give local admin access to end users. Just don't. If they need to raise privileges assign them a special account that they have to use the "Run As..." functionality to use, but end users should not have administrative privileges on their workstations.
* Software restrictions / egress filtering / AV / Education / disabling executables from temp directory all still apply for internal
* Segregate your network to prevent lateral movement in the instance there is compromise
|
65,852,340 |
I have written a code for a drag and drop using vanilla javascript. When I pick the first div, it does move to last automatically while I was trying to move next.
I don't want to use the jquery library.
What I tried is I created the main div that acts as a container so that inside of that container each div can be moved easily
I have attached what I tried, but I don't understand why this is happening.
```js
const draggables = document.querySelectorAll('.draggable')
const containers = document.querySelectorAll('.mainContainer')
draggables.forEach(draggable => {
draggable.addEventListener('dragstart', () => {
draggable.classList.add('dragging')
})
draggable.addEventListener('dragend', () => {
draggable.classList.remove('dragging')
})
})
containers.forEach(container => {
container.addEventListener('dragover', e => {
e.preventDefault()
const afterElement = getDragAfterElement(container, e.clientY)
const draggable = document.querySelector('.dragging')
if (afterElement == null) {
container.appendChild(draggable)
} else {
container.insertBefore(draggable, afterElement)
}
})
})
function getDragAfterElement(container, y) {
const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')]
return draggableElements.reduce((closest, child) => {
const box = child.getBoundingClientRect()
const offset = y - box.top - box.height / 2
if (offset < 0 && offset > closest.offset) {
return { offset: offset, element: child }
} else {
return closest
}
}, { offset: Number.NEGATIVE_INFINITY }).element
}
```
```css
body {
font-family: sans-serif;
}
.mainContainer {
padding: 6px 0;
width: 100%;
}
.draggable {
cursor: move;
display: inline-block;
margin: 0 6px;
z-index: 1;
color: #fff;
background-color: #087ee5;
border: 1px solid #0675d6;
border-radius: 4px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
text-align: center;
max-width: 300px;
min-width: 30px;
border-collapse: separate;
vertical-align: middle;
padding-left: 7px;
padding-right: 7px;
padding-top: 10px;
padding-bottom: 10px;
}
.draggable.dragging {
opacity: 0.5;
}
```
```html
<div class="mainContainer">
<p class="draggable" draggable="true">MOVE 1</p>
<p class="draggable" draggable="true">MOVE 2</p>
<p class="draggable" draggable="true">MOVE 3</p>
<p class="draggable" draggable="true">MOVE 4</p>
</div>
```
|
2021/01/22
|
[
"https://Stackoverflow.com/questions/65852340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8133198/"
] |
Add an event listener for the dragables on mouseover.
check if the dragable is already in your hand.
if not than append the Node of the dragable in your hand after the Node with mouseover
change the position of the dragged element to absolute and define its position x & y through top and left
|
23,860,150 |
I have this little simple trigger..
```
BEGIN
DECLARE FILE_NAME VARCHAR(250);
DECLARE FILE_REFR VARCHAR(500);
SET FILE_NAME = 'Foo';
SET FILE_REFR = 'Bar';
--- I'd like to execute the next statement, using variable FILE_REFR between %% in a LIKE clause:
SELECT COUNT(*) INTO @num_rows FROM referers WHERE filename = FILE_NAME AND ref NOT LIKE "%FILE_REFR%";
...
...
...
END
```
Unfortunately, the variable name is not being picked up as a variable.. but as a CHAR, I know there is something missing there.
Help is more than appreciated.. :)
|
2014/05/25
|
[
"https://Stackoverflow.com/questions/23860150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1395287/"
] |
Use the variable as:
```
CONCAT('%', FILE_REFR, '%');
```
So the complete select query is:
```
SELECT COUNT(*) INTO @num_rows FROM referers WHERE filename = FILE_NAME AND ref NOT LIKE CONCAT('%', FILE_REFR, '%');
```
Thanks
|
9,500,907 |
I just tested the TTS feature and I'm really disappointed. While the text is mostly recognizable the quality of the sound is horrible.
There is too much noise and it sounds as if there is a lot of clipping as well. I know that TTS can never be as good as a pre-recorded sound file, but I think I'd be satisfied if at least the clipping could be fixed.
I'd try `KEY_PARAM_VOLUME` but it's only supported since API 11 (I use 8), so I'm not sure if that would fix the clipping issue.
Also I'm pretty sure that if I'm streaming the sound to a file the clipping gets stored as well, so no gain from doing that and then using `SoundPool`to play at a lower volume.
Are there any other ways to improve TTS quality?
|
2012/02/29
|
[
"https://Stackoverflow.com/questions/9500907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1189831/"
] |
You can do
```
myOption map { success } getOrElse handleTheError
```
or with `scalaz`,
```
myOption.cata(success, handleTheError)
```
where `success` is something like
```
def success(op: Whatever) = {
doSomethingWith(op)
Path(request.path) match {
case "work" => println("--Let's work--")
case "holiday" => println("--Let's relax--")
case _ => println("--Let's drink--")
}
}
```
### Update
Your pseudocode
```
x -> y match {
case a -> c => {}
case a -> d => {}
case b => {}
}
```
can be literally translated to scala as
```
(x, y) match {
case (a, c) => {}
case (a, d) => {}
case (b, _) => {}
}
```
It looks nice (and that's probably what you wanted) if inner matcher have only few options (`c` and `d` in this case), but it leads to code duplication (repeating of pattern `a`). So, in general I'd prefer `map {} getOrElse {}`, or separation of pattern-matchers on smaller functions. But I repeat, in your case it looks reasonable.
|
54,654,667 |
I have numeric format of date `20001016083256` and I want to convert it into `datetime` format something like `yymmddhhmiss`.
Expected result is
```
2000-10-16 08:32:56
```
Is that possible in SQL Server?
Thanks a lot
|
2019/02/12
|
[
"https://Stackoverflow.com/questions/54654667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9501823/"
] |
Because `iterations[-1]` will evaluate to `undefined` (which is slow as it has to go up the whole prototype chain and can't take a fast path) also doing math with `NaN` will always be slow as it is the non common case.
Also initializing `iterations` with numbers will make the whole test more useful.
Pro Tip: If you try to compare the performance of two codes, they should both result in the same operation at the end ...
---
Some general words about performance tests:
Performance is the compiler's job these days, code optimized by the compiler will always be faster than code you are trying to optimize through some "tricks". Therefore you should write code that is likely by the compiler to optimize, and that is in every case, the *code that everyone else* writes (also your coworkers will love you if you do so). Optimizing that is the most benefitial from the engine's view. Therefore I'd write:
```
let acc = 0;
for(const value of array) acc += value;
// or
const acc = array.reduce((a, b) => a + b, 0);
```
However in the end *it's just a loop*, you won't waste much time if the loop is performing bad, but you will if the whole algorithm performs bad (time complexity of O(n²) or more). Focus on the important things, not the loops.
|
29,248,748 |
I have two two-dimensional arrays,
```
a = [[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"],
[17368, "I63.9"]]
```
and
```
b = [[17360, "I87.2"],
[17361, "s93.601"],
[17362, "h66.91"],
[17363, "h25.12"],
[17364, "Z51.89"],
[17365, "z00.121"],
[17366, "z00.129"],
[17367, "k55.9"],
[17368, "I63.9"]]
```
I would like to count similar rows in both the arrays irrespective of the character case, i.e., `"h25.12"` would be equal to `"H25.12"`.
I tried,
```
count = a.count - (a - b).count
```
But `(a - b)` returns
```
[[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"]]
```
I need the count as `5` since there are five similar rows when we do not consider the character case.
|
2015/03/25
|
[
"https://Stackoverflow.com/questions/29248748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1896986/"
] |
Instead of `a - b` you should do this:
```
a.map{|k,v| [k,v.downcase]} - b.map{|k,v| [k,v.downcase]} # case-insensitive
```
|
70,579,713 |
We are using default DOF grids to present the data in the database. We are using this function out of the box and we are doing only the required xml configuration.
In some cases, the tables contain several hundred thousand records and the DOF grid does not show any data, it shows only empty page, although it has to load only 400 records (by default) on the page.
We tryed to find a configuration parameter which can be related to this behavior, but without success, and we have no more options, since we are limited to the configuration in this case.
We were not able to find any particular reason for this behavior, or any good resolution of this problem.
|
2022/01/04
|
[
"https://Stackoverflow.com/questions/70579713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17830578/"
] |
The error is because Rust did not infer the type you expected.
In your code, the type of `value` is inferred to be `&i32` because `input` is a reference of a element in `inputs`, and you `push` a `value` later, therefore the type of `stack` is inferred to be `Vec<&i32>`.
A best fix is to explicitly specify the type of stack:
```rust
let mut stack: Vec<i32> = Vec::new();
```
And because `i32` has implemented `Copy` trait, you should never need to clone a `i32` value, if it is a reference, just dereference it.
Fixed code:
```rust
#[derive(Debug)]
pub enum CalculatorInput {
Add,
Subtract,
Multiply,
Divide,
Value(i32),
}
pub fn evaluate(inputs: &[CalculatorInput]) -> Option<i32> {
let mut stack: Vec<i32> = Vec::new();
for input in inputs {
match input {
CalculatorInput::Value(value) => {
stack.push(*value);
}
operator => {
if stack.len() < 2 {
return None;
}
let second = stack.pop().unwrap();
let first = stack.pop().unwrap();
let result = match operator {
CalculatorInput::Add => first + second,
CalculatorInput::Subtract => first - second,
CalculatorInput::Multiply => first * second,
CalculatorInput::Divide => first / second,
CalculatorInput::Value(_) => return None,
};
stack.push(result);
}
}
}
if stack.len() != 1 {
None
} else {
Some(stack.pop().unwrap())
}
}
```
|
2,119,399 |
In an exam there is given the general equation for quadratic: $ax^2+bx+c=0$.
It is asking: what does $\dfrac{1}{{x\_1}^3}+\dfrac{1}{{x\_2}^3}$ equal?
|
2017/01/29
|
[
"https://math.stackexchange.com/questions/2119399",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/411175/"
] |
BIG HINT:
$$\frac{1}{x\_1^3}+\frac{1}{x\_2^3}=\frac{x\_1^3+x\_2^3}{x\_1^3x\_2^3}=\frac{(x\_1+x\_2)(x\_1^2-x\_1x\_2+x\_2^2)}{x\_1^3x\_2^3}=\frac{(x\_1+x\_2)((x\_1+x\_2)^2-3x\_1x\_2)}{(x\_1x\_2)^3}$$
|
12,176 |
What are the best ways to translate `For all you know`?
For example:
>
> For all you know, she could be lying to you.
>
>
> In response to a friend getting upset that her friend isn't picking up her phone, I respond, "For all you know, something could have happened."
>
>
> A neighbor sends us some vegetables and I tell my wife, "We better wash them first, for all we know, they could be covered in pesticide"
>
>
>
|
2015/01/22
|
[
"https://chinese.stackexchange.com/questions/12176",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/3011/"
] |
Agree with StumpyJoePete.
As we all know = Everybody knows.
For all you know = You don't really know for sure.
I think Damian Siniakowicz's suggestion will work.
We better wash the vegetables first, for all we know, they could be covered in pesticide
我们还是先把蔬菜洗一下,说不定有農藥呢。
A couple more suggestions:
我们还是先把蔬菜洗一下,誰知道有沒有農藥呢?
我们还是先把蔬菜洗一下,可能有農藥呢。
|
31,423 |
I'm just starting to use CiviCRM. So I realize that this could be a very dumb question.
I'm trying to deduplicate contacts by name AND surname. When I create a new deduplicating rule using name and surname, it looks like it gets all the contacts with the same name OR surname.
For example, if I have
* Mario Rossi
* Mario Verdi
* Mario Bianchi
* Mario Neri
they are all shown as duplicates...but they are not.
Is there a way to create a rule which addresses just contacts with same name AND surname (or vice versa)?
Thank you in advance.
|
2019/07/19
|
[
"https://civicrm.stackexchange.com/questions/31423",
"https://civicrm.stackexchange.com",
"https://civicrm.stackexchange.com/users/7271/"
] |
Welcome to CiviCRM SE. Eileen's answer is definitely the right place to start, but you might want to look at a related question that I asked about the built-in (reserved) de-duplicate rules, as they aren't entirely clear from the documentation. It says "NAME" in the description, but actually uses the fields "First Name" and "Last Name" (You have used different terminology. It took me a while to work out how it worked.
See [Reserved de-dupe rules](https://civicrm.stackexchange.com/questions/29155/reserved-de-dupe-rules)
Update: Remembering odd behaviour with my previous issues, I looked again and have found that the de-dupe rules appear to be cached. So if you create a rule, adjust it and try with the new version, the old version is still used. I missed this before because I was checking the database and the rule is updated properly there. If you go to Administer >> System >> Cleanup Caches and Update Paths and select Cleanup Caches then try the de-dupe rule again it works as expected. If you were experimenting, then I expect this is the problem.
Alternatively if you delete the rule and add the new version it will also work.
A note on the page where you edit de-dupe rules to tell you to clear the cache would be very helpful. Let me know if this solves your problem and I'll report it as a bug/enhancement.
|
95,071 |
Does anyone know if the house number is included in Mapbox’ vector tiles, and if so how to access it for styling?
|
2014/05/06
|
[
"https://gis.stackexchange.com/questions/95071",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/27171/"
] |
Version 5 of the Mapbox Streets vector tiles includes the house number in a new layer.
I used the following to add them to the starting style:
```
#housenum_label {
text-name: '[house_num]';
text-face-name: @sans;
text-fill: darken(#cde, 20%);
text-size: 9;
}
```
|
12,252,363 |
1) Does LSP also apply to interfaces, meaning that we should be able to use a class implementing a specific interface and still get the expected behavior?
2) If that is indeed the case, then why is programming to an interface considered a good thing ( BTW- I know that programming to an interface increases loose coupling ), if one of the main reasons against using inheritance is due to risk of not complying to LSP? Perhaps because:
a) benefits of loose coupling outweight the risks of not complying to LSP
b) compared to inheritance, chances that a class ( implementing an interface ) will not adher to LSP are much smaller
thank you
|
2012/09/03
|
[
"https://Stackoverflow.com/questions/12252363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1483278/"
] |
>
> Does LSP also apply to interfaces, meaning that we should be able to use a class implementing a specific interface and still get the expected behavior?
>
>
>
LSP applies to the contract. The contract may be a class or an interface.
>
> If that is indeed the case, then why is programming to an interface considered a good thing ( BTW- I know that programming to an interface increases loose coupling ), if one of the main reasons against using inheritance is due to risk of not complying to LSP? Perhaps because:
>
>
>
It's not about an interface or a class. It's about a violation of the contract. Let's say that you have a `Break()` method in a `IVehicle` (or `VehicleBase`). Anyone calling it would expect the vehicle to break. Imagine the surprise if one of the implementations didn't break. That's what LSP is all about.
>
> a) benefits of loose coupling outweight the risks of not complying to LSP
>
>
>
ehh?
>
> b) compared to inheritance, chances that a class ( implementing an interface ) will not adher to LSP are much smaller
>
>
>
ehh?
You might want to read my SOLID article to understand the principle better: <http://blog.gauffin.org/2012/05/solid-principles-with-real-world-examples/>
**Update**
>
> To elaborate - with inheritance virtual methods may consume private members, to which subclasses overriding these virtual methods don't have access to.
>
>
>
Yes. That's good. members (fields) should always be protected ( = declared as private). Only the class that defined them really know what their values should be.
>
> Also, derived class inherits the context from parent and as such can be broken by future changes to parent class etc.
>
>
>
That's a violation of Open/closed principle. i.e. the class contract is changed by changing the behavior. Classes should be extended and not modified. Sure, it's not possible all the time, but changes should not make the class behave differently (other than bugfixes).
>
> Thus I feel it's more difficult to make subclass honour the contract than it is to make class implementing an interface honour it
>
>
>
There is a common reason to why extension through inheritance is hard. And that's because the relationship isn't a true `is-a` relationship, but that the developer just want to take advantage of the base class functionality.
That's wrong. Better to use composition then.
|
15,442,919 |
I've been reading up on SimpleDB and one downfall (for me) is the 1kb max per attribute limit. I do a lot of RSS feed processing and I was hoping to store feed data in SimpleDB (articles) and from what I've read the best way to do this is to shard the article across several attributes. The typical article is < 30kb of plain text.
I'm currently storing article data in DynamoDB (gzip compressed) without any issues, but the cost is fairly high. Was hoping to migrate to SimpleDB for cheaper storage with still fast retrievals. I do archive a json copy of all rss articles on S3 as well (many years of mysql headaches make me wary of db's).
Does anyone know to shard a string into < 1kb pieces? I'm assuming an identifier would need to be appended to each chunk for order of reassembly.
Any thoughts would be much appreciated!
|
2013/03/15
|
[
"https://Stackoverflow.com/questions/15442919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/799575/"
] |
Your code doesn't do what you think it does.
```
ArrayList[][] gridList = new ArrayList[300][150];
```
This first line allocates an `array` of `array` of `ArrayList`.
```
ArrayList al = this.gridList[a][b];
```
This second line retrieves the `ArrayList` at offset `b` in the `array` at offset `a` in the `array` gridList. *You should be aware that your code doesn't initialize either arrays*.
The equivalent type in C++ could be:
```
#include <vector>
#include <array>
std::array< std::array< std::vector<T>, 150>, 300> gridList;
```
where `T` is the type of the element stored in the vectors. Note that Java prior to generics only allowed to define ArrayList without specifying the element type, which is pretty much what your code does. In C++, this parameter is mandatory. The above variable definition will instantiate it for the current scope. you will need to use a `new` statement for a dynamic value (as in Java), and probably wrap it with a smart pointer.
To access an element of the grid, you can use the `[]` operator:
```
vector v = gridList[a][b];
```
Beware that this will trigger a full copy of the `vector` content in the grid at position < a,b > into `v`. As suggested, a more efficient way would be to write:
```
auto const &al = gridList[a][b];
```
Again, the memory model used by Java is very dynamic, so if you want code closer in behaviour to the Java version, you would probably have something like:
```
#include<memory>
typedef std::vector<int> i_vector;
typedef std::shared_ptr<i_vector> i_vector_ptr;
typedef std::array< std::array< i_vector_ptr>, 150>, 300> vector_grid;
typedef std::shared_ptr<vector_grid> vector_grid_ptr;
vector_grid_ptr gridList;
i_vector_ptr al = (*gridList)[a][b];
```
with type `T` being `int`, and each component of the grid type clearly defined. You still have to allocate the grid and each element (ie. `i_vector` here).
|
56,019,584 |
I have a big file with many lines starting like this:
```
22 16052167 rs375684679 A AAAAC . PASS DR2=0.02;AF=0.4728;IMP GT:DS
```
In these lines, `DR2`values range from 0 to 1 and I would like to extract those lines that contains`DR2`values higher than 0.8.
I've tried both `sed` or `awk` solutions, but neither seems to work... I've tried the following:
```
grep "DR2=[0-1]\.[8-9]*" myfile
```
|
2019/05/07
|
[
"https://Stackoverflow.com/questions/56019584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9717188/"
] |
This matches lines with a value greater than *or equal to* 0.8. If you insist on strictly greater than, then I'll have to add some complexity to prevent 0.8 from matching.
```
grep 'DR2=\(1\|0\.[89]\)' myfile
```
The trick is that you need two separate subpatterns: one to match 1 and greater, one to match 0.8 and greater.
|
29,247,002 |
I wanted to make my website and I wanted to add my page what I mad.
So I added some map code to custom page with
"display: inline-block;"
But if I start that page, It disappear like this picture.
```css
element.style {
border: 1px solid rgb(0, 0, 0);
padding: 0px;
width: 800px;
height: 480px;
display: none;
}
```
How can I find which code affected to my code?
Just tell me the way how can I find it.
I need skills plz
|
2015/03/25
|
[
"https://Stackoverflow.com/questions/29247002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4710217/"
] |
Hiding an element can be done by setting the display property to "none" or the visibility property to "hidden". (<http://www.w3schools.com/css/css_display_visibility.asp>)
Try it without the display none:
```
element.style {
border: 1px solid rgb(0, 0, 0);
padding: 0px;
width: 800px;
height: 480px;
}
```
|
2,508,720 |
I'm trying to create JUnit tests for my JPA DAO classes, using Spring 2.5.6 and JUnit 4.8.1.
My test case looks like this:
```
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:config/jpaDaoTestsConfig.xml"} )
public class MenuItem_Junit4_JPATest extends BaseJPATestCase {
private ApplicationContext context;
private InputStream dataInputStream;
private IDataSet dataSet;
@Resource
private IMenuItemDao menuItemDao;
@Test
public void testFindAll() throws Exception {
assertEquals(272, menuItemDao.findAll().size());
}
... Other test methods ommitted for brevity ...
}
```
I have the following in my jpaDaoTestsConfig.xml:
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- uses the persistence unit defined in the META-INF/persistence.xml JPA configuration file -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="CONOPS_PU" />
</bean>
<bean id="groupDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.GroupDao" lazy-init="true" />
<bean id="permissionDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.PermissionDao" lazy-init="true" />
<bean id="applicationUserDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.ApplicationUserDao" lazy-init="true" />
<bean id="conopsUserDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.ConopsUserDao" lazy-init="true" />
<bean id="menuItemDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.MenuItemDao" lazy-init="true" />
<!-- enables interpretation of the @Required annotation to ensure that dependency injection actually occures -->
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
<!-- enables interpretation of the @PersistenceUnit/@PersistenceContext annotations providing convenient
access to EntityManagerFactory/EntityManager -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<!-- transaction manager for use with a single JPA EntityManagerFactory for transactional data access
to a single datasource -->
<bean id="jpaTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- enables interpretation of the @Transactional annotation for declerative transaction managment
using the specified JpaTransactionManager -->
<tx:annotation-driven transaction-manager="jpaTransactionManager" proxy-target-class="false"/>
</beans>
```
Now, when I try to run this, I get the following:
```
SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@fa60fa6] to prepare test instance [null(mil.navy.ndms.conops.common.dao.impl.MenuItem_Junit4_JPATest)]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mil.navy.ndms.conops.common.dao.impl.MenuItem_Junit4_JPATest': Injection of resource fields failed; nested exception is java.lang.IllegalStateException: Specified field type [interface javax.persistence.EntityManagerFactory] is incompatible with resource type [javax.persistence.EntityManager]
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessAfterInstantiation(CommonAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:959)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:329)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:255)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:93)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:130)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:61)
at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:54)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:52)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Caused by: java.lang.IllegalStateException: Specified field type [interface javax.persistence.EntityManagerFactory] is incompatible with resource type [javax.persistence.EntityManager]
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.checkResourceType(InjectionMetadata.java:159)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.(PersistenceAnnotationBeanPostProcessor.java:559)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$1.doWith(PersistenceAnnotationBeanPostProcessor.java:359)
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:492)
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:469)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findPersistenceMetadata(PersistenceAnnotationBeanPostProcessor.java:351)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(PersistenceAnnotationBeanPostProcessor.java:296)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:745)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:448)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(AccessController.java:219)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:168)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:435)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:409)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:537)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:180)
at org.springframework.beans.factory.annotation.InjectionMetadata.injectFields(InjectionMetadata.java:105)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessAfterInstantiation(CommonAnnotationBeanPostProcessor.java:289)
... 18 more
```
It seems to be telling me that its attempting to store an EntityManager object into an EntityManagerFactory field, but I don't understand how or why. My DAO classes accept both an EntityManager and EntityManagerFactory via the @PersistenceContext attribute, and they work find if I load them up and run them without the @ContextConfiguration attribute (i.e. if I just use the XmlApplcationContext to load the DAO and the EntityManagerFactory directly in setUp ()).
Any insights would be appreciated.
|
2010/03/24
|
[
"https://Stackoverflow.com/questions/2508720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136449/"
] |
These are the correct combinations of annotation + interface:
```
@PersistenceContext
private EntityManager entityManager;
@PersistenceUnit
private EntityManagerFactory entityManagerFactory;
```
But when using spring's transaction and entity manager support, you don't need the `EntityManagerFactory` at all.
The reason why you don't need `EntityManagerFactory` is because the creation of the `EntityManager` is responsibility of the transaction manager. Here's what happens in short:
* the transaction manager is triggered before your methods
* the transaction manager gets the `EntityManagerFactory` (it is injected in it), creates a new `EntityManager`, *sets in in a `ThreadLocal`*, and starts a new transaction.
* then it delegates to the service method
* whenever `@PersistenceContext` is encountered, a proxy is injected (in your Dao), which, whenever accessed, gets the current `EntityManager` which has been set in the `ThreadLocal`
|
11,053,878 |
In a Rails 3.2 app, when I call a non-html format on a class - e.g. json, csv, etc - I get an error
```
Template is missing
Missing partial /path/to/template with {:locale=>[:en], :formats=>[:json].....
```
The template is called from a method in the controller.
How can I create a conditional statement in the controller that does something like:
```
if format is html
my_method_that_causes_the_error
end
```
Thanks
|
2012/06/15
|
[
"https://Stackoverflow.com/questions/11053878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/716294/"
] |
```
respond_to do |format|
format.html { my_method_that_causes_the_error }
format.csv { render :something }
end
```
|
14,849,026 |
I'm trying to pass some values through onclick which to me is so much faster. But I need to use some kind of "live" clicking and I was looking into .on() or .delegate(). However, if I do any of those, passing those values within `followme()` seems a little harder to get. Is there some kind of method that I'm not seeing?
```
<div class='btn btn-mini follow-btn'
data-status='follow'
onclick="followme(<?php echo $_SESSION['user_auth'].','.$randId;?>)">
Follow
</div>
function followme(iduser_follower,iduser_following)
{
$.ajax({
url: '../follow.php',
type: 'post',
data: 'iduser_follower='+iduser_follower+'&iduser_following='+iduser_following+'&unfollow=1',
success: function(data){
$('.follow-btn').attr("data-status",'follow');
$('.follow-btn').text('Follow');
}
});
}
```
As you can see, its easier to just pass values from PHP to jQuery... Is there another way?
|
2013/02/13
|
[
"https://Stackoverflow.com/questions/14849026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/659751/"
] |
You can assign more data values, and you know what use is logged in, all you need is to pass who to follow:
```
<div class='btn btn-mini follow-btn'
data-status='follow'
data-who='<?php echo $randId; ?>'
id='followBTN'>
Follow
</div>
<script>
$('#followBTN').on('click', function(){
$.ajax({
url: '../follow.php',
type: 'post',
data: {
iduser_following: $(this).attr('data-who')
},
success: function(data){
$('.follow-btn').attr("data-status",'follow');
$('.follow-btn').text(data.text);
}
});
});
</script>
```
You can process `$_SESSION['user_auth']` and the status directly from PHP, there is no need for you to pass them in jQuery. Make sure `document` is ready when you insert `on` click event.
|
26,821,797 |
Please advise me why I can't create this example in my home html file?
Here is an example from the [site](http://jsfiddle.net/eM2Mg/) and my html file:
```
<head>
<script src="http://dygraphs.com/dygraph-dev.js"></script>
<script>
g = new Dygraph(document.getElementById("graph"),
"X,Y,Z\n" +
"1,0,3\n" +
"2,2,6\n" +
"8,14,3\n",
{
legend: 'always',
animatedZooms: true,
title: 'dygraphs chart template'
});
</script>
<style>
.dygraph-title {
color: gray;
}
</style>
</head>
<body>
<div id="graph"></div>
</body>
```
what am I doing wrong?
|
2014/11/08
|
[
"https://Stackoverflow.com/questions/26821797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3731374/"
] |
javascript script must be after div or you need to use document ready to load body first and then script
```
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://dygraphs.com/dygraph-dev.js"></script>
<style>
.dygraph-title {
color: gray;
}
</style>
</head>
<body>
<div id="graph"></div>
<script>
g = new Dygraph(document.getElementById("graph"),
"X,Y,Z\n" +
"1,0,3\n" +
"2,2,6\n" +
"8,14,3\n",
{
legend: 'always',
animatedZooms: true,
title: 'dygraphs chart template'
});
</script>
</body>
</html>
```
|
17,955 |
Just like it says in the title, how can I store blocks of cheese for max shelf life? I will be making a grilled cheese sandwich and shredding 3 varieties of cheese (cheddar, swiss, parm(?)) and I am afraid that I won't be able to use three whole blocks on one sandwich.
|
2011/09/23
|
[
"https://cooking.stackexchange.com/questions/17955",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/3818/"
] |
Hard, aged cheeses like cheddar and Parmesan are fine to freeze, particularly if you're going to be melting them when you get around to using them anyway. Freezing causes ice particles to break up the molecules of the cheese, and when they thaw, they leave holes in what was (prior to freezing) a pretty smooth cheese. So you might notice if you freeze blocks of cheese, they are more crumbly when you unfreeze them than they were when you bought them. The cheeses you're working with should be fine if stored properly, but softer / creamier cheeses (brie, harvarti, etc.) might become somewhat unpleasant if you freeze them.
As far as storage is concerned, you can actually do one of two things:
1. Grate the cheese before you freeze it. All you need to do for this method is grate your cheese and put it in a ziploc freezer bag (thicker than a regular zip-top bag). Just make sure to squeeze the air out before sealing, and seal it well.
2. Freeze the cheese in blocks. Wrap them in plastic wrap and then put then in a ziploc bag, and you should be all set; it'll keep for 4-6 months. ([source](http://food.unl.edu/web/fnh/food-facts#canufreeze))
No matter which method you use, you may notice a slight change in texture. Make sure you thaw the cheese before using it. (Though I've put frozen shredded mozzarella on pizza and frozen shredded Mexican cheese blend - a blend of cheddar, monterey jack, queso blanco and asadero - on tacos and not had any trouble.)
|
58,720,960 |
We can use @Input as passing input props or data. We also can use `<ng-content>` to dump a load of html into the children component. Is there any way to pass html as Input. Like @Input html1, @Input html2, and use them in the child class component?
Suppose I have this html in child class:
```
<div class='wrapper'>
<div class="content1 exclusive-css-defined-to-this-component">
<div>{$content1}</div>
</div>
<div class="content2 exclusive-css-defined-to-this-component-2">
<div>{$content2}</div>
</div>
</div>
```
And I want to pass $content1 & $content2 as input.
|
2019/11/05
|
[
"https://Stackoverflow.com/questions/58720960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7055636/"
] |
I have found the solution, this can be done by:
```
<div class='wrapper'>
<div class="exclusive-css-defined-to-this-component">
<div><ng-content select="[content1]"></ng-content></div>
</div>
<div class="exclusive-css-defined-to-this-component-2">
<div><ng-content select="[content2]"></ng-content></div>
</div>
</div>
```
And we can use the component like:
```
<wrapper>
<div content>Any thing you want to put in content1</div>
<div content2>Any thing you want to put in content2</div>
</wrapper>
```
|
988,032 |
I need to write a script which writes to a file how many times this script has been executed.
How can I do that?
|
2017/12/20
|
[
"https://askubuntu.com/questions/988032",
"https://askubuntu.com",
"https://askubuntu.com/users/773615/"
] |
I assume you want to have a single file `countfile` that only contains one single number representing the execution counter.
You can read this counter into a shell variable `$counter` e.g. using one of these lines:
* ```
read counter < countfile
```
* ```
counter=$(cat countfile)
```
Simple integer additions can be done in Bash itself using the `$(( EXPRESSION ))` syntax. Then simply write the result back to our `countfile`:
```
echo "$(( counter + 1 ))" > countfile
```
You should probably also safeguard your script for the case that `countfile` doesn't exist yet and create one initialized with the value 1 then.
The whole thing might look like this:
```
#!/bin/bash
if [[ -f countfile ]] ; then
read counter < countfile
else
counter=0
fi
echo "$(( counter + 1 ))" > countfile
```
|
420,325 |
**Problem: It's a common problem for "NON-inverter" type microwave ovens to pop circuit breakers**, and mine is no exception.
**UPDATE Jan 2021: Extension / power strip added, (mentioned below) has still eliminated this problem completely! I think I've only popped that breaker once in two years.** Fascinating as this subject was, I'm done. Note that both virtually identical KitchenAid microwaves popped that breaker, but the other same sized circuit breaker circuit, (slightly longer than this run's 1 foot away from the main panel), has never popped the breaker with either microwave. So, AFAIK, this problem has been confirmed as a design defect, and not a malfunction, on a circuit that is on an unusually short run. And further, the added small amount of impedance added, eliminated these design symptoms.
There could be a huge number of reasons for this. Even though I thought I had really researched microwave ovens extensively, have replaced magnetrons in two nearly identical ovens, I found this one resource that taught me more than I had ever known. It covers design goals, troubleshooting, and things you'd never know, unless you both designed these ovens and also repaired them as a full time job:
[Notes on the Troubleshooting and Repair of Microwave Ovens](https://repairfaq.org/sam/micfaq.htm), written and compiled by Sam Goldwasser. I highly suggest you read it carefully. It will likely save you a ton of time, even if you are a master IEEE designer.
Based on what I've learned, I have new questions and new concerns:
**-- Using an add-on power strip could be dangerous, if not properly designed.** (This "fixed", masked or worked around other problems for me.) My strip is well built and I'm not concerned. But be aware that the magnetron is 5000v hot on one side, and grounded directly to the case. Lose the ground and /or a lousy partially floating neutral, (which I've seen before), and you could get killed from the case becoming some fraction of 5,000 VAC, through you to earth ground.
I've got two identically designed ovens, both of which deliver the same solid 700W, computed from testing heating water. (Litton manual says 1 liter 1 minute -->> deg C x 70 = Watts -- mine 18 f = 10 c x 70 = 700 watts). So, I doubt if I have a shorted diode, or have lost some turns in my transformer. But, arcing in the transformer itself, the triac, the diode, the capacitor becoming weak and things going on inside the magenetron, the waveguide itself, food buildup; these and many more factors can ALL affect performance, and can affect the startup and continuous draw of the oven. Inverters just would add to the complexity of determining what's really happening, since adding a switching power supply can add a set of different problems.
Before I added the power strip, throwing the breaker seemed to be getting worse, which could mean that the 20A breaker itself is getting weaker, (which I'd rather not replace). I had replaced magnetrons in two nearly identical ovens, and understand the specific designs of both, which I don't intend to modify at all. It seems to me that the bleed resister across the capacitor that discharges it, (and *does* work), does a "great job", as intended. But other people have said that this means that startup draw, to charge that capacitor, is the cause of about an extra 5-10A on a 10A microwave, for the short startup time.
Again though, I'd like to add something external to the oven, without opening the case, which might then work for many that have the heavy transformer and not an inverter switched power supply type oven.
My goal would be to design an add-on device that would limit the voltage / current for 0.1-0.5 seconds while the microwave is charging that capacitor (which doubles the DC voltage AFTER it is fully charged). On most ovens, I would guess that the control board's filter capacitor should keep that operational with just a very short term voltage drop, even if a substantial voltage drop to its power supply.
In a standard oven, there's a huge and heavy transformer that is serving as a huge inductor, fed with normal 120 Vac, usually using a solid state triac as a switch. (Panasonic, Sharp and many others use inverter power supplies.)
**SIMPLE solution, that has so far, *works!***
**SEE cautions about adding this, mentioned above!!**
Adding a simple 6-8 FT AWG 14 extension cord to the circuit seems to have fixed the problem. As @Charles Cowey suggested, my oven is plugged into a circuit that is literally one foot from the breaker box. It seems cold weather reduces AC use, increases the available line voltage enough, and puts this right at the edge.
I will have to open the power strip [and report back] to see if there are some added inductors inside. (AWG 14 has an impedance @60 HZ of only 3 ohms / DC resistance 2.5 ohms per 1000 feet. So ~.03 ohms added to an effective 12 ohm oven doesn't seem significant enough to fix it. Ref.: [AC/DC Chart / pub. by Anexter](https://www.anixter.com/content/dam/Anixter/Guide/7H0011X0_W&C_Tech_Handbook_Sec_07.pdf) ) In any case, if building a universal solution as inexpensively as possible, it seems that simply **CHOOSING a good surge protector with an added torroid coil inside, (which I have seen), should solve most of these problems.**
"Older ovens with large transformers" (by @Charles Cowey) implies that standard designs have changed, perhaps to switching supplies?? IF so, am I solving a problem that will be phased out in the next decade?
**OTHER Possible solutions?:**
**NOTE -- EXPERIMENTALLY rewiring that 120/240 VAC circuit feed is NOT a good idea--Do it wrong and you could get a 5000 V shock!**
**1.2 ohm resistor, in-line, before oven's 120 V ordinary line cord**
One simple method might be to simply add an in-line resistor. A 10A microwave @ 120 V is drawing 1200 W, with an effective impedance of 12 ohms. Simply adding a ~1.2 ohm resistor in series would cut the voltage/power by 10%, as well as the surge power, which is tripping breakers, which might do the job. While running of course, that resistor would be creating the heat of a 100 W lightbulb.
**Lightbulb: NO!**
Unfortunately, I need a lightbulb to use as a resister, which would have less resistance as it heats up, which of course incandescent bulbs do not. Nevertheless, this would be the perfect inexpensive method to use as the main component of this device.
**??**
**So, what could I build that would accomplish this??**
What I need is a resistor that starts as a 12 ohm resistor and becomes a 1.2 ohm resistor, or less.
**After research, there are inexpensive ($5 for 2) NTC (Negative Temp. Coefficient) devices that do ICL (Inrush Current Limiting). Unfortunately, they work by heating, and won't cool in less than 30 seconds, and so won't work** in ovens that cycle on and off every 6 seconds (@ 50% power setting).
[Amtherm company focuses on RTC devices and designs](https://www.ametherm.com/), and seem to be the best resource for designing circuits that utilize RTCs.
As a sidenote, these NTCs are using in virtually all of today's variable speed motors used commonly in HVAC systems. These RTCs often fail, and commonly the AC tech unknowingly recommends replacing the whole motor at a cost of > $1,000 rather than the < $5 RTC replacement!
|
2019/02/03
|
[
"https://electronics.stackexchange.com/questions/420325",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/211801/"
] |
In an older model microwave with a huge heavy transformer, the inrush current may be due to the transformer saturating when power is switched on at the peak of the voltage waveform. If that is the case, very little additional impedance may be required. I have seen the problem in a location where the distribution panel was in the basement directly below the kitchen counter. There may have been only about six feet of wire between the circuit breaker and the microwave. In that case, the problem was solved by replacing the standard 20-amp breaker with a 20-amp, high magnetic trip breaker.
It is possible that only a tiny impedance to the power feed, perhaps 15 feet of 12 AWG cable may be sufficient.
|
63,598,072 |
I have a deeply nested JSON document that is variable length and has variable arrays respective to the document, I am looking to unnest certain sections and write them to BigQuery, and disregard others.
I was excited about Dataprep by Trifacta but as they will be accessing the data, this will not work for my company. We work with healthcare data and only have authorized Google.
Has anyone worked with other solutions in GCP to transform JSONs? The nature of the document is so long and nested that writing a custom Regex and running it on a pod before ingestion is taking significant compute.
|
2020/08/26
|
[
"https://Stackoverflow.com/questions/63598072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12928451/"
] |
You can try this:
**[1] Flatten the JSON document using `jq`:**
```
cat source.json | jq -c '.[]' > target.json
```
**[2] Load transformed JSON file (using `autodetect`):**
```
bq load --autodetect --source_format=NEWLINE_DELIMITED_JSON mydataset.mytable target.json
```
**Result:**
>
> BigQuery will automatically create RECORD (STRUCT) data type for nested data
>
>
>
|
32,631,274 |
```
#!/usr/bin/env perl
use strict;
use warnings FATAL => qw ( all );
my ( $func, @list, $num );
$func = sub {
print $num // "undef"; print "\n";
};
@list = ( 1,2,3 );
foreach $num ( @list ) {
$func->();
};
```
This piece of perl prints
```
undef
undef
undef
```
instead of
```
1
2
3
```
The `$func` routine can see `@list`, so why not `$num`?
|
2015/09/17
|
[
"https://Stackoverflow.com/questions/32631274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1717295/"
] |
Because `foreach` loops implicitly localise their iterator variables.
See: [`perlsyn`](http://perldoc.perl.org/perlsyn.html#Foreach-Loops)
>
> The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. If the variable is preceded with the keyword my, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my, it uses that variable instead of the global one, but it's still localized to the loop. This implicit localization occurs only in a foreach loop.
>
>
>
But really - this doesn't come up often, because it's really bad form to do any sort of messing around with a loop iterator from outside. Narrow down your scope, and pass variables around to avoid bugs and troubleshooting pain.
|
307,168 |
Why I can't feel the actual speed of plane when the plane in the sky? I mean I cannot judge how fast the plane is going in terms of the light on the ground and I feel it is flying so slow. How can I explain this mismatch?
|
2017/01/24
|
[
"https://physics.stackexchange.com/questions/307168",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/118807/"
] |
You do not feel speed, you only feel acceleration, or other forces, like those from the wind on your face - and you cannot feel that in a plane.
So you do feel something when the plane is accelerating, taking off, sometimes when it banks, or in bad weather.
But a plane's speed is typically steady, unchanging, for most of the trip.
When changes in the plane's motion occur they are relatively small (except for very bad weather, jet stream turbulence and the like ). The plane's motion is normally kept within reasonable acceleration rates for the precise reason to avoid passenger discomfort (and to avoid excessive stress on the airframe).
So you're in a system that's designed to minimize your sensation of motion.
As you're high up, you cannot see how fast the plane's ground speed is. The closer you are to a passing object, the faster you think you're going. You're not close to the ground so it almost drifts by.
A similar effect is why some people experience more fear when driving that others. They concentrate on the road surface near their car and it gives a greater impression of speed than the place they should be looking (further ahead). You might also notice it if you were on a skateboard and compared the sensation of speed when standing to that when kneeling.
The speed doesn't change, but your brain picks up different clues to motion and interprets them as different speeds. In a high flying plane there are no obvious speed clues so your brain can interpret that as not moving fast.
|
203,057 |
I just realized that both seems to mean the same thing. However, I am not sure if this is something that's context-dependent or not. What do you think?
For example:
>
> I pressed and used the buttons at the right time and in the right
> combination.
>
>
> I pressed and used the buttons at the right time and with the right
> combination.
>
>
>
|
2019/03/30
|
[
"https://ell.stackexchange.com/questions/203057",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/91596/"
] |
Interesting question! I've never thought about this before.
This might depend on the individual and the dialect, so I will only be answering for myself and Australian English.
**In** a combination is used to describe a series of actions (for example, pressing buttons) being done in a particular order. The actions themselves are the combination.
>
> I pressed the buttons in the right combination.
>
>
>
**With** a combination is used to describe an action (for example, opening a lock) that needs to *use* a combination (a particular sequence). The action is not part of the combination.
>
> I opened the lock with the right combination.
>
>
>
So in your question, **"in the right combination" is correct.**
|
5,095,525 |
After discovering jQuery a few years ago, I realized how easy it was to really make interactive and user friendly websites without writing books of code. As the projects increased in size, so did also the time required to carry out any debugging or perhaps implementing a change or new feature.
From reading various blogs and staying somewhat updated, I've read about libraries similar to [Backbone.js](http://documentcloud.github.com/backbone/) and [JavascriptMVC](http://www.javascriptmvc.com/) which both sound like good alternatives in order to make the code more modular and separated.
However as being far from an Javascript or jQuery expert, I am not really not suited to tell what's a good cornerstone in a project where future ease of maintainability, debugging and development are prioritized.
**So with this in mind - what's common sense when starting a project where Javascript and jQuery stands for the majority of the user experience and data presentation to the user?**
Thanks a lot
|
2011/02/23
|
[
"https://Stackoverflow.com/questions/5095525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198128/"
] |
Both Backbone.js and JavascriptMVC are great examples of using a framework to organize large projects in a sane way ([SproutCore](http://www.sproutcore.com/) and [Cappuccino](http://cappuccino.org/) are nice too). I definitely suggest you choose a standard way of deal with data from the server, handling events from the DOM and responses from the sever, and view creation. Otherwise it can be a maintenance nightmare.
Beyond an MVC framework, you should probably choose a solution for these problems:
* Dependency management: how will you compile and load javascript files in the right order? My suggestion would be [RequireJS](http://requirejs.org/).
* Testing: testing UI code is never easy but the guys over at jQuery have been doing for a while and their testing tool [QUnit](http://docs.jquery.com/Qunit) is well documented/tested.
* Minification: you'll want to minify your code before deploying to production RequireJS has this built in but you could also use the [Closure Compiler](http://code.google.com/closure/compiler/) if you want to get crazy small source.
* Build System: All these tools are great but you should pull them all together in one master build system so you can run a simple command on the commandline and have you debug or production application. The specific tool to use depends on your language of choice - Ruby => [Rake](http://rake.rubyforge.org/), Python -> Write your own, **NodeJS** as a build tool (i like this option the most) -> [Jake](https://github.com/jcoglan/jake)
Beyond that just be aware if something feels clunky or slow (either tooling or framework) and refactor.
|
71,084,990 |
I have this question and I haven't found specific documentation to confirm the behavior and am unaware of how to manually check this myself.
Consider I have table A with b\_id foreign key to table B. If I run an update on a row in table A, does mysql always run the foreign key constraint check on table B even if A's b\_id goes unchanged or isn't passed in the update statement? such as `(select 1 from B where id = ?)`
Example:
`UPDATE A set A.name = "x", A.b_id = 1 where A.id = 1` I know this runs the foreign key check on B
`UPDATE A set A.name = "x" where A.id = 1` But does this also run the foreign key check even though b\_id goes unchanged since it was not passed?
`UPDATE A set A.name = "x" A.b_id = A.b_id where A.id = 1` And what about this? b\_id gets passed in with same existing value. Does the fk check run?
Any supporting documentation or help would be appreciated, as well as tips on how I can test this sort of behavior myself since using EXPLAIN doesn't help.
Edit: this is for INNODB engine and mysql 8.0
|
2022/02/11
|
[
"https://Stackoverflow.com/questions/71084990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3509128/"
] |
Foreign key integrity is checked always when the server detects that the data is changed by fact and needs in save to the disk. It is checked after all BEFORE UPDATE triggers execution (rather than data type check which is performed each time, before and after each separate trigger).
The reason is simple. Server does not store any flag which marks does the value is changed - it is more expensive than direct compare before real, physical, UPDATE execution. The value changing is not tracked. Server does not know does the value to be saved during the update is provided by the query text or, for example, is provided by one of the BEFORE UPDATE triggers in the trigger chain.
[small DEMO](https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=94451d3db69ecf964d682c81ad0e565a)
|