text:
Q: Why synchronized block is giving wrong answer? I am trying to learn synchronization. Got stuck here according to what I have learned the following code should give 8000 as the final result but I am getting a random result like below
 package threads;
import java.time.LocalDateTime;

public class A implements Runnable {
    String name;
    static Integer j=0;
    A(String name){
        this.name=name;
    }
    @Override
    public synchronized void  run() {
        for(int i=1;i<=1000;i++){
            synchronized(this){
            A.j++;
            }
        }
        System.out.println(j);
    }

package threads;

public class MainClass {
public static void main(String args[]){
    Thread t1=new Thread(new A("i am thread A "));
    Thread t2=new Thread(new A("i am thread B "));
    Thread t3=new Thread(new A("i am thread C "));
    Thread t4=new Thread(new A("i am thread D "));
    Thread t5=new Thread(new A("i am thread E "));
    Thread t6=new Thread(new A("i am thread F "));
    Thread t7=new Thread(new A("i am thread G "));
    Thread t8=new Thread(new A("i am thread H "));
    t1.setPriority(Thread.MAX_PRIORITY);
    t8.setPriority(Thread.MIN_PRIORITY);
    t1.start();
    t2.start();
    t3.start();
    t4.start();
    t5.start();
    t6.start();
    t7.start();
    t8.start();
    try {
        t1.join();
        t2.join();
        t3.join();
        t4.join();
        t5.join();
        t6.join();
        t7.join();
        t8.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
}

still getting output like 1293
2214
1403
3214
4214
5214
6224
7037
can anyone explain to me how to achieve synchronization and what is going wrong here?

A: This will solve the issue. You have to synchronize using a shared lock to all the threads since you are incrementing a static field. Otherwise each object will have it's own lock and increment the static field in parallel leading to a race condition. That's why you are not getting correct value which is 8000 in this case.
package bookmarks;

public class A implements Runnable {
    String name;
    static Integer j = 0;
    private static Object lock = new Object();

    A(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 1000; i++) {
            synchronized (lock) {
                A.j++;
            }
        }
        System.out.println(j);

    }

}

A: It is a common mistake to think that synchronized means "critical section", and that no other threads will run while a synchronized block is running.  But synchronized blocks are only exclusive with respect to other synchronized blocks that lock on the same lock.
The answers you got ("use a common lock") are right, but didn't really tell you why.  The other common mistake is to think about synchronized as protecting code, when really you should be thinking about it protecting data.  Any shared mutable data should be guarded by one and only one lock, and you should know exactly what that lock is.  (The more complex your locking scheme, the less likely you'll know what locks guard what data.)  So you should always be thinking in terms of "data X is guarded by lock L", and then make sure you acquire lock L whenever you access (read or write) that data.

A: There are a couple of issues in the code.

*

*Issue 1: Lock object added in synchronized(..) is not shared among
all thread instances

*Issue 2: System.out.println(j); line should be in the end after t8.join(); otherwise, you will be given 8 times output.
The rectified code
public class A implements Runnable {

    String name;
    static Integer j = 0;

    static Object lockObject = new Object();

    A(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 1000; i++) {
            synchronized (lockObject) {
                A.j++;
            }
        }
    }

    public static void main(String args[]) {
        Thread t1 = new Thread(new A("i am thread A "));
        Thread t2 = new Thread(new A("i am thread B "));
        Thread t3 = new Thread(new A("i am thread C "));
        Thread t4 = new Thread(new A("i am thread D "));
        Thread t5 = new Thread(new A("i am thread E "));
        Thread t6 = new Thread(new A("i am thread F "));
        Thread t7 = new Thread(new A("i am thread G "));
        Thread t8 = new Thread(new A("i am thread H "));
        t1.setPriority(Thread.MAX_PRIORITY);
        t8.setPriority(Thread.MIN_PRIORITY);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
        t7.start();
        t8.start();
        try {
            t1.join();
            t2.join();
            t3.join();
            t4.join();
            t5.join();
            t6.join();
            t7.join();
            t8.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(A.j);

    }
}


text:
Q: Google Chrome / macOS: Password field won't accept non-ASCII characters
Update
Apparently this is an unresolved issue with the OS X version of Google Chrome. It was first reported over seven years ago. If you happen to find yourself needing to enter a password containing non-ASCII characters, then here are your options:

*

*Type in the password somewhere else and transfer it to the password field via the clipboard.

*Use the developer tools to change the input type from password to text.

*Use a different browser

Are there any rules about the characters that can be entered into a password field? I've been experimenting with Chrome on a Mac and it looks like I can only enter "special" characters if they can be produced with a single keypress (not including modifier keys like Alt and Shift).
For example, I can enter a copyright symbol (©) with a single keypress (AltG), but the letter "o" with an umlaut (ö) requires two (AltU followed by O). In the latter case, the umlaut won't appear in the password. In Windows, it seems that these characters are obtained by typing in magic numbers while pressing the Alt key, so there are probably cross-platform differences in this behaviour. There may also be cross-browser differences.
The reason I'm asking is because I want to implement a sign-up form with a password entry field that can be switched from type="password" to type="text". This allows the user to check the contents of the field (assuming it's safe to do so), and allows me to use a random password generator to pre-fill this field with something that the user can then copy into the confirmation field. But by doing so, I'm changing the set of characters that this field accepts. This is obviously undesirable; if I choose Röntgen as a password, for example, I will never be able to log in (unless the log-in form is also switchable).
So what's the best approach here? I don't want to ban special characters altogether, but restricting everyone to printable ASCII looks like the easiest option.
To illustrate the issue, here's a form with two password fields. One field can be switched to an ordinary text input. Click the button to reveal the contents of the two fields.

function reveal() {
  if ($('#p1').attr('type') == 'password') {
    $('#p1').attr('type', 'text');
    $('#r').html('(Hide)');
  }
  else {
    $('#p1').attr('type', 'password');
    $('#r').html('(Reveal)');
  }
}

function show_passwords() {
  $('#out1').html($('#p1').val());
  $('#out2').html($('#p2').val());
}

  <form onsubmit="return false;">

Password:
<input type="password" id="p1" name="p1" size="20">
    (Reveal)

Confirm password:
<input type="password" id="p2" name="p2" size="20">

<button onclick="show_passwords(); return false">Show password field contents</button>

  </form>

Password:

Password confirm:

A: Original author of the report on the chromium bugtrack here. I was told to open the same issue on the webkit's bugtraq (back then Chrome ran on webkit) and a webkit dev told me that Cocoa (OSX UI framework) does not allow non-ASCII characters on password fields (and I've already found that issue, my OSX password is not as challenging as my online services passwords) and that the Webkit tries hard to mimic native behavior. So the problem is not your browser but OSX itself.
To be fair, when Chrome switched to Blink, there was a new message on the bugtrack:

This is still an issue.
  On the original WebKit bug, it was "decided" that allowing dead key input in password controls is not an ideal
  solution, and WebKit should strive to follow Cocoa's behavior.
As it stands now, Blink fails in both manners: dead keys do not behave as they do in text fields, and they do
  not follow NSSecureTextField's behavior either (i.e. behaving a though the key is not a dead key).
WebKit 601.2.7 in Safari 9.0.1 behaves as expected. Should Blink follow platform behavior as well, or would
  supporting dead keys in password fields be preferred?

But time has passed and nothing changed so far...
I just use Firefox which does not follow Cocoa's limitation and allows any characater on a password field.
If you don't want to force your users, just skip non ASCII characters from your generated password.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create table with few rows with migration in laravel I would like to create a table that will save the data for only 10 rows. How can I do it via migration in Laravel 5.3?

