问:
How to force git to update single file
I have a file which should be updated on github.
Although when i try to update this file with command

```<code>$ git commit -m 'update' package.json
</code>```

I recieve nothing to commit, working three clean.

Can i force git to update this file any way?

答:
Try</p>
```<code>git add package.json; git commit -m 'update'
</code>```

Title: How to force git to update single file

Body:
I have a file which should be updated on github.
Although when i try to update this file with command

$ git commit -m 'update' package.json

I recieve nothing to commit, working three clean.

Can i force git to update this file any way?

Body:
Try

git add package.json; git commit -m 'update'


来源: stackexchange

问:
How to find package for a dictionary object in Eclipse ADT?
I am trying to determine a package for an data element, or domain, or whatever via Eclipse ADT, but have no luck. I'm doing usual object search via project search (Ctrl-Shift-A), and both Global search (Ctrl-H), the result is the same.

I see domain properties window

and it has no clue about what package it is.

What I've tried so far:

Using filters in project search bar, callable via Ctrl-Space

Package filter does not help, it lists all packages, not the relevant ones, where this domain was found. Picking each and every package will take infinity amount of time, because the hierarchy is huge.

Pressing "Link with editor" button

For some reason it doesn't work, should it with DDIC objects? When I press it with domain opened right-side, just nothing happens. In the help and e.g. here they describe it should open the object in the left within hierarchy.

Is it something broken with my ADT or this button doesn't work with DDIC objects?

P.S. It is ABAP Cloud trial system, if that matters.

答: Package can be seen in Properties tool (see the bottom part of the screenshot below)

ContentLicense: CC BY-SA 4.0


问:
Does JavaScript provide a history of prior events that occurred?
I was wondering if JavaScript records information about the prior events that occurred so that I could use the information to perform a specific course of action in the current event?

For example, I have an element that has an OnBlur event handler, but I would like to know the event that occurred prior to the OnBlur event that triggered the OnBlur event to occur, such as the user pressing the Tab key, arrow key, or mouse click that moved focus away from the element.

So does JavaScript provide any mechanism to facilitate access to the events history or can people throw ideas to me at good ways of implementing this?

答: No, there is no such history maintained by any browser implementation: the history api I believe maintains URl traversal, but nothing tracks individual events. If you need one you will probably need to implement one yourself.</p>

ContentLicense: CC BY-SA 3.0


问:
Swift Macos GameController not showing. Controller.count return zero
I'm developing an app which includes Gamecontroller. I'm trying to show the connected controller count, but it´s not working.

Here is my simple code:

```<code>import Cocoa
import GameController

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        // - MARK: Controllers

        let controllers = GCController.controllers()
        print(controllers.count)
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }
}
</code>```

it always prints 0

What am I doing wrong?

EDIT:

The problem was i mised to add:

```<code>   let ctr = NotificationCenter.default
   ctr.removeObserver(self, name: .GCControllerDidConnect, object: nil)
   ctr.removeObserver(self, name: .GCControllerDidDisconnect, object: nil)
</code>```

To handle when a controller is connected

答:
Fixed using this tutorial: tvOS Games, Part 1: Using the Game Controller Framework

The next problem is to find a unique identifier for the device...

EDIT:

The problem was i mised to add:

```<code>let ctr = NotificationCenter.default
   ctr.removeObserver(self, name: .GCControllerDidConnect, object: nil)
   ctr.removeObserver(self, name: .GCControllerDidDisconnect, object: nil)
</code>```

To handle when a controller is connected

Body:
I'm developing an app which includes Gamecontroller. I'm trying to show the connected controller count, but it´s not working.

Here is my simple code:

import Cocoa
import GameController

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        // - MARK: Controllers

        let controllers = GCController.controllers()
        print(controllers.count)
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }
}

it always prints 0

What am I doing wrong?

EDIT:

The problem was i mised to add:

   let ctr = NotificationCenter.default
   ctr.removeObserver(self, name: .GCControllerDidConnect, object: nil)
   ctr.removeObserver(self, name: .GCControllerDidDisconnect, object: nil)

To handle when a controller is connected

Body:
Fixed using this tutorial: tvOS Games, Part 1: Using the Game Controller Framework

The next problem is to find a unique identifier for the device...

EDIT:

The problem was i mised to add:

let ctr = NotificationCenter.default
   ctr.removeObserver(self, name: .GCControllerDidConnect, object: nil)
   ctr.removeObserver(self, name: .GCControllerDidDisconnect, object: nil)

To handle when a controller is connected


问:
Autoscaling in seaborn of axis values and legend
So, I was learning to build deep learning models, and during the visualization part I plotted a scatterplot where x and y axis were longitude and latitude, respectively, and the hue was equal to house prices. Although the price values were in float format, the legend is showing in different scaled value.

```<code>import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv("../DATA/kc_house_data.csv")
sns.histplot(df['price'])
</code>```

```<code>non_top_1_perct = df.sort_values('price',ascending=False).iloc[216:]
plt.figure(figsize=(12,8))
sns.scatterplot(x= 'long', y= 'lat', data =non_top_1_perct,
           edgecolor = None, alpha = 0.2, palette  ='RdYlGn', hue='price')
</code>```

Here, in the first picture, one can notice that x-axis scale is in formatted into scientific notation. Also, in the legend box, if I want to show 7,700,000 instead of 1.6, how I have to rescale both of them?

Data: kaggle house data

答:
Here is an example how you can modify your legend based on the values of existing legend entries.

```<code>import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame({
    'lat': [4, 24, 31, 2, 3],
    'long': [3, 5, 5, 6, 7],
    'price':[35e6, 54899767, 57890789, 62890798, 70897871]
})
ax = sns.scatterplot(y="lat", x="long", data=df, hue='price')

# modify legend entries
handles = ax.get_legend().legendHandles
ax.legend(handles, [str(round(float(v.get_label())/1e6,1))+'m' for v in handles] , loc='upper left')

# disable scientific notation on y axis
ax.ticklabel_format(style='plain', axis='y')
</code>```

You have to adapt this to your task.

Body:
So, I was learning to build deep learning models, and during the visualization part I plotted a scatterplot where x and y axis were longitude and latitude, respectively, and the hue was equal to house prices. Although the price values were in float format, the legend is showing in different scaled value.

import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv("../DATA/kc_house_data.csv")
sns.histplot(df['price'])

non_top_1_perct = df.sort_values('price',ascending=False).iloc[216:]
plt.figure(figsize=(12,8))
sns.scatterplot(x= 'long', y= 'lat', data =non_top_1_perct,
           edgecolor = None, alpha = 0.2, palette  ='RdYlGn', hue='price')

Here, in the first picture, one can notice that x-axis scale is in formatted into scientific notation. Also, in the legend box, if I want to show 7,700,000 instead of 1.6, how I have to rescale both of them?

Data: kaggle house data

Body:
Here is an example how you can modify your legend based on the values of existing legend entries.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame({
    'lat': [4, 24, 31, 2, 3],
    'long': [3, 5, 5, 6, 7],
    'price':[35e6, 54899767, 57890789, 62890798, 70897871]
})
ax = sns.scatterplot(y="lat", x="long", data=df, hue='price')

# modify legend entries
handles = ax.get_legend().legendHandles
ax.legend(handles, [str(round(float(v.get_label())/1e6,1))+'m' for v in handles] , loc='upper left')

# disable scientific notation on y axis
ax.ticklabel_format(style='plain', axis='y')

You have to adapt this to your task.


问:
Select option in dropdown box using Rselenium
I'm trying to use RSelenium to select the theme 'loneliness' from the drop-down box in the tab mental health and wellbeing from https://analytics.phe.gov.uk/apps/covid-19-indirect-effects/#. I can get Rselenium to go the the mental health tab but I haven't had any luck in selecting the 'loneliness' theme. I would be grateful for any steer as I've reviewed many posts from Stack Overflow (you can chuckle at my many failed attempts) and still no joy.

I would be really grateful for any pointers!

```<code>library(tidyverse)
library(rvest)
library(RSelenium)

# Start Selenium server and browser

driver <- rsDriver(
  browser = "chrome",
  chromever = "97.0.4692.71"
)

remDr <- driver$client

# Navigate to wich tool
remDr$navigate("https://analytics.phe.gov.uk/apps/covid-19-indirect-effects/")

#changing the page to the mental health and well being tab
##avoided using href as the tab value keeps changing

webElem <- remDr$findElement(using = 'xpath', value = '//*[@id="page"]/nav/div/ul/li[8]/a')

# Highlight to check that was correctly selected - don't need but putting it in as a check

webElem$highlightElement()

# click the search link
webElem$clickElement()

# click the link
webElem$clickElement()

#multiple failed attempts of trying to selecting the theme = Loneliness - can't get to work :-(
##attempt 1
webElem <- remDr$findElement(using = 'xpath', value = "//*[@data-shinyjs-resettable-id='themeOPN']")
webElem$highlightElement()
webElem$clickElement()

webElem1 <- remDr$findElement(using = 'xpath', value = "//*[@data-selectable data-value='Loneliness']")
webElem1$highlightElement()
webElem1$clickElement()

##
##attempt 2
webElem <- remDr$findElement(using = 'xpath', value = "//*[@data-shinyjs-resettable-id='themeOPN']")
webElem$highlightElement()
webElem$clickElement()

webElem2 <- remDr$findElement(using = 'xpath', value = "/html/body/div[1]/div[2]/div/div[8]/div[3]/div[1]/form/div[1]/div/div/div[2]/div/div[2]")
webElem2$highlightElement()
webElem2$clickElement()

##
##attempt 3

webElem <- remDr$findElement(using = 'xpath', value = "//*[@data-shinyjs-resettable-id='themeOPN']")
webElem$highlightElement()
webElem$clickElement()

webElem3 <- remDr$findElement(using = 'xpath', value = "//*[text()='Loneliness']")
webElem3$highlightElement()
webElem3$clickElement()

##
##attempt 4

webElem <- remDr$findElement(using = 'xpath', value = "//*[@data-shinyjs-resettable-id='themeOPN']")
webElem$highlightElement()
webElem$clickElement()

webElem4 <- remDr$findElement(using = 'xpath', "/html/body/div[1]/div[2]/div/div[8]/div[3]/div[1]/form/div[1]/div/div/div[2]/div/[@value = 'Loneliness']")
webElem4$highlightElement()
webElem4$clickElement()

##
##attempt 5

webElem <- remDr$findElement(using = 'xpath', value = "//*[@data-shinyjs-resettable-id='themeOPN']")
webElem[[2]]$clickElement()
</code>```

