问:
Rails 3.0.9 Ajax response not executed
I'm using Rails 3.0.9 and jQuery 1.6.2 with jQuery-ujs.

Basically I'd like to ajaxfy my "add to cart" action.

In my view:

```<code><td><%= button_to "Add to cart", line_items_path(:coupon_id => coupon, :format => :js), :remote => true %>
</code>```

In my controller:

```<code>def create
@cart = current_cart
coupon = Coupon.find(params[:coupon_id])
@line_item = @cart.add_coupon(coupon.id)

respond_to do |format|
  if @line_item.save
    format.html { redirect_to(@line_item.cart) }
    format.js   {render :layout => false, :content_type => 'text/javascript'}
    format.xml  { render :xml => @line_item, :status => :created, :location => @line_item }
  else
    format.html { render :action => "new" }
    format.js   {render :layout => false, :content_type => 'text/javascript'}
    format.xml  { render :xml => @line_item.errors, :status => :unprocessable_entity }
  end
end
</code>```

end

I've also created a create.js.erb:

```<code>$("#my_cart").html("<%= escape_javascript(render(:partial => 'layouts/mycart')) %>");
</code>```

to update the cart item number whenever a new item is added.

When I click the "add to cart" button, a JS POST request is sent to the server:

```<code>    Started POST "/line_items.js?coupon_id=1" for 127.0.0.1 at Thu Aug 18 00:04:31 +0800 2011
  Processing by LineItemsController#create as JS
</code>```

And the response from the server is:

```<code>Rendered layouts/_mycart.html.erb (5.3ms)
Rendered line_items/create.js.erb (28.9ms)
Completed 200 OK in 127ms (Views: 58.7ms | ActiveRecord: 3.0ms)
</code>```

The response's body contains the javascript code to update my cart:

```<code>$("#my_cart").html("<li id=\"my_cart\"><a href=\"/carts/10\">My cart(1)<\/a>\n<\/li>");
</code>```

However, the web page is not updated. I tried different browsers (Chrome, Firefox, Safari). But if I manually run this code in Firebug's console, the page got updated. I've googled for a day and tried different solutions. None of them worked me. Could someone solve my problem?

Here's the code generated for button_to:

```<code><form method="post" action="/line_items.js?coupon_id=1" data-remote="true" class="button_to"><div><input type="submit" value="Add to cart" /><input name="authenticity_token" type="hidden" value="MdHScf0JVNu2UFXLxuindDvZ5TPBztfMMzv57w1LWX8=" /></div></form>
</code>```

答:
Problem solved!

I created a new project with the same settings and tried if ajax worked there. Surprisingly, it did. So I concluded that there must be some wrong settings in my project.

And I found and removed this from my application_controller.rb:

```<code>  def set_charset
      headers["Content-Type"] = "text/html; charset=utf-8"
  end

  def configure_charsets
      response.headers["Content-Type"] = "text/html; charset=utf-8"
      suppress(ActiveRecord::StatementInvalid) do
        ActiveRecord::Base.connection.execute 'SET NAMES UTF8'
      end
  end
</code>```

I copied this code from a tutorial to configure character set. Don't exactly know why it screwed everything up but I could move on with my project now!

Title: Rails 3.0.9 Ajax response not executed

Body:
I'm using Rails 3.0.9 and jQuery 1.6.2 with jQuery-ujs.

Basically I'd like to ajaxfy my "add to cart" action.

In my view:

<%= button_to "Add to cart", line_items_path(:coupon_id => coupon, :format => :js), :remote => true %>

In my controller:

def create
@cart = current_cart
coupon = Coupon.find(params[:coupon_id])
@line_item = @cart.add_coupon(coupon.id)

respond_to do |format|
  if @line_item.save
    format.html { redirect_to(@line_item.cart) }
    format.js   {render :layout => false, :content_type => 'text/javascript'}
    format.xml  { render :xml => @line_item, :status => :created, :location => @line_item }
  else
    format.html { render :action => "new" }
    format.js   {render :layout => false, :content_type => 'text/javascript'}
    format.xml  { render :xml => @line_item.errors, :status => :unprocessable_entity }
  end
end

end

I've also created a create.js.erb:

$("#my_cart").html("<%= escape_javascript(render(:partial => 'layouts/mycart')) %>");

to update the cart item number whenever a new item is added.

When I click the "add to cart" button, a JS POST request is sent to the server:

    Started POST "/line_items.js?coupon_id=1" for 127.0.0.1 at Thu Aug 18 00:04:31 +0800 2011
  Processing by LineItemsController#create as JS

And the response from the server is:

Rendered layouts/_mycart.html.erb (5.3ms)
Rendered line_items/create.js.erb (28.9ms)
Completed 200 OK in 127ms (Views: 58.7ms | ActiveRecord: 3.0ms)

The response's body contains the javascript code to update my cart:

$("#my_cart").html("
My cart(1)<\/a>\n<\/li>");

However, the web page is not updated. I tried different browsers (Chrome, Firefox, Safari). But if I manually run this code in Firebug's console, the page got updated. I've googled for a day and tried different solutions. None of them worked me. Could someone solve my problem?

Here's the code generated for button_to:

<form method="post" action="/line_items.js?coupon_id=1" data-remote="true" class="button_to">
<input type="submit" value="Add to cart" /><input name="authenticity_token" type="hidden" value="MdHScf0JVNu2UFXLxuindDvZ5TPBztfMMzv57w1LWX8=" />
</form>

Body:
Problem solved!

I created a new project with the same settings and tried if ajax worked there. Surprisingly, it did. So I concluded that there must be some wrong settings in my project.

And I found and removed this from my application_controller.rb:

  def set_charset
      headers["Content-Type"] = "text/html; charset=utf-8"
  end

  def configure_charsets
      response.headers["Content-Type"] = "text/html; charset=utf-8"
      suppress(ActiveRecord::StatementInvalid) do
        ActiveRecord::Base.connection.execute 'SET NAMES UTF8'
      end
  end

I copied this code from a tutorial to configure character set. Don't exactly know why it screwed everything up but I could move on with my project now!


来源: stackexchange

问:
Distribuited Transactions between COM+ and API Framework 4.6
how are you doing?  ;)

Can you help me out with this situation? :

We currently have a COM+ Component with DTC (Distributed Transactions)
and I need to migrate the transaction to a API .net (Framework 4.6)  using this transaction to processes returning it back to COM+ to commmit/abort the transaction.

However, I was trying to pass it  in the header as a parameter which is a guid generated from "mCTX.ContextInfo.GetActivityId" to use as a transaction into API (Framework 4.6) . But then the function needs a BASE64 token to validate de GetTransactionFromTransmitterPropagationToken function. Obviosly, to encode to base64 haven't work out to make the function regonize it as an function dtc.  Any ideas how to make it operational?

I haven't found anything similar to study and apply, it's been a big challenge.

COM+ (Transaction Created)

```<code>Private mCTX               As ObjectContext

Set mCTX = GetObjectContext()
idChaveLog = mCTX.ContextInfo.GetActivityId

If Not mCTX Is Nothing Then mCTX.SetComplete

On Error:
 If Not mCTX Is Nothing Then mCTX.SetAbort
</code>```

```<code>Example Guid Generated in idChaveLog: {38B5C47B-9E50-4AF5-9CB4-F5E6472B9FEB}
</code>```