A: Laravel 5.3 provides seeding, also combined with model factories. I'm guessing you're using Eloquent models instead of query builder.
Model Factory
Here an example from Laravel (https://laravel.com/docs/5.3/seeding#using-model-factories)
factory(App\User::class, 10)->create();

This code creates 10 fake users via the User Eloquent model. The declaration of a fake user could be done in database/factories/ModelFactory.php.
Seeding
Again, a partial example from Laravel (https://laravel.com/docs/5.3/seeding#writing-seeders). You can call the model factory directly from the existing DatabaseSeeder (no need to create a new seeder).
<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
    */
    public function run()
    {
        factory(App\User::class, 10)->create();
    }
}

Run

*

*php artisan db:seed to seed the data in existing table structure

*php artisan migrate:refresh --seed for completely rebuilding your database and running the seeders

Full documentation and examples, see the provided links above.

A: There is no such restriction. You can create table as usual and just add 10 rows. If you're asking about hwo to add 10 rows to the table, read about seeding.
Also, if you have just 10 simple rows, consider using config file for that. You can do something like this:
'my-data' => [
    1 => ['name' => 'John', 'age' => 30],
    2 => ['name' => 'Alan', 'age' => 40],
    ....
],

And access this data with config('my-config.my-data')

A: If you want a dummy data to be filled into your table without any hassle you can take a use of Faker Package by fzaninotto.
The process would be like
Install faker via running below command in terminal (from project's root directory):
composer require fzaninotto/faker

Then in your routes.php you can push dummy entries like this:
// Just for an example I am using route to demonstrate the general use
Route::get('/customers',function(){
    $faker = Faker\Factory::create();

    $limit = 10; // this value sets number of rows to be created

    // generate data by accessing properties
    for ($i = 0; $i < $limit; $i++) {
        User::create([
            'name' => $faker->name,
            'email' => $faker->email,
            'phoneNumber' => $faker->phoneNumber,
        ]);
    }
});

This would create total 10 rows  in your table with some dummy data.. Hope this helps


text:
Q: Varnish 7.2 CLI telnet logs I upgraded to varnish 7.2 and now it dumps the logs of varnishd into /var/log/messages on Centos 8 and can not figure out how to change the location of its logs! any clue would be appreciated.
Here is a sample of the log:
varnishd[2327]: CLI telnet ::1 54416 ::1 38535 Wr 200 Backend name ****

A: The work around was to create a varnish config for syslog to place the log file into the desired path so it would not put it into message.


text:
Q: passing two variables on onclick event in combo box          <select name="Country">
          <option value="">Select...</option>
          <option value="A">A</option>
         <option value="B">B</option>
         </select>

           <select name="Gender" onchange=func(this.value, country)>
          <option value="">Select...</option>
          <option value="M">m</option>
          <option value="F">F</option>
          </select>

i have 2 dropdown boxes named gender and country.
First i select the value from Country
Then i select the value from gender
On onclick event i want to pass the values of gender and country. I am not not able to pass
the value of gender.Is there any way by which i can pass the value

A: JavaScript is case sensitive. You gave the element the name Country, not country. It also has a value property. You also need to quote the attribute value whenever it has spaces.
<select name="Gender" onchange="func(this.value, Country.value)">

Note that this has nothing to do with JSP. What you've there is just HTML and JavaScript. JSP is merely a HTML/JavaScript code generator.


text:
Q: MS Access VBA - Download an XML file from stored procedure output I need to have a function that downloads an XML file from a stored procedure and saves it to the disk. Is this possible with MS Access VBA?
Here's my test sample in SQL Server:
CREATE TABLE [dbo].[TestXML](
[ID] [int] NOT NULL,
[PID] [int] NULL,
[Code] [int] NULL,
[Col1] [int] NULL,
[Col2] [int] NULL,
[Col3] [decimal](6, 2) NULL,
[Col4] [decimal](6, 2) NULL,
[Col5] [int] NULL,
CONSTRAINT [PK_TestXML] PRIMARY KEY CLUSTERED ([ID] ASC)
)

GO
INSERT [dbo].[TestXML] ([ID], [PID], [Code], [Col1], [Col2], [Col3], [Col4], [Col5]) VALUES (1, 1000, 10, 1, 2, CAST(0.20 AS Decimal(6, 2)), CAST(0.10 AS Decimal(6, 2)), 1)
INSERT [dbo].[TestXML] ([ID], [PID], [Code], [Col1], [Col2], [Col3], [Col4], [Col5]) VALUES (2, 1000, 20, NULL, 1, CAST(1.00 AS Decimal(6, 2)), CAST(1.00 AS Decimal(6, 2)), 1)
INSERT [dbo].[TestXML] ([ID], [PID], [Code], [Col1], [Col2], [Col3], [Col4], [Col5]) VALUES (3, 1000, 30, NULL, NULL, CAST(2.00 AS Decimal(6, 2)), CAST(2.00 AS Decimal(6, 2)), 5)
GO

Sproc
CREATE PROCEDURE returnXML
(@ID int,
 @xmlOut XML OUTPUT)

AS
BEGIN

SET NOCOUNT ON;

SELECT @xmlOut=(SELECT PID [p/@v],(
    SELECT Code as [code/@c], Col1 AS [code/val]
    FROM [dbo].[TestXML]
    WHERE ID=@ID
    FOR XML PATH(''),TYPE)
  FROM [dbo].[TestXML]
  WHERE ID=@ID
  FOR XML PATH('u'),TYPE)

END
GO

VBA (what I tried to do, but I don't know what to use for XML variables)
Function getXML(sproc As String, id As Integer) As Object
Dim cnn As New ADODB.Connection
    Dim rst As New ADODB.Recordset
    Dim cmd As ADODB.Command
    Dim cnnStr As String
    Dim Rs As New ADODB.Recordset
    Dim StrSproc As String

    Set cnn = New ADODB.Connection
    Set rst = New ADODB.Recordset
    Set cmd = New ADODB.Command
    Set Rs = New ADODB.Recordset

    cnnStr = getConnString()

    With cnn
        .CommandTimeout = 900
        .ConnectionString = cnnStr
        .Open
    End With
    With cmd
        .ActiveConnection = cnn
        .CommandType = adCmdStoredProc
        .CommandText = sproc
        .Parameters.Append .CreateParameter("@ID", adInteger, adParamInput, id)
        .Parameters.Append .CreateParameter("@xmlOut", adLongVarChar, adParamOutput)

    End With
    With Rs
        .CursorType = adOpenStatic
        .CursorLocation = adUseClient
        .LockType = adLockOptimistic
        .Open cmd
    End With
    Set rst = cmd.Execute(, , adCmdStoredProc)
    getXML = cmd.Parameters("@xmlOut").Value

End Function

Any kind of help would be appreciated, thank you!

A: Do you really have to use a T-SQL return parameter?
In general the return parameters of a stored procedure are best if you writing "other" T-SQL routines and want a value returned back.
For general code, why not just execute a select and return the value as a table, select like what is done in most cases?
So in place of
Select @MyXml = (blab la bla)

Just go
select (blab la bla).

Or at the end, simple declare @MyXml as a var, and go
Select @MyXml

If you take the above road, then your stored procedure becomes:
CREATE PROCEDURE returnXML
    (@ID INT)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT (SELECT PID [p/@v],(
    SELECT Code as [code/@c], Col1 AS [code/val]
    FROM [dbo].[TestXML]
    WHERE ID=@ID
    FOR XML PATH(''),TYPE)
FROM [dbo].[TestXML]
WHERE ID=@ID
FOR XML PATH('u'),TYPE)
END
GO

And in Access, if you have a pass-though query declared (you should have one for "general use", then you can go:
Sub Test1()

   Dim i        As Integer
   Dim strXML   As String

   i = InputBox("What id")
       With CurrentDb.QueryDefs("qryPassR")
      .SQL = "returnXML " & i
      strXML = .OpenRecordset()(0)
   End With

   Debug.Print strXML

And using a pt query in Access means you don't mess with connection strings in code.
So unless some "big" reason exists to have that return parameter, then you can use the above. And if you really must use some "existing" t-sql routine that returns a value, then I would suggest using a exec + a select @MyXml.
So even if you are forced to use the return value, you in the above .SQL = go something like:
declare @MyXML varcharmx
Myxml 1,@Mxml;select @myxml


text:
Q: return all pages which redirect to a page in wikipedia Is there any way using the wikipedia api to return a list of all results which redirect to that particular page in Wikipedia?
(similar to the 'what links here' option on the left hand side of the page, but restricted to pages that redirect there).

A: The Redirects API module yields redirects with fragment identifiers (links to sections).  [Example with Wikipedia:Disambiguation]
In earlier versions of the API, only the Backlinks module was available.  It lists every page linked.  However, redirects are being categorized (WP:RCAT) with templates that add links.  This practice has make this module useless for finding redirects on certain pages such as: ASCII, Java package, Surname, Typographical error, etc.

A: The backlinks API module has a filterredir parameter. Using this parameter you can filter backlinks to redirect only. Here's an example of a query for all pages that redirect to Main_Page:


text:
Q: xcode "expected unqualified-id" on cout I'm trying to make a program to calculate the y component of a user-input number for 7 different aspect ratios. This is probably a simple problem somewhere in the declarations at the top, but I have very little experience with c++. I am writing in xcode. Thanks!
I'm getting the following error messages:
19:13: Invalid operands to binary expression ('std::__1::basic_istream' and '')
32:6: Expected unqualified-id
    //
    //  aspect1.cpp
    //  aspectRatioCalculator
    //

    #include <iostream>

    using namespace std;

    int main()
    {

    int a;
    cout << "Enter a number to calculate its complements at multiple aspect ratios." << endl;

    cin>> a >> endl;

    int b = (a*9)/17;
    int c = (a*9)/16;
    int d = (a*5)/8;
    int e = (a*4)/5;
    int f = (a*3)/5;
    int g = (a*3)/4;
    int h = (a*2)/3;

    cout << "17:9 | " << a << ":" << b << endl;
    cout << "16:9 | " << a << ":" << c << endl;
    cout << " 8:5 | " << a << ":" << d << endl;
    cout << " 5:4 | " << a << ":" << e << endl;
    cout << " 5:3 | " << a << ":" << f << endl;
    cout << " 4:3 | " << a << ":" << g << endl;
    cout << " 3:2 | " << a << ":" << h << endl;

    }

A: std::endl is an output manipulator. It isn't meant to be used with input streams (which are used for input). Change this: cin >> a >> endl; to cin >> a; cout << endl;.


text:
Q: PHP - try and catch block (Exception) handling I'm in doubt about exception handling.
If I have a function foo(); is it same as if I handle it like this:
try {
    foo();
} catch (Exception $e) {
    // do someting
}

or if I do it in function like this:
foo() {
    try {
       // function body
    } catch (Exception $e) {
       // do someting
    }
}

And what if I do not throw Exception ? Code will continue to execute even if error appears ?

A: Yes, code will continue. In php exists errors and exceptions. You can handle errors with function set_error_handler(), handle uncathable exceptions with function set_exception_handler() and you can handle exceptions using try .. catch


text:
Q: Why doesn't Websphere like BIRT? I am trying to start a deployment of a project to Websphere and I get the following error trail. (Shortened)
ERROR org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'birtView' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'birtEngine' while setting bean property 'birtEngine'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'birtEngine': FactoryBean threw exception on object creation; nested exception is java.lang.RuntimeException: Could not start the Birt engine!
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'birtEngine': FactoryBean threw exception on object creation; nested exception is java.lang.RuntimeException: Could not start the Birt engine!
Caused by: java.lang.RuntimeException: Could not start the Birt engine!
Caused by: org.eclipse.birt.core.exception.BirtException: error.CannotStartupOSGIPlatform
Caused by: org.eclipse.birt.core.framework.FrameworkException: Cant register the ExtensionRegistry classpath
Caused by: org.eclipse.core.runtime.CoreException: Extension registry provider is already set.

The solution to the 3rd from bottom error as I have found online was to delete the following line of code.
config.setEngineHome("C:/birt-runtime-3_7_0/ReportEngine");

However, this is not present and unnecessary for our setup.
It(the BIRT specific code used) is very similar to this example online:
http://www.springsource.org/BusinessIntelligenceWithSpringAndBIRT
The BirtView and BirtEngineFactory are the only relevant parts to my project.
I have gone to this Bug Page and forum entry and tried the code addition. It did not work. The project starts up and works on Tomcat 6x without any issue.
http://www.eclipse.org/forums/index.php/m/727929/
https://bugs.eclipse.org/bugs/show_bug.cgi?id=351052
I have the class loader order in Web Sphere set to "Classes loaded with application class loader first." as in the example in the link below.
http://wiki.eclipse.org/BirtPOJO_Viewer_WebSphere_Deployment
I still get the same set of errors and I'm not sure what else I should be doing.
I know it is a bit hard to ask this without posting code, but would someone have an idea as to what I should look for?
Thanks.

A: I had exactly the same error as yours. I am using BIRT 3.7.2 and IBM WAS 8.5
With reference to the bug detailed below,
org.eclipse.core.runtime.CoreException when restarting the ReportEngine
and the actual reason of the bug, specified below,
ServiceLauncher.shutdown() doesn't release default RegistryProvider
I added the following line before the Platform.startup(..) call
   RegistryProviderFactory.releaseDefault();
After this, BIRT reports are working fine.
But, I'm doubtful, as to whether this will break anything in WAS's runtime or not.
The reason for this is ...
As explained in the bug, this exception occurs when Platform start-up is attempted for a second time. Here, on Platform.shutdown(), the RegistryProvider is not released, and hence the exception.
Now, in my case, IBM Websphere 8.5 internally uses OSGi and hence starts OSGi Platform.
Hence, when our application attempts to start the Platform again (the second start), the exception occurs.
My concern here is, this should not break anything with WAS's runtime (as it uses OSGi internally).
The Registry Provider is not null, as its set by BIRT runtime, so, the only problem here can be of Class Version mismatch i.e., WAS's Registry Provider and BIRTs Registry Provider, if different, then version clashes.
I'm not sure of the solution i have used.
Experts, please guide.


text:
Q: React useEffect rendering more than once I'm new in Hooks. I coded a project with componentDidMount.
Now I'm learning about hooks and rewriting this project with hooks. I want to fetch the data and print it on the console first.
However, it renders 3 times. It is probably because I used 2 setState in useEffect. However, in one of them I set the data to data array and in the other I keep the loading value for spinner control. How can I use useEffect like componentDidMount just one time to pull data and set my states?
When I write the console into useEffect, "React Hook useEffect has a missing dependency: 'data'." warning and returns an empty list.
Btw I deleted strictmode.
import React, { useState, useEffect } from "react";
import axios from "axios";

function App() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      const { data } = await axios.get("/data/data.json");
      setData(data);
      setLoading(false);
    };
    fetchData();
  }, []);
  console.log(data);
  return
App
;
}

export default App;

A: The component re-renders normally after each state update.
Hence, in your example, it re-renders when the value of data is updated and again, when loading is updated.
Please check this demo to examine how the renderings occur after each state change:

*

*Initial render

*After loading is set to true

*After data is fetched and set

*After loading is set to false

A: I think having the data variable twice might be causing a conflict with the linter. You can rename your data coming from your API call to prevent the warning: "React Hook useEffect has a missing dependency: 'data'."
Your component will re-render on each state update, but the useEffect will only run when your dependencies change. Since they aren't going to change, the API call only happens once.
To prove it, you can move the console.log(result) in your useEffect and see it only logs once. However, make sure you call it on your result and not data, because the state won't be updated until the next render after calling setData.
import React, { useState, useEffect } from "react";
import axios from "axios";

