问:
iOS UITabBarController created programmatically is not displaying its "More" navigation controller
I want to create an iOS UITabBarController with 6 child view controllers, which is just enough children to cause the "More" tab to appear on iPhone 11 Pro Max in portrait orientation.  As an experiment I'd like to do this programmatically in Swift, without making any modification to the Main.storyboard file of my Xcode project.  The following is my entire ViewController.swift file, using the default "Single View App" Xcode 11.5 on macOS Catalina 10.15.4.

```<code>import UIKit;

class ViewController: UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad();
        // Do any additional setup after loading the view.

        struct Band {
            let badge: String;
            let color: UIColor;
            let systemItem: UITabBarItem.SystemItem;
        }

        let bands: [Band] = [
            Band(badge: "0", color: .red,    systemItem: .bookmarks),
            Band(badge: "1", color: .orange, systemItem: .contacts),
            Band(badge: "2", color: .yellow, systemItem: .downloads),
            Band(badge: "3", color: .green,  systemItem: .favorites),
            Band(badge: "4", color: .blue,   systemItem: .featured),
            Band(badge: "5", color: .purple, systemItem: .history)
        ];

        let kids: [UIViewController] = bands.map {
            let viewController: UIViewController = UIViewController();
            viewController.tabBarItem = UITabBarItem(tabBarSystemItem: $0.systemItem, tag: Int($0.badge)!);
            viewController.tabBarItem.badgeValue = $0.badge;
            viewController.view.backgroundColor = $0.color;
            return viewController;
        }

        //Make sure all 6 kids are present and okay.
        kids.forEach {print($0.tabBarItem.tag, $0.tabBarItem.badgeValue!);}

        setViewControllers(kids, animated: true);  //Why only getting 4 of 6 in portrait?
        print("viewControllers!.count = \(viewControllers!.count)");
    }
}
</code>```

viewControllers!.count should be 6.  But when I run on the iPhone 11 Pro Max simulator in portrait orientation, viewControllers!.count is 4 and I see tabs for only the first 4 children, with no "More" tab.  (When I run the project on an iPhone 11 Pro Max simulator that is already in landscape orientation, viewControllers!.count is 6 and I see tabs for all 6 children.)  The same thing is happening on my iPhone 8 Plus simulator.  Why am I getting only 4 out of 6 with no "More" in portrait, and is it possible to do what I'm trying to do just by modifying the ViewController.swift file?  Thank you in advance.

答:
Sounds like you started with a default Single View app and then changed your class from:

```<code>class ViewController: UIViewController {
</code>```

to:

```<code>class ViewController: UITabBarController {
</code>```

which won't work.

Assuming that's the case:

delete the View Controller from your Storyboard

add a UITabBarController

delete the two "default" view controllers that come with it

set the Custom Class of the newly added tab bar controller to ViewController

That should do it.

Side note: I would change the class name...

```<code>class MyTabBarController: UITabBarController {
</code>```

Body:
I want to create an iOS UITabBarController with 6 child view controllers, which is just enough children to cause the "More" tab to appear on iPhone 11 Pro Max in portrait orientation.  As an experiment I'd like to do this programmatically in Swift, without making any modification to the Main.storyboard file of my Xcode project.  The following is my entire ViewController.swift file, using the default "Single View App" Xcode 11.5 on macOS Catalina 10.15.4.

import UIKit;

class ViewController: UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad();
        // Do any additional setup after loading the view.

        struct Band {
            let badge: String;
            let color: UIColor;
            let systemItem: UITabBarItem.SystemItem;
        }

        let bands: [Band] = [
            Band(badge: "0", color: .red,    systemItem: .bookmarks),
            Band(badge: "1", color: .orange, systemItem: .contacts),
            Band(badge: "2", color: .yellow, systemItem: .downloads),
            Band(badge: "3", color: .green,  systemItem: .favorites),
            Band(badge: "4", color: .blue,   systemItem: .featured),
            Band(badge: "5", color: .purple, systemItem: .history)
        ];

        let kids: [UIViewController] = bands.map {
            let viewController: UIViewController = UIViewController();
            viewController.tabBarItem = UITabBarItem(tabBarSystemItem: $0.systemItem, tag: Int($0.badge)!);
            viewController.tabBarItem.badgeValue = $0.badge;
            viewController.view.backgroundColor = $0.color;
            return viewController;
        }

        //Make sure all 6 kids are present and okay.
        kids.forEach {print($0.tabBarItem.tag, $0.tabBarItem.badgeValue!);}

        setViewControllers(kids, animated: true);  //Why only getting 4 of 6 in portrait?
        print("viewControllers!.count = \(viewControllers!.count)");
    }
}

viewControllers!.count should be 6.  But when I run on the iPhone 11 Pro Max simulator in portrait orientation, viewControllers!.count is 4 and I see tabs for only the first 4 children, with no "More" tab.  (When I run the project on an iPhone 11 Pro Max simulator that is already in landscape orientation, viewControllers!.count is 6 and I see tabs for all 6 children.)  The same thing is happening on my iPhone 8 Plus simulator.  Why am I getting only 4 out of 6 with no "More" in portrait, and is it possible to do what I'm trying to do just by modifying the ViewController.swift file?  Thank you in advance.

Body:
Sounds like you started with a default Single View app and then changed your class from:

class ViewController: UIViewController {

to:

class ViewController: UITabBarController {

which won't work.

Assuming that's the case:

delete the View Controller from your Storyboard

add a UITabBarController

delete the two "default" view controllers that come with it

set the Custom Class of the newly added tab bar controller to ViewController

That should do it.

Side note: I would change the class name...

class MyTabBarController: UITabBarController {


来源: stackexchange

问:
Flask message flashing fails across redirects
I'm currently working on a project using Flask and Google App Engine. Calling get_flashed_messages() returns empty when I flash a message then use a redirect():

```<code>@views.route('/todo/add', methods=["POST"])
def add_todo():
    flash('hey')
    return redirect(url_for('todo_list'))
</code>```

However, if I comment out

```<code># SERVER_NAME = 'localhost'
</code>```

then it seems to work fine. My problem is that I have to use subdomains so I need SERVER_NAME to be set.

What is the deal?

答:
I got it!
The trick is to set server name to something with dots.

So 'localhost' became 'app.local' and app.local should be added to /etc/hosts, pointing to the same address as localhost.

From the docs:

Please keep in mind that not only
  Flask has the problem of not knowing
  what subdomains are, your web browser
  does as well. Most modern web browsers
  will not allow cross-subdomain cookies
  to be set on a server name without
  dots in it. So if your server name is
  'localhost' you will not be able to
  set a cookie for 'localhost' and every
  subdomain of it. Please chose a
  different server name in that case,
  like 'myapplication.local' and add
  this name + the subdomains you want to
  use into your host config or setup a
  local bind.

ContentLicense: CC BY-SA 3.0

Body:
I'm currently working on a project using Flask and Google App Engine. Calling get_flashed_messages() returns empty when I flash a message then use a redirect():

@views.route('/todo/add', methods=["POST"])
def add_todo():
    flash('hey')
    return redirect(url_for('todo_list'))

However, if I comment out

# SERVER_NAME = 'localhost'

then it seems to work fine. My problem is that I have to use subdomains so I need SERVER_NAME to be set.

What is the deal?


问:
WebView page not available - “Upi:// ”

I have a shopping website with base on WordPress with Woo-commerce, and installed UPI Payment Plugin. and also I have make Android APP for my website using Web View.

****Problem****

WebView everything worked correctly but I used UPI payment link in one page to redirect to upi payments ("upi://pay?pn=DevShop&pa=eshop@kotak&tr=40766&tn=OrderID40766&am=1149&cu=INR") like this link and I'm getting ERR_UNKNOWN_URL_SCHEME error

I want My UPI Payment Link as above when clicked it open in default UPI APP like BHIM, PayTM, PhonePe or etc.. and Rest will handle through the above apps. following are the links of targeted apps.

https://play.google.com/store/apps/details?id=com.google.android.apps.nbu.paisa.user

https://play.google.com/store/apps/details?id=in.org.npci.upiapp

https://play.google.com/store/apps/details?id=net.one97.paytm

https://play.google.com/store/apps/details?id=com.phonepe.app

https://play.google.com/store/apps/details?id=com.mobikwik_new

https://play.google.com/store/apps/details?id=com.freecharge.android

Following is my Code in MainActivity.java

```<code>package com.shop.dev;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

  private WebView myWebView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      myWebView = (WebView) findViewById(R.id.webView);
      WebSettings webSettings = myWebView.getSettings();
      webSettings.setJavaScriptEnabled(true);
      webSettings.setAppCacheEnabled(true);
      myWebView.loadUrl("http://192.168.1.14/mzdec");
      myWebView.setWebViewClient(new WebViewClient());
  }

  @Override
  public void onBackPressed() {
      if(myWebView.canGoBack()) {
          myWebView.goBack();
      } else {
          super.onBackPressed();
      }
  }
}
</code>```

Following is my Code in AndroidManifest.xml

```<code><uses-permission android:name="android.permission.INTERNET"></uses-permission>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

<application    android:allowBackup="true"    android:icon="@mipmap/ic_launcher"    android:label="@string/app_name"    android:roundIcon="@mipmap/ic_launcher_round"    android:supportsRtl="true"    android:usesCleartextTraffic="true"    android:theme="@style/AppTheme">

<activity android:name=".MainActivity">

    <intent-filter>

        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />

    </intent-filter>

</activity>

</application>
</code>```

Help to resolve the Error.

Following are the Error When Payment Made via UPI Link.

答:
i'm sharing what worked for me. Hope the same with you. Added some code to the same that you've posted. Look for it within the webview client.</p>

```<code>public class MainActivity extends AppCompatActivity {
    private WebView myWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      myWebView = (WebView) findViewById(R.id.webView);
      WebSettings webSettings = myWebView.getSettings();
      webSettings.setJavaScriptEnabled(true);
      webSettings.setAppCacheEnabled(true);
      myWebView.loadUrl("http://192.168.1.14/mzdec");
      myWebView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView wv, String url) {
                if (url.startsWith("upi:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onBackPressed() {
        if(myWebView.canGoBack()) {
            myWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: WebView page not available - “Upi:// ”

Body:
I have a shopping website with base on WordPress with Woo-commerce, and installed UPI Payment Plugin. and also I have make Android APP for my website using Web View.

****Problem****

WebView everything worked correctly but I used UPI payment link in one page to redirect to upi payments ("upi://pay?pn=DevShop&pa=eshop@kotak&tr=40766&tn=OrderID40766&am=1149&cu=INR") like this link and I'm getting ERR_UNKNOWN_URL_SCHEME error

I want My UPI Payment Link as above when clicked it open in default UPI APP like BHIM, PayTM, PhonePe or etc.. and Rest will handle through the above apps. following are the links of targeted apps.

https://play.google.com/store/apps/details?id=com.google.android.apps.nbu.paisa.user

https://play.google.com/store/apps/details?id=in.org.npci.upiapp

https://play.google.com/store/apps/details?id=net.one97.paytm

https://play.google.com/store/apps/details?id=com.phonepe.app

https://play.google.com/store/apps/details?id=com.mobikwik_new

https://play.google.com/store/apps/details?id=com.freecharge.android

Following is my Code in MainActivity.java

package com.shop.dev;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

  private WebView myWebView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      myWebView = (WebView) findViewById(R.id.webView);
      WebSettings webSettings = myWebView.getSettings();
      webSettings.setJavaScriptEnabled(true);
      webSettings.setAppCacheEnabled(true);
      myWebView.loadUrl("http://192.168.1.14/mzdec");
      myWebView.setWebViewClient(new WebViewClient());
  }

  @Override
  public void onBackPressed() {
      if(myWebView.canGoBack()) {
          myWebView.goBack();
      } else {
          super.onBackPressed();
      }
  }
}

Following is my Code in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

<application    android:allowBackup="true"    android:icon="@mipmap/ic_launcher"    android:label="@string/app_name"    android:roundIcon="@mipmap/ic_launcher_round"    android:supportsRtl="true"    android:usesCleartextTraffic="true"    android:theme="@style/AppTheme">

<activity android:name=".MainActivity">

    <intent-filter>

        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />

    </intent-filter>

</activity>

</application>

Help to resolve the Error.

Following are the Error When Payment Made via UPI Link.

Body:
i'm sharing what worked for me. Hope the same with you. Added some code to the same that you've posted. Look for it within the webview client.

public class MainActivity extends AppCompatActivity {
    private WebView myWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      myWebView = (WebView) findViewById(R.id.webView);
      WebSettings webSettings = myWebView.getSettings();
      webSettings.setJavaScriptEnabled(true);
      webSettings.setAppCacheEnabled(true);
      myWebView.loadUrl("http://192.168.1.14/mzdec");
      myWebView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView wv, String url) {
                if (url.startsWith("upi:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onBackPressed() {
        if(myWebView.canGoBack()) {
            myWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}


问:
Docker: failed to start daemon: error while opening volume store metadata database: timeout
When I try to run Docker:

```<code>sudo dockerd
</code>```

I get this exception:

failed to start daemon: error while opening volume store metadata
  database: timeout

What I've tried but didn't help:

```<code>ps axf | grep docker | grep -v grep | awk '{print "kill -9 " $1}' | sudo sh
</code>```

答: The problem was that I had two instances of Docker running. I solved that by killing them and then started docker again using systemctl start docker

Body:
When I try to run Docker:

sudo dockerd

I get this exception:

failed to start daemon: error while opening volume store metadata
  database: timeout

What I've tried but didn't help:

ps axf | grep docker | grep -v grep | awk '{print "kill -9 " $1}' | sudo sh


问:
window.renderCustomMView is not a function in React
```<code>class Pop extends Component{
     constructor(props){
         super(props);
         window.renderCustomMView = this.renderCustomMView.bind(this);

         }

     renderCustomMView(){
      ....some code
     }
}

const Popup = ()=>{
window.renderCustomMView();
}

export {Popup};
</code>```

```<code>import {Popup} from 'path/to/parent';

class Video extends Component{
     constructor(props){
         super(props)
         }

