text:
Q: Is nested comprehensive - non optimized in Python? The question is: "Have I really to do handmade optimization or exists better explaining of this uncomprehensive comprehensive?"
Thanks! And please - don't minus my question... Even FORTRAN can optimize nested loops since 1990... or earlier.
Look the example.
dict_groups = [{'name': 'Новые Альбомы', 'gid': 4100014},
{'name': 'Synthpop [Futurepop, Retrowave, Electropop]', 'gid': 8564},
{'name': 'E:\\music\\leftfield', 'gid': 101522128},
{'name': 'Бренд одежды | MEDICINE', 'gid': 134709480},
{'name': 'Другая Музыка', 'gid': 35486626},
{'name': 'E:\\music\\trip-hop', 'gid': 27683540},
{'name': 'Depeche Mode', 'gid': 125927592}]

x = [{'gid': 35486626},{'gid': 134709480},{'gid': 27683540}]

Have to receive
rez = [{'name': 'Другая Музыка', 'gid': 35486626},
{'name': 'E:\\music\\trip-hop', 'gid': 27683540},
{'name': 'Бренд одежды | MEDICINE', 'gid': 134709480}]

One of the solutions is:
x_val = tuple(d["gid"] for d in x)
rez = [dict_el for dict_el in dict_groups if dict_el["gid"] in x_val]

with timing
%timeit x_val = tuple(d["gid"] for d in x)
1.55 µs ± 81.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit [dict_el for dict_el in dict_groups if dict_el["gid"] in x_val]
2.19 µs ± 93.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

one-row nested comprehensive solution gives:
%timeit [dict_el for dict_el in dict_groups if dict_el["gid"] in tuple(d["gid"] for d in x)]
11.9 µs ± 756 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

This is much slower! Its looks like expression tuple(d["gid"] for d in x) calculates each time!
7*1,55 + 2,19 = 13,04µs   It's near the 11.9µs....


text:
Q: Relations vs data constraints in database design To simplify the description let's assume we've got a DB model with TimeScopes (ID, start, end) and Processes with FK (TimeScopes.ID), and this is one-to-many relation where all processes holding a reference to the TimeScopes.ID are running within the given time scope.
So first, you define a single time scope and pick multiple processes running at that time scope.
TimeScopes
  |__
     Processes

There are some additional constraints in the application (no DB triggers in the DB so far), like assumptions that TimeScopes are not overlapping - only one TimeScope could be active at the time.
Now I've got a new requirement to add some new Processes that could be initiated at any moment in time without any constraint - so effectively they do not have to, but they could be running simultaneously at the same time (in parallel).
In this case, someone would define the process first and then assign it to such a new, single Process multiple time scopes without a constraint mentioned earlier. So this would be quite the opposite relation one Process to many TimeScopes.
Processes
  |__
     TimeScopes

I'm looking for help and advice on how to solve it?
From the relations perspective, I can adjust the relation between TimeScopes and Processes to many-to-many by adding a table to define relations in both directions.
TimeScopes
  |__
   __ TP-Relations
  |
Processes

What makes me uncertain about that is the additional time constraint from the existing model. That drives me to think about an alternative solution and define maybe a separate tables for NewProcesses and NewTimeScopes
NewProcesses
  |__
     NewTimeScopes

and later combine results between two models in queries by use of UNION statement.
Which seems to be better? Any other or better ideas?
Update/Rephrase the question
Let's say we've got Entities "A" and "B" in many-to-many relation made with additional "AB" (junction) table.
For some records representing A->B in 1-to-many relation, there are some additional constraints about the A records. Let's say we've got some triggers to watch each record in A doesn't cross the boundaries of another A record.
For other records representing B->A in 1-to-many relation these boundaries are not always acceptable so shouldn't be forced/checked.
Question: How to deal with such a problem?

*

*Modify the model/relations, how?

*Modify the triggers? but is it even possible on the DB level to recognise that some records would be entered for A->B vs B->A relations?

A: Based on the comments, it appears the following is true:

*

*A timescope can have many processes

*A process can belong to many timescopes

*A timescope should not have an overlapping start or end with another timescope if the timescope has more than one process.

I would separate this out into two questions:
How should I model the relationship between process and timescope?
It seems that this is a straightforward many-to-many relationship, so I would include a joining table as you suggest.
How should I ensure the business rule about overlapping timescopes?
I don't think you can enforce this through the entity relationships in your model. You then have a few options - if you must implement it at the database level, a trigger on the relation table should do the job - your rule applies only if there is more than 1 process for a given timescope, which will cause an insert or update event on your join table.
I am not a huge fan of triggers - they are hard to test, hard to debug, and can lead to performance problems. If at all possible, I'd implement this in the application layer.
Should you store different types of timescopes/processes in different tables?
This is partly philosophical, partly practical. In general, you should store similar types of entity in the same table. Especially if they vary in behaviour, but not attributes; don't repeat yourself and all that.
If you have different validation rules, but identical attributes, I'd keep them in a single table.
This is all subject to "understandability" - if your system describes mammals, keeping "humans" and "cats" in the same table with a type discriminator is probably fine. If your system describes "humans" and "tables", the fact that both have "leg_count" attributes is not a reason to keep them in the same table.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I want to capture a screenshot of an element with tooltip using selenium I want to capture the tooltip of Business menu using Selenium JAva..I used javascript and action class to mouse over, but failed to capture the tooltip... Below is my part of code..Any help is appreciated...
the web is "https://www.rediff.com/news"..Sel
By tooltip = By.xpath("/html/body/div[5]/div[1]/ul/li[3]/a");
        String TP_realtime = driver.findElement(tooltip).getAttribute("title");
        System.out.println("Tooltip is " + TP_realtime );

        WebElement realtime = driver.findElement(tooltip);

        js.executeScript("arguments[0].scrollIntoView();", realtime);
        Thread.sleep(1000);
        action.moveToElement(realtime).build().perform();
        Thread.sleep(6000);
        utils.HelperFunctions.captureScreenShot(driver, filename2);


text:
Q: If $\tau$ is strictly finer than the standard topology $\tau_{st}$ on $\mathbb{R}$, prove their difference $\tau \setminus \tau_{st}$ is uncountable I think I have a proof, but it's a little convoluted.
Since $\tau$ is strictly finer than than $\tau_{st}$, there is an open set $U \in \tau$ such that $U \notin \tau_{st}$. For every $x \in \mathbb{R}$, the sets $U \cup (-\infty, x+1) $ and $U \cup (x, +\infty)$ are both open in $\tau$. However, at most one of the two can be in $\tau_{st}$. For the sake of contradiction, assume both are in $\tau_{st}$, then so is their union, which is $U$, which cannot be true. Thus for every $x \in \mathbb{R}$ we have constructed at least one set open in $\tau$ which is not in $\tau_{st}$, proving their difference is not countable.
Is this correct? Can it be done easier?

A: Instead of the sets you are considering look at $U\setminus \{x\}$ for $x \in \mathbb R$.  You can see that $U\setminus \{x\}\neq U\setminus \{y\}$ whenever $x,y \in U$ and  $x \neq y$ ; also $U\setminus \{x\} \in \tau_{st} $ for at most one  $x$  (because $U =U\setminus \{x\})\cup U\setminus \{y\}))$ for $x \neq y$ and $U\setminus \{x\} \in \tau $ for all $x$.  When $U$ is countable consideration of the intervals $U \cup (x,x+1)$ can be used. I leave the details to you.


text:
Q: IIS Server Farm Health API? we have a Windows Server 2008 R2 running 4 virtual servers on a Server Farm, but currently the only way we're able to check the health of the servers is by RDP'ing on to the server that manages them and going into IIS. We would like to be able to have a webpage where we can see the healf of the servers and see which ones are available or unavailable.
Is there a way for us, to interact with the server (potentially via an API) and get information about the servers in our C# code?

A: There are plenty of performance counters at your disposal for monitoring IIS and related services remotely:

*

*Web Service Counters for the WWW Service

*Internet Information Services Global Counters

*Performance Counters for ASP.NET
You can check out these counter values through windows's Performance Monitor, which provides a fair user interface, or use the following C# code to develop your own monitoring tool:
var category = "Web Service";
var counter = "Current Connections";
var instance = "_Total";
var server = "192.168.0.1";

var perf = new PerformanceCounter(category , counter , instance , server);

int connections = (int)perf.NextValue();


text:
Q: Azure pipeline: exclusive lock sequential not locking jobs from other runs I have a Pipeline like:
lockBehavior: sequential
stages:
  ...

Inside the pipeline I have in the same stage jobs executed in the same computer, let's say job1->computer1 job2->computer1.
If After a first run, let's say run1, I ran the pipeline again run2 before that run1->job1 is finish, then run2->job1 is executed before run1->job2.
Is this a bug or am I missing something in the exclusive lock behaviour? Do I need to specify an environment instead of the computer directly?
Thanks a lot in advance.
I was expecting the lock to change the behaviour but the result is identical to not having a lock. The result is also the same if I place the lock inside the stage with the jobs.

A: To use exclusive lock check with sequential deployments or runLatest, follow these steps:
1.Enable the exclusive lock check on the environment (or another protected resource).
2.In the YAML file for the pipeline, specify a new property called lockBehavior. This can be specified for the whole pipeline or for a given stage.
Please refer to doc:Support for sequential deployments when using exclusive lock checks
Checks are used to control the execution of stages on protected resources:Protected resources
Please enable this with the target protected resource first.
Agent pool example:

Variable group example:

I test my pipeline with protected resource: variable group and it works. The run2 didn't execute until run1 finished and released protected resource.


text:
Q: wordpress user metadata not saving I'm using the strip connect api with wordpress, and I've managed to set up the flow to connect a user, and get their access token and userid. However, I need to save this in a way that's connected to the wordpress user, as I need to be able to come back and reference the code later, in order to allow the correct person to be paid. I wrote added a couple lines with add_user_meta() but my var_dump() comes out null. here's the some of the code:
global $wpdb;
$table = $wpdb->prefix."stripe_connect";

$wpdb->insert($table , array(
  'time'                    => current_time('mysql'),
  'access_token'            => $token,
  'stripe_publishable_key'  => $key,
  'stripe_user_id'          => $userid)
);

$user_ID = get_current_user_id();
add_user_meta($user_ID, 'stripe_userid', $userid, $unique);
add_user_meta($user_ID, 'stripe_token', $token, $unique);

$stripeuserid = get_user_meta($user_ID, 'stripe_userid', true);

var_dump($stripeuserid);

$response = '
Thank you for connecting with Stripe. This information has been saved in the database and can be viewed in the Admin Panel.
';

A: I figured it out, it had nothing to do with the way I was adding the data. The problem was with retrieving it.
This fixed it:
$user_ID = get_current_user_id();
update_user_meta($user_ID, 'stripe_userid', maybe_serialize( $userid ));
add_user_meta($user_ID, 'stripe_token', $token, $unique);

$stripeuserid = get_user_meta($user_ID, 'stripe_userid');

var_dump($stripeuserid);