function App() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      const { data: result } = await axios.get("/data/data.json");
      setData(result);
      setLoading(false);
      console.log(result); // runs once
    };
    fetchData();
  }, [setData, setLoading]);

  console.log(data); // runs 3 times
  return
App
;
}

export default App;


text:
Q: Matplotlib/Pyplot equivalent of ggplot coord_flip to swap x and y coordinates? I have a single NumPy array with ozone values which I want to be plotted with the mixing ratio on the x-axis and the pressure level on the y-axis.
In R and ggplot this can be done by a simple coord_flip(), but I can't find a way to do this simply in pyplot. I tried with the orientation option, and try to set the x value to the array but both don't work.
The example below, where I want the Vertical level to be the y-axis and O3 ppmv as the x-axis.

Thanks


text:
Q: Disk/Washer method proof checking This is a homework question, but i am just checking if what i am saying is correct,
The question in the book states that
A sphere of radius $r$ is cut by a plane of $h$ ($h < r$) units above the equator. Find the volume of the solid (spherical segment) above the plane.
Now i know that the upper hemisphere of any circle can be mapped on a 2 dimensional graph as
$$
f(x) = \sqrt{r^2-x^2}
$$
If this plane would be represented as a line on this graph that intersects with this function at 2 points, calling those points $a$ and $b$
$$
h = \sqrt{r^2-x^2}
$$
The positive point of intersection would be
$$
\sqrt{r^2-h^2} = a
$$
If i were to revolve this around the x-axis the volume would be
$$
V = 4\pi \int_{0}^{a} (\sqrt{r^2-x^2}-h^2)^2dx
$$
Due to symmetry, then i would continue with the integration
$$
V = 4\pi\int_0^{\sqrt{r^2-h^2}}(r^2-x^2 - 2h^2 \sqrt{r^2-x^2} - h^4)dx
$$
Therefore
$$
V = 4\pi [r^2\sqrt{r^2 - h^2} - \frac{(r^2-h^2)^{3/2}}{3} - h^4 \sqrt{r^2-h^2} + \int_{0}^{\sqrt{r^2-h^2}} 2h^2 \sqrt{r^2-x^2} dx]
$$
$$
\int_0^\sqrt{r^2-h^2} 2h^2 \sqrt{r^2-x^2} dx = h^3 \sqrt{r^2-h^2} + r^2 \tan^{-1}(\frac{\sqrt{r^2-h^2}}{h})
$$
Therefore the volume of this spherical segment would be
$$
V = 4\pi [r^2\sqrt{r^2 - h^2} - \frac{(r^2-h^2)^{3/2}}{3} - h^4 \sqrt{r^2-h^2} + h^3 \sqrt{r^2-h^2} + h^2 r^2 \tan^{-1}(\frac{\sqrt{r^2-h^2}}{h})]
$$
This was a problem for my calcus 2 class, and it seems like i over did this problem since i have never done a problem of this magnitude in the class thus far. Did i do this correctly? Was there an easier way to go about doing this?
EDIT: I know what i did wrong, i made a mistake with the washer method and did
$$
V = 2 \pi \int_a^b (R-r^2)^2 dx
$$
Instead of
$$
V = 2 \pi \int_{a}^b (R^2-r^2)dx
$$
I answered my own question down below.

A: It might help you to draw a labeled diagram. Figure out where the first disk is,
where the last one is, and what is the radius of a disk somewhere between them.
The integration limits $\int_0^{\sqrt{r^2 - x^2}}$ look vaguely like something
you could use to find the volume by cylindrical shells.
But the integrand for that method would be different from what you used.
The integrand for the disk method is actually much simpler than what you tried.

A: I found my mistake,
$$
V = 2 \pi \int_a^b (R^2 - r^2)dx
$$
Therefore
$$
V = 4 \pi \int_0^\sqrt{r^2-h^2} (r^2-x^2-h^2) dx
$$
$$
V = 4 \pi [r^2 \sqrt{r^2-h^2} - \frac{(r^2-h^2)^{3/2}}{3}
 - h^2 \sqrt{r^2-h^2}]$$
So much easier


text:
Q: How android device authentication finger print scanner can be used to generate fingerprint image/ what are the other options? Is it possible to generate an finger print image using the inbuilt finger print scanner available in modern android phones ?
It works fine for unlocking the device, but what are the other things can be done using it? kindly share some awesome things can be done using it for a developer.
i have a letv le 1s

A: With Android Fingerprint API, it's only allow to verify current user against user of device.
To get fingerprint image or template, you need to use external fingerprint scanners compatible with Android Platform and with SDK for Android. For instance:

*

*http://www.dermalog.com/en/products_solutions/fingerprintscanner/

*http://www.futronic-tech.com/product_fs80h.html

*http://www.crossmatch.com/authentication-hardware/


text:
Q: Problem with given instances writing MTL style code with Scala cats I am trying to write some Scala code to have custom behaviour in an mtl style. For example, in order to expose the "write to DB" functionality abstracting over the specific effect I wrote my own type class:
trait CanPersist[M[_]]:
  def persistToDB[A](a: A): M[Unit]

given CanPersist[IO] with
  def persistToDB[A](a: A): IO[Unit] = IO(???) // Write to DB

The IO instance can be easily implemented but what I'm interested in is automatically providing the instance for any IO-based monad stack:
// If a Transformer wraps a Monad that can persist then it can persist too
given persistTA[M[_]: CanPersist: Monad, T[_[_], _]: MonadTransformer]:
  CanPersist[[A] =>> T[M, A]] with
  def persistToDB[A](a: A): T[M, Unit] =
    summon[MonadTransformer[T]].lift(summon[CanPersist[M]].persistToDB(a))

The problem is apparently cats does not define its own MonadTransformer type class; luckily its pretty straightforward to write your own:
trait MonadTransformer[T[_[_], _]]:
  def lift[M[_]: Monad, A](ma: M[A]): T[M, A]

// A Monad Transformer is a Monad if it wraps a Monad
given monadTA[M[_]: Monad, T[_[_], _]: MonadTransformer]: Monad[[A] =>> T[M, A]] with
  def pure[A](a: A): T[M, A] = ??? // implementations are not relevant
  def flatMap[A, B](fa: T[M, A])(f: A => T[M, B]): T[M, B] = ???
  def tailRecM[A, B](a: A)(f: A => T[M, Either[A, B]]): T[M, B] = ???

// Both WriterT and EitherT are Monad Transformers
given writerMT[L: Monoid]: MonadTransformer[[M[_], A] =>> WriterT[M, L, A]] with
  def lift[M[_]: Monad, A](ma: M[A]): WriterT[M, L, A] =
    WriterT.liftF(ma)

given eitherMT[Err]: MonadTransformer[[M[_], A] =>> EitherT[M, Err, A]] with
  def lift[M[_]: Monad, A](ma: M[A]): EitherT[M, Err, A] =
    EitherT.liftF(ma)

And now onto the code that actually uses the CanPersist functionality:
def saveIntString[M[_]: Monad]
  (int: Int, string: String)
  (using P:CanPersist[M])
  : M[String] =
  for {
    _ <- P.persistToDB(int)
    _ <- P.persistToDB(string)
  } yield "done"

val res: WriterT[IO, String, String] = saveIntString(2, "test")
// Does not compile:
// no implicit argument of type CanPersist[M] was found for parameter P of method saveIntString
// where:    M is a type variable with constraint <: [V] =>> cats.data.WriterT[cats.effect.IO, String, V]
// I found:
//    persistTA[M, T]
// But given instance persistTA does not match type CanPersist[M].

The problem is the compiler apparently can not derive the correct instances; this confuses me though. I thought the compiler would be able to derive the correct instance:

*

*WriterT has a Transformer instance

*IO has a CanPersist instance

*Since WriterT is a Transformer and IO a monad that can persist WriterT[IO, _, _] should also have a CanPersist instance
Is there a way to define the described Transformer typeclass this way? Can the compiler derive such instances or is it impossible in Scala?

A: Problems with inference seem to be one of the reasons why the particular MTL implementation that you linked is relying on traits such as MonadPartialOrder instead of MonadTransformer-typeclasses.
Basically, what happens here is this: When you want to get from F to G

*

*The MonadPartialOrder-approach asks for a bridge from F to G

*Your approach asks to deconstruct G into [X] =>> T[M, X], then find a fancy universal bridge-builder T, and then use that contraption to build a bridge from F to ([X] =>> T[M, X]).

Thus, cats.mtl's approach is much simpler, and far less demanding of the inference algorithm. That's why cats.mtl works, whereas your approach doesn't.

I'll first sketch how your example can be fixed, then I'll speculate a little about why your approach does not work.
A solution with MonadPartialOrder
Here is how I'd try to approach your problem using the MonadPartialOrder from cats.mtl:
import cats.data.WriterT
import cats.syntax.all._
import cats.mtl.MonadPartialOrder

trait CanPersist[M[_]]:
  def persistToDB[A](a: A): M[Unit]

given CanPersist[IO] with
  def persistToDB[A](a: A): IO[Unit] = IO(???) // Write to DB

given persistTA[F[_]: CanPersist: Monad, G[_]]
  (using mpo: MonadPartialOrder[F, G]): CanPersist[G] with
    def persistToDB[A](a: A): G[Unit] =
      mpo(summon[CanPersist[F]].persistToDB(a))

def saveIntString[M[_]: Monad]
  (int: Int, string: String)
  (using P:CanPersist[M])
  : M[String] =
  for {
    _ <- P.persistToDB(int)
    _ <- P.persistToDB(string)
  } yield "done"

def res: WriterT[IO, String, String] = saveIntString(2, "test")

@main def main(): Unit =
  println("Run it with 'sbt clean compile run'")

The basic idea is to use MonadPartialOrder[F, G] to get from F to G, instead of requiring a MonadTransformer[T] to get from F to [X] =>> T[F, X].
This compiles and runs just fine on Scala 3.1.2, here is a complete build.sbt, if you want to try it out:
import Dependencies._

ThisBuild / scalaVersion     := "3.1.2"
ThisBuild / version          := "0.1.0-SNAPSHOT"
ThisBuild / organization     := "com.foobarbaz"
ThisBuild / organizationName := "example"

lazy val root = (project in file("."))
  .settings(
    name := "cats-mtl-so-question-72407103",
    scalacOptions += "-explaintypes",
    libraryDependencies += scalaTest % Test,
    libraryDependencies += "org.typelevel" %% "cats-core" % "2.7.0",
    libraryDependencies += "org.typelevel" %% "cats-mtl" % "1.2.1",
    libraryDependencies += "org.typelevel" %% "cats-effect" % "3.4-389-3862cf0",
  )

Why your approach does not work
The logic in your explanation seems fine to me, so I would say that the compiler currently cannot infer the required typeclasses. The reason why your solution does not work (whereas cats.mtl does), is that your solution is attempting to work at a higher level of abstraction than cats.mtl does.
The problem that an average MTL implementation is usually trying to solve looks somewhat like this:

For a fixed property P and two fixed monads LameMonad and FancyMonad, find a way to lift P from the LameMonad to the FancyMonad.

This is done for a few useful properties P (such as that you can Ask, Tell, access and mutate Stateful stuff and so on), and a reasonable amount of different combinations of LameMonad and FancyMonad, with the fancy monads usually arising from the lame monads by applying some monad transformer (such as those from cats.data._). Note how the the quantifiers "for a few", "for a reasonable amount" appear in the metadiscussion outside of the problem statement that we're trying to solve automatically.
Now, contrast this to your code, where you greet the compiler with the following signature:
given monadTA[M[_]: Monad, T[_[_], _]: MonadTransformer] // ... etc

