问:
"E: Invalid operation update" error while running shell scripts in WSL
I have a shell script called setup_wsl.sh which contains:

```<code>#!/bin/bash

echo "hai"
sudo apt-get update
sudo apt-get install \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg-agent \
    software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo apt-key fingerprint 0EBFCD88
sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io
</code>```

When i run the script as ./setup_wsl.sh in WSL ( installed distro is ubuntu 18.04), errors occur as:

```<code>hai
E: Invalid operation update
E: Unable to locate package
./setup_wsl.sh: 4: ./setup_wsl.sh: apt-transport-https: not found
./setup_wsl.sh: 5: ./setup_wsl.sh: ca-certificates: not found
curl: (3) Illegal characters found in URL
./setup_wsl.sh: 7: ./setup_wsl.sh: gnupg-agent: not found
: not found ./setup_wsl.sh: software-properties-common
: not found ./setup_wsl.sh:
</code>```

The first command of the script works fine as it gives output "hai".

Can someone help me to find why these errors occured?

答:
This is because of the carriage return in windows.
Switch to the LF carriage with a text editor and save the new one to run the script
or sed -i -e 's/\r$//' setup_wsl.sh</p>

Body:
I have a shell script called setup_wsl.sh which contains:

#!/bin/bash

echo "hai"
sudo apt-get update
sudo apt-get install \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg-agent \
    software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo apt-key fingerprint 0EBFCD88
sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io

When i run the script as ./setup_wsl.sh in WSL ( installed distro is ubuntu 18.04), errors occur as:

hai
E: Invalid operation update
E: Unable to locate package
./setup_wsl.sh: 4: ./setup_wsl.sh: apt-transport-https: not found
./setup_wsl.sh: 5: ./setup_wsl.sh: ca-certificates: not found
curl: (3) Illegal characters found in URL
./setup_wsl.sh: 7: ./setup_wsl.sh: gnupg-agent: not found
: not found ./setup_wsl.sh: software-properties-common
: not found ./setup_wsl.sh:

The first command of the script works fine as it gives output "hai".

Can someone help me to find why these errors occured?


来源: stackexchange

问:
TransactionRequiredException Executing an update/delete query
I am using hibernate JPA with spring and mongodb and I am running my application on Glassfish-4.0.

My service class is:

```<code>@Component
public class Test {
    @PersistenceContext
    EntityManager em;
    EntityManagerFactory emf;

    @Transactional
    public String persist(Details details) {
        details.getUsername();
        details.getPassword();

        Query query = em.createNativeQuery("db.details.find(username="+details.getUsername()+"&password="+details.getPassword());

        em.getTransaction().begin();
        em.persist(details);
        em.getTransaction().commit();
        em.flush();
        em.clear();
        em.close();
        query.executeUpdate();
        System.out.println("Sucessful!");
        return "persist";
    }
}
</code>```

And my spring-context.xml is :

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="com.javapapers.spring.mvc" />
    <context:annotation-config />
    <mvc:annotation-driven />
    <tx:annotation-driven transaction-manager="txManager" />
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="ogmTest"/>
    </bean>
    <bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager">
    </bean>
