text:
Q: Macroscopic field is space-time average of the microscopic fields? Panofsky and Phillips' Classical Electricity and Magnetism. Chapter 2, Section 3.
The authors show, assuming the microscopic field $\mathbf{\mathcal E}$ and the microscopic charge density $\rho_a$ are related by $\nabla\cdot\mathbf{\mathcal E} = \rho_a/\varepsilon_0$, that the macroscopic field $\mathbf E$ is related by
$$
\nabla\cdot\mathbf E = \nabla\cdot\mathbf{\bar{\mathcal E}}\tag{*},
$$
where bar denotes space-time average.
They then claim that this implies that $\mathbf{E} = \bar{\mathcal E}$.
Question: I don't agree that (*) implies $\mathbf{E} = \bar{\mathcal E}$. What if the curls don't match? There can be many functions (which don't differ by just constants) with same divergence, no?
Note that the microscopic fields are not static.

A: If you look at pages 248--258 in Jackson [1999] you will find a detailed explanation of why/how one can derive the macroscopic Maxwell's equations from the microscopic ones.  I won't rederive them here but will note a few important points.
First, you need to define macro vs micro.  In this context, we assume all spatial scales larger than 10-14 m to be macroscopic, since such scales are large compared to atomic nuclei and electrons.  Therefore, we can treat both as point sources/particles.  Note that there will be no equivalent $\mathbf{D}$ or $\mathbf{H}$ fields in the microscopic domain because all of the charges and currents are local in the microscopic context.
We also know that all of these point particles are constantly undergoing some form of oscillation due to thermal fluctuations, zero point vibration, or orbital motion.  We also know that the variations will occur on spatial scales of 10-10 m or less and temporal scales between 10-13 s and 10-17 s.  Almost all instrumentation will average out most of these variations resulting in relatively smooth and slowly varying (compared to the time scales above) macroscopic quantities.  This averaging is largely unavoidable for any device seeking to measure macroscopic quantities but it begs the question of what types of averages we should be performing.  Spatial or temporal ensemble averages?
It turns out that spatial ensemble averages are the correct answer and one need not worry about temporal.  So we define the spatial ensemble average of some function, $F\left( \mathbf{x}, t \right)$, with respect to some test function, $f\left( \mathbf{x} \right)$, as:
$$
\langle F\left( \mathbf{x}, t \right) \rangle = \int \ d^{3}x' \ f\left( \mathbf{x}' \right) \ F\left( \mathbf{x} - \mathbf{x}', t \right) \tag{0}
$$
So one might assume we need to know $f\left( \mathbf{x} \right)$ ahead of time but we do not need to explicitly define it.  We only require that it be continuous such that it has a rapidly converging Taylor series for distances comparable to atomic scales.  Without loss of generality, we can also show that:
$$
\begin{align}
  \partial_{j} \langle F\left( \mathbf{x}, t \right) \rangle & = \langle \partial_{j} F\left( \mathbf{x}, t \right) \rangle \tag{1a} \\
  \partial_{t} \langle F\left( \mathbf{x}, t \right) \rangle & = \langle \partial_{t} F\left( \mathbf{x}, t \right) \rangle \tag{1b}
\end{align}
$$
where $\partial_{j} = \tfrac{ \partial }{ \partial x_{j} }$ and $\partial_{t} = \tfrac{ \partial }{ \partial t }$.  This results because the partial differential operators commute through the integral and they are of the ordinate $\mathbf{x}$ not $\mathbf{x}'$.  Note you can also use a spatial Fourier transform to derive the macroscopic version of Maxwell's equations.
As an aside, this type of averaging is also what lets one derive macroscopic properties like the electric polarization, magnetic moment, and the magnetization of a medium.  But recall, the critical piece here is that the averaging be a proper spatial ensemble average, not just the mean of a bunch of measurements or a time average.  They are not always equivalent (in fact, they are rarely the same).
References

*

*J.D. Jackson, Classical Electrodynamics, Third Edition, John Wiley & Sons, Inc., New York, NY, 1999.


text:
Q: SELECT all columns from distinct two columns I need to SELECT * where distinct 'Rua' with different 'CP' in the following DB:
id      Rua                  Local           Conc       CP
81143   dos moinhos          Rio Tinto       Gondomar   0123
81142   dos Moinhos          Rio Tinto       Gondomar   4435
81141   dos Moinhos          Rio Tinto       Gondomar   4435

With the following query, i am able to obtain the two columns:
SELECT Rua, CP
FROM  Codigo
GROUP BY Rua, CP
HAVING COUNT(*) = 1

But i want all the columns. SELECT * returns "Column 'Codigo.id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."
So i came upon this answer: How do I (or can I) SELECT DISTINCT on multiple columns?
I didn't go for the accepted answer, as i need a fast query (this will be used for AJAX search suggestions). I used the other highly upvoted answer. So, i created the following query:
SELECT * From Codigo
WHERE  (Rua,CP) IN (
   SELECT Rua, CP
   FROM   Codigo
   GROUP  BY Rua, CP
   HAVING COUNT(*) = 1
);

That returns An expression of non-boolean type specified in a context where a condition is expected, near ',' error. Why it expects Rua after WHERE to be boolean? In the answer they used saleprice which don't seem boolean.
So my question is how can i select all columns including the rows with same Rua and CP, but those only once (DISTINCT)?

A: SQL Server does not support (a,b) in (val1,val2) syntax
Use EXISTS to check the pair
SELECT *
FROM   Codigo C1
WHERE  EXISTS (SELECT 1
               FROM   Codigo C2
               WHERE  C1.Rua = C2.Rua
                      AND C1.CP = C2.CP
               HAVING Count(*) = 1);

or use COUNT() Over() Window aggregate function to count the records for each Rua, CP combination and filter the group which is having count as 1 to find one Rua row per each different CP.
SELECT *
FROM   (SELECT *,
               Count(1)OVER(partition BY Rua, CP) AS cnt
        FROM   Codigo C1) A
WHERE  cnt = 1

This will be my preferred approach since it is much efficient than using EXISTS the optimizer has to scan/seek the table only once
If you don't want duplicate records then use ROW_NUMBER()
SELECT *
FROM   (SELECT *,
               Row_Number()OVER(partition BY Rua, CP Order by id) AS RN
        FROM   Codigo C1) A
WHERE  RN = 1

I have ordered the duplicate records using Id column and picked the first record out of duplicates.

A: Using Window Function (Single table read):
SELECT t.*
FROM
  (SELECT t.*, COUNT(1) OVER (partition BY Rua, CP) AS cnt FROM Codigo t
  ) t
WHERE cnt = 1;

Using EXISTS (Reads the table twice):
SELECT *
FROM Codigo t1
WHERE EXISTS
  (SELECT 1
  FROM Codigo t2
  WHERE t1.Rua    = t2.Rua
  AND t1.CP       = t2.CP
  GROUP BY Rua, CP
  HAVING COUNT(*) = 1
  );

JOIN (Twice again):
SELECT C1.*
FROM Codigo C1
INNER JOIN
  (SELECT Rua, CP FROM Codigo C2 GROUP BY Rua, CP HAVING COUNT(*) = 1
  ) C2
ON C1.Rua = C2.Rua
AND C1.CP = C2.CP;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spring WS SOAP Request set signature reference URI's Need to add Custom Reference URI values to my SignedInfo and SecurityTokenReference.
Using Spring-WS and Spring-WS-Security and have created a SOAP Client that consists of mutual authentication, address header and setting of the binary security token and signature... all generates fine... except the Service provider requires me to set Reference URI to a specific value and not of the one the framework sets up.
I'm not sure how it can be done? I'm Using Wss4jSecurityInterceptor to create the signatures etc, but not sure how to define the specific URI's.
I do have a custom ClientInterceptor and I thought that perhaps I could do it there, but not sure if that's possible either.
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="SIG-81fb309">
            <ds:SignedInfo>
               <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
                  <ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="SOAP-ENV wsa" />
               </ds:CanonicalizationMethod>
               <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
               <ds:Reference URI="#id-29b0d50b-caa1-422a-b90d-bb6543300ff1">
                  <ds:Transforms>
                     <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
                  </ds:Transforms>
                  <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
                  <ds:DigestValue>gqH/tJW0lrWqkuugE8cUgkK3ofk=</ds:DigestValue>
               </ds:Reference>
            </ds:SignedInfo>
            <ds:SignatureValue>abcdefg</ds:SignatureValue>
            <ds:KeyInfo Id="KI-624f4c36-5">
               <wsse:SecurityTokenReference wsu:Id="STR-b426">
                  <wsse:Reference URI="#X509-74d2f26b-6e2b-4c07-b290-d4e71a94cd21" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" />
               </wsse:SecurityTokenReference>
            </ds:KeyInfo>

So from above need to set custom <ds:Reference/> and  <wsse:Reference/> URI's
ds:Reference URI="MYCUSTOMURI" and
wsse:Reference URI="MYCUSTOMURI"


text:
Q: SQL user is not used for login My problem is occuring when I try to login to SQL using user:'root', host: 'localhost', database: 'db' and password: '' ,the console gives error like I didn't define user
[!] SQL Error: Error: ER_ACCESS_DENIED_ERROR: Access denied for user ''@'localhost' (using password: NO)
My server.js:
import SQL from 'mysql';

 SQL: {

      host: 'localhost'
      user: 'root'
      password: ''
      database: 'root'

};

function load() {
    var MySQL = SQL.createConnection(SQL)
    MySQL.connect((err) => {
          if(err) {
             console.log(err);
             process.exit(0);
          }

          for(var i = 0; i < 250; i++) console.log("\n");
          console.log('Successfuly logged in!');

    });

}
load();

What can be done to prevent this error?
I am new to SQL and JS so please, don't be harsh on me if it's a stupid question :)
EDIT: I want to mention that I tried changing values of host, user, password and database and whatever I put, it says the same error.
I tried setting some random word for pass, example: password: 'pass123'
but the console gives me the same error inluding using password: NO part.
What could cause that problem?

A: Your SQL field isn't a valid object.
Change
SQL: {

      host: 'localhost'
      user: 'root'
      password: ''
      database: 'root'

};

to
credentials = {

      host: 'localhost'
      user: 'root'
      password: ''
      database: 'root'

};


text:
Q: Cramers v when r = 1 and k = 2 I have just read that 'Cramér's V may also be applied to goodness of fit chi-squared models when there is a 1×k table (e.g.: r=1)'. It then goes on to say 'In this case k is taken as the number of optional outcomes and it functions as a measure of tendency towards a single outcome.'  The source  is https://en.wikipedia.org/wiki/Cram%C3%A9r%27s_V
So if Cramer's v = sqrt (x2/n * min k – 1, r – 1) what would I multiply by in my case where k = 2 and r = 1?