     callingFunction(){
      Popup();
     }
}
</code>```

When I import Popup it's imported. Then I call this function, it says window.renderCustomMView is not a function.

答:
You'd have to instantiate Pop somewhere  so that window.renderCustomMView = this.renderCustomMView.bind(this); is run.

Of course, there's not an obvious way to do that here, because you typically organize differently in React. You should make Popup a child component of Video and then use standard React techniques to update the Popup state when Video wants to trigger it.

Body:
class Pop extends Component{
     constructor(props){
         super(props);
         window.renderCustomMView = this.renderCustomMView.bind(this);

         }

     renderCustomMView(){
      ....some code
     }
}

const Popup = ()=>{
window.renderCustomMView();
}

export {Popup};

import {Popup} from 'path/to/parent';

class Video extends Component{
     constructor(props){
         super(props)
         }

     callingFunction(){
      Popup();
     }
}

When I import Popup it's imported. Then I call this function, it says window.renderCustomMView is not a function.


问:
Help with traversing a complex XSD document
My ultimate goal is to traverse an XSD document and display a TreeView (Silverlight 4.0) representation of all the XML elements in order as described by the XSD document.

So, if I had an XSD file that describes a set of elements that would look like

```<code><a>
  <b att1="foo" att2="foo2"/>
    <c />
  <d />
</a>
</code>```

then I would want to display a TreeView like:

```<code> a
 |_b
 | |_att1
 | |_att2
 | |_c
 |_d
</code>```

I don't care if the XSD document allows for multiple occurrences or optional elements and attributes. I want to list elements that occurr multiple times only once, and all required and optional elements/attributes should appear. For example a schema that allows

```<code><a>
  <b att1="foo" att2="this one was optional"/>
    <c />
  <d />
  <d />
</a>
</code>```

should still return the same TreeView I showed previously.

However, I am having trouble understanding the best way to go about doing this. I started to use an XmlReader to run through the xsd document, but then realized it can become complicated dealing with the references across files... e.g. elements that have "ref" or "type" attributes....or "extension" elements.

So, I created a WCF service so I could use the XmlSchema class and see what was there. I wrote the following code:

```<code>XmlTextReader reader = new XmlTextReader("http://myXsdLocation.com/SalesOrder.xsd");
XmlSchema myschema = XmlSchema.Read(reader, ValidationCallback);
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(myschema);
schemaSet.Compile();
</code>```

Debugging through that code, the schemaSet count increases to 8 after schemaSet.Compile(), which I assume means that with all the "include" references in the initial xsd file, as well as in the referenced xsd files, there are 8 xsd files altogether for the initial one to make sense.

But from noodling around in the schemaSet objects, I haven't found a way to elegantly traverse through the entire schema as if it were one giant XSD file.

Does anyone know a way to accomplish what I am trying to do? I just want to be able to pull each element in the order it would appear as one giant XSD file, and any attributes attached to the element and give the data to my TreeView. I'm okay with with the UI stuff, but need to know if it's better to write my own parser with the XmlReader or to use the XmlSchema and related classes. I've found similar questions throughout StackOverflow, but most of it referenced code gen tools or are unrelated to what I am looking for. I want to develop something to take any xsd and produce the tree I mentioned earlier.

答:
I'm not familiar with the XmlSchema API you refer to.

Another way to tackle this would be to use the Saxon schema processor to generate an SCM file, which is an XML representation of the schema component model - effectively the compiled schema in "canonical" form, which is an XML representation that is much easier to navigate than the raw XSD files.

Body:
My ultimate goal is to traverse an XSD document and display a TreeView (Silverlight 4.0) representation of all the XML elements in order as described by the XSD document.

So, if I had an XSD file that describes a set of elements that would look like

    <c />
  <d />

then I would want to display a TreeView like:

 a
 |_b
 | |_att1
 | |_att2
 | |_c
 |_d

I don't care if the XSD document allows for multiple occurrences or optional elements and attributes. I want to list elements that occurr multiple times only once, and all required and optional elements/attributes should appear. For example a schema that allows

    <c />
  <d />
  <d />

should still return the same TreeView I showed previously.

However, I am having trouble understanding the best way to go about doing this. I started to use an XmlReader to run through the xsd document, but then realized it can become complicated dealing with the references across files... e.g. elements that have "ref" or "type" attributes....or "extension" elements.

So, I created a WCF service so I could use the XmlSchema class and see what was there. I wrote the following code:

XmlTextReader reader = new XmlTextReader("http://myXsdLocation.com/SalesOrder.xsd");
XmlSchema myschema = XmlSchema.Read(reader, ValidationCallback);
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(myschema);
schemaSet.Compile();

Debugging through that code, the schemaSet count increases to 8 after schemaSet.Compile(), which I assume means that with all the "include" references in the initial xsd file, as well as in the referenced xsd files, there are 8 xsd files altogether for the initial one to make sense.

But from noodling around in the schemaSet objects, I haven't found a way to elegantly traverse through the entire schema as if it were one giant XSD file.

Does anyone know a way to accomplish what I am trying to do? I just want to be able to pull each element in the order it would appear as one giant XSD file, and any attributes attached to the element and give the data to my TreeView. I'm okay with with the UI stuff, but need to know if it's better to write my own parser with the XmlReader or to use the XmlSchema and related classes. I've found similar questions throughout StackOverflow, but most of it referenced code gen tools or are unrelated to what I am looking for. I want to develop something to take any xsd and produce the tree I mentioned earlier.


问:
Alternatives to Object-Oriented Programming?
OOP is probably the most used programming paradigm in today’s software design. My question is – what other paradigm(s) can compete with it and can stand in the place of OOP? To clarify that question, I’m not asking about what other paradigms there are. There are many of them, but I’d like to know which one…

Has been used in practice, not only in theory.

Can compete with OOP, so it can be used in a large project with a minimum of pain.

Can be used to develop a desktop app with business logic, databases, and so on.

Is not used alongside OOP, but as a replacement for OOP.

And if there is any, what are the pros/cons of it, why it is better/worse than OOP, what languages are the best to use it, what about using it in popular languages, has it any design patterns, and can it totally replace OOP?

答:
First of all please note that many of the programming languages currently in use (especially "higher level languages") are multi-paradigm. That means you are never building programs which are purely OOP (except if you use Smalltalk or Eiffel to build your big projects maybe).

Have a look at PHP for instance:

Has many elements of OOP (since version 5)

Was mostly procedural before

Has elements of declarative programming (e.g. the array functions)

Implemented many elements of functional programming (since version 5.4)

Basically PHP is gluing a lot of different paradigms together (and is a "glue language" itself).

Also Java implements a lot of concepts which are not from the Object-Oriented paradigm (e.g. from functional programming).

Have a look on the list of programming languages by type in Wikipedia: https://en.wikipedia.org/wiki/List_of_programming_languages_by_type#Imperative_languages (not 100% accurate).

Functional programming (subset of declerative programming)

Wideley used in practice (it became part of glued languages like PHP, also Java and many others have implemented concepts of functional programming)

Many ideas originate in LISP which is definitely worth a look

You can build whole applications e.g. with Haskell therefore it can "replace" OOP

Procedural programming

C (as a mostly procedural language) is still one of the most widely used languages

Many modern glue-languages were procedural in the beginning

Still many programs are mostly procedural (so if you want it can "replace" OOP)

Logical programming

Most prominent example is Prolog. This is used for specific tasks that benefit from rule-based logical queries

Can not "replace" OOP in terms of building a large project but may replace it in other terms

Declarative / Domain-specific languages in general

Using SQL in your projects? Then they are not purely OOP, SQL is essentially declarative.

Many domain-specific languages (like CSS) are declarative

Imperative programming in general

Tons of applications are not "object-oriented" but simply written in imperative style (e.g. assembly)

Look here for a great thread: https://softwareengineering.stackexchange.com/questions/117092/whats-the-difference-between-imperative-procedural-and-structured-programming

This list is not complete it shall just give an idea. Just note that you usually are using a lot of different paradigms when writing a big application and even each language you are using is implementing multiple paradigms.

OOP is usually considered a good choice for structuring large, complex relationships when modelling data. It is not always the paradigm to go with for many other tasks.


问:
How to assign default value to column variable if column value is coming as null
Hi I want to assign default value to column variable if value from select query for that variable is coming as null.

```<code>    @Entity
    @Table(name = "CDP_ALERTS")
    public class Country {