</beans>
</code>```

I am getting "TransactionRequiredException Executing an update/delete query"

How can this error be resolved?

答:
I was facing the same error inspite of adding @Transactional annotation at class level and importing org.springframework.transaction.annotation.Transactional.

Then I realized that since I was using hibernate query, I had imported javax.persistence.Query instead of import org.hibernate.query.Query.
Therefore adding import org.hibernate.query.Query solved the issue for me.

I hope this idea helps someone.

ContentLicense: CC BY-SA 4.0

Body:
I am using hibernate JPA with spring and mongodb and I am running my application on Glassfish-4.0.

My service class is:

@Component
public class Test {
    @PersistenceContext
    EntityManager em;
    EntityManagerFactory emf;

    @Transactional
    public String persist(Details details) {
        details.getUsername();
        details.getPassword();

        Query query = em.createNativeQuery("db.details.find(username="+details.getUsername()+"&password="+details.getPassword());

        em.getTransaction().begin();
        em.persist(details);
        em.getTransaction().commit();
        em.flush();
        em.clear();
        em.close();
        query.executeUpdate();
        System.out.println("Sucessful!");
        return "persist";
    }
}

And my spring-context.xml is :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="com.javapapers.spring.mvc" />
    <context:annotation-config />
    <mvc:annotation-driven />
    <tx:annotation-driven transaction-manager="txManager" />
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="ogmTest"/>
    </bean>
    <bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager">
    </bean>
</beans>

I am getting "TransactionRequiredException Executing an update/delete query"

How can this error be resolved?


问:
how to use cp-react-tree-table in my project?
New to typescript, try to follow the demo https://www.npmjs.com/package/cp-react-tree-table to use this control in my project, but get below information.

Try to search and seems it's related to module definition which confuse.

Hope someone can show me light.

```<code>import * as jQuery from 'jquery';
import TreeDataTable from 'cp-react-tree-table';
</code>```

'TreeDataTable' is declared but its value is never read.ts(6133)
Could not find a declaration file for module 'cp-react-tree-table'. 'path/node_modules/cp-react-tree-table/dist/index.js' implicitly has an 'any' type.

Try npm install @types/cp-react-tree-table if it exists or add a new declaration (.d.ts) file containing declare module 'cp-react-tree-table';ts(7016)
Could not find a declaration file for module 'cp-react-tree-table'. path/node_modules/cp-react-tree-table/dist/index.js' implicitly has an 'any' type.

Try npm install @types/cp-react-tree-table if it exists or add a new declaration (.d.ts) file containing declare module 'cp-react-tree-table';ts(7016)

Could not find a declaration file for module 'cp-react-tree-table'

答:
Your module doesn't have a type definition.
You should have install : @types/cp-react-tree-table but apparently it doesn't exist.

So you have to manualy create a file : "cp-react-tree-table.d.ts" containing the types.

You have examples of types definition here.

Body:
New to typescript, try to follow the demo https://www.npmjs.com/package/cp-react-tree-table to use this control in my project, but get below information.

Try to search and seems it's related to module definition which confuse.

Hope someone can show me light.

import * as jQuery from 'jquery';
import TreeDataTable from 'cp-react-tree-table';

'TreeDataTable' is declared but its value is never read.ts(6133)
Could not find a declaration file for module 'cp-react-tree-table'. 'path/node_modules/cp-react-tree-table/dist/index.js' implicitly has an 'any' type.

Try npm install @types/cp-react-tree-table if it exists or add a new declaration (.d.ts) file containing declare module 'cp-react-tree-table';ts(7016)
Could not find a declaration file for module 'cp-react-tree-table'. path/node_modules/cp-react-tree-table/dist/index.js' implicitly has an 'any' type.

Try npm install @types/cp-react-tree-table if it exists or add a new declaration (.d.ts) file containing declare module 'cp-react-tree-table';ts(7016)

Could not find a declaration file for module 'cp-react-tree-table'


问:
How do I pass data between Activities in Android application?
I have a scenario where, after logging in through a login page, there will be a sign-out button on each activity.

On clicking sign-out, I will be passing the session id of the signed in user to sign-out. Can anyone guide me on how to keep session id available to all activities?

Any alternative to this case

答:
```<code> Intent intent = new Intent(getBaseContext(), SomeActivity.class);
 intent.putExtra("USER_ID", UserId);
 startActivity(intent);

 On SomeActivity :

 String userId= getIntent().getStringExtra("("USER_ID");
</code>```


问:
how to Style a Spinner
I am new to Android and was working with Spinner. I wanted to know that how can we style the Spinner items? Change the fontFamily of the items, textColor, textSize.
 Can anyone help? Thank you.

答:
Make a custom layout

my_spinner_layout.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fontFamily="@font/clear_sans_regular"
    android:gravity="left"
    android:padding="5dip"
    android:textColor="@color/tealish"
    android:textSize="14sp" />
</code>```

here you can customize according to your need , and then use it inside your adapter

```<code>Spinner yourSpinner = (Spinner) findViewById(R.id.your_spinner_id;
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
    R.layout.my_spinner_layout, list);   //use your custom layout like this
dataAdapter.setDropDownViewResource(R.layout.my_spinner_layout);
yourSpinner.setAdapter(dataAdapter);
</code>```

Title: how to Style a Spinner

Body:
Make a custom layout

my_spinner_layout.xml

<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fontFamily="@font/clear_sans_regular"
    android:gravity="left"
    android:padding="5dip"
    android:textColor="@color/tealish"
    android:textSize="14sp" />

here you can customize according to your need , and then use it inside your adapter

Spinner yourSpinner = (Spinner) findViewById(R.id.your_spinner_id;
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
    R.layout.my_spinner_layout, list);   //use your custom layout like this
dataAdapter.setDropDownViewResource(R.layout.my_spinner_layout);
yourSpinner.setAdapter(dataAdapter);


问:
Problem to play downloaded HLS stream in the AVPlayer after update iOS 12.2
I encountered with a strange problem. After Apple released iOS 12.2 AVPlayer didn't play saved HLS stream correctly.

He stops playing video in the offline mode after 4-7 minutes and goes to the buffering. Player didn't call any observers, only AVPlayerItemPlaybackStalled sometimes called. Then, if i replace AVPlayerItem and start play from saved position video will be play correctly 4-7 minutes and stopes again. If i will turn the application to the background for 10 minutes video will be play again. If i will reboot phone all saved video will be play successfully. But all new video will be play with the same problem. Can anyone help me with this strange thing or tell in which direction to look?

This problem i have only on the iOS 12.2 and newer. All previous version play offline HLS correctly.

答: Ok, the problem was on the CDN side. Apple requires #EXT-X-PLAYLIST-TYPE:VOD string in the manifest after update to iOS 12.2</p>


问:
using opencv LineSegmentDetector to find line of an image
i have a color image and i should use opencv LineSegmentDetector algorithm to detect lines of the rectangles in the image

Here is my image:

i'm using this code :

import cv2
img = cv2.imread("rectangles.jpg",0)

#Create default parametrization LSD
lsd = cv2.createLineSegmentDetector(0)

#Detect lines in the image
lines = lsd.detect(img)[0]

#Draw detected lines in the image
drawn_img = lsd.drawSegments(img,lines)

#Show image
cv2.imshow("LSD",drawn_img )
cv2.waitKey(0)```
</div>
</div>
</p>

<p>and i'm getting this errpr:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><ipython-input-18-93ae667b0648> in <module>()
      3
      4 #Create default parametrization LSD
----> 5 lsd = cv2.createLineSegmentDetector(0)
      6
      7 #Detect lines in the image

error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\imgproc\src\lsd.cpp:143: error: (-213:The function/feature is not implemented) Implementation has been removed due original code license issues in function 'cv::LineSegmentDetectorImpl::LineSegmentDetectorImpl'</code>```

i checked open-cv version 4.1 documentation to use this method and here is the page , but i dont understand how should i use this method.

any help is appreciated.

答:
Did you read the error message?

error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\imgproc\src\lsd.cpp:143: error: (-213:The function/feature is not implemented)

  Implementation has been removed due original code license issues in function 'cv::LineSegmentDetectorImpl::LineSegmentDetectorImpl'

The class is not available due to license issues.

You can see that here in the original source.

Body:
i have a color image and i should use opencv LineSegmentDetector algorithm to detect lines of the rectangles in the image

Here is my image:

i'm using this code :

import cv2
img = cv2.imread("rectangles.jpg",0)

#Create default parametrization LSD
lsd = cv2.createLineSegmentDetector(0)

#Detect lines in the image
lines = lsd.detect(img)[0]

#Draw detected lines in the image
drawn_img = lsd.drawSegments(img,lines)

#Show image
cv2.imshow("LSD",drawn_img )
cv2.waitKey(0)

and i'm getting this errpr:

<ipython-input-18-93ae667b0648> in <module>()
      3
      4 #Create default parametrization LSD
----> 5 lsd = cv2.createLineSegmentDetector(0)
      6
      7 #Detect lines in the image

error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\imgproc\src\lsd.cpp:143: error: (-213:The function/feature is not implemented) Implementation has been removed due original code license issues in function 'cv::LineSegmentDetectorImpl::LineSegmentDetectorImpl'

i checked open-cv version 4.1 documentation to use this method and here is the page , but i dont understand how should i use this method.

any help is appreciated.


问:
Attempting to create a query that will return all records has me stumped
I have a database with three tables.  "Roster", "Training Courses", and "Course Enrollment"
Roster and Course Enrollment are connected by "ETID" (employee training ID).  Course Enrollment and Training Courses are connected by "Course ID".

I am trying to create a query that will return ALL employees, and a YES/NO value for all courses.
I've written the following to look at specific employees, but I cant seem to find the right way to return all employees. Any help would be appreciated.

```<code>SELECT [TRAINING COURSES].[course id]
     , [TRAINING COURSES].[course name]
     , "YES" AS Completed
     , [COURSE ENROLLMENT].[training date]
FROM [TRAINING COURSES]
INNER JOIN [COURSE ENROLLMENT]
            ON [COURSE ENROLLMENT].[course id]=[TRAINING COURSES].[course id]
WHERE [COURSE ENROLLMENT].[ETID]=[ENTER ETID]

UNION ALL

SELECT [TRAINING COURSES].[course id]
     , [TRAINING COURSES].[course name]
     , "No" AS Completed
     , NULL
FROM [TRAINING COURSES]
WHERE NOT EXISTS
(
    SELECT *
    FROM [COURSE ENROLLMENT]
    WHERE [COURSE ENROLLMENT].[course id]=[TRAINING COURSES].[course id]
    AND [COURSE ENROLLMENT].[ETID]=[ENTER ETID:]
)
ORDER BY [TRAINING COURSES].[course name];
</code>```

答:
You don't need to use Union in this query. Replace the INNER JOIN with a LEFT OUTER JOIN and it will accomplish the same as your query but will perform better.

```<code>SELECT [Training Courses].[Course Id], [Training Courses].[Course Name],
        IIF(IsNull([Course Enrollment].[ETID]), "NO", "YES") as Completed,
        [Course Enrollment].[Training Date]
FROM    [Training Courses]
        LEFT OUTER JOIN [Course Enrollment]
            ON [Training Courses].[Course Id] = [Course Enrollment].[Course Id]
ORDER BY [Training Courses].[Course Name]
</code>```

If you want all employees and all courses, you'll need to do a cross join between the Roster and Training Course table. You would then do a left join with the course enrollment table to get the yes no like above.

ContentLicense: CC BY-SA 3.0

Body:
I have a database with three tables.  "Roster", "Training Courses", and "Course Enrollment"
Roster and Course Enrollment are connected by "ETID" (employee training ID).  Course Enrollment and Training Courses are connected by "Course ID".

I am trying to create a query that will return ALL employees, and a YES/NO value for all courses.
I've written the following to look at specific employees, but I cant seem to find the right way to return all employees. Any help would be appreciated.

SELECT [TRAINING COURSES].[course id]
     , [TRAINING COURSES].[course name]
     , "YES" AS Completed
     , [COURSE ENROLLMENT].[training date]
FROM [TRAINING COURSES]
INNER JOIN [COURSE ENROLLMENT]
            ON [COURSE ENROLLMENT].[course id]=[TRAINING COURSES].[course id]
WHERE [COURSE ENROLLMENT].[ETID]=[ENTER ETID]

UNION ALL

SELECT [TRAINING COURSES].[course id]
     , [TRAINING COURSES].[course name]
     , "No" AS Completed
     , NULL
FROM [TRAINING COURSES]
WHERE NOT EXISTS
(
    SELECT *
    FROM [COURSE ENROLLMENT]
    WHERE [COURSE ENROLLMENT].[course id]=[TRAINING COURSES].[course id]
    AND [COURSE ENROLLMENT].[ETID]=[ENTER ETID:]
)
ORDER BY [TRAINING COURSES].[course name];

Body:
You don't need to use Union in this query. Replace the INNER JOIN with a LEFT OUTER JOIN and it will accomplish the same as your query but will perform better.

SELECT [Training Courses].[Course Id], [Training Courses].[Course Name],
        IIF(IsNull([Course Enrollment].[ETID]), "NO", "YES") as Completed,
        [Course Enrollment].[Training Date]
FROM    [Training Courses]
        LEFT OUTER JOIN [Course Enrollment]
            ON [Training Courses].[Course Id] = [Course Enrollment].[Course Id]
ORDER BY [Training Courses].[Course Name]

If you want all employees and all courses, you'll need to do a cross join between the Roster and Training Course table. You would then do a left join with the course enrollment table to get the yes no like above.


答:
Create a new file like cp-react-tree-table.d.ts then add the following content to resolve the error quickly, but it's unsafe.

```<code>    declare module "cp-react-tree-table" {
      let TreeDataTable: any;
      export default TreeDataTable;
    }
</code>```

Also, make sure typescript honoring our declaration file.

Title: how to use cp-react-tree-table in my project?

Body:
Create a new file like cp-react-tree-table.d.ts then add the following content to resolve the error quickly, but it's unsafe.

    declare module "cp-react-tree-table" {
      let TreeDataTable: any;
      export default TreeDataTable;
    }

Also, make sure typescript honoring our declaration file.


问:
Popup resizing based on orientation
I have assignment to make a resizable popup based on the device orientation. I am instantiating it over the window like this.

```<code>let window = UIApplication.shared.keyWindow
let popOver = DeletePopUpViewController(nibName: "DeletePopUpViewController", bundle: nil)
popOver?.loadViewIfNeeded()
popOver?.view.frame = window!.frame
window?.addSubview(popOver!.view)
</code>```

I have added constraints in the IB, since my task for now wasn't to be resizable. Now I need to transfer my constraints to the code, and this is what bothers me. I was able to detect orientation change with observer like -

```<code>NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: UIDevice.orientationDidChangeNotification, object: nil)

@objc private func rotated() {
    if UIDevice.current.orientation == UIDeviceOrientation.landscapeLeft || UIDevice.current.orientation == UIDeviceOrientation.landscapeRight {
         //code to implement constraints and size in landscape.
    }
    if UIDevice.current.orientation == UIDeviceOrientation.portrait || UIDevice.current.orientation == UIDeviceOrientation.portraitUpsideDown {
        //code to implement constraints and size in portrait.
    }
}
</code>```

Could you please give me some guidelines where to start from since I am fairly new to Swift and haven't done a lot of constraints in code. Also article would be helpful as well. Basically every help is welcome.

Thanks in advance.

答:
Please refer below code:

```<code>let window = UIApplication.shared.keyWindow
let popOver = DeletePopUpViewController(nibName:   "DeletePopUpViewController", bundle: nil)
popOver?.loadViewIfNeeded()
popOver.tag = 1000
popOver?.view.frame = window!.frame
window?.addSubview(popOver!.view)

@objc private func rotated() {
    let window = appDelegate.window!

    if let popup = window.viewWithTag(1000){
        popup.frame = window.bounds
    }
}
</code>```

Update: With autolayout

```<code>  func addPopoverView(){
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let rootVC = appDelegate.window?.rootViewController else {
            return
        }
        let viewToAdd = UIView()
        let count = rootVC.view.subviews.count
        rootVC.view.insertSubview(viewToAdd, at: count)
        viewToAdd.translatesAutoresizingMaskIntoConstraints = false
        viewToAdd.leadingAnchor.constraint(equalTo: rootVC.view.leadingAnchor, constant: 0).isActive = true
        viewToAdd.trailingAnchor.constraint(equalTo: rootVC.view.trailingAnchor, constant: 0).isActive = true
        viewToAdd.topAnchor.constraint(equalTo: rootVC.view.topAnchor, constant: 0).isActive = true
        viewToAdd.bottomAnchor.constraint(equalTo: rootVC.view.bottomAnchor, constant: 0).isActive = true
        viewToAdd.backgroundColor = UIColor.red
    }
</code>```

Title: Popup resizing based on orientation

Body:
I have assignment to make a resizable popup based on the device orientation. I am instantiating it over the window like this.

let window = UIApplication.shared.keyWindow
let popOver = DeletePopUpViewController(nibName: "DeletePopUpViewController", bundle: nil)
popOver?.loadViewIfNeeded()
popOver?.view.frame = window!.frame
window?.addSubview(popOver!.view)

I have added constraints in the IB, since my task for now wasn't to be resizable. Now I need to transfer my constraints to the code, and this is what bothers me. I was able to detect orientation change with observer like -

NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: UIDevice.orientationDidChangeNotification, object: nil)