A: If you divide the chi-square value by N and (k - 1), you will get a statistic [that ranges from 0 to 1 when conducting a chi-square goodness of fit test with equally distributed theoretical probabilities (e.g. 0.50 and 0.50 in your case). See this source.  See also the examples and documentation for this function.

A: While Mangiafico's response more than answers the question, I wish to add a bit of clarification which I have found personally useful.  (And my hope is to record in one place some of the information I have located on this topic.)
In brief, I was recently teaching a mathematical statistics course, and on the online homework system I use, I added a question to an assignment on multinomial distributions and goodness-of-fit tests.  Curiously, it was a question I had written some time ago.  When students started complaining that the question wasn't grading correctly, I did some investigating.  And this is how I located this thread.
First, the statistic being referred to in this thread does not quite appear to me to be the Cramér's $V$.  And, it took some time to locate a relatively easily accessible reference, but I did locate one.
Lomax & Hahs-Vaughn (2012) introduce an effect size (not labelled $V$ or such) for a multinomial goodness-of-fit (GoF) test (p.220)
$$\text{effect size} = \frac{\chi^2}{N(J-1)}$$
where $\chi^2$ is the test statistic for the GoF test, $N$ is the total sample size, and $J$ is the number of distinct categories.  The reason I'm reluctant to label this as a version of Cramér's V is because it does not include the square-root, and this is not an association problem.  (For reference, Cramér's $V$ is a measure of association—not fit—and is given by
$$V=\sqrt{\frac{\chi^2}{N \cdot \min(r-1,c-1)}}$$
as indicated here https://en.wikipedia.org/wiki/Effect_size#Other_metrics.)
The other common effect size that is reported for general chi-square tests is Cohen's W (https://en.wikipedia.org/wiki/Effect_size#Cohen's_w), which can be expressed as
$$W = \sqrt{\sum_{i=1}^J \frac{(p_j-\pi_j)^2}{\pi_j}}$$
or equivlalently
$$W = \sqrt{\frac{\chi^2}{N}}.$$
While this value can range from 0 to values larger than 1, the effect size proposed here does indeed range from 0 to 1, if the assumption is for an equiprobably distribution among the $J$ categories.
So, in summary, there appear to be three effect sizes that are related to each other in some fashion.  The first two are for fit to a multinomial distributions, and the last is for an association.  Summarized here, they are

*

*for a $1\times J$ table: Cohen's $W = \sqrt{\frac{\chi^2}{N}}$

*for a $1\times J$ table: quasi-$V = \frac{\chi^2}{N\cdot(J-1)}$

*for a $r\times c$ table: Cramér's $V = \sqrt{\frac{\chi^2}{N \cdot \min(r-1,c-1)}}$

As a brief addendum, I include here the proof that this quasi-$V$ obtains the (maximal) value of 1 if the expected frequencies are based on $J$ equiprobable categories and all of the frequency appears in only one of the $J$ categories.
$$\begin{align}V &= \frac{\chi^2}{N\cdot(J-1)} \\
&= \frac{1}{N\cdot(J-1)} \left(\frac{(N-\frac{N}{J})^2}{\frac{N}{J}} + (J-1)\frac{(0-\frac{N}{J})^2}{\frac{N}{J}}\right) \\
&= \frac{J}{J-1} \left((1-\frac{1}{J})^2 + (J-1)(\frac{1}{J})^2\right)\\
&= \frac{J}{J-1} \left(\left(\frac{J-1}{J}\right)^2 + \frac{J-1}{J^2}\right)\\
&= \frac{J-1}{J} + \frac{1}{J} \\
&= 1\end{align}$$


text:
Q: Writing a function in R to solve Plank's equation I am trying to write my first function in R to calculate emittance using Plank's function for different temperatures. I can do it manually as below for temperatures from 200 to 310 K.
pi <- 3.141593
h <- 6.626068963e-34
c <- 2.99792458e+8
lambda <- 4 * 1e-6
k <- 1.38e-23
t <- c (200:310)
a <- (2*pi*(c^2)*h)/(lambda^5)
b <- exp((h*c)/(lambda*k*t))
B <- a * (1/(b-1))

Where B is the vector of values I want.
Now here is an effort to write a function in R:
P_function <- function(t, pi = 3.141593, h = 6.626068963e-34, c = 2.99792458e+8,
             lambda = 4 * 1e-6, k = 1.38e-2) {
         ((2*pi*(c^2)*h)/(lambda^5)) *((1/(exp((h*c)/(lambda*k*t))-1)))
}

Now for different values of t (200-300K), how do I implement this function?

A: Couple of problems. First, pi is already a defined constant at better precision than you are using.
> rm(pi)  # remove your copy
> pi
[1] 3.141593   # default for console printing is  only 8 digits
> print(pi, digits=18)
[1] 3.14159265358979312  # but there is more "depth" to be had

Second, it makes no sense to put scientific constants in the parameter list. Since they're constant they can be defined in the body. Parameter lists are for items that might vary from situation to situation.
newPfun <- function(t) { h <- 6.626068963e-34
   c <- 2.99792458e+8
   lambda <- 4 * 1e-6
   k <- 1.38e-23
   a <- (2*pi*(c^2)*h)/(lambda^5)   #pi is already defined
   b <- exp((h*c)/(lambda*k*t))
   B <- a * (1/(b-1))
 return(B) }

This is just your original code "packaged" to accept a vector of temperatures. (And I'm pretty sure that's not the right spelling the scientist's name.)
Not sure where your second function is flawed. Perhaps a mismatched parenthesis. After trying to duplicate the results with a single expression and failing multiple times, I'm now wondering if it's really a problem with numerical overflow (or underflow).


text:
Q: Cakephp could not create tmp folder I'm using vagrant to setup my centos 6.6 x86_64 virtual OS. I have installed apache and cakephp into it.
I have let Apache run as vagrant user and in vagrant group. And the vagrant's Vagrantfile has the line config.vm.synced_folder "./gym", "/var/www", mount_options: ["dmode=777", "fmode=777"].
After I run the index.php, the cakephp report the error:

PHP Warning:  /var/www/gym_new/app/tmp/cache/persistent/ is not writable in /var/www/cake_2_6/Cake/Cache/Engine/FileEngine.php on line 385
PHP Warning:  _cake_core_ cache was unable to write 'file_map' to File cache in /var/www/cake_2_6/Cake/Cache/Cache.php on line 328

So I open the FileEngine.php there is the code trigger error:
/**
 * Determine is cache directory is writable
 *
 * @return bool
 */
    protected function _active() {
        $dir = new SplFileInfo($this->settings['path']);
        if (Configure::read('debug')) {
            $path = $dir->getPathname();
            if (!is_dir($path)) {
                mkdir($path, 0775, true);
            }
        }
        if ($this->_init && !($dir->isDir() && $dir->isWritable())) {
            $this->_init = false;
            trigger_error(__d('cake_dev', '%s is not writable', $this->settings['path']), E_USER_WARNING);
            return false;
        }
        return true;
    }

I think the permission has no problem so I create a brand new php just under webroot:

$path = "/var/www/gym_new/app/tmp/cache/";
if(mkdir($path, 0775, true) && is_dir($path) && is_writable($path))
{
    echo "true";
}
else
{
    echo "false";
    $error = error_get_last();
    echo $error['message'];
}

My code runs perfect and the folders (tmp and cache) is created successful. But the same code in cakephp cannot go through. So is there anything I have missed? The cakephp file is outside of the webroot, dose this cause the problem ?

A: The problem is if (Configure::read('debug')).
I found I haven't set debug to non-zero value, so cakephp won't create the folders even they don't exist.


text:
Q: overpass query took long time and no response I have a list with 900 (lat,lon) sets.
I used a loop to query each (lat,lon).
It stuck on 3rd set (48.55888888888889,12.404166666666667) and had no response.
My language is Java and reference this example(example).
The stuck line is HttpResponse response = getHttpClient().execute(post);
below is my query
[out:json][timeout:100];(way(around:5000,lat,lon)["waterway"="river"];way(around:5000,lat,lon)["waterway"="riverbank"];way(around:5000,lat,lon)["waterway"="waterfall"];way(around:5000,lat,lon)["tunnel"="*"];way(around:5000,lat,lon)["landuse"="forest"];way(around:5000,lat,lon)["natural"="water"];way(around:5000,lat,lon)["natural"="coastline"];way(around:5000,lat,lon)["natural"="geyser"];way(around:5000,lat,lon)["natural"="bay"];way(around:5000,lat,lon)["natural"="beach"];);
(._;>;);out body;
It can work on overpass turbo and take about 5 secs.
overpass_query
could any one give me some suggestions?

A: Many thanks for @mmd 's response help me to solve this problem.
status can check the resource you can use. My problem is allocate the resource. There are 2 slot available for each IP. I printed the response from overpass and got Error: runtime error: open64: 0 Success /osm3s_v0.7.54_osm_base Dispatcher_Client::request_read_and_idx::rate_limited. Please check /api/status for the quota of your IP address.
My solution is add TimeUnit.SECONDS.sleep(10); before httppost and add response.getEntity().getContent().close(); after getting the result.
Finally it works!


text:
Q: JQuery Click() not working after element ID change I try to change element id and then do something with it.
This script changes id, but click does not work. Some friends provided the following solution, but I would like to understand why.
Thanks for help.
$('#some').hover(
   function(){
       $(this).attr('id', 'new');
   }
);
$('#new').click(
   function(){
       $(this).fadeTo('slow' , 0.2);
   }
);

Solution:
$('#new').on('click',
function(){
   $(this).fadeTo('slow' , 0.2);
}
);

But why can't I use 'click' directly?
Update:
Thank you all for the answer. Here's a follow up:
I used the 'on' method to initiate the click event. Can I then include the same id in the function itself for it to fade?
Code:
       $('#new').live('click',
        function(){
       $('#new').fadeTo('slow' , 0.2);
       }
       );

I tried on my end but it failed to start the event. Any workaround suggestion is appreciated.

A: You are changing the DOM property dynamically. And events are attached to DOM, not to DOM property like class,id,name-value, etc. To make it work,Event delegation is the solution:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$(document).on('click','#new',function(){
   $(this).fadeTo('slow' , 0.2);
});

A: Try this code:
$('#some').hover(
    function(){ $(this).attr('id', 'new');
    $('#new').click( function(){
          $(this).fadeTo('slow' , 0.2);
    })
});

Your problem is when you define the second function, there is no element called $('#new') and the function cannot be binded, so if you define the second function inside the first, you avoid this.
I tried this code, and works perfect for me
1st)Change the id of #some to #new when mouse is over #some element
2nd)Fade #new when clicked #new element


text: Q: How can I configure securityDefinitions for swagger-ui? I've added the latest swagger ui to a project which auto generates the swagger.json definitions but doesn't include the new securityDefinitions object. I want to set up basic auth and have seen various docs about the objects and configs but don't understand where to add my securityDefinitions configs to the API so they are picked up in swagger.json. I also have the complete project source so am wondering if I'm supposed to add them to the swagger-config.yaml and make a custom dist build?


text:
Q: scaling of motor power For car engines, the cylinder volume is often associated with the engine power, which suggests scaling of the power as $L^3$ where L is the linear size. Consider a system consisting of a motor and its energy supply, e.g., an internal combustion engine with a fuel tank, or an electric motor with a battery, or a steam turbine with a nuclear reactor etc. Now we scale the system geometrically, up or down by some factor, using same materials, and assume that in the scaled system nothing breaks or burns through, so it can function. What should we expect for the scaling of the output mechanical power? Would it be close to $L^3$? Can an example be constructed where the scaling is very different from $L^3$?