The contextual bound : MonadTransformer demands that the compiler solves a problem that looks roughly like

For a fixed T, find a unique constructive proof that
for all monads M, [X] => T[M, X] is also a monad.

Note how the for all quantifier has now slipped into the problem statement of the task we are trying to automate, and also note that now the compiler is somehow supposed to infer the "right" way to match a higher kind Foo against [A] =>> T[M, A] with a higher-kinded M.
The task of matching against [A] =>> T[M, A] is tricky (thanks to subclassing / inheritance even trickier than in Haskell), and actually somewhat ill-defined. For example, WriterT[IO, String, V] can be decomposed in multiple ways: is it

[X[_], Y] =>> WriterT[X, String, Y] applied to IO and V

or is it

[X[_], Y] =>> WriterT[IO, Y, X[V]] applied to Id[_] and String

or is it any other combination? Some conventions (taking the rightmost argument first etc.) seem to work in most common cases, but apparently not in your particular case.
So, without being able to tell for sure, I assume that all those universal quantifications over higher kinds somehow manage to confuse the compiler badly enough that the approach becomes impractical. I also assume that this is one of the reasons why cats.mtl is using MonadPartialOrder instead of MonadTransformer-typeclasses: the MonadPartialOrder[F, G] tells you just that you can do with G anything you can do with F, for two fixed monads F and G. The kinds of both parameters are * -> *, which is much more benign than all those higher-kinded [X[_], Y] =>> Z[X, Y]-lambdas.
So, to reiterate, MTL is doing this:
For a few selected `P`, `F`, `G`, solve problem: "lift P from F to G"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^
meta-level, interpreted by humans                 easy for compiler

whereas you are attempting something closer to this (waves hands handwavily):
For a fixed `P`, solve: "for all `F`, `G`, lift `P` from `F` to `G`"
^^^^^^^^^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
meta-level, easy                 too hard for the compiler

which is sufficient, but not necessary (and therefore unnecessarily hard for the compiler).


text:
Q: SELECT dentro do UPDATE Tenho o seguinte Banco de Dados:

    cd_telefone|cd_cliente  |nr_ddd |nr_telefone
    1          | 30         | 11    |2562-2791
    2          | 30         | 11    |2562-2791
    3          | 31         | 13    |8888-8888
    4          | 30         | 11    |5555-5555
    5          | 30         | 13    |9623-54002
    6          | 30         | 11    |1111-2525

Minha intenção e passar o valor do ddd e telefone, e retornar o cd_telefone, e a partir do cd_telefone, atualizar o numero existente.
Meu Código esta assim, não da erro, porem não funciona:

UPDATE tb_telefones SET nr_ddd='" + dddNovo + "', nr_telefone='" + telNovo+ "'
WHERE cd_telefone = (
    SELECT cd_telefone FROM tb_telefones
    WHERE nr_ddd='" + dddAntigo + "' AND nr_telefone='" + telAntigo + "'
)

A: Como explicação do comentário na minha resposta acima:
o select que você esta utilizando é :
    UPDATE tb_telefones SET nr_ddd='" + dddNovo + "', nr_telefone='" + telNovo+ "'
    WHERE cd_telefone = (SELECT cd_telefone
                         FROM tb_telefones
                         WHERE nr_ddd='" + dddAntigo + "'
                           AND nr_telefone='" + telAntigo + "'
    )

tente utilizar desta forma :
    UPDATE tb_telefones SET nr_ddd='" + dddNovo + "', nr_telefone='" + telNovo+ "'
    WHERE cd_telefone =(SELECT top 1 cd_telefone
                        FROM tb_telefones
                        WHERE nr_ddd='" + dddAntigo + "'
                          AND nr_telefone='" + telAntigo + "'
    )

assim no select você pega apenas o primeiro valor retornado pelo select

A: Para que funcione você teria que se certificar que o resultado do seu select seja apenas de um valor, você pode fazer isso ultilizando por exemplo :
SELECT top1 cd_telefone FROM tb_telefones WHERE nr_ddd='" + dddAntigo + "' AND nr_telefone='" + telAntigo + "')

A: Normalmente utilizo um loop nesta situação:
for dd in( (SELECT cd_telefone
          FROM tb_telefones
         WHERE nr_ddd = '" + dddAntigo + "'
           AND nr_telefone = '" + telAntigo + "')loop
UPDATE tb_telefones
   SET nr_ddd = '" + dddNovo + "', nr_telefone = '" + telNovo+ "'
 WHERE cd_telefone = dd.cd_telefone;
end loop;

A: Me desculpe eu não havia lido com a devida atenção a sua pergunta.
Acredito que no seu caso apenas trocar o = por in
UPDATE tb_telefones SET nr_ddd='" + dddNovo + "', nr_telefone='" + telNovo+ "'
WHERE cd_telefone in (
    SELECT cd_telefone FROM tb_telefones
    WHERE nr_ddd='" + dddAntigo + "' AND nr_telefone='" + telAntigo + "'
)
Onde você vai incluir esse codigo.


text:
Q: Popup screen not working on Android, but does on iOS I'm trying to create an popup that contains help information. The below code works perfect on iOS, but on Android the labels aren't displayed (the close button is).
I'm hoping there is an easy fix ;-)
Thanks in advance!
function helpPopup() {

var myModal = Ti.UI.createWindow({
    backgroundColor : 'transparent',
    navBarHidden:true
});

var wrapperView    = Ti.UI.createView(); // Full screen
var backgroundView = Ti.UI.createView({  // Also full screen
    backgroundColor : '#000',
    opacity         : 0.5
});
backgroundView.addEventListener('click', function () {
    myModal.close();
});
var containerView  = Ti.UI.createView({  // Set height appropriately
    height          : 300,
    backgroundColor : '#FFF'
});
var someLabel      = Ti.UI.createLabel({
    text    : 'Here is your modal',
    top     : 40
});

var contactName = Ti.UI.createLabel({
    text    :'Name',
    top     :60
});

var closeButton    = Ti.UI.createButton({
    title  : 'Close',
    bottom : 40
});
closeButton.addEventListener('click', function () {
    myModal.close();
});

containerView.add(someLabel);
containerView.add(contactName);
containerView.add(closeButton);

wrapperView.add(backgroundView);
wrapperView.add(containerView);

myModal.add(wrapperView);

myModal.open({
    animate : true
});

}

A: It turns out that Android uses white as a default label color.... iOS uses black.
So after I changed the font color it worked on both Android on iOS:
var someLabel = Ti.UI.createLabel({
text : 'Here is your modal',
top : 40,
color : '#000'
});


text:
Q: Email input field width changes only with inline style I have an email input field which was set to 80% width in an inline style.  I moved the width parameter to a class with width: 80% but now the width shows 100%.
The html:

<input type="text" class="joinpage_input" autofocus="autofocus" placeholder="Your email address" id="email_field" name="email_field" font-size: 18px;" required>

The css:
.center_text_grid {
    display: grid;
    grid-column: 4 / 15;
    grid-row: 20 / 20;
    display: block;
    overflow: auto;
    padding-left: 0%;
    align-items: center;
    justify-items: center; }

.mktg_text{
    font-family: roboto_thinregular;
    font-size: 13pt;
    color: rgb(117,163,126);
    line-height: 1.5; }

.joinpage_input{
    border-radius: 15px;
    border-style: ridge;
    border-color: rgb(250,250,250);
    border-width: 1px;
    background-color: black;
    height: 45px;
    width: 80%;
    text-align: center;
    font-family: robotoregular;
    font-size: 18pt;
    font-weight: bold;
    color: rgb(150,150,150);
    letter-spacing: 2px; }

::placeholder {
    color: rgb(150,150,150);
    font-family: camphorW01-Thin,calibri,arial;
    font-size: 12pt;
    opacity: 1;
}

Why doesn't the width: 80%; govern when it's the class on the button and the other two classes have no width parameters?  Why does it work as an inline style and not as a class style?

A: Code could look something like this:

.joinpage_input {
  width: 80%;
  height: 45px;
  border: 1px ridge rgb(250, 250, 250);
  border-radius: 15px;
  background-color: black;
  text-align: center;
  font-size: 18pt;
  font-weight: bold;
  color: rgb(150, 150, 150);
  letter-spacing: 2px;
}

::placeholder {
  color: rgb(150, 150, 150);
  font-size: 12pt;
}

  <input id="email_field" name="email_field" class="joinpage_input" type="email" placeholder="Your email address" autofocus required>


text:
Q: How to create a role that cannot create or alter a table? I want to create a role named manager in postgresql . This role can update, select, delete and insert data in all tables but users that belong to this role cannot create a table nor modify the schema.
I tried the following sql statement:
CREATE ROLE manager
  NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE NOREPLICATION;
How can I achieve this condition?.

A: The privilege to create tables is granted to new roles automatically. You need to REVOKE the role's CREATE privilege on the schema (not the database):
REVOKE CREATE ON SCHEMA myschema FROM manager;

Per documentation on GRANT:

CREATE
For databases, allows new schemas to be created within the database.
For schemas, allows new objects to be created within the schema. To rename an existing object, you must own the object and have this
  privilege for the containing schema.
For tablespaces, allows tables, indexes, and temporary files to be created within the tablespace, and allows databases to be created that
  have the tablespace as their default tablespace. (Note that revoking
  this privilege will not alter the placement of existing objects.)

And REVOKE all direct privileges any role might have in respective schemas. By default, plain roles only have privileges for the schema public and schemas they create themselves.


text:
Q: Not able to set Image Source in Silverlight 4 Not able to set image source Uri on find Object.
Stackpanel contain two children Textbox and image control.
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
  var textBox = (TextBox)sender;
  textBox.Style = Application.Current.Resources["TextBoxNormal"] as Style;
  textBox.FontSize = 15;
  textBox.Foreground = new SolidColorBrush(Colors.Gray);

  var stackpanel = textBox.Parent as StackPanel;
  if (stackpanel == null)return;
  var img = stackpanel.Children.Where(a => a is Image).FirstOrDefault();

  if (textBox.Text != "")
  {
     //I was trying set Uri as mention below, but there is Nothing like "Image.Source"
     //image.Source = new BitmapImage(new Uri("/Images/Others/TickRight.png", UriKind.RelativeOrAbsolute));

  }

A: So I Would suggest Trouble shooting here.
if (textBox.Text != "")
  {
      BitmapImage picture =  new BitmapImage(new Uri("/Images/Others/TickRight.png", UriKind.RelativeOrAbsolute));
      picture.ImageFailed += (o, e) => System.Threading.SynchronizationContext.Current.Send((oo) => System.Windows.Browser.HtmlPage.Window.Alert("Image failed: " + e.ErrorException), null);
      picture.ImageOpened += (o, e) => System.Threading.SynchronizationContext.Current.Send((oo) => System.Windows.Browser.HtmlPage.Window.Alert("Image opened: " + e.OriginalSource), null);

      image.Source = picture;
  }

//BANG.. your error should be naked!

A: You need cast img as Image
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
  var stackpanel = textBox.Parent as StackPanel;
  if (stackpanel == null)return;
  var img = stackpanel.Children.Where(a => a is Image).FirstOrDefault() as Image;
 }


text:
Q: Ajax response is undefined I'm a newbie coder. I'm trying to insert the var cPrice in my front-end HTML page. However, it is undefined and I can't figure out why.
///////////// Display Pop-up finciton //////////////////
//Start//