@objc private func rotated() {
    if UIDevice.current.orientation == UIDeviceOrientation.landscapeLeft || UIDevice.current.orientation == UIDeviceOrientation.landscapeRight {
         //code to implement constraints and size in landscape.
    }
    if UIDevice.current.orientation == UIDeviceOrientation.portrait || UIDevice.current.orientation == UIDeviceOrientation.portraitUpsideDown {
        //code to implement constraints and size in portrait.
    }
}

Could you please give me some guidelines where to start from since I am fairly new to Swift and haven't done a lot of constraints in code. Also article would be helpful as well. Basically every help is welcome.

Thanks in advance.

Body:
Please refer below code:

let window = UIApplication.shared.keyWindow
let popOver = DeletePopUpViewController(nibName:   "DeletePopUpViewController", bundle: nil)
popOver?.loadViewIfNeeded()
popOver.tag = 1000
popOver?.view.frame = window!.frame
window?.addSubview(popOver!.view)

@objc private func rotated() {
    let window = appDelegate.window!

    if let popup = window.viewWithTag(1000){
        popup.frame = window.bounds
    }
}

Update: With autolayout

  func addPopoverView(){
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let rootVC = appDelegate.window?.rootViewController else {
            return
        }
        let viewToAdd = UIView()
        let count = rootVC.view.subviews.count
        rootVC.view.insertSubview(viewToAdd, at: count)
        viewToAdd.translatesAutoresizingMaskIntoConstraints = false
        viewToAdd.leadingAnchor.constraint(equalTo: rootVC.view.leadingAnchor, constant: 0).isActive = true
        viewToAdd.trailingAnchor.constraint(equalTo: rootVC.view.trailingAnchor, constant: 0).isActive = true
        viewToAdd.topAnchor.constraint(equalTo: rootVC.view.topAnchor, constant: 0).isActive = true
        viewToAdd.bottomAnchor.constraint(equalTo: rootVC.view.bottomAnchor, constant: 0).isActive = true
        viewToAdd.backgroundColor = UIColor.red
    }


问:
How to post data in from back-end testcase to controller
I am new to php and I am currently trying to make a testcase for an add function I wrote for adding records in the table "project_point" of my database. In this testcase I want to post some test data to that add function and check if the data is set correctly.

Project Point Add function

```<code>public function addProjectPoint (Request $request) {
    $point = new ProjectPoint();

    $location = new Point($request->markerLat, $request->markerLong);

    $point->project_id = $request->project_id;
    $point->location = $location;
    $point->area = $request->area;
    $point->name = $request->name;
    $point->information = $request->information;
    $point->category = $request->category;

    $point->save();
}
</code>```

My test case

```<code>public function testCreateProjectPoint()
    {
        $this->post('admin/projectpoint/create', [
            'project_id' => 1,
            'markerLat' => 5.287020206451416,
            'markerLong' => 51.68828138589033,
            'area' => null,
            'name' => 'TestCaseProjectPoint',
            'information' => 'This is a automated test ProjectPoint, please delete this point!',
            'category' => 'bezienswaardigheid'
        ]);

        $this->assertDatabaseHas('interest_point', [
            'project_id' => 1,
            'location' => new Point(5.287020206451416, 51.68828138589033),
            'area' => null,
            'name' => 'TestCaseProjectPoint',
            'information' => 'This is a automated test ProjectPoint, please delete this point!',
            'category' => 'bezienswaardigheid'
        ]);

        /*
        $test = factory(ProjectPoint::class)->create();

        $this->post('admin/projectpoint/create', $test);

        $this->assertDatabaseHas('project_point', $test);
        */
    }
</code>```

ProjectPoint model

```<code>class ProjectPoint extends Model
{
    use SpatialTrait;

    protected $table = 'interest_point';

    protected $fillable = ['project_id', 'name', 'information', 'category' ];

    protected $spatialFields = [
        'location',
        'area'
    ];

    public $timestamps = false;

    public function project()
    {
        return $this->belongsTo('App\Models\Project', 'project_id');
    }
}
</code>```

The output of the test is:

```<code>Failed asserting that a row in the table [interest_point] matches the attributes {
    "project_id": 1,
    "location": {
        "type": "Point",
        "coordinates": [
            51.68828138589033,
            5.287020206451416
        ]
    },
    "area": null,
    "name": "TestCaseProjectPoint",
    "information": "This is a automated test ProjectPoint, please delete this point!",
    "category": "bezienswaardigheid"
}.
</code>```

But I expect to see the test case succeed and when checking the database no records have been added to the database

答: Have you tried still putting location and area in your fillables?

Body:
I am new to php and I am currently trying to make a testcase for an add function I wrote for adding records in the table "project_point" of my database. In this testcase I want to post some test data to that add function and check if the data is set correctly.

Project Point Add function

public function addProjectPoint (Request $request) {
    $point = new ProjectPoint();

    $location = new Point($request->markerLat, $request->markerLong);

    $point->project_id = $request->project_id;
    $point->location = $location;
    $point->area = $request->area;
    $point->name = $request->name;
    $point->information = $request->information;
    $point->category = $request->category;

    $point->save();
}

My test case

public function testCreateProjectPoint()
    {
        $this->post('admin/projectpoint/create', [
            'project_id' => 1,
            'markerLat' => 5.287020206451416,
            'markerLong' => 51.68828138589033,
            'area' => null,
            'name' => 'TestCaseProjectPoint',
            'information' => 'This is a automated test ProjectPoint, please delete this point!',
            'category' => 'bezienswaardigheid'
        ]);

        $this->assertDatabaseHas('interest_point', [
            'project_id' => 1,
            'location' => new Point(5.287020206451416, 51.68828138589033),
            'area' => null,
            'name' => 'TestCaseProjectPoint',
            'information' => 'This is a automated test ProjectPoint, please delete this point!',
            'category' => 'bezienswaardigheid'
        ]);

        /*
        $test = factory(ProjectPoint::class)->create();

        $this->post('admin/projectpoint/create', $test);

        $this->assertDatabaseHas('project_point', $test);
        */
    }

ProjectPoint model

class ProjectPoint extends Model
{
    use SpatialTrait;

    protected $table = 'interest_point';

    protected $fillable = ['project_id', 'name', 'information', 'category' ];

    protected $spatialFields = [
        'location',
        'area'
    ];

    public $timestamps = false;

    public function project()
    {
        return $this->belongsTo('App\Models\Project', 'project_id');
    }
}

The output of the test is:

Failed asserting that a row in the table [interest_point] matches the attributes {
    "project_id": 1,
    "location": {
        "type": "Point",
        "coordinates": [
            51.68828138589033,
            5.287020206451416
        ]
    },
    "area": null,
    "name": "TestCaseProjectPoint",
    "information": "This is a automated test ProjectPoint, please delete this point!",
    "category": "bezienswaardigheid"
}.

But I expect to see the test case succeed and when checking the database no records have been added to the database


问:
How to print HTML geolocation?
I'm using HTML5 Geolocation and wants to print the returned user location in the input field.