A: This is really a comment not an answer, but it got a bit long for the comment box.
The problem with your question is that the power of the engine is related to the amount of fuel/air mixture that burns with each cycle, and the frequency (i.e. engine speed). There is clearly some connection between the amount of fuel/air mixture burned per cycle and the size of the cylinder it's burning in, but the efficiency of cylinder filling is affected by so many other factors that we rarely see any but the most basic correlation.
For example, most family cars come in a range of types from those aimed at grannies to those aimed at excessively enthusiastic teenagers and over this range you'll find that engines of the same size can produce very different powers. Typically this is because the valve timing and lift differs between the different engines and hence the cylinder filling efficiency varies. You might wonder why car manufacturers don't always aim at maximum filling efficiency - it's because if you maximise filling efficiency you tend to find you get a high efficiency at only a narrow range of engine speeds, which is great for the racetrack but not much use driving to supermarket.
If you take some example engine cylinder of capacity $C$ then the fuel/air mixture that fills it has to flow in through the inlet valves, and because air has a non-zero viscosity this takes time. If you now double the cylinder size (i.e. raise its volume to $8C$) but don't change the valve size the air/fuel flow rate wouldn't be adequate to fill the cylinder in the time available between cycles. So you double the valve size as well, but of course this only increases the valve area, $A$, by a factor of four to $4A$, and the ratio of valve area ($\approx$ flow rate) to cylinder volume has fallen by a factor of two. This means power won't scale with $L^3$. In practice engine manufacturers combine increased cylinder volume with changes to the valve design, and not simply size. Even so it's hard to maintain efficiency over a large range of cylinder sizes, which is why large engines tend to have more cylinders rather than the same number of bigger cylinders.

A: Leaving heat engines aside for now, let's try to understand the scaling for a DC electric motor with a battery, which seems to be a simpler case to analyze. For a circuit including a battery with EMF $E$, a motor, and some effective resistance R (distributed between the battery, motor winding, and connecting wires) one can write the energy equation
$E \; I = I^2 R + P_{mech}$
where $P_{mech}$ is the mechanical power in the motor.
Consider the maximum mechanical power for given $E$ and $R$. The maximum of the quadratic function is achieved at $I_0 = \frac{1}{2} E/R$ and is equal to $P_{max} = \frac{1}{4} E^2/R$.

Next, note that if we scale this system geometrically, keeping same materials, then $E$ stays the same (it is set by the electric chemistry of the materials) and $R$ scales as 1/L, where L is the linear size of the system. So the conclusion is that $P_{max}$ scales as L to the first power.


text:
Q: Angular js' $isEmpty functionality in form input My code looks something like this -
<form name="myForm" ng-submit="!myForm.phone.$isEmpty(this.$viewValue)" action="/my/url" method="get">
<input name="phone">
<button type="submit">submit</button>
</form>

Now I can't submit the form even if I fill the phone number field.
But if I code like this :
<form name="myForm" ng-submit="!myForm.phone.$isEmpty(myForm.phone.$viewValue)" action="/my/url" method="get">
<input name="phone">
<button type="submit">submit</button>
</form>

Its perfectly working now.
So the difficulty is with 'this'. I cant even check the context of this, it should be the the context of $scope.myForm.phone, but somehow it isn't. Can someone please explain.

A: That's not what ng-submit is for. ng-submit is a function or expression called when the form is submitted. It's nothing to do with validation. If you want to ensure the text field is not empty before it's submitted you just need to add required and then if it is empty myForm.$invalid will be true.
Is this what you are trying to do:
html
<form name="myForm" ng-submit="submit(phone)">
    <input name="phone" type="text" ng-model="phone.value" required>
    <button type="submit" ng-disabled="myForm.$invalid" >submit</button>
</form>

controller
$scope.submit = function(phone){
    console.log('phone', phone);
}

$scope.phone = {
    value: ''
};

update
The this that you passed into the ng-submit is a reference to your controller. Since you have the name attribute set to myForm you can access the form model via this.myForm and the phone model via this.myForm.phone. So if you wanted to use $isEmpty to verify if the field is empty you would have to use:
this.myForm.phone.$isEmpty(this.myForm.phone.$viewValue)

A: ng-submit is used to provide a handler for the moment when the form IS submitted.
 What you're looking for is disabling submit button with ng-disabled
<form name="myForm" ng-submit="functionInController()" action="/my/url" method="get">
<input name="phone" required>
<button type="submit" ng-disabled="myForm.$invalid">submit</button>
</form>

Pay attention to required directive added to the input. Which makes sure this field is not empty for submit


text:
Q: The getter key was called on null Until two days ago the app was running normally. When I tried to run it again yesterday, without making any changes I get the following error:
 ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building Builder(dirty):
The getter 'key' was called on null.
Receiver: null
Tried calling: key

The relevant error-causing widget was:
  MaterialApp file:///C:/Users/jakel/Documents/GitHub/app_inspecciones/lib/main.dart:19:5

When the exception was thrown, this was the stack:
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1      ExtendedNavigator.builder.<anonymous closure> (package:auto_route/src/extended_navigator.dart:37:36)
#2      _MaterialAppState._materialBuilder.<anonymous closure> (package:flutter/src/material/app.dart:756:39)
#3      Builder.build (package:flutter/src/widgets/basic.dart:7555:48)
#4      StatelessElement.build (package:flutter/src/widgets/framework.dart:4569:28)
#5      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4495:15)
#6      Element.rebuild (package:flutter/src/widgets/framework.dart:4189:5)
#7      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4474:5)
#8      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4469:5)
...     Normal element mounting (258 frames)
#266    Element.inflateWidget (package:flutter/src/widgets/framework.dart:3541:14)
#267    Element.updateChild (package:flutter/src/widgets/framework.dart:3306:18)
#268    RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1182:16)
#269    RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1153:5)
#270    RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:1095:18)
#271    BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2647:19)
#272    RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1094:13)
#273    WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:934:7)
#274    WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:915:7)
(elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)

════════════════════════════════════════════════════════════════════════════════════════════════════

The error is in main.dart
Future main() async {
 Provider.debugCheckInvalidValueType = null;
 WidgetsFlutterBinding.ensureInitialized();
 await configureDependencies();
 final navigatorKey = GlobalKey<NavigatorState>();
 await FlutterDownloader.initialize();
 runApp(
   MaterialApp(
     builder: ExtendedNavigator.builder(
       observers: [ClearFocusOnPop()],
       navigatorKey: navigatorKey,
       router: AutoRouter(),
       builder: (context, extendedNav) => GestureDetector(
         onTap: () async {
           // esto quita el foco (y esconde el teclado) al hacer tap
           // en cualquier lugar no-interactivo de la pantalla https://flutterigniter.com/dismiss-keyboard-form-lose-focus/
           final currentFocus = FocusScope.of(context);
           if (!currentFocus.hasPrimaryFocus &&
               currentFocus.focusedChild != null) {
             currentFocus.focusedChild.unfocus();
           }
         },
         child: Theme(
           data: customTheme,
           child: BlocProvider(
             create: (context) =>
                 getIt<AuthBloc>()..add(const AuthEvent.startingApp()),
             child: AuthListener(
               navigatorKey: navigatorKey,
               child: extendedNav,
             ),
           ),
         ),
       ),
     ), //InspeccionScreen(),
   ),
 );
}

This is my dependences in pubspec.yaml file
dependencies:
  flutter:
    sdk: flutter
  auto_route: ^0.6.9
  collection: ^1.14.13
  cupertino_icons: ^0.1.3
  dartz: ^0.9.2
  data_connection_checker: ^0.3.4
  dropdown_search: ^0.4.8
  enum_to_string: ^1.0.14
  flutter_archive: ^2.0.1
  flutter_bloc: ^6.1.1
  flutter_downloader: ^1.5.2
  freezed_annotation: ^0.12.0
  get_it: ^5.0.1
  image_picker: ^0.6.7+15
  injectable: ^1.0.5
  intl: ^0.16.1
  json_annotation: ^3.1.1
  kt_dart: ^0.8.0
  moor: ^3.3.1
  moor_db_viewer: ^2.0.3
  multi_select_flutter: ^3.1.6
  rflutter_alert: ^1.1.0
  open_file: ^3.0.3
  path: ^1.7.0
  path_provider: ^1.6.18
  pdf: ^1.13.0
  provider: ^4.3.2+2
  reactive_forms: ^7.6.2
  share: ^0.6.5+4
  shared_preferences: ^0.5.12+4
  sqlite3_flutter_libs: ^0.3.0
  timeline_tile: ^1.0.0
  checkbox_formfield: ^0.1.0+3

dev_dependencies:
  flutter_test:
    sdk: flutter
  auto_route_generator: ^0.6.10
  build_runner: ^1.10.9
  flutter_launcher_icons: ^0.8.1
  freezed: ^0.12.6
  injectable_generator: ^1.0.6
  json_serializable: ^3.5.1
  lint: ^1.3.0
  moor_generator: ^3.3.1

But I don't understand why it works before and now it doesn't.
I have already tried looking for information on the web but did not find anything. I don't know what could have happened. Maybe it was the flutter update to version 2.0.2
Could anyone help me, please?

A: Try using the latest version of auto_route.
ExtendedNavigator.builder is deprecated now.
Use routeDelegate property of material app.
final _appRouter = AppRouter()
   ...
  Widget build(BuildContext context){
      return MaterialApp.router(
             routerDelegate: _appRouter.delegate(...initialConfig),
             routeInformationParser: _appRouter.defaultRouteParser(),
         ),
  }

A: follow up on this thread, https://github.com/Milad-Akarie/auto_route_library/issues/378
temp solution is adding an onGenerateRoute or dummy widget to home property in materialapp widget


text:
Q: Oracle Combine several columns into one I have a question in regarding to Oracle Sql,
If I have a data called A, with 8 columns:
Spot| ID |Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday
-------------------------------------------------------------------------
   A| 1  | 0.1  |0.15  | ...........................................
-------------------------------------------------------------------------
   A| 2  | 0.2  |0.2   | ...........................................
-------------------------------------------------------------------------
   A| 3  | 0.3  |0.25  | ...........................................
-------------------------------------------------------------------------
   A| 4  | 0.4  |0.4   | ...........................................
-------------------------------------------------------------------------

Can I convert it to a table B like this:
Spot| Day of Week  | ID | Value
-------------------------------------------------------------------------
   A| 1            | 1  |  0.1
-------------------------------------------------------------------------
   A| 1            | 2  |  0.2
-------------------------------------------------------------------------
   A| 1            | 3  |  0.3
-------------------------------------------------------------------------
   A| 1            | 4  |  0.4
-------------------------------------------------------------------------
   A| 2            | 1  |  0.15
-------------------------------------------------------------------------
 .......................................................................

Which is to combine columns (Sunday through Saturday) to a new column called 'Day of Week'
How can I do that please? Thanks!

A: There are essentially three ways to do this, each with their advantages and disadvantages. (There may be more than three, these are the ones I know.)
The first method uses UNION ALL and it is fine for small tables (performance is not important). It works in any version of Oracle. It goes something like this:
select spot, 1 as day_of_week, id, sunday  as value from a union all
select spot, 2               , id, monday           from a union all
.......

It's inefficient, because the base table (A) is read seven times, one time for each branch of UNION ALL. Some rows may be cached, so perhaps it's not totally I/O time multiplied by seven, but it's still inefficient.
Since Oracle 11.1 we have had PIVOT and UNPIVOT. You need unpivoting, like this:
select  spot, day_of_week, id, value
from    a
unpivot ( value for day_of_week in ( sunday as 1, monday as 2, .... ) )
;