$('#button1').on('click', function() {
// Show the popup
$('#openPopup').show();
// Get the symbol and name and show it in the popup
const symbolID = document.getElementById("symbolSearch").value.toUpperCase();
document.getElementById("currentSymbol").innerHTML = symbolID;

$.get("http://localhost:5000/placeOrder", function(err, price) {
    console.log(price.currentPrice);

    var cPrice = price.currentPrice // On the server-side it prints the correct value.

    console.log(cPrice) // However, here the front-end value is undefined.
    if (err) { console.log(err) } else {
        document.getElementById("currPrice").innerHTML = cPrice
    }

});

// Execute the function for retrieving the price
//userAction();

A: Read the docs: jQuery.get() for the success function callback:
the first argument is the PlainObject data

jQuery.get( url [, data ] [, success ] [, dataType ] )
fn success
Type: Function( data, textStatus, jqXHR )
A callback function that is executed if the request succeeds. Required if dataType is provided, but you can use null or jQuery.noop as a placeholder.

There's also a

Deprecation notice:
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

therefore you'd better go with a more readable code using .done() and .fail():
$.get("http://localhost:5000/placeOrder")
  .done((data) => {
    console.log(data);
    console.log(data.currentPrice);
  })
  .fail((jqXHR, textStatus, errorThrown) => {
    console.log(jqXHR);
  });


text:
Q: Bootstrap Modal > Loop While > Abrir item dentro do Modal Acredito ser questão de colocar o código no local certo, porém estou quebrando a cabeça e não consigo...
Fiz um teste com o código padrão do BootStrap, onde funciona sobre um botão. Inclusive coloquei as chamadas de dados dentro dele e funcionou.
A questão agora é, minha index retorna valores do banco pelo while:
  while ($posts = mysql_fetch_array($busca)){
                extract($posts);
                ?>

                                <a href="single.php?id=<?php echo $posts['id']?>" title="<?php echo $posts['titulo']; ?>" >
                                <?php echo $posts['titulo']; ?>

                        <a href="single.php?id=<?php echo $posts['id']?>" title="<?php echo $posts['titulo']; ?>" class="thumbnail">
                            <img src="uploads/<?php echo $posts['path'] ?>" title="<?php echo $posts['titulo']; ?>" alt=""  id="blc-img" />

Visitas <?php echo $posts['visitas'] ?>

                <?php
                    };
                ?>

Como posso adaptar este código para que ao clicar em um dos itens, ele abra no Modal, e não no single.php? como esta no momento.
Código do modal:`
<button type="button" class="btn btn-primary" data-toggle="modal"    data-target=".bs-example-modal-lg">Large modal</button>

      ...

`

Não irei modificar o código padrão do Modal(acredito não haver necessidade).
Gostaria que ao clicar em um dos itens retornados, ele abra em Modal.
Modal com botão funcionando:

Minha ideia é quando clicar no post(aquele abaixo do Catalogo), ela abra da mesmo forma que o do botão.
Agradeço desde já!

A: Cria uma função em js que você chama ela passando o id do filme, ai essa função chama seu single.php por ajax passando o id e depois carrega o html vindo do single.php dentro do modal e depois abre o modal.
 function carregarItem(id)
    {
        $( ".modal-content" ).load( "single.php", { id: id }, function() {
            ('.bs-example-modal-lg').modal('show');
        });
    }

Chamada HTML:

   <a onclick='carregarItem(<?php echo $posts['id']?>)' title="<?php echo $posts['titulo']; ?>" >
   <?php echo $posts['titulo']; ?>

A: Imagino pelo oq eu entendi que quando clicar nos links você deve fazer uma solicitação ajax para a url no caso para o single.php dai pegar o retorno que deve ser um html de preferencia e jogar dentro da div do modal depois abrir o modal. Agora tem o problema do parametro acho que teria que implementar assim:
Exemplo:
Seu link:

   <a class='linkmodal' id='<?php echo $posts['id']?>' title="<?php echo $posts['titulo']; ?>" >
   <?php echo $posts['titulo']; ?>

//vinculei a solicitação ajax ao click do a e pego o id na propriedade do elemento

$('a.linkmodal').click(function(){
        $.ajax({
            url: 'single.php',
            data: {id: $(this).attr('id')}
        }).done(function(data) {
            $('div.modal-content').html(data);
        });

//aqui chamar abertura da modal codigo depende do plugin

});


text:
Q: java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.NullPointerException My app gives me this error when using this onclicklistener
private OnClickListener btn_Config_Onclick = new OnClickListener() {
    public void onClick(View v) {
        Bundle bundle = new Bundle();
        bundle.putString("Name", selected_Name);
        bundle.putString("Image", selected_Image);

        Intent intent = new Intent(v.getContext(), Configure.class);
        intent.putExtras(bundle);
        v.getContext().startActivity(intent);
    }
};

The class for configure is here: http://pastebin.com/njMa9buE
and the complete error here: http://pastebin.com/REemSken
I have been looking over everything and cant for the life of me find whats wrong, everything is correctly defined in the manifest etc.
Hoping fresh eyes will find the issue

A: You never initialize chk_RunVNC. It is null. You never assign anything to it. So this throws a NullPointerException in onCreate():
chk_RunVNC.setOnCheckedChangeListener(chk_RunVNC_OnCheckedChange);


text:
Q: Displaying two strings in a table using d3.js I've been trying to use d3.js to display a table using two input strings, I've added the code below. When displaying the second string, only the characters with indices that are greater than the length of the string x are displayed.
I think it's something related to the anonymous functions, when iterating through the second string, i begins with the index value it finished off with in the first string e.g., only "fo" is displayed from the second string instead of "fresihnfo". Can anyone give me some pointers on how to fix this?
Thanks!
        var x = ["a", "e", "d", "i", "r", "z"];
        var y = ["f", "r", "s", "i", "h", "n", "f", "o"];

        var w = (x.length + 1) * 50;
        var h = (y.length + 1) * 50;

        var svg = d3.select("body")
                    .append("svg")
                    .attr("width", w)
                    .attr("height", h);

        /*Displays the first string*/
        svg.selectAll("rect")
           .data(x)
           .enter()
           .append("rect")
           .attr("x", function(d, i) {
                return (i * 45) + 45;
           })
           .attr("y", "0px")
           .attr("width", "40px")
           .attr("height", "40px")
           .attr("fill", "rgb(0, 0, 102)");

        svg.selectAll("text")
           .data(x)
           .enter()
           .append("text")
           .text(function(d) {
                return d;
           })
           .attr("text-anchor", "middle")
           .attr("x", function(d, i) {
                return (i * 45) + 65;
           })
           .attr("y", "27px")
           .attr("font-family", "sans-serif")
           .attr("font-size", "20px")
           .attr("fill", "white");

        /*Displays the second string*/
        svg.selectAll("rect")
           .data(y)
           .enter()
           .append("rect")
           .attr("x", "0px")
           .attr("y", function(d, i) {
                return ((i - x.length) * 45) + 45;
           })
           .attr("width", "40px")
           .attr("height", "40px")
           .attr("fill", "rgb(0, 0, 102)");

        svg.selectAll("text")
           .data(y)
           .enter()
           .append("text")
           .text(function(d) {
                return d;
           })
           .attr("text-anchor", "middle")
           .attr("x", "20px")
           .attr("y", function(d, i) {
                return ((i - x.length) * 45) + 70;
           })
           .attr("font-family", "sans-serif")
           .attr("font-size", "20px")
           .attr("fill", "white");

Current output:

Desired output would be to have the rest of the string y displayed in the left column.

A: As Marc said, the problem is that your second selection each time is being interpretted as an update to your first selection, not as a new set of elements.  And since you only work on the enter() part of the update, you don't even see the fact that you've changed the data for your first set of rectangles.
To confirm that the first set of rectangles have been given the data from your second array, right-click on one, choose "Inspect Element" and then open up the properties tab in your inspector -- the __data__ property holds the element's D3 data object.
So how do you fix it?  You need a way of distinguishing between the two groups of rectangles in your select statement.  There are two options:
Option 1: Use sub-selections on SVG group elements (<g>)
You've got two groups of rectangles, so it makes sense to use the svg grouping element to keep them organized.  Instead of adding your rectangles directly to your svg, add a group element to the svg and then add the rectangles/text to it.
svg.append("g").selectAll("rect") //etc.

Do the same for the second set of rectangles, and they'll all be nicely arranged in the second group, so long as your select statement is always called from the group selection, it will only select elements that are part of that group.
Option 2: Use a class attribute to distinguish the two element types
You've got two types of values, x and y, so you should distinguish which type your svg elements belong to by setting a corresponding class attribute.  Then, in your select statement, make sure you only select elements of the correct class.  The CSS selector format for an element of a certain class is elementName.ClassName, so your code would look like:
.selectAll("rect.x")
  .data(x)
enter()
  .append("rect")
  .classed("x", true)
  // etc.

Or, Option 3: Use both
If you're going to want to update the rectangles in the future, just putting them in two groups isn't good enough -- you need a way to distinguish the groups, too.  So add an x or y class when you append the <g> elements and use a "g.x" or "g.y" selector when you create them.
I highly recommend you read up on selections, selectors, nested selections, and the update process if you want to keep your D3 code straight.  There's a list of tutorials on the wiki.
P.S.  The i values that you create as named parameters of your anonymous functions are always limited in scope to that function.  You could give them different names if you wanted, their value will always be the value that D3 passes in to them -- the data object for the first parameter, and the index within the current selection for the second parameter.

A: the main goal of selectAll() is to select exist elements in the container,  when worked with data()
it will join data with elements so we can
use enter() to add new element for new data items;
use update() to update elements which match the data.
use exit() to remove elements without data to match
when you use svg.selectAll("rect").data(x).enter() to append rect selectAll() will return 0 element
data(x).enter() will produce  placeholder for each data so you can append all data in x
but when use svg.selectAll("rect").data(y).enter() to append rect for y. selectAll() will return 6
rects, so data(y).enter() will product placeholder for 'f' and 'o' this is why you only get two
elements
solution: use different selector for x and y, such as different class name
svg.selectAll(".x").data(x).enter().append("rect").attr("class", "x"); // other operation

svg.selectAll(".y").data(x).enter().append("rect").attr("class", "y"); // other operation

you can get deep understand of d3 selection and data join with these articles:
http://bost.ocks.org/mike/join/
http://bost.ocks.org/mike/selection/


text:
Q: Get length between two coordinates? I'm trying to get the length between two coordinates using a Raphael.js path.
If I for example have this path:
M612 295 L690 429 L642 565 L540 432 L711 379 L763 502 L683 585 L480 612 L605 466 L717 318 L888 466 L756 586 L609 392 L835 248 L874 472 L927 622 L724 674 L708 403 L563 391
Then I want to be able to get the length between 711 379 and 927 622, is that possible?

A: Using pythagorean theorem, just like Ivan pointed out, is the way to go.
I created this lib to solve my problem.
Here is an example.
var paper = Raphael(10, 50, 320, 200);
var path = paper.path("M10 10 L90 90 L21 18 L19 31");

path.getLengthBetweenCoordinates({
  y: 10,
  x: 10
}, {
  x: 21,
  y: 18
});

/* => 212.86170582141557 */


text:
Q: Have two or more tuples with the same attribute value With SQL, can I have more than one tuple with the same value for all the attributes in the table? Are there any conflicts or problems here?

A: There is no way for that!
The reason is Primary key values Data Integrity Rule.

Primary key values: A primary key value rule defined on a key (a
  column or set of columns) specifies that each row in the table can be
  uniquely identified by the values in the key.

https://docs.oracle.com/cd/B28359_01/server.111/b28318/data_int.htm#CNCPT1623


text:
Q: Java - Restricting by what a method can be called I have methods set to public because they must be called by an exterior class, but I only ever want them called by one or two methods. Being called by other methods could create bugs in my program. So, in order to prevent me from accidentally programming around my own methods, I have been doing stuff like this within the methods of which I want to restrict callers:
if(trace.length<2){
    throw new Exception("Class should not call its own function.");
}else if(trace[1].getClassName()!=desiredClassName || trace[1].getMethodName()!=desiredMethodName){
    throw new Exception(trace[1].getClassName()+"\" is invalid function caller. Should only be called by "+desiredClassName+"->"+desiredMethodName+".");
}

Is there something else I should be doing, or should I just not forget how my program works?

A: You should be using visibility to restrict calling - making a method public (or for that matter, javadocing it) is not going to work unless you have dicipline (and you control the callers too). From your description, you are neither.
What you can do is make the class package private, and put it in the same package as the two callers of that class. As long as you have a proper package structure, this can work. E.g.:
Your class that should only be called by A and B:
package thepackage.of.a.and.b;
//imports here
class CallableByAB {
 public void methodA(){}
 public void methodB(){}
}

A:
package thepackage.of.a.and.b;
public class A {
   /*...other code here */
   new CallableByAB().methodA();
   /*...other code here */
}

B:
package thepackage.of.a.and.b;
public class B {
   /*...other code here */
   new CallableByAB().methodB();
   /*...other code here */
}

other classes cannot call  new CallableByAB() or import it. hence, safety.

A: This seems like a very brittle solution to a problem you should not need to solve.
In this particular case you may not suffer too greatly in future maintenance, just a couple of methods with these kind of special guards. But imagine trying to apply such logic to many methods across a large code base - it's just not a tenable thing to do. Even in your case you are effectivley writing code that cannot be reused in other contexts.
The fact that you need to do this surely reflects some kind of mis-design.
I infer that you have some kind of stateful interface whose state gets fouled up if called unexpectedly. Ideally I would want to make the interface more robust, but if that just cannot be done: If there are particular methods that should use this interface can you move those methods to a specific class - maybe an inner class of the current objtec you have - and have a handle visible only in this class?
 private Class TheLegalCaller {
      private RestrictedCallee myCallee = new RestricatedCallee() ; // or other creation
      public void doOneThing() { myCallee.doOne(); }
      public void doOtherThing() } myCallee.doOther(); }
 }