Is this possible? If so how?

    var x = document.getElementById("demo");

    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
      } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
      }
    }

    function showPosition(position) {
      x.innerHTML = "Latitude: " + position.coords.latitude +
      "
Longitude: " + position.coords.longitude;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text">
<button onclick="getLocation()">Try It</button>
<p id="demo"></p></code>```

答:
You can handle the error to know the root cause, it could be possible that the position is unavailable

Check the way to handle error in this answer

instead of assigning the values directly to x.innerHTML first, check if you are getting the position coordinates using console.log

```<code>function showPosition(position) {
         console.log(position)
        // x.innerHTML = "Latitude: " + position.coords.latitude +
        // "<br>Longitude: " + position.coords.longitude;
       }
</code>```

and then once you successfully receive the position details, assign it to your variable

```<code>function showPosition(position) {
            // console.log(position)
             x.innerHTML = "Latitude: " + position.coords.latitude +
             "<br>Longitude: " + position.coords.longitude;
           }
</code>```

Title: How to print HTML geolocation?

Body:
I'm using HTML5 Geolocation and wants to print the returned user location in the input field.

Is this possible? If so how?

    var x = document.getElementById("demo");

    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
      } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
      }
    }

    function showPosition(position) {
      x.innerHTML = "Latitude: " + position.coords.latitude +
      "
Longitude: " + position.coords.longitude;
    }

<input type="text">
<button onclick="getLocation()">Try It</button>

Body:
You can handle the error to know the root cause, it could be possible that the position is unavailable

Check the way to handle error in this answer

instead of assigning the values directly to x.innerHTML first, check if you are getting the position coordinates using console.log

function showPosition(position) {
         console.log(position)
        // x.innerHTML = "Latitude: " + position.coords.latitude +
        // "<br>Longitude: " + position.coords.longitude;
       }

and then once you successfully receive the position details, assign it to your variable

function showPosition(position) {
            // console.log(position)
             x.innerHTML = "Latitude: " + position.coords.latitude +
             "<br>Longitude: " + position.coords.longitude;
           }


问:
Microservice and service collaboration
In the context of a Microservice architecture, a single business operation can require collaboration between two or more services.

Suppose we have an Order Management Service and a Product Catalog Service.
When the user adds an order item to an order, the Order Management Service will persist a OrderItem object which have the following attributes among many others :

```<code>OrderItem
+ Id
+ ProductId
+ ProductName
</code>```

In order for the Order Management Service to fill the ProductName attribute, we have 4 choices as I see it :

Choice 1 : ProductName is given by the client app as it probably already has this data from previous requests

Choice 2 : If the architecture uses an Api Gateway, the gateway will be responsible for retrieving the ProductName from the Product Catalog Service then provide it to the Order Management Service.

Choice 3 : The Order Management Service will call directly the Product Catalog Service and asks him for the ProductName givent a product id.

Choice 4 : The Order Management Service has a duplicate (but not exhaustive) product informations in its own database and these datas will be updated each time an update event is received from the Product Catalog Service.

Among these 4 choices, the n°1 seems not ok to me as we can't trust the client to give us a correct and updated value of ProductName.

I would like to have your opinion about what you think the best choice is and why !

Thanks !

Riana

答:
Choice 1 : ProductName is given by the client app as it probably already has this data from previous requests

Like you said, it is not the best idea because the client may have stale information. Maybe acceptable if the product information changes infrequently and/or you have a secondary verification at order processing.

Choice 2 : If the architecture uses an Api Gateway, the gateway will be responsible for retrieving the ProductName from the Product Catalog Service then provide it to the Order Management Service.

IMHO, this is not a good idea. By doing so your domain/business logic will leak into the API Gateway. The gateway now knows the relationship between Orders and Products. This API gateway configuration/scripting will need to be maintained and introduces additional coupling.

Choice 3 : The Order Management Service will call directly the Product Catalog Service and asks him for the ProductName givent a product id.

This is my preferred choice. Though I do not recommend "direct" synchronous calls. Perhaps a retrieval of the ProductName via a messaging mechanism (message queue, event bus). Chained synchronous calls will reduce the availability of your services. You can find more information at Microservice Messaging Pattern.

Choice 4 : The Order Management Service has a duplicate (but not exhaustive) product informations in its own database and these datas will be updated each time an update event is received from the Product Catalog Service.

Data duplication is generally frowned upon unless there is a really good reason for it. In this case I don't see any. Why bother splitting the databases into two for each of the services yet duplicate the data between them? Also, to have the data updated each time an update event is received indicates that some kind of event/messaging infrastructure is available, in that case, why not just use messaging?

This duplication may be justifiable for high volume, low latency look ups, but it is a slippery slope that may end up with duplicated data all over your services. Imagine the repercussions of a length or type/format change of the ProductName string...

Title: Microservice and service collaboration

Body:
In the context of a Microservice architecture, a single business operation can require collaboration between two or more services.

Suppose we have an Order Management Service and a Product Catalog Service.
When the user adds an order item to an order, the Order Management Service will persist a OrderItem object which have the following attributes among many others :

OrderItem
+ Id
+ ProductId
+ ProductName

In order for the Order Management Service to fill the ProductName attribute, we have 4 choices as I see it :

Choice 1 : ProductName is given by the client app as it probably already has this data from previous requests

Choice 2 : If the architecture uses an Api Gateway, the gateway will be responsible for retrieving the ProductName from the Product Catalog Service then provide it to the Order Management Service.

Choice 3 : The Order Management Service will call directly the Product Catalog Service and asks him for the ProductName givent a product id.

Choice 4 : The Order Management Service has a duplicate (but not exhaustive) product informations in its own database and these datas will be updated each time an update event is received from the Product Catalog Service.

Among these 4 choices, the n°1 seems not ok to me as we can't trust the client to give us a correct and updated value of ProductName.

I would like to have your opinion about what you think the best choice is and why !

Thanks !

Riana


问:
How inject Logger in custom service
I have ImportExportService.

In StartUp class in method ConfigureServices I use it as

```<code>services.AddImportExportService(Configuration.GetConnectionString("DefaultConnection"));
</code>```

Extential method AddImportExportService:

```<code>public static class IServiceCollectionExtension
    {
        public static IServiceCollection AddImportExportService(this IServiceCollection services,
            string connString,
            ILogger<ImportExportService> logger
            )
        {
            services.AddTransient<IImportExportService, ImportExportService>(provider => new ImportExportService(connString));
            return services;
        }
    }
</code>```

ExportImportService uses logging.
I tried to inject Logging in service as param in constructor like ILoger<ImportExportService> logger, but constructor includes only one param and extension method AddImportExportService get error.

How inject Logging in ExportImportService? Thank you

答:
```<code>services.AddTransient<IImportExportService, ImportExportService>(provider => new ImportExportService(connString));
</code>```

should be

```<code>services
    .AddTransient<IImportExportService, ImportExportService>(
        provider => new ImportExportService(connString, provider.GetRequiredService<ILogger<ImportExportService>>()));
</code>```

assuming the constructor of ImportExportService has two arguments. Then the extension needs only two arguments:

```<code>public static IServiceCollection AddImportExportService(
    this IServiceCollection services,
    string connString)
</code>```

Title: How inject Logger in custom service

Body:
I have ImportExportService.

In StartUp class in method ConfigureServices I use it as

services.AddImportExportService(Configuration.GetConnectionString("DefaultConnection"));

Extential method AddImportExportService:

public static class IServiceCollectionExtension
    {
        public static IServiceCollection AddImportExportService(this IServiceCollection services,
            string connString,
            ILogger<ImportExportService> logger
            )
        {
            services.AddTransient<IImportExportService, ImportExportService>(provider => new ImportExportService(connString));
            return services;
        }
    }

ExportImportService uses logging.
I tried to inject Logging in service as param in constructor like ILoger<ImportExportService> logger, but constructor includes only one param and extension method AddImportExportService get error.

How inject Logging in ExportImportService? Thank you

Body:
services.AddTransient<IImportExportService, ImportExportService>(provider => new ImportExportService(connString));

should be

services
    .AddTransient<IImportExportService, ImportExportService>(
        provider => new ImportExportService(connString, provider.GetRequiredService<ILogger<ImportExportService>>()));

assuming the constructor of ImportExportService has two arguments. Then the extension needs only two arguments:

public static IServiceCollection AddImportExportService(
    this IServiceCollection services,
    string connString)


问:
Multi-Touch tutorial, stuck on unknown variable
I am trying to implement this multi-touch android tutorial

http://www.zdnet.com/blog/burnette/how-to-use-multi-touch-in-android-2-part-5-implementing-the-drag-gesture/1789?tag=mantle_skin;content

I am stuck in Step 5 for the implementation, what is the start variable?

```<code>  switch (event.getAction() & MotionEvent.ACTION_MASK) {
   case MotionEvent.ACTION_DOWN:
      savedMatrix.set(matrix);
      start.set(event.getX(), event.getY());
      Log.d(TAG, "mode=DRAG" );
      mode = DRAG;
      break;
   case MotionEvent.ACTION_UP:
   case MotionEvent.ACTION_POINTER_UP:
      mode = NONE;
      Log.d(TAG, "mode=NONE" );
      break;
   case MotionEvent.ACTION_MOVE:
      if (mode == DRAG) {
         matrix.set(savedMatrix);
         matrix.postTranslate(event.getX() - start.x,
         event.getY() - start.y);
      }
      break;
}
</code>```

Thanks

答:
You can download the complete source here.
The start variable is of type PointF, it represents the starting point of the gesture.</p>

Body:
I am trying to implement this multi-touch android tutorial

http://www.zdnet.com/blog/burnette/how-to-use-multi-touch-in-android-2-part-5-implementing-the-drag-gesture/1789?tag=mantle_skin;content

I am stuck in Step 5 for the implementation, what is the start variable?

  switch (event.getAction() & MotionEvent.ACTION_MASK) {
   case MotionEvent.ACTION_DOWN:
      savedMatrix.set(matrix);
      start.set(event.getX(), event.getY());
      Log.d(TAG, "mode=DRAG" );
      mode = DRAG;
      break;
   case MotionEvent.ACTION_UP:
   case MotionEvent.ACTION_POINTER_UP:
      mode = NONE;
      Log.d(TAG, "mode=NONE" );
      break;
   case MotionEvent.ACTION_MOVE:
      if (mode == DRAG) {
         matrix.set(savedMatrix);
         matrix.postTranslate(event.getX() - start.x,
         event.getY() - start.y);
      }
      break;
}

Thanks


问:
MIPS: load byte instruction
Assume that the processor is executing the following instruction:

```<code>lb $t3,-7($s0)
</code>```

Moreover, assume that the instruction above is located at address 0x004000f0,
register $t3 contains value 0x20040144, and that register $s0 contains value
0x305502db. What value has registers $t3 after that the instruction has finished executing?

From my calculation:

The format of the instruction is:

```<code>lb RegDest, Offset(RegSource)
</code>```

we know $s0 contains value 0x305502db, which leads to 0x305502db - 7 = 0x305502d4 and this value will be loaded in $t3. I am confused here now because the correct answer says $t3 = unknown, how come?

答:
0x305502db - 7 = 0x305502d4

... so the lb instruction will load the byte from the memory (for example: RAM) at address 0x305502d4, sign-extend it and write it into the register $t3.

If the RAM contains the value 0x5A at address 0x305502d4, $t3 will contain the value 0x0000005A. If it contains the value 0xA5, $t3 will contain the value 0xFFFFFFA5.

... the correct answer says $t3 = unknown, how come?

Your exercise does not contain any information about the content of the RAM at address 0x305502d4.

Therefore you cannot say which value $t3 will contain.

Title: MIPS: load byte instruction

Body:
Assume that the processor is executing the following instruction:

lb $t3,-7($s0)

Moreover, assume that the instruction above is located at address 0x004000f0,
register $t3 contains value 0x20040144, and that register $s0 contains value
0x305502db. What value has registers $t3 after that the instruction has finished executing?

From my calculation:

The format of the instruction is:

lb RegDest, Offset(RegSource)

we know $s0 contains value 0x305502db, which leads to 0x305502db - 7 = 0x305502d4 and this value will be loaded in $t3. I am confused here now because the correct answer says $t3 = unknown, how come?


问:
Reason for using "Hash.new { Hash.new(false) }"
Encountered some code which sets an instance variable like so:

@square_array = Hash.new { Hash.new(false) }
```

<p>Is there a reason to do it this way?</p>

<p>Rather then one of the following:</p>

<pre class="lang-rb prettyprint-override"><code>@square_array = Hash.new

# or

@square_array = {}
</code>```

答:
Yes, there is a reason. If you define hash with {} and try to get value of non-existing key, you get nil

```<code>hash = {}
#=> {}
hash[:a]
#=> nil
</code>```

But if you define it with Hash.new you can set define value for non-existing key

```<code>hash =  Hash.new { Hash.new(false) }
#=> {}
hash[:a]
#=> {}
hash[:a][:a]
#=> false
</code>```

Body:
Encountered some code which sets an instance variable like so:

@square_array = Hash.new { Hash.new(false) }

Is there a reason to do it this way?

Rather then one of the following:

@square_array = Hash.new

# or

@square_array = {}

Body:
Yes, there is a reason. If you define hash with {} and try to get value of non-existing key, you get nil

hash = {}
#=> {}
hash[:a]
#=> nil

But if you define it with Hash.new you can set define value for non-existing key

hash =  Hash.new { Hash.new(false) }
#=> {}
hash[:a]
#=> {}
hash[:a][:a]
#=> false


问:
How to test async functions that update PublishSubject or BehaviorSubject object (RxDart) in Flutter
I've been learning flutter for a few weeks and come from an Android background so far I love it and I have also been delighted to find that Flutter was designed with testing in mind from day one. However, I've been having an issue running the following test.

```<code>main() => {
  test('test get popular repos', () async {
    final testOwner = Owner(1010, "testLink");
    final testRepo =
        Repo(101, testOwner, "testRepo", "description", 'htmlUrl', 500);
    final testRepoResponse = RepoResponse(List.from([testRepo]), null);
    final uiModel = PopRepo(testRepo.owner.avatarUrl, testRepo.name,
        testRepo.description, "Stars: ${testRepo.stargazersCount}");
    final searchData = SearchData(List.from([uiModel]), null);

    final Repository mockRepository = _mockRepository();

    when(mockRepository.getPopularReposForOrg("org"))
        .thenAnswer((_) => Future.value(testRepoResponse));

    final repoSearchBloc = RepoSearchPageBloc(mockRepository);
    await repoSearchBloc.getPopularRepos("org");

    await expectLater(repoSearchBloc.resultSubject.stream, emits(searchData));
  }),
};

class _mockRepository extends Mock implements Repository {}
</code>```

My RepoSearchBloc takes data from a Repository and transforms it into the Ui model. Finally it posts that now UI-ready data to the Subject

this is the method under test in the RepoSearchBloc

```<code>getPopularRepos(String org) async {
if (org == null || org.isEmpty)
  return resultSubject.add(SearchData(List(), null));
RepoResponse response = await _repository.getPopularReposForOrg(org);
if (response.error == null) {
  List<Repo> repoList = response.results;
  repoList.sort((a, b) => a.stargazersCount.compareTo(b.stargazersCount));
  var uiRepoList = repoList
      .map((repo) => PopRepo(repo.owner.avatarUrl, repo.name,
          repo.description, "Stars: ${repo.stargazersCount}"))
      .take(3)
      .toList();
  resultSubject.add(SearchData(uiRepoList, null));
} else {
  ErrorState error = ErrorState(response.error);
  resultSubject.add(SearchData(List(), error));
}
</code>```

When I run the test I keep getting this message no matter what I do it seems with either BehaviorSubject or PublishSubject:

```<code>ERROR: Expected: should emit an event that <Instance of 'SearchData'>
  Actual: <Instance of 'BehaviorSubject<SearchData>'>
   Which: emitted * Instance of 'SearchData'
</code>```

Any ideas how to get this test to pass?

答:
Ended up figuring this out with the help of a user Nico @Rodsevich of the Flutter Glitter community

anyways using his suggestion to use await for

I came up with the following solution which passed

```<code>    await for (var emittedResult in repoSearchBloc.resultSubject.stream) {
      expect(emittedResult.results[0].repoName, testRepo.name);
      return;
    }
</code>```

The RxDart library has some subject tests for reference but my subject being posted to asynchronously did not adhere to their test cases so this solution ended up being just what I needed.

Also @Abion47 's comment also seems to do the job when I move async inside the parameter for expected

```<code>expectLater( (await repoSearchBloc.resultSubject.stream.first as SearchData).results[0].repoName, testRepo.name);
</code>```

Body:
I've been learning flutter for a few weeks and come from an Android background so far I love it and I have also been delighted to find that Flutter was designed with testing in mind from day one. However, I've been having an issue running the following test.

main() => {
  test('test get popular repos', () async {
    final testOwner = Owner(1010, "testLink");
    final testRepo =
        Repo(101, testOwner, "testRepo", "description", 'htmlUrl', 500);
    final testRepoResponse = RepoResponse(List.from([testRepo]), null);
    final uiModel = PopRepo(testRepo.owner.avatarUrl, testRepo.name,
        testRepo.description, "Stars: ${testRepo.stargazersCount}");
    final searchData = SearchData(List.from([uiModel]), null);

    final Repository mockRepository = _mockRepository();

    when(mockRepository.getPopularReposForOrg("org"))
        .thenAnswer((_) => Future.value(testRepoResponse));

    final repoSearchBloc = RepoSearchPageBloc(mockRepository);
    await repoSearchBloc.getPopularRepos("org");

    await expectLater(repoSearchBloc.resultSubject.stream, emits(searchData));
  }),
};

class _mockRepository extends Mock implements Repository {}

My RepoSearchBloc takes data from a Repository and transforms it into the Ui model. Finally it posts that now UI-ready data to the Subject

this is the method under test in the RepoSearchBloc

getPopularRepos(String org) async {
if (org == null || org.isEmpty)
  return resultSubject.add(SearchData(List(), null));
RepoResponse response = await _repository.getPopularReposForOrg(org);
if (response.error == null) {
  List<Repo> repoList = response.results;
  repoList.sort((a, b) => a.stargazersCount.compareTo(b.stargazersCount));
  var uiRepoList = repoList
      .map((repo) => PopRepo(repo.owner.avatarUrl, repo.name,
          repo.description, "Stars: ${repo.stargazersCount}"))
      .take(3)
      .toList();
  resultSubject.add(SearchData(uiRepoList, null));
} else {
  ErrorState error = ErrorState(response.error);
  resultSubject.add(SearchData(List(), error));
}

When I run the test I keep getting this message no matter what I do it seems with either BehaviorSubject or PublishSubject:

ERROR: Expected: should emit an event that <Instance of 'SearchData'>
  Actual: <Instance of 'BehaviorSubject<SearchData>'>
   Which: emitted * Instance of 'SearchData'

Any ideas how to get this test to pass?

Body:
Ended up figuring this out with the help of a user Nico @Rodsevich of the Flutter Glitter community

anyways using his suggestion to use await for

I came up with the following solution which passed

    await for (var emittedResult in repoSearchBloc.resultSubject.stream) {
      expect(emittedResult.results[0].repoName, testRepo.name);
      return;
    }

The RxDart library has some subject tests for reference but my subject being posted to asynchronously did not adhere to their test cases so this solution ended up being just what I needed.

Also @Abion47 's comment also seems to do the job when I move async inside the parameter for expected

expectLater( (await repoSearchBloc.resultSubject.stream.first as SearchData).results[0].repoName, testRepo.name);


问:
Split String by Two Characters Ignore Whitespace Before, In Between or After any of the Characters
I have an input string for example

```<code>var input = "'Test string','abc'";
</code>```

I want to split it by exactly two characters that is ', ignoring white spaces before, in between or after the delimiters. For example based on the input I'm expecting the following output.

```<code>index0='Test string'
index1='abc'
</code>```

I want to retain that output even if my input looks like any of these.

```<code>var input = "'Test string','abc'";
var input = "'Test string ','abc'";
var input = "'Test string' ,'abc'";
var input = "'Test string', 'abc'";
var input = "'Test string   '   ,   'abc'";
</code>```

As long as there are two characters ', (single quote and comma) regardless that they have spaces before, in between or after, I want to split a string based on those two char delimiters. Splitting should only by two chars. If an input has only ' or , retain the input as is. Only split the input by ', not by any of the two chars. Please help. Here's my code.

```<code>   static void Main(string[] args)
    {
        var input = "'Test string','abc'";
        var results = Regex.Split(input, @"[ ',]+");
        foreach (var item in results)
            Console.WriteLine(item);
        Console.ReadLine();

    }
</code>```

答:
You can create method like below to get desired value. Call this method for each data.

```<code>private string GetValues(string input)
{
    StringBuilder newValue = new StringBuilder();
    string[] parts = input.Split(',');
    int counter = 0;
    foreach (string str in parts)
    {
        newValue.AppendLine("index" + counter++ + ":" + "'" + str.Trim().Trim('\'').Trim() + "'");

    }
    return newValue.ToString();
}
</code>```

Input:

```<code>"'Test string','abc'";
"'Test string ','abc'";
"'Test string' ,'abc'";
"'Test string', 'abc'";
"'Test string   '   ,   'abc'";
"Test string','abc','John's test'";
</code>```

Output is as below:

```<code>index0:'Test string'
index1:'abc'

index0:'Test string'
index1:'abc'

index0:'Test string'
index1:'abc'

index0:'Test string'
index1:'abc'

index0:'Test string'
index1:'abc'

index0:'Test string'
index1:'abc'
index2:'John's test'
</code>```

Body:
I have an input string for example

var input = "'Test string','abc'";

I want to split it by exactly two characters that is ', ignoring white spaces before, in between or after the delimiters. For example based on the input I'm expecting the following output.

index0='Test string'
index1='abc'

I want to retain that output even if my input looks like any of these.

var input = "'Test string','abc'";
var input = "'Test string ','abc'";
var input = "'Test string' ,'abc'";
var input = "'Test string', 'abc'";
var input = "'Test string   '   ,   'abc'";

As long as there are two characters ', (single quote and comma) regardless that they have spaces before, in between or after, I want to split a string based on those two char delimiters. Splitting should only by two chars. If an input has only ' or , retain the input as is. Only split the input by ', not by any of the two chars. Please help. Here's my code.

   static void Main(string[] args)
    {
        var input = "'Test string','abc'";
        var results = Regex.Split(input, @"[ ',]+");
        foreach (var item in results)
            Console.WriteLine(item);
        Console.ReadLine();

    }

Body:
You can create method like below to get desired value. Call this method for each data.

private string GetValues(string input)
{
    StringBuilder newValue = new StringBuilder();
    string[] parts = input.Split(',');
    int counter = 0;
    foreach (string str in parts)
    {
        newValue.AppendLine("index" + counter++ + ":" + "'" + str.Trim().Trim('\'').Trim() + "'");

    }
    return newValue.ToString();
}

Input:

"'Test string','abc'";
"'Test string ','abc'";
"'Test string' ,'abc'";
"'Test string', 'abc'";
"'Test string   '   ,   'abc'";
"Test string','abc','John's test'";

Output is as below:

index0:'Test string'
index1:'abc'

index0:'Test string'
index1:'abc'

index0:'Test string'
index1:'abc'

index0:'Test string'
index1:'abc'

index0:'Test string'
index1:'abc'

index0:'Test string'
index1:'abc'
index2:'John's test'


问:
I am getting multiple calls from angular to the Post API in Node
I am trying to write a file from the data from the database but I'm getting multiple calls from the angular causing multiple entries of the same data.How can I stop that? And also it is causing to override write file after some time.

I am not getting what exactly should I do. I have tried subscribing thing in service in angular but it was of no help.
component.ts

```<code>import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NgbModalRef, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
import { CountryService } from './country.service';
import { ConfigService } from '../config.service';

@Component({
  selector: 'app-country',
  templateUrl: './country.component.html',
  styleUrls: ['./country.component.scss'],
  encapsulation: ViewEncapsulation.None,
  providers: []
})
export class CountryComponent implements OnInit {
  public modalRef: NgbModalRef;
  public form: FormGroup;
  public selectedCountry;
  public countries;
  constructor(public fb: FormBuilder, public toastrService: ToastrService,
    public modalService: NgbModal, public configService: ConfigService,
    public countryService: CountryService) {

  }

  ngOnInit() {
    this.form = this.fb.group({
      country: [null, Validators.compose([Validators.required])],
    });
    this.getCountries();
  }

  public getCountries() {
    this.countryService.getCountries((data) => {
      this.countries = data.countries;
    }, (err) => { });
  }

  public selectCountry(country) {
    this.countryService.selectCountry(country, (resp) => {
    }, (err) => { });
  }
}
</code>```

service.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { ConfigService } from '../config.service';
import { ToastrService } from 'ngx-toastr';

@Injectable({
  providedIn: 'root'
})
export class CountryService {
  private setHeaders() {
    const headers = new HttpHeaders({
      'content-type': 'application/json',
    });
    return headers;
  }
  constructor(private configService: ConfigService, public http: HttpClient, public toastrService: ToastrService) { }

  selectCountry(country: any, callback, errCallback) {
       const options = {
      headers: this.setHeaders(),
    };
    this.http.post(this.configService.url + '/selectedCountry', country, options).subscribe((resp: any) => {
      callback(resp);
    }, err => {
      errCallback(err);
    });
  }

  getCountries(callback, errCallback) {
       const options = {
      headers: this.setHeaders(),
    };
    this.http.get(this.configService.url + '/countries', options).subscribe((resp: any) => {
         callback(resp.msg);
    }, err => {
      errCallback(err);
    });
  }

}
</code>```

I want the call to be sent only once, not twice

答:
Btw. - Please consider adding the NGRX lib in your app.

An angular-service is considered as a data holder. So make there an instance variable.
It could look like:

```<code>export class Service{
  private countries;
  ...
  public getCountries(){
     return this.countries;
  }

  public loadCountries(){
     this.http.get("url").subscribe(countries => this.countries = countries);
  }
}
</code>```

Then in your component class, you just get the countries.

```<code>export class Component{
  public coutries;
  ...
  public ngOnInit(){
    this.countryService.getCountries(countries => this.countries=coutries);
  }
 }
</code>```

And last but not least - load the countries in your AppComponent.

```<code>export class AppComponent{
  ...
  public ngOnInit(){
     this.countryService.loadCountries();
  }
}
</code>```

Body:
I am trying to write a file from the data from the database but I'm getting multiple calls from the angular causing multiple entries of the same data.How can I stop that? And also it is causing to override write file after some time.

I am not getting what exactly should I do. I have tried subscribing thing in service in angular but it was of no help.
component.ts

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NgbModalRef, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
import { CountryService } from './country.service';
import { ConfigService } from '../config.service';

@Component({
  selector: 'app-country',
  templateUrl: './country.component.html',
  styleUrls: ['./country.component.scss'],
  encapsulation: ViewEncapsulation.None,
  providers: []
})
export class CountryComponent implements OnInit {
  public modalRef: NgbModalRef;
  public form: FormGroup;
  public selectedCountry;
  public countries;
  constructor(public fb: FormBuilder, public toastrService: ToastrService,
    public modalService: NgbModal, public configService: ConfigService,
    public countryService: CountryService) {

  }

  ngOnInit() {
    this.form = this.fb.group({
      country: [null, Validators.compose([Validators.required])],
    });
    this.getCountries();
  }

  public getCountries() {
    this.countryService.getCountries((data) => {
      this.countries = data.countries;
    }, (err) => { });
  }

  public selectCountry(country) {
    this.countryService.selectCountry(country, (resp) => {
    }, (err) => { });
  }
}

service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { ConfigService } from '../config.service';
import { ToastrService } from 'ngx-toastr';

@Injectable({
  providedIn: 'root'
})
export class CountryService {
  private setHeaders() {
    const headers = new HttpHeaders({
      'content-type': 'application/json',
    });
    return headers;
  }
  constructor(private configService: ConfigService, public http: HttpClient, public toastrService: ToastrService) { }

  selectCountry(country: any, callback, errCallback) {
       const options = {
      headers: this.setHeaders(),
    };
    this.http.post(this.configService.url + '/selectedCountry', country, options).subscribe((resp: any) => {
      callback(resp);
    }, err => {
      errCallback(err);
    });
  }

  getCountries(callback, errCallback) {
       const options = {
      headers: this.setHeaders(),
    };
    this.http.get(this.configService.url + '/countries', options).subscribe((resp: any) => {
         callback(resp.msg);
    }, err => {
      errCallback(err);
    });
  }

}

I want the call to be sent only once, not twice

Body:
Btw. - Please consider adding the NGRX lib in your app.

An angular-service is considered as a data holder. So make there an instance variable.
It could look like:

export class Service{
  private countries;
  ...
  public getCountries(){
     return this.countries;
  }

  public loadCountries(){
     this.http.get("url").subscribe(countries => this.countries = countries);
  }
}

Then in your component class, you just get the countries.

export class Component{
  public coutries;
  ...
  public ngOnInit(){
    this.countryService.getCountries(countries => this.countries=coutries);
  }
 }

And last but not least - load the countries in your AppComponent.

export class AppComponent{
  ...
  public ngOnInit(){
     this.countryService.loadCountries();
  }
}


问:
Secret QR Code - Only read by my own scanner app
I am working on a social app like Instagram, Snap Chat, and Facebook. I need to generate a QR code of user profiles. I have hidden user ids from the database. I have a scanner in my app to scan the QR code. The functionality is working fine.

But when my generated QR codes are read by other scanner apps, like the iOS default scanner, it reads the user id (string, text) from the QR code.

I have used Swift default code for QR code generation.

QR code read only by my app.

Like Snap Chat, Messenger, etc.

答:
Have a look at this article

How is Snapchat QR code so different than others?

Snapchat and other apps have designed their own methods to create and read a QR code. Snapchat uses its own processing techniques to detect a series of dots to scan the code. It uses the snapchat logo for reference in the image to know where exactly to start the scanning. I am pretty sure Facebook and other apps are doing something similar.

You can maybe look at something that Instagram is doing. They use Text Detection to read a users name tag. You can look into this article for the same.

Text Detection Article

As far as i know there is no direct way that you can achieve this. You will have to essentially re-invent the wheel and come up with your own way to generate and read a code that is specific to your app.

Another approach would be to use an encryption algorithm to encrypt and decrypt your message and then using the QR code generator to generate a QR code of the encrypted message.


问:
How to get last value of an array input text in JS?
This is my code from controller where I used looping to show this.

```<code><input type="hidden" class="notif_date" value="'.$created_at.'">
</code>```

the sample data of this are multiple dates: 2019-05-28 13:45:45

Now I'm trying the get the last date that will be shown using JavaScript.

Currently I have this code:

```<code>var last_date =  document.getElementsByClassName("notif_date");
console.log(last_date);
</code>```

But this only gets the array of input types

So I tried to use last() and place like this console.log(last_date.last()); and this gives me an error like this

Uncaught TypeError: last_date.last is not a function

How can I get the last value of date using JavaScript?

答:
To get last element you can use following code

```<code>let elements = document.getElementsByClassName("notif_date");
console.log(elements[elements.length-1]);
</code>```

This code will provide you the correct output which you want.

Edited

If you want to get value of last element then use this:-

```<code>console.log(elements[elements.length-1].val());
</code>```

Note: But you can't get value directly from document.getElementsByClassName("notif_date"). Because this return multiple object of multiple class elements.

But if you want to get value of all the elements then you need to loop this.

Body:
This is my code from controller where I used looping to show this.

<input type="hidden" class="notif_date" value="'.$created_at.'">

the sample data of this are multiple dates: 2019-05-28 13:45:45

Now I'm trying the get the last date that will be shown using JavaScript.

Currently I have this code:

var last_date =  document.getElementsByClassName("notif_date");
console.log(last_date);

But this only gets the array of input types

So I tried to use last() and place like this console.log(last_date.last()); and this gives me an error like this

Uncaught TypeError: last_date.last is not a function

How can I get the last value of date using JavaScript?

Body:
To get last element you can use following code

let elements = document.getElementsByClassName("notif_date");
console.log(elements[elements.length-1]);

This code will provide you the correct output which you want.

Edited

If you want to get value of last element then use this:-

console.log(elements[elements.length-1].val());

Note: But you can't get value directly from document.getElementsByClassName("notif_date"). Because this return multiple object of multiple class elements.

But if you want to get value of all the elements then you need to loop this.


问:
getting windows user account (profiles) list
I'm trying to take names of all windows user accounts. my code is working but it prints unnecessary user account also,

here is the code I'm using,

```<code>Dim query As New SelectQuery("Win32_UserAccount")
Dim searcher As New ManagementObjectSearcher(query)
For Each envVar As ManagementObject In searcher.[Get]()
    Console.WriteLine(envVar("Name"))
Next
</code>```

Output:

```<code>Administrator
DefaultAccount
Guest
Sam
WDAGUtilityAccount
</code>```

Sam is the only user account I created on this PC. I can assume Administrator and Guest accounts come as default with windows. But DefaultAccount and WDAGUtilityAccount accounts are extremely unnecessary for printing in here.  How can I prevent those unnecessary accounts printing from this code

答:
As the Jimi's suggestion, I have updated my code by using Disabled property.

Win32_UserAccount class

```<code>Dim query As New SelectQuery("Win32_UserAccount")
Dim searcher As New ManagementObjectSearcher(query)
For Each envVar As ManagementObject In searcher.[Get]()
   If Not envVar("Disabled").ToString.ToUpper.Equals("TRUE") Then
       Console.WriteLine(envVar("Name"))
   End If
Next
</code>```

Body:
I'm trying to take names of all windows user accounts. my code is working but it prints unnecessary user account also,

here is the code I'm using,

Dim query As New SelectQuery("Win32_UserAccount")
Dim searcher As New ManagementObjectSearcher(query)
For Each envVar As ManagementObject In searcher.[Get]()
    Console.WriteLine(envVar("Name"))
Next

Output:

Administrator
DefaultAccount
Guest
Sam
WDAGUtilityAccount

Sam is the only user account I created on this PC. I can assume Administrator and Guest accounts come as default with windows. But DefaultAccount and WDAGUtilityAccount accounts are extremely unnecessary for printing in here.  How can I prevent those unnecessary accounts printing from this code

Body:
As the Jimi's suggestion, I have updated my code by using Disabled property.

Win32_UserAccount class

Dim query As New SelectQuery("Win32_UserAccount")
Dim searcher As New ManagementObjectSearcher(query)
For Each envVar As ManagementObject In searcher.[Get]()
   If Not envVar("Disabled").ToString.ToUpper.Equals("TRUE") Then
       Console.WriteLine(envVar("Name"))
   End If
Next


问:
I have a couple of Linux commands, which i want to run on windows machine. How to Run Linux commands from Python on Windows
I have some Linux commands which will generate token. I've automated those commands using OS library form Python on Linux machine. It is working fine.

But, When I try the same code in the windows it is returning nothing.

The following is the code I've tried.

```<code>uniqueKey = os.popen('echo -n kittu | base64')
data = uniqueKey.read()
print data
</code>```

in Linux I got the following output

```<code>a210dHU=
</code>```

in windows it is empty.

答:
Commands are specific to the OS. For example on Linux, ls lists files in a directory, while on Windows it's dir.

Windows has an echo like Linux but does not support the flag -n—the two commands are not related, only coinciding in name.

Windows also does not have a base64 command.

Nor does it use | to mean piping, though I believe PowerShell does.

Why use OS commands at all? Python supports base64 encoding natively:

```<code>uniqueKey = base64.b64encode('kittu')
</code>```

Body:
I have some Linux commands which will generate token. I've automated those commands using OS library form Python on Linux machine. It is working fine.

But, When I try the same code in the windows it is returning nothing.

The following is the code I've tried.

uniqueKey = os.popen('echo -n kittu | base64')
data = uniqueKey.read()
print data

in Linux I got the following output

a210dHU=

in windows it is empty.

Body:
Commands are specific to the OS. For example on Linux, ls lists files in a directory, while on Windows it's dir.

Windows has an echo like Linux but does not support the flag -n—the two commands are not related, only coinciding in name.

Windows also does not have a base64 command.

Nor does it use | to mean piping, though I believe PowerShell does.

Why use OS commands at all? Python supports base64 encoding natively:

uniqueKey = base64.b64encode('kittu')


问:
Thread Safe Accessing Enums in Java
I want to know that the following code can be used in multi-threaded environment thread safely. I hope to use Task class as an accessing layer.

```<code>public class Task {
    public static enum TaskList {

        TASK_A {

            @Override
            void doProcess() {
                System.out.println("processing task A");

            }
        },
        TASK_B {
            @Override
            void doProcess() {
                System.out.println("processing task B");

            }
        },
        TASK_C {
            @Override
            void doProcess() {
                System.out.println("processing task C");
            }
        };

        abstract void doProcess();
    }
}
</code>```

This is how it is going to be used.

```<code>public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                //following code will be executed in multiple threads.

                Task.TaskList task = Task.TaskList.TASK_A;
                task.doProcess();

            }
        });
        thread.start();
    }
</code>```

答:
Using enums has little to do with thread safety.

Your code (as presented here in the question) is thread-safe. But the following isn't:

```<code>public class Task {
    public static enum TaskList {

        TASK_A {
            int x = 0;

            @Override
            void doProcess() {
                x++;
                System.out.println("processing task A: " + x);

            }
        };

        abstract void doProcess();
    }
}
</code>```

As you see, it being an enum has no bearing on thread safety. What matters is whether the object (enum value in this case) has any internal state that can change without being properly synchronized, and whether everything that the actual code calls is thread-safe as well.

Title: Thread Safe Accessing Enums in Java

Body:
I want to know that the following code can be used in multi-threaded environment thread safely. I hope to use Task class as an accessing layer.

public class Task {
    public static enum TaskList {

        TASK_A {

            @Override
            void doProcess() {
                System.out.println("processing task A");

            }
        },
        TASK_B {
            @Override
            void doProcess() {
                System.out.println("processing task B");

            }
        },
        TASK_C {
            @Override
            void doProcess() {
                System.out.println("processing task C");
            }
        };

        abstract void doProcess();
    }
}

This is how it is going to be used.

public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                //following code will be executed in multiple threads.

                Task.TaskList task = Task.TaskList.TASK_A;
                task.doProcess();

            }
        });
        thread.start();
    }