       @Column(name = "alert_reported_time")
    private String alertReportedTime;

    @Column(name = "unique_id")
    private String uniqueTrxId;

    @Column(name = "status_data")
    private String status;

public String getAlertReportedTime() {
        return alertReportedTime;
    }

    public void setAlertReportedTime(String alertReportedTime) {
        this.alertReportedTime = alertReportedTime;
    }
public String getUniqueTrxId() {
        return uniqueTrxId;
    }

    public void setUniqueTrxId(String uniqueTrxId) {
        this.uniqueTrxId = uniqueTrxId;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
    }
</code>```

Here status_data column value is coming as null sometime.
below is the select query.

```<code>@Query( "SELECT a FROM Country a WHERE to_char(alert_reported_time,'DD-MM-YY')=to_char(current_date,'DD-MM-YY') order by alert_reported_time desc")
    List<Country> findCountryByDate();
</code>```

Below is the output where in one object I am getting value as closed for status but in one object I am getting value as null.

{

```<code>[
        "alertSubject": "CWDigital Alert in MS onlinepayment with StatusCode 400",
        "alertReportedTime": "2020-05-29 15:16:03",
        "uniqueTrxId": "1018",
        "status": null,
        "reason": null,
        "conversationId": "ecd6184d-b2f1-4545-c5f2-1ac6d1df48fc",
        "clusterName": "patlacw01",
        "statusCode": "400\n",
        "nameSpace": "com-att-cwdigital-shop-prod"
    },
    {
        "alertSubject": "CWPOS Alert-500 in mS OrderManagement from pbhmacw01 and m26845@prod.shop.cwdigital.att.com",
        "alertReportedTime": "2020-05-29 15:15:41",
        "uniqueTrxId": "1017",
        "status": "CLOSED",
        "reason": null,
        "conversationId": "ee66359e-f87d-4eff-ce50-02ff6e18879a",
        "clusterName": "pbhmacw01",
        "statusCode": "500\n",
        "nameSpace": "com-att-cwpos-prod"
    }]
</code>```

答:
You need to set the  nativeQuery = true, and use each column in select query with some sql method which return the expected value if that column has null value. Like in H2 you can use IFNULL(column, expectedvalue), in oracle you can use nvl(column, exepectedValue).

example:

String query = "Select alertReportedTime, uniqueTrxId, IFNULL(status, 'defaultvalue') as status from CDP_ALERTS";

@Query(value = query, nativeQuery = true)

List <Country>  findCountryByDate();

Body:
Hi I want to assign default value to column variable if value from select query for that variable is coming as null.

    @Entity
    @Table(name = "CDP_ALERTS")
    public class Country {

       @Column(name = "alert_reported_time")
    private String alertReportedTime;

    @Column(name = "unique_id")
    private String uniqueTrxId;

    @Column(name = "status_data")
    private String status;

public String getAlertReportedTime() {
        return alertReportedTime;
    }

    public void setAlertReportedTime(String alertReportedTime) {
        this.alertReportedTime = alertReportedTime;
    }
public String getUniqueTrxId() {
        return uniqueTrxId;
    }

    public void setUniqueTrxId(String uniqueTrxId) {
        this.uniqueTrxId = uniqueTrxId;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
    }

Here status_data column value is coming as null sometime.
below is the select query.

@Query( "SELECT a FROM Country a WHERE to_char(alert_reported_time,'DD-MM-YY')=to_char(current_date,'DD-MM-YY') order by alert_reported_time desc")
    List<Country> findCountryByDate();

Below is the output where in one object I am getting value as closed for status but in one object I am getting value as null.

{

[
        "alertSubject": "CWDigital Alert in MS onlinepayment with StatusCode 400",
        "alertReportedTime": "2020-05-29 15:16:03",
        "uniqueTrxId": "1018",
        "status": null,
        "reason": null,
        "conversationId": "ecd6184d-b2f1-4545-c5f2-1ac6d1df48fc",
        "clusterName": "patlacw01",
        "statusCode": "400\n",
        "nameSpace": "com-att-cwdigital-shop-prod"
    },
    {
        "alertSubject": "CWPOS Alert-500 in mS OrderManagement from pbhmacw01 and m26845@prod.shop.cwdigital.att.com",
        "alertReportedTime": "2020-05-29 15:15:41",
        "uniqueTrxId": "1017",
        "status": "CLOSED",
        "reason": null,
        "conversationId": "ee66359e-f87d-4eff-ce50-02ff6e18879a",
        "clusterName": "pbhmacw01",
        "statusCode": "500\n",
        "nameSpace": "com-att-cwpos-prod"
    }]


问:
Vlookup() equivalent in Dplyr
My df looks like:

```<code>library(tidyverse)
df_1 <- tibble::tribble(
          ~sub_date, ~value_1, ~value_2,
          "2020-05",       58,      130,
          "2020-05",       58,       "check",
          "2020-03",       50,      120,
          "2020-03",       55,       "check",
          "2020-03",       55,       "check"
          )
</code>```

I want to change the values of the rows containing "check" with the reference values here:

```<code>df_ref <- tibble::tribble(
            ~sub_date, ~ref_value,
            "2020-05",        123,
            "2020-03",        234
            )
</code>```

Basically - using the df_ref table as a reference only for the rows containing check.

I want to use the equivalent of a lookup() in excel, used in a if() function.

Final result being:

```<code>df_final <- tibble::tribble(
              ~sub_date, ~value_1, ~value_2,
              "2020-05",       58,      130,
              "2020-05",       58,      123,
              "2020-03",       50,      120,
              "2020-03",       55,      234,
              "2020-03",       55,      234
              )
</code>```

答:
You can also just do it a single line with ifelse and match since we aren't really interested in joining the dataframes. Wrap it in as.numeric if you want numeric output.

library(dplyr)

mutate(df_1,
       value_2 = ifelse(value_2 == "check",
                        df_ref$ref_value[match(sub_date, df_ref$sub_date)],
                        value_2))
```

Title: Vlookup() equivalent in Dplyr

Body:
My df looks like:

library(tidyverse)
df_1 <- tibble::tribble(
          ~sub_date, ~value_1, ~value_2,
          "2020-05",       58,      130,
          "2020-05",       58,       "check",
          "2020-03",       50,      120,
          "2020-03",       55,       "check",
          "2020-03",       55,       "check"
          )

I want to change the values of the rows containing "check" with the reference values here:

df_ref <- tibble::tribble(
            ~sub_date, ~ref_value,
            "2020-05",        123,
            "2020-03",        234
            )

Basically - using the df_ref table as a reference only for the rows containing check.

I want to use the equivalent of a lookup() in excel, used in a if() function.

Final result being:

df_final <- tibble::tribble(
              ~sub_date, ~value_1, ~value_2,
              "2020-05",       58,      130,
              "2020-05",       58,      123,
              "2020-03",       50,      120,
              "2020-03",       55,      234,
              "2020-03",       55,      234
              )


问:
how compilers detect overflow in numbers while compiling?
Compiler deal with source code as strings so in C++ for example when it encourage statement like unsigned char x = 150; it knows from type limits that unsigned char must be in range between 0 and 255.

My question is while the number 150 remain string what algorithm compiler use to compare digit sequence - 150 in this case - against type limits?

I made a simple algorithm to do that for type 'int' for decimal, octal, hexadecimal and little endian binary but i don't think compiler do such thing like that to detect overflow in numbers.

the algorithm i made are coded in C++:

```<code>typedef signed char int8;
typedef signed int  int32;

#define DEC  0
#define HEX  1
#define OCT  2
#define BIN  3

bool isOverflow(const char* value, int32 base)
{
    // left-most digit for maximum and minimum number
    static const char* max_numbers[4][2] =
    {
        //                 INT_MAX                           INT_MIN
        {                       "2147483647",                       "2147483648" }, // decimal
        {                         "7fffffff",                         "80000000" }, // hexadecimal
        {                      "17777777777",                      "20000000000" }, // octal
        { "01111111111111111111111111111111", "10000000000000000000000000000000" }  // binary
    };

    // size of strings in max_numbers array
    static const int32 number_sizes[] = { 10, 8, 11, 32 };

    // input string size
    int32 str_len = strlen(value);

    // is sign mark exist in input string
    int32 signExist = ((base == DEC || base == OCT) && *value == '-');

    // first non zero digit in input number
    int32 non_zero_index = signExist;

    // locate first non zero index
    while(non_zero_index < str_len && value[non_zero_index] == 0) non_zero_index++;

    // if non_zero_index equal length then all digits are zero
    if (non_zero_index == str_len) return false;

    // get number of digits that actually represent the number
    int32 diff = str_len - non_zero_index;

    // if difference less than 10 digits then no overflow will happened
    if (diff < number_sizes[base]) return false;
    // if difference greater than 10 digits then overflow will happened
    if (diff > number_sizes[base]) return true;

    // left digit in input and search strings
    int8 left1 = 0, left2 = 0;

    // if digits equal to 10 then loop over digits from left to right and compare
    for (int32 i = 0; non_zero_index < str_len; non_zero_index++, i++)
    {
        // get input digit
        left1 = value[non_zero_index];
        // get match digit
        left2 = max_numbers[signExist][i];

        // if digits not equal then if left1 is greater overflow will occurred, false otherwise
        if (left1 != left2) return left1 > left2;
    }

    // overflow won't happened
    return false;
}
</code>```

This algorithm can be optimized to work with all integers types but with float-point i have to make new one to work with IEEE float-point representation.

i think compilers use efficient algorithm to detect overflow other than mine, don't you?

答:
It seems simplest for the compiler to convert the string representation into an integer in one step, and then compare against upper and lower bounds of the type in a secondary step.

I can't imagine why it would be better to compare strings.

For floats, the problem is harder due to precision and rounding.

Body:
Compiler deal with source code as strings so in C++ for example when it encourage statement like unsigned char x = 150; it knows from type limits that unsigned char must be in range between 0 and 255.

My question is while the number 150 remain string what algorithm compiler use to compare digit sequence - 150 in this case - against type limits?

I made a simple algorithm to do that for type 'int' for decimal, octal, hexadecimal and little endian binary but i don't think compiler do such thing like that to detect overflow in numbers.

the algorithm i made are coded in C++:

typedef signed char int8;
typedef signed int  int32;

#define DEC  0
#define HEX  1
#define OCT  2
#define BIN  3

bool isOverflow(const char* value, int32 base)
{
    // left-most digit for maximum and minimum number
    static const char* max_numbers[4][2] =
    {
        //                 INT_MAX                           INT_MIN
        {                       "2147483647",                       "2147483648" }, // decimal
        {                         "7fffffff",                         "80000000" }, // hexadecimal
        {                      "17777777777",                      "20000000000" }, // octal
        { "01111111111111111111111111111111", "10000000000000000000000000000000" }  // binary
    };

    // size of strings in max_numbers array
    static const int32 number_sizes[] = { 10, 8, 11, 32 };

    // input string size
    int32 str_len = strlen(value);

    // is sign mark exist in input string
    int32 signExist = ((base == DEC || base == OCT) && *value == '-');

    // first non zero digit in input number
    int32 non_zero_index = signExist;

    // locate first non zero index
    while(non_zero_index < str_len && value[non_zero_index] == 0) non_zero_index++;

    // if non_zero_index equal length then all digits are zero
    if (non_zero_index == str_len) return false;

    // get number of digits that actually represent the number
    int32 diff = str_len - non_zero_index;

    // if difference less than 10 digits then no overflow will happened
    if (diff < number_sizes[base]) return false;
    // if difference greater than 10 digits then overflow will happened
    if (diff > number_sizes[base]) return true;

    // left digit in input and search strings
    int8 left1 = 0, left2 = 0;

    // if digits equal to 10 then loop over digits from left to right and compare
    for (int32 i = 0; non_zero_index < str_len; non_zero_index++, i++)
    {
        // get input digit
        left1 = value[non_zero_index];
        // get match digit
        left2 = max_numbers[signExist][i];

        // if digits not equal then if left1 is greater overflow will occurred, false otherwise
        if (left1 != left2) return left1 > left2;
    }

    // overflow won't happened
    return false;
}

This algorithm can be optimized to work with all integers types but with float-point i have to make new one to work with IEEE float-point representation.

i think compilers use efficient algorithm to detect overflow other than mine, don't you?


问:
Entity Framework Core 3.0 error - SqlException: Invalid column name
I get the following error when I migrate my ASP.NET Core MVC from 2.2 to 3.0

SqlException: Invalid column name 'ContractProfileContractId'.

My statement which throws the error:

```<code>var totalemployees =   _context.EmployeeProfile.Where(x => x.Active == true).ToList();
</code>```

When I add the column ContractProfileContractId to the Employees table, the apps works, but I need to add more and more columns for other tables.

I started coding this app in .NET Core 1.1 (2017), migrated it to 2.0, 2.1 and 2.2 (1 year ago) and now to 3.0.

I tried 3.1 migration and same problem exists.

The application passed the login screen without any error. The error appears only after trying to query from the database using EF.

Any ideas?

答:
I had this same issue on a .net core 2.2 to 3.1 migration. In my case our model never correctly had all the navigation properties / foreign keys setup. Then I guess because of some change in EF it now generates the model different (probably more accurately).

To diagnose the issue you can add a new migration and see what columns/FKs that ef believes it needs to correct. Then go back to your model builder and correct setup the missing relations.

Then you can remove the migration and try again eventually you should see that adding the migration results in an empty migration.

Body:
I get the following error when I migrate my ASP.NET Core MVC from 2.2 to 3.0

SqlException: Invalid column name 'ContractProfileContractId'.

My statement which throws the error:

var totalemployees =   _context.EmployeeProfile.Where(x => x.Active == true).ToList();

When I add the column ContractProfileContractId to the Employees table, the apps works, but I need to add more and more columns for other tables.

I started coding this app in .NET Core 1.1 (2017), migrated it to 2.0, 2.1 and 2.2 (1 year ago) and now to 3.0.

I tried 3.1 migration and same problem exists.

The application passed the login screen without any error. The error appears only after trying to query from the database using EF.

Any ideas?


问:
Sequelize and Node.js : Foreign key constraint when deleting with cascade "set null"
I'm using Sequelize version 4.4.10, Node.js and SQLite. Here are my models :

Subscription.js

```<code>module.exports = (sequelize, DataTypes) => {
  let Subscription = sequelize.define('Subscription', {
    id: { type: DataTypes.STRING(50), primaryKey: true },
    title: DataTypes.STRING(100),
    url: DataTypes.STRING(50),
    thumbnail_url: DataTypes.STRING(50)
  })

  Subscription.associate = (models) => {
    Subscription.belongsToMany(models.Tag, {
      through: models.TagSubscription,
      onDelete: 'set null',
      onUpdate: 'set null'
    })
  }

  return Subscription
}
</code>```

Tag.js

```<code>module.exports = (sequelize, DataTypes) => {
  let Tag = sequelize.define('Tag', {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    title: { type: DataTypes.STRING(25) }
  })

  Tag.associate = models => {
    Tag.belongsToMany(models.Subscription, {
      through: models.TagSubscription,
      onDelete: 'set null',
      onUpdate: 'set null'
    })
  }

  return Tag
}
</code>```

TagSubscription.js

```<code>module.exports = (sequelize, DataTypes) => {
  let TagSubscription = sequelize.define('TagSubscription', {

  })

  return TagSubscription
}
</code>```

Here is my subscription repository :

SubscriptionRepository.js

```<code>let models = require('../models')
let logger = require('bug-killer')

class SubscriptionRepository {

  async deleteAll () {
    try {
      await models.Subscription.destroy({ where: {} })
    } catch (error) {
      logger.error('SubscriptionRepository.deleteAll() error')
      throw (error)
    }
  }

  async findOne (subId) {
    try {
      let subscription = await models.Subscription.findOne({ where: { id: subId } })
      return subscription
    } catch (error) {
      logger.error('SubscriptionRepository.findOne() error')
      throw (error)
    }
  }

  async create (sub) {
    try {
      let subscription = await models.Subscription.create({
        id: sub.id,
        title: sub.title,
        url: sub.url,
        thumbnail_url: sub.thumbnail_url
      })

      return subscription
    } catch (error) {
      logger.error('SubscriptionRepository.create() error')
      throw (error)
    }
  }
}

exports.SubscriptionRepository = SubscriptionRepository
</code>```

And here is the function I want to test :

```<code>async refreshData () {
    try {
      let extracted = this.getExtractedData(undefined)
      await subscriptionRepository.deleteAll()
      await models.Subscription.bulkCreate(extracted.items, { ignoreDuplicates: true, updateOnDuplicates: ['title', 'url', 'thumbnail_url', 'createdAt', 'updatedAt'] })
    } catch (error) {
      console.log(error)
    }
  }
</code>```

When I call refreshData, it logs me the following error :

```<code>Executing (default): DELETE FROM `Subscriptions`
error SubscriptionRepository.deleteAll() error
{ SequelizeForeignKeyConstraintError: SQLITE_CONSTRAINT: FOREIGN KEY constraint failed
    at Query.formatError (/home/xavier/Projets/youtube_manager/node_modules/sequelize/lib/dialects/sqlite/query.js:374:18)
    at Statement.afterExecute (/home/xavier/Projets/youtube_manager/node_modules/sequelize/lib/dialects/sqlite/query.js:119:32)
    at Statement.replacement (/home/xavier/Projets/youtube_manager/node_modules/sqlite3/lib/trace.js:19:31)
  name: 'SequelizeForeignKeyConstraintError',
  parent:
   { Error: SQLITE_CONSTRAINT: FOREIGN KEY constraint failed
     errno: 19,
     code: 'SQLITE_CONSTRAINT',
     sql: 'DELETE FROM `Subscriptions`' },
  original:
   { Error: SQLITE_CONSTRAINT: FOREIGN KEY constraint failed
     errno: 19,
     code: 'SQLITE_CONSTRAINT',
     sql: 'DELETE FROM `Subscriptions`' },
  sql: 'DELETE FROM `Subscriptions`',
  fields: undefined,
  table: undefined,
  value: undefined,
  index: undefined }
</code>```

Why this error ? Since I specified the "set null" behavior for both my delete and update cascade, destroy() function shouldn't fail with foreign key violation.

答:
Try

```<code>onDelete: 'cascade',
onUpdate: 'cascade'
</code>```

since it can't set it to null if it is not there

Body:
I'm using Sequelize version 4.4.10, Node.js and SQLite. Here are my models :

Subscription.js

module.exports = (sequelize, DataTypes) => {
  let Subscription = sequelize.define('Subscription', {
    id: { type: DataTypes.STRING(50), primaryKey: true },
    title: DataTypes.STRING(100),
    url: DataTypes.STRING(50),
    thumbnail_url: DataTypes.STRING(50)
  })

  Subscription.associate = (models) => {
    Subscription.belongsToMany(models.Tag, {
      through: models.TagSubscription,
      onDelete: 'set null',
      onUpdate: 'set null'
    })
  }

  return Subscription
}

Tag.js

module.exports = (sequelize, DataTypes) => {
  let Tag = sequelize.define('Tag', {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    title: { type: DataTypes.STRING(25) }
  })

  Tag.associate = models => {
    Tag.belongsToMany(models.Subscription, {
      through: models.TagSubscription,
      onDelete: 'set null',
      onUpdate: 'set null'
    })
  }

  return Tag
}

TagSubscription.js

module.exports = (sequelize, DataTypes) => {
  let TagSubscription = sequelize.define('TagSubscription', {

  })

  return TagSubscription
}

Here is my subscription repository :

SubscriptionRepository.js

let models = require('../models')
let logger = require('bug-killer')

class SubscriptionRepository {