答:
Looks like the dropdowns are using selectize.js. Something like the below seems to work:

library(tidyverse)
library(rvest)
library(RSelenium)

# Start Selenium server and browser

driver <- rsDriver(
  browser = "chrome",
  chromever = "98.0.4758.80"
)

remDr <- driver$client

# Navigate to wich tool
remDr$navigate("https://analytics.phe.gov.uk/apps/covid-19-indirect-effects/")
select_tab <- remDr$findElement(using = "xpath", value = '//*[@id="indicatortable"]/div/div[1]/div[2]/div[6]/div/div[6]/div/a')

# Highlight to check that was correctly selected - don't need but putting it in as a check

select_tab$highlightElement()
select_tab$clickElement()

remDr$executeScript("
  var s = $('#themeOPN').selectize()[0];
  s.selectize.setValue('Loneliness');
")

```

Body:
I'm trying to use RSelenium to select the theme 'loneliness' from the drop-down box in the tab mental health and wellbeing from https://analytics.phe.gov.uk/apps/covid-19-indirect-effects/#. I can get Rselenium to go the the mental health tab but I haven't had any luck in selecting the 'loneliness' theme. I would be grateful for any steer as I've reviewed many posts from Stack Overflow (you can chuckle at my many failed attempts) and still no joy.

I would be really grateful for any pointers!

library(tidyverse)
library(rvest)
library(RSelenium)

# Start Selenium server and browser

driver <- rsDriver(
  browser = "chrome",
  chromever = "97.0.4692.71"
)

remDr <- driver$client

# Navigate to wich tool
remDr$navigate("https://analytics.phe.gov.uk/apps/covid-19-indirect-effects/")

#changing the page to the mental health and well being tab
##avoided using href as the tab value keeps changing

webElem <- remDr$findElement(using = 'xpath', value = '//*[@id="page"]/nav/div/ul/li[8]/a')

# Highlight to check that was correctly selected - don't need but putting it in as a check

webElem$highlightElement()

# click the search link
webElem$clickElement()

# click the link
webElem$clickElement()

#multiple failed attempts of trying to selecting the theme = Loneliness - can't get to work :-(
##attempt 1
webElem <- remDr$findElement(using = 'xpath', value = "//*[@data-shinyjs-resettable-id='themeOPN']")
webElem$highlightElement()
webElem$clickElement()

webElem1 <- remDr$findElement(using = 'xpath', value = "//*[@data-selectable data-value='Loneliness']")
webElem1$highlightElement()
webElem1$clickElement()

##
##attempt 2
webElem <- remDr$findElement(using = 'xpath', value = "//*[@data-shinyjs-resettable-id='themeOPN']")
webElem$highlightElement()
webElem$clickElement()

webElem2 <- remDr$findElement(using = 'xpath', value = "/html/body/div[1]/div[2]/div/div[8]/div[3]/div[1]/form/div[1]/div/div/div[2]/div/div[2]")
webElem2$highlightElement()
webElem2$clickElement()

##
##attempt 3

webElem <- remDr$findElement(using = 'xpath', value = "//*[@data-shinyjs-resettable-id='themeOPN']")
webElem$highlightElement()
webElem$clickElement()

webElem3 <- remDr$findElement(using = 'xpath', value = "//*[text()='Loneliness']")
webElem3$highlightElement()
webElem3$clickElement()

##
##attempt 4

webElem <- remDr$findElement(using = 'xpath', value = "//*[@data-shinyjs-resettable-id='themeOPN']")
webElem$highlightElement()
webElem$clickElement()

webElem4 <- remDr$findElement(using = 'xpath', "/html/body/div[1]/div[2]/div/div[8]/div[3]/div[1]/form/div[1]/div/div/div[2]/div/[@value = 'Loneliness']")
webElem4$highlightElement()
webElem4$clickElement()

##
##attempt 5

webElem <- remDr$findElement(using = 'xpath', value = "//*[@data-shinyjs-resettable-id='themeOPN']")
webElem[[2]]$clickElement()


问:
Using List as a key in map in Dart
Here is my Dart code

```<code>var mp = new Map();
  mp[[1,2]] = "Hi";
  mp[[3,5]] = "sir";
  mp.remove([3,5]);
  print(mp);
</code>```

Output here is null

How can i access value at mp[[3,5]]?

答:
You add a list instance as a key to the Map object. You need the corresponding list instance to delete it again.

There are two ways to access

First;

  final mp = {};
  mp[[1,2]] = "Hi";
  mp[[3,5]] = "sir";
  mp.removeWhere((key, value) {
    if(key is List){
      return key.first == 3 && key[1] == 5;
    }
    return false;
  });
```
<p>Second;</p>
<pre class="lang-dart prettyprint-override"><code>  final mp = {};
  final key = [3, 5];
  mp[[1,2]] = "Hi";
  mp[key] = "sir";
  mp.remove(key);
</code>```

Title: Using List as a key in map in Dart

Body:
Here is my Dart code

var mp = new Map();
  mp[[1,2]] = "Hi";
  mp[[3,5]] = "sir";
  mp.remove([3,5]);
  print(mp);

Output here is null

How can i access value at mp[[3,5]]?

Body:
You add a list instance as a key to the Map object. You need the corresponding list instance to delete it again.

There are two ways to access

First;

  final mp = {};
  mp[[1,2]] = "Hi";
  mp[[3,5]] = "sir";
  mp.removeWhere((key, value) {
    if(key is List){
      return key.first == 3 && key[1] == 5;
    }
    return false;
  });

Second;

  final mp = {};
  final key = [3, 5];
  mp[[1,2]] = "Hi";
  mp[key] = "sir";
  mp.remove(key);


问:
How can we riffle shuffle the elements of a list in Python?
I want to shuffle the elements of a list without importing any module.
The type of shuffle is a riffle shuffle. It is where you want to divide the number of elements of the list into two and then interleave them.

If there are odd number of elements then the second half should contain the extra element.

eg:

```<code>list = [1,2,3,4,5,6,7]
</code>```

Then the final list should look like

```<code>[1,4,2,5,3,6,7]
</code>```

答:
```<code>def riffle(deck):
    new_deck = []
    deck_1 = deck[:len(deck)//2]
    deck_2 = deck[len(deck)//2::]
    for i in range(len(deck)//2):
        new_deck.append(deck_1[i])
        new_deck.append(deck_2[i])
    if len(deck) % 2 == 1:
        new_deck.append(deck[-1])
    return new_deck

deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
print(riffle(deck))
</code>```

Body:
I want to shuffle the elements of a list without importing any module.
The type of shuffle is a riffle shuffle. It is where you want to divide the number of elements of the list into two and then interleave them.

If there are odd number of elements then the second half should contain the extra element.

eg:

list = [1,2,3,4,5,6,7]

Then the final list should look like

[1,4,2,5,3,6,7]


问:
CometD/Bayeux client for iphone
Im looking for a Bayeux/CometD client for the iPhone. Objective-C implementation would work. Any idea where I can get it from? or any idea how I can create one cometD client for iphone .</p>

答: This one can be a good start.</p>

Title: CometD/Bayeux client for iphone

Body: This one can be a good start.


问:
Use Javascript to access a variable passed through Twig
I have a controller that passes an array to a twig template, which I want to use in a script written on that page.  How would I go about doing that?

I've tried this in my .twig template:

```<code><script>
    $(document).ready(function(){
        var test = {{ testArray }};
});
</script>
</code>```

but that only works if it's a string.

答:
json_encode works well, in combination with the raw filter.

```

Don't forget the JSON_HEX_TAG flag.

Otherwise, you can get broken HTML. A string containing

Body:
I have a controller that passes an array to a twig template, which I want to use in a script written on that page.  How would I go about doing that?

I've tried this in my .twig template:

but that only works if it's a string.

Body:
json_encode works well, in combination with the raw filter.

<script>
    $(document).ready(function(){
        let test = {{ testArray | json_encode(constant('JSON_HEX_TAG')) | raw }};
    });
</script>

Don't forget the JSON_HEX_TAG flag.

Otherwise, you can get broken HTML. A string containing <!--<script> is a good way to test that.


问:
How to write Jquery script in Vuejs
I try code to build Navbar in Vueenter image description herejs, while scrolling change color using Jquery and CSS script. This work but, in part .... Vue js not support syntax $, when i refresh page. There error " $ not defined". I'm new here and at Vuejs, sorry if there is a wrong word in the delivery. I hope someone can help me. Thank you :).

This code Vue :

.navbar{
  transition:500ms ease;
  background: transparent;
  font-weight: 600;
}

.navbar.scrolled {
  background:#fff;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
}

.nav-link {
  color: white;
}

.nav-link:hover {
  color: lightgray;
}
.nav-link:focus {
  color: lightgray;
}

.navbar-brand.change-black, .nav-link.change-black {
  color:#000;
}

.nav-link.change-black:hover, .nav-link.change-black:focus {
  color:#0d6efd;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
    <b-app>
        <b-nav class="navbar navbar-expand-lg pt-12 pb-12 fixed-top fluid"
        data-aos="fade-down" data-aos-duration="700"
        >
            <b-container>
                    <b-col lg="3">
                        <b-nav-item class="navbar-brand" href="#">
                            <span>APR</span>
                        </b-nav-item>
                    </b-col>
                    <b-col lg="8" class="d-flex">
                        <b-nav-item class="nav-link" href="#">Home</b-nav-item>
                        <b-nav-item class="nav-link" href="#">Procedure</b-nav-item>
                        <b-nav-item class="nav-link" href="#">About</b-nav-item>
                    </b-col>
                    <b-col lg="1" class="d-flex" right>
                        <b-nav-item-dropdown
                        id="my-nav-dropdown"
                        text="Masuk"
                        toggle-class="nav-link-custom"
                        right
                        >
                            <b-dropdown-item>Lecturer</b-dropdown-item>
                            <b-dropdown-divider></b-dropdown-divider>
                            <b-dropdown-item>Secretary</b-dropdown-item>
                        </b-nav-item-dropdown>
                    </b-col>
            </b-container>
        </b-nav>
    </b-app>

</template>

<script>
export default {
        name: 'CoverLayout',
        data () {
            return {
            }
        },
}

$(window).scroll(function(){
$('.navbar').toggleClass('scrolled', $(this).scrollTop() > 50);
$('.nav-link').toggleClass('change-black', $(this).scrollTop() > 50);
$('.navbar-brand').toggleClass('change-black', $(this).scrollTop() > 50);
$('.back-to-top').toggleClass('active', $(this).scrollTop() > 50);
});

</script></code>```

[Work if i not refresh page
][Error when i refresh page]

答:
Stay away from jQuery when using Vue. Just stick with plain old vanilla JS. It's more than capable of handling this task by using an event listener.

Something like:

```<code>const navBar = document.querySelector(".navbar");
const navLink = document.querySelector(".nav-link");
const navBarBrand = document.querySelector(".navbar-brand");
const backToTop = document.querySelector(".back-to-top");

window.addEventListener('scroll',handleScroll);

function handleScroll(){
      let scrollPosition = window.pageYOffset || window.scrollY || document.body.scrollTop || document.documentElement.scrollTop;

  if(scrollPosition >50) {
    navbar.classList.add("scrolled");
    navLink.classList.add("change-black");
    navBarBrand.classList.add("change-black");
    backToTop.classList.add("active");
 } else {
    // ...
 }

}
</code>```

Title: How to write Jquery script in Vuejs

Body:
I try code to build Navbar in Vueenter image description herejs, while scrolling change color using Jquery and CSS script. This work but, in part .... Vue js not support syntax $, when i refresh page. There error " $ not defined". I'm new here and at Vuejs, sorry if there is a wrong word in the delivery. I hope someone can help me. Thank you :).

This code Vue :

.navbar{
  transition:500ms ease;
  background: transparent;
  font-weight: 600;
}

.navbar.scrolled {
  background:#fff;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
}

.nav-link {
  color: white;
}

.nav-link:hover {
  color: lightgray;
}
.nav-link:focus {
  color: lightgray;
}

.navbar-brand.change-black, .nav-link.change-black {
  color:#000;
}

.nav-link.change-black:hover, .nav-link.change-black:focus {
  color:#0d6efd;
}

<template>

                            APR

                        Home
                        Procedure
                        About

                            Lecturer

                            Secretary

</template>

[Work if i not refresh page
][Error when i refresh page]

Body:
Stay away from jQuery when using Vue. Just stick with plain old vanilla JS. It's more than capable of handling this task by using an event listener.

Something like:

const navBar = document.querySelector(".navbar");
const navLink = document.querySelector(".nav-link");
const navBarBrand = document.querySelector(".navbar-brand");
const backToTop = document.querySelector(".back-to-top");

window.addEventListener('scroll',handleScroll);

function handleScroll(){
      let scrollPosition = window.pageYOffset || window.scrollY || document.body.scrollTop || document.documentElement.scrollTop;

  if(scrollPosition >50) {
    navbar.classList.add("scrolled");
    navLink.classList.add("change-black");
    navBarBrand.classList.add("change-black");
    backToTop.classList.add("active");
 } else {
    // ...
 }

}


问:
how to copy data from one xml files in to another using java xslt

I need to replace all ? in file1.xml with element value present in File2.xml.

And also need to remove extra element node present in File1.xml whose value is not present in File2.xml. (i.e. In my sample input need to remove totalDueWithoutTax element from file1.xml as it is not present in File2.xml.

There may be the cases where we have multiple elements in File2 but only one corresponsing element in File1. Like in my below example we have two salesInfo element in File2 but in File1 we have only one. In that case as a expected output we need both salesInfo element of File2.

This is just sample input. In real scenario input xmls can be different means we can get different format of xmls everytime.

Please suggest me how to do that in java. It would be better if we can achieve this using xslt.

```<code>        **File 1 -- input xml**
       <order>
            <orderId>?</orderId>
             <sales>
              <salesInfo>
                <salesChannel>?</salesChannel>
                <senderSystemId>?</senderSystemId>
                <applicationId>?</applicationId>
                <totalDueWithoutTax>?</totalDueWithoutTax>
              </salesInfo>
              <salesid>?</salesid>
           </sales>
        </order>

        **File 2 -- input xml**

        <order>
          <orderId>4567</orderId>
          <sales>
              <salesInfo>
                <salesChannel>abc</salesChannel>
                <senderSystemId>def</senderSystemId>
                <applicationId>123</applicationId>
                <esignatureCaptureMode>INLINE</esignatureCaptureMode>
              </salesInfo>
              <salesInfo>
                <salesChannel>xyz</salesChannel>
                <senderSystemId>uvw</senderSystemId>
                <applicationId>234</applicationId>
                <esignatureCaptureMode>outline</esignatureCaptureMode>
              </salesInfo>
              <salesid>789</salesid>
        </sales>
        </order>

        **Expected output:**

        <order>
            <orderId>4567</orderId>
            <sales>
              <salesInfo>
                <salesChannel>abc</salesChannel>
                <senderSystemId>def</senderSystemId>
                <applicationId>123</applicationId>
              </salesInfo>
              <salesInfo>
               <salesChannel>xyz</salesChannel>
                <senderSystemId>uvw</senderSystemId>
                <applicationId>234</applicationId>
              </salesInfo>
              <salesid>789</salesid>
          </sales>
        </order>
</code>```

答:
An "out of the box" suggestion: you might like to think of your file1 as representing a little templating language. If you think of it that way, then one option that comes to mind is to translate your little templating language into XSLT (a translation which, of course, can be done using XSLT).

So your transformation would convert

```<code><salesChannel>?</salesChannel>
</code>```

to

```<code><salesChannel>
      <xsl:value-of select="order/salesinfo/saleschannel"/>
</salesChannel>
</code>```

where the expression in the select attribute is obtained by calling path().

The advantage of this approach is that you can start to grow your "little templating language" to include extra features, such as loops and conditionals, as the requirements appear.

Body:
I need to replace all ? in file1.xml with element value present in File2.xml.

And also need to remove extra element node present in File1.xml whose value is not present in File2.xml. (i.e. In my sample input need to remove totalDueWithoutTax element from file1.xml as it is not present in File2.xml.

There may be the cases where we have multiple elements in File2 but only one corresponsing element in File1. Like in my below example we have two salesInfo element in File2 but in File1 we have only one. In that case as a expected output we need both salesInfo element of File2.

This is just sample input. In real scenario input xmls can be different means we can get different format of xmls everytime.

Please suggest me how to do that in java. It would be better if we can achieve this using xslt.

        **File 1 -- input xml**
       <order>
            <orderId>?</orderId>
             <sales>
              <salesInfo>
                <salesChannel>?</salesChannel>
                <senderSystemId>?</senderSystemId>
                <applicationId>?</applicationId>
                <totalDueWithoutTax>?</totalDueWithoutTax>
              </salesInfo>
              <salesid>?</salesid>
           </sales>
        </order>

        **File 2 -- input xml**

        <order>
          <orderId>4567</orderId>
          <sales>
              <salesInfo>
                <salesChannel>abc</salesChannel>
                <senderSystemId>def</senderSystemId>
                <applicationId>123</applicationId>
                <esignatureCaptureMode>INLINE</esignatureCaptureMode>
              </salesInfo>
              <salesInfo>
                <salesChannel>xyz</salesChannel>
                <senderSystemId>uvw</senderSystemId>
                <applicationId>234</applicationId>
                <esignatureCaptureMode>outline</esignatureCaptureMode>
              </salesInfo>
              <salesid>789</salesid>
        </sales>
        </order>

        **Expected output:**

        <order>
            <orderId>4567</orderId>
            <sales>
              <salesInfo>
                <salesChannel>abc</salesChannel>
                <senderSystemId>def</senderSystemId>
                <applicationId>123</applicationId>
              </salesInfo>
              <salesInfo>
               <salesChannel>xyz</salesChannel>
                <senderSystemId>uvw</senderSystemId>
                <applicationId>234</applicationId>
              </salesInfo>
              <salesid>789</salesid>
          </sales>
        </order>

Body:
An "out of the box" suggestion: you might like to think of your file1 as representing a little templating language. If you think of it that way, then one option that comes to mind is to translate your little templating language into XSLT (a translation which, of course, can be done using XSLT).

So your transformation would convert

<salesChannel>?</salesChannel>

to

<salesChannel>
      <xsl:value-of select="order/salesinfo/saleschannel"/>
</salesChannel>

where the expression in the select attribute is obtained by calling path().

The advantage of this approach is that you can start to grow your "little templating language" to include extra features, such as loops and conditionals, as the requirements appear.


问:
Change background-color of html5 video element
I've got the following website:
beta.leifsigersen.com

There's a movie on the front page which sometimes takes a little while to load (sometimes less than a second, sometimes a few seconds). Before the movie is loaded there's black background/borders. How can I change the color of this?

I've tried to use CSS of the video-element, but without any luck.

答:
I have used overlay content like so: Ionic/Angular

.html

```<code><video autoplay muted loop playsinline preload="auto" onloadedmetadata="this.muted = true">
  <source [src]="video" type="video/mp4" />
</video>

<div class="overlay-content"></div>
</code>```

.scss

```<code> video {
     object-fit: cover;
     width: 100vw;
     height: 60vh;
     top: 0;
     left: 0;
     opacity: 0.5;
     -webkit-filter: blur(5px);
     -moz-filter: blur(5px);
     -o-filter: blur(5px);
     -ms-filter: blur(5px);
     filter: blur(5px);
 }

 .overlay-content {
     position: absolute;
     top: 0;
     left: 0;
     background: rgba(6, 56, 82, 0.5);
     width: 100vw;
     height: 60vh;
 }
</code>```

Body:
I have used overlay content like so: Ionic/Angular

.html

<video autoplay muted loop playsinline preload="auto" onloadedmetadata="this.muted = true">
  <source [src]="video" type="video/mp4" />
</video>

<div class="overlay-content"></div>

.scss

 video {
     object-fit: cover;
     width: 100vw;
     height: 60vh;
     top: 0;
     left: 0;
     opacity: 0.5;
     -webkit-filter: blur(5px);
     -moz-filter: blur(5px);
     -o-filter: blur(5px);
     -ms-filter: blur(5px);
     filter: blur(5px);
 }

 .overlay-content {
     position: absolute;
     top: 0;
     left: 0;
     background: rgba(6, 56, 82, 0.5);
     width: 100vw;
     height: 60vh;
 }


问:
R How to web scrape data from StockTwits with RSelenium?
I want to get some information from tweets posted on the platform StockTwits.
Here you can see an example tweet: https://stocktwits.com/Kndihopefull/message/433815546

I would like to read the following information: Number of replies, number of reshares, number of likes:

I think this is possible with the RSelenium-package. However, I am not really getting anywhere with my approach.
Can someone help me?

```<code>library(RSelenium)

url<- "https://stocktwits.com/Kndihopefull/message/433815546"

# RSelenium with Firefox
rD <- RSelenium::remoteDriver(browser="firefox", port=4546L)
remDr <- rD[["client"]]
remDr$navigate(url)
Sys.sleep(4)

# get the page source
web <- remDr$getPageSource()
web <- xml2::read_html(web[[1]])
</code>```

I would like to have a list (or a data set) as a result, which looks like this:

```<code>$Reply
[1] 1

$Reshare
[1] 1

$Like
[1] 7
</code>```

答:
To get required info we can do,

```<code>library(rvest)
library(dplyr)
library(RSelenium)
#launch browser
driver = rsDriver(browser = c("firefox"))
url = "https://stocktwits.com/ArcherUS/message/434172145"

remDr <- driver$client
remDr$navigate(url)

#First we shall get the tags

remDr$getPageSource()[[1]] %>%
  read_html() %>% html_nodes('.st_3kvJrBm') %>%
  html_attr('title')
[1] "Reply"   "Reshare" "Like"    "Share"   "Search"

#then the number associated with it
remDr$getPageSource()[[1]] %>%
  read_html() %>% html_nodes('.st_3kvJrBm') %>%
  html_text()
[1] ""  ""  "2" ""  ""
</code>```

The last two items Share and Search will be empty.

The faster approach would be by using rvest.

```<code>library(rvest)
url = "https://stocktwits.com/ArcherUS/message/434172145"

url %>%
  read_html() %>% html_nodes('.st_3kvJrBm') %>%
  html_attr('title')

url %>%
  read_html() %>% html_nodes('.st_3kvJrBm') %>%
  html_text()
</code>```

Body:
I want to get some information from tweets posted on the platform StockTwits.
Here you can see an example tweet: https://stocktwits.com/Kndihopefull/message/433815546

I would like to read the following information: Number of replies, number of reshares, number of likes:

I think this is possible with the RSelenium-package. However, I am not really getting anywhere with my approach.
Can someone help me?

library(RSelenium)

url<- "https://stocktwits.com/Kndihopefull/message/433815546"

# RSelenium with Firefox
rD <- RSelenium::remoteDriver(browser="firefox", port=4546L)
remDr <- rD[["client"]]
remDr$navigate(url)
Sys.sleep(4)

# get the page source
web <- remDr$getPageSource()
web <- xml2::read_html(web[[1]])

I would like to have a list (or a data set) as a result, which looks like this:

$Reply
[1] 1

$Reshare
[1] 1

$Like
[1] 7

Body:
To get required info we can do,

library(rvest)
library(dplyr)
library(RSelenium)
#launch browser
driver = rsDriver(browser = c("firefox"))
url = "https://stocktwits.com/ArcherUS/message/434172145"

remDr <- driver$client
remDr$navigate(url)

#First we shall get the tags

remDr$getPageSource()[[1]] %>%
  read_html() %>% html_nodes('.st_3kvJrBm') %>%
  html_attr('title')
[1] "Reply"   "Reshare" "Like"    "Share"   "Search"

#then the number associated with it
remDr$getPageSource()[[1]] %>%
  read_html() %>% html_nodes('.st_3kvJrBm') %>%
  html_text()
[1] ""  ""  "2" ""  ""

The last two items Share and Search will be empty.

The faster approach would be by using rvest.

library(rvest)
url = "https://stocktwits.com/ArcherUS/message/434172145"

url %>%
  read_html() %>% html_nodes('.st_3kvJrBm') %>%
  html_attr('title')

url %>%
  read_html() %>% html_nodes('.st_3kvJrBm') %>%
  html_text()


问:
validate form input from custom library in Codeigniter 3
I have a website where there are multiple form validation processes with the same ruleset. so I want to move the validation code into a single library file. but when I test it, the validation always fails.. why?

here's my code:

the library file:

```<code><?php
/*
 * filename: My_validations.php
 * filedir: application/libraries/
 */
defined('BASEPATH') or exit('No direct script access allowed');

class My_validations
{
    public function __construct()
    {
        $this->ci = &get_instance();
    }

    public function get_rules($params=[])
    {
        $rules = [];

        $module = $params['module'];

        if ($module == 'test')
        {
            $rules[] = [
                'field' => 'phone',
                'label' => 'test phone 1',
                'rules' => 'callback__test_rule1'
            ];
        }

        return $rules;
    }
    // end public function get_rules

    public function _test_rule1()
    {
        return true;
    }
}
</code>```

the controller file:

```<code><?php
/*
 * filename: test1.php
 * filedir: application/modules/test/controllers/
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class Test extends MY_Controller
{
    public function test1()
    {
        $this->load->library('form_validation');
        $this->load->library('My_validations');

        if ($this->input->server('REQUEST_METHOD') == 'POST')
        {
            $params = [
                'module' => 'test',
            ];
            $rules = $this->my_validations->get_rules($params);
            echo 'rules <br>';
            print_r($rules);
            $this->form_validation->set_rules($rules);
            echo 'validate';
            $validate = $this->form_validation->run();
            echo '```'.($validate ? 'OK' : 'failed').'```'; // always 'failed'
        }
        $this->load->view('form', $this->data);
    }
}
</code>```

and here's the form:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form method="post" action="">
        <input type="hidden" id="csrf" name="<?php echo $csrf_name; ?>" value="<?php echo $csrf; ?>">

        <div>
            <label>Phone</label>
            <input type="text" name="phone" value="<?php echo $this->input->post('phone'); ?>">
        </div>

        <input type="submit" value="Kirim">
    </form>
</body>
</html>
</code>```

答:
The form validation callback will only fire on a method inside the current controller. Or extend CI_Form_validation class:

```<code>class MY_Form_validation extends CI_Form_validation {

    function __constuct() {
        parent::__constuct();
    }

    public function get_rules($params=[])
    {
        $rules = [];

        $module = $params['module'];
        if ($module == 'test')
        {
            $rules[] = [
                'field' => 'phone',
                'label' => 'test phone 1',
                'rules' => '_test_rule1'
            ];
        }

        return $rules;
    }
    // end public function get_rules

    public function _test_rule1()
    {
        return TRUE;
    }
}
</code>```

Don't forget to remove "callback_" prefix in rules.

After your corntroller will looks like:

```<code><?php
/*
 * filename: test1.php
 * filedir: application/modules/test/controllers/
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class Test extends MY_Controller
{
    public function test1()
    {
        $this->load->library('form_validation');
        //$this->load->library('My_validations');

        if ($this->input->server('REQUEST_METHOD') == 'POST')
        {
            $params = [
                'module' => 'test',
            ];
            //$rules = $this->my_validations->get_rules($params);
            $rules = $this->form_validation->get_rules($params);
            echo 'rules <br>';
            print_r($rules);
            $this->form_validation->set_rules($rules);
            echo 'validate';
            $validate = $this->form_validation->run();
            echo '```'.($validate ? 'OK' : 'failed').'```'; // always 'failed'
        }
        $this->load->view('form', $this->data);
    }
}
</code>```

Body:
I have a website where there are multiple form validation processes with the same ruleset. so I want to move the validation code into a single library file. but when I test it, the validation always fails.. why?

here's my code:

the library file:

<?php
/*
 * filename: My_validations.php
 * filedir: application/libraries/
 */
defined('BASEPATH') or exit('No direct script access allowed');

class My_validations
{
    public function __construct()
    {
        $this->ci = &get_instance();
    }

    public function get_rules($params=[])
    {
        $rules = [];

        $module = $params['module'];

        if ($module == 'test')
        {
            $rules[] = [
                'field' => 'phone',
                'label' => 'test phone 1',
                'rules' => 'callback__test_rule1'
            ];
        }

        return $rules;
    }
    // end public function get_rules

    public function _test_rule1()
    {
        return true;
    }
}

the controller file:

<?php
/*
 * filename: test1.php
 * filedir: application/modules/test/controllers/
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class Test extends MY_Controller
{
    public function test1()
    {
        $this->load->library('form_validation');
        $this->load->library('My_validations');

        if ($this->input->server('REQUEST_METHOD') == 'POST')
        {
            $params = [
                'module' => 'test',
            ];
            $rules = $this->my_validations->get_rules($params);
            echo 'rules
';
            print_r($rules);
            $this->form_validation->set_rules($rules);
            echo 'validate';
            $validate = $this->form_validation->run();
            echo '
'.($validate ? 'OK' : 'failed').'
'; // always 'failed'
        }
        $this->load->view('form', $this->data);
    }
}

and here's the form:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <form method="post" action="">
        <input type="hidden" id="csrf" name="<?php echo $csrf_name; ?>" value="<?php echo $csrf; ?>">

            Phone
            <input type="text" name="phone" value="<?php echo $this->input->post('phone'); ?>">

        <input type="submit" value="Kirim">
    </form>

Body:
The form validation callback will only fire on a method inside the current controller. Or extend CI_Form_validation class:

class MY_Form_validation extends CI_Form_validation {

    function __constuct() {
        parent::__constuct();
    }

    public function get_rules($params=[])
    {
        $rules = [];

        $module = $params['module'];
        if ($module == 'test')
        {
            $rules[] = [
                'field' => 'phone',
                'label' => 'test phone 1',
                'rules' => '_test_rule1'
            ];
        }

        return $rules;
    }
    // end public function get_rules

    public function _test_rule1()
    {
        return TRUE;
    }
}

Don't forget to remove "callback_" prefix in rules.

After your corntroller will looks like:

<?php
/*
 * filename: test1.php
 * filedir: application/modules/test/controllers/
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class Test extends MY_Controller
{
    public function test1()
    {
        $this->load->library('form_validation');
        //$this->load->library('My_validations');

        if ($this->input->server('REQUEST_METHOD') == 'POST')
        {
            $params = [
                'module' => 'test',
            ];
            //$rules = $this->my_validations->get_rules($params);
            $rules = $this->form_validation->get_rules($params);
            echo 'rules <br>';
            print_r($rules);
            $this->form_validation->set_rules($rules);
            echo 'validate';
            $validate = $this->form_validation->run();
            echo '<pre>'.($validate ? 'OK' : 'failed').'</pre>'; // always 'failed'
        }
        $this->load->view('form', $this->data);
    }
}


问:
AWS Aurora Serverless - Communication Link Failure
I'm using MySQL Aurora Serverless cluster (with the Data API enabled) in my python code and I am getting a communications link failure exception. This usually occurs when the cluster has been dormant for some time.

But, once the cluster is active, I get no error. I have to send 3-4 requests every time before it works fine.

Exception detail:

The last packet sent successfully to the server was 0 milliseconds
  ago. The driver has not received any packets from the server. An error
  occurred (BadRequestException) when calling the ExecuteStatement
  operation: Communications link failure

How can I solve this issue? I am using standard boto3 library

答:
I also got this issue, and taking inspiration from the solution used by Arless and the conversation with Jimbo, came up with the following workaround.

I defined a decorator which retries the serverless RDS request until the configurable retry duration expires.

```<code>import logging
import functools
from sqlalchemy import exc
import time

logger = logging.getLogger()

def retry_if_db_inactive(max_attempts, initial_interval, backoff_rate):
    """
    Retry the function if the serverless DB is still in the process of 'waking up'.
    The configration retries follows the same concepts as AWS Step Function retries.
    :param max_attempts: The maximum number of retry attempts
    :param initial_interval: The initial duration to wait (in seconds) when the first 'Communications link failure' error is encountered
    :param backoff_rate: The factor to use to multiply the previous interval duration, for the next interval
    :return:
    """

    def decorate_retry_if_db_inactive(func):

        @functools.wraps(func)
        def wrapper_retry_if_inactive(*args, **kwargs):
            interval_secs = initial_interval
            attempt = 0
            while attempt < max_attempts:
                attempt += 1
                try:
                    return func(*args, **kwargs)

                except exc.StatementError as err:
                    if hasattr(err.orig, 'response'):
                        error_code = err.orig.response["Error"]['Code']
                        error_msg = err.orig.response["Error"]['Message']

                        # Aurora serverless is waking up
                        if error_code == 'BadRequestException' and 'Communications link failure' in error_msg:
                            logger.info('Sleeping for ' + str(interval_secs) + ' secs, awaiting RDS connection')
                            time.sleep(interval_secs)
                            interval_secs = interval_secs * backoff_rate
                        else:
                            raise err
                    else:
                        raise err

            raise Exception('Waited for RDS Data but still getting error')

        return wrapper_retry_if_inactive

    return decorate_retry_if_db_inactive
</code>```

which can then be used something like this:

```<code>@retry_if_db_inactive(max_attempts=4, initial_interval=10, backoff_rate=2)
def insert_alert_to_db(sqs_alert):
    with db_session_scope() as session:
        # your db code
        session.add(sqs_alert)

    return None
</code>```

Please note I'm using sqlalchemy, so the code would need tweaking to suit specific purposes, but hopefully will be useful as a starter.

Body:
I also got this issue, and taking inspiration from the solution used by Arless and the conversation with Jimbo, came up with the following workaround.

I defined a decorator which retries the serverless RDS request until the configurable retry duration expires.

import logging
import functools
from sqlalchemy import exc
import time

logger = logging.getLogger()

def retry_if_db_inactive(max_attempts, initial_interval, backoff_rate):
    """
    Retry the function if the serverless DB is still in the process of 'waking up'.
    The configration retries follows the same concepts as AWS Step Function retries.
    :param max_attempts: The maximum number of retry attempts
    :param initial_interval: The initial duration to wait (in seconds) when the first 'Communications link failure' error is encountered
    :param backoff_rate: The factor to use to multiply the previous interval duration, for the next interval
    :return:
    """

    def decorate_retry_if_db_inactive(func):

        @functools.wraps(func)
        def wrapper_retry_if_inactive(*args, **kwargs):
            interval_secs = initial_interval
            attempt = 0
            while attempt < max_attempts:
                attempt += 1
                try:
                    return func(*args, **kwargs)

                except exc.StatementError as err:
                    if hasattr(err.orig, 'response'):
                        error_code = err.orig.response["Error"]['Code']
                        error_msg = err.orig.response["Error"]['Message']

                        # Aurora serverless is waking up
                        if error_code == 'BadRequestException' and 'Communications link failure' in error_msg:
                            logger.info('Sleeping for ' + str(interval_secs) + ' secs, awaiting RDS connection')
                            time.sleep(interval_secs)
                            interval_secs = interval_secs * backoff_rate
                        else:
                            raise err
                    else:
                        raise err

            raise Exception('Waited for RDS Data but still getting error')

        return wrapper_retry_if_inactive

    return decorate_retry_if_db_inactive

which can then be used something like this:

@retry_if_db_inactive(max_attempts=4, initial_interval=10, backoff_rate=2)
def insert_alert_to_db(sqs_alert):
    with db_session_scope() as session:
        # your db code
        session.add(sqs_alert)

    return None

Please note I'm using sqlalchemy, so the code would need tweaking to suit specific purposes, but hopefully will be useful as a starter.


问:
Can anyone help me in defining a url without hook_menu and link it to a function in drupal?
In drupal I want to define a URL without hook_menu(), so that I can link the URL to a function that will be return a JSON (I want to call it from JavaScript code).

```<code>function(){
  $arr = array('a'=>'one', ..........);

  return json_encode($arr);
}
</code>```

Let me know how I can define a URL without hook_menu(), and link it to a function.

答:
Yes, but No

If you absolutely must hack your way around something to call a specific php file. Like if you actually have a file at /somepath/yourscript.php this could be callable from the general web. From there, you'd have to bootstrap Drupal yourself if you wanted anything in the Drupal namespace, or you'd have to use require or include for each file where you wanted to call something... but it's a bad idea.

To bootstrap Drupal you'd need something like this:

```<code>include_once 'path.to.../includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
</code>```

At which point you are welcome to blow your own face off with whatever monstrosity you create. Hopefully, you've noticed that by bootstrapping Drupal you probably don't save any time doing what you wanted in the first place by putting some rogue script in your file system.

The Drupal Way

Instead, use what Drupal gives you... A menu hook implemented as a MENU_CALLBACK. This will take a request right off the wire and send it to your function, as you desire. In your function, nothing stops you from looking at $_POST and $_GET variables, but you do get some Drupal sugar, in that your MENU_CALLBACK can accept URL parameters, check their validity, and pass them into your function so you have some assurances that you are working with valid data.

You need only define your menu hook and your callback function. To use validation, you can use a named argument, like %arg instead of the % in the example below. If you use the named parameters, you then would create a function called arg_load($arg) which would make sure you have a valid parameter, then return a value to be passed into your callback_function. Here's what your Drupal code might look like:

```<code>function your_module_menu(){
    $items['js/calls/this/path/%'] = array(
      'title' => 'Some callback',
      'description' => 'Will call callback_function',
      'page callback' => 'callback_function',
      'page arguments' => array(4),
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK
   );

// moar code here!

return $items;
}

function callback_function($url_var){
  // drupal_json_output manages your content-type header
  // and the json_encode for you.
  drupal_json_output($url_var);
}
</code>```

I think the Drupal way is much better than the hacky one off file way for a few reasons. One, developers will understand what you are doing if you go the Drupal way. Two, you can change the URL as needed.

The only reason I'd go for the standalone file is if, the file has nothing to do with anything you need out of Drupal AND that action had to be damn fast. Like so fast the difference in time between bootstrapping Drupal and not would take too damn long. In that case I'd probably use apache or nginx to forward a URL path to the file somewhere else in the filesystem. And if this is the case, I'll gladly eat my humble pie.

Body:
In drupal I want to define a URL without hook_menu(), so that I can link the URL to a function that will be return a JSON (I want to call it from JavaScript code).

function(){
  $arr = array('a'=>'one', ..........);

  return json_encode($arr);
}

Let me know how I can define a URL without hook_menu(), and link it to a function.

Body:
Yes, but No

If you absolutely must hack your way around something to call a specific php file. Like if you actually have a file at /somepath/yourscript.php this could be callable from the general web. From there, you'd have to bootstrap Drupal yourself if you wanted anything in the Drupal namespace, or you'd have to use require or include for each file where you wanted to call something... but it's a bad idea.

To bootstrap Drupal you'd need something like this:

include_once 'path.to.../includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

At which point you are welcome to blow your own face off with whatever monstrosity you create. Hopefully, you've noticed that by bootstrapping Drupal you probably don't save any time doing what you wanted in the first place by putting some rogue script in your file system.

The Drupal Way

Instead, use what Drupal gives you... A menu hook implemented as a MENU_CALLBACK. This will take a request right off the wire and send it to your function, as you desire. In your function, nothing stops you from looking at $_POST and $_GET variables, but you do get some Drupal sugar, in that your MENU_CALLBACK can accept URL parameters, check their validity, and pass them into your function so you have some assurances that you are working with valid data.

You need only define your menu hook and your callback function. To use validation, you can use a named argument, like %arg instead of the % in the example below. If you use the named parameters, you then would create a function called arg_load($arg) which would make sure you have a valid parameter, then return a value to be passed into your callback_function. Here's what your Drupal code might look like:

function your_module_menu(){
    $items['js/calls/this/path/%'] = array(
      'title' => 'Some callback',
      'description' => 'Will call callback_function',
      'page callback' => 'callback_function',
      'page arguments' => array(4),
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK
   );

// moar code here!

return $items;
}

function callback_function($url_var){
  // drupal_json_output manages your content-type header
  // and the json_encode for you.
  drupal_json_output($url_var);
}

I think the Drupal way is much better than the hacky one off file way for a few reasons. One, developers will understand what you are doing if you go the Drupal way. Two, you can change the URL as needed.

The only reason I'd go for the standalone file is if, the file has nothing to do with anything you need out of Drupal AND that action had to be damn fast. Like so fast the difference in time between bootstrapping Drupal and not would take too damn long. In that case I'd probably use apache or nginx to forward a URL path to the file somewhere else in the filesystem. And if this is the case, I'll gladly eat my humble pie.


问:
Install Error(-100) in Google Play Core in app update
We implemented some time ago In App Updates using Google Play Core library, and recently (started on September 8th) to shown on our Crashlytics lots of Install Error (-100) crashes.
Not sure if Google Play rollout something on that day, but even after we update the library to version 1.8.0 (before it was 1.7.3), the crashes continue reaching up to 7% of our daily active users.
Following the stacktrace of the crash:

```<code>Caused by com.google.android.play.core.install.InstallException: Install Error(-100): An internal error happened in the Play Store. (https://developer.android.com/reference/com/google/android/play/core/install/model/InstallErrorCode#ERROR_INTERNAL_ERROR)
   at com.google.android.play.core.appupdate.o.a(o.java:6)
   at com.google.android.play.core.internal.o.a(o.java:28)
   at com.google.android.play.core.internal.j.onTransact(j.java:20)
   at android.os.Binder.execTransactInternal(Binder.java:1056)
   at android.os.Binder.execTransact(Binder.java:1029)
</code>```

The question is what is this error? Internal Error seems to be a generic one, which doesn't say much about how can I fix it.

It seems to be a duplicated of this one, but as there is no answer to it I'm asking again.
How to solve install status code -100 while working with In-App update in Android?

答:
I have solution!

For testing you app you mast to upload two versions of apk to the Enternal app sharing.

First version - for example version code 1, the second version - version code 2.

Nexn step - You need to get the first app link from enternal app storage and follow this link, install this apk on your smartphone.

Next - follow on link of the second app, but dont press any button on opened screen, just close market screen. 3. Step three - open the first app and try to update by following your update steps logic in your app.

Body:
We implemented some time ago In App Updates using Google Play Core library, and recently (started on September 8th) to shown on our Crashlytics lots of Install Error (-100) crashes.
Not sure if Google Play rollout something on that day, but even after we update the library to version 1.8.0 (before it was 1.7.3), the crashes continue reaching up to 7% of our daily active users.
Following the stacktrace of the crash:

Caused by com.google.android.play.core.install.InstallException: Install Error(-100): An internal error happened in the Play Store. (https://developer.android.com/reference/com/google/android/play/core/install/model/InstallErrorCode#ERROR_INTERNAL_ERROR)
   at com.google.android.play.core.appupdate.o.a(o.java:6)
   at com.google.android.play.core.internal.o.a(o.java:28)
   at com.google.android.play.core.internal.j.onTransact(j.java:20)
   at android.os.Binder.execTransactInternal(Binder.java:1056)
   at android.os.Binder.execTransact(Binder.java:1029)

The question is what is this error? Internal Error seems to be a generic one, which doesn't say much about how can I fix it.

It seems to be a duplicated of this one, but as there is no answer to it I'm asking again.
How to solve install status code -100 while working with In-App update in Android?


问:
Error 404 on page reload with vue3 routing
Problem

When I hit reload on a route, e.g /installer, in vue3.js I get the following error:

Code

I use the Router with the following setup:

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});
```

Additional Information

(I don't use createWebHashHistory to get rid of the hashtags in url)

I also get this error when I go to the route, e.g. /installer, directly and not via link.

Question

How to resolve this error?

答:
If you are using nginx, I suggest add this line to the nginx config file:

```<code>location / {
  try_files $uri $uri/ /index.html;
}
</code>```

refer to: https://next.router.vuejs.org/guide/essentials/history-mode.html#apache

Body:
Problem

When I hit reload on a route, e.g /installer, in vue3.js I get the following error:

Code

I use the Router with the following setup:

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

Additional Information

(I don't use createWebHashHistory to get rid of the hashtags in url)

I also get this error when I go to the route, e.g. /installer, directly and not via link.

Question

How to resolve this error?

Body:
If you are using nginx, I suggest add this line to the nginx config file:

location / {
  try_files $uri $uri/ /index.html;
}

refer to: https://next.router.vuejs.org/guide/essentials/history-mode.html#apache


问:
See pages in server,MODX
I am new to coding, trying MODX now.My problem is, I can't see the pages I made on cms back to my server. Is there something I haven't done in order to see them?
Thanks in advance</p>

答: MODX stores all pages(named "resources") in database that's maybe the reason why you can't see them. All chunks, templates, template variables(TV) and snippets(all of them are also involved in the creation of the final page code ) are also in database.</p>

Title: See pages in server,MODX


问:
Module not found: Error: You attempted to import , problems with relative import
ERROR in ./src/index.js 7:0-30

Module not found: Error: You attempted to import ../main/App which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.
You can either move it inside src/, or add a symlink to it from project's node_modules/.

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from '../main/App';              (**My problem is here**)
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
</code>```

答:
I guess the solution is in error so bring your App.js or main folder inside of the src folder and then  it works</p>
```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from '../main/App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
</code>```

Body:
ERROR in ./src/index.js 7:0-30

Module not found: Error: You attempted to import ../main/App which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.
You can either move it inside src/, or add a symlink to it from project's node_modules/.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from '../main/App';              (**My problem is here**)
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

Body:
I guess the solution is in error so bring your App.js or main folder inside of the src folder and then  it works

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from '../main/App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);


问:
How do i re-run useEffect hook if the localstorage value has been changed?
I'm trying to re-run the useEffect hook based if any new item has been added to the localstorage.

My useEffect looks like this :

```<code>useEffect(() => {
      //getting all localstorage items and setting to a variable
      const localStorageItems = { ...localStorage }

      // filtering out the localstorage items for keys that only starts with "HTTP" & pushing it to the state called "testData" using setTestData useState hook.

      const filteredByKey = Object.fromEntries(
        Object.entries(localStorageItems).filter(([key, value]) => {
          if (key.startsWith("http")) {
            testArr2.push({ urls: [key, value] })
            // setTestData({ urls: [key, value] })
            setTestData((prev) => [...prev, { key, value }])
          }
        })
      )
    }, [])
</code>```

My problem is when I hit a button(adding a new data) this useEffect should ideally re-run, setting the latest data to the "testData" state.

The Problem :

I cannot pass window.localstorage to the useEffect's array dependency list, as it is external variable I believe and react doesn't allow it.

What I have tried:

I have looked at this answer on SO, but my situation is a bit complex as I'm loading the entire items to a variable first(I'm not aware of any better alternatives)

I have tried to put the state value in the dependency list, but it doesn't work and goes to infinite loop.

Please help.
Thanks for reading this far.

答: i can give you a work around for this use case, create react context that syncs with localStorage. you can use the context as a useEffect dependency. sync means, take the value from localStorage at starting and update the context along with the localStorage from your app.

Body:
I'm trying to re-run the useEffect hook based if any new item has been added to the localstorage.

My useEffect looks like this :

useEffect(() => {
      //getting all localstorage items and setting to a variable
      const localStorageItems = { ...localStorage }

      // filtering out the localstorage items for keys that only starts with "HTTP" & pushing it to the state called "testData" using setTestData useState hook.

      const filteredByKey = Object.fromEntries(
        Object.entries(localStorageItems).filter(([key, value]) => {
          if (key.startsWith("http")) {
            testArr2.push({ urls: [key, value] })
            // setTestData({ urls: [key, value] })
            setTestData((prev) => [...prev, { key, value }])
          }
        })
      )
    }, [])

My problem is when I hit a button(adding a new data) this useEffect should ideally re-run, setting the latest data to the "testData" state.

The Problem :

I cannot pass window.localstorage to the useEffect's array dependency list, as it is external variable I believe and react doesn't allow it.

What I have tried:

I have looked at this answer on SO, but my situation is a bit complex as I'm loading the entire items to a variable first(I'm not aware of any better alternatives)

I have tried to put the state value in the dependency list, but it doesn't work and goes to infinite loop.

Please help.
Thanks for reading this far.


问:
Dreamweaver source code view, is it possible to add "tags"?
I do'nt know if this is possible or if its called tags

im using dreamweaver cs4, in source mode view it displays line numbers to the left, I wish I could add some kind of "tag" to a certain line, and then have some sort of menu where it scrolls me to the tag.

Does this makes any sense?

It's because I have a huge source file that I need to navigate a lot in different places while coding and this "feature" would make my life a LOT easier.

Any help is appreciated.

Best Regards

答: It sounds like you're looking is what I've heard called a number of times "bookmarking". Unfortunately, Dreamweaver does not have this functionality built in. Not quite the same thing, but if you remember the line number you can jump to the line using a keyboard shortcut: CTRL+G on Windows, I think Cmd+, on Mac this pop up a little dialog you can enter the line number and hit enter to jump to that line.</p>


问:
Convert Git into TFVC with history
Is there any tool to convert Git Repos into TFVC with history or convert TFS into TFVC including the history?

答:
Git-TFS will do this, but be aware that TFVC and Git are very different models for source control so the tool may not be able to get all history of all branches. Some historic actions inside TFVC may cause the tool to fail (such as branch Renames).

The best way to figure out if you have a problem is to run the tool against your TFVC instance.

run something like

```<code>git tfs clone http://tfsServer:8080/tfs/DefaultCollection $/Project1/Trunk --branches=all
</code>```

Or

```<code>git tfs clone http://dev.azure.com/organisation $/Project1/Trunk --branches=all
</code>```

And see what happens. This command will create a local Git Repo which you can look at to ensure all of your branches and history have been converted

Title: Convert Git into TFVC with history

Body:
Git-TFS will do this, but be aware that TFVC and Git are very different models for source control so the tool may not be able to get all history of all branches. Some historic actions inside TFVC may cause the tool to fail (such as branch Renames).

The best way to figure out if you have a problem is to run the tool against your TFVC instance.

run something like

git tfs clone http://tfsServer:8080/tfs/DefaultCollection $/Project1/Trunk --branches=all

Or

git tfs clone http://dev.azure.com/organisation $/Project1/Trunk --branches=all

And see what happens. This command will create a local Git Repo which you can look at to ensure all of your branches and history have been converted


问:
Functions LEAST, GREATEST not considering NULL
Can you please tell me how to make the least and greatest function output the minimum and maximum date, not taking into account NULL values.

a
b
c
d
e
f

2021-01-01
2020-02-03
NULL
NULL
2020-10-13
NULL

result

least
greatest

2020-02-03
2021-01-01

答:
You can use the functions MIN() and MAX() for the respective values. As for ignoring NULL values, just add that to the where part of your query, e.g:

```<code>SELECT MIN(t.day) AS least, MAX(t.day) AS greatest
FROM yourTable AS t
WHERE t.day IS NOT NULL
</code>```

Of course, you still need to adapt that statement to your specific case.

Body:
You can use the functions MIN() and MAX() for the respective values. As for ignoring NULL values, just add that to the where part of your query, e.g:

SELECT MIN(t.day) AS least, MAX(t.day) AS greatest
FROM yourTable AS t
WHERE t.day IS NOT NULL

Of course, you still need to adapt that statement to your specific case.


问:
Error : IllegalArgumentException: The style on this component requires your app theme to be Theme.MaterialComponents
Below are my dependencies

```<code>implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
</code>```

My layout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:fitsSystemWindows="true">

    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/bottomBar"
        style="@style/Widget.MaterialComponents.BottomAppBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:backgroundTint="@color/colorPrimary"
        app:fabAlignmentMode="center"
        app:fabCradleMargin="10dp"
        app:fabCradleVerticalOffset="4dp"
        app:navigationIcon="@drawable/ic_drawer" >

    </com.google.android.material.bottomappbar.BottomAppBar>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_anchor="@id/bottomBar"
        app:srcCompat="@drawable/ic_apps" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

The Above code is working fine for me

But when i update the dependencies of material design

```<code>implementation 'com.google.android.material:material:1.1.0-alpha01'
</code>```

I'm getting below error:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{neel.com.bottomappbar/neel.com.bottomappbar.MainActivity}: android.view.InflateException: Binary XML file line #11: Binary XML file line #11: Error inflating class com.google.android.material.bottomappbar.BottomAppBar
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2485)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2545)
        at android.app.ActivityThread.access$1100(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5602)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
     Caused by: android.view.InflateException: Binary XML file line #11: Binary XML file line #11: Error inflating class com.google.android.material.bottomappbar.BottomAppBar
        at android.view.LayoutInflater.inflate(LayoutInflater.java:543)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at neel.com.bottomappbar.MainActivity.onCreate(MainActivity.kt:16)
        at android.app.Activity.performCreate(Activity.java:6358)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2438)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2545)
        at android.app.ActivityThread.access$1100(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5602)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
     Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class com.google.android.material.bottomappbar.BottomAppBar
        at android.view.LayoutInflater.createView(LayoutInflater.java:649)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:768)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:708)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:839)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:802)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:519)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at neel.com.bottomappbar.MainActivity.onCreate(MainActivity.kt:16)
        at android.app.Activity.performCreate(Activity.java:6358)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2438)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2545)
        at android.app.ActivityThread.access$1100(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5602)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance(Native Method)
        at android.view.LayoutInflater.createView(LayoutInflater.java:623)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:768)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:708)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:839)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:802)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:519)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at neel.com.bottomappbar.MainActivity.onCreate(MainActivity.kt:16)
        at android.app.Activity.performCreate(Activity.java:6358)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2438)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2545)
        at android.app.ActivityThread.access$1100(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5602)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
     Caused by: java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.MaterialComponents (or a descendant).
        at com.google.android.material.internal.ThemeEnforcement.checkTheme(ThemeEnforcement.java:240)
        at com.google.android.material.internal.ThemeEnforcement.checkMaterialTheme(ThemeEnforcement.java:215)
        at com.google.android.material.internal.ThemeEnforcement.checkCompatibleTheme(ThemeEnforcement.java:143)
        at com.google.android.material.internal.ThemeEnforcement.obtainStyledAttributes(ThemeEnforcement.java:78)
        at com.google.android.material.bottomappbar.BottomAppBar
</code>```

答:
I had this problem when I was testing the TextInputEditText which was inside a TextInputLayout with style that had parent parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox"

And the solution was to add the theme in the tests as follows

```<code>val scenario = launchFragmentInContainer<Fragment>(themeResId = R.style.Theme_APP)
</code>```

Body:
Below are my dependencies

implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

My layout.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:fitsSystemWindows="true">

    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/bottomBar"
        style="@style/Widget.MaterialComponents.BottomAppBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:backgroundTint="@color/colorPrimary"
        app:fabAlignmentMode="center"
        app:fabCradleMargin="10dp"
        app:fabCradleVerticalOffset="4dp"
        app:navigationIcon="@drawable/ic_drawer" >

    </com.google.android.material.bottomappbar.BottomAppBar>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_anchor="@id/bottomBar"
        app:srcCompat="@drawable/ic_apps" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

The Above code is working fine for me

But when i update the dependencies of material design

implementation 'com.google.android.material:material:1.1.0-alpha01'

I'm getting below error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{neel.com.bottomappbar/neel.com.bottomappbar.MainActivity}: android.view.InflateException: Binary XML file line #11: Binary XML file line #11: Error inflating class com.google.android.material.bottomappbar.BottomAppBar
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2485)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2545)
        at android.app.ActivityThread.access$1100(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5602)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
     Caused by: android.view.InflateException: Binary XML file line #11: Binary XML file line #11: Error inflating class com.google.android.material.bottomappbar.BottomAppBar
        at android.view.LayoutInflater.inflate(LayoutInflater.java:543)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at neel.com.bottomappbar.MainActivity.onCreate(MainActivity.kt:16)
        at android.app.Activity.performCreate(Activity.java:6358)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2438)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2545)
        at android.app.ActivityThread.access$1100(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5602)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
     Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class com.google.android.material.bottomappbar.BottomAppBar
        at android.view.LayoutInflater.createView(LayoutInflater.java:649)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:768)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:708)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:839)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:802)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:519)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at neel.com.bottomappbar.MainActivity.onCreate(MainActivity.kt:16)
        at android.app.Activity.performCreate(Activity.java:6358)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2438)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2545)
        at android.app.ActivityThread.access$1100(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5602)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance(Native Method)
        at android.view.LayoutInflater.createView(LayoutInflater.java:623)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:768)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:708)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:839)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:802)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:519)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at neel.com.bottomappbar.MainActivity.onCreate(MainActivity.kt:16)
        at android.app.Activity.performCreate(Activity.java:6358)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2438)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2545)
        at android.app.ActivityThread.access$1100(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5602)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
     Caused by: java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.MaterialComponents (or a descendant).
        at com.google.android.material.internal.ThemeEnforcement.checkTheme(ThemeEnforcement.java:240)
        at com.google.android.material.internal.ThemeEnforcement.checkMaterialTheme(ThemeEnforcement.java:215)
        at com.google.android.material.internal.ThemeEnforcement.checkCompatibleTheme(ThemeEnforcement.java:143)
        at com.google.android.material.internal.ThemeEnforcement.obtainStyledAttributes(ThemeEnforcement.java:78)
        at com.google.android.material.bottomappbar.BottomAppBar

Body:
I had this problem when I was testing the TextInputEditText which was inside a TextInputLayout with style that had parent parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox"

And the solution was to add the theme in the tests as follows

val scenario = launchFragmentInContainer<Fragment>(themeResId = R.style.Theme_APP)


问:
HTML Canvas image to Base64 problem
I'm having a problem with retrieving the base64 version of an image displayed on a canvas. I've looked at the other questions but none of the solutions including canvas2image seem to work.

Here's my code:

```<code><!DOCTYPE>
<html>
<head>
  <style>#canvas {cursor: pointer;}</style>
</head>
<body>
    <canvas id="canvas"></canvas>

    <script type="text/javascript">

        var can = document.getElementById('canvas');
        var ctx = can.getContext('2d');

        var img = new Image();
        img.onload = function(){
            can.width = img.width;
            can.height = img.height;
            ctx.drawImage(img, 0, 0, img.width, img.height);
        }
        img.src = 'http://sstatic.net/stackoverflow/img/newsletter-ad.png';

        can.onclick = function() {
            ctx.translate(img.width-1, img.height-1);
            ctx.rotate(Math.PI);
            ctx.drawImage(img, 0, 0, img.width, img.height);
        };

   document.write(can.toDataURL()); //isn't writing the correct base64 image

    </script>
</body>
</html>
</code>```

Here's the test link: http://jsfiddle.net/mrchief/hgTdM/1/ thanks, Mrchief

What I need is the correct base64 output of the image in the canvas.

The problem is that it won't output the correct base64 version of the image.. But as you can see, the image inside the canvas is displayed without any problems.

I've tested it on chrome & firefox

Thanks very much..

答:
Your document.write() call occurs immediately upon page load, before your img is loaded and drawn and before your onclick handler can ever run. You need to wait to generate the data URI until after everything has finished happening to the canvas.

Ignoring the onclick, here's something that writes out the data url after the image has loaded and been drawn to the canvas in a rotated fashion:

<!DOCTYPE html>

  <title>Rotated Image Data URL</title>

  <canvas id="canvas"></canvas>
  <textarea id="data" rows="20" cols="80"></textarea>

```

You can see this demo in action here: http://phrogz.net/tmp/upside-down-image-url.html

Note that the image you load must be on the same domain as your script, or else you will not be allowed to create the data URL.

Title: HTML Canvas image to Base64 problem

Body:
I'm having a problem with retrieving the base64 version of an image displayed on a canvas. I've looked at the other questions but none of the solutions including canvas2image seem to work.

Here's my code:

<!DOCTYPE>

    <canvas id="canvas"></canvas>

Here's the test link: http://jsfiddle.net/mrchief/hgTdM/1/ thanks, Mrchief

What I need is the correct base64 output of the image in the canvas.

The problem is that it won't output the correct base64 version of the image.. But as you can see, the image inside the canvas is displayed without any problems.

I've tested it on chrome & firefox

Thanks very much..

Body:
Your document.write() call occurs immediately upon page load, before your img is loaded and drawn and before your onclick handler can ever run. You need to wait to generate the data URI until after everything has finished happening to the canvas.

Ignoring the onclick, here's something that writes out the data url after the image has loaded and been drawn to the canvas in a rotated fashion:

<!DOCTYPE html>
<html><head>
  <title>Rotated Image Data URL</title>
  <style type="text/css" media="screen">
    canvas, textarea { display:block }
  </style>
</head><body>
  <canvas id="canvas"></canvas>
  <textarea id="data" rows="20" cols="80"></textarea>
  <img id="echo">
  <script type="text/javascript">
      var can = document.getElementById('canvas');
      var ctx = can.getContext('2d');

      var img = new Image();
      img.onload = function(){
        can.width  = img.width;
        can.height = img.height;
        ctx.translate(img.width-1, img.height-1);
        ctx.rotate(Math.PI);
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var url = document.getElementById('data').value = can.toDataURL();
        document.getElementById('echo').src = url;
      }
      img.src = 'gkhead.jpg';
  </script>
</body></html>

You can see this demo in action here: http://phrogz.net/tmp/upside-down-image-url.html

Note that the image you load must be on the same domain as your script, or else you will not be allowed to create the data URL.


问:
ArrayList and initializing a 2D array not working?
I'm learning the AP CSA course and tried to print these arrays. It keeps saying "can't find symbol" and not gonna lie I have absolutely no idea what that means.</p>
```<code>//ArrayList:
    public class al{
        public static void main(String[] args){
            List l = new ArrayList();
            System.out.print(l.size());
        }
    }
</code>```
```<code>//2DArray:
    public class arrays{
       public static void main(String[] args){
          int[][] arry =  {{1,2,3},
                           {1,2,3},
                           {1,2,3}};
          printArray(arry);
       }
    }
</code>```

答:
In your first program to print the ArrayList, it is failing because you need to import the List and ArrayList in your program, please try this

```<code>import java.util.ArrayList;
import java.util.List;
public class al{
    public static void main(String[] args){
        List l = new ArrayList();
        System.out.print(l.size());
    }
}
</code>```

In the second program the printArray method you called is missing in definition, i.e you have to define the printArray method in your class, you are using it from method main then you need to declare it static like below

```<code>static void printArray(int[][] arr){
    for(int i=0; i<arr.length; i++){
        String row = "";
        for(int j=0; j<arr[0].length;j++){
            row+=arr[i][j]+" ";
        }
        System.out.println(row);
    }
}
</code>```

Also while you are learning, please also read about the naming conventions in java (i suppose you are learning java), like a Class name should start from a capital letter.

Body:
I'm learning the AP CSA course and tried to print these arrays. It keeps saying "can't find symbol" and not gonna lie I have absolutely no idea what that means.

//ArrayList:
    public class al{
        public static void main(String[] args){
            List l = new ArrayList();
            System.out.print(l.size());
        }
    }

//2DArray:
    public class arrays{
       public static void main(String[] args){
          int[][] arry =  {{1,2,3},
                           {1,2,3},
                           {1,2,3}};
          printArray(arry);
       }
    }

Body:
In your first program to print the ArrayList, it is failing because you need to import the List and ArrayList in your program, please try this

import java.util.ArrayList;
import java.util.List;
public class al{
    public static void main(String[] args){
        List l = new ArrayList();
        System.out.print(l.size());
    }
}

In the second program the printArray method you called is missing in definition, i.e you have to define the printArray method in your class, you are using it from method main then you need to declare it static like below

static void printArray(int[][] arr){
    for(int i=0; i<arr.length; i++){
        String row = "";
        for(int j=0; j<arr[0].length;j++){
            row+=arr[i][j]+" ";
        }
        System.out.println(row);
    }
}

Also while you are learning, please also read about the naming conventions in java (i suppose you are learning java), like a Class name should start from a capital letter.