text:
Q: Find the value of $x$, for which the function $h(x) = \frac 1{(x-5)^2+4(x-5)+4}$ is undefined Picture of problem
I'm having an issue with a simple SAT question. If you can't see from the picture, I'm being asked to find the value of $x$, for which the function:
$$h(x) = \frac 1{(x-5)^2+4(x-5)+4}$$
is undefined.
I figured that for it to be undefined, it should be equal to 1/0. This therefore means that $(x-5)^2+4(x-5)+4 = 0$. I further simplified it into
$$(x-5)((x-5)+4) = 0$$
However, this gives me either $x = 1$ or $x = -3$, both of which are false. The answer is $3$. Why do I get $-3$, when the answer is $3$?

A: You factorised the denominator incorrectly, leaving out the $+4$ term. The correct factorisation is  $(x-5+2)(x-5+2) = 0$, or equivalently $(x-3)(x-3) = 0$.

A: We can use $(a+b)^2=a^2+2ab+b^2$.
By this formula we get  $$(x-5+2)^2=0$$ or
$$x-5=-2$$ or $$x=3$$

A: HINT: your denominator can be written as $$(x-5)^2+4(x-5)+4=(x-3)^2$$

A: Ahhh, I see what you are doing. In reply to user476879, you said:

If (x-5)((x-5)+4) = -4
  then (x-5)(x-1) = -4
  in that case it's either x-5=-4 or x-1=-4
  neither of which are correct (respectively leading to x=1 or x=-3)

Nope. You can't solve for x like that. You have to get one side of the equation to equal zero first. It can't be -4, -10, 200, or anything else. It's got to be zero. Only once you get it to zero can you solve for what value of x will make it zero.
If you don't understand, please post again because this misunderstanding will cause you to have troubles with many many more SAT problems. Good Luck on it!

A: First of all, kudos to you for correctly identifying that what you need to do is find the value of $x$ that makes the denominator equal to 0. It appears to me that that this problem is designed to test the SAT taker on two components - the first being the ability to identify that $h(x)$ is undefined if and only if the denominator is equal to 0, and the second being the ability to solve algebraically for which $x$ value will make the denominator equal to 0.
All of the other correct answers certainly sufficient, but I am going to provide my method of solving as well. It is semantically no different from the other correct solutions, just different syntax, but I imagine you are in high school and when I was in high school some methods of solving equations did not click well for me and others did, so I will provide mine just in case it is the one that works for you.
$$(x-5)^2 + 4(x-5) + 4 = 0\\
\implies x^2 - 10x + 25 + 4x - 20 + 4 = 0\\
\implies x^2 - 6x + 9 = 0.$$
From here, someone with a good eye would catch that $$x^2 - 6x + 9 = (x-3)^2,$$
thus the unique solution to our problem is $x = 3$. However if a student is not as skilled in spotting factorizations, it would be just as easy to recall the quadratic equation:
$$ax^2 + bx + c = 0 \iff x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}, \hspace{4mm} \text{(for } a \text{ not = 0)}$$
and use this to arrive at
$$x = \frac{6 \pm \sqrt{6^2 - 4(1)(9)}}{2} = \frac{6 \pm 0}{2} = 3.$$
This answer may seem too long for the SAT where speed matters - but that is only because I was verbose in explanation. When I initially used this method to solve your problem on paper by hand it probably took about 15 seconds.
Hope you find the answer that works for you here on MSE and good luck on your SAT!

A: Set $y:= (x-5)$,  the denominator reads:
$D(y) = y^2 + 4y + 4$,
Consider the function $H(y): = \dfrac{1}{D(y)}$.
$H(y)$ is not defined for $y$ values with $D(y) =0$.
Find the zeroes of $D(y)$:
$D(y) = y^2 + 4y +4 =0$.
Note:
$D(y) = y^2 + 4y +4 = (y+2)^2 = 0$.
Hence $y = -2$ is excluded:
Domain of $H(y): \mathbb{R}$ \ {$-2$}.
Proceed to exclude the corresponding $x$ value, recall $y=x-5,$ from the domain of the original function $h(x)$.

A: The denominator has to be zero for the chosen $x$ values of course;
$(x-5)^2+4(x-5)+4=0$
We can name $(x-5)=a$ to make things easier.
$a^2+4a+4=0$
That is a perfect square;
$(a+2)^2=0$
$a=-2$ so $x-5=-2 \rightarrow x=3$


text:
Q: How to check that element contains child  tag or not? I want to write robot framework test case for below situation:
How to check that an element contains child tag(
)or not?
First
, doesn't contain
 tag
Second
, contains
 as child tag
Example:

        This Heading Is On A Single Line

        This Heading Is

        On Two Lines

A: Here are two approaches, in the same test case. The first one gets the html value of the parent element, and then you can check for the presence of whatever substring.
The 2nd one uses xpath - it checks does the parent element has a direct child of br type - I'd recommend it, cause it doesn't depend on string parsing, with all its negatives (case, whitespace, etc).
*** Variables ***
${parent element}       xpath=//h6[@id="this-heading-is-on-a-single-line"]

*** Test Cases ***
A testcase
    ${value}=   Get Element Attribute   ${parent element}@innerHTML

    # will be ${true} if there's
, ${false} otherwise
    ${string presence check}=   Run Keyword And Return Status   Should Contain   ${value}

    ${xpath presence check}=    Run Keyword And Return Status   Element Should Be Visible   ${parent element}/br
    # again - ${true} if there's
; if it's not guaranteed to be a direct child of the
, use // - e.g. ${parent element}//br

A: Here is a complete possible solution:
*** Settings ***
Library           String

*** Test Cases ***
Negative Test
    ${myteststring}=    Set Variable
 \ \ \ \ \
 \ \ \ \ \ \ \ \ \ This Heading Is On A Single Line \ \ \ \ \ \ \
 \ \ \ \

    ${result}=    Contains
?    ${myteststring}
    Should Not Be True    ${result}

Positive Test
    ${myteststring}=    Set Variable
 \ \ \ \ \
 \ \ \ \ \ \ \ \ \ This Heading Is \
 \ \ \ \ \ \ \ \ \ On Two Lines \ \ \ \ \ \ \

    ${result}=    Contains
?    ${myteststring}
    Should Be True    ${result}

*** Keywords ***
Contains
?
    [Arguments]    ${arg1}
    ${result}=    Get Regexp Matches    ${arg1}    (?im)

    ${result}=    Evaluate    len(${result}) > 0
    [Return]    ${result}


text:
Q: How to convert 15-Oct-14 varchar to datetime format 2014-10-23 00:00:00.000 I have tried many combinations i want to convert my Date which is imported from excel and is stored as varchar in 15-Oct-14 format, what i want is to convert it to MSSqlserver datetime format 2014-10-23 00:00:00.000 i have tried all combination from http://www.sql-server-helper.com/tips/date-formats.aspx but nothing is working for me.

A: Check the below script and hope this suits your requirement:
Set dateformat ymd
Select convert(datetime,'15-Oct-14',105)

A: Try this (solution with guard):
set dateformat YMD;

select
  case
    when isdate(date_column) = 1 then convert(date, date_column, 105)
  end [converted_date]

A: Try this
select cast('15-Oct-14' as datetime)


text:
Q: Workbook.open issues Hello I am trying to open a file with reference to a cell G13, first few times it work but after wards i am unable to have the code work anymore.
Please help
Sub ConvertTextToNumbers()
Dim wBook As Workbook
Dim LastRow As Long, LastCol As Long
Dim Rangetemp As Range
Dim Workbook1 As Range

Set Workbook1 = Range("G13")
'Enter here the path of your workbook
Set wBook = Workbooks.Open("Workbook1")
LastRow = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastCol = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

For c = 1 To LastCol
Set Rangetemp = Cells(c).EntireColumn
Rangetemp.TextToColumns DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 1), TrailingMinusNumbers:=True
Next c
End Sub


text:
Q: Prove that this sequence converges. Given that $x_n\geqslant 0$, $x_{n+1}\leqslant x_n+\dfrac{1}{n^2}$, prove this sequence converges.
I want to prove by The monotone bounded convergence theorem.
$$
0\leqslant x_n=\displaystyle\sum_{i=1}^{n-1}(x_{i+1}-x_i)\leqslant\displaystyle\sum_{i=1}^{n-1}\dfrac{1}{i^2}<\dfrac{\pi^2}{6}
$$
My question is how to prove the sequence is monotonous.


text:
Q: Adding Publisher Action to visual force page I've override object view page in order to customize look and feel on sf1. Is it possible to add "Publisher Action button(+)"? The (+) icon shows up when using default layout but it disppears when override default action

A: The code turns off the Publisher for VF pages.
You can't do it in a supported way. I've filed a feature request to allow this. In the mean time, I wrote you a function to try.
var unsupportedShowMdp=function(a){
    SfdcApp.projectOneNavigator.fireContainerEvent(
        "one:updateMDPVisibility",{show:a}
    )
};

// Use it like this

unsupportedShowMdp(true);

Unsupported. I give it a 80% chance it stops working next release, but by then we might have a supported way of doing this.


text:
Q: Spring app doesn't find datasource in config files When I deploy my spring app (Spring 2.5.6) onto a Tomcat (6.0), start up fails with
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateSessionFactory' defined in class path resource [C.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' is defined

My web.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="[snip]" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>[snip]</display-name>
<welcome-file-list>
   [snip]
</welcome-file-list>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:All.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>[snip]</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>[snip]</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>

All.xml imports a number of configuration files:
<import resource="A.xml"/>
<import resource="B.xml"/>
<import resource="C.xml"/>
...

B.xml defines a data source:
<jee:jndi-lookup id="dataSource" jndi-name="[snip]"/>

C.xml creates a hibernate session factory, referencing the data source from B.xml:
<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="mappingResources">
        <list>
            <value>[snip]</value>
            <value>[snip]</value>
        </list>
    </property>
    <property name="hibernateProperties">
  <props>
       [snip]
  </props>
</property>
<property name="dataSource" ref="dataSource" />
</bean>

When I deploy my WAR file, above exception occurs. My questions are:

*

*Why?

*Why does the same exception not occur in my JUnit test that I wrote to test the validity of the spring configuration? Here's the test:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/All.xml" })
public class ImfSpringConfigurationTest {
  [snip]]
}
Note: In the JUnit test, I use a different All.xml file to replace B.xml with a file that defines a data source without jndi lookup, like so:
<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName = "oracle.jdbc.driver.OracleDriver"
    [snip] />

**
Turns out, this configuration is correct. It was the deploy of another module operating on some of the same config files that threw the exception, not this deploy process.

A: Try pull in the top level context using a wildcard operator :
<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/classes/spring*.xml</param-value>
</context-param>


text:
Q: Reference to element in ArrayList which is later moved assume the following code:
ArrayList<A> aList = new ArrayList<>();
for(int i = 0; i < 1000; ++i)
    aList.add(new A());
A anElement = aList.get(500);
for(int i = 0; i < 100000; ++i)
    aList.add(new A());