Body:
Using enums has little to do with thread safety.

Your code (as presented here in the question) is thread-safe. But the following isn't:

public class Task {
    public static enum TaskList {

        TASK_A {
            int x = 0;

            @Override
            void doProcess() {
                x++;
                System.out.println("processing task A: " + x);

            }
        };

        abstract void doProcess();
    }
}

As you see, it being an enum has no bearing on thread safety. What matters is whether the object (enum value in this case) has any internal state that can change without being properly synchronized, and whether everything that the actual code calls is thread-safe as well.


问:
I want to compare 2 hash sets and take out the differences
I have 2 hash sets like this.

```<code>Hash_1 = {1, 2, 3, 4, 5}
Hash_2 = {4, 5, 6, 7, 8}
</code>```

I am using C#

I want to compare those two sets and want to get the output like

```<code>Hash_3 = {1, 2, 3, 6, 7, 8}
</code>```

答:
Or you could use SymmetricExceptWith

Modifies the current HashSet<T> object to contain only elements that
are present either in that object or in the specified collection, but
not both.

```<code>var h1 = new HashSet<int>() { 1, 2, 3, 4, 5 };
var h2 = new HashSet<int>() { 4, 5, 6, 7, 8 };

h1.SymmetricExceptWith(h2);

Console.WriteLine(string.Join(",", h1));
</code>```