API .net (Framework 4.6) (Filter used to get TokenID to propagation of the transaction generated on COM+ (GUID)

```<code>public class EnlistToDistributedTransactionActionFilter : ActionFilterAttribute
    {
        private const string TransactionId = "TransactionToken";

        /// <summary>
        /// Retrieve a transaction propagation token, create a transaction scope and promote the current transaction to a distributed transaction.
        /// </summary>
        /// <param name="actionContext">The action context.</param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Contains(TransactionId))
            {
                var values = actionContext.Request.Headers.GetValues(TransactionId);
                if (values != null && values.Any())
                {
                    byte[] transactionToken = Convert.FromBase64String(values.FirstOrDefault());
                    var transaction = TransactionInterop.GetTransactionFromTransmitterPropagationToken(transactionToken);
                    var transactionScope = new TransactionScope(transaction);

                    actionContext.Request.Properties.Add(TransactionId, transactionScope);
                }
            }
        }
</code>```

答:
You can try this

In Windows search and type: "dcomcnfg" to bring up Component Services

In the center pane, double click Computers, My Computer, then open the Distributed Transaction Coordinator folder

Right click on Local DTC, and choose properties

On the Security tab, under Security Settings, check the boxes for

Network DTC Access and Enable XA Transactions

Click OK to save changes

ContentLicense: CC BY-SA 4.0

Body:
how are you doing?  ;)

Can you help me out with this situation? :

We currently have a COM+ Component with DTC (Distributed Transactions)
and I need to migrate the transaction to a API .net (Framework 4.6)  using this transaction to processes returning it back to COM+ to commmit/abort the transaction.

However, I was trying to pass it  in the header as a parameter which is a guid generated from "mCTX.ContextInfo.GetActivityId" to use as a transaction into API (Framework 4.6) . But then the function needs a BASE64 token to validate de GetTransactionFromTransmitterPropagationToken function. Obviosly, to encode to base64 haven't work out to make the function regonize it as an function dtc.  Any ideas how to make it operational?

I haven't found anything similar to study and apply, it's been a big challenge.

COM+ (Transaction Created)

Private mCTX               As ObjectContext

Set mCTX = GetObjectContext()
idChaveLog = mCTX.ContextInfo.GetActivityId

If Not mCTX Is Nothing Then mCTX.SetComplete

On Error:
 If Not mCTX Is Nothing Then mCTX.SetAbort

Example Guid Generated in idChaveLog: {38B5C47B-9E50-4AF5-9CB4-F5E6472B9FEB}