Now the downside with this is that it only pushes the problem up a level, if you randomly use TheLegalCaller in the wrong places then I guess you still have an issue. But maybe by making the restriction very visible it aids your memory?

A: Try using access rules.
http://groups.google.com/group/google-web-toolkit/browse_thread/thread/90c424dc44db523e

A: I found a very simple way to do that, but requires some coding methodology:
class AllowedCaller {
  private Object key;
  public boolean getKey(){
    return key;
  }
  public void allowedCallingMethod(RestrictedAccessClass rac){
    this.key = rac;
    rac.restrictedMethod();
    this.key = null;
  }
}

class RestrictedAccessClass{
  public void restrictedMethod(){
    if(allowedCallerInstance.getKey() != this){
      throw new NullPointerException("forbidden!");
    }
    // do restricted stuff
  }
}

I think it could be improved to prevent multithread simultaneous access to restrictedMethod().
Also, the key could be on another class other than AllowedCaller (so RestrictedAccessClass would not need to know about AllowedClass), and such control could be centralized, so instead of a single key, it could be an ArrayList with several object keys allowed at the same time.


text:
Q: Find prob. that only select red balls from $n$ (red+blue) balls There are 4 blue balls and 6 red balls(total 10 balls). $X$ is a random variable of the number of selected balls(without replacement), in which
$$P(X=1)=0.1$$
$$P(X=2)=0.5$$
$$P(X=3)=0.2$$
$$P(X=4)=0.1$$
$$P(X=10)=0.1$$
Then, what is probability of only selecting red balls?
This is what I have tried:
The (conditional) probability that all $r$ of the balls are selected from the red is just: ${6\choose r}\big/{10\choose r}$, for $0\leq r\leq 6$ , and $0$ elsewhere.
That is, let $N_R$ be the number of red balls selected, and $N_r$ the total number of balls selected, then:
$$\mathsf P(N_r=N_R\mid N_r=r) = \frac{6!/(6-r)!}{10!/(10-r)!} \mathbf 1_{r\in\{1\ldots 6\}}$$
As the number of balls selected is a random variable with the specified distribution, then the probability that all balls selected are red is:
$$\begin{align}
\mathsf P(N_R=N_r) & =\frac{1}{10}\frac{6!\,(10-1)!}{(6-1)!\,10!}+\frac 5{10}\frac{6!\,(10-2)!}{(6-2)!\,10!}+\frac{1}{5}\frac{6!\,(10-3)!}{(6-3)!\,10!}+...
\\[1ex] &
\end{align}$$

A: Since there is $6$ red balls, if $10$ balls are selected, probability of selecting only red balls is $0$ and we only have to consider selecting $1,2,3,4$ balls.
Let $R$ be number of red balls selected.
$$\begin{align}P(R=i|X=i)&=\frac{_6P_i}{_{10}P_i}\\
P(R=X)&=\sum\limits_{i=1}^4P(X=i)\cdot P(R=i|X=i)\\
&=0.1\cdot \frac 6{10}+0.5\cdot \frac {6\cdot5}{10\cdot9}+0.2\cdot \frac {6\cdot5\cdot4}{10\cdot9\cdot8}+0.1\cdot \frac {6\cdot5\cdot4\cdot3}{10\cdot9\cdot8\cdot7}\\
&=\frac{187}{700}\end{align}$$

A: Let $A = \{\text{Choose only red}\}.$ Let $X$ be the number of balls drawn, and let $R$ be the number of red balls drawn. Then
\begin{align*}
P(A) &=\sum_{k = 0}^{6} P(R  = k|X = k)P(X = k)\tag 1\\
&=\sum_{k = 0}^{6} \frac{\binom{6}{k}}{\binom{10}{k}}p_k\\
&=\frac{\binom{6}{1}}{\binom{10}{1}}(.1)+\frac{\binom{6}{2}}{\binom{10}{2}}(.5)+\frac{\binom{6}{3}}{\binom{10}{3}}(.2)+\frac{\binom{6}{4}}{\binom{10}{4}}(.1)+\frac{\binom{6}{5}}{\binom{10}{5}}(0)+\frac{\binom{6}{6}}{\binom{10}{6}}(0)\tag2\\
&= \frac{187}{700},
\end{align*}
where in $(1)$ it has to be the case that the number the random number you draw has to equal the number of red balls you draw; in $(2)$, $p_5 = p_6 = 0$ since according to the distribution of $X$, you cannot draw 5 or 6 times.
So, our answers agree, almost. If you complete your calculation (since you didn't post it), our answers should agree.


text:
Q: Boolean in React useState is casted to its contrary value During creating my own sign up hook while using Firebase Auth, I've encountered a strange issue.
export const useSignup = () => {
   const [error, setError] = useState(null);
   const [isPending, setIsPending] = useState(false);
   const [isFulfilled, setIsFulfilled] = useState(false);
   const { dispatch } = useAuthContext();

   const signup = async (email, password) => {
      setError(null);
      setIsPending(true);

      try {
         const res = await projectAuth.createUserWithEmailAndPassword(
            email,
            password
         );

         if (!res) {
            throw new Error('Sign up has failed, please try again.');
         }

         dispatch({ type: 'LOGIN', payload: res.user });

         // Will be casted as 'true', no idea why
         setIsFulfilled(false);

         if (!isCancelled) {
            setIsPending(false);
            setError(null);
         }
      } catch (err) {
         if (!isCancelled) {
            setError(err.message);
            setIsPending(false);

            // Will be casted as 'false', also no idea why
            setIsFulfilled(true);
         }
      }
   };

   return { signup, error, isPending, isFulfilled };
};

After registration process will be complete, I want to set state of isFulfilled to true and pass it forward, but strangely, while debugging and logging it to console, it outputs false, even if I check it immediately after invoking setIsFulfilled(true).
What interferes with state, so it outputs a contrary Boolean values?

A: remember that when setting states (ie, when using setIsPending) it's an asynchronous call, so don't expect them to act synchronous without their respective awaits. also, perhaps the use of useEffect might be useful looking at your implementation


text:
Q: How to maintain svn revision number in svn2git migration repository Recently one of my Svn project migrated to git using svn2git, is it possible to maintain old revision number in migrated git repository?

A: Use option -m/--metadata, See https://github.com/nirvdrum/svn2git#options-reference.


text:
Q: Mounting a Galxy S5 as a USB I have a Galaxy S5 and tried to use various methods to connect/mount as a USB. Went through all the steps at How to connect Android 7.1 to Ubuntu Linux with USB?
This was all using version 16.04, and have now tried it on a 18.04 version, same issues. Trying to mount is further hampered by the annoying access message on the Samsung. Pressing 'allow' doesn't give access, it simply prompts another message every few seconds.
$ mtp-detect libmtp version: 1.1.13

Listing raw device(s) Device 0 (VID=04e8 and PID=6860) is a Samsung Galaxy models (MTP). Found 1 device(s): Samsung: Galaxy models (MTP) (04e8:6860) @ bus 3, dev 26 Attempting to connect device(s) ignoring libusb_claim_interface() = -6PTP_ERROR_IO: failed to open session, trying again after resetting USB interface LIBMTP libusb: Attempt to reset device LIBMTP PANIC: failed to open session on second attempt Unable to open raw device 0 OK.

A: This works perfectly for me ..

*

*Make some path under HOME. (I had many permissions problems when trying to do this under /media )

mkdir ~/myphone

*Connect the device to the USB cable

*Ignore any messages on Ubuntu, but take the "allow" option on the Phone, if it appears

*Use jmtpfs to mount the mtp device
jmtpfs ~/myphone
Device 0 (VID=04e8 and PID=6860) is a Samsung Galaxy models (MTP).
LIBMTP ERROR: couldnt parse extension samsung.com/devicestatus:0

*Although it gives an error, the device is available

jmtpfs -l
Device 0 (VID=04e8 and PID=6860) is a Samsung Galaxy models (MTP).
Available devices (busLocation, devNum, productId, vendorId, product, vendor):
1, 9, 0x6860, 0x04e8, Galaxy models (MTP), Samsung

*Check with the mount command ...

mount
jmtpfs on /home/oygle/myphone type fuse.jmtpfs (rw,nosuid,nodev,relatime,user_id=1000,group_id=10 00)

*Also the ls command

ls -al  ~/myphone
total 4
drwxr-xr-x 3 oygle oygle 0 Jan 1 1970 .
drwxr-xr-x 47 oygle oygle 4096 Sep 14 08:50 ..
drwxr-xr-x 15 oygle oygle 0 Apr 4 4460147 Phone

*It can be accessed via Dolphin,etc

*Unmount before disconnecting the cable
fusermount -u  ~/myphone

*Disconnect the micro usb cable

*I have no idea if all the various commands to modify files, shown in the tutorial at https://ubuntuforums.org/showthread.php?t=2226702 was necessary or were used by jmtpfs. Certainly in the early stages of attempting this, those modifications were done, but IMO the tutorial was for "connecting", not mounting.


text:
Q: javascript based slideshow not working I'm trying to implement a simple javascript/jquery-1.6.2 slideshow (I'm not used to javascript), the problem I have is that the items are all shown and I don't know how to hide them.
here is my PHP/HTML code:
  <?php
  $c = 0;
  // show parts of latest news:
  foreach ($items AS $data) {

    // news image
    $image = './images/'.$data['image'];
    // description
    $part_description = substr(nl2br($data['content']), 0, 120);
    ?>

    <div id="cap_<?php echo $c; ?>" class="cap" >

<a href="<?php echo WEBSITE.'/news/view?id='.$data['id']; ?>" >
        <?php echo $data['title']; ?>

            <a href="<?php echo WEBSITE.'/news/view?id='.$data['id']; ?>" >
              <img alt="Item image" width="200"
                   src="<?php echo $image; ?>" />

            By
            <?php echo $data['author']; ?>

        <?php echo stripslashes($part_description); ?>
        <a href="<?php echo WEBSITE.'/news/view?id='.$data['id']; ?>" >
          read more

    <?php
    $c++;
  }
  // show links:
  ?>

  <?php
  for ($i=0; $i<$k; $i++) {
    ?>
    <a href="javascript:slideShow(<?php echo $i; ?>, <?php echo $k; ?>);" class="link_number" id="link_<?php echo $i; ?>">
      <?php echo $i+1; ?>

    <?php
  }
  ?>