Output

```<code>1,2,3,7,6,8
</code>```

Internally it just uses

```<code>foreach (T item in other)
{
   if (!Remove(item))
   {
      AddIfNotPresent(item);
   }
}
</code>```

Source Code here

Body:
I have 2 hash sets like this.

Hash_1 = {1, 2, 3, 4, 5}
Hash_2 = {4, 5, 6, 7, 8}

I am using C#

I want to compare those two sets and want to get the output like

Hash_3 = {1, 2, 3, 6, 7, 8}

Body:
Or you could use SymmetricExceptWith

Modifies the current HashSet<T> object to contain only elements that
are present either in that object or in the specified collection, but
not both.

var h1 = new HashSet<int>() { 1, 2, 3, 4, 5 };
var h2 = new HashSet<int>() { 4, 5, 6, 7, 8 };

h1.SymmetricExceptWith(h2);

Console.WriteLine(string.Join(",", h1));

Output

1,2,3,7,6,8

Internally it just uses

foreach (T item in other)
{
   if (!Remove(item))
   {
      AddIfNotPresent(item);
   }
}

Source Code here


问:
In Ruby on Rails, render 'shared/score', :locals => { :score => @foo.score } will not pass in the local?
Maybe I missed something in http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials

It seems that to render a partial, we can use