API .net (Framework 4.6) (Filter used to get TokenID to propagation of the transaction generated on COM+ (GUID)

public class EnlistToDistributedTransactionActionFilter : ActionFilterAttribute
    {
        private const string TransactionId = "TransactionToken";

        ///
        /// Retrieve a transaction propagation token, create a transaction scope and promote the current transaction to a distributed transaction.
        ///
        /// <param name="actionContext">The action context.</param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Contains(TransactionId))
            {
                var values = actionContext.Request.Headers.GetValues(TransactionId);
                if (values != null && values.Any())
                {
                    byte[] transactionToken = Convert.FromBase64String(values.FirstOrDefault());
                    var transaction = TransactionInterop.GetTransactionFromTransmitterPropagationToken(transactionToken);
                    var transactionScope = new TransactionScope(transaction);

                    actionContext.Request.Properties.Add(TransactionId, transactionScope);
                }
            }
        }


问:
Importing jQuery in SvelteKit
How do I import jQuery in SvelteKit (with TypeScript support)?

const jq = window.$ as one would do in Svelte runs into window is not defined.

Update as of Aug 2022: No longer running into window is not defined. See selected answer.

答:
You can just use import as syntax:

```<code>import * as $jq from 'jquery';
</code>```

Or you can do like this

```<code>import { onMount } from 'svelte';
import js from 'jquery';

onMount(() => {
  window.jq = js;
});
</code>```

Title: Importing jQuery in SvelteKit

Body:
You can just use import as syntax:

import * as $jq from 'jquery';

Or you can do like this

import { onMount } from 'svelte';
import js from 'jquery';

onMount(() => {
  window.jq = js;
});


问:
How can I create every combination possible for the contents of two arrays?
I have two arrays:

```<code>var array1 = ["A", "B", "C"];
var array2 = ["1", "2", "3"];
</code>```

How can I set another array to contain every combination of the above, so that:

```<code>var combos = ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"];
</code>```

答:
Here's a short recursive one that takes N arrays.

```<code>function permuteArrays(first, next, ...rest) {
  if (rest.length) next = permuteArrays(next, ...rest);
  return first.flatMap(a => next.map(b => [a, b].flat()));
}
</code>```

Or with reduce (slight enhancement of Penny Liu's):

```<code>function multiply(a, b) {
  return a.flatMap(c => b.map(d => [c, d].flat()));
}
[['a', 'b', 'c'], ['+', '-'], [1, 2, 3]].reduce(multiply);
</code>```

Runnable example:

function permuteArrays(first, next, ...rest) {
  if (rest.length) next = permuteArrays(next, ...rest);
  return first.flatMap(a => next.map(b => [a, b].flat()));
}

const squish = arr => arr.join('');
console.log(
  permuteArrays(['A', 'B', 'C'], ['+', '-', '×', '÷'], [1, 2]).map(squish),
  permuteArrays(['a', 'b', 'c'], [1, 2, 3]).map(squish),
  permuteArrays([['a', 'foo'], 'b'], [1, 2]).map(squish),
  permuteArrays(['a', 'b', 'c'], [1, 2, 3], ['foo', 'bar', 'baz']).map(squish),
)```

Body:
I have two arrays:

var array1 = ["A", "B", "C"];
var array2 = ["1", "2", "3"];

How can I set another array to contain every combination of the above, so that:

var combos = ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"];

Body:
Here's a short recursive one that takes N arrays.

function permuteArrays(first, next, ...rest) {
  if (rest.length) next = permuteArrays(next, ...rest);
  return first.flatMap(a => next.map(b => [a, b].flat()));
}

Or with reduce (slight enhancement of Penny Liu's):

function multiply(a, b) {
  return a.flatMap(c => b.map(d => [c, d].flat()));
}
[['a', 'b', 'c'], ['+', '-'], [1, 2, 3]].reduce(multiply);

Runnable example:

function permuteArrays(first, next, ...rest) {
  if (rest.length) next = permuteArrays(next, ...rest);
  return first.flatMap(a => next.map(b => [a, b].flat()));
}

const squish = arr => arr.join('');
console.log(
  permuteArrays(['A', 'B', 'C'], ['+', '-', '×', '÷'], [1, 2]).map(squish),
  permuteArrays(['a', 'b', 'c'], [1, 2, 3]).map(squish),
  permuteArrays([['a', 'foo'], 'b'], [1, 2]).map(squish),
  permuteArrays(['a', 'b', 'c'], [1, 2, 3], ['foo', 'bar', 'baz']).map(squish),
)


问:
Display Math Notation and Math Questions on View?
Anyone know how to display math question include math notation in view? For example: 8 to the power of 2 ; square root of 16.

Any suggestions, methods and comments are appreciated. Thanks :-)

答:
Do you mean something like MathML used in web frameworks like MathJax?

I don't believe there is any in-built support for anything like this in IOS.

You could try to 'hack' something together with a IOS UIWebView like this question states.

ContentLicense: CC BY-SA 3.0


问:
How to get user from init bash script Linux(before user session created)
At Debian im trying to change specific directory ownership after every reboot. But in my case it doesnt work, because user always set as root at reboot time.
When i try this in terminal it works well (i think because myUser session created) but i need to change it at reboot time.

So far i refer this link but it fails for me : https://unix.stackexchange.com/questions/183183/using-chown-useruser-inside-bash-script

CURRENT_USER=$(who | awk 'NR==1{print $1}')

sudo chown -R $CURRENT_USER:$CURRENT_USER /myfile/foo

second way:

sudo chown -R ${USER:=$(/usr/bin/id -run)}:$USER /myfile/foo

i dont want to write like this :

sudo chown myUser:myUser /myfile/foo

答:
Linux is a multiuser system. There can be more than one users logged in simultaneously or no one at all. Often there is no way to define something like a "default" user. There are however workarounds that you could use to find the "default" user if the machines are setup as typical single user company computers.

Take the user with UID 1000. If all the machines are setup so that the "default" user has UID 1000, you could just use this UID instead of the username in the chown command.

Look for the subdirectories of /home. Only standard (non-system) users have a home directory. On standard systems they are named with the username.

That beeing set: Your script will be highly dependent on the specific setup of the machines. Also there might be a less intrusive, less machine dependent and more secure solution to your problem. You could try to

leave root as owner of the directory but enable read and write permissions for other users.

set the sticky bit for the directory (just like /tmp).

make a new group that owns the directory and add the users to it.

The last option is actually used a lot. For example often web servers make their source directories owned by a group called www and users, that are allowed to read/write the data are added to that group. This also works well in real multiuser systems like servers or shared machines.


问:
Find a specific string between 2 strings
This is for Notepad++. I am trying to Find a word between two words; and if found, mark the whole thing.

```<code>    <lootgroup name="Random1" count="1">
      <item group="filler"/>
      <item group="filler"/>
    </lootgroup>

    <lootgroup name="Random2" count="1">
      <item group="filler"/>
      <item group="schematics"/>
      <item group="filler"/>
    </lootgroup>

    <lootgroup name="Random2" count="1">
      <item group="filler"/>
      <item group="schematics"/>
      <item group="filler"/>
      <item group="schematics"/>
    </lootgroup>

</code>```

So I want to Find "schematics" between <lootgroup   and   </lootgroup>; and if found, mark/select all lines including <lootgroup   and   </lootgroup>.

I know about <lootgroup(.*?)</lootgroup> will select everything in between but I cannot figure out what to replace (.*?) with to match only if schematics is present between the two.

Number of "Item Groups" varies and "Item Group" is not always the name. That's why I'm searching for "schematic".

Using Notepad++ Find and Mark function.

Much appreciated.

答:
The below code works for me ....

Find:^\s*<loot(.*\n.*){0,2}schem[\S\s]+?group>

Replace with:nothing

Body:
This is for Notepad++. I am trying to Find a word between two words; and if found, mark the whole thing.

    <lootgroup name="Random1" count="1">
      <item group="filler"/>
      <item group="filler"/>
    </lootgroup>

    <lootgroup name="Random2" count="1">
      <item group="filler"/>
      <item group="schematics"/>
      <item group="filler"/>
    </lootgroup>

    <lootgroup name="Random2" count="1">
      <item group="filler"/>
      <item group="schematics"/>
      <item group="filler"/>
      <item group="schematics"/>
    </lootgroup>

So I want to Find "schematics" between <lootgroup   and   </lootgroup>; and if found, mark/select all lines including <lootgroup   and   </lootgroup>.

I know about <lootgroup(.*?)</lootgroup> will select everything in between but I cannot figure out what to replace (.*?) with to match only if schematics is present between the two.

Number of "Item Groups" varies and "Item Group" is not always the name. That's why I'm searching for "schematic".

Using Notepad++ Find and Mark function.

Much appreciated.


问:
How to make my navbar fit the max width value while not having enough content?
So I have a navbar that has like 4 links and I need it to be a specific width, and i want it to be responsive so I used max-width: 65em, however this results in it not being 65em unless theres alot of content inside which isn't there cuz of the nature of a navbar.

How do I make my nav bar content have a width of 65em while being responsive when i decrease screen size? Do I have to mess with media queries and breakpoints for is there a solution?

Navbar code:

```<code>const Nav = styled.nav `
  margin-bottom: 5em;
  box-sizing: border-box;
  max-width: 65em;
  display:flex;
  justify-content: space-between;
`

<Nav>
      <Logo to="/">saif</Logo>
      <NavLinks>
        <StyledNavLink to="about">About</StyledNavLink>
        <StyledNavLink to="projects">Projects</StyledNavLink>
        <StyledNavLink to="coding-challenges">Coding Challenges</StyledNavLink>
        <StyledNavLink to="contact">Get in touch</StyledNavLink>
      </NavLinks>
</Nav>

</code>```

答:
```<code>const Nav = styled.nav `
  margin-bottom: 5em;
  box-sizing: border-box;
  max-width: 65em;
  width:100% ;
  display:flex;
  justify-content: space-between;
`

<Nav>
      <Logo to="/">saif</Logo>
      <NavLinks>
        <StyledNavLink to="about">About</StyledNavLink>
        <StyledNavLink to="projects">Projects</StyledNavLink>
        <StyledNavLink to="coding-challenges">Coding Challenges</StyledNavLink>
        <StyledNavLink to="contact">Get in touch</StyledNavLink>
      </NavLinks>
</Nav>

</code>```

Try giving width to nav in percentage .
I have given 100% , you can change it to your convenience.
Try running this code .
I hope this solves your issue .

Body:
So I have a navbar that has like 4 links and I need it to be a specific width, and i want it to be responsive so I used max-width: 65em, however this results in it not being 65em unless theres alot of content inside which isn't there cuz of the nature of a navbar.

How do I make my nav bar content have a width of 65em while being responsive when i decrease screen size? Do I have to mess with media queries and breakpoints for is there a solution?

Navbar code:

const Nav = styled.nav `
  margin-bottom: 5em;
  box-sizing: border-box;
  max-width: 65em;
  display:flex;
  justify-content: space-between;
`

      <Logo to="/">saif</Logo>
      <NavLinks>

      </NavLinks>

Body:
const Nav = styled.nav `
  margin-bottom: 5em;
  box-sizing: border-box;
  max-width: 65em;
  width:100% ;
  display:flex;
  justify-content: space-between;
`

<Nav>
      <Logo to="/">saif</Logo>
      <NavLinks>
        <StyledNavLink to="about">About</StyledNavLink>
        <StyledNavLink to="projects">Projects</StyledNavLink>
        <StyledNavLink to="coding-challenges">Coding Challenges</StyledNavLink>
        <StyledNavLink to="contact">Get in touch</StyledNavLink>
      </NavLinks>
</Nav>

Try giving width to nav in percentage .
I have given 100% , you can change it to your convenience.
Try running this code .
I hope this solves your issue .


问:
Tableau connecting to Snowflake using Key-Pair authentication

I'm trying to connect tableau to Snowflake using the Key-pair authentication method. I have generated the keys and associated it with the user. I'm looking for some guidance as how can I configure it on Tableau to use those keys for login to snowflake.

答:
It looks like it's possible by specifying additional parameters:
Tableau - Snowflake key-pair authentication</p>


问:
How to use a dot "." to access members of dictionary?
How do I make Python dictionary members accessible via a dot "."?

For example, instead of writing mydict['val'], I'd like to write mydict.val.

Also I'd like to access nested dicts this way. For example

```<code>mydict.mydict2.val
</code>```

would refer to

```<code>mydict = { 'mydict2': { 'val': ... } }
</code>```

答:
One could use dotsi, for full list, dict and recursive support, with some extension methods

```<code>pip install dotsi
</code>```

and

```<code>>>> import dotsi
>>>
>>> d = dotsi.Dict({"foo": {"bar": "baz"}})     # Basic
>>> d.foo.bar
'baz'
>>> d.users = [{"id": 0, "name": "Alice"}]   # List
>>> d.users[0].name
'Alice'
>>> d.users.append({"id": 1, "name": "Becca"}); # Append
>>> d.users[1].name
'Becca'
>>> d.users += [{"id": 2, "name": "Cathy"}];    # `+=`
>>> d.users[2].name
'Cathy'
>>> d.update({"tasks": [{"id": "a", "text": "Task A"}]});
>>> d.tasks[0].text
'Task A'
>>> d.tasks[0].tags = ["red", "white", "blue"];
>>> d.tasks[0].tags[2];
'blue'
>>> d.tasks[0].pop("tags")                      # `.pop()`
['red', 'white', 'blue']
>>>
>>> import pprint
>>> pprint.pprint(d)
{'foo': {'bar': 'baz'},
 'tasks': [{'id': 'a', 'text': 'Task A'}],
 'users': [{'id': 0, 'name': 'Alice'},
           {'id': 1, 'name': 'Becca'},
           {'id': 2, 'name': 'Cathy'}]}
>>>
>>> type(d.users)       # dotsi.Dict (AKA dotsi.DotsiDict)
<class 'dotsi.DotsiList'>
>>> type(d.users[0])    # dotsi.List (AKA dotsi.DotsiList)
<class 'dotsi.DotsiDict'>
>>>
</code>```

Body:
How do I make Python dictionary members accessible via a dot "."?

For example, instead of writing mydict['val'], I'd like to write mydict.val.

Also I'd like to access nested dicts this way. For example

mydict.mydict2.val

would refer to

mydict = { 'mydict2': { 'val': ... } }

Body:
One could use dotsi, for full list, dict and recursive support, with some extension methods

pip install dotsi

and

>>> import dotsi
>>>
>>> d = dotsi.Dict({"foo": {"bar": "baz"}})     # Basic
>>> d.foo.bar
'baz'
>>> d.users = [{"id": 0, "name": "Alice"}]   # List
>>> d.users[0].name
'Alice'
>>> d.users.append({"id": 1, "name": "Becca"}); # Append
>>> d.users[1].name
'Becca'
>>> d.users += [{"id": 2, "name": "Cathy"}];    # `+=`
>>> d.users[2].name
'Cathy'
>>> d.update({"tasks": [{"id": "a", "text": "Task A"}]});
>>> d.tasks[0].text
'Task A'
>>> d.tasks[0].tags = ["red", "white", "blue"];
>>> d.tasks[0].tags[2];
'blue'
>>> d.tasks[0].pop("tags")                      # `.pop()`
['red', 'white', 'blue']
>>>
>>> import pprint
>>> pprint.pprint(d)
{'foo': {'bar': 'baz'},
 'tasks': [{'id': 'a', 'text': 'Task A'}],
 'users': [{'id': 0, 'name': 'Alice'},
           {'id': 1, 'name': 'Becca'},
           {'id': 2, 'name': 'Cathy'}]}
>>>
>>> type(d.users)       # dotsi.Dict (AKA dotsi.DotsiDict)
<class 'dotsi.DotsiList'>
>>> type(d.users[0])    # dotsi.List (AKA dotsi.DotsiList)
<class 'dotsi.DotsiDict'>
>>>


问:
jQuery .fadeOut problems in FireFox 6.0
So far, I have the fadeIn working, but the fadeOut has not been quite right.  Right now, as soon as the mouse leaves the hover area, it doesn't look like any fadeOut is happening at all.  I would like to have a smooth fade out that completes before the next animation (the next fadeIn) begins and doesn't queue up.  Basically this is over some links that are within  tags.  I'm in the home stretch now!

P.S. I know I'm not using .hover.  I'd rather stick with mouseover and mouseleave for now, or even mouseout.  Please accomodate this small request.

```<code><script>
    $("a").mouseover(function () {
        $("div").fadeIn(0, function () {
            $("span").fadeIn(3000,0.0);
        });
        return false;
    });

    $dequeue;

    $("a").mouseleave(function () {
        $("span").fadeOut(3000,0.0);
    });
</script>

<!DOCTYPE html>

<html>
<head>
<script type="text/javascript" src="jQuery.js"></script>
</head>
<body>

<a href="#">MouseOver!</a>

<div>

<h3><span>Sample Text</span></h3>

</div>
</body>
</html>
</code>```

Edit: 08/18/2011

I realized that there may be script conflicting with the one above.  I have an additional jquery script running on the same page.  By itself it works fine, but when I add the script for the text box (above) the .fadeOut on both images and text becomes ignored or at the very least, inconsistent.

2nd jQuery script:

```<code><script>
$(document).ready(function(){

$(".latest_img").fadeTo("slow", 0.0);
$(".latest_img").hover(function(){
$(this).fadeTo(1000, 1.0).dequeue();

},function(){
$(this).fadeTo(1000, 0.0).dequeue();
});
});
</script>
</code>```

Here is an example of one of the four "targets" that should prompt the text and image to display (there are four text boxes accompanying four images - each get shown by a mouseover on the target).

HTML:

```<code><div class="gallerycontainer">
<div width="100%" height="30%">

<a class="thumbnail" href="#thumb"><h2 class="ftb" id="tg1">Target A</h2>

<span class="txspan">
<img src="img/ima.jpg" class="latest_img" id="images" />
<h3 class="text"><br>Textbox content for Target A</h3></span></a>

</div>
</div>
</code>```

答:
sans the $dequeue both events seem to be working

http://jsfiddle.net/pxfunc/y9qd6/

```<code>$("a").mouseover(function() {
    $("div").fadeIn(0, function() {
        $("span").fadeIn(3000, 0.0);
    });
    return false;
});

// remove $dequeue

$("a").mouseleave(function() {
    $("span").fadeOut(3000, 0.0);
});
</code>```

EDIT:

http://jsfiddle.net/pxfunc/y9qd6/

```<code>var $a = $('a'),
    $div = $('div'),
    $span = $('span');

$a.mouseover(function() {
    $div.show();
    $span.fadeIn(1000);
}).mouseleave(function() {
    $span.stop(true, true).fadeOut(1000);
});
</code>```

this should work like you're looking for, the span fades out completely before fading back in.

Title: jQuery .fadeOut problems in FireFox 6.0

Body:
So far, I have the fadeIn working, but the fadeOut has not been quite right.  Right now, as soon as the mouse leaves the hover area, it doesn't look like any fadeOut is happening at all.  I would like to have a smooth fade out that completes before the next animation (the next fadeIn) begins and doesn't queue up.  Basically this is over some links that are within  tags.  I'm in the home stretch now!

P.S. I know I'm not using .hover.  I'd rather stick with mouseover and mouseleave for now, or even mouseout.  Please accomodate this small request.

<!DOCTYPE html>

MouseOver!

Sample Text

Edit: 08/18/2011

I realized that there may be script conflicting with the one above.  I have an additional jquery script running on the same page.  By itself it works fine, but when I add the script for the text box (above) the .fadeOut on both images and text becomes ignored or at the very least, inconsistent.

2nd jQuery script:

Here is an example of one of the four "targets" that should prompt the text and image to display (there are four text boxes accompanying four images - each get shown by a mouseover on the target).

HTML:

Target A

Textbox content for Target A

Body:
sans the $dequeue both events seem to be working

http://jsfiddle.net/pxfunc/y9qd6/

$("a").mouseover(function() {
    $("div").fadeIn(0, function() {
        $("span").fadeIn(3000, 0.0);
    });
    return false;
});

// remove $dequeue

$("a").mouseleave(function() {
    $("span").fadeOut(3000, 0.0);
});

EDIT:

http://jsfiddle.net/pxfunc/y9qd6/

var $a = $('a'),
    $div = $('div'),
    $span = $('span');

$a.mouseover(function() {
    $div.show();
    $span.fadeIn(1000);
}).mouseleave(function() {
    $span.stop(true, true).fadeOut(1000);
});

this should work like you're looking for, the span fades out completely before fading back in.


问:
Avoid Where phrase with gorm
I'm trying to update every record in a table:

```<code>sqlDB.Table("task").Where("1=1").Update("status", 1)
</code>```

And I can't avoid the 1=1 where condition. Is that the right way to do it?

答:
According to https://gorm.io/docs/update.html#Block-Global-Updates

This should work:

```<code>db.Session(&gorm.Session{AllowGlobalUpdate: true}).Model(&User{}).Update("name", "jinzhu")
</code>```

Title: Avoid Where phrase with gorm

Body:
I'm trying to update every record in a table:

sqlDB.Table("task").Where("1=1").Update("status", 1)

And I can't avoid the 1=1 where condition. Is that the right way to do it?

Body:
According to https://gorm.io/docs/update.html#Block-Global-Updates

This should work:

db.Session(&gorm.Session{AllowGlobalUpdate: true}).Model(&User{}).Update("name", "jinzhu")


问:
Why `VkPipelineStageFlagBits` does not only define pipeline stages?
VkPipelineStageFlagBits defines flags corresponding to stages that we would expect in a Graphics Pipeline such as VK_PIPELINE_STAGE_VERTEX_SHADER_BIT or VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, etc. We also have Compute Pipeline stages such as VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT.

But there are also some flags defined here that does not seem to correspond to any Graphics or Compute Pipeline stage at all, such as VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT and VK_PIPELINE_STAGE_ALL_COMMANDS_BIT (from which VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT and VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT are defined). Instead, these are defined in the specification by referring to commands. For instance:

VK_PIPELINE_STAGE_TRANSFER_BIT specifies the following commands:

All copy commands, including vkCmdCopyQueryPoolResults

vkCmdBlitImage2 and vkCmdBlitImage

vkCmdResolveImage2 and vkCmdResolveImage

All clear commands, with the exception of vkCmdClearAttachments

So if it is not a pipeline stage, why is it listed in Vk**PipelineStage**FlagBits? Why is it named this way? What does it mean if I use VK_PIPELINE_STAGE_TRANSFER_BIT as srcStageMask or dstStageMask in VkSubpassDependency for instance?

答:
Transfers can be inserted pretty much anywhere into a pipeline to move data between buffers. These are normal commands with dependencies that can be queued, and typically have dedicated hardware so other shaders can run in parallel. The "clear" commands use a constant value as the source for the copy operation, but still use the DMA engine, so they are in the same group.

These bits largely correspond to the resources that will be used. In the case of VkSubpassDependency, they define which resources need to be synchronized for the pipeline to deliver correct results, so if you use a Copy or Clear operation in the first subpass, you need to specify VK_PIPELINE_STAGE_TRANSFER_BIT in the srcStageMask to denote that the first subpass will use the DMA engine, so handover to the second subpass requires the write caches of the DMA engine to be flushed. Omitting this bit would allow an invalid optimization, so it is diallowed to use a Copy or Clear command then.

The "All Commands", "Top of Pipe" and "Bottom of Pipe" are just shorthands to save on negotiation during pipeline setup.


问:
How to set Java JDK path in Android Studio Arctic Fox, Bumblebee, etc.?
How can I set the new path for Java JDK? I tried to change the environment variables but it did not work.

IDE: Android Studio Arctic Fox | 2020.3.1 Beta 4

IDE: Android Studio Bumblebee | 2021.1.1

答: Android Studio Bumblebee | 2021.1.1 Patch 1 has a fix for "Env variables not sourced when launched from Mac OS X to Monterey Dock" - See https://androidstudio.googleblog.com/2022/02/android-studio-bumblebee-202111-patch-1.html


问:
What command can structure and layout code in Atom?
I copied code and pasted it in Atom (text editor), but it is all wrapped and very unclear to understand now. I'm looking for a command that unwraps the code and structures it automatically, instead of manually adding tabs and spaces.

example of what I mean with wrapped text

答: I replaced all the ">" with "> \n", which makes it a bit more clear already, but still not perfect</p>


问:
What is an acceptable render time for a react app?
In the "React Developer Tools" extension, a profiler has been added that displays the time spent on rendering. Are there any guidelines/table? For example, an acceptable render time for an average web application should be 50-300ms. Or like performance index in chrome developer tool?</p>

答:
In generally, render should take about 16 milliseconds. Any longer than that and things start feeling really janky.
I would recommend this article on performance in react. He is explaining more about profiling and performance in react.

performance with react(with forms) : https://epicreact.dev/improve-the-performance-of-your-react-forms/

 profiling article: https://kentcdodds.com/blog/profile-a-react-app-for-performance


问:
Should I use AWS Glue or Spark on EMR for processing binary data to parquet format
I have a work requirement of reading binary data from sensors and produce parquet output results for Analytics.

For storage I have chosen s3 and Dynamodb.

For processing engine I’m confused on how to choose between AWS EMR or AWS Glue.

Data processing code base will be maintained in python coupled with Spark.

Please post your suggestion on choosing between AWS EMR or AWS Glue.

答:
Using Glue / EMR depends on your use-case.

EMR is a managed cluster of servers and costs less than Glue, but it also requires more maintenance and set-up overhead. You can not only run Spark but also other frameworks on EMR like Flink.

Glue is serverless Spark / Python and really easy to use. It does not run on the latest Spark version and abstracts a lot of Spark away, in a good but also in a bad sense, that you can not set specific configurations very easily.


问:
Trouble with arrays in Javascript
I need an array to be created with a PHP loop.

It will look like:

```<code>[ utcdate1:[ series1:[value], series2:[value], series3:[value], utcdate2:[ series1:[value], series2:[value], series3:[value], etc..... ]
</code>```

Here is my code:

```<code>totals = { <?php
    for ($i=0; $i < count($date); $i++) {
        echo "Date.UTC(".
             $year[$i].",".
             $month[$i].",".
             $day[$i].
             "):[ Movies:[".$nomovies[$i].
             "], Shows:[".$noshows[$i].
             "], Music:[".$nomusic[$i].
             "] ]";
        if ($i < (count($date)-1)) {
            echo ",";
        }
    } ?> };
</code>```

Why doesn't this code work?

答:
You cannot compute JS property name on the fly. Try this:

```<code>totals = {};
<?php
for ($i=0; $i < count($date); $i++) {
    echo "totals[Date.UTC(".
         $year[$i].",".
         $month[$i].",".
         $day[$i].
         ")] = [ Movies:[".$nomovies[$i].
         "], Shows:[".$noshows[$i].
         "], Music:[".$nomusic[$i].
         "] ];";
} ?>
</code>```

EDIT:
While we're at it, JavaScript is not Java.  JavaScript runs in browsers and is the future of HTML5.  Java commonly runs on server, as programs, or as applet, and is now a static type traditional programming language.  They are quite different, really, both in syntax and in concept.

So, tag wisly next time.

Title: Trouble with arrays in Javascript

Body:
I need an array to be created with a PHP loop.

It will look like:

[ utcdate1:[ series1:[value], series2:[value], series3:[value], utcdate2:[ series1:[value], series2:[value], series3:[value], etc..... ]

Here is my code:

totals = { <?php
    for ($i=0; $i < count($date); $i++) {
        echo "Date.UTC(".
             $year[$i].",".
             $month[$i].",".
             $day[$i].
             "):[ Movies:[".$nomovies[$i].
             "], Shows:[".$noshows[$i].
             "], Music:[".$nomusic[$i].
             "] ]";
        if ($i < (count($date)-1)) {
            echo ",";
        }
    } ?> };

Why doesn't this code work?

Body:
You cannot compute JS property name on the fly. Try this:

totals = {};
<?php
for ($i=0; $i < count($date); $i++) {
    echo "totals[Date.UTC(".
         $year[$i].",".
         $month[$i].",".
         $day[$i].
         ")] = [ Movies:[".$nomovies[$i].
         "], Shows:[".$noshows[$i].
         "], Music:[".$nomusic[$i].
         "] ];";
} ?>

EDIT:
While we're at it, JavaScript is not Java.  JavaScript runs in browsers and is the future of HTML5.  Java commonly runs on server, as programs, or as applet, and is now a static type traditional programming language.  They are quite different, really, both in syntax and in concept.

So, tag wisly next time.


问:
Encrypt Django project
I have a project (django) running in our office in server. There are some people who have access in server. But I want to do something so that other people (who have access in server) can not read, or write, or edit, or do anything in my project (django)'s source code.

Server is running using Ubuntu OS.

答:
The trick with permissions will help restrict access to non-privileged users, but the administrator with su can read anything.

So the administrator could read your config, keys, any other credentials or make a backup from PostgreSQL or another database and read data under Django's user credentials that could be found in your config.

You can install your app in the cloud in your infrastructure and if you need to make calls in your internal infrastructure there are a lot of technics - from ssh tunnel to writing a simple proxy app.

Title: Encrypt Django project


问:
DNN library is not found ssd_mobile_net_v2 in Colab
I'm training a hand detection model with Tensorflow and I have a problem.

This is the code to train the model:

```<code>!cd RealTimeObjectDetection/RealTimeObjectDetection && python Tensorflow/models/research/object_detection/model_main_tf2.py --model_dir=/content/RealTimeObjectDetection/RealTimeObjectDetection/Tensorflow/workspace/models/my_ssd_mobnet --pipeline_config_path=Tensorflow/workspace/models/my_ssd_mobnet/pipeline.config --num_train_steps=5000
</code>```

I have this error:

```<code>Node: 'ssd_mobile_net_v2_fpn_keras_feature_extractor/model/Conv1/Conv2D'
DNN library is not found.
     [[{{node ssd_mobile_net_v2_fpn_keras_feature_extractor/model/Conv1/Conv2D}}]] [Op:__inference__dummy_computation_fn_15081]
</code>```

答: From what I can find, this has to do with the newer version of TensorFlow (2.8.0). I was able to resolve the issue by following this - https://github.com/tensorflow/models/issues/10479#issuecomment-1029626502</p>

Body:
I'm training a hand detection model with Tensorflow and I have a problem.

This is the code to train the model:

!cd RealTimeObjectDetection/RealTimeObjectDetection && python Tensorflow/models/research/object_detection/model_main_tf2.py --model_dir=/content/RealTimeObjectDetection/RealTimeObjectDetection/Tensorflow/workspace/models/my_ssd_mobnet --pipeline_config_path=Tensorflow/workspace/models/my_ssd_mobnet/pipeline.config --num_train_steps=5000

I have this error:

Node: 'ssd_mobile_net_v2_fpn_keras_feature_extractor/model/Conv1/Conv2D'
DNN library is not found.
     [[{{node ssd_mobile_net_v2_fpn_keras_feature_extractor/model/Conv1/Conv2D}}]] [Op:__inference__dummy_computation_fn_15081]


问:
Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger
I've got an interesting problem in which the org.apache.log4j.Logger class is not found during runtime. I'm trying to get authorized and that is where it's failing:

OAuthAuthorizer oauthAuthorizer = new OAuthAuthorizer(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, SAML_PROVIDER_ID, userId);

I'm using JDeveloper 11.1.1.6. Here is what I know:

I've looked in my UI.war/WEB-INF/lib directory and I see the log4j-1.2.17.jar there.

The class complaining about it is org.opensaml.xml.XMLConfigurator

```<code>Caused by: java.lang.NoClassDefFoundError: org/apache/log4j/Logger
    at org.opensaml.xml.XMLConfigurator.<clinit>(XMLConfigurator.java:60)
    at org.opensaml.DefaultBootstrap.initializeXMLTooling(DefaultBootstrap.java:195)
    at org.opensaml.DefaultBootstrap.bootstrap(DefaultBootstrap.java:91)
    at com.intuit.ipp.aggcat.util.SAML2AssertionGenerator.getSAMLBuilder(SAML2AssertionGenerator.java:156)
    at com.intuit.ipp.aggcat.util.SAML2AssertionGenerator.createSubject(SAML2AssertionGenerator.java:187)
    at com.intuit.ipp.aggcat.util.SAML2AssertionGenerator.buildAssertion(SAML2AssertionGenerator.java:114)
    at com.intuit.ipp.aggcat.util.SAML2AssertionGenerator.generateSignedAssertion(SAML2AssertionGenerator.java:83)
    at com.intuit.ipp.aggcat.util.SamlUtil.createSignedSAMLPayload(SamlUtil.java:156)
    at com.intuit.ipp.aggcat.util.OAuthUtil.getOAuthTokens(OAuthUtil.java:60)
    at com.intuit.ipp.aggcat.core.OAuthAuthorizer.<init>(OAuthAuthorizer.java:85)
    at com.incomemax.view.intuit.WebUtil.getAggCatService(WebUtil.java:91)
</code>```

```<code>Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Logger
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:305)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:246)
    ... 64 more
</code>```

I decomplied XMLConfigurator and oddly it doesn't import org.apache.log4j.Logger It uses org.slf4j.Logger which is also in my jars directory (slf4j-api-1.7.5.jar). Also interesting is that line 60 (see stack trace) is a blank line in my decompile.

Of course if I add Logger.xxxxx during design time, it finds it just fine.

I'm using the code/jars directly from the sample java code, but imported into my existing application.

I've been scouring the web for answers and I believe I've checked all the areas I can think of. I also referenced this very good page: http://myarch.com/classnotfound/

Given authorization is step 1 in using the Intuit Developer API, I'm kinda stuck.

Adding output from @jhadesdev suggestion:

All versions of log4j Logger:

zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/log4j-1.2.17.jar!/org/apache/log4j/Logger.class

All versions of log4j visible from the classloader of the OAuthAuthorizer class:

zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/log4j-1.2.17.jar!/org/apache/log4j/Logger.class

All versions of XMLConfigurator:

jar:file:/C:/Oracle/Middleware11116/modules/com.bea.core.bea.opensaml2_1.0.0.0_6-1-0-0.jar!/org/opensaml/xml/XMLConfigurator.class

zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/ipp-java-aggcat-v1-devkit-1.0.2.jar!/org/opensaml/xml/XMLConfigurator.class

zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/xmltooling-1.3.1.jar!/org/opensaml/xml/XMLConfigurator.class

All versions of XMLConfigurator visible from the class loader of the OAuthAuthorizer class:

jar:file:/C:/Oracle/Middleware11116/modules/com.bea.core.bea.opensaml2_1.0.0.0_6-1-0-0.jar!/org/opensaml/xml/XMLConfigurator.class

zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/ipp-java-aggcat-v1-devkit-1.0.2.jar!/org/opensaml/xml/XMLConfigurator.class

zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/xmltooling-1.3.1.jar!/org/opensaml/xml/XMLConfigurator.class

I'm still working on interpreting the results.

答: Add compile 'org.apache.logging.log4j:log4j-1.2-api:2.17.1' and then it will automatically work</p>

Body:
I've got an interesting problem in which the org.apache.log4j.Logger class is not found during runtime. I'm trying to get authorized and that is where it's failing:

OAuthAuthorizer oauthAuthorizer = new OAuthAuthorizer(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, SAML_PROVIDER_ID, userId);

I'm using JDeveloper 11.1.1.6. Here is what I know:

I've looked in my UI.war/WEB-INF/lib directory and I see the log4j-1.2.17.jar there.

The class complaining about it is org.opensaml.xml.XMLConfigurator

Caused by: java.lang.NoClassDefFoundError: org/apache/log4j/Logger
    at org.opensaml.xml.XMLConfigurator.<clinit>(XMLConfigurator.java:60)
    at org.opensaml.DefaultBootstrap.initializeXMLTooling(DefaultBootstrap.java:195)
    at org.opensaml.DefaultBootstrap.bootstrap(DefaultBootstrap.java:91)
    at com.intuit.ipp.aggcat.util.SAML2AssertionGenerator.getSAMLBuilder(SAML2AssertionGenerator.java:156)
    at com.intuit.ipp.aggcat.util.SAML2AssertionGenerator.createSubject(SAML2AssertionGenerator.java:187)
    at com.intuit.ipp.aggcat.util.SAML2AssertionGenerator.buildAssertion(SAML2AssertionGenerator.java:114)
    at com.intuit.ipp.aggcat.util.SAML2AssertionGenerator.generateSignedAssertion(SAML2AssertionGenerator.java:83)
    at com.intuit.ipp.aggcat.util.SamlUtil.createSignedSAMLPayload(SamlUtil.java:156)
    at com.intuit.ipp.aggcat.util.OAuthUtil.getOAuthTokens(OAuthUtil.java:60)
    at com.intuit.ipp.aggcat.core.OAuthAuthorizer.<init>(OAuthAuthorizer.java:85)
    at com.incomemax.view.intuit.WebUtil.getAggCatService(WebUtil.java:91)

Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Logger
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:305)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:246)
    ... 64 more

I decomplied XMLConfigurator and oddly it doesn't import org.apache.log4j.Logger It uses org.slf4j.Logger which is also in my jars directory (slf4j-api-1.7.5.jar). Also interesting is that line 60 (see stack trace) is a blank line in my decompile.

Of course if I add Logger.xxxxx during design time, it finds it just fine.

I'm using the code/jars directly from the sample java code, but imported into my existing application.

I've been scouring the web for answers and I believe I've checked all the areas I can think of. I also referenced this very good page: http://myarch.com/classnotfound/

Given authorization is step 1 in using the Intuit Developer API, I'm kinda stuck.

Adding output from @jhadesdev suggestion:

All versions of log4j Logger:

zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/log4j-1.2.17.jar!/org/apache/log4j/Logger.class

All versions of log4j visible from the classloader of the OAuthAuthorizer class:

zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/log4j-1.2.17.jar!/org/apache/log4j/Logger.class

All versions of XMLConfigurator:

jar:file:/C:/Oracle/Middleware11116/modules/com.bea.core.bea.opensaml2_1.0.0.0_6-1-0-0.jar!/org/opensaml/xml/XMLConfigurator.class

zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/ipp-java-aggcat-v1-devkit-1.0.2.jar!/org/opensaml/xml/XMLConfigurator.class

zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/xmltooling-1.3.1.jar!/org/opensaml/xml/XMLConfigurator.class

All versions of XMLConfigurator visible from the class loader of the OAuthAuthorizer class:

jar:file:/C:/Oracle/Middleware11116/modules/com.bea.core.bea.opensaml2_1.0.0.0_6-1-0-0.jar!/org/opensaml/xml/XMLConfigurator.class

zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/ipp-java-aggcat-v1-devkit-1.0.2.jar!/org/opensaml/xml/XMLConfigurator.class

zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/xmltooling-1.3.1.jar!/org/opensaml/xml/XMLConfigurator.class

I'm still working on interpreting the results.


问:
How to read sheet names of excel sheet from S3 in AWS Wrangler?
I have an excel sheet which is placed in S3 and I want to read sheet names of excel sheet.
I have read excel sheet with aws wrangler using awswrangler.s3.read_excel(path)
How can I read sheetnames using AWS Wrangler using Python?</p>

答:
According to the awswrangler docs of the read_excel() function:

This function accepts any Pandas’s read_excel() argument.

And in pandas:

sheet_name : str, int, list, or None, default 0

so you could try something like this:

```<code>import awswrangler as wr
wr.s3.read_excel(file_uri,sheet_name=your_sheet)
</code>```

I am currently facing a similar problem in AWS Glue, but did not manage to get it working yet.

Body:
According to the awswrangler docs of the read_excel() function:

This function accepts any Pandas’s read_excel() argument.

And in pandas:

sheet_name : str, int, list, or None, default 0

so you could try something like this:

import awswrangler as wr
wr.s3.read_excel(file_uri,sheet_name=your_sheet)

I am currently facing a similar problem in AWS Glue, but did not manage to get it working yet.


问:
Event on view rendering finished
After navigating to a new view i want to start a background thread, which does some validation and reports changes to my view. I am building the ui and starting the thread on AfterNavigationObserver#afterNavigation.

Most of the time this works, but when the background thread finishes too fast it can't update the view cause the rendering is not finished and the component to update is not visible yet. The possible solution would be to start the background thread after the rendering is finished and the view is visible in the browser. What is the recommended way to do this? I looked through the APIs but can't find a matching event.

Using vaadin-flow 14.8.

In the following minimal example the second accordion panel should be opened when the task finished. It works on my pc mostly with a timeout of 500 ms or greater. Going below this value or removing the sleep results in not opening the second accordion.

The view:

import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.accordion.Accordion;
import com.vaadin.flow.component.accordion.AccordionPanel;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.page.Push;
import com.vaadin.flow.router.AfterNavigationEvent;
import com.vaadin.flow.router.AfterNavigationObserver;
import com.vaadin.flow.router.Route;
import de.fs_aut.ddm.desktop.bgtasks.TimeConsumingTask;
import org.springframework.beans.factory.annotation.Autowired;

@Route("debug")
@Push
public class DebugView extends VerticalLayout implements AfterNavigationObserver {

  @Autowired
  private TimeConsumingTask task;

  private UI ui;
  private Accordion acc;
  private AccordionPanel firstPanel;
  private AccordionPanel secondPanel;

  @Override
  public void afterNavigation(AfterNavigationEvent event) {
    removeAll();
    acc = new Accordion();
    firstPanel = new AccordionPanel("First task", new Label("first task in progress"));
    secondPanel = new AccordionPanel("second task", new Label("second task in progress"));
    acc.add(firstPanel);
    acc.add(secondPanel);
    add(acc);
    startValidation();
  }

  public void startValidation() {
    ui = UI.getCurrent();
    task.sleep().addCallback(result -> {
      ui.access(() -> {
        acc.open(secondPanel);
      });
    }, error -> {
    });
  }
}
```
<p>The async task:</p>
<pre class="lang-java prettyprint-override"><code>import java.time.LocalDateTime;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;

/**
 * Testdummy. Does nothing but waits.
 *
 */
@Service
public class TimeConsumingTask {

  @Async
  public ListenableFuture<String> sleep() {
    try {
      Thread.sleep(500);
    } catch (final InterruptedException e) {
      e.printStackTrace();
    }
    return AsyncResult.forValue("Validation finished at " + LocalDateTime.now().toString());
  }
}
</code>```

答:
Knoobie's answer should be checked, but (if I remember correctly) StackOverflow guidelines prefers code over a link to the same.

Every Component the onAttach(DetachEvent) method. From the Javadoc:

`protected void onAttach(AttachEvent attachEvent)

Called when the component is attached to a UI.

The default implementation does nothing.

This method is invoked before the AttachEvent is fired for the component.

Parameters:

attachEvent - the attach event

You can override this method in any Component:

public class MyComponent extends VerticalLayout {
  @Override
  protected void onAttach(AttachEvent event) {
    System.out.println("I attached: " + event);
  }
}
```
<p><code>Component</code> also implements <code>AttachNotifier</code>, which offers the this method:</p>
<pre class="lang-java prettyprint-override"><code>public class MyComponent extends VerticalLayout {
  public MyComponent() {
    addAttachListener(event -> System.out.println("I attached: " + event));
  }
}
</code>```

Note the docs quoted above! The onAttach method is called before the event.

Another approach is from JavaScript to wait for the v-loading-indicator's first child to have display: none.

Title: Event on view rendering finished

Body:
After navigating to a new view i want to start a background thread, which does some validation and reports changes to my view. I am building the ui and starting the thread on AfterNavigationObserver#afterNavigation.

Most of the time this works, but when the background thread finishes too fast it can't update the view cause the rendering is not finished and the component to update is not visible yet. The possible solution would be to start the background thread after the rendering is finished and the view is visible in the browser. What is the recommended way to do this? I looked through the APIs but can't find a matching event.

Using vaadin-flow 14.8.

In the following minimal example the second accordion panel should be opened when the task finished. It works on my pc mostly with a timeout of 500 ms or greater. Going below this value or removing the sleep results in not opening the second accordion.

The view:

import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.accordion.Accordion;
import com.vaadin.flow.component.accordion.AccordionPanel;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.page.Push;
import com.vaadin.flow.router.AfterNavigationEvent;
import com.vaadin.flow.router.AfterNavigationObserver;
import com.vaadin.flow.router.Route;
import de.fs_aut.ddm.desktop.bgtasks.TimeConsumingTask;
import org.springframework.beans.factory.annotation.Autowired;

@Route("debug")
@Push
public class DebugView extends VerticalLayout implements AfterNavigationObserver {

  @Autowired
  private TimeConsumingTask task;

  private UI ui;
  private Accordion acc;
  private AccordionPanel firstPanel;
  private AccordionPanel secondPanel;

  @Override
  public void afterNavigation(AfterNavigationEvent event) {
    removeAll();
    acc = new Accordion();
    firstPanel = new AccordionPanel("First task", new Label("first task in progress"));
    secondPanel = new AccordionPanel("second task", new Label("second task in progress"));
    acc.add(firstPanel);
    acc.add(secondPanel);
    add(acc);
    startValidation();
  }

  public void startValidation() {
    ui = UI.getCurrent();
    task.sleep().addCallback(result -> {
      ui.access(() -> {
        acc.open(secondPanel);
      });
    }, error -> {
    });
  }
}

The async task:

import java.time.LocalDateTime;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;

/**
 * Testdummy. Does nothing but waits.
 *
 */
@Service
public class TimeConsumingTask {

  @Async
  public ListenableFuture<String> sleep() {
    try {
      Thread.sleep(500);
    } catch (final InterruptedException e) {
      e.printStackTrace();
    }
    return AsyncResult.forValue("Validation finished at " + LocalDateTime.now().toString());
  }
}

Body:
Knoobie's answer should be checked, but (if I remember correctly) StackOverflow guidelines prefers code over a link to the same.

Every Component the onAttach(DetachEvent) method. From the Javadoc:

`protected void onAttach(AttachEvent attachEvent)

Called when the component is attached to a UI.

The default implementation does nothing.

This method is invoked before the AttachEvent is fired for the component.

Parameters:

attachEvent - the attach event

You can override this method in any Component:

public class MyComponent extends VerticalLayout {
  @Override
  protected void onAttach(AttachEvent event) {
    System.out.println("I attached: " + event);
  }
}

Component also implements AttachNotifier, which offers the this method:

public class MyComponent extends VerticalLayout {
  public MyComponent() {
    addAttachListener(event -> System.out.println("I attached: " + event));
  }
}

Note the docs quoted above! The onAttach method is called before the event.

Another approach is from JavaScript to wait for the v-loading-indicator's first child to have display: none.


问:
Link to second local html file with PhoneGap
I want to switch from the index.html file to a second html file called projects.html in a PhoneGap App on Android. If I write something like Second Page the projects.html page opens, but I get a prompt "[]" and then "usePolling" and then "getPort". In adb logcat the error "D/PhoneGapLog( 3288): file:///android_asset/www/phonegap.0.9.6.js: Line 810 : JSCallback Error: Request failed." appears. Looking around on the internet using multiple html files seems to me to be some kind of an issue with phonegap. Any ideas how I could get this to work?

答:
As a solution for this problem, you can either edit phonegap.0.9.5.js and comment out all lines that contain the prompt() function (there are six lines).

Or you download PhoneGap 0.9.4 (PhoneGap 0.9.4 doesn't use the prompt() function), extract the phonegap.0.9.4.js file from it, delete phonegap.0.9.5.js from the assets/www/ directory and place phonegap.0.9.4.js in the assets/www/ directory instead.


问:
Add line break for string assignment (For html rendering)
I am trying to create a new line like so:

```<code>let myString= "";
for (const [key, value] of Object.entries(response)) {
   myString += response + "\n";
}
</code>```

But the HTML outputs space instead of line break

答:
You'll want to use
 to create a new line in html. Browsers don't generally respect whitespace unless wrapped in a ```

Body:
I am trying to create a new line like so:

let myString= "";
for (const [key, value] of Object.entries(response)) {
   myString += response + "\n";
}

But the HTML outputs space instead of line break

Body: You'll want to use <br> to create a new line in html. Browsers don't generally respect whitespace unless wrapped in a <pre>