  async deleteAll () {
    try {
      await models.Subscription.destroy({ where: {} })
    } catch (error) {
      logger.error('SubscriptionRepository.deleteAll() error')
      throw (error)
    }
  }

  async findOne (subId) {
    try {
      let subscription = await models.Subscription.findOne({ where: { id: subId } })
      return subscription
    } catch (error) {
      logger.error('SubscriptionRepository.findOne() error')
      throw (error)
    }
  }

  async create (sub) {
    try {
      let subscription = await models.Subscription.create({
        id: sub.id,
        title: sub.title,
        url: sub.url,
        thumbnail_url: sub.thumbnail_url
      })

      return subscription
    } catch (error) {
      logger.error('SubscriptionRepository.create() error')
      throw (error)
    }
  }
}

exports.SubscriptionRepository = SubscriptionRepository

And here is the function I want to test :

async refreshData () {
    try {
      let extracted = this.getExtractedData(undefined)
      await subscriptionRepository.deleteAll()
      await models.Subscription.bulkCreate(extracted.items, { ignoreDuplicates: true, updateOnDuplicates: ['title', 'url', 'thumbnail_url', 'createdAt', 'updatedAt'] })
    } catch (error) {
      console.log(error)
    }
  }

When I call refreshData, it logs me the following error :

Executing (default): DELETE FROM `Subscriptions`
error SubscriptionRepository.deleteAll() error
{ SequelizeForeignKeyConstraintError: SQLITE_CONSTRAINT: FOREIGN KEY constraint failed
    at Query.formatError (/home/xavier/Projets/youtube_manager/node_modules/sequelize/lib/dialects/sqlite/query.js:374:18)
    at Statement.afterExecute (/home/xavier/Projets/youtube_manager/node_modules/sequelize/lib/dialects/sqlite/query.js:119:32)
    at Statement.replacement (/home/xavier/Projets/youtube_manager/node_modules/sqlite3/lib/trace.js:19:31)
  name: 'SequelizeForeignKeyConstraintError',
  parent:
   { Error: SQLITE_CONSTRAINT: FOREIGN KEY constraint failed
     errno: 19,
     code: 'SQLITE_CONSTRAINT',
     sql: 'DELETE FROM `Subscriptions`' },
  original:
   { Error: SQLITE_CONSTRAINT: FOREIGN KEY constraint failed
     errno: 19,
     code: 'SQLITE_CONSTRAINT',
     sql: 'DELETE FROM `Subscriptions`' },
  sql: 'DELETE FROM `Subscriptions`',
  fields: undefined,
  table: undefined,
  value: undefined,
  index: undefined }

Why this error ? Since I specified the "set null" behavior for both my delete and update cascade, destroy() function shouldn't fail with foreign key violation.

Body:
Try

onDelete: 'cascade',
onUpdate: 'cascade'

since it can't set it to null if it is not there


问:
Apollo Client - Calling concat on a terminating link, which will have no effect
I have the following Apollo Links:

```<code> const link = ApolloLink.from([
    serializingLink,
    httpAuthLink,
    queueLink,
    retryLink,
    errorLink,
    uploadLink,
    httpLink
  ]);

</code>```

And they are all with the correct setup
After adding a new link, that error started to appear in the console:

```<code>Error: You are calling concat on a terminating link, which will have no effect
</code>```

By reading another issue, I saw that this can be related with the order of the links inside of the array.

答: A terminating link is one that actually sends the request and receives the response. There should only ever be one terminating link at the very end of your chain. In the code you posted, there's at least two terminating links -- uploadLink and httpLink. Assuming uploadLink was created using createUploadLink, there's no need to include both it and httpLink. UploadLink is a drop in replacement for HttpLink, so you can just remove the httpLink alltogether.

Body:
I have the following Apollo Links:

 const link = ApolloLink.from([
    serializingLink,
    httpAuthLink,
    queueLink,
    retryLink,
    errorLink,
    uploadLink,
    httpLink
  ]);

And they are all with the correct setup
After adding a new link, that error started to appear in the console:

Error: You are calling concat on a terminating link, which will have no effect

By reading another issue, I saw that this can be related with the order of the links inside of the array.


问:
Does Hive's Create External Table copy data?
I have a Spark application that writes output files in Avro format. Now I would like that data to be available in Hive, because an application which would utilise that data can only do so through a Hive table.

It is described here that one can do that by using CREATE EXTERNAL TABLE in Hive. Now my question is, how efficient is the CREATE EXTERNAL TABLE method. Would it copy all the Avro data somewhere else on the HDFS to work, or does it just create some metainfo, which it can use to query Avro data?

Also, what if I want to keep on adding new Avro data to that table. Can I create such an external table once, and then keep adding the new Avro data to it? Also what if someone queries the data while it's being updated. Does it allow atomic transactions?

答:
Hive CREATE TABLE statement does not copy any data. Data remains in the location specified in the table DDL. CREATE TABLE creates metadata only in Hive metastore.

You can add files later in the same location.

HDFS does not allow updates. You can delete files and put new files. select will return empty dataset in the middle between delete and putting new files.

Also when you manipulate files directly, Hive statistics is not refreshed because Hive does not know that you have changed the data.

Hive does not know if you changed files because filesystem and Hive are loosely connected. Hive has a metadata with table schema definition, serde and location, statistics, etc. And it remains the same after you changed data in the table location.

Hive transactions are atomic. If you inserting or rewriting data using HiveQL, it writes data into temporary location and only if the command succeeds files are moved to the table location (old files are deleted in case of rewrite). If SQL fails the data remains as it was before command.

But since Hive does not copy data from the table location into some internal managed storage, if you manipulating files when Hive is reading them, then it will be an exception in hive process. Hive cannot lock table during your files operation because Hive does not know about it. Filesystem is quite detached from hive and you can do everything in filesystem as if there is no Hive exists at all.

Read also about Hive ACID mode: Hive Transactions

Also read about the difference between managed and external tables in Hive.


问:
faster arithmetic operations in C++
In a function containing expensive operations such as floating-point division, sqrt or cbrt, are there any ways to specify the accuracy of the result in order reduce computation time? I.e. if I am happy to have a result that is within +/- 0.01 of the correct answer, or within 5%, is there a way to specify this?</p>

答:
There is no standard way to control accuracy in c++.

The best way might be to roll your own implementation based on the accuracy needs of your project. For example it is possible to use a look-up table instead of trigonometric functions, or other functions if the range of input is small. It is also possible to use a less accurate approximation of the desired function. A taylor series with few terms for example.

You can also vectorize your work using intrinsics or your GPU.

Title: faster arithmetic operations in C++


问:
How can I get the months between two dates in Oracle SQL
I need to get the numbers of the months between two dates.
For example, between those dates: "03/03/2020 - 06/06/2020"
I need something like "(03,04,05,06)".</p>

答:
For Oracle:</p>

```<code>SQL> column months format a24
SQL> select banner from v$version where rownum=1;

BANNER
--------------------------------------------------------------------------------
Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production

SQL> select '(' || listagg(m, ',') || ')' as months
  2  from (
  3   select
  4   extract(month from to_date('03/03/2020')) m1,
  5   extract(month from to_date('06/06/2020')) m2
  6   from dual) mm
  7  inner join (
  8   select level as m
  9   from dual
 10   connect by level <= 12) l
 11  on m >= m1 and m <=m2
 12  ;

MONTHS
------------------------
(3,4,5,6)

SQL>
</code>```

Body:
For Oracle:

SQL> column months format a24
SQL> select banner from v$version where rownum=1;

BANNER
--------------------------------------------------------------------------------
Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production

SQL> select '(' || listagg(m, ',') || ')' as months
  2  from (
  3   select
  4   extract(month from to_date('03/03/2020')) m1,
  5   extract(month from to_date('06/06/2020')) m2
  6   from dual) mm
  7  inner join (
  8   select level as m
  9   from dual
 10   connect by level <= 12) l
 11  on m >= m1 and m <=m2
 12  ;

MONTHS
------------------------
(3,4,5,6)

SQL>


问:
Change color of FontAwsome Glyph
I'm using FontAwesome Glyphs in a button and want to change the color in a method. Does anyone know how to do this? I also tried "-fx-fill: black;". Both don't work.</p>

```<code>import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
public FontAwesomeIcon close;
close.setStyle("-fx-fill: black;");
</code>```

答:
try this</p>

```<code>import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView;

FontAwesomeIconView fa = new FontAwesomeIconView(FontAwesomeIcon.CLOSE);
fa.setStyle("-fx-font-family: FontAwesome; -fx-fill: BLACK; -fx-font-size: 28px");
</code>```

Title: Change color of FontAwsome Glyph

Body:
I'm using FontAwesome Glyphs in a button and want to change the color in a method. Does anyone know how to do this? I also tried "-fx-fill: black;". Both don't work.

import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
public FontAwesomeIcon close;
close.setStyle("-fx-fill: black;");

Body:
try this

import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView;

FontAwesomeIconView fa = new FontAwesomeIconView(FontAwesomeIcon.CLOSE);
fa.setStyle("-fx-font-family: FontAwesome; -fx-fill: BLACK; -fx-font-size: 28px");


问:
Use of useSelector redux hooks
I made state in redux hooks I don't know how to import or useSelector the state I want

Here I am using the useSelector Send to state in Login file

```<code>function Login(props) {

var classes = useStyles();
var dispatch = useDispatch();

const { username, password } = useSelector((state) => ({
    ...state.combineReducers,
    ...state.userReducer,
}));
</code>```

And that is nav file
And here I want to get what's in the state

```<code>function nav(props) {

    const { username } = useSelector((state) => ({
        ...state.combineReducers,
        ...state.userReducer,
    }));
</code>```

The error

```<code> Failed to compile.

./src/NAVBAR/nav.js
  Line 27:  React Hook "useSelector" is called in function "nav" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks
</code>```

I have tried in many ways but it fails

答:
I have faced a similar problem and found a simple solution.

```<code>const username = useSelector(state => state.userReducer.username)
</code>```

so, we have taken specific username state from the reducer. This work for me:)

Title: Use of useSelector redux hooks

Body:
I made state in redux hooks I don't know how to import or useSelector the state I want

Here I am using the useSelector Send to state in Login file

function Login(props) {

var classes = useStyles();
var dispatch = useDispatch();

const { username, password } = useSelector((state) => ({
    ...state.combineReducers,
    ...state.userReducer,
}));

And that is nav file
And here I want to get what's in the state

function nav(props) {

    const { username } = useSelector((state) => ({
        ...state.combineReducers,
        ...state.userReducer,
    }));

The error

 Failed to compile.

./src/NAVBAR/nav.js
  Line 27:  React Hook "useSelector" is called in function "nav" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

I have tried in many ways but it fails

Body:
I have faced a similar problem and found a simple solution.

const username = useSelector(state => state.userReducer.username)

so, we have taken specific username state from the reducer. This work for me:)


问:
cannot select specific column after merging it with another data frame
```<code>unitown=pd.merge(Q1(),Q5(),how='inner',left_on=['State','RegionName'],right_index=True)
</code>```

i created this new data frame called unitown after merging two data frames with index 'State' and 'RegionName'.
Below is how unitown looks like:
enter image description here

from the pic you can see it has column named in the format of Year and Quarter. However when I try unitown['2000Q1'] it gives me the following error:

```<code> 2798             if self.columns.nlevels > 1:
   2799                 return self._getitem_multilevel(key)
-> 2800             indexer = self.columns.get_loc(key)
   2801             if is_integer(indexer):
   2802                 indexer = [indexer]
~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2646                 return self._engine.get_loc(key)
   2647             except KeyError:
-> 2648                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2649         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2650         if indexer.ndim > 1 or indexer.size > 1:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: '2000Q1'*
</code>```

I have tried unitown.columns.tolist() and below is part of the output:

```<code>['State',
 'RegionName',
 Period('2000Q1', 'Q-DEC'),
 Period('2000Q2', 'Q-DEC'),
 Period('2000Q3', 'Q-DEC'),
 Period('2000Q4', 'Q-DEC'),
 Period('2001Q1', 'Q-DEC'),
 Period('2001Q2', 'Q-DEC'),
 Period('2001Q3', 'Q-DEC'),
 Period('2001Q4', 'Q-DEC'),
 Period('2002Q1', 'Q-DEC'),
 Period('2002Q2', 'Q-DEC'),
 Period('2002Q3', 'Q-DEC'),
</code>```

I am not sure why it gives such error given '2000Q1' is clearly one of the column names. Can anyone please help me on this? Thanks a lot!

答:
This should resolve the issue:</p>

```<code>df.columns = [str(col) for col in df.columns]
</code>```

Body:
unitown=pd.merge(Q1(),Q5(),how='inner',left_on=['State','RegionName'],right_index=True)

i created this new data frame called unitown after merging two data frames with index 'State' and 'RegionName'.
Below is how unitown looks like:
enter image description here

from the pic you can see it has column named in the format of Year and Quarter. However when I try unitown['2000Q1'] it gives me the following error:

 2798             if self.columns.nlevels > 1:
   2799                 return self._getitem_multilevel(key)
-> 2800             indexer = self.columns.get_loc(key)
   2801             if is_integer(indexer):
   2802                 indexer = [indexer]
~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2646                 return self._engine.get_loc(key)
   2647             except KeyError:
-> 2648                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2649         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2650         if indexer.ndim > 1 or indexer.size > 1:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: '2000Q1'*

I have tried unitown.columns.tolist() and below is part of the output:

['State',
 'RegionName',
 Period('2000Q1', 'Q-DEC'),
 Period('2000Q2', 'Q-DEC'),
 Period('2000Q3', 'Q-DEC'),
 Period('2000Q4', 'Q-DEC'),
 Period('2001Q1', 'Q-DEC'),
 Period('2001Q2', 'Q-DEC'),
 Period('2001Q3', 'Q-DEC'),
 Period('2001Q4', 'Q-DEC'),
 Period('2002Q1', 'Q-DEC'),
 Period('2002Q2', 'Q-DEC'),
 Period('2002Q3', 'Q-DEC'),

I am not sure why it gives such error given '2000Q1' is clearly one of the column names. Can anyone please help me on this? Thanks a lot!

Body:
This should resolve the issue:

df.columns = [str(col) for col in df.columns]


问:
Pyspark join dataframe based on function
I have 2 dataframes that look like that

networks

```<code>+----------------+-------+
|    Network     | VLAN  |
+----------------+-------+
| 192.168.1.0/24 | VLAN1 |
| 192.168.2.0/24 | VLAN2 |
+----------------+-------+
</code>```

flows

```<code>+--------------+----------------+
|  source_ip   | destination_ip |
+--------------+----------------+
| 192.168.1.11 | 192.168.2.13   |
+--------------+----------------+
</code>```

Ideally I would like to get something like this

```<code>+--------------+----------------+-------------+------------------+
|  source_ip   | destination_ip | source_vlan | destination_vlan |
+--------------+----------------+-------------+------------------+
| 192.168.1.11 | 192.168.2.13   | VLAN1       | VLAN2            |
+--------------+----------------+-------------+------------------+
</code>```

Unfortunately the flows dataframe does not contain the subnetmask. What I have tried so far without pyspark

Get a distinct list of subnets (in this example [24])

For every subnet and source_ip compute the network ipaddress.ip_network('{}/{}'.format(ip,sub), strict=False)

Search if that subnet exists in dataframe "networks" and return VLAN otherwise return empty string

I tried to do a similar approach with pyspark but it does not work as well as I think there might be better ways of doing it?

```<code>def get_available_subnets(df):
    split_col = split(df['network'], '/')
    df = df.withColumn('sub', split_col.getItem(1))
    return df.select('sub').distinct()

def get_vlan_by_ip(ip, infoblox, subnets):
    for sub in subnets:
        net = ipaddress.ip_network('{}/{}'.format(ip,sub), strict=False)
        if net:
            search = infoblox.filter(infoblox.network == str(net))

            if not search.head(1).isEmpty():
                return search.first.vlan
    return hashlib.sha1(str.encode(ip)).hexdigest()

subnets = get_available_subnets(infoblox_networks_df).select('sub').rdd.flatMap(lambda x: x).collect()

short = flows_filtered_prepared_df.limit(1000)

partial_vlan_func = partial(get_vlan_by_ip, infoblox=infoblox_networks_df, subnets=subnets)
get_vlan_udf = udf(lambda ip: partial_vlan_func(ip), StringType())

short.select('source_ip', 'destination_ip', get_vlan_udf('source_ip').alias('source_vlan')).show()
</code>```

答:
This method completely avoids the use of udf, leveraging split and slice, but perhaps there is a better way. The benefit of this approach is that it directly leverages the bits present in the subnet mask and that it's written purely in PySpark.

Context for the solution: IP addresses can be split and masked by the subnet. This means that 8, 16, 24, 32 tell you which parts of the IP matter - this motivates the division by 8 and using the resulting column to slice the IP address ArrayType column once it's split from its original StringType.

NB: pyspark.sql.functions.slice will work in newer version of PySpark >= 2.4, some older ones need to use f.expr("slice(...)").

The setup:

```<code>flows = spark.createDataFrame([
    (1, "192.168.1.1", "192.168.2.1"),
    (2, "192.168.2.1", "192.168.3.1"),
    (3, "192.168.3.1", "192.168.1.1"),
], ['id', 'source_ip', 'destination_ip']
)
networks = spark.createDataFrame([
    (1, "192.168.1.0/24", "VLAN1"),
    (2, "192.168.2.0/24", "VLAN2"),
    (3, "192.168.3.0/24", "VLAN3"),
], ['id', 'network', 'vlan']
)
</code>```

Some pre-processing:

```<code>networks_split = networks.select(
    "*",
    (f.split(f.col("network"), "/")[1] / 8).cast("int").alias("bits"),
    f.split(f.split(f.col("network"), "/")[0], "\.").alias('segmented_ip')
)
networks_split.show()
+---+--------------+-----+----+----------------+
| id|       network| vlan|bits|    segmented_ip|
+---+--------------+-----+----+----------------+
|  1|192.168.1.0/24|VLAN1|   3|[192, 168, 1, 0]|
|  2|192.168.2.0/24|VLAN2|   3|[192, 168, 2, 0]|
|  3|192.168.3.0/24|VLAN3|   3|[192, 168, 3, 0]|
+---+--------------+-----+----+----------------+

networks_masked = networks_split.select(
    "*",
    f.expr("slice(segmented_ip, 1, bits)").alias("masked_bits"),
)
networks_masked.show()
+---+--------------+-----+----+----------------+-------------+
| id|       network| vlan|bits|    segmented_ip|  masked_bits|
+---+--------------+-----+----+----------------+-------------+
|  1|192.168.1.0/24|VLAN1|   3|[192, 168, 1, 0]|[192, 168, 1]|
|  2|192.168.2.0/24|VLAN2|   3|[192, 168, 2, 0]|[192, 168, 2]|
|  3|192.168.3.0/24|VLAN3|   3|[192, 168, 3, 0]|[192, 168, 3]|
+---+--------------+-----+----+----------------+-------------+

flows_split = flows.select(
    "*",
    f.split(f.split(f.col("source_ip"), "/")[0], "\.").alias('segmented_source_ip'),
    f.split(f.split(f.col("destination_ip"), "/")[0], "\.").alias('segmented_destination_ip')
)
flows_split.show()
+---+-----------+--------------+-------------------+------------------------+
| id|  source_ip|destination_ip|segmented_source_ip|segmented_destination_ip|
+---+-----------+--------------+-------------------+------------------------+
|  1|192.168.1.1|   192.168.2.1|   [192, 168, 1, 1]|        [192, 168, 2, 1]|
|  2|192.168.2.1|   192.168.3.1|   [192, 168, 2, 1]|        [192, 168, 3, 1]|
|  3|192.168.3.1|   192.168.1.1|   [192, 168, 3, 1]|        [192, 168, 1, 1]|
+---+-----------+--------------+-------------------+------------------------+
</code>```

Finally, I crossJoin and filter on the slice based on the bits of my mask, such as:

```<code>flows_split.crossJoin(
    networks_masked.select("vlan", "bits", "masked_bits")
).where(
    f.expr("slice(segmented_source_ip, 1, bits)") == f.col("masked_bits")
).show()
+---+-----------+--------------+-------------------+------------------------+-----+----+-------------+
| id|  source_ip|destination_ip|segmented_source_ip|segmented_destination_ip| vlan|bits|  masked_bits|
+---+-----------+--------------+-------------------+------------------------+-----+----+-------------+
|  1|192.168.1.1|   192.168.2.1|   [192, 168, 1, 1]|        [192, 168, 2, 1]|VLAN1|   3|[192, 168, 1]|
|  2|192.168.2.1|   192.168.3.1|   [192, 168, 2, 1]|        [192, 168, 3, 1]|VLAN2|   3|[192, 168, 2]|
|  3|192.168.3.1|   192.168.1.1|   [192, 168, 3, 1]|        [192, 168, 1, 1]|VLAN3|   3|[192, 168, 3]|
+---+-----------+--------------+-------------------+------------------------+-----+----+-------------+
</code>```

Exactly the same approach can be done for destination_ip, such as:

```<code>flows_split.crossJoin(
    networks_masked.select("vlan", "bits", "masked_bits")
).where(
    f.expr("slice(segmented_destination_ip, 1, bits)") == f.col("masked_bits")
).show()
+---+-----------+--------------+-------------------+------------------------+-----+----+-------------+
| id|  source_ip|destination_ip|segmented_source_ip|segmented_destination_ip| vlan|bits|  masked_bits|
+---+-----------+--------------+-------------------+------------------------+-----+----+-------------+
|  1|192.168.1.1|   192.168.2.1|   [192, 168, 1, 1]|        [192, 168, 2, 1]|VLAN2|   3|[192, 168, 2]|
|  2|192.168.2.1|   192.168.3.1|   [192, 168, 2, 1]|        [192, 168, 3, 1]|VLAN3|   3|[192, 168, 3]|
|  3|192.168.3.1|   192.168.1.1|   [192, 168, 3, 1]|        [192, 168, 1, 1]|VLAN1|   3|[192, 168, 1]|
+---+-----------+--------------+-------------------+------------------------+-----+----+-------------+
</code>```

Finally, you either join the resulting two tables together on source_ip and destination_ip (since you have the vlan information attached as required), or you merge the previous two steps together and crossJoin and filter twice.

Hope this helps!

Body:
I have 2 dataframes that look like that

networks

+----------------+-------+
|    Network     | VLAN  |
+----------------+-------+
| 192.168.1.0/24 | VLAN1 |
| 192.168.2.0/24 | VLAN2 |
+----------------+-------+

flows

+--------------+----------------+
|  source_ip   | destination_ip |
+--------------+----------------+
| 192.168.1.11 | 192.168.2.13   |
+--------------+----------------+

Ideally I would like to get something like this

+--------------+----------------+-------------+------------------+
|  source_ip   | destination_ip | source_vlan | destination_vlan |
+--------------+----------------+-------------+------------------+
| 192.168.1.11 | 192.168.2.13   | VLAN1       | VLAN2            |
+--------------+----------------+-------------+------------------+

Unfortunately the flows dataframe does not contain the subnetmask. What I have tried so far without pyspark

Get a distinct list of subnets (in this example [24])

For every subnet and source_ip compute the network ipaddress.ip_network('{}/{}'.format(ip,sub), strict=False)

Search if that subnet exists in dataframe "networks" and return VLAN otherwise return empty string

I tried to do a similar approach with pyspark but it does not work as well as I think there might be better ways of doing it?

def get_available_subnets(df):
    split_col = split(df['network'], '/')
    df = df.withColumn('sub', split_col.getItem(1))
    return df.select('sub').distinct()

def get_vlan_by_ip(ip, infoblox, subnets):
    for sub in subnets:
        net = ipaddress.ip_network('{}/{}'.format(ip,sub), strict=False)
        if net:
            search = infoblox.filter(infoblox.network == str(net))

            if not search.head(1).isEmpty():
                return search.first.vlan
    return hashlib.sha1(str.encode(ip)).hexdigest()

subnets = get_available_subnets(infoblox_networks_df).select('sub').rdd.flatMap(lambda x: x).collect()

short = flows_filtered_prepared_df.limit(1000)

partial_vlan_func = partial(get_vlan_by_ip, infoblox=infoblox_networks_df, subnets=subnets)
get_vlan_udf = udf(lambda ip: partial_vlan_func(ip), StringType())

short.select('source_ip', 'destination_ip', get_vlan_udf('source_ip').alias('source_vlan')).show()

Body:
This method completely avoids the use of udf, leveraging split and slice, but perhaps there is a better way. The benefit of this approach is that it directly leverages the bits present in the subnet mask and that it's written purely in PySpark.

Context for the solution: IP addresses can be split and masked by the subnet. This means that 8, 16, 24, 32 tell you which parts of the IP matter - this motivates the division by 8 and using the resulting column to slice the IP address ArrayType column once it's split from its original StringType.

NB: pyspark.sql.functions.slice will work in newer version of PySpark >= 2.4, some older ones need to use f.expr("slice(...)").

The setup:

flows = spark.createDataFrame([
    (1, "192.168.1.1", "192.168.2.1"),
    (2, "192.168.2.1", "192.168.3.1"),
    (3, "192.168.3.1", "192.168.1.1"),
], ['id', 'source_ip', 'destination_ip']
)
networks = spark.createDataFrame([
    (1, "192.168.1.0/24", "VLAN1"),
    (2, "192.168.2.0/24", "VLAN2"),
    (3, "192.168.3.0/24", "VLAN3"),
], ['id', 'network', 'vlan']
)

Some pre-processing:

networks_split = networks.select(
    "*",
    (f.split(f.col("network"), "/")[1] / 8).cast("int").alias("bits"),
    f.split(f.split(f.col("network"), "/")[0], "\.").alias('segmented_ip')
)
networks_split.show()
+---+--------------+-----+----+----------------+
| id|       network| vlan|bits|    segmented_ip|
+---+--------------+-----+----+----------------+
|  1|192.168.1.0/24|VLAN1|   3|[192, 168, 1, 0]|
|  2|192.168.2.0/24|VLAN2|   3|[192, 168, 2, 0]|
|  3|192.168.3.0/24|VLAN3|   3|[192, 168, 3, 0]|
+---+--------------+-----+----+----------------+

networks_masked = networks_split.select(
    "*",
    f.expr("slice(segmented_ip, 1, bits)").alias("masked_bits"),
)
networks_masked.show()
+---+--------------+-----+----+----------------+-------------+
| id|       network| vlan|bits|    segmented_ip|  masked_bits|
+---+--------------+-----+----+----------------+-------------+
|  1|192.168.1.0/24|VLAN1|   3|[192, 168, 1, 0]|[192, 168, 1]|
|  2|192.168.2.0/24|VLAN2|   3|[192, 168, 2, 0]|[192, 168, 2]|
|  3|192.168.3.0/24|VLAN3|   3|[192, 168, 3, 0]|[192, 168, 3]|
+---+--------------+-----+----+----------------+-------------+

flows_split = flows.select(
    "*",
    f.split(f.split(f.col("source_ip"), "/")[0], "\.").alias('segmented_source_ip'),
    f.split(f.split(f.col("destination_ip"), "/")[0], "\.").alias('segmented_destination_ip')
)
flows_split.show()
+---+-----------+--------------+-------------------+------------------------+
| id|  source_ip|destination_ip|segmented_source_ip|segmented_destination_ip|
+---+-----------+--------------+-------------------+------------------------+
|  1|192.168.1.1|   192.168.2.1|   [192, 168, 1, 1]|        [192, 168, 2, 1]|
|  2|192.168.2.1|   192.168.3.1|   [192, 168, 2, 1]|        [192, 168, 3, 1]|
|  3|192.168.3.1|   192.168.1.1|   [192, 168, 3, 1]|        [192, 168, 1, 1]|
+---+-----------+--------------+-------------------+------------------------+

Finally, I crossJoin and filter on the slice based on the bits of my mask, such as:

flows_split.crossJoin(
    networks_masked.select("vlan", "bits", "masked_bits")
).where(
    f.expr("slice(segmented_source_ip, 1, bits)") == f.col("masked_bits")
).show()
+---+-----------+--------------+-------------------+------------------------+-----+----+-------------+
| id|  source_ip|destination_ip|segmented_source_ip|segmented_destination_ip| vlan|bits|  masked_bits|
+---+-----------+--------------+-------------------+------------------------+-----+----+-------------+
|  1|192.168.1.1|   192.168.2.1|   [192, 168, 1, 1]|        [192, 168, 2, 1]|VLAN1|   3|[192, 168, 1]|
|  2|192.168.2.1|   192.168.3.1|   [192, 168, 2, 1]|        [192, 168, 3, 1]|VLAN2|   3|[192, 168, 2]|
|  3|192.168.3.1|   192.168.1.1|   [192, 168, 3, 1]|        [192, 168, 1, 1]|VLAN3|   3|[192, 168, 3]|
+---+-----------+--------------+-------------------+------------------------+-----+----+-------------+

Exactly the same approach can be done for destination_ip, such as:

flows_split.crossJoin(
    networks_masked.select("vlan", "bits", "masked_bits")
).where(
    f.expr("slice(segmented_destination_ip, 1, bits)") == f.col("masked_bits")
).show()
+---+-----------+--------------+-------------------+------------------------+-----+----+-------------+
| id|  source_ip|destination_ip|segmented_source_ip|segmented_destination_ip| vlan|bits|  masked_bits|
+---+-----------+--------------+-------------------+------------------------+-----+----+-------------+
|  1|192.168.1.1|   192.168.2.1|   [192, 168, 1, 1]|        [192, 168, 2, 1]|VLAN2|   3|[192, 168, 2]|
|  2|192.168.2.1|   192.168.3.1|   [192, 168, 2, 1]|        [192, 168, 3, 1]|VLAN3|   3|[192, 168, 3]|
|  3|192.168.3.1|   192.168.1.1|   [192, 168, 3, 1]|        [192, 168, 1, 1]|VLAN1|   3|[192, 168, 1]|
+---+-----------+--------------+-------------------+------------------------+-----+----+-------------+

Finally, you either join the resulting two tables together on source_ip and destination_ip (since you have the vlan information attached as required), or you merge the previous two steps together and crossJoin and filter twice.

Hope this helps!


问:
How to check if clicked on UI object?
I am new to Unity and trying to make a basic minesweeper game. I have a square prefab and I want to learn if it is clicked. But I can not do it listening because I need both left click and right click. How can I do that?</p>

答:
You can try usign the Input.GetKeyDown function in the Update:

```<code>
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            //print("Right click");
        }
        else if (Input.GetKeyDown(KeyCode.Mouse1))
        {
            //print("Left click");
        }
    }
</code>```

For detecting if the mouse is over the spesific game object you can use:

```<code>void OnMouseOver()
     {
         ///
     }
</code>```

Or

```<code>Ray ray;
     RaycastHit hit;

     void Update()
     {
         ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         if(Physics.Raycast(ray, out hit))
         {
             print (hit.collider.name);
         }
     }
</code>```

Title: How to check if clicked on UI object?

Body:
You can try usign the Input.GetKeyDown function in the Update:

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            //print("Right click");
        }
        else if (Input.GetKeyDown(KeyCode.Mouse1))
        {
            //print("Left click");
        }
    }

For detecting if the mouse is over the spesific game object you can use:

void OnMouseOver()
     {
         ///
     }

Or

Ray ray;
     RaycastHit hit;