```<code>render 'shared/score'
</code>```

but the next section talks about locals

```<code>render :partial => 'bar', :locals => { :score => @foo.score }
</code>```

But what about the first form?

```<code>render 'shared/score', :locals => { :score => @foo.score }
</code>```

The line above will not pass in the locals, why?

It seems like it has to be

```<code>render :partial => 'shared/score', :locals => { :score => @foo.score }
</code>```

but why is that?  (I am using Rails 3.0.6)

答:
You actually want:

```<code>render 'shared/score', { :score => @foo.score }
</code>```

Explanation

You can look at this for their source code on render.

http://api.rubyonrails.org/classes/ActionView/Rendering.html#method-i-render

If you see that if the first parameter is NOT a hash, it will default to that being the name of the partial, and pass the second paramater as locals.

The catch is that it wants the locals of in the 2nd paramater. :locals => {:score => @foo.score} may seem right at first, but you actually want: {:score=> @foo.score}.

The reason for this is that it sets the :locals option for the _render_partial method to the second paramater. So if you were to do it your way, it would actually look like:

```<code>:locals => {:locals => {:score=>@foo.score}}
</code>```

Which doesn't make much sense.

Body:
Maybe I missed something in http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials

It seems that to render a partial, we can use

render 'shared/score'

but the next section talks about locals

render :partial => 'bar', :locals => { :score => @foo.score }

But what about the first form?

render 'shared/score', :locals => { :score => @foo.score }

The line above will not pass in the locals, why?

It seems like it has to be

render :partial => 'shared/score', :locals => { :score => @foo.score }

but why is that?  (I am using Rails 3.0.6)

Body:
You actually want:

render 'shared/score', { :score => @foo.score }

Explanation

You can look at this for their source code on render.

http://api.rubyonrails.org/classes/ActionView/Rendering.html#method-i-render

If you see that if the first parameter is NOT a hash, it will default to that being the name of the partial, and pass the second paramater as locals.

The catch is that it wants the locals of in the 2nd paramater. :locals => {:score => @foo.score} may seem right at first, but you actually want: {:score=> @foo.score}.

The reason for this is that it sets the :locals option for the _render_partial method to the second paramater. So if you were to do it your way, it would actually look like:

:locals => {:locals => {:score=>@foo.score}}

Which doesn't make much sense.


问:
AzureDevops Agent - Allow Connection to ADO and Local Nuget feed
Currently we have a build agent which goes via our corporate proxy to communicate with ADO and the public Nuget Repositories.

We now have a need to also pull Nuget packages from our local nuget server.

The problem is, we have the proxy set so that the agent can do what it has always done, and have now added our local nuget feed host to the .proxybypass file.

It doesn't appear that this file is being honored, and is attempting to go via the proxy, and so we are getting a 403 forbidden error from our proxy as it is not configured for local traffic.

Has anyone else come across this scenario, or know of a way around this?

答:
AzureDevops Agent - Allow Connection to ADO and Local Nuget feed