This will work faster; it is not clear how Oracle implemented this under the hood, it may still do a UNION ALL, but a smart one - where the same row is used seven times, instead of being read repeatedly from disk. The disadvantage, of course, is that it is not available in older versions of Oracle.
The third method uses a Cartesian join. It will work fast and it is available in all versions.
select a.spot, h.day_of_week, id,
       case h.day_of_week when 1 then sunday
                          when 2 then monday
                          ..................
                          when 7 then saturday
       end  as value
from   a
       cross join
       ( select level as day_of_week from dual connect by level <= 7) h
;

The subquery h in this solution may look fancy, but all it does is to create an inline view h with a single column, day_of_week, with the values from 1 to 7. It can be created in any other way, this is just a fast (and common) one.

A: You can use UNPIVOT:
Oracle Setup:
CREATE TABLE your_table ( spot, id, sunday, monday, tuesday, wednesday, thursday, friday, saturday ) AS
  SELECT 'A', 1, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4 FROM DUAL UNION ALL
  SELECT 'A', 2, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45 FROM DUAL UNION ALL
  SELECT 'A', 3, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5 FROM DUAL;

Query:
SELECT *
FROM   your_table
UNPIVOT ( Value FOR Day_of_week IN (
  sunday    AS 1,
  monday    AS 2,
  tuesday   AS 3,
  wednesday AS 4,
  thursday  AS 5,
  friday    AS 6,
  saturday  AS 7
 ) );

Output:
S ID DAY_OF_WEEK VALUE
- -- ----------- -----
A  1           1    .1
A  1           2   .15
A  1           3    .2
A  1           4   .25
A  1           5    .3
A  1           6   .35
A  1           7    .4
A  2           1   .15
A  2           2    .2
A  2           3   .25
A  2           4    .3
A  2           5   .35
A  2           6    .4
A  2           7   .45
A  3           1    .2
A  3           2   .25
A  3           3    .3
A  3           4   .35
A  3           5    .4
A  3           6   .45
A  3           7    .5


text: Q: How to transpose a JavaRDD in Spark using Java 8 I have a tab delimited file with numbers (forming a matrix) and I want to transpose the values. I've seen the other question where there is a scala answer but I can't seem to make it work using Java.


text:
Q: Is it safe to load a scene with LoadSceneMode.Additive while unloading the same scene index in an UnloadAsync call in Unity? I am learning the workflow of using sub scenes in Unity, but some little details elude me. For reference, my loaded scenes are:

*

*Bootstrapper and Game State (Index 0)

*Game Scene (Index 1)

*Audio Handler (Index 3)

In a case where I need to refresh my game scene, my instinct would be to do the following:
void RefreshScene()
{
    int sceneNumber = 1;
    SceneManager.UnloadSceneAsync(sceneNumber, UnloadSceneOptions.UnloadAllEmbeddedSceneObjects)
    SceneManager.LoadScene(sceneNumber, LoadSceneMode.Additive);
}

But I fear I might be opening myself to weird race conditions? Does Unity handle this case gracefully? Or would I need to actually wait for the scene unloading to be done first in this case with code such as
IEnumerator RefreshScene()
{
    int sceneNumber = 1;
    var task = SceneManager.UnloadSceneAsync(sceneNumber, UnloadSceneOptions.UnloadAllEmbeddedSceneObjects)
    while(!task.isDone)
    {
        yield return null;
    }
    SceneManager.LoadScene(sceneNumber, LoadSceneMode.Additive);
    OnLoadIsDone();
    yield return null;
}

The problem however with the above code is that I get a frame where no camera is present.

A: I believe it is safe. You can also use additive load on a loading scene, unload the precious scene completely and when that's done load it again. Have the loading scene have a UI Overlay Canvas that is above all other UI. Once the scene is fully loaded unload the loading scene.
I can write a more detailed answer when not on mobile if you need.


text:
Q: onResume() isn't triggering on TabHost items switching I have a TabHost with two tabs in it. The first time I switch to the second tab the onResume() method of my second's tab's activity invoked. Then I have an AlertDialog shown and after it disappears the 'onResume()' method isn't called but I really wait for it. I presume that invocation of 'AlertDialog' triggers 'onPause()' method and the 'onResume()' should be called before 'Activity' is actually shown and ready for interaction with user. But in face 'onPause()' isn't called when I switch back to the first tab which is another activity.
Can you advice why the 'onPause()' and 'onResume()' methods aren't called and what methods are called after showing an 'AlertDialog' or switching between tabs?

A: When you create a TabHost to hold Activities, the childrens inside it can't manage their own lifecycled methods (onResume, onPause, onCreated, etc), and the parent (the holder) must do all the managements. I've implemented this behavior by overwriting onPause and onResume in the holder (the Activity that defines the tabhost), like this:

@Override
public void onPause() {
    super.onPause();
    try {
        mlam.dispatchPause(isFinishing());
    } catch (Exception e) {}
}

@Override
public void onResume() {
    super.onResume();
    try {
        mlam.dispatchResume();
    } catch (Exception e) {}
}

Where "mlam" is the LocalActivityManager instance. With it, I think that your onResume/onPause methods gonna be triggered. Hope that this helps you in some way.

A: @mthama's answer worked perfectly fine and had declared LocalActivityManager as a local variable at the Tabhost level. However if I wanted just one of the onResume() on a specific tab to fire, I did as follows.
protected void onResume() {
     super.onResume();
     try {
         if(mLocalActivityManager != null){
             TabActivityOne tabActivity1 = (TabActivityOne) mLocalActivityManager.getActivity("tabId1");
             if(tabActivity1 != null){
                 tabActivity1.onResume();
             }
         }
    } catch (Exception e) {

    }
}

A:
I presume that invocation of 'AlertDialog' triggers 'onPause()' method and the 'onResume()' should be called before 'Activity' is actually shown and ready for interaction with user

AlertDialog does not affect the Activity's Life Cycle.
Check out the Activity's Life Cycle Flow Chart Here.
When switching between Tabs, if you want a call back method why don't you use a TabChanged Listener

A: I have the same problem, and I try this, and it works~~
private OnTabChangeListener TabChangeListener = new OnTabChangeListener() {

    @Override
    public void onTabChanged(String tabId) {
        if (tabId.equals("download")){
            mlocalActivityManager.dispatchPause(isFinishing());
            mlocalActivityManager.dispatchResume();
            tabs.setCurrentTab(1);
        }
    }
};


text:
Q: What happens to the Javascript "wrapper" code when the NodeJs source code gets compiled to binary? I just recently started a Course about Nodejs, where its internals are covered just to get a good mental model about how it is built and how it works. Yet, something that I can't find information about is what happens to the "wrapper Js code" that is bound (through the process.binding('<CppObjName>')) to the compiled C++ Objects when NodeJs Itself gets compiled for a specific platform:

*

*Is it stored somewhere in the host machine as plain text and then fed (say, "loaded") as javascript to the V8 when the NodeJs executable (NodeJs Itself) is run?

*Or is it "compiled" to a specific binary format and bundled together with the rest of the compiled C++ Code and V8 (so when when the NodeJs executable is run, such binary is the one loaded into the V8 in order to provide such Objects to the Node API)?


text:
Q: include css in magento2 for custom theme I am trying to include custom css and js in custom theme and should come on all pages.
I have tried this from the Magento DevDocs, but I can't make it right and it's not showing. Please help me.

A: For keep css and js in all pages you have to customize default_head_blocks.xml file. set file,
magento2/app/design/frontend/{Vendor}/{themename}/Magento_Theme/layout/default_head_blocks.xml file
Put inside <head> tag,
<css src="css/styles.css"/>
<script src="js/custom.js"/>

Add your css file inside,
app/design/frontend/{Vendor}/{theme}/web/css/styles.css

Add your custom js
 app/design/frontend/{Vendor}/{theme}/web/js/custom.js

Remove cache folder and try.
Its now working in all pages of site.

A: When I updated my theme, my css files got deleted from app/design/bluesky/frontend/theme-name/web/css/custom.css and also the path from the
default_head_block_xml.


text:
Q: Custom column on django-tables2 that mix multiple foreignkeys I am trying to make a custom column on django-tables2 with a function that returns the field that is not empty from 3 possibles foreign keys (just one can be not empty). Here is what I've done:
Models.py
class Sitiocancelado(models.Model):
    x = models.OneToOneField(X, on_delete=models.CASCADE, null=True,blank=True)
    y = models.OneToOneField(Y, on_delete=models.CASCADE, null=True, blank=True)
    z = models.OneToOneField(Z, on_delete=models.CASCADE, null=True, blank=True)
    fecha_de_cancelacion = models.DateField(null=True, blank=True)
    comentarios = models.TextField(max_length=200, null=True, blank=True)
    slug = models.SlugField(max_length=100, editable=False)

    def __str__(self):
        return self.z.y.x.nombre_del_sitio

Tables.py
class SitiocanceladoTable(tables.Table):

    def columna_combinada(table):
        if x == None:
            if y == None:
                return z
            else:
                return y
        else:
            return x

    Sitio = tables.Column(columna_combinada)

    class Meta:
        model = Sitiocancelado
        attrs = {
            'class': 'table table-striped table-bordered',
            'id': 'example',
            'width' : '100%',
        }
        fields = ('Sitio',)
        exclude = ('id', 'slug', 'sitioproyecto', 'sitiocontratado', 'sitiooperando',)

Does it make any sense?

A: That's not really how custom columns work. You basically have two options:
render_<columnname>
This looks a bit like your example. Define a column and a method on the table class with name render_<column name>. No need to supply that name to the column you defined. Your example would look like this:
class SitiocanceladoTable(tables.Table):
    Sitio = tables.Column(empty_values=())

    class Meta:
        model = Sitiocancelado

    def render_Sitio(self, record):
        if record.x == None:
            if record.y == None:
                return record.z
            else:
                return record.y
        else:
            return record.x

This method is good for one-offs. It is not much extra code, and the code is very close with the rest of the definition of the table.
Note that I added emtpy_values=(). This will make sure your custom implementation of the render function used, even if django-tables2 thinks your column is empty. It's the responsibility of the custom column to render a proper default.
Subclassing Column
If you need the functionality of this column in multiple tables, or multiple times in the same table, it might be cleaner to subclass Column or one of the more specific Column implementations.
Your example might look like this:
class CombinedFKColumn(tables.Column):
    def render(self, record):
        return getattr(record, 'x', getattr(record, 'y', getattr(record, 'z', self.default)))

class SitiocanceladoTable(tables.Table):
    Sitio = tables.CombinedFKColumn(empty_values=())

    class Meta:
        model = Sitiocancelado


text:
Q: Python methods (user-defined) returning "builtins.AttributeError: 'NoneType'" I have this project for college and I'm running into a couple of errors in the test file provided by the teachers.
Most of them are related to this. For example, doing the following:
caminho(posicao(0,0)).caminho_junta_posicao('este').caminho_origem()

returns:
Traceback (most recent call last):
  File "<string>", line 1, in <fragment>
builtins.AttributeError: 'NoneType' object has no attribute 'caminho_origem'

However, doing this:
c1 = caminho(posicao(0,0))
c1.caminho_junta_posicao('este')
c1.caminho_origem()

