text:
Q: Unable to create record in Community I have the following objects Contact (looks up to) -> Account, Project, Project Role (looks up to Contact and Project)
A portal user has the following access to the objects:

*

*Account (Public Read-Only)

*Contact (Controlled By Parent)

*Project (Read-Only)

*Project Role (Read, Create, Edit)

When I try to create a Project Role record in the community I receive the following error:

EDIT: I'm able to save Project Role when the contact associated with the Project Role record is created by the community user.
What am I missing here? I suspect either Account or Contact is the issue here for the Portal user but I'm not sure.


text:
Q: Incorporate location selection drop-down widget into split panel Earth Engine App I am relatively new to using the ui module for creating Earth Engine Apps. I used the split panel code from the Earth Engine example apps https://google.earthengine.app/view/split-panel to create my own version for viewing NAIP imagery over time.
I am interested in taking this a step further, where I can add in a drop down widget that will allow my end users to select different locations, and the app will subsequently zoom to their selection. I am using a FeatureCollection of locations from which I derive the list for selection.
I have found a snippet of code which is getting me closer to what I am looking for (https://code.earthengine.google.com/2217e2c7de9571f3177fd7acdbdfd516) and I have added it underneath the split panel code. The panel and widget look good, but I am unable to get the app to zoom in to the location of interest. I believe it has to do with the callback function for the location selection widget, but I am uncertain exactly how to get this part of the script working correclty.
Would anyone happen to have a solution?

A: You were almost there. Inside the onChange function in ui.Select object, you were setting the center of a new ui.Map object whereas what is being displayed on screen are leftMap and rightMap objects.
So change the function to:
var select = ui.Select({
  items: names.getInfo(),
  placeholder: ('Choose Area of Interest'),
  style: {width: '290px'},
  onChange: function(key) {
    // Map.clear(); //clears previous calculations from map upon new selection
    var selection = ee.Feature(fc.filter(ee.Filter.eq('name', key)).first());
    // print(selection)
    leftMap.centerObject(selection); //centers map on Plantation selection
    // show Plantation
    var layer = ui.Map.Layer(selection, {color:'blue'}, 'Plantation');
    leftMap.layers().set(1, layer); //adds Plantation selection to the map
    // rightMap.layers().set(0, layer); //adds Plantation selection to the map
    var conversion = ee.FeatureCollection(selection); //converts the Plantation selection into a feature collection for future analyses
  }
});

And the drop-down location selector will work as intended.
Link to modified code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: i can't print all the print so I have code to convert a words .txt (300000 word) to a list but the  terminal is deleting some parts and can't read it, so can I print this to a .txt or print a % of the print .
this is the code to convert .txt to a list:
def load_words():
    with open('words_alpha.txt') as word_file:
        valid_words = set(word_file.read().split())

    return valid_words

if __name__ == '__main__':
    english_words = load_words()
    print(english_words)

A: You can simplify with one function and it should theoretically work. If it doesn't work for 300000 word try first a smaller file.
def countWordsInFile():

    array = []
    fileName = getUserText("Enter the name of the file you want to read array from")
    openFile = openNewFile(fileName,"read")
    i = openFile
    for words in i.read().split():
        for word in words:
            array.append(word)

    print(array)


text:
Q: How to convert a Date got at runtime from user in String format into Date format to feed it in the database public Date getTransactionDate()
    {
        System.out.println("Enter the transaction Date");
        String date = sc.next();
        DateFormat df = DateFormat.getDateInstance();
       String s1 = df.format(date);
       Date d1 = null;
       try
       {
           d1 = (Date) df.parse(s1);
       } catch (java.text.ParseException e)
       {
        // TODO Auto-generated catch block
        System.out.println(e.getMessage());
       }
          return d1;
   }

Date d2 = new PreparedStmnt().getTransactionDate();

public static void addTransaction(Connection connection, PreparedStatement preparedStatement , long transac_Id , Date transac_date)
    throws SQLException
{
    String sqlQuery = "INSERT INTO TRANSACTIONS VALUES (?,?)";
    preparedStatement = connection.prepareStatement(sqlQuery);
    preparedStatement.setLong(1, transac_Id);
    preparedStatement.setDate(2, transac_date);
    preparedStatement.executeUpdate();
}

Its a Simple Transaction entry where i want the user to provide date at runtime and then store that in the database.But while doing so, I'm getting a bug saying:
Exception in thread "main" java.lang.IllegalArgumentException: Cannot              format given Object as a Date
        at java.text.DateFormat.format(Unknown Source)
        at java.text.Format.format(Unknown Source)
        at bluePrint.PreparedStmnt.getTransactionDate(PreparedStmnt.java:76)
        at bluePrint.PreparedStmnt.main(PreparedStmnt.java:30)
Well this is my first project m working on. So, please help me.

A: you should use sc.nextLine() Instead sc.next() because its not consider space
you can try like
System.out.println("Enter the transaction Date");
        String string = "January 2, 2010";
        Scanner sc = new Scanner(System.in);
        string = sc.nextLine();
        System.out.println(string);
        DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
        try {
            Date date = format.parse(string);

            System.out.println(date);
        } catch (java.text.ParseException e) {
            // TODO Auto-generated catch block
            System.out.println(e.getMessage());
        }

this worked for me. entered date format January 2, 2010


text:
Q: Strongly exposed points/Exposed points I was studying and I got the next doubt:
We suppose that $(X,\|\cdot\|)$ is a Banach space and $C$ it is a convex closed subset of X.
We say that $x\in C$ it is an exposed point of $C$ if $\exists x^*\in X^*$ such that $x$ it is the only one point of $C$  that $x^*(x)=\displaystyle\sup_C x^*$.
We say that $x\in C$ it is an strongly exposed point of $C$ if $\exists x^*\in X^*$ such that for every sequence $(x_n)\subset C$ that verifies $x^*(x_n)\to \displaystyle\sup_C x^*$ then $\|x_n-x\|\to 0$.
It's true that every strongly exposed point it is an exposed point.
So I try to view if every exposed point it is an strongly exposed point (it would be false!).
Suppose that $x\in C$ it is an exposed point, then there is $x^*\in X^*$ such that $x^*(x)=\displaystyle\sup_C x^*$.
Let $(x_n)\in C$ such that $x^*(x_n)\to \displaystyle\sup_C x^*$.
$x_n$ must converge ($x^*$ is continuous), so we suppose that $x_n\to y\in C$ ($C$ is closed). Then, by continuity $x^*(x_n)\to x^*(y)=\displaystyle\sup_C x^*$.
So by the uniqueness, $x=y$ and then $\|x_n-x\|=\|x_n-y\|\to 0$. Then $x$ it is an strongly exposed point.
The question is: what is wrong in my reasoning? There is a counterexample of Lindenstrauss for example (7.73 in the a book of Fabian: Functional Analysis and Infinite-Dimensional Geometry).
Many thanks beforehand.

A: You have to prove $x_n$ converges to $x$ in norm. You have assumed that $x_n$ converges to $y$. This assumption is wrong. First of all, from the hypothesis (i.e., $x^*(x_n)$ converges to $x^*(x)$) we could only conclude $x_n$ converges to $x$ w. r. to the weak topology on $X$, provided $x_n$ is a bounded (norm) sequence.


text:
Q: How to specify preprocessor options in Visual Studio On Linux with g++ I use -DPROGRAMNAME_VERSION=1.6 and -DEIGEN_NO_DEBUG to properly set some text and increase the speed of execution respectively.  I am doing some testing on Windows and am having trouble duplicating the executable with VS 2013. I searched around SO and found suggestions for Properties->C/C++->Preprocessor->Preprocessor Definitions.  This agrees with Microsoft's documentation found here https://msdn.microsoft.com/en-us/library/hhzbb5c8.aspx.  The problem is that when I try to do it with
/DEIGEN_NO_DEBUG
/DPROGRAMNAME_VERSION=1.6

The log file shows the default value of version 1.00 and the execution time is twice that of the expected time.
The /DEIGEN_NO_DEBUG is used for C++ Eigen while the other is used as such:
#ifndef PROGRAMNAME_VERSION
#define PROGRAMNAME_VERSION 1.00
#endif

Both have been tested and work on Linux.  The answers on SO have been accepted which makes me think there is some small trick I am missing to make this work.

A: Praetorian gave the correct answer.  Visual Studio doesn't use the same /D or -D that g++, etc use.  It inserts that for you.  The correct usage is as shown in his comment.

I'm guessing you put /DPROGRAMNAME_VERSION=1.6 into the settings instead of PROGRAMNAME_VERSION=1.6. MS build will insert the /D for you when invoking the compiler. – Praetorian


text:
Q: Apache Jena: adding GraphNode (N3 formula) to Model (ARQInternalErrorException) I'm attempting to add a Graph node to a Model (N3 formula)
The output should be roughly like the below:
<http://localhost:8080/patches/#cf0ba48fa8b0421c8b025c3ea6b41a4f>
        a       <http://www.w3.org/ns/solid/terms#Patch> ;
        <http://www.w3.org/ns/solid/terms#patches>
                <http://example.com/#me> ;
        <http://www.w3.org/ns/solid/terms#inserts> { http://example.com/#me http://example.com/#property http://example.com/#resource } .

Note that the #inserts property here is a "GraphNode" or N3 formula, I'm modelling a graph of the triples to write when a Task is complete
I tried the code below:
Model out = ModelFactory.createDefaultModel();
out.add(endState, SolidTerms.inserts, out.asRDFNode(NodeFactory.createGraphNode(inserts.getGraph())));

but this throws [org.apache.jena.sparql.ARQInternalErrorException: Unknown node type:  {http://example.com/#me @http://example.com/#property http://example.com/#resource}]
I've tried many other ways of putting the Graph in the model with no success, posting this one because it was my first and I think the most rational. Maybe it's a bug or Jena just doesn't support the GraphNode type in RDFNode ?
The @ in the output puzzled me a bit, but I checked that it's not included in my property definition, it's maybe added in by the createGraphNode or the error serialization


text:
Q: I don't know priority of some lines OOP I have problem at my code I don't know priority of some lines,
I want to make (Game guess the number),
have user and computer player both have (10) points,
so the user input number form 1 to 2, if (user input) == (number of guess),
will -1 from computer points(10) = 9, and vice versa,
so my problem at the points, after first time user input number it Become as they were automatically(10),
sorry about my english so bad.
at below my code, I hope any one help me thank you.
from random import randint as any_number

class Game():
    def __init__(self, name, number, points):
        self.name = name
        self.number = number
        self.points = points

    def score(self, other):
        guess = any_number(1, 2)
        if self.number == guess:
            print('{} your are correct'.format(self.name))
            other.points = other.points - 1
        else:
            print('{} your are incorrect'.format(self.name))
        print('{} points is ({}) and {} points is ({})'.format(self.name, self.points, other.name, other.points))

while True:
    user1 = int(input('Guess a number from 1 to 2: '))
    computer = any_number(1, 2)

    p1 = Game('Player1', user1, 10)       #  <---- my problem here
    p2 = Game('player2', computer, 10)    #  <---- my problem here

    if type(user1) == int:
        p1.score(p2)
        print('================================================= ')
        p2.score(p1)
    else:
        print('your input is Error')

A: If I well understood your issue, the problem is that you are creating a new instance of type Game in every turn, so try this:
from random import randint as any_number

class Game():
    def __init__(self, name, number, points):
        self.name = name
        self.number = number
        self.points = points

    def score(self, other):
        guess = any_number(1, 2)
        if self.number == guess:
            print('{} your are correct'.format(self.name))
            other.points = other.points - 1
        else:
            print('{} your are incorrect'.format(self.name))
        print('{} points is ({}) and {} points is ({})'.format(self.name, self.points, other.name, other.points))

p1 = Game('Player1', user1, 10)
p2 = Game('player2', computer, 10)

while True:
    user1 = int(input('Guess a number from 1 to 2: '))
    computer = any_number(1, 2)

    if type(user1) == int:
        p1.score(p2)
        print('================================================= ')
        p2.score(p1)
    else:
        print('your input is Error')


text:
Q: Auth::attempt($credentials) always returns false Hi there I am new to laravel and I am trying to code functionality of my login form here are the codes:
this is how I create new user (works well)
public function action_newuser()
{

    $email = Input::get('email');
    $password = Input::get('password');
    $new_user = Input::get('new_user', 'off');
    $first_name= Input::get('firstname');
    $last_name= Input::get('last_name');
    $username= Input::get('username');

    $user = new User();
    $user->email = $email;
    $user->password = Hash::make($password);
    $user->first_name =$first_name;
    $user->last_name= $last_name;
    $user->username= $username;
    try{

        $user->save();
    }
    catch(Exception $e) {
        echo "Failed to create new user!";
    }

This is my login function:
public function action_login()
{

    $password = Input::get('password');
    $username= Input::get('username');
    $remember= Input::get('remember', 'off');
    if($remember =='off')   $remember=FALSE;
    if($remember =='on') $remember=TRUE;
    $credentials = array(
            'username' => $username,
            'password' => $password,
            'remember' => $remember
        );
     if( Auth::attempt($credentials))
        {
            return Redirect::to('dashboard/index');
        }
        else
        {
            #I put this line to check are the values passed from my form are correct.
            echo $password.'  ' .$username.' '. $remember;

        }

}

When I submit login form it always shows a blank page has values of $password, $username and $remember values. This means Auth::attempt() is not working well.
What can be the problem?

A: Fool me!
Although I have checked it many times, I could not see the line 'username' => 'email',  in auth config file.
it should be 'username' => 'username', since I am going to use username for login.

A: Check to make sure that your database password field is 60 characters.

A: To all laravel 4 developers who are facing the Auth::attempt() login failure with valid creditials!
Solution:

*

*In app/config/app.php change type:  'cipher' => MCRYPT_RIJNDAEL_128 to 'cipher' => MCRYPT_RIJNDAEL_256 and re-hash all passwords

*In Model add method:
 public function setPasswordAttribute($pass) {

     $this->attributes['password'] = Hash::make($pass);
 }

*In UserController:
//Create User or Register
   public function postCreate() {

    $input = Input::all();
    $user = new User;
    $user->username = Input::get('username');
    $user->email = Input::get('email');
    $user->password = Hash::make(Input::get('password'));
    $user = User::create($input);
    return Redirect::action("Frontend\HomeController@index");

}
//Login or Sign in
public function postSignin() {

    $userdata = array(
        'username' => Input::get('username'),
        'password' => Input::get('password')
    );

    if (Auth::attempt($userdata, true)) {
         Session::put('username', Auth::user()->username);
         return Redirect::action("Frontend\HomeController@index");
    } else {
         return Redirect::action("Frontend\UserController@getLogin")
                ->with('message', 'Your username/password combination was incorrect')
                ->withInput();
}

Hope i have helped someone out there


text:
Q: Angular ui grid error in css file When i was try implement angular ui-grid, I am geeting this error. some help me to sort this problem.

A: My first guess:
To import css you should use this line:
<link rel="stylesheet" href="styles/ui-grid-unstable.min.css" />

in your index.html.
I guess you import it as Javascript which will not work.


text:
Q: Is the sum of these two sets open or closed? $C_1$ = {$(x, y) | x > 0, y > 0, xy \ge 1$} - closed convex set
$C_2$ = {$(x, y) | x = 0$} - closed convex set
Where the Minkowski sum of two sets is A + B = { a + b | $a \epsilon A$, $b \epsilon B$}
Then, $C_1 + C_2$ = {$(x, y) | x \ne 0, y > 0, xy \ge 1$}
Not really sure if the sum of the two sets is correct but then it would be closed, correct?

A: $C_2$ is the $y$-axis, and $C_1+C_2$ is the right half-plane (excluding the $y$-axis), it happens to be open in this example, but not closed.
To elaborate, take any $(x,y)$ with $x>0$ i.e. any point in the right half-plane.
Then $(x,\frac1x)\in C_1$ and $(0,y-\frac1x)\in C_2$, so $(x,y)=(x,\frac1x)+(0,y-\frac1x)\in C_1+C_2$, which proves that the right half-plane is contained in $C_1+C_2$. For the other direction take any $(x,y_1)\in C_1$ (so by assumption $x>0$ and $y_1=\frac1x$) and any $(0,y_2)\in C_2$, then $(x,y_1)+(0,y_2)=(x,y_1+y_2)$ clearly belongs to the right half-plane since $x>0$.


text:
Q: TcpClient can't connect To TcpListener i want to use a TcpListener - TcpClient connection inside Network.
It is only working when i start the application both on one device, when i use 2 different devices in Network there is this Error:
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
Exception: System.Net.Sockets.SocketException (0x80004005): Es konnte keine Verbindung hergestellt werden, da der Zielcomputer die Verbindung verweigerte 127.0.0.1:1300
bei System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
bei System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
 bei System.Net.Sockets.TcpClient.Connect(IPEndPoint remoteEP)`bei System.Net.Sockets.TcpClient.Connect(IPAddress address, Int32 port)`

I thought this is because of Windows Firewall but even when i deactivate the Firewall, the Problem exists.
Server:
 ipAddress = Dns.GetHostEntry("localhost").AddressList[1];
                    server = new TcpListener(IPAddress.Any, port);
                    server.Start();

                    clients = new List<TcpClient>();

                    Console.WriteLine("Starte Server ..." + ipAddress + " : " + port);

                    receiver = new List<TCPReceiveMessages>();

How i Accept Client:
  clientAccepter = new Thread(this.accpeting);
              clientAccepter.Start();

and the Thread inside:
private void accpeting()
    {
        //Client socket erstellen
        socketForClient = server.AcceptSocket();

        while (accept)
        {
            //clients werden hinzugefügt
            clients.Add(server.AcceptTcpClient());
            receiver.Add(new TCPReceiveMessages(this));
       }

        socketForClient.Close();
        model.getController().setLoading(false, " ");
    }

And well the Client is Connecting to the correct ipAdress and port.
I hope anyone can help me :)
Edit 1: I changed the Ip Adress to 192.168.1.3, because it is inside network, now the TcpClient says that the Server is not reacting after a time span or the connect had troubles because the connected Host didn't react.

A: The Problem was that i used wrong ipAdress:

*

*changed ip adress to 192.168.1.3

*changed port to 5550

*had Problems: disabled Firewall
-> it worked

*enabled Firewall
-> it worked too
:) happing codeing


text:
Q: vb.net Get PrivateMemorySize64 and process id sort by memory size I've got the following:
Dim plist() As Process = Process.GetProcesses()

    For Each prs As Process In plist

        ListBox1.Items.Add(prs.ProcessName + "   (" + (prs.PrivateMemorySize64 / 1024000).ToString() + " MB)")

But id really like to get it to list it by memory size if possible? If anyone has any ideas it would be much appreciated

A: Here is a basic sample, you will have to customise it to your needs.
Public Class Form1
'
Dim pList() As Process = Nothing
'
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    '
    Dim pItem As Process = Nothing
    Dim pCounter As Integer = Nothing
    '
    pList = Process.GetProcesses()
    For pCounter = 0 To pList.Count - 1
        pItem = pList(pCounter)
        ListBox1.Items.Add(pItem.ProcessName + "   (" + (pItem.PrivateMemorySize64 / 1024000).ToString() + " MB)")        '
    Next
    'sort list
    SortProcessList()
    '
End Sub
'
Sub SortProcessList()
    '
    Dim i As Integer
    Dim j As Integer
    Dim pTmp As Process
    '
    'sort list based on lowest usage first
    For i = 0 To pList.Count - 2
        For j = i + 1 To pList.Count - 1
            If pList(i).PrivateMemorySize64 > pList(j).PrivateMemorySize64 Then
                pTmp = pList(i)
                pList(i) = pList(j)
                pList(j) = pTmp
            End If
        Next
    Next
    ReloadSortedList()
    '
End Sub

Sub ReloadSortedList()
    '
    Dim pItem As Process = Nothing
    Dim pCounter As Integer = Nothing
    '
    ListBox1.Items.Clear()
    For pCounter = 0 To pList.Count - 1
        pItem = pList(pCounter)
        ListBox1.Items.Add(pItem.ProcessName + "   (" + (pItem.PrivateMemorySize64 / 1024000).ToString() + " MB)")        '
    Next
    'tidy up
    pItem = Nothing
    pCounter = Nothing
    '
End Sub

End Class


text:
Q: Save video frames as images c# , Emgu cv I am trying to save videos frames to a folder but it's not working. I am using emgu cv image processing library for this project.
public void ProcessFrame(object sender, EventArgs arg)
{
    Mat mat = new Mat();

    capture.Retrieve(mat);

    FrameRate = capture.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.Fps);
    Thread.Sleep((int)(1000.0 / FrameRate));

    imageBox1.Image = mat;

    if (mat != null)
    {
        mat.Save(@"C:\Desktop\images");
    }
    else
    {
        MessageBox.Show("null image");
    }

    //GetVideoFrames1();
}

A: If you are using EmguCV, I highly recommend using Emgu's own VideoWriter (http://www.emgu.com/wiki/files/1.3.0.0/html/3fb90645-ecc4-0c4e-b238-6d0ca38f4ebc.htm), this allows you to create a video file and continuously write to it when you receive a new Mat, ie
VideoWriter writer = new VideoWriter(filePath + @"\" + fileName + ".avi", yourCodec, fps, size, true);
for(;;)
{
    Mat image = getNextFrame();
    writer.Write(frame);
}


text:
Q: How can I detect a click on the background of a JavaScript window? I am trying to make a JavaScript game on https://code.org game lab to increase reaction time and accuracy, and I cannot figure out how to detect a click on the background to decrease lives. Here is the code I have so far:
1  var score = 0;
2  var lives = 3;
3  var target1 = createSprite(randomNumber(50, 350), randomNumber(50, 350));
4  target1.setAnimation("Target1");
5  target1.scale = 0.5;
6  target1.setCollider("circle");
8  var target2 = createSprite(randomNumber(50, 350), randomNumber(50, 350));
9  target2.setAnimation("Target2");
10 target2.scale = 0.5;
11 target2.setCollider("circle");
12
13 function draw() {
14         scoreboard();
15         targetClick();
16         life();
17         drawSprites();
18 }
19
20 function scoreboard() {
21         background("black");
22         textSize(20);
23         text("Lives: " + lives, 10, 375, 100, 100);
24         text("Score: " + score, 10, 10, 100, 100);
25 }
26 function targetClick() {
27         if (mousePressedOver(target1)) {
28                 target1.x = randomNumber(50, 350);
29                 target1.y = randomNumber(50, 350);
30                 score = score + 1;
31         }
32         if (mousePressedOver(target2)) {
33                 target2.x = randomNumber(50, 350);
34                 target2.y = randomNumber(50, 350);
35                 score = score + 1;
36         }
37 }
38 function life() {
39   if (mousePressedOver(mousePressedOver(background)) {
40     lives = lives - 1;
41   }
42   if (lives <= 0) {
43           target1.destroy();
44           target2.destroy();
45           textSize(50);
46           text("Game Over!", 10, 150);
47   }
48 }

Line 39 is where I need it.
Can anyone help?
Edit: After some testing I realized if I could detect a click, just in general like a mousePressed() I could also use mouseX and mouseY to see if it was in the area of one of the targets and if it wasn't, I could remove a life.

A: MousePressedOver works if the mouse is pressed and over the element. So users can hold the right click and just move around the canvas to get points. To avoid that and solve the decreasing lives problem, you can use the combination we often use for click events in Game Lab. mouseWentDown() && mouseIsOver(target1)(&& means "and"). This triggers when the mouse clicked and it is over the target. To decrease lives you can simply add ! before the mouseover() since it's the not operator of the JavaScript. It basically means "trigger when the mouse is clicked, and when it is not over the target."
Here's the full code;
var score = 0;
  var lives = 3;
  var target1 = createSprite(randomNumber(50, 350), randomNumber(50, 350));
  target1.setAnimation("Target1");
  target1.scale = 0.5;
  target1.setCollider("circle");
  var target2 = createSprite(randomNumber(50, 350), randomNumber(50, 350));
  target2.setAnimation("Target2");
  target2.scale = 0.5;
  target2.setCollider("circle");

 function draw() {
         scoreboard();
         targetClick();
         life();
         drawSprites();
 }

 function scoreboard() {
         background("black");
         textSize(20);
         text("Lives: " + lives, 10, 375, 100, 100);
         text("Score: " + score, 10, 10, 100, 100);
 }
 function targetClick() {

         if (mouseWentDown() && mouseIsOver(target1)) {
                 target1.x = randomNumber(50, 350);
                 target1.y = randomNumber(50, 350);
                 score = score + 1;

         }
         if (mouseWentDown() && mouseIsOver(target2)) {
                 target2.x = randomNumber(50, 350);
                 target2.y = randomNumber(50, 350);
                 score = score + 1;

         }
 }

 function life() {
   if (mouseWentDown()&& !mouseIsOver(target1)&& !mouseIsOver(target2)) {
     lives = lives - 1;
   }
   if (lives <= 0) {
           target1.destroy();
           target2.destroy();
           textSize(50);
           text("Game Over!", 10, 150);
   }
 }


text:
Q: Make object move in 6 sides of the cube unity Hello there I want to make my object moves in 6 sides of the cube
like this one
Example
the problem is in changing the direction of the cube I don't know how I should move
any help, please?


text:
Q: How to sort data on the closest distance basis in QGIS? I'm preparing a map in QGIS 3.16.5 with the set of points and polygons in two layers. Unfortunately during a field work data were collected a bit randomly and objects of subsequent names are scattered on the map (by object I mean both: points & polygons). For instance, I have an object named 100 very close to object 1, while object 2 is located in a large distance. I want to rename objects to get some logical order of the names. I was going to export data to .csv, then change names in spreadsheet and import it again to a new layer.
Before that I need to sort data somehow using location and distance between objects as a rule. I would like to have object no. 1 in the first row, then, in the second row, the object that is closest to 1, in the third row object that is closest to this from the second row, in the fourth row object that is closest to this from the third row, and so on. In the end I would like to have numbers assigned respectively to each object.
Can it be done?


text:
Q: Entity Framework | Propriedade double que permite null Minha propriedade permite valores double e valores null.
No Banco de Dados SQL Server ela está configurada como decimal(18, 2).
Porém quando seto algum valor (ex: 5.00), passa a dar o erro abaixo.
Erro:

The 'Avaliacao' property on 'Ocorrencia' could not be set to a 'System.Decimal' value. You must set this property to a non-null value  of type 'System.Double'.

Model:
public class Ocorrencia
{
    [Key]
    public int id { get; set; }
    public double? Avaliacao { get; set; }
}

Como deve ficar para funcionar corretamente?

A: Você pode fazer o cast para double
ocorrencia.Avaliacao = (double)5.00;

A: Possivelmente você não está forçando a notação para double:
ocorrencia.Avaliacao = 5.00D;


text:
Q: Akka websocket - how to close connection by server? So here is my websocket server implementation.
val route = get {
  pathEndOrSingleSlash {
    handleWebSocketMessages(websocketFlow)
  }
}

def websocketFlow: Flow[Message, Message, Any] =
  Flow[Message]
    .collect { case TextMessage.Strict(textMessage) => protocol.hydrate(textMessage) }
    .via(chatActorFlow(UUID.randomUUID()))
    .map(event => TextMessage.Strict(protocol.serialize(event)))

def chatActorFlow(connectionId: UUID) : Flow[Protocol.Message, Protocol.Event, Any] = {

  val sink = Flow[Protocol.Message]
    .map(msg => Protocol.SignedMessage(connectionId, msg))
    .to(Sink.actorRef(chatRef, Protocol.CloseConnection(connectionId)))

  val source = Source
      .mapMaterializedValue {
        actor : ActorRef => {
          chatRef ! Protocol.OpenConnection(actor, connectionId)
        }
      }

  Flow.fromSinkAndSource(sink, source)
}

I'm wondering if there is any way to close connection once message of type ConnectionClosed is sent by chatRef?

A: The solution below allows to drop connections from the server side by terminating the Actor materialized by the Source.actorRef stage. This is simply done by sending a PoisonPill to it.
Now, it is still not clear to me how you'd like to identify a "banned" client at connection time, so the example is - on purpose - very simple: the server drops any connection after a maximum amount of clients are connected. If you want to use any other strategy to kick out clients at any time, you can still apply the same logic and send PoisonPill to their own source actors.
object ChatApp extends App {

  implicit val system = ActorSystem("chat")
  implicit val executor: ExecutionContextExecutor = system.dispatcher
  implicit val materializer = ActorMaterializer()

  val route = get {
    pathEndOrSingleSlash {
      handleWebSocketMessages(websocketFlow)
    }
  }

  val maximumClients = 1

  class ChatRef extends Actor {
    override def receive: Receive = withClients(Map.empty[UUID, ActorRef])

    def withClients(clients: Map[UUID, ActorRef]): Receive = {
      case SignedMessage(uuid, msg) => clients.collect{
        case (id, ar) if id == uuid => ar ! msg
      }
      case OpenConnection(ar, uuid) if clients.size == maximumClients => ar ! PoisonPill
      case OpenConnection(ar, uuid) => context.become(withClients(clients.updated(uuid, ar)))
      case CloseConnection(uuid) => context.become(withClients(clients - uuid))
    }
  }

  object Protocol {
    case class SignedMessage(uuid: UUID, msg: String)
    case class OpenConnection(actor: ActorRef, uuid: UUID)
    case class CloseConnection(uuid: UUID)
  }

  val chatRef = system.actorOf(Props[ChatRef])

  def websocketFlow: Flow[Message, Message, Any] =
    Flow[Message]
      .mapAsync(1) {
        case TextMessage.Strict(s) => Future.successful(s)
        case TextMessage.Streamed(s) => s.runFold("")(_ + _)
        case b: BinaryMessage => throw new Exception("Binary message cannot be handled")
      }.via(chatActorFlow(UUID.randomUUID()))
      .map(TextMessage(_))

  def chatActorFlow(connectionId: UUID) : Flow[String, String, Any] = {

    val sink = Flow[String]
      .map(msg => Protocol.SignedMessage(connectionId, msg))
      .to(Sink.actorRef(chatRef, Protocol.CloseConnection(connectionId)))

    val source = Source.actorRef(16, OverflowStrategy.fail)
      .mapMaterializedValue {
        actor : ActorRef => {
          chatRef ! Protocol.OpenConnection(actor, connectionId)
        }
      }

    Flow.fromSinkAndSource(sink, source)
  }

  Http().bindAndHandle(route, "0.0.0.0", 8080)
    .map(_ => println(s"Started server..."))

}


text:
Q: Evento teclado não funciona Jquery Gostaria de saber porque este evento não funciona com algumas teclas. A tecla que desejo é a seta para baixo (40), mas esta não funciona. Já as teclas Enter (13) e as letras e números funcionam normalmente. Já removi todo o código Jquery, e nada.
$('input[name=buscar]').keypress(function(e) {
    console.log(e.which);
    if(e.which == 40) {
        alert('You pressed enter!');
    }
});

A: Você deve utilizar o evento keydown neste caso, porque o evento keypress não será disparado por teclas que não são "imprimíveis", como as setas do teclado, por exemplo.

The keypress event is sent to an element when the browser registers
  keyboard input. This is similar to the keydown event, except that
  modifier and non-printing keys such as Shift, Esc, and delete trigger
keydown events but not keypress events. Other differences between the
  two events may arise depending on platform and browser.

Notas

*

*O evento keydown pode ser utilizado para capturar as teclas Shift,
ESC e Delete

*O evento keypress na verdade pode capturar as setas do teclado em alguns browsers, mas o keydown é mais confiável para este cenário, conforme indica a própria documentação

*Você deve utilizar as propriedades .ctrlKey , .altKey e
.shiftKey do objeto event para verificar se as teclas ctrl, alt
e shift foram disparadas

Código funcionando com keydown

$('input[name=buscar]').keydown(function(e) {
    console.log(e.which);
    if(e.which == 40) {
        alert('You pressed enter!');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" name="buscar" />

Fonte:
https://stackoverflow.com/questions/19347269/jquery-keypress-arrow-keys
https://api.jquery.com/keypress/


text:
Q: Filter products by options I have following database structure to store product options.

Now i have problem to filter out products that match only given options. First i did WHERE option_id IN (array of options), but that would give me products that match any of the options and that is not solution. User wants to filter out only products with given material, color, and size for instance. And if i do WHERE option_id = 4 AND option_id = 6 for instance i get nothing.
Here is my query:
SELECT DISTINCT p.id AS id,
                ...
FROM products p
LEFT JOIN product_categories pc ON p.id = pc.product_id
LEFT JOIN product_images pi ON p.id = pi.product_id
LEFT JOIN product_options po ON p.id = po.product_id
WHERE p.product_active = 1
  AND po.option_id = 1 // only to get the idea
GROUP BY id
ORDER BY id DESC
LIMIT 0,
      12

Just to mention it is PHP application , where user select options from select element with or without multiple attribute.
How to acomplish this?

A: You can use having:
SELECT p.id AS id,  ...
FROM products p JOIN
     product_categories pc
     ON p.id = pc.product_id LEFT JOIN
     product_images pi
     ON p.id = pi.product_id JOIN
     product_options po
     ON p.id = po.product_id
WHERE p.product_active = 1 AND
      po.option_id IN (4, 6)
GROUP BY p.id
HAVING COUNT(DISTINCT po.option_id) = 2
ORDER BY p.id DESC
LIMIT 0, 12;

The HAVING clause is specifying that a given id has two matching options.  Because of the WHERE clause, these are the only two options that you care about.
I didn't change your approach (you didn't supply the complete query), but you are doing joins along different dimensions -- categories, images, and options.  This creates a Cartesian product for each product, and that is often not the best approach to such a query.

A: There is no need for LEFT JOIN in the solution.
SELECT DISTINCT p.id AS id
FROM products p
JOIN product_options po ON p.id = po.product_id
WHERE p.product_active = 1
      AND po.option_id IN (1, 2, 3)
GROUP BY p.id
HAVING COUNT(po.option_id) = 3

My solution keep only tables necessary to find the products with specified options.
In the case you want products having exactly this options and no others you can use NOT EXISTS:
SELECT DISTINCT p.id AS id
FROM products p
JOIN product_options po ON p.id = po.product_id
WHERE p.product_active = 1 AND
      po.option_id IN (1, 2, 3) and
      NOT EXISTS (
        SELECT 1
        FROM product_options po2
        WHERE p.id = po2.product_id and po2.option_id NOT IN (1, 2, 3)
      )
GROUP BY p.id
HAVING COUNT(po.option_id) = 3

If you want to select products accoding to the other conditions (like product categories and so on) then use IN in the WHERE clause. This approach avoids generating duplicate po.option_id and the outer query will still work correctly even without DISTINCT in COUNT.
SELECT DISTINCT p.id AS id
FROM products p
JOIN product_options po ON p.id = po.product_id
WHERE p.product_active = 1 AND
      po.option_id IN (1, 2, 3) AND
      -- use the following IN predicate to select products with specific features without introducing duplicates in your query
      p.id IN (
         select product_id FROM product_categories WHERE <your_condition>
      )
GROUP BY p.id
HAVING COUNT(po.option_id) = 3

A: You select products with image lists. Something like:
select products.*, group_concat(product_images.id)

Additionally there may be options the product must all meet. This is criteria that belongs in the WHERE clause.
select
  p.*,
  (select group_concat(image) from product_images i where i.product_id = p.id) as images
from products p
where product_active = 1
and id in
(
  select product_id
  from product_options
  where option_id in (1,3,55,97)
  group by product_id
  having count(*) = 4 -- four options in this example
);

A: Thanks guys, i've managed to return exactly what i wanted.
Now i just have problem with pagination query for the filtered products.
Final search query:
SELECT DISTINCT p.id AS id,
                main_price,
                promotion_price,
                NEW,
                sale,
                recommended,
                COUNT(pi.filename) AS image_count,
                GROUP_CONCAT(DISTINCT pi.filename
                             ORDER BY pi.main_image DESC, pi.id ASC) AS images,
                name_sr,
                uri_sr,
                description_sr
FROM products p
LEFT JOIN product_categories pc ON p.id = pc.product_id
LEFT JOIN product_images pi ON p.id = pi.product_id
LEFT JOIN product_options po ON p.id = po.product_id
WHERE p.product_active = 1
  AND po.option_id IN(1)
  AND p.main_price BETWEEN 5250.00 AND 14000.00
GROUP BY id
HAVING COUNT(DISTINCT po.option_id) = 1
ORDER BY id DESC
LIMIT 0,
      12

Pagination query is something like this i modified it accorgin to new filter query:
SELECT COUNT(DISTINCT p.id) AS number
FROM products p
LEFT JOIN product_categories pc ON p.id = pc.product_id
LEFT JOIN product_images pi ON p.id = pi.product_id
LEFT JOIN product_options po ON p.id = po.product_id
WHERE p.product_active = 1
  AND po.option_id IN(1)
  AND p.main_price BETWEEN 5250.00 AND 14000.00
GROUP BY(p.id)
HAVING COUNT(DISTINCT po.option_id) = 1

If i leave out DISTINCT in SELECT COUNT i don't get filtered pagination, if i set DISTINCT i get number of rows that corespond to pagination. I suppose i could add another count(*) to all of this with subquery, but not sure if that is way to go and if there is more efficient and elegant way to do this.


text:
Q: Facebook Graph API: get all public photos by a specific location I don't think it's possible but maybe I'm missing something.
I would like to get all public photos attached to a specific location.
I tried:

*

*graph.facebook.com/place/tagged/. This doesn't seem to return recent results.

*graph.facebook.com/search?type=location&center=coordinates&distance=200. This only returns results related to a user (and users friends).

Any ideas on this?

A: I don't think this is possible.
if you just need photos from a specific place I would use instagram instead.

A: Facebook will never be so generous to give all public images to a query. That is like Terabytes of data which can be accessed by anyone with a line of code.
What you can do is get the images of the user and users friends. If its a public app, the user base should grow and you get exposure to more images.
Hope that helps.


text:
Q: Random "Printer selected is not valid" errors on Win2K8R2 I recently changed the printing code for automated printing to a TPrinter based solution. (The old solution, writing text directly to the printer network device worked without errors for many years.)
The application is written in Delphi 2009 Enterprise and runs continuously in a user session (not as a service). In regular intervals, the application scans a database for new documents, creates the text to be printed, and sends it to a printer.
Before printing, the code sets the printer index:
  PrinterToUse := Printer.Printers.IndexOf(MyPrinterName);

  if PrinterToUse > -1 then
  begin
    Printer.PrinterIndex := PrinterToUse;
  end
  else
  begin
    Assert(False, Format('Printer %s not found', [MyPrinterName]));
  end;

Where MyPrinterName could be for example \\PRINTSERVER\PR001. For my test phase, I use one locally installed printer with the new printing method, so the printer name is always the same.
In random intervals, printing fails with the EPrinter exception 'Printer selected is not valid'.
If this exception occurs, printing of the document fails - I added a workaround which uses the 'legacy' print method when this happens.
I suspect that there could be bugs in the VCL printers unit. In Quality Central I found only one related entry - http://qc.embarcadero.com/wc/qcmain.aspx?d=127390. I could try a newer Delphi version, if the problem remains it could be a printer driver issue. Updating printer drivers is also an option, which I have to try.
I will also improve error handling, and re-try printing one or two times when the error occurs.
Are there other experiences with this random error and has there been a solution?


text:
Q: django: sqlite3.OperationalError: no such table i don't now why, but from one day to another y started to have problems when i tried to run the tests.
I'm using django 1.1 (customer requirements) and when i running test whith:
python manage.py test --setting=settingsTest

it throw:
Traceback (most recent call last):
  File "manage.py", line 11, in <module>
    execute_manager(settings)
  File "/usr/lib/pymodules/python2.6/django/core/management/__init__.py", line 362, in execute_manager
    ...
  File "/usr/lib/pymodules/python2.6/django/db/backends/sqlite3/base.py", line 193, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: programas_act_actividadesprograma

but i have in settingsTest.py
INSTALLED_APPS = (
    'django.contrib.auth',
    ...

    'site.programas_act',
    ...
)

and in /var/www/site/programas_act/models.py
class ActividadesPrograma(models.Model):
    ...

I removed the file named in settingsTest.DATABASE_NAME and run:
python manage.py syncdb --setting=settingsTest

but still failing.
If i run in django shell_plus:
import settings
print settings.INSTALLED_APPS
for app in settings.INSTALLED_APPS:
    print app

I can see the app, but when i run:
from django.db import connection
cursor = connection.cursor()
qry="""SELECT name FROM sqlite_master
WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%'
UNION ALL
SELECT name FROM sqlite_temp_master
WHERE type IN ('table','view')
ORDER BY 1"""
cursor.execute(qry)
results = cursor.fetchall()
for tablename in results:
    print tablename

I can't found that tablename.
Anyone can help me?
Thanks

A: I had this problem, too. Turned out that I had to add a TEST_NAME property in the settings.py file to identify the test database properly. It solved the problem for me:
if 'test' in sys.argv:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(os.path.dirname(__file__), 'test.db'),
            'TEST_NAME': os.path.join(os.path.dirname(__file__), 'test.db'),
        }
    }

A: Are these Selenium tests, by any chance? This page says you need to define a TEST_NAME for your database, because for some reason the in-memory database is quite broken.

A: Personally, I'd neglected to run makemigrations before running my tests. The docs say migrate is automatically run for you on the test database, but you need to have run makemigrations to reflect the latest changes.

A: I think 'manage.py test' starts with empty database, so there's no way how 'syncdb' can help you.
Also I'm not sure if it's typo just in your question, but settings parameter is called
--settings

and not:
--setting

btw. if you're importings settings in code, use import this way:
from django.conf import settings


text:
Q: How to sort a numeric set of strings that are added to a combobox? C# I want to display in ascendent order a list of string  (numbers) that is added to a combobox. The project is in .NET 4.7.2
I have a string list of numbers such as:
{"3.453","1.123","2.024","1.567"}
and I would like that when these are displayed in my combobox they appear in order :
{,"1.123","1.567","2.024","3.453"}
The values come from reading multiple XML files and when the name == CardID is found it is added to the combobox "cb_card" items.
...
 if (name == "CardID")
                {
                    if (!mainWindow.cb_card.Items.Contains(value))
                    {
                        mainWindow.cb_card.Items.Add(value);
                    }
                }
...

I have tried to:

*

*Set the Combobox property Sorted = "true"  but an error appears:

XLS0413 The property 'Sorted' was not found in type 'ComboBox'.

*I tried to add the values to a list, then sort the list and finally add them to the combobox. I edited the code shown above:

...
List<string> sortedCardId = new List<string>();
 if (name == "CardID")
                {
                    if (!mainWindow.cb_card.Items.Contains(value))
                    {
                      sortedCardId.Add();
                    }
                }

sortedCardId.Sort();
foreach (string ID in sortedCardId)
{
    mainWindow.cb_card.Items.Add(ID);
}
...

but the  order stayed the same as when it is nor ordered.
I tried some variants of this last code, by converting the string list in doubled, sort it and reconvert it ot string, but I got to many errors qhich I couldn't debugg with my current knowledge.

*I tried to add the values to an array instad of a list, sort the array and add the values, but then the combobox appeared empty.

thanks a lot for your time and help in advance .

A: You can use List.Sort for this. If you are sure that the list contains only numeric values that can be parsed as a decimal (or double, ...), you can use a custom sort comparison that converts the strings to a decimal before comparing them:
var lst = new List<string>() {"3.453","1.123","2.024","1.567"};
lst.Sort((string a, string b) => (int)(decimal.Parse(a) - decimal.Parse(b)));
// This writes the list content as "1.123, 2.024, 1.567, 3.453"
Console.WriteLine(string.Join(", ", lst));

When comparing two items, the comparison returns

*

*less than 0: a is smaller than b

*0: a == b

*greater than 0: a is bigger than b

This is why subtracting b from a leads to a correct result of the comparison.


text:
Q: How to make an object with the same behaviour than open() before with and for statement I would like to create a class in Python that receive a filename, and return an object that can be handled by a context manager and iterable by a for-loop.
Basicly, the file will be parsed line by line (iterable). The class will split each line into a defined pattern and will return at each step of iteration a tuple of values.
I know that I need to implement __iter__, __next__ methods to make it iterable but I do not clearly understand how to proceed. The file is one of my class attribute, and I want the iterator to yield parsed line at each iteration.
I also know that I need to implement __enter__ and __exit__ methods, but this also is a little bit fuzzy to me.
class myfile:
    def __init__(self,file,**kwargs):
        self._file = open(file,'r')

    def __del__(self):
        self._file.close()

    def __enter__(self):
        # Not sure what am I supposed to return here

    def __exit__(self):
        self._file.close()

    def __iter__(self):
        # What iterator must be returned

    def __next__(self):
        return parseLine(x)

    def parseLine(self,line):
        #Stuff:
        return *values

I am not looking for an out-of-the box code, rather I would like to understand what each of those magic methods exactly needs to properly works in order to get the desired behaviour.
Update:
I finally resolved to do it in the following way:
class myfile:
    def __init__(self,file,**kwargs):
        self._file = open(file,'r')

    def __del__(self):
        self._file.close()

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self._file.close()

    def __iter__(self):
        for fline in self._file:
            yield self.parseLine(fline)

    def parseLine(self,line):
        # Stuff
        return *values

It seems to have the behaviour I am looking for. It works when I perform:
with myfile(r'x.txt') as pf:
    for i in pf:
        print(i)

Is this a good way to achieve it? Is it pythonic enough?

A: Just return self in both cases.
Your class is itself the iterator (since you are providing a __next__ method), and if you don't have a special value for __enter__ to return you generally just return self.
In fact, that's exactly what a file object does for both cases:
>>> fobj = open('/dev/null')
>>> fobj.__enter__() is fobj
True
>>> fobj.__iter__() is fobj
True

For __iter__ you'd return a different object if you wanted to support independent iteration over the object; that new object would then return self for __iter__ and provide the __next__ method rather than this class.
For __enter__ you'd return whatever was convenient for the user to bind to in a with statement. For example, some database connection objects return a new cursor object, so that you can do:
with conn as cursor:
    # handle a transaction, using the already produced cursor

Note that your updated version returns a generator from __iter__, which is a new iterator each time you call iter(myfile('...')). These iterators are not really independent as iter(fileobj) will always return the file object itself, so iterating over one generator will affect the other generators as the file position advances.
Moreover, since file objects are their own iterator, you can use the next() function directly on a file object, but you cannot do the same on your object.
A better solution is to stick to returning self and make your __next__ method do the parsing:
def __iter__(self):
    return self

def __next__(self):
    return self.parseLine(next(self._file))


text:
Q: Does the "Lockdown Mode" only protect Apple apps? If you mainly use Open Source alternatives, does this feature offer nothing? I enabled Lockdown Mode today. The advertising sounds very good:

What is Lockdown Mode?
Lockdown Mode is an optional, extreme protection that's designed for
the very few individuals who, because of who they are or what they do,
might be personally targeted by some of the most sophisticated digital
threats. Most people are never targeted by attacks of this nature.

Then I took a closer look at the KB article and I don't use these services at all, but Open Source alternatives.
This mode does not bring me anything? I use Lockdown Mode on iOS and macOS. Is there any hidden benefit?

A: Yes, some protections only apply to the services listed. There are some that apply to your computer overall, though.
Additionally, even if you don't use the services, protections against incoming data are still relevant.


text:
Q: MediaWiki - How to do a hard redirect? I need to redirect to another article, as soon as i get to a page. In other words: the URL needs to change to the original article. How do i do that?
www.myWiki.org/RD

should e.g. jump to
www.myWiki.org/redirect

As soon as the user gets there.

A: On the Page [[RD]] write this:
#REDIRECT [[redirect]]

And than www.myWiki.org/RD gets hard redirected to www.myWiki.org/redirect.
This works on current Mediawiki versions, in older versions you will get a soft redirect.
More on mediawiki.org Help:Redirects


text:
Q: Can't get the selected value of a dropdown in php The dropdown in question is  called subCategory ,
it's contents are populated by selecting another dropdown category that its onchange event is triggering an ajax request.
The problem is that even though that the contents of subcategory are populated (visible) as expected and I can see them and select them in the subcategory dropdown, when I perform the php post I can only get the value the initial option <option value="subCategory1">Select a subcategory</option> no matter if I select any other elements.
Maybe the dom doesn't refresh but I am not sure..
PHP print_r of $_REQUEST straight after submit
Array ( [act] => additem  [category] => 200381 [subCategory] => subCategory )

HTML (edited)
<form id="additemform" action="add-item.php?act=additem" method="post" enctype='multipart/form-data'>

        <select id="category" class="category"  name="category">
            <option value="category1">Select a category</option>
            {html_options values=$cat_id_array  options=$cat_names_array selected=$smarty.session.additem_category}
        </select>

        <select id="subCategory"  class="subCategory" name="subCategory">
            <option value="subCategory1">Select a subcategory</option>
                {html_options  options=$smarty.session.subcategories selected=$smarty.session.additem_subcategory}
        </select>

        <input id="submit-addItem" type="button" value="Add my item" />

</form>

PAGE SOURCE:

 <select id="category" class="category"  name="category">
    <option value="category1">Select a category</option>
    <option value="200381" selected="selected">Antiques</option>
    <option value="200841" >Other cat</option>
</select>

<select id="subCategory"  class="subCategory" name="subCategory">
    <option value="subCategory1">Select a subcategory</option>
    <option value="23430118">Digital Art</option>
    <option value="6643435">Photographic Images</option>
</select>

JQUERY
$(function () {
    //$("#subCategory").selectbox();
    $("#section-category #category").selectbox({
    onChange: function () {
        var id=$(this).val();
        var dataString = 'id='+ id;

        $.ajax
        ({
        type: "POST",
        url: "findsub.php",
        data: dataString,
        cache: false,
        success: function(html)
        {
            //$("#subCategory").selectbox("detach")
            $("#subCategory").html(html);
        // $("#section-category #subCategory").selectbox();
        }
    });

},
effect: "slide"
});

$('.subCategory').change(function() {
//NOTE I CAN SEE THE SELECTED VALUE OF THE SUBCATEGORY NORMALLY IN THIS ALERT
    alert($(this).serialize());
return false;
});

A: The reason that this was not working is that I had another select box (further down)  with the same name and first option as the subcategory, the PHP was taking this value .
This now works,thanks


text:
Q: Question about derivative I need to check whether I've done it correctly

*

*To find whether a point is maximum of function $f(x)$, we have to checked whether $f''(x)>0, f''(x)=0$ or $f''(x)<0?$

*To find the inflection point of the function, we have to find, $f''(x)=0, f'(x)=0,$ $f(x)=0.$

*When choose the value of $\sqrt{(64,3)},$ $X_o$ has the value: $64, 0,3$ or $X_o>64.$
My answers are the following.
$1. f''(x)<0$
$2. f''(x)=0$
$3. X_o = 64.$

A: Your first two answers are correct.
If you mean by $\sqrt{(64, 3)}$ that you need to find the value of $x_0$ in order to determine the distance of the point $(64, 3)$ from the origin, then you'd want $x_0 = 0$, the $x$-coordinate of the origin:
Distance = $\sqrt{(64 - 0)^2 + (3 - 0)^2}$.
But it will work equally well if we reverse the positions:
Distance = $\sqrt{(0 - 64)^2 + (0 - 3)^2}$. So $x_0 = 64$ works just as well.
But the value of the distance between $(64, 3)$ and $(0, 0)$ is $\sqrt{73}$.
So the answer for $(3)$ depends on what is meant by $x_0$.


text:
Q: Why does my useState set function not set the correct value? I have a react component that gets data from an API end point so that it can render some HTML.
I know that the call to the API works becuase I can out put the response in console.log(). However when I call the set function defined in the Use State so that I can set the state object when I console.log() that value it is empty.
This is my first react project so I may be missing something every fundamental, can only exaplain whats going on here?
This is the code so far:
function RenderCmsComponents() {
    const location = useLocation();

    const [componentItems, setCmsComponents] = useState([]);

    const getComponents = async () => {
        const componentList = await API.fetchPageComponents(location.pathname);
        setCmsComponents(componentList.CmsComponents);

        console.log(componentList.CmsComponents); //Works
        console.log(componentItems); // this is Empty, why?
    };

    useEffect(() => {
        getComponents();
    }, []);

    return (
        <div>
            <p> Render CMS Components for `{location.pathname}`</p>
        </div>
    );
}
export default RenderCmsComponents;


text:
Q: 1960's horror film with tentacled slug-like creatures I vaguely recall a scary movie that I watched, as a kid, approx around 1970.
In the movie there were these giant (maybe 1 meter long) slug-like creatures, complete with a tentacle to better terrorize folks.
The only memorable scene is when two people were in a car and PLOP! one of the creatures landed on their windshield.
Any ideas what this movie could be?

A: Whilst it sounds like a classic, I don't remember windshield scene but your description of the creatures sounds familiar. Technically, they're brains and spines with added tentacles but I can see a kid in the 70's seeing them as slug-like.
The wonderful, brain sucking creatures from the 1958 classic "Fiend Without a Face"

A: Are you referring to The 1988's remake of The Blob?
I remembered there's a car scene where a couple gets eaten by a creature with tentacles in that movie. I always thought that movie is creepy.

A: Island of Terror. 1966. Peter Cushing.

An isolated remote island community is threatened by an attack by tentacled silicates which liquefy and digest bone and tissue.

Trailer:


text:
Q: C# Session Variable works only in method I am creating Session Variable in my ActionResult method and it works fine within this method but whenever I make a call from other method in the same Controller I get Null Reference. I read a lot of questions here and nothing really helped me. No idea what could cause this issue. If You would have any ideas on that I would be really thankful for answer.
Might help:

*

*The retrieve is happening on Button Click from user. But I don't think it changes anything.

*It also won't work in another method that is not called on button click.

*Method in which I retrieve it is a void method.

*It is not a timeout issue for sure. I added timeout before and did not help.

In this specific example I am using List object, but it goes the same way with any other object I will assign to Session.
Declaration:
  List<Thread> tList = Session["tList"] as List<Thread>;
        if (tList == null)
        {
            tList = new List<Thread>();
            Session["tList"] = tList;
        }

Fail Retrive in other method:
 var t = new Thread(() =>
        {
            foreach (var item in Session["tList"] as List<Thread>)
            {
                try
                {
                    item.Abort();
                }
                catch (Exception)
                {
                }
            }
        });

web.config(The whole system.web section since maye there is something else blocking it. No idea):
<authentication mode="Forms">
  <forms cookieless="UseCookies" loginUrl="~/user/login" slidingExpiration="true"></forms>
</authentication>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<httpModules></httpModules>
<sessionState cookieless="true" regenerateExpiredSessionId="true" />


text:
Q: How to use scala case classes when delegation is needed Let's assume in our application we want to model cars. We also want to model a car repository where we store some registered cars. How should that be modeled in scala?
Here comes my approach: First, I create a case class PlainCar. This is just a car how it exists in real world, with nothing special in it. Next I create a CarRepository. I also create a RegisteredCar. The CarRepository can now store PlainCars and return them as RegisteredCars. Both PlainCar and RegisteredCar extend the trait Car which provides all the comon methods like drive. RegisteredCar however is special - it owns an instance of PlainCar but also adds a method registrationNumber which returns the registration number; all other methods are just delegated to the PlainCar instance.
I feel however, that there are some flaws of this design. One is that I have to change RegisteredCar when I add a method/property to PlainCar which I think should not have to be done.
My question is therefore, can this be modeled better and if so, how? Are there other drawbacks that I am missing?
Some advice on naming conventions would also be appreciated because PlainCar sounds quite awkward to me.

A: It sounds as if registration is a state which only has meaning in the context of a repository.  You have described two states, (registered with the repository, not registered with the repository).  It sounds to me as if what you need is a car container (wrapper if you like).  Think of it as a collection which can hold one car, in the same way that Option[Car] or Either[Car, Motorbike] can only hold one object.
So create a RepositoryItem sealed base trait (or sealed abstract class) and create case class instances (which extend RepositoryItem) for each state.  The Registered variant would have a registration number.  Make your Repository a container of RepositoryItems.  It should not be part of the same set of case classes.
Advantages of this approach include

*

*You can make it generic (RepositoryItem[A] or RepositoryItem[+A] rather than RepositoryItem[Car]).  This means it could become a repository of other things (or could easily expand to hold motorbikes as well as cars).

*Complete separation of concerns between repository implementation and car implementation.  One can change (or add new features) without affecting the other.

*You can create new subclasses of Car as often as you like.  Even if you create Repository[Car] from the start, rather than making it generic, it will be able to hold Car subclasses with no modification.

Have a look at the way Option and Either are designed.  You might want to implement at least map, so that you can manipulate a car (or replace it with a bike) without having to take it out of the repository slot.
EDIT:
To explain a point which may have created confusion, judging by your comment...
The Option and Either types have a map function (as does List and any other monad).  The map function allows you to pass in a function which can manipulate the object contained.  You get back a transformed object still wrapped in the Option.
scala> val o = Some(3)
o: Some[Int] = Some(3)

scala> o map (_ * 5)
res2: Option[Int] = Some(15)

No dependencies between Option and Int but because Option implements map you can manipulate the Int without removing it from Option wrapping.

A: I feel like I'm missing something, but I would just make your CarRepository a Map[RegistrationNumber, PlainCar] or something similar.  Usually with immutable objects, it's much easier to create this kind of association outside the original object.
My second choice would be RegisteredCar extends PlainCar, but I think this creates unnecessary coupling and copies.  Both of those options would allow you to just rename PlainCar to Car.


text:
Q: Java Concurrent - no speedUp gained LU algorithm - False sharing? I have a question for you about a concurrent software on java.
The main algorithm of my application have to factor an A matrix into LU matrices : A = LU. The decompose method pasted here, makes the Gauss-Jordan reduction. The software is designed to work on square matrix with the position A[0][0] != 0.
Unfortunately, for the correct working of the algorithm, I have to wait that every row actualizes the values.
I tried to make this algorithm parallel using a barrier (for wait the actualization of every row and increment the "rigaCorrente" value) but I don't gain a real speedUp even if in the parallel version my processors (2.4 GHz Core 2 Duo P8600) work at 80% of the total (instead of 40-50% of the serial one).
My fear is that I'm encountering a false sharing situation. Is the problem related to the false sharing or to other matters? I know that the JVM performs good optimizations but it still uses the half power of the processor. I don't think it's impossible improve the algorithm!
My serial code:
    public void decompose(){
    int n = A.length;
    for(int k=0; k<n-1;k++) {
        for(int i=k+1; i<n; i++) {
            A[i][k] = A[i][k]/A[k][k];
            for(int j=k+1; j<n; j++) {
                A[i][j] = A[i][j] - A[i][k] * A[k][j];
            }
        }
    }
    decomposed = true;
}

My parallel code:
    public class Manager {
private double [][] A;

private Semaphore main = new Semaphore(0);
private CyclicBarrier barriera;

private AtomicInteger index;
private int rigaCorrente = 0;
private boolean stop = false;

public Manager(final double A[][], final int numThr){
    this.A = A;
    this.index = new AtomicInteger(1);

    barriera = new CyclicBarrier(numThr, new Runnable(){

        @Override
        public void run() {

        rigaCorrente++;
        index = new AtomicInteger(rigaCorrente+1);

    if(rigaCorrente == A.length - 1){
            setStop(true);
            main.release();
        }
    }

    });
}

The thread class:
    public class Deco implements Runnable {

private Manager manager;

public Deco(Manager manager){
    this.manager = manager;
}

@Override
public void run() {
    double [][] A = manager.getA();

while(manager.getStop() == false){
    int i;
    while((i = (manager.getIndex().getAndIncrement())) < (A.length)){
    double pivot = A[i][manager.getRigaCorrente()]/A[manager.getRigaCorrente()]                        [manager.getRigaCorrente()];

        for(int k = manager.getRigaCorrente(); k<A.length; k++)
            A[i][k] = A[i][k] - (pivot*A[manager.getRigaCorrente()][k]);

        A[i][manager.getRigaCorrente()] = pivot;
 }

        manager.acquireBarriera();

    }// Stop

}

   }

Main for parallel code:
    package luConcurrent.test;
    import java.util.Arrays;
    import java.util.Scanner;

    import lu.DecompositionLU;
    import lu.IO;

    public class Starter {
private static IO io;
private static DecompositionLU dec;
public static void main(String[] args) throws Exception {
    io = new IO("//Users//black//Desktop//serie//2500.txt");
    int numThr = 2;

    double [][] A = io.readMatrixFromInputFile();
    double [] b = io.readArrayFromInputFile();
    double [] x;

    dec = new DecompositionLU(A);

    System.out.println("A.length: "+A.length);

    Manager manager = new Manager(A,numThr);
    Thread[] pool = new Thread[numThr];

    for(int i=0; i<pool.length; i++){
        pool[i] = new Thread(new Deco(manager));
    }

    long inizio = System.nanoTime();

    for(int i = 0; i<pool.length; i++){
        pool[i].start();
    }

    manager.getMain().acquire();

    dec.ProgresiveSustitution(b);
    x = dec.RegresiveSustitution(b);

    long fine = System.nanoTime()-inizio;

    System.out.println("Solution is: "+Arrays.toString(x));
    Scanner sc = new Scanner(System.in);
    sc.nextLine();
    System.out.println("Tempo: "+fine);
    sc.close();

}
    }

Results:
    1000x1000 Serial: 1154679000 nanoSec
    1000x1000 Parallel 2 Threads: 1135663000 nanoSec

    1750x1750 Serial: 7502559000 nanoSec
    1750x1750 Parallel 2 Threads: 6667129000 nanoSec

    4000x4000 Serial: 89851311000 nanoSec
    4000x4000 Parallel 2 Threads: 84348616000 nanoSec

A: I wouldn't jump to the conclusion that false sharing is occurring. The parallel version of the algorithm adds a bunch of overhead that is probably responsible for reducing its performance below what you're expecting.
The serial version simply has three nested loops: an outer loop over k, a middle loop over i, and an inner loop over j. All it does is array access and arithmetic, so this should be quite fast.
The parallel version runs its outer loop over rigaCorrente (current row, if I'm not mistaken) using a CyclicBarrier at each iteration. This adds overhead. A cyclic barrier causes early-arriving threads to wait until the last has arrived. Well, you have only two threads, so the one that arrives first must wait for the second. That's some dead time there. Even if the threads finish at about the same time, there is overhead performing the barrier synchronization. And then one thread must wait while the other runs the barrier action.
The middle loop is over index which is an AtomicInteger fetched by the getIndex method call. The method call adds overhead, and getAndIncrement adds some contention between the threads.
The inner loop (confusingly over k instead of j as in the serial version) has a method call to getRigaCorrente inside of it. Sometimes -- but only sometimes -- the JVM can inline method calls. I don't see the implementation of getRigaCorrente here, but since rigaCorrente is a private instance variable of manager that isn't volatile, and it's read and written by multiple threads, perhaps this method is synchronized. That would add even more overhead.
The problem here is that the threads have to interact with shared state quite a bit during the run. This adds overhead and contention. I'd suggest trying to find a way to partition the work among threads in advance, then tell each thread what work it needs to do, and then have them all run independently.

A: COMPLETE REWRITE OF ANSWER:
Here is my solution using the Fork/Join framework:
public void decompose()
{
    final Semaphore semaphore = new Semaphore(0);

    class Decompose extends RecursiveAction {
        private final int k;

        Decompose(int k) {
            this.k = k;
        }

        protected void compute() {
            final int n = A.length;
            for (int i = k + 1; i < n; i++) {
                A[i][k] = A[i][k] / A[k][k];
                for (int j = k + 1; j < n; j++) {
                    A[i][j] = A[i][j] - A[i][k] * A[k][j];
                }
            }

            semaphore.release();
        }
    };

    ForkJoinPool mainPool = new ForkJoinPool();
    for (int k = 0; k < A.length - 1; k++) {
        mainPool.execute(new Decompose(k));
    }
    semaphore.acquireUninterruptibly(A.length - 1);
}

In my case, these are the number I got for a 1000x1000 matrix:
1000x1000 Serial   : 234351000 nanoSec
1000x1000 Fork/Join:  61580000 nanoSec

This is on a iMac i7 2600.

A: There are several things wrong with your time measurement. First of all you include the start() call in your measurement, which would be ok if you want to know the time if you do not reuse those threads, but then you must include the creation overhead as well. If you plan on reusing the threads, you must leave the start call outside of the time measurement, as it is much more than a simple boolean set to true.
The other issue is that the serial version is much easier to optimize for the JVM, so what you measure here might already be the optimized version vs the probably not-yet-optimized threaded version. If you want to make sure that you get the optimized version in both cases, you need to warm-up the JVM first by doing several dry runs.
Then the manager.getRigaCorrente() call looks very suspicious. In your Manager class this is not defined, but an int with the same name is present. Whatever you get from there repeatedly will most likely either violate threading rules or - if you properly synchronized it - will slow things down tremendously, so there seems to be an algorithmic problem as well. Hard to tell if you do not give us the real code used.


text:
Q: How to use Scala UDF in PySpark? I want to be able to use a Scala function as a UDF in PySpark
package com.test

object ScalaPySparkUDFs extends Serializable {
    def testFunction1(x: Int): Int = { x * 2 }
    def testUDFFunction1 = udf { x: Int => testFunction1(x) }
}

I can access testFunction1 in PySpark and have it return values:
functions = sc._jvm.com.test.ScalaPySparkUDFs
functions.testFunction1(10)

What I want to be able to do is use this function as a UDF, ideally in a withColumn call:
row = Row("Value")
numbers = sc.parallelize([1,2,3,4]).map(row).toDF()
numbers.withColumn("Result", testUDFFunction1(numbers['Value']))

I think a promising approach is as found here:
Spark: How to map Python with Scala or Java User Defined Functions?
However, when making the changes to code found there to use testUDFFunction1 instead:
def udf_test(col):
    sc = SparkContext._active_spark_context
    _f = sc._jvm.com.test.ScalaPySparkUDFs.testUDFFunction1.apply
    return Column(_f(_to_seq(sc, [col], _to_java_column)))

I get:
 AttributeError: 'JavaMember' object has no attribute 'apply'

I don't understand this because I believe testUDFFunction1 does have an apply method?
I do not want to use expressions of the type found here:
Register UDF to SqlContext from Scala to use in PySpark
Any suggestions as to how to make this work would be appreciated!

A: Agree with @user6910411, you have to call apply method directly on the function.
So, your code will be.
UDF in Scala:
import org.apache.spark.sql.expressions.UserDefinedFunction
import org.apache.spark.sql.functions._

object ScalaPySparkUDFs {

    def testFunction1(x: Int): Int = { x * 2 }

    def getFun(): UserDefinedFunction = udf(testFunction1 _ )
}

PySpark code:
def test_udf(col):
    sc = spark.sparkContext
    _test_udf = sc._jvm.com.test.ScalaPySparkUDFs.getFun()
    return Column(_test_udf.apply(_to_seq(sc, [col], _to_java_column)))

row = Row("Value")
numbers = sc.parallelize([1,2,3,4]).map(row).toDF()
numbers.withColumn("Result", test_udf(numbers['Value']))

A: The question you've linked is using a Scala object. Scala object is a singleton and you can use apply method directly.
Here you use a nullary function which returns an object of UserDefinedFunction  class co you have to call the function first:
_f = sc._jvm.com.test.ScalaPySparkUDFs.testUDFFunction1() # Note () at the end
Column(_f.apply(_to_seq(sc, [col], _to_java_column)))


text:
Q: Send Email with Attachement using SSRS Action Property For the customized reason, I developed a report that is reporting on the SharePoint document lists and so far it's all good.
By using Action property, I linked the original SharePoint path to SSRS and user can open the document using the link from the report very easily.
New Requirements
Business wants a link in the report to send the email. So that when the user clicks on that new link, the document should be emailed directly to the specified email address.
Is there a way to do such thing using action property in SSRS?
I'm using SSRS 2008R2

Note:
I want to explore my options is SSRS before going out of this domain.
Thanks in advance.

A: No, what you are asking about, or attempting to make happen with a Action property is not possible. Their best bet would be to run the report, export the report the Excel, or Word, and then email the report from within that application.
Action properties only allow for a few things to happen:

*

*Go to another report

*Go to a bookmark within the current report

*Go to a URL

The go to a URL can be a mailto: protocol, but all that would do is open the end users default email client; there would be no attachment, or report results in the email body.


text:
Q: Unable to connect my Android Phone to my laptop using as a hotspot I am using a 3G dongle. And I want to use internet on my Android phone.
See following screenshot, I press the button but it just give the message that connection established and after that, it came into its original state.
What network should I select in the combo?
How can I achieve this?

A: It seems you want to use the internet connection of your computer on android phone. Hotspot button actually does not create a hotspot in ubuntu instead creates an ad-hoc.
 First of all as we all know stock rom of android i.e. the one which comes with the phone does not support ad-hoc mode (surprisingly), and even ice-cream sandwich (android 4.0) won't support ad-hoc mode. So, we need to create an access point (hotspot) using Ubuntu to which any android phone can easily connect. In windows you can use connectify to do that and it works perfectly well but with Ubuntu you may have certain problems, depending on whether your wifi-card supports access point mode (master mode) or not. Now, even if your wifi-card supports access point mode, the next problem is whether the driver of your wifi-card supports AP mode or not, if it does then the problem is solved and if does not then you have three options:
1- Wait till the driver recieves an update for AP mode. (many wifi-card drivers are still in staging stage)
2- Buy a wifi-dongle and make sure it supports AP mode on ubuntu.
3- Use windows, where connectify will do the job for you.
If you are interested you can post the name of your wifi-card driver so that i can help you further. command: lshw -c network

A: Since you use ath9k driver, you will be pleased to know that supports all the modes. To create a hotspot follow the link:
How to stop Wireless AP Hosting using Network Manager on Ubuntu?


text:
Q: Django/Docker: web container not up-to-date code EDIT 22/05/2022
Docker version 20.10.14
docker-compose version 1.25.0
I delete again all containers/images and re-build using docker-compose -f docker-compose.preprod.yml build --force-rm --no-cache but I still observe the same issue: code in not up-to-date in web container

I use Django docker app and do not manage to apply code update to my web container.
I've tried to delete all containers (docker rm -f ID ; docker system prune) and images (docker rmi -f ID ; docker image prune) related to my app and re-build with docker-compose -f docker-comose.preprod.yml build
Then I run docker-compose -f docker-comose.preprod.yml up but for some reasons when I connect to my web running container (docker exec -it web sh) and read my updated files, I observe that update are not applied...
How should I do to make my update applied?
# Pull the official base image
FROM python:3.8.3-alpine

# Set a work directory
WORKDIR /usr/src/app

# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# install psycopg2 dependencies
RUN apk update && apk add postgresql-dev gcc g++ python3-dev musl-dev

RUN apk --update add libxml2-dev libxslt-dev libffi-dev musl-dev libgcc openssl-dev curl postgresql-client
RUN apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev nano
RUN pip3 install psycopg2 psycopg2-binary

# install xgettext for i18n
RUN apk add gettext

# Install dependencies
COPY requirements/ requirements/
RUN pip install --upgrade pip && pip install -r requirements/preprod.txt

# Copy the entrypoint.sh file
COPY entrypoint.preprod.sh .

# Copy the initdata sql file
COPY initdata.preprod.sql .

# Copy the project's files
COPY . .

RUN chmod +x entrypoint.preprod.sh

version: '3.7'

services:
    web:
        restart: always
        container_name: ecrf_web
        build:
            context: ./app
            dockerfile: Dockerfile.preprod
        command: gunicorn core.wsgi:application --bind 0.0.0.0:8000
        volumes:
            - app_volume:/usr/src/app
            - static_volume:/usr/src/app/static
            - media_volume:/usr/src/app/media
        expose:
            - 8000
        env_file:
            - ./.env.preprod
        entrypoint: [ "/usr/src/app/entrypoint.preprod.sh" ]
        depends_on:
            - redis
        healthcheck:
            test: [ "CMD", "curl", "-f", "http://localhost:8000/" ]
            interval: 30s
            timeout: 10s
            retries: 50

    redis:
        container_name: ecrf_redis
        image: "redis:alpine"

    celery:
        container_name: ecrf_celery
        build:
            context: ./app
            dockerfile: Dockerfile.preprod
        command: celery -A core worker -l info
        volumes:
            - app_volume:/usr/src/app
        env_file:
            - ./.env.preprod
        depends_on:
            - web
            - redis

    celery-beat:
        container_name: ecrf_celery-beat
        build:
            context: ./app
            dockerfile: Dockerfile.preprod
        command: celery -A core beat -l info
        volumes:
            - app_volume:/usr/src/app
        env_file:
            - ./.env.preprod
        depends_on:
            - web
            - redis

    nginx:
        container_name: ecrf_nginx
        build: ./nginx
        restart: always
        volumes:
            - static_volume:/usr/src/app/static
            - media_volume:/usr/src/app/media
        ports:
            - 1370:80
        depends_on:
            - web

volumes:
    static_volume:
    media_volume:
    app_volume:


text:
Q: Setting window.location in JavaScript hangs I have an ASP.NET MVC app. My app uses jQuery on the client side. The user can enter values into several fields and click "Refresh". The Refresh is behaving oddly.
When Refresh is clicked, I execute the following JavaScript:
function refresh() {
    var chosen = "(someField eq 'value')";
    try {
        if (chosen) {
            var url = 'http://localhost:8089/item&c=' + chosen;
            alert(url);
            window.location = url;
        } else {
            window.location = 'http://localhost:8089/item';
        }
        return false;
    } catch (ex1) {
        alert(ex1);
    }
}

The value for chosen is actually generated via a function. I've noticed when I use a certain type of control, the page hangs. Here is what is odd, I can see the request made in Fiddler. Yet, my breakpoint in my controller action is never hit. If I copy and paste the url from the alert call into the address bar, my breakpoint gets successfully hit. So, I'm totally confused.

*

*Due to the fact this involves a specific control, I at first assumed this was a JavaScript error. However, I do not see any JavaScript error in the console. I also checked to see if any exceptions were being swallowed and I did not see any.

*The fact I see the request in Fiddler, would imply that I'm getting to the web server. Yet, if I have a breakpoint on the very first line of the controller action, I would expected that to trip. It does not trip in the scenario where I use the control. It does trip if I do NOT use the control. The result in Fiddler sits at '-'. It never returns. Plus, I do not get an exception thrown in my ASP.NET view.
I'm totally stuck on this and looking for ideas of potential causes. Thank you.

A: This behavior is usually the result of a problem during model binding for the controller.
A quick step to try is making sure the query string values you are sending are properly encoded.
var chosen = "(someField eq 'value')";
chosen = encodeURIComponent(chosen);

Would eliminate any bad character problems that the model binder might be having.


text:
Q: CloudKit Dashboard index queryable, sortable and searchable I need to be able to search a field of type NSString in CloudKit records. I found a comment saying that there used to be a searchable index type for fields. Now there are only queryable and sortable. What do I set the index type for the field in order to be able to search for a specific string in a field in all the records?
Also, does one option include the other? I mean is one of the options inclusive of the other? For example, if I choose queryable, does that mean the field is also sortable, whereas when I choose sortable it only makes it sortable but not queryable? Or if I want to choose both, would I have to create separate indexes, one for queryable and one for sortable?

A: You can still set the index type to searchable, there are 3 types: Queryable, Sortable and Searchable.
One option does not include the other, so yes you will have to create separate indexes if you wish to have the field queryable and sortable.


text:
Q: How to temporary disable XSS Auditor in chrome v68 on Ubuntu I'm developing XSS vulnerable system with php in ubuntu 18.04 but i can not figure it out how to close XSS Auditor in Chrome v68 temporarily. Also i tried to do in Firefox but it response 404.

A: guys i don't change chrome settings but i add this script to my code and it works.
<?php header("X-XSS-Protection: 0; mode=block"); ?>

This code part helps to change HTTP Response header.


text:
Q: Python Check if item in list is free I've got an array, that contains 9 char variables. I print them in a row of 3 using for loop. I would like to check if 2 of 3 variables in a row are the same and create function that will change the third one to match the others.
I would like to do it both vertically and horizontally. Do i have to change my array into 2D array? It would made me to change nearly half of the code.Is there a chance that i wouldn't have to write the if statements manually like this:
if array[0] == array[1]:
    change the_third_var
elif array[1] == array[2]:
    change the_first_var
elif array[0] == array[2]:
    change the_sec_var

but it will check it automatically using for or any other loop?
Will the solution help me to simplify the code below (optional)?
def check_winner(pl_array, player_choice, computer_choice):
    vertical = [2, 5, 8]
    diagonal = [6, 7, 8]
    # checking vertical lines
    for each in vertical:
        if pl_array[each - 2] == pl_array[each - 1] == pl_array[each]:
            if pl_array[each] == player_choice or pl_array[each] == computer_choice:
                return True
    # checking diagonal lines
    for every in diagonal:
        if pl_array[every - 6] == pl_array[every - 3] == pl_array[every]:
            if pl_array[every] == player_choice or pl_array[every] == computer_choice:
                return True
    # across
    if pl_array[8] == pl_array[4] == pl_array[0]:
        if pl_array[8] == player_choice or pl_array[8] == computer_choice:
            return True
    elif pl_array[6] == pl_array[4] == pl_array[2]:
        if pl_array[6] == player_choice or pl_array[2] == computer_choice:
            return True
    else:
        return False

Any help appreciated.

A: Even though it's a little verbose I rather have the if/elif logic you posted than any other option. You can wrap it in a function and simply call it whenever you need which will reduce the amount of code.
That said, you can also do the following ugly thing:
for i in range(-1, 2):
    if arr[i-1] == arr[i]:
        arr[i+1] = arr[i]


text:
Q: how to exchange data between activity and layout xml in android I need to exchange data between activity and it's layout xml in Android. But I do not find a way to do this in Android. For example, views and controller in mvc pattern always has a way to exchange data between. So I am wondering is there any way to exchange data between them to should I refresh my mind and realize there is no such way?

A: use below code to get value from layout in your activity
 String value;
  EditText editText= (EditText) findViewById(R.id.editText);
 value=editText.getText();

A: code in xml example:
<ImageView
  android:id="@+id/image_view"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  />

in java class (like onCreate()):
ImageView image = (ImageView) findViewById(R.id.image_view);

Then you can do what you want with image

A: I believe you're unsure exactly what you're asking. If you want to exchange information, such as ID or text entered into a textfield then any good android tutorial should be-able to demonstrate this. Considering your last comment I think you're talking about GET and POST based technologies which can be done usingREST andSOAP, or both if you want.
This questions answer has a good implementation and definition of what both of these webservices are.
P.S. If this is what you're looking for then upvote that answer.

A: As some additional info, the "view" (XML Layout file) gets set by your activity initially on your activity's onCreate method. Right after you call it's parent method (super.onCreate()).
To maintain scope throughout the activity I tend to declare all the layout widgets that I need to the activity to interact with outside of any methods and within the class.
TextView textWelcomeMessage;

public void MyActivity(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // before calling setContentView() we have the option to change
    // window features ex requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_my_activity);

    // Now to set the textview
    textWelcomeMessage = (TextView) findViewById(R.id.textWelcomeMessage);

    // Set some data
    textWelcomeMessage.setText("Hello, welcome to my activity");
}

It's not exactly like traditional php style mvc since static typing changes thing up a bit and we have to worry about scope. But the core principles can still apply as far as data abstraction and separation go. Hope this helps =)


text:
Q: Ground planes on 2 layer PCB I know there are multiple questions about this topic, but I didn't found an exact answer to my question.
My situation: I'm having a 2 layer PCB. On the PCB there are multiple SMD components and traces both of them on the top and on the bottom side. All signals and power traces (+5V and +3V3) are already routed. Now my idea was to create a ground plane: one on the top and one on the bottom layer.

My questions:

*

*Is it a good idea to have a ground plane on both layers?

*Should the ground planes be connected with vias or is it enough that they are connected through the GND pads of my USB and Ethernet connector?

If anyone needs additional information, please write a comment and I will try to provide this information.

Edit: I want to add some future details about the PCB. The PCB has a size of about 60x60mm. The main components on the board are a microcontroller from Microchip (PIC32MZ) and a ethernet PHY from Texas Instruments (DP83848). Furthermore the board contains a USB-B and ethernet port. The 5V from the USB port is used as the power supply of the device.

A: Create a copper pour/fill on the top and bottom and stitch them with as many small vias as is reasonably possible. Try to place a GND stitch via next to any signal or power vias you are using to allow return current to flow to the opposite side. Also stitching the entire perimeter of the board while respecting the board houses copper to edge rule is often recommended. Some PCB software has the functionality to automatically fill your board with such stitching vias.