Afterwards anElement still correctly references aList[500], even though the ArrayList presumably reallocated its data multiple times during the second for loop. Is this assumption incorrect, and if not, how does Java manage to have anElement still point at the correct data in memory?
My theories are that either instead of freeing the memory anElement references, that memory now points to the current aList data, or alternatively the reference anElement has is updated when growing the array. Both of these theories however have really bad Space/Time Performance implication, so I consider them unlikely.
Edit:
I misunderstood how arrays store elements, I assumed they store them directly, but in reality they store references, meaning that anElement and aList[500] both point to some object on the heap, solving the problem I failed to understand!

A: When array that internally stores elements of an ArrayList becomes full, new, larger array is being created and all elements from the previous array are being copied to new one at the same indexes and now there is a space for new elements. Garbage collector will get rid of previous, not needed any more array.
You might want to have a look at the code of implementation of ArrayList here to see details of how it works "under the hood".
Second loop in your code, added next 100000 elements after the 1000th element so now you have 101000 elements in aList, first 1000 elements weren't moved anywhere. With get() method you only read that element, nothing is moved nor deleted from that ArrayList.
Note that ArrayList doesn't really work like array (e.g. array of As is A[]) and it's not a fixed-size collection - ArrayList changes its size when adding or removing elements - e. g. if you remove element at index 0 (aList.remove(0);), then element that was stored at index 1000 is now stored at index 999 and size of ArrayList also changes from 1000 to 999.

A: If you want to know how an ArrayList works internally just look at the sources you can find online, for example here:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java
Here you can clearly see that an Object[] is used internally that is resized to int newCapacity = (oldCapacity * 3)/2 + 1; when deemed neccessary.
The indexes stay the same, as long as you add something to the back. Should you insert something in the middle all indexes of elements behind this are incremented by one.

A: That is not Java, but an implementation detail of the given JVM. You can read something here: https://www.artima.com/insidejvm/ed2/jvm6.html for example, so there are complete books about JVM internals.
A simple approach is to have a map of objects, so you refer that map first, and then find the current location of the actual object. Then it is simple to move the actual object around, as its address is stored in a single copy, in that map.
One could say this is slow and store address directly, and go without the extra step of looking up the object in a map. This way moving the object around will require more work, though still possible, just all pointers have to be updated (as raw pointers do not appear on the language level, casting to numbers temporarily or storing inside some random array and similar magic can not do harm here, you can always track that something is a pointer pointing the object you are moving around or not).


text:
Q: bootstrap padding around jumbotrons and navbar? I am trying to learn the basics of bootstrap for responsive websites. When I put elements into the "row" class then there is not any margins or padding to the elements and no free space, but with elements such as jumbotron and the navbar then there seems to be padding i cant get rid of on the left and right side.
Any help would be appreciated.

    lorem ipsum
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent">

      </button>

              home

              about

              contact

lorem ipsum

lorem ipsum

subscribe to our newsletter

    <form class="col-lg-6 col-md-6 col-sm-6 col-xs-12 newsForm">
        <input type="email" placeholder="enter your email..." class="box">
        <button type="submit" class="button">></button>
      </form>

A: Boostrap by default apply padding on the navbar you can remove right and left padding by simply doing that:
.navbar.custom-navbar {
    padding-left: 0rem !important;
    padding-right: 0rem !important;
}

apply custom-navbar class on  element.
To remove jumbotron left and right padding remove
 which is inside jumbotron like that:

odtom.com

a site showcasing everything odt.

Also to remove horizontal scroll from the page place the row inside conatiner-fluid.

subscribe to our newsletter

            <form class="col-lg-6 col-md-6 col-sm-6 col-xs-12 newsForm">
                <input type="email" placeholder="enter your email..." class="box">
                <button type="submit" class="button">></button>
            </form>

A: I'm not sure if this will answer your question, but the left and right paddings in the jumbotron element are coming from the ".container-fluid" class. It seems that you are targeting the container with the ".jumbotron-fluid" class, which is the one currently set to padding-left and right to 0px.
Just target this class to remove or amend the paddings if that's what you need.
.container-fluid {
   width: 100%;
   padding-right: 15px;
   padding-left: 15px;
   margin-right: auto;
   margin-left: auto;
}


text:
Q: Using INotifyPropertyChanged in WPF applicatoin I'm using .Net 4.6.1 with a WPF application. We have an ObservableCollection and we want to bind the collection to a listview that needs to have sorting alphabetically and auto updating upon new item in the collection.
I use CollectionViewSource and searched here on StackOverflow for updating I need to use INotifyPropertyChanged. But for some reason it doesn't work :(.
Object class:
using System.Text;
using System.Threading.Tasks;

namespace ObservableCollection
{
    public class AlarmTypes : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string name;
        public AlarmTypes(string _name)
        {
            this.name = _name;
        }

        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                OnPropertyChanged("Name");

            }
        }

        protected void OnPropertyChanged(string prop)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(prop));
            }
        }
    }
}

XAML file
<Window x:Class="ObservableCollection.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ObservableCollection"
        xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase"
        xmlns:clr="clr-namespace:System;assembly=mscorlib"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>

        <Grid.Resources>
            <CollectionViewSource x:Name="CollectionViewSource" x:Key="src" Source="{Binding alarmTypes }" IsLiveFilteringRequested="True">
                <CollectionViewSource.LiveSortingProperties>
                    <clr:String>Name</clr:String>
                </CollectionViewSource.LiveSortingProperties>
                <CollectionViewSource.SortDescriptions>
                    <componentModel:SortDescription PropertyName="Name" />
                </CollectionViewSource.SortDescriptions>
            </CollectionViewSource>
        </Grid.Resources>

        <ListView x:Name="lstAlarmTypes" HorizontalAlignment="Left" Height="319" Margin="585,48,0,0" VerticalAlignment="Top" Width="157" ItemsSource="{Binding Source={StaticResource src}}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Name"  DisplayMemberBinding="{Binding Name}" />
                </GridView>
            </ListView.View>
        </ListView>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="10,48,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Name="textBox1"/>
        <Button Content="Add item" HorizontalAlignment="Left" Margin="173,51,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
        <ListView x:Name="LstNames2" HorizontalAlignment="Left" Height="301" Margin="339,66,0,0" VerticalAlignment="Top" Width="180">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Name"  DisplayMemberBinding="{Binding Name}"/>
                </GridView>
            </ListView.View>
        </ListView>

    </Grid>
</Window>

XAML.cs code behind:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ObservableCollection
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private ObservableCollection<AlarmTypes> alarmTypes = new ObservableCollection<AlarmTypes>();
        private ObservableCollection<AlarmTypes> sortedTypes = new ObservableCollection<AlarmTypes>();

        public MainWindow()
        {
            InitializeComponent();
            LstNames2.ItemsSource = alarmTypes;

            var alarmType = new AlarmTypes("inbraak");
            alarmTypes.Add(alarmType);

            var alarmType2 = new AlarmTypes("alarm");
            //alarmType.Name = textBox1.Text;
            alarmTypes.Add(alarmType2);

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var alarmType = new AlarmTypes(textBox1.Text);
            //alarmType.Name = textBox1.Text;
            alarmTypes.Add(alarmType);

        }
    }
}

I don't know if the binding doesn't work or it's the property or I still need something else. The first list has a binding just to the Observable collection and that works when inputting data from the textbox. But the second listview that has the collectionViewSource apparently doesn't work. Any ideas whats missing?

A: You need to turn alarmTypes into a public property.