doesn't return any errors but the intended position.
And I can't figure out why that happens.
Bellow is the code defining both of the classes from the example, as my problem with others lies in very similar. Any help would really be appreciated. Thanks.
class posicao:
    def __init__(self,l,c):
        self.posicao=(l,c)
    def posicao_linha(self):
        return self.posicao[0]
    def posicao_coluna(self):
        return self.posicao[1]
    def posicao_igual(self,p2):
        return self.posicao[0] == p2.posicao_linha() and self.posicao[1]\
               == p2.posicao_coluna()
    def posicao_relativa(self,d):
        if d=='norte':
            return posicao(self.posicao_linha()-1,self.posicao_coluna())
        elif d=='sul':
            return posicao(self.posicao_linha()+1,self.posicao_coluna())
        elif d=='este':
            return posicao(self.posicao_linha(),self.posicao_coluna()+1)
        elif d=='oeste':
            return posicao(self.posicao_linha(),self.posicao_coluna()-1)

class caminho:
    def __init__(self,p):
        self.caminho = [p]
    def caminho_junta_posicao(self,d):
        p = self.caminho[-1]
        self.caminho = self.caminho + [p.posicao_relativa(d)]
    def caminho_origem(self):
        return self.caminho[0]
    def caminho_destino(self):
        return self.caminho[-1]
    def caminho_antes_destino(self):
        return self.caminho[:-1]
    def caminho_apos_origem(self):
        return self.caminho[1:]
    def caminho_comprimento(self):
        return len(self.caminho)
    def caminho_contem__ciclos(self):
        for p in range(len(self.caminho)):
            for p2 in self.caminho[p:]:
                if p2.posicao_igual(self.caminho[p]):
                    return True
        return False
    def caminho_elimina_ciclos(self):
        caminho = self.caminho
        if self.caminho_contem_ciclos():
            for p in caminho:
                for p2 in caminho[caminho.index(p):]:
                    if p.posicoes_iguas(p2):
                        caminho = caminho[:index(p)]+caminho[index(p2):]