And my js function:
function slideShow(id, max) {
  var inputHide = null;
  for (var i=0; i<max; i++) {
    $('#cap_'+id).fadeOut(500);
    inputHide = document.getElementById('cap_'+i);
    document.getElementById('link_'+i).style.backgroundColor = '#999999';
  }
  $('#cap_'+id).fadeIn(500);
  document.getElementById('link_'+id).style.backgroundColor = 'black';
}

I have two questions:
Q1: how can I fix this problem and show only one
Q2: is it better if I use a ready-to-use script like jqueryui?

A: In terms of your second question, It depends on what you need, and your understanding of JS. If you have a pure JS script, and you understand how and why it works, you can tailor it to your needs more. 'personalise it', if you like. However if your knowledge of JS is limited, then a ready to use script may suit you better.
A good way to learn things is to find a pure JS script somewhere (probably many on here), and use that one, but do your research and use your initiative until you understand how it works. Then you can use it in other projects, change it, use bits of it. That's how I learnt most of my javascript!
I've had some trouble with slideshows recently too, good luck! :)

A: Q1: this should work: inputHide.style.display = 'none';
Q2: In my opinion, both ways are good


text:
Q: Unsat core generation with .NET Z3 API I'm trying to turn on unsat core generation, using Z3 4.3.0 and the .NET API.
Calling context.UpdateParamValue("unsat_core", "true") throws an exception with the message "Error setting 'unsat_core', reason: unknown option".
Checking context.SimplifyParameterDescriptions lists only these parameters:
(:ite-extra-rules, :flat, :elim-and, :local-ctx, :local-ctx-limit, :blast-distinct, :som, :som-blowup, :hoist-mul, :hoist-cmul, :algebraic-number-evaluator, :mul-to-power, :expand-power, :expand-tan, :max-degree, :eq2ineq, :sort-sums, :gcd-rounding, :arith-lhs, :elim-to-real, :push-to-real, :elim-rem, :udiv2mul, :split-concat-eq, :bit2bool, :blast-eq-value, :elim-sign-ext, :hi-div0, :mul2concat, :expand-select-store, :sort-store, :max-memory, :max-steps, :push-ite-arith, :push-ite-bv, :pull-cheap-ite, :cache-all)

This is related to a previously asked question which didn't seem to get a conclusive answer.