     void Update()
     {
         ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         if(Physics.Raycast(ray, out hit))
         {
             print (hit.collider.name);
         }
     }


问:
MySQL implement search based on multiple filters
From the table structure below I'd like to be able to provide search filters based on combinations of attributes:

Table: animalAttributes

```<code>id      attributeId     animalId
1       455             55
2       999             55
3       685             55
4       999             89
5       455             89
6       333             93
7       685             93
8       999             93
--------------------------------
</code>```

The front end would have checkboxes e.g.

```<code>Animal options

Colour
[ ] Black      (id 685)
[x] Brown      (id 999)

Body Covering
[ ] Fur        (id 233)
[ ] Scales     (id 333)
[x] Feathers   (id 455)
</code>```

I'd expect the above checked boxes to select all animals that are brown AND have feathers. I can get this data with the following query:

```<code>SELECT animalId
FROM animalAttributes
WHERE attributeId IN (999,455)
GROUP BY animalId
HAVING COUNT(DISTINCT attributeId) = 2;
</code>```

The issue I'm having is when there are multiple options selected from multiple filters e.g.

```<code>Animal options

Colour
[x] Black      (id 685)
[x] Brown      (id 999)

Body Covering
[x] Fur        (id 233)
[ ] Scales     (id 333)
[x] Feathers   (id 455)
</code>```

I'd expect the above checked boxes to select all animals that are (black OR brown) AND have (fur OR feathers). I can get this data with the following query:

```<code>SELECT animalId
FROM animalAttributes
WHERE
attributeId IN (685,233) ||
attributeId IN (685,455) ||
attributeId IN (999,233) ||
attributeId IN (999,455)
GROUP BY animalId
HAVING COUNT(DISTINCT attributeId) = 2;
</code>```

If I wanted to add additional filters such as "Has Tail", "Can fly", "Blood type", etc, am I right in thinking I'd need to calculate all combinations (cartesian product) and follow the same pattern as above? e.g. 5 filters, each with 1 or more options selected

```<code>attributeId IN (x,x,x,x,x) ||
attributeId IN (x,x,x,x,x) ||
attributeId IN (x,x,x,x,x) ||
...
HAVING COUNT(DISTINCT attributeId) = 5;
</code>```

other tables for reference

Table: attributes

```<code>attributeId    attributeCategoryId    attribute

233            1                      Fur
333            1                      Scales
455            1                      Feathers
685            2                      Black
999            2                      Brown
-----------------------------------------------
</code>```

Table: attributeCategories

```<code>attributeCategoryId    category
1                      Body covering
2                      Colour
------------------------------------
</code>```

答:
```<code>attributeId IN (685,233) ||
attributeId IN (685,455) ||
attributeId IN (999,233) ||
attributeId IN (999,455)
</code>```

will be the same as if you write:
    attributeId IN (685,233,455,999,233)

Try:

```<code>SELECT aa.animalId
FROM animalAttributes aa
LEFT JOIN attributes a ON a.attributeId = aa.attributeId
WHERE
(aa.attributeId IN (685,99) AND a.attributeCategoryId=1) AND
(aa.attributeId IN (223,455) AND a.attributeCAtegoryId=2)
GROUP BY animalId
</code>```

Or in words:
(black OR brown AND isColor) AND (fur OR feathers AND isBodyCovering)

Untestet, but you should get the idea.

Body:
From the table structure below I'd like to be able to provide search filters based on combinations of attributes:

Table: animalAttributes

id      attributeId     animalId
1       455             55
2       999             55
3       685             55
4       999             89
5       455             89
6       333             93
7       685             93
8       999             93
--------------------------------

The front end would have checkboxes e.g.

Animal options

Colour
[ ] Black      (id 685)
[x] Brown      (id 999)

Body Covering
[ ] Fur        (id 233)
[ ] Scales     (id 333)
[x] Feathers   (id 455)

I'd expect the above checked boxes to select all animals that are brown AND have feathers. I can get this data with the following query:

SELECT animalId
FROM animalAttributes
WHERE attributeId IN (999,455)
GROUP BY animalId
HAVING COUNT(DISTINCT attributeId) = 2;

The issue I'm having is when there are multiple options selected from multiple filters e.g.

Animal options

Colour
[x] Black      (id 685)
[x] Brown      (id 999)

Body Covering
[x] Fur        (id 233)
[ ] Scales     (id 333)
[x] Feathers   (id 455)

I'd expect the above checked boxes to select all animals that are (black OR brown) AND have (fur OR feathers). I can get this data with the following query:

SELECT animalId
FROM animalAttributes
WHERE
attributeId IN (685,233) ||
attributeId IN (685,455) ||
attributeId IN (999,233) ||
attributeId IN (999,455)
GROUP BY animalId
HAVING COUNT(DISTINCT attributeId) = 2;

If I wanted to add additional filters such as "Has Tail", "Can fly", "Blood type", etc, am I right in thinking I'd need to calculate all combinations (cartesian product) and follow the same pattern as above? e.g. 5 filters, each with 1 or more options selected

attributeId IN (x,x,x,x,x) ||
attributeId IN (x,x,x,x,x) ||
attributeId IN (x,x,x,x,x) ||
...
HAVING COUNT(DISTINCT attributeId) = 5;

other tables for reference

Table: attributes

attributeId    attributeCategoryId    attribute

233            1                      Fur
333            1                      Scales
455            1                      Feathers
685            2                      Black
999            2                      Brown
-----------------------------------------------

Table: attributeCategories

attributeCategoryId    category
1                      Body covering
2                      Colour
------------------------------------

Body:
attributeId IN (685,233) ||
attributeId IN (685,455) ||
attributeId IN (999,233) ||
attributeId IN (999,455)

will be the same as if you write:
    attributeId IN (685,233,455,999,233)

Try:

SELECT aa.animalId
FROM animalAttributes aa
LEFT JOIN attributes a ON a.attributeId = aa.attributeId
WHERE
(aa.attributeId IN (685,99) AND a.attributeCategoryId=1) AND
(aa.attributeId IN (223,455) AND a.attributeCAtegoryId=2)
GROUP BY animalId

Or in words:
(black OR brown AND isColor) AND (fur OR feathers AND isBodyCovering)

Untestet, but you should get the idea.


问:
Single selection recyclerView not working in fragment
I'm using singleSelection recyclerView it was working correct in activity but when i conevert it activity to fragment it's showing me error like

I'm using this code in freagment

```<code>public class HomeworkFragment extends Fragment implements HomeworkAdapter.SingleClickListener
</code>```

.

```<code>adapter = new HomeworkAdapter(view.getContext(), productList);
                        adapter.setOnItemClickListener(view.getContext()); //error here
                        recyclerView.setAdapter(adapter);
</code>```

.

```<code> @Override
    public void onItemClickListener(int position, View view) {
        adapter.selectedItem();
    }
</code>```

This code in Adapter

```<code>private static SingleClickListener sClickListener;

 public void setOnItemClickListener(SingleClickListener clickListener) {
        sClickListener = clickListener;
    }

    public interface SingleClickListener {
        void onItemClickListener(int position, View view);
    }
</code>```

I don't know what is the problem but i tries only fewThings like getActivity(), view.getContext() but nothing works

When it was in activity I was doing this adapter.setOnItemClickListener(HomeworkActivity.this); it was working fine in activity

Thanks in advance!

Happy coding!

答: your method setOnItemClickListener(SingleClickListener clickListener) takes SingleClickListener  as an  argument so you should pass this or HomeFragment.this instead of context

Body:
I'm using singleSelection recyclerView it was working correct in activity but when i conevert it activity to fragment it's showing me error like

I'm using this code in freagment

public class HomeworkFragment extends Fragment implements HomeworkAdapter.SingleClickListener

.

adapter = new HomeworkAdapter(view.getContext(), productList);
                        adapter.setOnItemClickListener(view.getContext()); //error here
                        recyclerView.setAdapter(adapter);

.