A: The code you expect to work (but doesn't) doesn't work because your method caminho_junta_posicao() doesn't explicitly return a value, which means it returns None, causing the error you're seeing.
The code which you stated did work (your second example), didn't actually work when I tried it (Python 3.1.3) -- I got the same error as before.
This is as expected, in that the behavior is consistent.

A: This method:
def caminho_junta_posicao(self,d):
    p = self.caminho[-1]
    self.caminho = self.caminho + [p.posicao_relativa(d)]

doesn't explicitly return anything, so the result of calling it is None.  Therefore,
 caminho(posicao(0,0)).caminho_junta_posicao('este')

will give None, and None doesn't have a caminho_origem() method, hence your error.
Python convention is usually that methods which act in-place (like .append, .extend, and here your .caminho_junta_posicao) return None, which makes chaining like this impossible.  On the other hand, it makes accidentally modifying the original object in a chain which you think is working on copies much harder.  Sometimes chaining does come in handy, though (see the pandas library, for example, which makes extensive use of it to great benefit.)
I don't recommend doing this, but if you modified the method to return self at the end, i.e.
def caminho_junta_posicao(self,d):
    p = self.caminho[-1]
    self.caminho = self.caminho + [p.posicao_relativa(d)]
    return self

then the result of caminho(posicao(0,0)).caminho_junta_posicao('este') would be your (now-modified) caminho object, and you could chain it the way you tried.


text:
Q: Understanding Multiplication/Dot Product of Two Numbers/Two Vectors This might be a silly question, but I just realized I don't think I understand what multiplication really is. For example I know $3\cdot4=12$ because that's what you learn in school. If we go with the idea of multiplication as repeated addition, $3\cdot4$ means add $3$ to $0$ (the zero elements) $4$ times. So here we have multiplication defined in terms of addition and the zero/identity element for natural numbers.
My confusion is around numbers that have units. Say we have oranges, how does one interpret $3$ oranges $\cdot 4$ oranges?
Does adding a unit (oranges) to the number make it a vector and therefore the multiplication operator has a different meaning because for two vectors it's dot products? If so, why do we interpret the multiplication of a basis vector with itself to be 1?

A: It may be hard to understand from an outside point of
view but mathematics is based on precise definitions
that are decided on by mathematicians among themselves.
Thus, for example, the dot product of a unit vector
with itself is $\,1\,$ as a consequence of the precise
definition of the dot product of vectors. However, in
order to multiply oranges by oranges there is no such
precise definition of the result. Of course, you or
anyone else are free to come up with a definition if
that is desired. This new hypothetical definition may
not be useful or well defined but it could be done.
Other than that, there is no currently meaningful way
to multiply two oranges, as far as I know.
As for the precise definition of dot product of two
vectors, such as $\,\vec{i}\cdot\vec{i}\,,$ this is
closely related to the definition
of vectors themselves as geometric objects (loosely
imagined as arrows in space). The origin of vectors
has a long and interesting history. Some of this is
in Michael J. Crowe's book, A History of Vector
Analysis and several other sources. More details
are not suitable for MSE.

A: I think learning a bit of Abstract Algebra (here's an introduction) will answer some of these questions. An operator (addition/multiplication/etc) and type of objects (integers/reals/vectors/etc) it acts on - come together. You need to define what a multiplication is for this type of objects. For instance:

*

*Multiplication of 2 integers can be represented with repeated addition as you mentioned

*(Scalar) Multiplication of a geometrical vector (an arrow) is stretching squeezing that vector. Imagine a physical stretching of an arrow without multiplication of its components. You just have an instruction to stretch 2x and that's what you do with a pen and paper.

You can come up with any mathematical operation which does craziest things. But most of such operations will be useless. E.g. they won't help finding unknown $x$ in the equation: $a*x=b$ where $*$ is your new mathematical operation, and $a, x, b$ are your new type of objects (I don't know.. let's say they are circles - you multiply circles). While existing, real maths creates these structures & operations in a way to be useful for some purpose.
Dot product is not a multiplication in the typical sense. E.g. you can't solve  $a\cdot x=b$. This operation has a completely different purpose - it's useful for different reasons. E.g. it can be used:

*

*To define length of a vector: $|a|=\sqrt{a\cdot a}$

*To find a unit vector (of length 1) that points to the same direction: $\frac{a}{|a|}$

*To find out if vectors are perpendicular (when $a\cdot b=0$)

*To find projections of one vector onto another ($b\cdot \frac{a}{|a|}$)

That's why Dot Products are useful - not because they can e.g. solve equations. Incidentally all this math can be generalized. Notice that e.g. functions like polynomials also have similar properties like geometrical vectors: you can multiply them by a scalar, you can add them. But then - what would be a length of such "vector"? What is a dot product? To answer these questions a list of requirements are introduced for such products taken from what we just saw like length of a unit vector $\frac{a}{|a|}$ is 1, and others. So if we could come up with a new operation that obeys these properties - we can use it the way we used dot products.
Such products are now called Inner Products and Dot Product is just one of the implementations. For functions for instance you could define a different implementation like $\int{f(x)f(x)dx}$ is going to be similar to $a \cdot a$. It's possible to define all sorts of implementations for Inner Product, but they still have to obey those roles. And now we can define what length is and it means to be perpendicular for functions and other entities that obey similar rules. And we can re-use all the maths from vectors with these entities - when used in such a way these entities and their respective operations are called Abstract Vectors.
Now units is about giving physical sense to numbers. Can you multiply oranges? Mathematically - the requirement is that you have right entities (e.g. integers) and appropriate operation (e.g. multiplication). But whether this has physical sense - that's not up to math to decide. If $orange^2$ (area of a field of oranges) makes sense - then go ahead and do the operation.
If you use oranges as one of the components of your vector e.g. then $|o|=\sqrt{o \cdot o}$ is still a length of a vector, so it gives you number of oranges in it (which you knew from the vector's component already).


text:
Q: My accumulator is registering as a string....SO LOST My problem is probably simple as usual guys and gals, I've been working on this thing for 13 hours now and I can't get this this to accumulate the names variable.
I need it to count players that I have input data for. This is the error message I'm getting:
line 25, in main
    name += 1
TypeError: Can't convert 'int' object to str implicitly

For this input/output:
You will be asked to enter players names and scores
When you have no more names, enter End

Enter Player's Name or end to end program:vxzcvzvc
Enter vxzcvzvc's golf score: 3
Enter Player's Name or end to end program:zcvxcxzvxzv5
Enter zcvxcxzvxzv5's golf score: 6
Enter Player's Name or end to end program:zcvxvczx
Enter zcvxvczx's golf score: 5
Enter Player's Name or end to end program:end
You have written end players records to golf.txt

This is my code:
def main():
     #Program that reads each player's name and golf score as input
     #Save to golf.txt
     outfile = open('golf.txt', 'w')

     #define name
     name = 0
     name += 1

     # introduction to user explaining required information to be entered
     print("You will be asked to enter players names and scores")
     print("When you have no more names, enter End")
     print("\n")

     #Enter input, leave blank to quit program
     while True:
         name = input("Enter Player's Name or end to end program:")
         if name == "end":
              break
         score = input("Enter "+ str(name)+"'s golf score: ")

         #write to file golf.txt
         outfile.write(name + "\n")

         outfile.write(str(score) + "\n")

     #output for number of names recorded
     print("You have written", name,"players records to golf.txt")
     outfile.close()
main()

A: You need a separate variable for counting the number of scores that have been written:
def main():
    outfile = open('golf.txt', 'w')

    # Change this:
    count = 0

    print("You will be asked to enter players names and scores")
    print("When you have no more names, enter End")
    print("\n")

    while True:
        name = input("Enter Player's Name or end to end program:")
        if name == "end":
            break
        score = input("Enter {}'s golf score: ".format(name))
        outfile.write(name + "\n")
        outfile.write(str(score) + "\n")
        # add this:
        count += 1

    # change this:
    print("You have written {} players records to golf.txt".format(count))
    outfile.close()

main()


text:
Q: Properties of two solutions of free fall ODE The equation $$\ddot{s}(t) = -\gamma M \cdot \frac{1}{s(t)^2}$$ models a free fall trajectory under the influence of gravity from a large distance ($\gamma$ and $M$ are constant). One of the solutions to this equation has the form $$\overline{s}(t) = at^{2/3}$$
I want to show that if $s(t) > 0$ for all $t\in \{t\in\mathbb{R}:t\ge 0\}$, $s(t_0) = \overline{s}(t_0)$, $0<\dot{s}(t_0)<\dot{\overline{s}}(t)$, then $s(t) < \overline{s}(t)$ and $\dot{s}(t)<\dot{\overline{s}}(t)$ for all $t>t_0$. Moreover, $\dot{s}(t)$ has one zero.
I'm including my questions within my solution attempt below, and I'm asking you to kindly answer these questions.

My attempt:

Let $d(t):= \overline{s}(t)-s(t)=at^{2/3}-s(t)$, then $d(t_0)=0$. $\dot{d}(t)=\dot{\overline{s}}(t)-\dot{s}(t)=\frac{2a}{3t^{1/3}}-\dot{s}(t)$ and $\dot{d}(t_0)>0$. Also, $\ddot{d}(t_0)=0$. Thus we have that there is a $t'>t_0$ in the $\varepsilon$-neightbourhood of $t_0$ such that $\dot{d}(t')>0$, so that ${d}(t')>0$ and $\ddot{d}(t')>0$.

I'm stuck here. Can we rigorously conclude from the above that $\dot{d}(t)>0$ for all $t$?

For the second part of the question, if we have that $\lim\limits_{t\to \infty} \dot{s}(t)=0$ and $\dot{s}(t)<\dot{\overline{s}}(t)$, then does this imply that $\lim\limits_{t\to\infty} \dot{s}(t) <0$? I think this only implies that $\lim\limits_{t\to\infty} \dot{s}(t) \le 0$. Also, taking this limit does not necessarily imply $\dot{s}(t)$ has a root somewhere.
Would appreciate some help with this.


text:
Q: How to use Application.OpenForms in c# In a c# project how to use "Application.OpenForms"
how it use in the project, for identify a Form is already open or not...
can you show me a example.

A: Timesheet ts = (Timesheet)Application.OpenForms["Timesheet"];
ts.Invoke((MethodInvoker)(() => ts.dataGrid3.DataSource = null));


text:
Q: Distribute negative account balances to positive account balances to minimize the amount left over Using excel, I have a list of accounts in column A (call them Account 1, Account 2, Account 3, etc.). In column B, I have an account balance for each individual account, ranging from -10.00 to 10.00.
For clarity:
Col A        Col B
Account 1    -5.15
Account 2     3.94
Account 3     9.13
Account 4    -0.33
Account 5     8.04
etc.

I'm dealing with hundreds of accounts.
What I would like to do, is figure out the most efficient way to balance every account to zero. And do so by allocating negative balances to positive balances. Whether that be multiple accounts with negative balances being consolidated to balance 1 account with a positive balance, or 1 negative account balancing multiple positive accounts. My goal is to have the value left over after every account has been balanced to zero, to be as close to zero as possible.
Lastly, in col C, I'd like the cells in each row to call out which account(s) to pull from, to balance the account in col A to zero. In col D, I'd like the cells in each row to call out the value needed from the account(s) in col C, to be allocated to the account in col A.
I'm not sure if this can be done with formulas, or using VBA. Each and every solution is more than welcomed.
Thank you.

A: Not much data to test with but try this. It first sorts the data on Sheet1 by column B. The credits and matching debits appear on Sheet2. It only tries to match single values so wouldn't choose two smaller values that might be a better match than one larger value.
Option Explicit
Sub AccountMatch()

    Dim iLastRow As Long, i As Long, j As Long, iRow As Long
    Dim credit As Currency, debit As Currency

    iLastRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
    For i = 2 To iLastRow
        Sheet1.Cells(i, 3) = i
    Next

    ' results sheet
    Sheet2.Cells.Clear
    iRow = 1

    ' sort values
    With Sheet1.Sort
         With .SortFields
            .Clear
            .Add Key:=Range("B2:B" & iLastRow), SortOn:=xlSortOnValues, _
                 Order:=xlDescending, DataOption:=xlSortNormal
         End With
        .SetRange Range("A1:C" & iLastRow)
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

    ' match credit to debits
    i = 2
    credit = Sheet1.Cells(i, "B")
    Do While credit > 0
        iRow = iRow + 1
        Sheet2.Cells(iRow, 1) = Sheet1.Cells(i, 1)
        Sheet2.Cells(iRow, 2) = credit

        ' match negative moving upwards
        For j = iLastRow To 1 Step -1
            If Sheet1.Cells(j, 4) = "" Then
                debit = Sheet1.Cells(j, "B")
                If debit > 0 Then Exit For
                If credit + debit > 0 Then
                    Sheet2.Cells(iRow, 3) = Sheet1.Cells(j, 1)
                    Sheet2.Cells(iRow, 4) = debit
                    iRow = iRow + 1
                    'mark as matched
                    Sheet1.Cells(j, 4) = Sheet1.Cells(i, 1)
                    credit = credit + debit
                 End If
             End If
        Next
        Sheet2.Cells(iRow, 3) = "Remaining"
        Sheet2.Cells(iRow, 4) = credit

        ' next largest credit
        i = i + 1
        credit = Sheet1.Cells(i, "B")
    Loop

    MsgBox "Done"

End Sub


text:
Q: React server-side and client side rendering not seamless First the page was rendered by the server, then on client/ browser side, the Javascript script re-render the whole page!
I don't think this is how it's supposed to be since it's very bad user experience.
One thing I noticed is that the data-reactid attribute of my root element as rendered by server is some hash like .2t5ll4229s and all the children has that as prefix e.g. .2t5ll4229s.0 (the first child). Whereas, on the browser side, the data-reactid is .0 for the root element and .0.0 for the first child.
If data-reactid is really the culprit here, is there a way to set it a value of choice like eric123 for both client side and server side.
If data-reactid is not the culprit here, how do I go about making server and client side rendering of React seamless i.e. only certain elements should be re-rendered by the client side, not everything!?
My index-server-local.html template:

...
<body>
    <div id="content" class="container-fluid wrapper no-padding-left no-padding-right">
        {{{reactHtml}}}
    </div>
    <script src="bundle.js"></script>
</body>
...

My server.js:

server.get('*', function (req, res) {
        console.log('request url', req.url);
        log.debug('routes are', JSON.stringify(routes));
        res.header("Access-Control-Allow-Origin", "*");
        match({routes, location: req.url}, (error, redirectLocation, renderProps) => {
    if (renderProps) {
        let htmlStr = React.renderToString(<RoutingContext {...renderProps} />);
        res.render('index-server-local', { reactHtml: htmlStr });
    }
}

My browser.js:

React.render(<Router history={history} routes={routeConfig} />, document.getElementById('content'));

I'm using react-router 1.0.0 and React 0.13.3.

A: We need serialize data(or state) in server side, and send it to client side to deserialize, otherwise, the data in client side is different with the moment server render it. it will reload for sure.
One exception: pure static page, in this case React recommend us use renderToStaticMarkup

Similar to renderToString, except this doesn't create extra DOM attributes such as data-react-id, that React uses internally. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save lots of bytes.

So, how we serialize - deserialize?
Here is a simple version:
in your index-server-local.html template:
   <script src="bundle.js"></script>

to:
   <script dangerouslySetInnerHTML={{{{__html: 'window.__data=' + JSON.stringify({key: 'value'})}}}} />
   <script src="bundle.js"></script>

And in client side, we can use __datadata now. how to map the data to your component it's based on your choice.
I recommend Reudx for this:
   createStore(browserHistory, initialState)

And then
   <Provider store={store}>
     { component }
   </Provider>


text:
Q: Why backspace key deletes the entire row in JRuby and what can be the fix for it? I have developed a couple of tools in JRuby. Both the tools prompt for few questions to the user. While answering these questions if the user wants to correct a wrong entry and hits backspace key that deletes the entire line (including the question) instead of deleting just one character.
Below is the piece of code that prompts the questions:
require highline/import

def prompt
  begin
      input=ask("\t\tEnter user name: ") do |ch|
              ch=true
          end

      input
  rescue => e
       print "Error -"+e
  end

end

I was wondering if anyone of you have seen this kind of problem before and what can be the fix for this? Really appreciate your time and help.
Thanks in advance.

A: Below is the working piece of the code. I removed \t and changed ch=true to ch.readline=true. Thank for all of your help and guidance.
require highline/import

def prompt
    begin
        input=ask("Enter user name: ") do |ch|
              ch.readline=true
            end

        input
     rescue => e
          print "Error -"+e
      end
end

A: If you are using highline gem, then when reading the input instead of
input=ask("Enter the Input: "){|ch| ch.echo = true}

use
input=ask("Enter the Input: ") do |ch|
   ch.readline=true
end

Source: https://www.ruby-forum.com/topic/4406162


text:
Q: max and group by question with LINQ I want to group the below query by GetSetDomainName and select the row which has the maximum GetSetKalanGun.In other words, I am trying to get the row with the maximum KALANGUN among those which have the same DOMAINNAME.
var kayitlar3 = (
    from rows in islemDetayKayitListesi
    select new
    {
        KAYITNO = rows.GetSetKayitNo,
        HESAPADI = rows.GetSetHesapAdi,
        URUNNO = rows.GetSetUrunNo,
        URUNADI = rows.GetSetUrunAdi,
        URUNMIKTAR = rows.GetSetUrunMiktar,

        ISLEMTARIHI = rows.GetSetIslemTarihi,
        HIZMETDURUMU = rows.GetSetHizmetDurumu,
        TOPLAMTUTAR = rows.GetSetToplamTutar,

        HIZMETBASLANGICTARIHI = rows.GetSetHizmetBaslangicTarihi,
        HIZMETBITISTARIHI = rows.GetSetHizmetBitisTarihi,
        KALANGUN = rows.GetSetKalanGun
        DOMAINNAME = rows.GetSetDomainName,
        SIPARISDURUMU = rows.GetSetSiparisDurumu
    }).AsQueryable();

This is what I get
KAYITNO DOMAINNAME KALANGUN
1       asdf.com      30
2       domnam.com    172
3       asdf.com      40
4       xyz.com       350

This is what I want
KAYITNO DOMAINNAME KALANGUN
 2       domnam.com    172
 3       asdf.com      40
 4       xyz.com       350

var islemDetayKayitListesi = new List<IslemDetayKayit>();

islemDetayKayitListesi get filled with a foreach loop, with no problem
And that is what IslemDetayKayit looks like
public class IslemDetayKayit
{
    public int GetSetKayitNo { get; set; }
    public string GetSetHesapAdi { get; set; }
    public string GetSetUrunNo { get; set; }
    public string GetSetUrunAdi { get; set; }
    public double GetSetUrunMiktar { get; set; }
    public string GetSetIslemTarihi { get; set; }
    public string GetSetHizmetDurumu { get; set; }
    public string GetSetToplamTutar { get; set; }
    public string GetSetHizmetBaslangicTarihi { get; set; }
    public string GetSetHizmetBitisTarihi { get; set; }
    public int GetSetKalanGun { get; set; }
    public string GetSetSiparisDurumu { get; set; }
    public string GetSetDomainName { get; set; }
}

EDIT : I figured out that there was some other problem in my code, and corrected it.After that all the answer I had to this question works.Thank you for helping and teaching me new things.

A: This will do the trick:
var q =
    from item in kayitlar3
    group item by item.DOMAINNAME into g
    select g.OrderByDescending(i => i.KALANGUN).First();

You can also try this:
var q =
    from row in islemDetayKayitListesi
    group row by row.GetSetDomainName into g
    let highest = g.OrderByDescending(r => r.GetSetKalanGun).First()
    select new
    {
        KAYITNO = highest.GetSetKayitNo,
        DOMAINNAME = g.Key,
        KALANGUN = highest.GetSetKalanGun
    };

Note that this would yield the same results. If it doesn't, there is a problem with your code that we can't see by looking at the information that you posted.

A: You could use:
var kayitlar3 =
    islemDetayKayitListesi.
    Select(rows =>
    new
    {
        KAYITNO = rows.GetSetKayitNo,
        HESAPADI = rows.GetSetHesapAdi,
        URUNNO = rows.GetSetUrunNo,
        URUNADI = rows.GetSetUrunAdi,
        URUNMIKTAR = rows.GetSetUrunMiktar,

        ISLEMTARIHI = rows.GetSetIslemTarihi,
        HIZMETDURUMU = rows.GetSetHizmetDurumu,
        TOPLAMTUTAR = rows.GetSetToplamTutar,

        HIZMETBASLANGICTARIHI = rows.GetSetHizmetBaslangicTarihi,
        HIZMETBITISTARIHI = rows.GetSetHizmetBitisTarihi,
        KALANGUN = rows.GetSetKalanGun,
        DOMAINNAME = rows.GetSetDomainName,
        SIPARISDURUMU = rows.GetSetSiparisDurumu
    }).
    GroupBy(a =>
        //To ignore case and trailing/leading whitespace
        a.DOMAINNAME.ToUpper().Trim()).
    Select(g =>
         g.OrderByDescending(a => a.KALANGUN).FirstOrDefault()).
    AsQueryable();

EDIT:
So using this code:
        List<Thing> islemDetayKayitListesi = new List<Thing>();
        Thing a = new Thing() { GetSetDomainName = "abc.com", GetSetKayitNo = 1,
            GetSetKalanGun = 40 };
        Thing b = new Thing() { GetSetDomainName = "abc.com", GetSetKayitNo = 2,
            GetSetKalanGun = 300 };
        Thing c = new Thing() { GetSetDomainName = "xyz.com", GetSetKayitNo = 3,
            GetSetKalanGun = 400 };
        Thing d = new Thing() { GetSetDomainName = "123.com", GetSetKayitNo = 4,
            GetSetKalanGun = 124 };
        islemDetayKayitListesi.Add(a);
        islemDetayKayitListesi.Add(b);
        islemDetayKayitListesi.Add(c);
        islemDetayKayitListesi.Add(d);
        var kayitlar3 =
            islemDetayKayitListesi.
                Select(rows =>
                new
                {
                    KAYITNO = rows.GetSetKayitNo,
                    HESAPADI = rows.GetSetHesapAdi,
                    URUNNO = rows.GetSetUrunNo,
                    URUNADI = rows.GetSetUrunAdi,
                    URUNMIKTAR = rows.GetSetUrunMiktar,

                    ISLEMTARIHI = rows.GetSetIslemTarihi,
                    HIZMETDURUMU = rows.GetSetHizmetDurumu,
                    TOPLAMTUTAR = rows.GetSetToplamTutar,

                    HIZMETBASLANGICTARIHI = rows.GetSetHizmetBaslangicTarihi,
                    HIZMETBITISTARIHI = rows.GetSetHizmetBitisTarihi,
                    KALANGUN = rows.GetSetKalanGun,
                    DOMAINNAME = rows.GetSetDomainName,
                    SIPARISDURUMU = rows.GetSetSiparisDurumu
                }).
                GroupBy(anon =>
                    anon.DOMAINNAME).
                Select(g =>
                    g.OrderByDescending(anon => anon.KALANGUN).First()).
                AsQueryable();
        kayitlar3.ToList().
            ForEach(anon => Console.WriteLine("{0}, {1}, {2}",
                anon.KAYITNO, anon.DOMAINNAME, anon.KALANGUN));

    struct Thing
    {
        public int GetSetKayitNo { get; set; }
        public int GetSetHesapAdi { get; set; }
        public int GetSetUrunNo { get; set; }
        public int GetSetUrunAdi { get; set; }
        public int GetSetUrunMiktar { get; set; }

        public int GetSetIslemTarihi { get; set; }
        public int GetSetHizmetDurumu { get; set; }
        public int GetSetToplamTutar { get; set; }

        public int GetSetHizmetBaslangicTarihi { get; set; }
        public int GetSetHizmetBitisTarihi { get; set; }
        public int GetSetKalanGun { get; set; }
        public string GetSetDomainName { get; set; }
        public int GetSetSiparisDurumu { get; set; }
    }

I get the expected output:
2, abc.com, 300
3, xyz.com, 400
4, 123.com, 124

A: After clarification about your desired output, this will return the row with the top KALANGUN per DOMAINNAME:
var kayitlar3 = (
from rows in islemDetayKayitListesi
select new
{
    KAYITNO = rows.GetSetKayitNo,
    HESAPADI = rows.GetSetHesapAdi,
    URUNNO = rows.GetSetUrunNo,
    URUNADI = rows.GetSetUrunAdi,
    URUNMIKTAR = rows.GetSetUrunMiktar,

    ISLEMTARIHI = rows.GetSetIslemTarihi,
    HIZMETDURUMU = rows.GetSetHizmetDurumu,
    TOPLAMTUTAR = rows.GetSetToplamTutar,

    HIZMETBASLANGICTARIHI = rows.GetSetHizmetBaslangicTarihi,
    HIZMETBITISTARIHI = rows.GetSetHizmetBitisTarihi,
    KALANGUN = rows.GetSetKalanGun
    DOMAINNAME = rows.GetSetDomainName,
    SIPARISDURUMU = rows.GetSetSiparisDurumu
})
.GroupBy(rr => rr.DOMAINNAME)
.SelectMany(gg => gg.OrderByDescending(rr => rr.KALANGUN).First());

A: Try
  from rows in islemDetayKayitListesi
  group rows by new { rows.GetSetDomainName} into results
  let MaxKALANGUN = results.Max(i=>i.KALANGUN)
  select new
  {
        KAYITNO = results.First(i=>i.KALANGUN== MaxKALANGUN).GetSetKayitNo
        DOMAINNAME = results.Key.GetSetDomainName ,
        KALANGUN = MaxKALANGUN
  }

If you want the complete class, try
  from rows in islemDetayKayitListesi
  group rows by new { rows.GetSetDomainName} into results
  let MaxKALANGUN = results.Max(i=>i.KALANGUN)
  select results.First(i=>i.KALANGUN== MaxKALANGUN)


text:
Q: Auth::user session is not persistent I am working on a dummy project to know more about middlewares. I want to create custom registration for this project.
I changed 1

*

*User Model

*users Table

*Login Controller

For now I don't need a registration page. I just filled a dummy data in users table. I want to see how this auth middle ware works for a group of routes.
So, After that I tried logging in using the same credentials. I was able to log in however, If I want to navigate other pages its throwing a login in page. Somehow, Auth is getting destroyed.
What am I missing here?
Here is my route file
Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::group(['middleware' => ['web','auth']], function () {
    Route::view('/home', 'home')->name('home');
    Route::view('something','SuperAdmin.something')->name('something');
});

This is my Login Controller
<?php

    namespace App\Http\Controllers\Auth;

    use Auth;
    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;
    use Illuminate\Foundation\Auth\AuthenticatesUsers;

    class LoginController extends Controller
    {
        use AuthenticatesUsers;

        protected $redirectTo = '/home';

        public function login(Request $request){
            $email = trim($request->email);
            $password = $request->password;

            if(Auth::attempt(['email' => $email, 'password' => $password])){
                return view('SuperAdmin.dashboard');
            }
            return redirect()->route('login');
        }

        public function __construct()
        {
            $this->middleware('guest')->except('logout');
        }
    }

I am redirecting to {{something}} view from home.blade.php. The Auth works for just one page.
How can I get it working as default?


text:
Q: How do I hide/close a div using jquery when $(document) is clicked? I have a simple dropdown menu and I'd like to have this menu close/hide automatically if any area outside of it is clicked. Can't think of a simple way to do this. Would love a solution/example on jfiddle if possible.
JQuery:
$('.micropostOptions').on('click',function(){
    var postMenu = $(this).find('.postMenu');

    if(postMenu.is(':hidden') ){
        $('.postMenu').hide();
        $('.micropostOptions').removeClass("postMenuHoverState");
        postMenu.show();
        $(this).hide().addClass('postMenuHoverState').show(60);

    }else{
        postMenu.hide() ;
        $(this).removeClass("postMenuHoverState");
    }

});

sCSS:
.micropostOptions {
    position:absolute;
    height:17px;
    width:17px  ;
    top:5px;
    right:5px;
    background:white url("/assets/arrow_down_alt1.png") no-repeat;
    background-position:0px 0px;

        &:hover {
            background: url("/assets/arrow_down_alt1_hover.png") no-repeat;
            background-position:0px 0px;
            cursor:pointer !important;

        }

}

.postMenuActivate {
    display:block;
}

.postMenuHoverState {
    background: url("/assets/arrow_down_alt1_hover.png") no-repeat;
    background-position:0px 0px;
    cursor:pointer !important;
}

.postMenu {
    position:absolute;
    display:none;
    padding-bottom:20px;
    background-color:white !important;
    border:1px solid $main-background-color;
    height:163px;
    width:170px;
    top:18px;
    right:2px;
    -webkit-box-shadow: 0 10px 6px -6px #777;
    -moz-box-shadow: 0 10px 6px -6px #777;
    box-shadow: 0 10px 6px -6px #777;
    color:gray;
    z-index:3000;

        li {

        font-size:12px;
        height:33px;
        background-color:white !important;

            a span {
                float:left;
                width:160px;
                height:33px;
                line-height:33px;
                padding-left:10px;
                color:gray;

                  &:hover {
                    background-color:#4D90FE !important;
                    color:white;
                    //  #DD4B39,#D14836
                    }
            }

            &:hover {
            background-color:#4D90FE;
            color:white;

            }
        }

        .deletePost {
            //position:relative;
            padding-top:0px !important;
            padding-left:0px !important;
            height:39px;
            width:170px;
            text-align:center;
            padding-bottom:7px;
            border-bottom:1px solid #d9d9d9;

                a {

                    span {
                    float:left;
                    padding-left:0px !important;
                        height:46px !important;
                        width:170px !important;
                        line-height:46px;
                    }
                }

                a span:hover {
                    background-color:#DD4B39 !important;
                    color:white;
                //  #DD4B39,#D14836
                }
        }

        .reportAbuse {
            border-top:1px solid #d9d9d9;

                a span:hover {
                    background-color:gray !important;;
                }

        }

}

HTML:

<%= link_to content_tag(:span, "Delete post"), m, :method => :delete, :confirm => "Are you sure?", :title => m.content, :class => "message_delete" %>

<%= link_to content_tag(:span, "Pause commenting"), "2" %>

<%= link_to content_tag(:span, "Block commenter"), "3" %>

<%= link_to content_tag(:span, "Open in new window"), "4" %>

<%= link_to content_tag(:span, "Report abuse"), "5" %>

Kind regards

A: try this:
// Fast way to attach handlers to body
$(document.body).click(function(ev) {
    // Get the clicked element through ev.target
    var clickedElement = $(ev.target);
    // If the element is a visible .postMenu, then ignore.
    if(clickedElement.is('.microPostOptions:visible')) {
        return;
    }
    // If not then slide it up. Note else not needed as we returned early.
    $('.microPostOptions').slideUp();
});

A: Basically, you need to do something like this:
http://jsfiddle.net/49N8s/1/
$(document).on('click', function(e){
    var menu = $('.postMenu');
    var target = $(e.target);
    if(menu.has(target).length > 0 || menu.is(target)){
        return false;
    }
    menu.hide();
});

A: Something like this:
$('html').click(function() {
$('.postMenu').hide();
});


text:
Q: Python Django edit data in database by forms (django v.1.9.4) My goal is add data to database via form and make them editable via edit form.
My error:

Exception Type: NoReverseMatch at /testtable/car/new/
      Exception Value: Reverse for 'car_list' with arguments '()' and keyword  arguments '{'pk': 2}' not found. 0 pattern(s) tried: []

and next problem is how to make a link to edit data
in template/car_list.html to car_edit.html.
Edit Delete
Edit Delete

When I type manually in Explorer http://localhost:8000/testtable/car/1/ it works, I see details of first article in database, but forms with pk arguments doesnt work.
MyApp/testtable/models.py
from django.db import models
import datetime
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class TableParemeters(models.Model):
     author = models.ForeignKey('auth.User')
     car_brand = models.CharField(max_length=20)
     car_type = models.CharField(max_length=20)
     car_colour = models.CharField(max_length=20)
     car_fuel = models.CharField(max_length=20)
     car_trans = models.CharField(max_length=20)
     car_license_plate = models.CharField(max_length=20)
     created_date = models.DateTimeField(default=timezone.now)

def __str__(self):
    return "%s %s" % (self.car_brand, self.car_type)

MyApp/testtable/views.py
from django.shortcuts import redirect, get_object_or_404, render_to_response, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import loader
from django.views import generic
from django.utils import timezone
from django.template import RequestContext
from django.core.context_processors import csrf
from django.contrib.auth.models import User

from .models import TableParemeters
from .forms import CarForm

def car_list(request):
    cars = TableParemeters.objects.all().order_by('id')
    return render(request, 'testtable/car_list.html', {'cars': cars})

def car_detail(request, pk):
    car = get_object_or_404(TableParemeters, pk=pk)
    return render(request, 'testtable/car_detail.html', {'car': car})

def car_new(request):
    if request.method == "POST":
        form = CarForm(request.POST)
        if form.is_valid():
            car = form.save(commit=False)
            car.save()
            return redirect ('car_list', pk=car.pk)
    else:
         form = CarForm()
    return render(request, 'testtable/car_new.html', {'form': form})

def car_edit(request, pk):
    car = get_object_or_404(TableParemeters, pk=pk)
    if request.method == "POST":
        form = CarForm(request.POST, instance=car)
        if form.is_valid():
            car = formsave(commit=False)
            car.save()
            return redirect('car_detail', pk=car.pk)
    else:
         form = CarForm(instance=car)
    return render(request, 'testtable/car_edit.html', {'form': form})

MyApp/testtable/forms.py
from django import forms
from .models import TableParemeters

class CarForm(forms.ModelForm):

    class Meta:

        model = TableParemeters
        fields = '__all__'

MyApp/testtable/urls.py
from django.conf.urls import include, url
from . import views

app_name = 'testtable'

urlpatterns = [
     #login
     #url(r'^$', views.login_page, name='login'),
     #logout
     #carlist url
    url(r'^$', views.car_list, name='car_list'),
     #detail car url
    url(r'^car/(?P<pk>\d+)/$', views.car_detail, name='car_detail'),
     #add new car to list url
    url(r'^car/new/$', views.car_new, name='car_new'),
     #edit car in the list
    url(r'^car/(?P<pk>\d+)/edit/$', views.car_edit, name='car_edit'),
    ]

MyApp/testtable/template/testtable/car_list.html
{% extends 'testtable/base.html' %}
{% block content %}

        ID
        Brand
        Type
        Colour
        Fuel
        Transmition
        License Plate
        Created Date
        Author

{% for testtable in cars %}

        {{ testtable.car_id }}
        {{ testtable.car_brand }}
        {{ testtable.car_type }}
        {{ testtable.car_colour }}
        {{ testtable.car_fuel }}
        {{ testtable.car_trans }}
        {{ testtable.car_license_plate }}
        {{ testtable.created_date }}
        {{ testtable.author }}
        Edit Delete

{% endfor %}

{% endblock %}

A: I mean, that car_list not need pk and django can't found any url for car_list with parameter.
Maybe you can try replace line:
return redirect ('car_list', pk=car.pk)
with:
return redirect ('car_list')


text:
Q: Building an OpenCV application with Visual Studio 2008 and running it from another computer I've made a simple OpenCV application with Visual Studio 2008 and I've built it in both release mode and debug mode.It works fine from my computer but when I try to run it from another computer which doesn't have OpenCV installed or has another version of Visual Studio with OpenCV it doesn't work.
How can I make the app work from a computer which doesn't have either Visual Studio or OpenCV installed ?
I'm thinking to add the external dependencies ( lib's and dll's ) into the app's folder, change the path in Visual Studio and rebuild it.
Thanks in advance and sorry for the ultranoobish question :)

A: You don't need to distribute the libs; those are just needed for building the executable.
Just copy the dlls somewhere where the executable can see them (either in the same dir as the exe, or in a dir that's on the system path) and you should be golden.

A: Copying DLL's with the application or to the path is a good start, but may not be enough. It took me a long time to find out why OpenCV application didn't work on another machine. Visual Studio runtime and OpenMP are used by OpenCV. Those are not installed by default and error messages, if any, are not all that helpful.
You need to build OpenCV and your application with setting (in Visual Studio):
Configuration Properties -> C/C++ -> Code Generation -> Runtime Library -> Multi-threaded (/MT)
You need to disable OpenMP support too if that's the problem. Build system changed with OpenCV 2.0. If I remember right, older version had different project files for version without OpenMP.


text:
Q: ASP.NET / Oracle issue: TNS Could not resolve the connect identifier specified I've got a local copy of an ASP.NET web application running in Visual Studio 2010. The code is an exact duplicate of the code running on my dev environment.
When I try to connect to my Oracle database through ASP.NET, it throws a "TNS could not resolve the connect identifier specified." The weird thing is this database is in my TNSNAMES.ORA file, and when I use TNSPING or Microsoft Data Link to connect, it works fine.
I tried tinkering with the permissions on my Oracle directory, but that didn't seem to help.

A: Using TNS:
(For ASP.NET Core you need the TNS_ADMIN environment variable pointing to the directory where tnsnames.ora is located)
Data Source = TORCL; User Id = myUsername; Password = myPassword;

Not using TNS:
Data Source = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP) (HOST = MyHost) (PORT = MyPort))) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = MyOracleSID));
User Id = myUsername; Password = myPassword;