text:
Q: $H_m(\mathbb{R}^n)$ , the completion of $C_C^{\infty}(\mathbb{R}^n)$ Theorem: Let $m$ be a positive integer. Then $H_m(\mathbb{R}^n)=\{ u \in D'(\mathbb{R}^n): D^{\alpha} u \in L^2(\mathbb{R}^n), |\alpha| \leq m\}$
$\to ||u||_{H_m}^2=(2 \pi)^{-n} \int (1+|\xi|^2)^m |\widehat{u}(\xi)|^2 d{\xi}<+\infty$
Furthermore, $H_m(\mathbb{R}^n)$ is the completion  of $C_C^{\infty}(\mathbb{R}^n)$ ad for the metric $( \star) ||u||_m=\left( \sum_{|\alpha| \leq m} \int |D^{\alpha}u|^2\right)^{\frac{1}{2}} $
Proof: There are constants $c_m$ such that $$(1) \sum_{|\alpha| \leq m } |\xi^{\alpha}|^2 \leq (1+ |\xi|^2)^m \leq c_m \sum_{|\alpha| \leq m} |\xi^{\alpha}|^2$$
We have $\xi^{\alpha} \widehat{u}(\xi)=\widehat{D^{\alpha} u}$, so $D^{\alpha} u \in L^2(\mathbb{R}^n) \Rightarrow \xi^{\alpha} \widehat{u}(\xi) \in L^2(\mathbb{R}^n)$
From $(1)$ we have that the two metrics $(\star)$ and $||u||_m^2=(2 \pi)^{-n} \int (1+|\xi|^2)^m |\widehat{u}(\xi)|^2 d{\xi}$ are equivalent.
Claim: each Cauchy sequence $(\phi_j)_{j=1}^{\infty} \in C_C^{\infty}(\mathbb{R}^n)$ as for the metric $||\cdot||_m$ converges to an element of $H_m(\mathbb{R}^n)$.
We have that $\phi_j$ is Cauchy in $L^2(\mathbb{R}^n)$,  $D^{\alpha}\phi_j$ is Cauchy in $L^2(\mathbb{R}^n)$.
$||\phi_j||_m^2=\sum_{|\alpha| \leq m} |D^{\alpha} \phi_j|^2 dx$
Let $u$ the $L^2$-limit of $\phi_j$ and $u^{\alpha}$ is the $L^2$-limit of $D^{\alpha}\phi_j$ , then
$$\int_{\mathbb{R}^n} \psi D^{\alpha} \phi_j=(-1)^{|\alpha|} \int_{\mathbb{R}^n} D^{\alpha} \psi \phi_j dx, \psi \in C_C^{\infty}(\mathbb{R}^n)$$
$$\Rightarrow \int_{\mathbb{R}^n} \psi u^{\alpha} dx=(-1)^{|\alpha|} \int D^{\alpha}{\psi} u dx \Rightarrow u^{\alpha}=D^{\alpha} u$$
Furthermore, each function $u \in H_m(\mathbb{R}^n)$ is the limit of a sequence $(\phi_j)_{j=1}^{\infty}$.
We define $u_{\epsilon}(x)= \int_{\mathbb{R}^n} \psi_{\epsilon}(x-y) u(y) dy$.
$$||u_{\epsilon}||_{L^2} \leq ||u||_{L^2}, ||D^{\alpha} u_{\epsilon}||_{L^2} \leq ||D^{\alpha} u||_{L^2}$$
$$||D^{\alpha} u_{\epsilon}- D^{\alpha} u||_{L^2(\mathbb{R}^n)} \to 0$$
We consider a cutoff function $\phi \in C_C^{\infty}(\mathbb{R}^n),  0 \leq \phi \leq 1$ and $\phi=1$ for $|x|<1$.
We define $g_{\epsilon}(x)=\phi( \epsilon x) u_{\epsilon}(x)$.
$D^{\alpha} g_{\epsilon}-D^{\alpha} u=D^{\alpha} (\phi(\epsilon x) u_{\epsilon }x)-D^{\alpha} u(x)= \phi(\epsilon x) D^{\alpha} u_{\epsilon}(x)- \phi(\epsilon x) D^{\alpha} u+ \phi(\epsilon x) D^{\alpha}u-D^{\alpha} u+ \epsilon(\dots)=\phi(\epsilon x) (D^{\alpha} u_{\epsilon}(x)-D^{\alpha}u)+(\phi(\epsilon x)-1) D^{\alpha}u+ \epsilon (\dots)$
$\Rightarrow D^{\alpha} g_{\epsilon} \overset{L^2}{\rightarrow} D^{\alpha}u$
Firts of all, how does the relation $(1)$ imply that the metrics $(\star)$ and $||u||_m^2=(2 \pi)^{-n} \int (1+|\xi|^2)^m |\widehat{u}(\xi)|^2 d{\xi}$ are eqivalent?
Secondly, in order to show that $H_m(\mathbb{R}^n)$ is the completion of $C_{C}^{\infty}(\mathbb{R}^n)$, do we need to show that each sequence of $C_C^{\infty}(\mathbb{R}^n)$ converges to an element of $H_m(\mathbb{R}^n)$ and that each element of $H_m(\mathbb{R}^n)$ is the limit of a sequence of $C_C^{\infty}(\mathbb{R}^n)$ ? If so, why?
Why are $\phi_j$ and $D^{\alpha} \phi_j$ Cauchy sequences in $L^2(\mathbb{R}^n)$ ?
In addition, why do we look for the difference $D^{\alpha}g_{\epsilon}-D^{\alpha}u $ ?
And how did we calculate $D^{\alpha}(\phi( \epsilon x) u_{\epsilon}(x))$ ?

A: The first question follows by definition, $H_m(\mathbb{R}^n)$ is the completion of $C_{c}^\infty(\mathbb{R}^n)$ iff (by definition) $H_m(\mathbb{R}^n) = \overline{C_{c}^\infty(\mathbb{R}^n)}^{|| \cdot ||_m}$, i.e. $\forall u \in H_m(\mathbb{R}^n)$ exists $\lbrace u_k \rbrace \subset C_{c}^\infty(\mathbb{R}^n)$ such that $u_k \rightarrow u$ in the $H_m$-norm.
The second question follows because the test functions (with their derivatives) are uniformly limited.
The third question follows by approximation theorem with regular functions, in this case consider the regularized function (convolution) of the weak derivative, that precisely approximates the weak derivative.
The last question should follow from the Leibniz rule.
Note that the point where it checks that $u_\alpha = D^\alpha u$ follows by Schwartz inequality, in the sense
$\displaystyle \left \vert \int \psi [D^\alpha \phi_j - u_\alpha] dx  \right \vert \leq ||\psi||_2 ||D^\alpha \phi_j - u_\alpha ||_2 \rightarrow 0 $
then
$\displaystyle \int \psi D^\alpha \phi_j dx = (-1)^{|\alpha|} \int \phi_j D^\alpha \psi dx \rightarrow (-1)^{|\alpha|} \int  u_\alpha D^\alpha \psi dx$
by definition, $\forall \psi \in C^{\infty}_c(\mathbb{R}^n)$, this means that ($\star$) $u_\alpha = D^\alpha u$ is a weak derivative. The point ($\star$) follow by this lemma
"Let $f_n \in L^{1}_{loc}(\Omega)$ with $f_n$ admits weak derivative $g_n=D^\alpha f_n$. If $f_n \rightarrow f$ and $g_n \rightarrow g$ in $L^{1}_{loc}(\Omega)$ then $g=D^\alpha f$"
Proof. $\forall \phi \in C_{c}^\infty(\Omega)$ we have
$\displaystyle \int_{\Omega} g \phi dx = \lim_{n \rightarrow \infty} \int_{\Omega} g_n \phi dx = \lim_{n \rightarrow \infty} (-1)^{|\alpha|} \int_{\Omega} f_n D^\alpha \phi dx = (-1)^{|\alpha|} \int_{\Omega} f D^\alpha \phi dx$


text:
Q: IonToggle firing twice in React-based Ionic project In the following block of code, the IonToggle is firing twice for some unknown reason. I had it already replaced with a normal button and it works fine. If I keep the IonToggle and remove the line setUpdating(true) it also works fine.
Is it some known bug, or is there something wrong with this code.
import { AppContext } from './../AppContextProvider';

const LightController: React.FC<InterfaceLamp> = ({ id, color, brightness, turnedOn }) => {
  const { state, dispatch } = useContext(AppContext);
  const [isUpdating, setUpdating] = useState(false);
  const isMount = useIsMount();

  const handleUpdateToggle = async (isToggled: boolean) => {
    lightService.toggleLight(state.api, id, isToggled, state.auth.username,
    state.auth.password).then((res) => {
      if (!res.error) {
        [...]
        dispatch({
          key: 'devices',
          data: devices,
        })
      }
      setUpdating(false);
    })
  }

 const handleToggle = (isToggled: boolean) => {
    setUpdating(true);
    handleUpdateToggle(isToggled);
  }

  return (

      <Loader isLoading={isUpdating} message={"Updating devices"} onClose={() => { }} />

          <IonItem lines={"none"}>
            <button onClick={(e)=>handleToggle(!turnedOn)}>toggle</button>
            <IonToggle checked={turnedOn} onIonChange={(e) => handleToggle(e.detail.checked)}/>
          </IonItem>

  );
};

export default LightController;

A: value="true"
why are you setting the value here? dont think it is necessary

A: As of Ionic React v5.5.0, IonToggle and IonCheckbox have still got the same issue.
The simplest workaround is to add an onClick event listener to the IonItem component that usually wraps the IonToggle component. (Alternately, use any other wrapper component with onClick.) This approach makes it possible to keep the native-looking IonToggle.


text:
Q: How to "cut off the tail" of a series I have a list of 10 terms with their scores. The first x tend to be much more important than the rest. So I want to find x.
For example, plotting this list shows a plateau after third term. Hence we keep the first 3 terms. Even intuitively, keeping first 3 terms seems appropriate.
    badge                                   =>    7.00709342956543
    unlocked                                =>    7.00709342956543
    foursquare                              =>   5.830315748850505
    https                                   =>   5.001254081726074
    you've unlocked                         =>   4.954763253529866
    50xxxxxx badge                          =>   4.954763253529866
    all badges                              =>   4.954763253529866
    unlocked far                            =>   4.954763253529866
    badges                                  =>   4.954763253529866
    just unlocked                           =>   4.954763253529866

But how to generate this cutoff programmatically? I prefer stuff available in standard libraries.

A: I am assuming your "terms" will be sorted in a descending order as shown in the example you have provided. I would simply establish a delta (say 0.5) which represents a difference small enough to be ignorable.
I would then traverse through the collection of terms adding them a resultant collection and as soon as I see a term within "delta" of my previously seen term, I'll end my iteration and potentially remove the last seen term from my resultant collection as well.
Does that make sense?
Something that looks like this:
delta = 0.5
result = []
for term in termMapSortedKeys:
     if (previousTermValue - delta >= termMap[term]):
          break
     else:
          result.append(term)
          previousTermValue = termMap[term]
del result[-1]
return result

A: For a std-lib friendly way, you can use itertools.tee to do comparisons between the items in the list and return the deltas as in iterator. Then grab the data within your tolerance using itertools.takewhile.
import itertools, sys

def delta(data):
    '''yield the original data and the delta to the next item as tuple'''
    a, b = itertools.tee(data)
    yeild (next(b, None), sys.maxint) # assume the first item always passes :)
    for n in itertools.izip(a, b):
        yield n[1], abs(n[1] - n[0])

# example...
data = [0,1,2,3,4,6,6.125,6.25,6.375,6,6,6.25,5,6,6, 4.5, 2.5, 7]
data.sort()
print data
# [0, 1, 2, 2.5, 3, 4, 4.5, 5, 6, 6, 6, 6, 6, 6.125, 6.25, 6.25, 6.375, 7]

filter_fn = lambda x: x[1] > .05 # tolerance goes here...
trimmed = [item[0] for item in itertools.takewhile(filter_fn , delta(data))]
print trimmed
# [0, 1, 2, 2.5, 3, 4, 4.5, 5, 6]


text:
Q: Is it possible to disable find function on a webpage, not just CTRL + F? I would like to disable find function. I have a text uploded and the users shuld read the whole text without cheats, like CTRL + F. I have already disabled CTRL + F.
But I can open the find bar frome the browser menu.
I hope someone has an idea.

A: It's not really an answer for your question but here is something better.
Just put a span with a space in the words, that should not searchable and make the span hidden.
for example:

"This is a te st."

and the css:
.foo{
    font-size:0;
}

https://jsfiddle.net/y8g10jsr/
try to search for "test" with CTRL+F

A: You can degenate image based on you text on the fly with javascript library html2canvas. For example if you want to transform div with id docs into image, your code will be

$(document).ready(function(){html2canvas($('#docs'), {
  onrendered: function(canvas) {
    $('#docs').html(canvas);
  }
});});

This script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.

P.S. But user still will be able to see text if he will check html of the page

A: I've just tried this as a workaround and it seems to render the text unsearchable.

.overlook::after {
    content: attr(data-text);
 }

Tested in Chrome, Firefox and IE.
edit:
Oh I hadn't seen the comment below the question - please up vote the original if you find this useful.


text:
Q: How to define unix permission constants (READ, WRITE, EXECUTE) I want to define these constants and | them for different operations to generate correct permissions.
Defining them as :
public static final int READ = 4;
public static final int WRITE = 2;
public static final int EXECUTE = 1;

gives me correct result as expected, like READ | WRITE | EXECUTE or WRITE | EXECUTE.
Does defining them as
public static final int READ = 0x4;
public static final int WRITE = 0x2;
public static final int EXECUTE = 0x1;

give me any benefit?

A: Since they are equivalent in hex or decimal, that only adds in terms of readability for other developers. It's functionally the same.
Although, if you are doing it for readability, octal would be even better given the underlying system:
public static final int READ = 04;
public static final int WRITE = 02;
public static final int EXECUTE = 01;

or even more obvious:
public static final int READ = 1<<2;
public static final int WRITE = 1<<1;
public static final int EXECUTE = 1;

But that might be excessive :)


text:
Q: Play framework with Postgres. Error in column name I am trying to create a simple application using play Framework 2.5 with postgresql. The idea is to save new entries in a table.
The database contains two tables. A journal is connected to a reference in a manyToOne relationship, so a reference must always have a journal. Both tables have more fields, but in summary they look like this:
CREATE TABLE reference (
reference_id integer NOT NULL,
journal_id integer NOT NULL
title character varying(512));

CREATE TABLE journal (
journal_id integer NOT NULL,
journal_title character varying(128) NOT NULL);

ALTER TABLE ONLY reference ADD CONSTRAINT reference_journal_id_fkey FOREIGN KEY (journal_id)
REFERENCES journal(journal_id) ON UPDATE CASCADE ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED;

I have mapped the tables to Play like this:
Reference.java
import com.avaje.ebean.Model;
import com.avaje.ebean.*;

@Entity
@Table(name="reference")
public class Reference extends Model{