Just you said, it seems nuget not honor the setting in the .proxybypass file.

To resolve this issue, you can try to add proxy settings into Nuget.Config file on your build agent server, like following:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
    <config>
        <add key="http_proxy" value="http://proxy_hostname_or_ip:3128" />
        <add key="https_proxy" value="http://proxy_hostname_or_ip:3128" />
    </config>

  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </packageSources>

</configuration>
</code>```

You can check the Nuget Proxy Settings and this thread for some more details.

Hope this helps.

Body:
AzureDevops Agent - Allow Connection to ADO and Local Nuget feed

Just you said, it seems nuget not honor the setting in the .proxybypass file.

To resolve this issue, you can try to add proxy settings into Nuget.Config file on your build agent server, like following:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <config>
        <add key="http_proxy" value="http://proxy_hostname_or_ip:3128" />
        <add key="https_proxy" value="http://proxy_hostname_or_ip:3128" />
    </config>

  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </packageSources>

</configuration>

You can check the Nuget Proxy Settings and this thread for some more details.

Hope this helps.


问:
Can't customize the _URL in flowers_tf_lite.ipynb colab
I'm using this Colab to retrain a classification image model with my own data hosted on google drive.
But apparently there is a issue with URL. it just say 8192/Unknown - 0s 0us/step. I have impression that it doesn't arrive to download data via the link. Help me please. Excuse me for bad english

The code:

```<code>import tensorflow as tf

import os

_URL = "https://drive.google.com/uc?
 export=download&confirm=IbID&id=1cyPjY_wPxFpt7cO8Q1EaeexNzLzpTtpD"

 zip_file = tf.keras.utils.get_file(origin=_URL,
                               fname="panel.tgz",
                               extract=True)

base_dir = os.path.join(os.path.dirname(zip_file), 'panel')
</code>```

The result:

```<code>Downloading data from https://drive.google.com/uc?
export=download&confirm=IbID&id=1cyPjY_wPxFpt7cO8Q1EaeexNzLzpTtpD
8192/Unknown - 0s 0us/step
</code>```

答: This URL can't download. It is Cloud file link.  In your case, the test file should be upload in FTP.</p>

Body:
I'm using this Colab to retrain a classification image model with my own data hosted on google drive.
But apparently there is a issue with URL. it just say 8192/Unknown - 0s 0us/step. I have impression that it doesn't arrive to download data via the link. Help me please. Excuse me for bad english

The code:

import tensorflow as tf

import os

_URL = "https://drive.google.com/uc?
 export=download&confirm=IbID&id=1cyPjY_wPxFpt7cO8Q1EaeexNzLzpTtpD"

 zip_file = tf.keras.utils.get_file(origin=_URL,
                               fname="panel.tgz",
                               extract=True)

base_dir = os.path.join(os.path.dirname(zip_file), 'panel')

The result:

Downloading data from https://drive.google.com/uc?
export=download&confirm=IbID&id=1cyPjY_wPxFpt7cO8Q1EaeexNzLzpTtpD
8192/Unknown - 0s 0us/step


问:
How to config web socket with Nginx server?
I am running node.js and socket.io, using Nginx server.
 Here is my /etc/nginx/conf.d/site.conf:

```<code>server {
   listen 443;
   server_name localhost;

   client_max_body_size 20M;

   location /websocket/ {
               root ChatWithSocket;
               index index.html index.htm index.nginx-debian.html;
               proxy_pass http://localhost:4000;
               proxy_http_version 1.1;
               proxy_set_header Upgrade $http_upgrade;
               proxy_set_header Connection 'upgrade';
               proxy_set_header Host $host;
               proxy_cache_bypass $http_upgrade;
 }

}
</code>```

Here is my /ChatWithSocket/index.js:

```<code>var express = require('express');
var socket = require('socket.io');

// App setup
var app = express();
var server = app.listen(4000, function(){
    console.log('listening for requests on port 4000,');
});

// Static files
app.use(express.static('public'));

//Socket setup
var io = socket(server);

io.on('connection', function(socket){
    console.log('made socket connection', socket.id);

    //Show diconnect log when we refresh page
    socket.on('disconnect', function(){
        console.log('The socket disconnected');
    });

    // Handle chat event
    socket.on('chat', function(data){
        // console.log(data);
        io.sockets.emit('chat', data);
    });

    // Handle typing event
    socket.on('typing', function(data){
        socket.broadcast.emit('typing', data);
    });
});
</code>```

Here is my /ChatWithSocket/public/chat.js:

```<code>// Make connection
var socket = io.connect('http://localhost:4000');

// Query DOM
var message = document.getElementById('message'),
      handle = document.getElementById('handle'),
      btn = document.getElementById('send'),
      output = document.getElementById('output'),
      feedback = document.getElementById('feedback'),
      chatWindow = document.getElementById('chat-window');
......................................................
</code>```

T

I cannot run with address https://localhost/websocket/.I have followed many online guides say about Nginx + WebSocket, but I don't know where I made a mistake. Please help me.

答:
Use this config and try again. You do not need to update proxy_pass localhost:4000 --> proxy_pass 40.115.176.82:4000. This is incorrect. Issue is with the client.

```<code>map $http_upgrade $connection_upgrade {
  default upgrade;
  ''      close;
}

server {
   listen 443;
   server_name localhost;

   client_max_body_size 20M;

   # smart-shingi log_format data >>
   if ($http_token ~ "(\S{10})$") {
       set $h_token $1;
   }
   # << smart-shingi log_format data

   error_page  500 502 503 504  /50x.html;
   location = /50x.html {
       root  /usr/share/nginx/html;
   }

   location / {
       deny  all;
   }

   location ~ /\. {
       deny  all;
   }

   location = /favicon.ico {
       error_page     404 = @favicon;
       access_log     off;
       log_not_found  off;
   }

   location @favicon {
       empty_gif;
       access_log     off;
       log_not_found  off;
   }

   location /drive/ {
       root   /usr/share/nginx/webapp;
       index  login.html;
       allow  all;
   }

   location /websocket/ {
    proxy_pass http://localhost:4000;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;  # pass the host header - http://wiki$
    proxy_http_version 1.1;  # recommended with keepalive connections $

    ### WebSocket proxying - from http://nginx.org/en/docs/http/websocke$
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
}

   location ~ \.txt {
       root    /usr/share/nginx/androidApp;
   }
}
</code>```

And in client try

```<code>// Make connection
var socket = io('https://40.115.176.82', {path: ' /websocket/'})

// Query DOM
var message = document.getElementById('message'),
      handle = document.getElementById('handle'),
      btn = document.getElementById('send'),
      output = document.getElementById('output'),
      feedback = document.getElementById('feedback'),
      chatWindow = document.getElementById('chat-window');
</code>```

Also check which version of socketio you are using.

Body:
I am running node.js and socket.io, using Nginx server.
 Here is my /etc/nginx/conf.d/site.conf:

server {
   listen 443;
   server_name localhost;

   client_max_body_size 20M;

   location /websocket/ {
               root ChatWithSocket;
               index index.html index.htm index.nginx-debian.html;
               proxy_pass http://localhost:4000;
               proxy_http_version 1.1;
               proxy_set_header Upgrade $http_upgrade;
               proxy_set_header Connection 'upgrade';
               proxy_set_header Host $host;
               proxy_cache_bypass $http_upgrade;
 }

}

Here is my /ChatWithSocket/index.js:

var express = require('express');
var socket = require('socket.io');

// App setup
var app = express();
var server = app.listen(4000, function(){
    console.log('listening for requests on port 4000,');
});

// Static files
app.use(express.static('public'));

//Socket setup
var io = socket(server);

io.on('connection', function(socket){
    console.log('made socket connection', socket.id);

    //Show diconnect log when we refresh page
    socket.on('disconnect', function(){
        console.log('The socket disconnected');
    });

    // Handle chat event
    socket.on('chat', function(data){
        // console.log(data);
        io.sockets.emit('chat', data);
    });

    // Handle typing event
    socket.on('typing', function(data){
        socket.broadcast.emit('typing', data);
    });
});

Here is my /ChatWithSocket/public/chat.js:

// Make connection
var socket = io.connect('http://localhost:4000');

// Query DOM
var message = document.getElementById('message'),
      handle = document.getElementById('handle'),
      btn = document.getElementById('send'),
      output = document.getElementById('output'),
      feedback = document.getElementById('feedback'),
      chatWindow = document.getElementById('chat-window');
......................................................

T

I cannot run with address https://localhost/websocket/.I have followed many online guides say about Nginx + WebSocket, but I don't know where I made a mistake. Please help me.

Body:
Use this config and try again. You do not need to update proxy_pass localhost:4000 --> proxy_pass 40.115.176.82:4000. This is incorrect. Issue is with the client.

map $http_upgrade $connection_upgrade {
  default upgrade;
  ''      close;
}

server {
   listen 443;
   server_name localhost;

   client_max_body_size 20M;

   # smart-shingi log_format data >>
   if ($http_token ~ "(\S{10})$") {
       set $h_token $1;
   }
   # << smart-shingi log_format data

   error_page  500 502 503 504  /50x.html;
   location = /50x.html {
       root  /usr/share/nginx/html;
   }

   location / {
       deny  all;
   }

   location ~ /\. {
       deny  all;
   }

   location = /favicon.ico {
       error_page     404 = @favicon;
       access_log     off;
       log_not_found  off;
   }

   location @favicon {
       empty_gif;
       access_log     off;
       log_not_found  off;
   }

   location /drive/ {
       root   /usr/share/nginx/webapp;
       index  login.html;
       allow  all;
   }

   location /websocket/ {
    proxy_pass http://localhost:4000;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;  # pass the host header - http://wiki$
    proxy_http_version 1.1;  # recommended with keepalive connections $

    ### WebSocket proxying - from http://nginx.org/en/docs/http/websocke$
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
}

   location ~ \.txt {
       root    /usr/share/nginx/androidApp;
   }
}

And in client try

// Make connection
var socket = io('https://40.115.176.82', {path: ' /websocket/'})

// Query DOM
var message = document.getElementById('message'),
      handle = document.getElementById('handle'),
      btn = document.getElementById('send'),
      output = document.getElementById('output'),
      feedback = document.getElementById('feedback'),
      chatWindow = document.getElementById('chat-window');

Also check which version of socketio you are using.