A: Make sure you have installed the Oracle Database client (x86 or x64).
Make sure you have the PATH configured to use the Oracle bin folder:

PATH=C:\Oracle\product\11.2.0\client_1\bin

Make sure your tnsnames.ora file is in the directory:

C:\Oracle\product\11.2.0\client_1\network\admin

You can try and use the following connection string:
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.1)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=MYDATABASE)));User ID=myusername;Password=mypassword;

UPDATE:
I don't have this environment variable (cause I use the extended connection string) but someone here and here suggest to add TNS_ADMIN.

A: If all the above validations fail, try the following.
This is what solved my issue.
It is the name of the TNS entry in tnsnames.ora file.
Example:
I had abc.xyz = (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort))(CONNECT_DATA=(SERVICE_NAME=MyOracleSID)));
I still got ORA-12154: TNS:could not resolve the connect identifier specified
Then I changed it to,
abcxyz = ()
and it worked.
Basically I removed special characters like . and _ in the TNS entry name.

A: *

*Installed VirtualBox 5.0.20

*Installed CentOS 7 on VirtualBox

*Installed Oracle 11g R2 (11.0.2)

*Create a database

*Installed Windows 10 on VirtualBox

*Installed VisualStudio Professional 2012 and step by step update SP1 to SP5

*Update Nuget Package Manager