    @Id
    public Long reference_id;

    @ManyToOne
    @Constraints.Required
    public Journal journal;

    @Constraints.Required
    public String title;

Journal.java
import com.avaje.ebean.Model;
import com.avaje.ebean.*;

@Entity
@Table(name="journal")
public class Journal extends Model {
    @Id
    public Long journal_id;
    public String journal_title;

    @OneToMany(mappedBy = "journal")
    public List<Reference> journal_references = new ArrayList<Reference>();

    public static Find<Long,Journal> find = new Find<Long,Journal>(){};

    public static Map<String,String> options() {
        LinkedHashMap<String,String> options = new LinkedHashMap<String,String>();
        for(Journal j: Journal.find.orderBy("journal_title").findList()) {
            options.put(j.journal_id.toString(), j.journal_title);
        }
        return options;
    }

plugins.sbt
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.4")
addSbtPlugin("com.typesafe.sbt" % "sbt-play-enhancer" % "1.1.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "3.0.1")

Build.sbt
lazy val root = (project in file(".")).enablePlugins(PlayJava)
lazy val myProject = (project in file(".")).enablePlugins(PlayJava, PlayEbean)
libraryDependencies ++= Seq(
  javaJdbc,
  cache,
  javaWs,
  "com.adrianhurt" %% "play-bootstrap" % "1.0-P25-B3",
  "org.hibernate" % "hibernate-entitymanager" % "4.3.8.Final"
)

libraryDependencies += "postgresql" %  "postgresql" % "9.1-901-1.jdbc4"

routesGenerator := InjectedRoutesGenerator
fork in run := true

The view is created correctly, it shows the proper fields and a select with the journal names from the Journal table.
create.scala.html
@b3.form(routes.Reference.save()) {

<fieldset>
    @b3.text(referenceForm("title"), '_label -> "Title", '_help -> "")

    @b3.select(
    journal_referenceForm("journal.journal_id"),
    options(Journal.options),
    '_label -> "Journal:",
    '_default -> "-- Choose a Journal --",
    '_showConstraints -> false,
    'multiple -> false ,
    '_help -> ""
    )

    @b3.free(){
    <input type="submit" value="Save the Reference" class="btn btn-primary"> or
    Cancel
    }
</fieldset>
}

When running the application I get the message "Database 'default' needs evolution! An SQL script will be run on your database -". The problem is that the field journal_id is renamed to journal_journal_id in the script.
Create table core.reference (
journal_reference_id          bigserial not null,
journal_journal_id            bigint,
title                         varchar(255)
constraint pk_journal_reference primary key (journal_reference_id));

And of course, when trying to save a new entry, I get the error that the field journal_journal_id doesn't exist in the table reference.
I have checked the names in the database and the models and they are correct. I have also regenerated the script many times without success. I have no much experience with play so I have no idea what the source of the error could be.
Thanks in advance ! Any help is greatly appreciated.


text:
Q: Devexpress Gridwiew Toolbars Custom Buttons No reaction I have a problem ,
Devexpress AspxGridwiew  ToolBars CustomButtons   Not working.?
enter image description here
Event
 protected void ASPxGridView1_CustomButtonCallback(object sender, ASPxGridViewCustomButtonCallbackEventArgs e)
    {
        if (e.ButtonID != "Detay") return;
        id = ASPxGridView1.GetRowValues(ASPxGridView1.FocusedRowIndex, "ID").ToString();
        ASPxPopupDetay.PopupHorizontalAlign = PopupHorizontalAlign.WindowCenter;
        ASPxPopupDetay.PopupVerticalAlign = PopupVerticalAlign.WindowCenter;
        ASPxPopupDetay.Modal = true;
        ASPxPopupDetay.ShowOnPageLoad = true;
    }

ScreenCast

A: SOLVED
AspxGridview.EnableCallBacks  =  False ;


text:
Q: Pass content of ts variable in js file I was wondering if it's possible to use the content of a ts variable and use it in js file ?
I'm feeling trapped now I realize that I don't know how can I achieve it.
Please send me any suggestion easy to implement if possible.
My ts file with the printedOption that I want to use in my js file.
The content of this variable is the value of my select input.
 validateLuggages() {
      this.printedOption = this.selectedOption;
      this.http.get(`/routes/luggages`)
        .subscribe((data) => {
          this.parsedForLuggages = data;
     })
      return this.printedOption;
}

Now, How can I create the instance and use this variable in my JS file ?

A: To use any typescript variable inside javascript code you may firstly export the variable in typescript file which you want to use in the js file.
Then, you can simply use the import statement and import the variable from the correct path.
You can check the example below and refer the link for better clarity. LINK
// Add to tsconfig.json:
{
"compilerOptions": {
...
"allowJs": true
...
}
}
import MyModule from './../pages/MyModule';


text:
Q: Using Stripe CLI correctly in docker I would like to use Stripe CLI in docker. I have to mention that I am new to docker.  I have loaded stripe/stripe-cli from dockerHub.
docker run --rm -it stripe/stripe-cli:latest.
docker image ls also shows me that the image is available locally. But docker ps does not show me a stripe CLI container? Is this right or wrong?
When I run
docker run -it stripe/stripe-cli login
I have to authenticate with Stripe in the browser. This is the output:
Your pairing code is: xxxx-xxxx-xxx-xxxxx
This pairing code verifies your authentication with Stripe.
To authenticate with Stripe, please go to: https://dashboard.stripe.com/stripecli/confirm_auth?t=5ifDAxXxXxXxXxX
⣾ Waiting for confirmation... > Done! The Stripe CLI is configured for Mike's Test Stripe with account id add1_xxx

Please note: this key will expire after 90 days, at which point you'll need to re-authenticate.

My que
I do that successfully but I still can't use stripe-cli afterwards? What am I missing?

A: To retain configuration you need to use bind mounts (-v attribute).
On https://stripe.com/docs/cli/login you can see that configuration is stored inside .config/stripe/config.toml so we can mount ~/.config/stripe from our local disk
docker run --rm -v ~/.config/stripe:/root/.config/stripe -it stripe/stripe-cli:latest login

Your pairing code is: asd-asd
This pairing code verifies your authentication with Stripe.
To authenticate with Stripe, please go to: https://dashboard.stripe.com/stripecli/confirm_auth?t=asdasdasdasd
⢿ Waiting for confirmation... > Done! The Stripe CLI is configured for asd with account id acct_asd

Please note: this key will expire after 90 days, at which point you'll need to re-authenticate.

so now we can repeat without need to log in again
docker run --rm -v ~/.config/stripe:/root/.config/stripe -it stripe/stripe-cli:latest customers list

A: If your purpose is simply testing your webhooks do what their documentation says:

Since Docker containers are ephemeral, stripe-cli login cannot be used without defining a data volume. You can use the --api-key flag instead.

docker run --rm -it stripe/stripe-cli:latest listen --api-key sk_test_XXXXXX --forward-to localhost/stripe_hook

A: I think there should be a docker compose solution too here. This is my working setup:
Framework: Django 4
Python: 3.9
version: "3.9"

services:
  stripe-cli:
    image: stripe/stripe-cli
    container_name: stripe-cli
    command: "listen --api-key ${STRIPE_API_KEY} --device-name ${STRIPE_DEVICE_NAME} --forward-to web:8000/payment/webhook/"
    env_file:
      - stripe_cli.env

  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"

Contents of .env file (remember this should stay locally on the machine. Dont commit this file. create it locally)
STRIPE_API_KEY = rk_test_somelongkey***************
STRIPE_DEVICE_NAME = Name

Please note a few things:
In "web:8000", 'web' is service name of the django project

A: docker run's --rm option indicates that the container will be removed after it exits.
And commands do exit unless it listens to something e.g. listen.
Note that the default entrypoint of this docker image is /bin/stripe; that is, it expects one of the stripe cli command.
e.g. docker run --rm stripe/stripe-cli:latest customers list
(as in stripe customers list otherwise)
Looking at the way its Dockerfile is written, I suppose it's intended to be used as one-off command execution as opposed to bash-kind of interactive platform.
A simple solution seems to be the use of STRIPE_API_KEY or --api-key option. Set this env var and you're good to go for any command, even without login.


text:
Q: Mechanize cannot find the form in login page I am trying to use Ruby and Mechanize to log into a website, but with one particular log-in form I am having trouble. For some reason, Mechanize does not seem to recognize the form.
Mechanize.new.get("website").form returns nil and forms returns [].
agent = Mechanize.new
fm_raw_mechanize = agent.get("https://www.fitmob.com/login")
fm_form = fm_raw_mechanize.form   #nil
fm_form.login = "rebeccamhathaway@gmail.com"
fm.password = "classpass"
fm.submit

Any ideas here?
Should I try another similar gem (recommendations)?
This is the source code from the "form". Notice the JavaScript on_click:

<input type="text" name="email" id="email" value="kevin@gmail.com" placeholder="Email address">

<input type="password" name="pwd" id="pwd" placeholder="Password">
Valid passwords have 6 characters or more

Forgot your password?

<button id="login_email">Log in via email</button>

or

<button id="login_fb">Facebook Connect</button>

Don't have an account? Request an invite

A: Have you tried something like the following:
$ pry
require 'mechanize'
agent = Mechanize.new
fm_raw_mechanize = agent.get('https://www.fitmob.com/login')
email_field = fm_raw_mechanize.at "#email"
email_field.attributes["value"].value = "me@email.com"
fm_raw_mechanize.at('input[@name="pwd"]')['value'] = "password"
agent.click(fm_raw_mechanize.at("#login_email"))


text:
Q: How does a Servant client handle received cookies? I want to use a Servant client to first call a login endpoint to obtain a session cookie and then  make a request against an endpoint that requires cookie authentication.
The API is (simlified)
import qualified Servant                       as SV
import qualified Servant.Auth.Server           as AS
import qualified Servant.Client                as SC

-- Authentication and X-CSRF cookies
type CookieHeader = ( SV.Headers '[SV.Header "Set-Cookie" AS.SetCookie
                                  , SV.Header "Set-Cookie" AS.SetCookie]
                      SV.NoContent )

type LoginEndpoint = "login" :> SV.ReqBody '[SV.JSON] Login :> SV.Verb 'SV.POST 204 '[SV.JSON] CookieHeader
type ProtectedEndpoint = "protected" :> SV.Get '[SV.JSON]
-- The overall API
type Api = LoginEndpoint :<|> (AS.Auth '[AS.Cookie, AS.JWT] User :> ProtectedEndpoint)

apiProxy :: Proxy Api
apiProxy = Proxy

I define the client as follows:
loginClient :: Api.Login -> SC.ClientM Api.CookieHeader
protectedClient :: AC.Token -> SC.ClientM Text :<|> SC.ClientM SV.NoContent
loginClient :<|> protectedClient = SC.client Api.apiProxy

How does the client handle the authentication cookie? I can think of two ways. When executing a request in the ClientM monad, like
do
  result <- SC.runClientM (loginClient (Login "user" "password")) clientEnv
  [..]

where Login is the login request body and clientEnv of type Servant.Client.ClientEnv, the cookie could part of the result, it could be updated in the cookieJar TVar inside clientEnv, or both. I would assume the TVar to be updated, so that a subsequent request with the same clientEnv would send the received cookies along. However, my attempt to read the TVar and inspect its contents using Network.HTTP.Client.destroyCookieJar revealed an empty array. Is this intended? I couldn't find anything in the documentation.
Thus, to make an authenticated call, I would need to extract the cookie from the header in the result (how?), update the TVar, create a new clientEnv that references this TVar, and make the authenticated call using this new environment. Is this indeed the suggested procedure? I'm asking because I suppose the use case is so standard that there should be a more streamlined solution. Is there? Am I missing something?

A: After some experimentation, I figured out that the Servant client indeed does maintain cookies in the cookieJar that is part of the clientEnv. To be more precise, clientEnv contains the field cookieJar, which is of type Maybe (TVar CookieJar). It is the TVar the client updates according to the Set-Cookie instructions of subsequent requests. It is up to the developer to create and initialize that TVar before making the first request; otherwise, the Servant client will discard cookies between requests.
In addition, it is possible to retrieve cookies in the same way as the request body. To this end, the cookies to be retrieved must be defined as part of the API type, like in the example of my original question:
type LoginEndpoint = "login" :> SV.ReqBody '[SV.JSON] Login :> SV.Verb 'SV.POST 204 '[SV.JSON] CookieHeader

Disassembling the returned was a little tricky at first, because I needed to figure out the final type that results from Servant's type-level machinery. Ultimately, I did the following:
SV.Headers resp h <- tryRequest clientEnv (loginClient (Api.Login "user" "pwd"))
let headers = SV.getHeaders h

where tryRequest is a helper to execute runClientM and extract the Right part. The pattern match resp contains the return value (here NoContent), while h is is an HList of the different headers. It can be converted into a regular list of Network.HTTP.Types.Header using Servant's getHeaders function.
It would then be possible to change or generate new headers and submit them with a new request by adding a new header to the cookieJar TVar (see the cookie-manipulating functions in Network.HTTP.Client).


text:
Q: Automatically open reports in search? In Splunk Enterprise 6.3.0, is there a way to make reports automatically open in the Search app ?
Right now, I have to open a report, click on Edit, and then hit "Open in Search" ?

A: You can create a new dashboard with the saved search, and then every time you open the dashboard you open it also.


text:
Q: posting PHP to URL via WebClient in C# Here my code is
$url="http://www.example.com";
    $post_data="username=dssasdasd&extension=123";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec ($ch);
    $status = curl_getinfo($output, CURLINFO_HTTP_CODE);
    if ($status == 200)
    {echo "Successfully Sended";}
    else{echo "Try Again";}
curl_close ($ch);

I need to send this data using Webclient C#.

A: You can use this code sample
             string url = "http://Example.com/admin"
             using (WebClient client = new WebClient())
             {
                 var data = new NameValueCollection();
                 data.Add("username","asdsdsad");
                 data.Add("extension", 123);

                 var Bytecode = client.UploadValues(url, data);
                 string htmlCode = Encoding.UTF8.GetString(Bytecode, 0, Bytecode.Length);
                 // Or you can get the file content without saving it:

             }

Finally, You will get response in htmcode


text:
Q: Tkinter Checkbutton State Change using Dictionaries StackOverflow,
So I'm still working on this GUI in Tkinter and I've set up my checkbutton dictionaries and whatnot. Essentially I have one main checkbutton group, then 3 sub-checkbutton groups whose states should be changed according to which button is active in the main checkbutton group. My problem is, however, only the last checkbutton of the sub-checkbutton groups is becoming active, while those above it remain disabled.
Here is the code:
def enable_location_state():

#Retrieve values to determine whether or not the checkbutton is checked
#0 is off, 1 is on
    dt1 = datatype['Joint Angle'].get()
    dt2 = datatype['Joint Acceleration'].get()
    dt3 = datatype['Ground Reaction Force'].get()
    dt4 = datatype['Muscle Activation'].get()

    if dt1 == 1 or dt2 == 1:
        ja_cb.configure(state=ACTIVE)
    elif dt1 == 0 and dt2 == 0:
        ja_cb.configure(state=DISABLED)

    if dt3 == 1:
        grf_cb.configure(state=ACTIVE)
    elif dt3 == 0:
        grf_cb.configure(state=DISABLED)

    if dt4 == 1:
        emg_cb.configure(state=ACTIVE)
    elif dt4 == 0:
        emg_cb.configure(state=DISABLED)

ilabel1 = Label(root, text=' Measurement',font=("Bold",18)).grid(row=1,column=0)

#Options for the checkbuttons
datatype = {'Joint Angle' : 0,
         'Joint Acceleration' : 0,
         'Ground Reaction Force' : 0,
         'Muscle Activation' : 0
}

for measure in datatype:
    datatype[measure] = IntVar()
    dt_cb = Checkbutton(root, text=measure,
                        variable=datatype[measure],command =     enable_location_state)
    dt_cb.grid(column=0, sticky='W', padx=20)

#EMG
ilabel2 = Label(root, text='Muscle Group(s)',font=("Bold",18),padx=30).grid(row=1,column=1)

emg_groups = {'Quadriceps' : 0,
              'Hamstrings' : 0,
              'Calves' : 0
}

for i, measure in enumerate(emg_groups):
    emg_groups[measure] = IntVar()
    emg_cb = Checkbutton(root, text=measure,     variable=emg_groups[measure],state=DISABLED)
    emg_cb.grid(column=1, row=i+2, sticky='W', padx=30)

emg1 = emg_groups['Quadriceps'].get()
emg2 = emg_groups['Hamstrings'].get()
emg3 = emg_groups['Calves'].get()

ilabel3 = Label(root, text='Ground Reaction Force',font=("Bold",18),padx=30).grid(row=1,column=2)

grf_groups = {'Ground Reaction Force' : 0,
              'Gait' : 0,
}

for i, measure in enumerate(grf_groups):
    grf_groups[measure] = IntVar()
    grf_cb = Checkbutton(root, text=measure,     variable=grf_groups[measure],state=DISABLED)
    grf_cb.grid(column=2, row=i+2, sticky='W', padx=30)

grf1 = grf_groups['Ground Reaction Force'].get()
grf2 = grf_groups['Gait'].get()

#JOINT ANGLES - Both Acceleration and Angles
ilabel4 = Label(root, text='Joints',font=("Bold",18)).grid(row=1,column=3)

ja_groups = {'Hips' : 0,
              'Knees' : 0,
              'Ankles' : 0,
}

for i, measure in enumerate(ja_groups):
    ja_groups[measure] = IntVar()
    ja_cb = Checkbutton(root, text=measure, variable=ja_groups[measure],state=DISABLED)
    ja_cb.grid(column=3, row=i+2, sticky='W', padx=20)

ja1 = ja_groups['Hips'].get()
ja2 = ja_groups['Knees'].get()
ja3 = ja_groups['Ankles'].get()

The "main" checkbutton group is the datatype dictionary/group, and the subgroups are the EMG, GRF, and JA groups. I honestly don't know how to read individual states/values of checkbuttons made with dictionaries, either, and I think knowing how to do that would be beneficial to this problem as well.
Thank you for your time.

A: In this group of code, and others like it, you overwrite each emg_cb so it refers to the last one created only.  That is what the IntVar() is for, so use emg_groups in enable_location_state() instead.  A little testing with a simple program goes a long way towards seeing what works and what does not.  Checkbutton http://effbot.org/tkinterbook/checkbutton.htm and Tkinter Variables reference http://effbot.org/tkinterbook/variable.htm
for i, measure in enumerate(emg_groups):
    emg_groups[measure] = IntVar()
    emg_cb = Checkbutton(root, text=measure, variable=emg_groups[measure],state=DISABLED)
    emg_cb.grid(column=1, row=i+2, sticky='W', padx=30)


text:
Q: Rank of a simple matrix series Problem Specifications and Given conditions

*

*I have a matrix $L$ with rank 3 and dimension $ 3 \times 3$. $L =  K_0+\sum_{n=1}^{\infty}K_i $ . Rank of $K_0$ is 3 and rank of L is also 3. Rank of $K_i, i>0 $ are less than 3.

*I have another matrix with $M =  K_0+\sum_{n=1}^{\infty}K_i s^n$. We know already rank of $K_0$ as 3. s is not a matrix,it is a variable

*Dimension of $K_i$ and M are $ 3 \times 3$

Question

*

*What is the rank of M? Can we say that it cant be less than 3?

*What is the rank of $\sum_{n=1}^{\infty}K_i x^n$
Please provide proof thanks

A: In general no. You can say that the set of $s$ where the rank is maximal is open.
Let's say $M=M(s)$ and $L=M(1)$.
Consider $K_0=2I$, $K_1=\begin{pmatrix}-1&0&0\\0&0&0\\0&0&0\end{pmatrix}$ and $K_i=0$ for $i>1$.
Then the rank of $L=M(1)$ is $3$ but the rank of $M(2)$ is $2$.
$M(s)$ depends continuously on $s$. Therefore the set where $\det(M(s))\neq 0$ is open. So you only know that if $L$ has rank $3$, then this is true for $s$ sufficiently close to $1$.


text:
Q: Kill a nested while loop I'm trying to make a basic loop, and I want to exit the nested loop when I loop the parent. The nested loop should restart each time the parent loops.
#!/bin/bash

loop1=0
i=0

while [[ $loop1 -eq "0" ]]; do

    let "i+=1"
    echo $i "--------------"

    loop2=0
    j=0

    while [[ $loop2 -eq "0" ]]; do

        let "j+=1"
        echo $j $i
        sleep .2

    done &

    loop2=1
    sleep 2

done

My desired output would look like this:
1 --------------
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 1
10 1
2 --------------
1 2
2 2
3 2
4 2
5 2
6 2
7 2
8 2
9 2
10 2

I'm getting that output, sort of, but the original nested loop doesn't terminate, so I also get 11 1, 12 1, 13 1, and so on.
I'm sure this is dead simple, but I'm not getting it.

A: I'm not exactly sure what the practical use for this exercise is, but to kill background processes, I'd recommend saving the process id from $! and then just shooting it with kill.
The script element backgrounded with & runs in a subshell, a distinct shell process, so no changes to shell variables take any effect, in one direction or the other. (Usually this just comes up with changes in the child not showing in the parent, since usually we wait for the child process to complete.)
This:
#!/bin/bash

i=0
while true; do   # the loop runs forever, so just use 'true' here
    let "i+=1"
    echo $i "--------------"

    j=0
    while true; do
        let "j+=1"
        echo $j $i
        sleep .2
    done &

    pid=$!
    # disown   # remove the comment marker here
    sleep .5   # shorter timeout
    kill $pid
done

prints:
1 --------------
1 1
2 1
3 1
2 --------------
1 2
2 2
3 2
loop.sh: line 19:  4113 Terminated              while true; do
    let "j+=1"; echo $j $i; sleep .2;
done
3 --------------
1 3
2 3
...

The shell prints out notices when it sees its child processes dying, we can get rid of that by disowning the child (remove the comment marker from the line).

A: Someone in the comments turned me onto the "jobs" command, and how to kill a process based on that. So this is what I ended up doing. Seemed the most straightforward.
i=0
while true; do
    let "i+=1"
    echo $i "--------------"

    j=0
    while true; do
        let "j+=1"
        echo $j $i
        sleep .2
    done &

    sleep 2

    # jobs
    kill %"$i"
done


text:
Q: Filling a course array with course information So, I have Students.java and TestStudents.java. I'm suppose to create 3 student objects and then assign them 3-5 classes with (courseName, creditHours, and letterGrade) and then print out a average of the grades of the 5 classes. I create the students, but what I'm lost on is filling the array with course information tied to each student. I think I developed a weak spot with arrays, I understand using a loop to fill it - but what are the parameters of the loop AND how do I make the array specific to each student?
The other challenge I'm having is I haven't been told exactly what the Course class is doing, only that it's necessary and obviously contains the computeGPA method
import codelibraries.chp10.Course;
public class Students
{
  private String _fname;
  private String _lname;
  private Course[] _carry;
  private int _numCourses;

  public Students(String first, String last, int NumCourses)
  {
  _fname = first;
  _lname = last;
  _numCourses=NumCourses;
  _carry = new Course[NumCourses];
  }

  //THIS IS WHERE IM LOST
  public void createCourse(String courseName, int creditHours, char letterGrade)
  {
  Course tempCourse = new Course(courseName, creditHours, letterGrade);
  _carry[] = tempCourse;
  }

  public String toString()
  {
  return "Student " + _fname + " " + _lname + " has a  " + Course.computeGPA(_carry) + " GPA";
  }

}

MAIN PROGRAM
public class TestStudents
      {
      public static void main (String[] args)
      {

  Students Jane = new Students ("Jane", "Doe", 5);
        Jane.createCourse("Math", 4, 'A');
        Jane.createCourse("English", 3, 'A');
        Jane.createCourse("CS", 4, 'A');
        Jane.createCourse("Chemistry", 3, 'B');
        Jane.createCourse("Health", 2, 'B');

        //Automatically calls toString
  Students John = new Students ("John", "Smith", 5);
  Students David = new Students ("David", "Hill", 3);

  System.out.println(Jane);
  System.out.println(John);
  System.out.println(David);
  }
 }

This is a route I'm trying but I really don't know.
public void createCourse(String courseName, int creditHours, char letterGrade)
  {
  Course tempCourse = new Course(courseName, creditHours, letterGrade);

  int i = 1;
  if (_carry[i]!=null){
  i++;
  }
  _carry[i] = tempCourse;
  }

A: You can assign a value to the 1st unassigned index in the array like this:
for( int i =0; i< _carry.length; i++) {
    if(_carry[i] == null) {
        _carry[i] = course;
        break;
    }
}

Using arrays for this is not ideal though. If you have a variable length list of items a List is better suited because you can just add more items to it.


text:
Q: FCKeditor on MediaWiki with PHP 5.3.2 installed Trying to install FCKEditor extension for MediaWiki. Following instruction on official site - getting copy from svn.
After that - include it into LocalSettings.php with:
require_once("$IP/extensions/FCKeditor/FCKeditor.php");
Than i got error when try to open my Wiki:
Magic word 'NORICHEDITOR' not found

Backtrace:
#0 /usr/share/mediawiki/includes/MagicWord.php(244):     Language->getMagic(Object(MagicWord))
#1 /usr/share/mediawiki/includes/MagicWord.php(197): MagicWord->load('NORICHEDITOR')
#2 /var/lib/mediawiki/extensions/FCKeditor/FCKeditor.body.php(79):     MagicWord::get('NORICHEDITOR')
#3 [internal function]: FCKeditor_MediaWiki::onParserBeforeInternalParse(Object(Parser), '
internalParse('
parse('
outputWikiText('
view()
#10 /usr/share/mediawiki/includes/Wiki.php(63): MediaWiki->performAction(Object(OutputPage), Object(Article), Object(Title), Object(User), Object(WebRequest))
#11 /usr/share/mediawiki/index.php(116): MediaWiki->initialize(Object(Title), Object(Article), Object(OutputPage), Object(User), Object(WebRequest))
#12 {main}

I have installed MediaWiki 1.15.1, PHP 5.3.2.
I found some information about problems with this PHP version, but no solutions can be found.
Extension: www.mediawiki.org/wiki/Extension_talk:FCKeditor_(Official)

A: Looks like you've got an extension version not compatible with your MediaWiki version. Pick a correct version here. Also, you should know that your MW is outdated and does not receive critical security updates and that FCKeditor has been abandoned by its developers.


text:
Q: 2 Signatures added to wse security I needed to signature in the wse security with SAML token similar to Need signature after SAML token in client request But when I followed the example I get signature for both the soap body and the timestamp. Where as the server where I send the request to need only the timestamp signature (error: Two references found in the signature for the timestamp. Expected one reference). I spent many hours searching in the google and tweaking the WCF settings but to no avail. Following is the signature with 2 references (to body and to the timestamp). Is there anything I can do before manually creating the wse header and its contents
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="#_0">
<Transforms><Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/></Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><DigestValue>DFvTr5YpOqj58TjzI6gd6BNhETw=</DigestValue>
</Reference>
<Reference URI="#_1">
<Transforms><Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/></Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><DigestValue>K05w1zXD270nLcMhwK6uPP+2qL4=</DigestValue>
</Reference>
</SignedInfo><SignatureValue>truncatedsignature</SignatureValue><KeyInfo><o:SecurityTokenReference b:TokenType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" xmlns:b="http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd"><o:KeyIdentifier ValueType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLID">_9329f9d7-db5c-4971-940c-b2a4e400238e</o:KeyIdentifier></o:SecurityTokenReference></KeyInfo></Signature>


text:
Q: How portable is this C syntax? I know GCC and probably Clang accept this syntax, but if I'm making games for the common 5 platforms (Mac, Windows, Linux, iOS, Android(Java)) but if I get C to run on Android probably by bridging Java and C, how portable is this? Should this be avoided?
I know that this is a bad funciton because simply return num*num; is enough but this syntax, should I avoid it?
int square(int num) {
    int x = ({
        int y = num;
        y*y;
    });
    return x;
}

A: This is not standard C. It's a GNU C extension called Statement Expressions. You should avoid it if you want maximum portability.


text:
Q: Bootstrap custom open and close button hamburger menu I'm building a hamburger menu using Bootstrap. I want to use my own open and close buttons. I have succeeded at doing that. But I am having an issue :cthe hamburger icon does not show completely
Here is the code:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">

    <button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">

    </button>

Link

Link

Link

the css:

Here are the images that I use:

Any ideas?
Here is a picture of the broken hamburger menu:

A: You have a missing " here:
style="margin-left:20px">

Instead of adding an image to the close span, it might be better to use Javascript to change the class and have your css added to that class so the hamburger changes to x on hit.
Check out: Bootstrap mobile menu icon change to x close


text:
Q: Jmeter csv variable that refers to another csv In Jmeter I've defined two CSV Data Set Config.
First one contains some columns:
Name, Surname, Adress, ....

In the second one I would like configure a column that takes the value from the first CSV Data Set Config:
SecondName = ${Name}, Age, ...

For the SecondName I've tryied these values, but no valid result:
${Name}
${__evalVar(Name)})
${__eval(${Name})}
${__V(${Name})}
${__groovy(vars.get("Name"))}

Please could you help me to solve this issue?
Thanks,
Carlo

A: You cannot.
Take a look at JMeter Test Elements Execution Order
0. Configuration elements
1. Pre-Processors
2. Timers
3. Sampler
4. Post-Processors (unless SampleResult is null)
5. Assertions (unless SampleResult is null)
6. Listeners (unless SampleResult is null)

*

*CSV Data Set Config is a configuration element therefore it's initialized before anything else

*The variable is being read when a thread (virtual user) executes a Sampler

*So your 2nd CSV Data Set Config is getting the variable value at step 3 and being initialized at step 0 when the variable doesn't exist/has the value yet

The solution would be migrating to __CSVRead() function, see How to Pick Different CSV Files at JMeter Runtime article for more details.


text:
Q: Questions about deductive closures of first order logic... Given a first order logic with equality,
$\mathscr{L}$ be a language with a fixed finite signature.
$\Sigma$ the set of all closed (without free variable) well-formed formulas. I guess this set must be countable .
Now I start getting rid of some formulas of $\Sigma$.
I delete all formulas $\phi$ that can be proved in the deductive system $\vdash\phi$. (it includes the logically valid formulas and the "equality" valid ones).
Then I delete all formulas $\phi$ whose negation can be proved in the deductive system $\vdash\neg\phi$. (hopefully now I have no contradictory formula like $A\land\neg A$)
And the last step, if two formulas are logically equivalent I only take one. Like a quotient based on provability. (I'm not sure if that step is posible...)
After that I finish with a set of sentences,  $\tau = \{\phi_1, \phi_2, \phi_3,...\}$
Is $\tau$ countable?
Is $\tau$ computably enumerable?
There is a short name for $\tau$ used in logic texts? Like the set of all distinct theories? (see below questions)
The deductive closure of any (consistent) set of sentences of $\Sigma$ must be the same as the deductive closure of some $\phi_n$?
The deductive closure of $\phi_n$ is equal to the deductive closure of $\phi_m$ only when $n=m$?
Deductive closure I mean the set of all theorems on can deduce using the input sentences as axioms in the deductive system.
Then I have a follow-up , maybe makes no sense at this point, depending on the responses...
Now imagine I start the argument with the first order logic with the same signature but without equality.
Are the two $\tau$'s related? Like the second one is included in the first...
Now imagine I start the argument with a first order logic with equality an iota (I think it is called pitfol calculus) and the same signature, are again the three $\tau$'s related somehow?


text:
Q: Obtener el mayor valor de una tabla mySQL en java Quiero realizar una consulta que devuelva el mayor codigo en una tabla mySQL. Tengo el siguiente código:
public class Conexion {
Connection con;

public Conexion() {
    try {
        Class contr = Class.forName("com.mysql.cj.jdbc.Driver");
    }

    catch(ClassNotFoundException cnfe) {
        System.out.println("com.mysql.cj.jdbc.Driver");
    }

    try {
        con = DriverManager.getConnection
        ("jdbc:mysql://127.0.0.1:3306/colegio?serverTimezone=UTC","java", "password");
        System.out.println("Conexión con la base de datos exitosa");
    }
    catch(SQLException sqle) {
        System.out.println("Error al establecer la conexión");
    }
}

public String getHighestCodigo() {
    String codigo = "0";
    try {
        Statement st = con.createStatement();
        String query = "select MAX(codigo) from empleados";

        ResultSet rs = st.executeQuery(query);
        while(rs.next()) {
            codigo = rs.getString("codigo");
        }

        System.out.println("El mayor código es: " + codigo);
    } catch(SQLException e) {
        System.out.println("No se ha encontrado el mayor código");
    }

    return codigo;
}

Si quito el bucle while sigue dando error así que interpreto que el fallo está en la línea
ResultSet rs = st.executeQuery(query);

Pero no se cómo solucionarlo. log:
run:
Conexión con la base de datos exitosa
No se ha encontrado el mayor código
BUILD SUCCESSFUL (total time: 6 seconds)


text:
Q: REGEX: how to match the syntax ? I have a Bug at my simple REGEX.
I have been trying to write some simple regular expressions at C++ using std::regex. Here is my code so far.
#include <iostream>
#include <regex>
#include <string>

int main(void)
{
    std::string str = "Hello world";
    std::regex rx("\w+\s\w+"), rx2("ello");
    std::cout << std::boolalpha << std::regex_match(str.begin(), str.end(), rx) << "\n";
    std::cout << std::boolalpha << std::regex_search(str.begin(), str.end(), rx2) << "\n";
    return 0;
}

This program should print (according to a tutorial)
true
true

but it prints
false
false

Where am I making a mistake? Thanks in advance.
Note: I'm using g++ -std=c++0x %file.cpp% -o %file% if it helps

A: As already stated g++ (GCC) does not have a proper implementation for regex (it is unimplemented but still compiles).
The Boost library has an implementation for regexes that is almost completely compatible with regexes in C++11. You could use that with minimal changes in your code (just using boost:: instead of std::).
Here is a code that compiles and works:
#include <iostream>
#include <boost/regex.hpp>
#include <string>

int main(void)
{
    std::string str = "Hello world";
    boost::regex rx("\\w+\\s\\w+"), rx2("ello");
    std::cout << std::boolalpha << boost::regex_match(str.begin(), str.end(), rx) << "\n";
    std::cout << std::boolalpha << boost::regex_search(str.begin(), str.end(), rx2) << "\n";
    return 0;
}

Note that I have also fixed missing escapes for the backslashes for rx because it does not work without it.
To compile this you have to install libboost-regex-dev package (or something similar if not using Ubuntu/Debian) and execute this:
g++ -std=c++0x main.cpp -lboost_regex -o test


text:
Q: Out of memory in embedded Hazelcast vs ehCache 3 I have tried to put in cache some objects.
With Hazelcast I have an Out of memory when I put around 30 objects.
However, with ehCache 3 I can put 1000 without problems.
Am I using properly Hazelcast?
HAZELCAST:
     Config config = new Config().addCacheConfig(new
     CacheSimpleConfig().setName("testCache"));
     config.setInstanceName("hzInstanceTest");
     HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);

     List<CaLpgDataRowDto<CaBigNumber>> bigList = lpgDatasource.getDataRows();

     while (bigList.size() <= 5000000)
     {
        bigList.addAll(bigList);
     }

     lpgDatasource.setDataRows(bigList);

     ICacheManager hazelcastCacheManager = instance.getCacheManager();
     ICache<String, CaLpgDataCollectionDto<CaBigNumber>> cache = hazelcastCacheManager.getCache("testCache");

     System.out.println("Free memory before (bytes): " + Runtime.getRuntime().freeMemory());

     for (int i = 0; i < 33 ; i++)
     {
        cache.put("objectTest"+i, lpgDatasource);
     }

     System.out.println("Free memory after  (bytes): " + Runtime.getRuntime().freeMemory());

EHCACHE 3:
    CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
           .withCache("ehInstanceTest",
                 CacheConfigurationBuilder
                       .newCacheConfigurationBuilder(String.class, CaLpgDataCollectionDto.class, ResourcePoolsBuilder
                             .heap(10)))
           .build();

     cacheManager.init();

     Cache<String, CaLpgDataCollectionDto> testCache = cacheManager.createCache("testCache",
           CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, CaLpgDataCollectionDto.class, ResourcePoolsBuilder.heap(1000)));

     List<CaLpgDataRowDto<CaBigNumber>> bigList = lpgDatasource.getDataRows();

     while (bigList.size() <= 5000000)
     {
        bigList.addAll(bigList);
     }

     lpgDatasource.setDataRows(bigList);

     System.out.println("Free memory before (bytes): " + Runtime.getRuntime().freeMemory());

     for (int i = 0; i < 1000 ; i++)
     {
        testCache.put("objectTest"+i,lpgDatasource);
     }

     System.out.println("Free memory after  (bytes): " + Runtime.getRuntime().freeMemory());

A: This line is to blame:
bigList.addAll(bigList);

Try adding unique items to the list to build it up, rather than add it to itself.
Otherwise it's a list of 5,000,000 references to significantly less than 5,000,000 objects. Different cache managers will handle this differently, depending whether or not they serialize the list.


text:
Q: Need a regex for matching one of multiple classes I'm upgrading all my websites and have redesigned them so that all the URL's default to lower case, which forced me to also change all my image names and paths to lower case. The regexes I used did the job. Unfortunately, they changed a lot of other things to lower case as well.
For example, this is what a typical div looked like before:

And this is what SOME of them look like now:

I emphasized SOME, because some div's (and other tags) were changed and others weren't.
So I'd like to find a regex that will help me search for a particular class - e.g. Cool, R or Wx500. It's a little tricky because 1) my classes aren't always listed in a particular order, and some class names consist of a single letter (e.g. B = border and R = float to the right).
So I guess what I'd like to be able to do is search for div's that include the class "Cool," then search for div's that include the class "R." It would also be helpful if I could make my searches case sensitive. For example, I might need to search for div's with the class R - but only in cases where it was changed to lower case (e.g. [div class="cool r"]
Can that be done? Dreamweaver has a pretty good regular expression utility, but it can't pick one class out of a series, as far as I know. I'm working on a Mac, and Dreamweaver and TextWrangler are my primary text editors.

A: You can use the following
(class=".*?\b)r(\b.*?")

Instead of r use the class that you want to search for and replace with $1new$2 where new is the new class name that you want.
Explanation:

*

*.*? non-greedy match any character.

*\b match word boundary (" counts as a boundary).

*() group, the first part will be in group 1 ($1), the second part in group 2 ($2)

For example the following will be matched:

But the following will not be matched:

A: If Dreamweaver doesn't support lookarounds (I don't have a copy to test with), you should also be able to use this:
using cool as an example class
Find (
]+ )?class="([^"]+ )?)cool( |")
Replace with $1Cool$4
Since $1/$4 means "everything matched by the first/fourth subexpression in parentheses".


text:
Q: WPF gridview button column disable only the button I need to disable gridview button only when data bind or button click because I need to disable that button for existing records only and when user add new record need to active my grid button.
here is my XAML code,

                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <Button Name="grdBtnAdd" Cursor="Hand"   Click="Button_Click_1" Width="20" Height="20" >

                                        <Button.Template>
                                            <ControlTemplate>
                                                <Border Style="{StaticResource borstyle}" BorderBrush="#282828"  BorderThickness=".5" CornerRadius="3" Name="bor"  >

                                                    <Image Width="20" Height="18" Source="/Images\plus1.png"></Image>
                                                </Border>

                                            </ControlTemplate>
                                        </Button.Template>
                                    </Button>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>

please help me. I found how to disable button after click grid button. I need a way to disable grid buttons.

A: If i understood the issue correctly than the following should work:
Bind the button IsEnabled property to a property in the viewModel.
<Button Name="grdBtnAdd" IsEnabled="{Binding IsNewRecordsAvailable}" Cursor="Hand" Click="Button_Click_1" Width="20" Height="20">
...
</Button>

Set the viewModel as the views' dataContext:
Sub New()
    Me.Datacontext = new viewModel
End Sub

The viewModel will implement INotifyPropertyChanged, and the property will look like this:
 Private m_isNewRecordsAvailable As Boolean
    Public Property IsNewRecordsAvailable() As Boolean
        Get
            Return m_isNewRecordsAvailable
        End Get
        Set(ByVal value As Boolean)
            m_isNewRecordsAvailable = value
            NotifyPropertyChanged("IsNewRecordsAvailable")
        End Set
    End Property

Now when you want to enable or disable the button , just set IsNewRecordsAvailable to true or false.
Here are some more examples:
http://msdn.microsoft.com/en-us/library/ms229614.aspx
http://www.codeproject.com/KB/cs/BindBetterINotifyProperty.aspx


text:
Q: Opening a url with pdf file in a native android webview I'm trying to open a pdf file in a Android WebView from a url.
When i searched for information online on how to achieve this, i found that you need to extend the url with this in front of it:
"http://docs.google.com/gview?embedded=true&url="
I don't want to do like that.i just want to override the webview from the relevant pdf file.
My code snippet as below;
    WebSettings settings = webView.getSettings();
    String userAgent = settings.getUserAgentString();
    userAgent += "ABC";
    settings.setUserAgentString(userAgent);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.clearCache(true);
    webView.loadUrl(webViewUrl);
    webView.setWebViewClient(new WebViewClient(){
              ///..code here...}

Someone who knows about it,please help me on this matter??


text:
Q: What is the proper approach to get data with one to many relationship I am following a tutorial in Django where I found a certain for loop to get the entities in a model which is actually filtering the data.
The below is the model (models.py)
class Brand(models.Model):
    name = models.CharField(max_length=30)
    origin = models.CharField(max_length=50)

class Model(models.Model):
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
    model_name = models.CharField(max_length=30)

class Review(models.Model):
    article = models.CharField(max_length=2000)
    label_model = models.ManyToManyField(Model)

The below is the views.py
from django.views import generic
from .models import Brand
from .models import Model
from .models import Review

class BrandListView(generic.ListView):
    template_name = 'phonereview/brands.html'
    context_object_name = 'all_phone_brands'

    def get_queryset(self):
        return Brand.objects.all()

class ModelDetailView(generic.DetailView):
    model = Brand
    template_name = 'phonereview/models.html'

class ReviewDetailView(generic.DetailView):
    model = Model
    template_name = 'phonereview/reviews.html'

The below is the template
1) Listing brands (tempates/appname/brands.html)

    {% for brand in all_phone_brands %}

                {{ brand.name }}

    {% endfor %}

Here the all_phone_brands is coming from views.py.
2) Template for listing phone models

    {% for model_item in brand.model_set.all  %}

            {{ model_item.model_name }}

    {% endfor %}

Even though the code works, I am not sure putting brand.model_set.all is the proper approach. I guess, there must be a better approach then this.
Can anyone help me doing it in a proper way?

A: Use prefetch_related to optimize the query as,
Brand.objects.prefetch_related('model_set')

see the documentation for more details.


text:
Q: How to override a templates default option with javascript and css I´m using a template built upon bootstrap. It has a sidebar menu which can be toggled clicking on a button with the following code:
<a href="javascript:;" class="menu-toggler responsive-toggler" data-toggle="collapse" data-target=".navbar-collapse">

The menu's default state is uncollapsed. I know the following are very simple questions, but I have almost zero experience with javascript and css, and have not found a way to do it:
How can I call the previous code's functionality upon page load?
And what exactly is href="javascript:;" calling? How does it work?
Thank you.

A: For a more accurate answer, please provide a link to the template.

How can I call the previous code's functionality upon page load?

Try to simulate a click of the link on page load, with something like
 document.querySelector('.menu-toggler.responsive-toggler').click();

And what exactly is href="javascript:;" calling? How does it work?

Apparently, it call javascript code from a link, but I have to say I have never this syntax before. In this particuliar case, it cancels the basic anchor functionnality to go to another webpage or id in the page.