A: The exact form the configuration needs to take depends on which parts of Z3, and which version is being used. The SimplifyParameterDescriptions are only for the simplifier (either calls to the Simplify tactic, or Expr.Simplify). Unsat-core generation needs to be enabled either on the Context (via it's constructor and option unsat_core), or via the parameters of a Goal (see Context.MkGoal).
I can't test it where I am right now, but I think the old version (master/4.3.0) used the same parameter name in upper case. Newer versions (i.e., the unstable branch) also have a function for setting global parameters in Global.SetParamValue. Sorry about the confusion, but the parameter setting infrastructure was completely replaced since the last master release.


text:
Q: How can I resolve "Property cannot be accessed on possibly null value" in FlowType? The following function signature:
type SaveComplete = {
  id: string
};

const handleReduce = ((state, { payload: { id } }: Action<SaveComplete>) => {
   // `id` is used unconditionally
};

...results in the following FlowType error:
property `id`. Property cannot be accessed on possibly null value

How can I fix this error?

A: The cause was that the type for Action had not been imported into the file.


text:
Q: Coherency matrix of partially polarized light doesn't contain all information on polarization state? The electric field of quasi-monochromatic, partially polarized light can be expressed by the following random process (Goodman, Statistical optics)
$$\bar{E}(t,\bar{x})=u_{x}(t,\bar{x})\bar{e}_{x}+u_{y}(t,\bar{y})\bar{e}_{y}$$
$$u_{x}(t,\bar{x})=\Psi_{x} e^{i(\bar{k}\cdot\bar{x}-\omega t)}$$
$$u_{y}(t,\bar{x})=\Psi_{y} e^{i(\bar{k}\cdot\bar{x}-\omega t)}$$
where $\Psi_{x}$ and $\Psi_{y}$ are radom phasor sums (which are circular complex Gaussian random variables). The joint statistics of $u_{x}=a+bi$ and $u_{y}=c+di$ describe the polarization state. Knowing that $E(u_{x})=E(u_{y})=0$, the covariance matrix of these two complex is given by
$$C=\begin{bmatrix}
E(aa)&E(ac)&E(ab)&E(ad)\\
E(ca)&E(cc)&E(cb)&E(cd)\\
E(ba)&E(bc)&E(bb)&E(bd)\\
E(da)&E(dc)&E(db)&E(dd)
\end{bmatrix}=\begin{bmatrix}
E(aa)&E(ac)&0&E(ad)\\
E(ac)&E(cc)&E(bc)&0\\
0&E(bc)&E(aa)&E(bd)\\
E(ad)&0&E(bd)&E(cc)
\end{bmatrix}$$
This matrix has 6 free parameters. However, one often states that the polarization is determined by the coherency matrix
$$J=\begin{bmatrix}
E(u_{x}u_{x}^{\ast})&E(u_{x}u_{y}^{\ast})\\
E(u_{y}u_{x}^{\ast})&E(u_{y}u_{y}^{\ast})
\end{bmatrix}=\begin{bmatrix}
2E(aa)&E(ac)+E(bd)+i(E(bc)-E(ad))\\
E(ac)+E(bd)-i(E(bc)-E(ad))&2E(cc)
\end{bmatrix}
$$
which has only $4$ free parameters because two pairs of free parameters of $C$ are combined in two free parameters in $J$. So we lost 2 degrees of freedom. Does this mean that $E(ac)=E(bd)$ and $E(bc)=-E(ad)$ or does this mean that the coherency matrix doesn't contain all information on the polarization state?

A: Jones Matrices cannot express partial polarization.
For that you need Stokes Vectors and the related Mueller Matrices (for transforming one Stokes vector into another).
Interestingly a Stokes Vector can be trivially separated into a fully polarized vector and a fully unpolarized vector.


text:
Q: Why is insertion sort Θ(n^2) in the average case? Insertion sort has a runtime that is Ω(n) (when the input is sorted) and O(n2) (when the input is reverse sorted).  On average, it runs in Θ(n2) time.
Why is this?  Why isn't the average case closer to O(n log n), for example?

A: To answer this question, let's first determine how we can evaluate the runtime of insertion sort.  If we can find a nice mathematical expression for the runtime, we can then manipulate that expression to determine the average runtime.
The key observation we need to have is that the runtime of insertion sort is closely related to the number of inversions in the input array.  An inversion in an array is a pair of elements A[i] and A[j] that are in the wrong relative order - that is, i < j, but A[j] < A[i].  For example, in this array:
0 1 3 2 4 5

There is one inversion: the 3 and 2 should be switched.  In this array:
4 1 0 3 2

There are 6 inversions:

*

*4 and 1

*4 and 0

*4 and 3

*4 and 2

*1 and 0

*3 and 2

One important property of inversions is that a sorted array has no inversions in it, since every element should be smaller than everything coming after it and larger than everything coming before it.
The reason this is significant is that there is a direct link between the amount of work done in insertion sort and the number of inversions in the original array.  To see this, let's review some quick pseudocode for insertion sort:

*

*For i = 2 .. n: (Assuming 1-indexing)

*

*Set j = i - 1.

*While A[j] > A[j + 1]:

*

*Swap A[j] and A[j + 1].

*Set j = j - 1.

Normally, when determining the total amount of work done by a function like this, we could determine the maximum amount of work done by the inner loop, then multiply it by the number of iterations of the outer loop.  This will give an upper bound, but not necessarily a tight bound.  A better way to account for the total work done is to recognize that there are two different sources of work:

*

*The outer loop, which counts 2, 3, ..., n, and

*The inner loop, which performs swaps.

That outer loop always does Θ(n) work.  The inner loop, however, does an amount of work that's proportional to the total number of swaps made across the entire runtime of the algorithm.  To see how much work that loop will do, we will need to determine how many total swaps are made across all iterations of the algorithm.
This is where inversions come in.  Notice that when insertion sort runs, it always swaps adjacent elements in the array, and it only swaps the two elements if they form an inversion.  So what happens to the total number of inversions in the array after we perform a swap?  Well, graphically, we have this:
 [---- X ----] A[j] A[j+1] [---- Y ----]

Here, X is the part of the array coming before the swapped pair and Y is the part of the array coming after the swapped pair.
Let's suppose that we swap A[j] and A[j+1].  What happens to the number of inversions?  Well, let's consider some arbitrary inversion between two elements.  There are 6 possibilities:

*

*Both elements are in X, or both elements are in Y, or one element is in X and one element is in Y.  Then the inversion is still there, since we didn't move any of those elements.

*One element is in X or Y and the other is either A[j] or A[j+1].  Then the inversion is still there, since the relative orderings of the elements haven't changed, even though their absolute positions might have.

*One element is A[j] and the other A[j+1].  Then the inversion is removed after the swap.

This means that after performing a swap, we decrease the number of inversions by exactly one, because only the inversion of the adjacent pair has disappeared.  This is hugely important for the following reason: If we start off with I inversions, each swap will decrease the number by exactly one.  Once no inversions are left, no more swaps are performed.  Therefore, the number of swaps equals the number of inversions!
Given this, we can accurately express the runtime of insertion sort as Θ(n + I), where I is the number of inversions of the original array.  This matches our original runtime bounds - in a sorted array, there are 0 inversions, and the runtime is Θ(n + 0) = Θ(n), and in a reverse-sorted array, there are n(n - 1)/2 inversions, and the runtime is Θ(n + n(n-1)/2) = Θ(n2).  Nifty!
So now we have a super precise way of analyzing the runtime of insertion sort given a particular array.  Let's see how we can analyze its average runtime.  To do this, we'll need to make an assumption about the distribution of the inputs.  Since insertion sort is a comparison-based sorting algorithm, the actual values of the input array don't actually matter; only their relative ordering actually matters.  In what follows, I'm going to assume that all the array elements are distinct, though if this isn't the case the analysis doesn't change all that much.  I'll point out where things go off-script when we get there.
To solve this problem, we're going to introduce a bunch of indicator variables of the form Xij, where Xij is a random variable that is 1 if A[i] and A[j] form an inversion and 0 otherwise.  There will be n(n - 1)/2 of these variables, one for each distinct pair of elements.  Note that these variables account for each possible inversion in the array.
Given these X's, we can define a new random variable I that is equal to the total number of inversions in the array.  This will be given by the sum of the X's:

I = Σ Xij

We're interested in E[I], the expected number of inversions in the array.  Using linearity of expectation, this is

E[I] = E[Σ Xij] = Σ E[Xij]

So now if we can get the value of E[Xij], we can determine the expected number of inversions and, therefore, the expected runtime!
Fortunately, since all the Xij's are binary indicator variables, we have that

E[Xij] = Pr[Xij = 1] = Pr[A[i] and A[j] are an inversion]

So what's the probability, given a random input array with no duplicates, that A[i] and A[j] are an inversion?  Well, half the time, A[i] will be less than A[j], and the other half of the time A[i] will be greater than A[j].  (If duplicates are allowed, there's a sneaky extra term to handle duplicates, but we'll ignore that for now).  Consequently, the probability that there's an inversion between A[i] and A[j] is 1 / 2.  Therefore:

E[I] = ΣE[Xij] = Σ (1 / 2)

Since there are n(n - 1)/2 terms in the sum, this works out to

E[I] = n(n - 1) / 4 = Θ(n2)

And so, on expectation, there will be Θ(n2) inversions, so on expectation the runtime will be Θ(n2 + n) = Θ(n2).  This explains why the average-case behavior of insertion sort is Θ(n2).
Hope this helps!

A: For fun I wrote a program which ran through all data combinations for a vector of size n counting comparisons and found that the best case is n-1 (all sorted) and the worst is (n*(n-1))/2.
Some results for different n:
  n min     ave     max ave/(min+max) ave/max

  2   1     1         1        0.5000
  3   2     2.667     3        0.5334
  4   3     4.917     6        0.5463
  5   4     7.717    10        0.5512
  6   5    11.050    15        0.5525
  7   6    14.907    21        0.5521
  8   7    19.282    28        0.5509
  9   8    24.171    36        0.5493
 10   9    29.571    45        0.5476
 11  10    35.480    55        0.5458
 12  11    41.897    66        0.5441

It seems the average value follows min closer than it does max.
EDIT: some additional values
 13  12    48.820    78        0.5424
 14  13    56.248    91        0.5408

EDIT: value for 15
 15  14    64.182   105        0.5393

EDIT: selected higher values
 16  15    72.619   120        -       0.6052
 32  31   275.942   496        -       0.5563
 64  63  1034.772  1953        -       0.5294
128 127  4186.567  8128        -       0.5151
256 255 16569.876 32640        -       0.5077

I recently wrote a program to compute the average number of comparisons for insertion sort for higher values of n. From these I have drawn the conclusion that as n approaches infinity the average case approaches the worst case divided by two.

A: Most algorithms have average-case the same as worst-case.  To see why this is, let's call O the worst-case and Ω the best-case.  Presumably, O >= Ω as n goes to infinity.  For most distributions, the average case is going to be close to the average of the best- and worst-case - that is, (O + Ω)/2 = O/2 + Ω/2.  Since we don't care about coefficients, and O >= Ω, this is the same as O.
Obviously, this is an oversimplification.  There are running time distributions that are skewed such that the assumption of the average-case being the average of the worst-case and the best-case is not valid*.  But this should give you a decent intuition as to why this is.
*As mentioned by templatetypedef in the comments, some examples are quicksort/quickselect, BST lookup (unless you balance the tree), hash table lookup, and the simplex method.

A: Lets take a look into program : General Representation

Loop : j = 1 to n
{
   temp = array[j]
   k = j - 1

   Loop until : ( k > 0 ) and ( array[k] > temp ) {
       array[k+1] = array[k]     // shifting one element at a time
       k = k - 1
   }

   array[k+1] = temp

}

Outer Loop : 1 - 2 - 3 - 4 - 5 - .... n
Inner Loop : for every single element there will be a inner loop of its own
Lets take an example of array : [ 3, 2, 9, 1, 2, 6, 5 ]  ( average-case )
                 3  -  2  -  9  -  1  - ..... n
                       |     |     |          |
    no. of loop        1     0     3       (n + 1) / 2

 (n+1)/2 -> (multiple cases. so, using median of all probabilities)

so, for  every element that is ( n )
inside loop is running ( (n+1)/2 ) number of times
 -> n(n+1)/2
 -> (n2 + n )/2
 -> n2 + n            // drop constants
 -> n2                // drop lower order terms

so that's why even for average case Time complexity is : O(n*n)
Note :
All loops that grow proportionally to the input size have a linear time complexity O(n). If you loop through only half of the array, that's still O(n). Remember that we drop the constants so 1/2 n => O(n).


text:
Q: How to swap images from side bar to the middle div on clicking on those sidebar images? I'm new to JavaScript and I'm trying to build a web page and I've 3 images of that product in my sidebar and one main image in the middle now I want to get the sidebar image in the middle when a user clicks on that sidebar image. I don't know how to go about this. I've already tried couple of ways which I've found online, one of them is this
1. How to swap image and video to another div?
But these are not working out for me.

A: What you have to do is save both images in a variable and then swap them. Look at the example below

var imgleft,
    imgcenter,
    $center = $(".center img");
$(".sidebar img").click(function(){
  imgleft = $(this).attr("src");
  imgcenter = $center.attr("src");
  $center.attr("src", imgleft);
  $(this).attr("src", imgcenter);
});
.sidebar{
  position: absolute;
  top: 0;
  width: 70px;
  height: 100%;
  background: red;
}
.center{
  width: 80px;
  height: 80px;
  margin:25% auto;
}

A: You can use javascript's event handling (on each of your sidebar images) to solve this problem. First add the following java script code in your html:

Then you can simply add the above functions in the onClick attributes of your three sidebar div's accordingly. This can be done like this:

    ...

    ...

    ...


text:
Q: Airy function and expansions I evaluate the following limit involving the Airy functions
$$\lim_{l \to 0} \text{Ai}(z+l) \text{Bi}^{'}(z) - \text{Bi}(z+l) \text{Ai}^{'}(z) \qquad (1)$$
by making a Taylor expansion of the Airy functions, writing $\text{Ai}(z+l) \approx \text{Ai}(z) + l \text{Ai}^{'}(z) + \cdots$ and $\text{Bi}^{'}(z+l) \approx \text{Bi}^{'}(z) + l \text{Bi}^{''}(z) + \cdots$. Substituting gives the limit as
$$\lim_{l \to 0} W( \text{Ai}(z), \text{Bi}(z) ) + \text{terms of order} \, l.$$
where $W()$ is the Wronskian (equal to $1/\pi$ here) which is expected (for small $l$ you are indeed determining the Wronskian).
The question: Shouldn't I get the same result for $l$ fixed and letting $z \to \infty$?
As $z$ increases the naïve argument appears to be that you are evaluating something between two points that are getting closer and closer to each other. However I don't seem to get the answer expected. For example if I were to look at (1) and make use of the (first order) asymptotic forms for large (positive) $z$ then I would get terms like (ignoring factors like $z^{\pm 1/4}, \pi$ that appear)
$$e^{-2/3 (z+l)^{3/2}} e^{2/3 z^{3/2}} - e^{+2/3 (z+l)^{3/2}} e^{-2/3 z^{3/2}} $$
which is OK for fixed $z$ and letting $l \to 0$ but isn't bounded for $z \to \infty$.


text:
Q: Open Xml Format sdk 2.0 Line Breaks I have written a function which collects from a two dimensional array. The issue I am having it that I used a string builder to put them both into one string but I would like a break in between
public static string[,] ArrSkills = new string[,]
{
    { "Live The Dream More" },
    { "And Even More" }
};

public static void WriteSkills()
{
    StringBuilder Builder = new StringBuilder();
    foreach (string s in ArrSkills)
    {
        Builder.AppendLine(s);
    }
    GetSkills = Builder.ToString(); ;
}

The output at the moment is "Live The Dream MoreAnd Even More" when using AppendLine the output has two unknown character symbols where the line break should be. I am writing to a custom XML linked to content controls. I was just wondering how would I be able to spit the array so both parts go on separate lines;

Live The Dream More
  And Even More

A: Just incase any one would like to know I have sorted this issue for getting a break point for my project any way. What I did was use the content control as plain text and then set the properties to "Allow carriage returns". From there I use the code
StringBuilder Builder = new StringBuilder();

        string Spacing = Environment.NewLine;

        string newline = "";

        foreach (string s in ArrSkills)
        {
            newline = string.Format("{0}{1}", Spacing, s);

            foreach (var Item in newline)
            {
                Builder.Append(Item);
            }
        }
        GetSkills = Builder.ToString();

with allowing Allowing carriage the method for Environment.NewLine allows a line break


text:
Q: How long did the first implementation of javascript take? I'm curious: how many days, weeks, months or years did it to code the first stable version of JavaScript?

A:
JavaScript, not to be confused with Java, was created in 10 days in May 1995 by Brendan Eich, then working at Netscape and now of Mozilla.

From W3C's A Short History of JavaScript.


text:
Q: Django Internationalization - Language not change I have already searched on many post but none could solve my problem.
My settings.py :
from os import path
PROJECT_ROOT = path.abspath(path.dirname(__file__))
LOCALE_PATHS = (path.join(PROJECT_ROOT, '/conf/locale/'),)

TIME_ZONE = 'UTC'
LANGUAGE_CODE = 'fr-fr'
USE_I18N = True
USE_L10N = True
gettext = lambda x: x
LANGUAGES = (
    ('fr', gettext('French')),
    ('en', gettext('English')),
)

TEMPLATE_CONTEXT_PROCESSOR = (
    "django.core.context_processors.i18n",
)

MIDDLEWARE_CLASSES = (
    "django.middleware.locale.LocaleMiddleware",
)

urls.py :
from django.conf.urls import *
urlpatterns = patterns ('',
    ...
    url(r'^i18n/', include('django.conf.urls.i18n')),
)

template.html (reduced version) :
<div id="header">
    ...
    {% include 'i18n.html' %}
</div>

i18n.html :
{% load i18n %}

{% trans "Une ligne de test" %}
<form action="/i18n/setlang/" method="post">
    {% csrf_token %}
    <input name="next" type="hidden" value="{{ request.get_full_path|slice:'3:' }} />
    <select name="language">
        {% get_current_language as LANGUAGE_CODE %}
        {% get_available_languages as LANGUAGES %}
        {% get_language_info_list for LANGUAGES as languages %}
        {% for language in languages %}
            <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}>
                {{ language.name_local }} ({{ language.code }})
            </option>
        {% endfor %}
    </select>
    <input type="submit" value="Go" />
</form>

I know this code has already appeared in many other posts but none solutions helped me.
My problem is that when i submit the form, the page reloads but the dropdown return on "French".
Furthermore, when i try an obsolete translation in /locale/fr/LC_MESSAGES/django.po for "Une ligne de test", i don't have the translate so I believe it doesn't access but I don't know why
Someone would have something to offer me please ?

|     UPDATE     |
When I run python manage.py runserver the translation don't work but I have in the terminal "POST /i18n/setlang/ HTTP/1.1" 302 0 so I think that this calls for the function set_language() but I really don't understand why the language don't change and why an obsolete translation doesn't display with the initial language.
And when I try LANGUAGE_CODE = "en", the dropdown take the value English but all the page stay in French.
For the information, I use Django 1.4.11 but I don't think that's my problem.

|     UPDATE     |
I tried too with this template, with only one choice to try change the language but the result is always the same.
<form action="/i18n/setlang/" method="post">
    {% csrf_token %}
    <input type="hidden" name="language" value="en" />
    <input type="hidden" name="next" value "{{ request.get_full_path|slice:'3:' }}" />
    <input type="submit" value="English" />
</form>

What does it missing ?