 @Override
    public void onItemClickListener(int position, View view) {
        adapter.selectedItem();
    }

This code in Adapter

private static SingleClickListener sClickListener;

 public void setOnItemClickListener(SingleClickListener clickListener) {
        sClickListener = clickListener;
    }

    public interface SingleClickListener {
        void onItemClickListener(int position, View view);
    }

I don't know what is the problem but i tries only fewThings like getActivity(), view.getContext() but nothing works

When it was in activity I was doing this adapter.setOnItemClickListener(HomeworkActivity.this); it was working fine in activity

Thanks in advance!

Happy coding!


问:
How to find if the previous character is the same
I am trying to create a calculator.

My problem is the buttons could be double clicked creating 2 of the same characters next to each other (Example: 2++2). I want to remove the second plus sign.

So far I've managed to use this:

if(!y.includes("+")) {
  summed.push("+")
  document.getElementById("num").innerHTML = summed.join('')
}
```

But this will only allow 1 plus sign and would disable any other. My intended solution should be this (3+3+3) and not this (3++3). Hopefully this is understandable.

答:
try out this:</p>

```<code>let math = [...]

if(math[math.length - 1] == "+") {
// do not allow to append another +
}
</code>```

Body:
I am trying to create a calculator.

My problem is the buttons could be double clicked creating 2 of the same characters next to each other (Example: 2++2). I want to remove the second plus sign.

So far I've managed to use this:

if(!y.includes("+")) {
  summed.push("+")
  document.getElementById("num").innerHTML = summed.join('')
}

But this will only allow 1 plus sign and would disable any other. My intended solution should be this (3+3+3) and not this (3++3). Hopefully this is understandable.

Body:
try out this:

let math = [...]

if(math[math.length - 1] == "+") {
// do not allow to append another +
}