*Run in Nuget Package Manager Console: Install-Package Oracle.ManagedDataAccess

*Create a web project.

*Keep a tnsnames.ora file in the project bin folder

TNSNAMES.ORA
MYDB= (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.56.2)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=SID_NAME)));
use the source code in step 12 except the connection string as below:
string constr = "user id=test;password=test;data source=MYDB";

or follow steps 12.

*Used the following namespace in code
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;

*To connect Oracle Database used the following statement:
string constr = "user id=test;password=test;data source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.56.2)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=SID_NAME)))";
OracleConnection con = new OracleConnection(constr);
try
{
con.Open();
ViewData["Message"] = "Connected";
con.Dispose();
}
catch (Exception ex)
{
ViewData["Message"] = ex.Message;
}

*That's it. It's worked.

A: I got the same error: ORA-12154: TNS:could not resolve the connect identifier specified
When I try to connect Oracle Data source from Visual Studio.
Steps to resolve this issue.
Make sure you have Oracle client installed on your system, also Oracle Wallet Manager installed.

*

*Open Oracle Wallet Manager and Add certificates provided by your organization.

*Navigate to 'C:\APP\ORACLE\product\11.2.0\client_1\network\admin' (or similar folder structure in your desktop) folder and replace the 'tnsnames.ora' and 'sqlnet.ora' files with attached.

*In the C:\ORACLE\product\11.2.0.3\network\admin --> Add SQL.net.ora and tnsnames.ora files

*In SQL.net.ora file, modify the wallet path as created in the step-1
Restart your system and start creating Shared Data Source.

A: Another possible scenario where this error occurs is if you are using IISExpress locally to test.
When the TNS entry is added/modified, IISExpress must be restarted so that the new value is honored.
In my case, I was debugging an application and had stopped it to modify the TNS entry, however I then ran the application again but the same IISExpress instance was used to run the API.
Once I stopped the app and manually closed IISExpress, I was able to make my modifications on TNSNAMES work properly on the next execution.


text:
Q: unable to use System.Security.Cryptography.RijndaelManaged in windows phone 8 project C# I trying to encrypt data in a project but I'm unable to use the System.Security.Cryptography.RijndaelManaged in my project.
I tried to create a new application with the specified class and it worked independently. But unluckily unable to add the application to my project.
Next thing I'm gonna try is the portable class, but still have no idea how will that work.
So if you guys know how could I use the System.Security.Cryptography.RijndaelManaged in a windows phone 8 project,
Regards,
Also I'm using the AES CBC PKCS7 encryption for additional info, hope for your response.


text:
Q: What does this symbol mean in IntelliJ? (check mark between file icon and file name) In the project navigator in IntelliJ IDEA I have an icon similar to a check mark between the file icon and file name. I can't find any explanation in the  Icon Reference.
Does anybody know what it means?

A: It is a bookmark. Use menu item Navigate > Bookmarks > Show Bookmarks to show all your bookmarks.

A: There are two ways to remove it:

*

*You can click on the folder and press F11.

*You can click on the folder and then use the menu item: Navigate > Bookmarks > Toggle Bookmark


text:
Q: File Upload With Progress I know this has been discussed a number of times, but the problem I'm having at the moment is finding a solution that is easy to work with and does not require much hacking around.
I want to be able to upload a file, and report on its progress. I've been playing with SWFUpload, and it seems like a bit to much messing around for my liking. Integrating it with code igniter just seems like it's going to cause headaches.
I want a visual progress indicator of some sort to show the user their upload hasn't stagnated. Even if it was just a spinner saying "Uploading. Do not close this window until upload is complete." that would be enough for me.
Security is the most important. Using something like SWFUpload is going to require passing variables to the upload form such as the user ID and other information I'd rather not give snooping noses the opportunity to sniff.
Any possible solutions. Help is much appreciated.

A: You should take a look at HTML5 FormData and XMLHttpRequest 2 which allow you watch the progress directly in javascript.

A: You must customize the tool to meet your requirement , especially when its open source .

Security is the most important. Using something like SWFUpload is
  going to require passing variables to the upload form such as the user
  ID and other information I'd rather not give snooping noses the
  opportunity to sniff.

Why you need to pass user ID ? i think its HTTP matter not SWFUpload,so you can make it secure .
Look here : http://demo.swfupload.org/Documentation/

A: I'm actually on the hunt for the same thing. A few of the options I have encountered so far are:

*

*http://www.uploadify.com

*http://valums.com/ajax-upload/ (Which is now headed off by Ben Colon here - github dot com / bencolon / file-uploader )

I haven't used any of those solutions because I'm not quite sure how to customize them for my application. But it looks like so far in my research, those are links that keep popping up.