问:
How to download latest artifact from nexus using jenkins pipeline?
I have a situation where it demands to download latest maven build artifacts from Nexus repository by using Jenkins pipeline? Do anyone have any suggestions?
I have already searched through internet but without any help.
I tried to use "curl" but with no help.</p>

```<code>  curl -L -u admin:admin123 https://<Nexus URL>/repository/<Repo
       Name>/version.txt --insecure >
   version.txt
</code>```

答: You can use maven plugin for this.....mvn org.apache.maven.plugins:maven-dependency-plugin:2.4:get -DrepoUrl=http://10.101.15.190:8081/nexus/content/repositories/releases/ -Dartifact=bits:update-service:1.0.3 -Ddest=Setups/Services/update-service.jar

Body:
I have a situation where it demands to download latest maven build artifacts from Nexus repository by using Jenkins pipeline? Do anyone have any suggestions?
I have already searched through internet but without any help.
I tried to use "curl" but with no help.

  curl -L -u admin:admin123 https://<Nexus URL>/repository/<Repo
       Name>/version.txt --insecure >
   version.txt


来源: stackexchange

问:
Why does asp.net running on .net 4.8 add a http header x-aspnet-version: 4.0.30319
I do have .net 4.8 installed. When i create a new simple asp.net mvc application using visual studio 2019 and start the website using the builtin IIS-Express, it will add the following header:

x-aspnet-version: 4.0.30319

The same header is also added when i'm hosting the site using IIS. I am aware that i can remove this header (and i will), but i would like to understand the version number.
It seems version 4.0.30319 was the initial .net 4.0 version number. What is the point to have this in the http header when using .net 4.8?

答:
That is the CLR version.

All .NET Framework 4 versions use CLR 4.0.30319.xxxxx

xxxxx is less than 42000 for .NET Frameworks 4 to 4.5.2

xxxxx is greater than 42000 for .NET Frameworks 4.6 and higher

The xxxxx extension is not part of the header for security purposes, so as not to divulge the patch state of the server.

ContentLicense: CC BY-SA 4.0


问:
Make UINavigationBar transparent
How do you make a UINavigationBar transparent? Though I want its bar items to remain visible.

答:
If you build with the latest beta iOS 13.4 and Xcode 11.4, the accepted answer won't work anymore.
I've found another way, maybe it's just a bug in the beta software, but I'm writing it down there, just in case

(swift 5)

```<code>import UIKit

class TransparentNavBar :UINavigationBar {
    override func awakeFromNib() {
        super.awakeFromNib()
        self.setBackgroundImage(UIImage(), for: .default)
        self.shadowImage = UIImage()
        self.isTranslucent = true
        self.backgroundColor = .clear
        if #available(iOS 13.0, *) {
            self.standardAppearance.backgroundColor = .clear
            self.standardAppearance.backgroundEffect = .none
            self.standardAppearance.shadowColor = .clear
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Make UINavigationBar transparent

Body:
If you build with the latest beta iOS 13.4 and Xcode 11.4, the accepted answer won't work anymore.
I've found another way, maybe it's just a bug in the beta software, but I'm writing it down there, just in case

(swift 5)

import UIKit

class TransparentNavBar :UINavigationBar {
    override func awakeFromNib() {
        super.awakeFromNib()
        self.setBackgroundImage(UIImage(), for: .default)
        self.shadowImage = UIImage()
        self.isTranslucent = true
        self.backgroundColor = .clear
        if #available(iOS 13.0, *) {
            self.standardAppearance.backgroundColor = .clear
            self.standardAppearance.backgroundEffect = .none
            self.standardAppearance.shadowColor = .clear
        }
    }
}


问:
Mock exported const arrow functions with Jest
Given the following example with a basic test, I'd expect bar to be returned when sendMessage.message is mocked with Jest. Instead, when called, it returns the original value of "Hello World".

serviceBus.js

export const message = () => {
  return "Hello world";
};

export const foo = () => {
  return message();
};
```

<h3>mockDemo.test.js</h3>

<pre class="lang-js prettyprint-override"><code>import * as sendMessage from "../src/services/serviceBus";

describe("sendMessage", () => {
  sendMessage.message = jest.fn(() => {
    return "bar";
  });

  it(`message should return bar`, async () => {
    expect(sendMessage.message()).toBe("bar");
    expect(sendMessage.foo()).toBe("bar");
  });
});
</code>```

And the results as follows:

$ ./node_modules/.bin/jest ./__tests__/mockDemo.test.js
 FAIL  __tests__/mockDemo.test.js
  MessageReceiver Router
    ✕ message should return bar (9ms)

  ● MessageReceiver Router › message should return bar

    expect(received).toBe(expected) // Object.is equality

    Expected: "bar"
    Received: "Hello world"

       9 |   it(`message should return bar`, async () => {
      10 |     expect(sendMessage.message()).toBe("bar");
    > 11 |     expect(sendMessage.foo()).toBe("bar");
         |                               ^
      12 |   });
      13 | });
      14 |

      at Object.<anonymous> (__tests__/mockDemo.test.js:11:31)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
```

<p>It looks as if <code>sendMessage.foo</code> is calling the bound function once imported of <code>message</code>, which by default returns <code>Hello World</code>.</p>

<p>How would one mock <code>message</code> in this context? </p>

<h3>Update</h3>

<p>Using <code>jest.fn().mockImplementation(() => "bar");</code> results in the same behaviour:</p>

<pre class="lang-js prettyprint-override"><code>describe("MessageReceiver Router", () => {
  //   sendMessage.message.mockImplementation = jest.fn(() => {
  //     return "bar";
  //   });

  sendMessage.message = jest.fn().mockImplementation(() => "bar");

  it(`message should return bar`, async () => {
    expect(sendMessage.message()).toBe("bar");
    expect(sendMessage.foo()).toBe("bar");
  });
});
</code>```

Results:

```<code>$ ./node_modules/.bin/jest ./__tests__/mockDemo.test.js
 FAIL  __tests__/mockDemo.test.js
  MessageReceiver Router
    ✕ message should return bar (10ms)

  ● MessageReceiver Router › message should return bar

    expect(received).toBe(expected) // Object.is equality

    Expected: "bar"
    Received: "Hello world"

      11 |   it(`message should return bar`, async () => {
      12 |     expect(sendMessage.message()).toBe("bar");
    > 13 |     expect(sendMessage.foo()).toBe("bar");
         |                               ^
      14 |   });
      15 | });
      16 |

      at Object.<anonymous> (__tests__/mockDemo.test.js:13:31)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.175s
</code>```

答:
You should use spyOn method to mock the sendMessage.message method.

```<code>import * as sendMessage from "../src/services/serviceBus";

describe("sendMessage", () => {
   jest.spyOn(sendMessage, 'message').mockReturnValue("bar")

  it(`message should return bar`, async () => {
    expect(sendMessage.message()).toBe("bar");
    expect(sendMessage.foo()).toBe("bar");
  });
});
</code>```

Body:
Given the following example with a basic test, I'd expect bar to be returned when sendMessage.message is mocked with Jest. Instead, when called, it returns the original value of "Hello World".

serviceBus.js

export const message = () => {
  return "Hello world";
};

export const foo = () => {
  return message();
};

mockDemo.test.js

import * as sendMessage from "../src/services/serviceBus";

describe("sendMessage", () => {
  sendMessage.message = jest.fn(() => {
    return "bar";
  });

  it(`message should return bar`, async () => {
    expect(sendMessage.message()).toBe("bar");
    expect(sendMessage.foo()).toBe("bar");
  });
});

And the results as follows:

$ ./node_modules/.bin/jest ./__tests__/mockDemo.test.js
 FAIL  __tests__/mockDemo.test.js
  MessageReceiver Router
    ✕ message should return bar (9ms)

  ● MessageReceiver Router › message should return bar

    expect(received).toBe(expected) // Object.is equality

    Expected: "bar"
    Received: "Hello world"

       9 |   it(`message should return bar`, async () => {
      10 |     expect(sendMessage.message()).toBe("bar");
    > 11 |     expect(sendMessage.foo()).toBe("bar");
         |                               ^
      12 |   });
      13 | });
      14 |

      at Object.<anonymous> (__tests__/mockDemo.test.js:11:31)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total

It looks as if sendMessage.foo is calling the bound function once imported of message, which by default returns Hello World.

How would one mock message in this context?

Update

Using jest.fn().mockImplementation(() => "bar"); results in the same behaviour:

describe("MessageReceiver Router", () => {
  //   sendMessage.message.mockImplementation = jest.fn(() => {
  //     return "bar";
  //   });

  sendMessage.message = jest.fn().mockImplementation(() => "bar");

  it(`message should return bar`, async () => {
    expect(sendMessage.message()).toBe("bar");
    expect(sendMessage.foo()).toBe("bar");
  });
});

Results:

$ ./node_modules/.bin/jest ./__tests__/mockDemo.test.js
 FAIL  __tests__/mockDemo.test.js
  MessageReceiver Router
    ✕ message should return bar (10ms)

  ● MessageReceiver Router › message should return bar

    expect(received).toBe(expected) // Object.is equality

    Expected: "bar"
    Received: "Hello world"

      11 |   it(`message should return bar`, async () => {
      12 |     expect(sendMessage.message()).toBe("bar");
    > 13 |     expect(sendMessage.foo()).toBe("bar");
         |                               ^
      14 |   });
      15 | });
      16 |

      at Object.<anonymous> (__tests__/mockDemo.test.js:13:31)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.175s

Body:
You should use spyOn method to mock the sendMessage.message method.

import * as sendMessage from "../src/services/serviceBus";

describe("sendMessage", () => {
   jest.spyOn(sendMessage, 'message').mockReturnValue("bar")

  it(`message should return bar`, async () => {
    expect(sendMessage.message()).toBe("bar");
    expect(sendMessage.foo()).toBe("bar");
  });
});


问:
SQL Select unique values by one column with the latest value by another column
I have the following table structure:

```<code>leads:

name  | email | date
-------------------------------------------------------
John  | john@mail.com  | 2020-01-21
J     | john@mail.com  | 2020-01-20
Alex  | alex@mail.com  | 2020-01-19
A     | alex@mail.com  | 2020-01-18
James | james@mail.com | 2020-01-17
</code>```

I need to select only rows with UNIQUE emails and the LATEST associated name so the expected result is:

```<code>name  | email | date
-------------------------------------------------------
John  | john@mail.com  | 2020-01-21
Alex  | alex@mail.com  | 2020-01-19
James | james@mail.com | 2020-01-17
</code>```

答:
Use not exists</p>

```<code>select * from tbl a
where not exist(select 1 from tbl b where a.email = b.email  and a.date < b.date)
</code>```

Body:
I have the following table structure:

leads:

name  | email | date
-------------------------------------------------------
John  | john@mail.com  | 2020-01-21
J     | john@mail.com  | 2020-01-20
Alex  | alex@mail.com  | 2020-01-19
A     | alex@mail.com  | 2020-01-18
James | james@mail.com | 2020-01-17

I need to select only rows with UNIQUE emails and the LATEST associated name so the expected result is:

name  | email | date
-------------------------------------------------------
John  | john@mail.com  | 2020-01-21
Alex  | alex@mail.com  | 2020-01-19
James | james@mail.com | 2020-01-17

Body:
Use not exists

select * from tbl a
where not exist(select 1 from tbl b where a.email = b.email  and a.date < b.date)


问:
How to get the exact path to the script that was loaded in Lua?
What I am trying to do is perform "hot-reloading" of lua files as I work on them.

My problem is that I don't know how to match the file that changed with entries in the package.loaded table.  While I can guess it, I was wondering if the full path is stored anywhere.

Given a file called mymodule.lua, when we run this:

```<code>local x = require('mymodule')
</code>```

First lua looks in package.loaded to see if it's already loaded.  If not, then Lua looks for modules using the LUA_PATH, which we can see at runtime like so:

```<code>> print(package.path)
/usr/share/lua/5.3/?.lua;/usr/share/lua/5.3/?/init.lua;/usr/lib64/lua/5.3/?.lua;/usr/lib64/lua/5.3/?/init.lua;./?.lua;./?/init.lua
</code>```

After the above module is loaded, we can see that it's loaded by looking for it in the package.loaded table like so:

```<code>> for i,v in pairs(package.loaded) do
>> print(i, v)
>> end
debug   table: 0x55fa3bfe8b80
table   table: 0x55fa3bfe51e0
math    table: 0x55fa3bfe7820
mymodule    table: 0x55fa3bfe60f0
_G  table: 0x55fa3bfe2bc0
utf8    table: 0x55fa3bfe8700
bit32   table: 0x55fa3bfe9070
os  table: 0x55fa3bfe68f0
package table: 0x55fa3bfe4860
io  table: 0x55fa3bfe54e0
coroutine   table: 0x55fa3bfe4f90
string  table: 0x55fa3bfe7560
</code>```

My approach for handling hot-reloading is to null out the entry in this table package.loaded.mymodule = nil and then reload the script again like so
require('mymodule')  This appears to work fine - the module is reloaded.

But then there are caveats...  For example, if the module is actually setup as myproject/mymodule/init.lua, and this is loaded like so require('mymodule') then the entry in the package.loaded table will simply be mymodule and not something more helpful in this case such as mymodule/init.lua  I have no way of knowing that it's the init.lua file that I need to watch instead of mymodule.lua

In m case, I track the files in C.  My challenge is that I have to somehow guess which entry in the package.loaded table goes with which file.

What I'd like to know is if there's a table somewhere that contains the path to whatever .lua files are loaded so that I can just monitor that list.

Maybe package.loaded is the wrong place to look?

答:
It's possible to modify two searchers to collect module file paths into table package.loadedfrom

```<code>-- this block should be at the beginning of the main script
do
   assert(_VERSION:match"^Lua 5%.[2-4]$")  -- only for Lua 5.2+
   package.loadedfrom = {}

   local function save(modname, loader, path)
      if type(loader) == "function" then
         package.loadedfrom[modname] = path
      end
      return loader, path
   end

   local orig_searcher_2 = package.searchers[2]
   package.searchers[2] =
      function(modname)
         return save(modname, orig_searcher_2(modname))
      end

   local orig_searcher_3 = package.searchers[3]
   package.searchers[3] =
      function(modname)
         return save(modname, orig_searcher_3(modname))
      end
end

-- now require all your modules
require"mymodule"
require"mymodule2"

-- now get the list of module file paths
for modname, filepath in pairs(package.loadedfrom) do
   print(modname, filepath)
end
</code>```

Body:
What I am trying to do is perform "hot-reloading" of lua files as I work on them.

My problem is that I don't know how to match the file that changed with entries in the package.loaded table.  While I can guess it, I was wondering if the full path is stored anywhere.

Given a file called mymodule.lua, when we run this:

local x = require('mymodule')

First lua looks in package.loaded to see if it's already loaded.  If not, then Lua looks for modules using the LUA_PATH, which we can see at runtime like so:

> print(package.path)
/usr/share/lua/5.3/?.lua;/usr/share/lua/5.3/?/init.lua;/usr/lib64/lua/5.3/?.lua;/usr/lib64/lua/5.3/?/init.lua;./?.lua;./?/init.lua

After the above module is loaded, we can see that it's loaded by looking for it in the package.loaded table like so:

> for i,v in pairs(package.loaded) do
>> print(i, v)
>> end
debug   table: 0x55fa3bfe8b80
table   table: 0x55fa3bfe51e0
math    table: 0x55fa3bfe7820
mymodule    table: 0x55fa3bfe60f0
_G  table: 0x55fa3bfe2bc0
utf8    table: 0x55fa3bfe8700
bit32   table: 0x55fa3bfe9070
os  table: 0x55fa3bfe68f0
package table: 0x55fa3bfe4860
io  table: 0x55fa3bfe54e0
coroutine   table: 0x55fa3bfe4f90
string  table: 0x55fa3bfe7560

My approach for handling hot-reloading is to null out the entry in this table package.loaded.mymodule = nil and then reload the script again like so
require('mymodule')  This appears to work fine - the module is reloaded.

But then there are caveats...  For example, if the module is actually setup as myproject/mymodule/init.lua, and this is loaded like so require('mymodule') then the entry in the package.loaded table will simply be mymodule and not something more helpful in this case such as mymodule/init.lua  I have no way of knowing that it's the init.lua file that I need to watch instead of mymodule.lua

In m case, I track the files in C.  My challenge is that I have to somehow guess which entry in the package.loaded table goes with which file.

What I'd like to know is if there's a table somewhere that contains the path to whatever .lua files are loaded so that I can just monitor that list.

Maybe package.loaded is the wrong place to look?

Body:
It's possible to modify two searchers to collect module file paths into table package.loadedfrom

-- this block should be at the beginning of the main script
do
   assert(_VERSION:match"^Lua 5%.[2-4]$")  -- only for Lua 5.2+
   package.loadedfrom = {}

   local function save(modname, loader, path)
      if type(loader) == "function" then
         package.loadedfrom[modname] = path
      end
      return loader, path
   end

   local orig_searcher_2 = package.searchers[2]
   package.searchers[2] =
      function(modname)
         return save(modname, orig_searcher_2(modname))
      end

   local orig_searcher_3 = package.searchers[3]
   package.searchers[3] =
      function(modname)
         return save(modname, orig_searcher_3(modname))
      end
end

-- now require all your modules
require"mymodule"
require"mymodule2"

-- now get the list of module file paths
for modname, filepath in pairs(package.loadedfrom) do
   print(modname, filepath)
end


问:
ResourceBundle not found for MessageSource when placed inside a folder
I am trying to use resource bundles with Spring's Message Source. Here is the way I am doing it:

```<code>@Component
public class MessageResolver implements MessageSourceAware {

    @Autowired
    private MessageSource messageSource;

    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    public String getMessage(){
        return messageSource.getMessage("user.welcome", new Object[]{"Rama"} , Locale.US);
    }

}
</code>```

And here is my folder structure:

messages_en_US.properties contains just one line:

```<code>user.welcome=Welcome {0}
</code>```

Here is the xml configuration used:

```<code><bean name="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename">
        <value>resourcebundles/messages</value>
    </property>
</bean>
</code>```

Here is the error I am getting:

```<code>WARNING: ResourceBundle [resourcebundles/messages] not found for MessageSource: Can't find bundle for base name resourcebundles/messages, locale en_US
Exception in thread "main" org.springframework.context.NoSuchMessageException: No message found under code 'user.welcome' for locale 'en_US'.
</code>```

But if I move my resource bundle to directly under the resources folder, it is working fine. In this case, here is the xml configuration I am using:

```<code><bean name="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
    <value>messages</value>
</property>
</code>```

Is is that if I have to use ResourceBundleMessageSource, I should put my resource bundles directly under the resources? If i have to keep it in specified folder only, is there any other way to get this one work?

Thanks!

答:
Is is that if I have to use ResourceBundleMessageSource, I should put
  my resource bundles directly under the resources? If i have to keep it
  in specified folder only, is there any other way to get this one work?

You can define your messages in your own package, it does not need to be located in the resources folder.

Using Spring 5.2.2.RELEASE versioned components, this is the way I managed to make it work:

The qualified name of the file would be:

```<code>/tutproject/src/com/tutproject/app/messages/messages.properties
</code>```

The bean is defined like this in the my Spring Bean Configuration File (XML):

```<code><bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename"
    value="/com/tutproject/app/messages/messages">
</property>
</bean>
</code>```

The Java build path includes tutproject/src , this is the part of the location omitted in the XML definition.

Some additional useful information from the ResourceBundleMessageSource class:

The basenames follow {@link java.util.ResourceBundle}
  conventions: essentially,  * a fully-qualified classpath location. If
  it doesn't contain a package qualifier  * (such as {@code
  org.mypackage}), it will be resolved from the classpath root.  * Note
  that the JDK's standard ResourceBundle treats dots as package
  separators:  * This means that "test.theme" is effectively equivalent
  to "test/theme".

Body:
I am trying to use resource bundles with Spring's Message Source. Here is the way I am doing it:

@Component
public class MessageResolver implements MessageSourceAware {

    @Autowired
    private MessageSource messageSource;

    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    public String getMessage(){
        return messageSource.getMessage("user.welcome", new Object[]{"Rama"} , Locale.US);
    }

}

And here is my folder structure:

messages_en_US.properties contains just one line:

user.welcome=Welcome {0}

Here is the xml configuration used:

<bean name="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename">
        <value>resourcebundles/messages</value>
    </property>
</bean>

Here is the error I am getting:

WARNING: ResourceBundle [resourcebundles/messages] not found for MessageSource: Can't find bundle for base name resourcebundles/messages, locale en_US
Exception in thread "main" org.springframework.context.NoSuchMessageException: No message found under code 'user.welcome' for locale 'en_US'.

But if I move my resource bundle to directly under the resources folder, it is working fine. In this case, here is the xml configuration I am using:

<bean name="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
    <value>messages</value>
</property>

Is is that if I have to use ResourceBundleMessageSource, I should put my resource bundles directly under the resources? If i have to keep it in specified folder only, is there any other way to get this one work?

Thanks!

Body:
Is is that if I have to use ResourceBundleMessageSource, I should put
  my resource bundles directly under the resources? If i have to keep it
  in specified folder only, is there any other way to get this one work?

You can define your messages in your own package, it does not need to be located in the resources folder.

Using Spring 5.2.2.RELEASE versioned components, this is the way I managed to make it work:

The qualified name of the file would be:

/tutproject/src/com/tutproject/app/messages/messages.properties

The bean is defined like this in the my Spring Bean Configuration File (XML):

<bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename"
    value="/com/tutproject/app/messages/messages">
</property>
</bean>

The Java build path includes tutproject/src , this is the part of the location omitted in the XML definition.

Some additional useful information from the ResourceBundleMessageSource class:

The basenames follow {@link java.util.ResourceBundle}
  conventions: essentially,  * a fully-qualified classpath location. If
  it doesn't contain a package qualifier  * (such as {@code
  org.mypackage}), it will be resolved from the classpath root.  * Note
  that the JDK's standard ResourceBundle treats dots as package
  separators:  * This means that "test.theme" is effectively equivalent
  to "test/theme".


问:
What does it mean to pre-increment $#array?
I've come across the following line of code.  It has issues:

it is intended to do the same as push

it ought to have used push

it's hard to read, understand

I've since changed it to use push

it does something I thought was illegal, but clearly isn't

here it is:

```<code>$array [++$#array] = 'data';
</code>```

My question is: what does it mean to pre-increment $#array?  I always considered $#array to be an attribute of an array, and not writable.

答:
First of all, that's foul.

That said, I'm also surprised that it works. I would have guessed that ++$#array would have gotten the "Can't modify constant" error you get when trying to increment a number. (Not that I ever accidentally do that, of course.) But, I guess that's exactly where we were wrong: $#array isn't a constant (a number); it's a variable expression. As such you can mess with it. Consider the following:

```<code>my @array = qw/1 2 3/;

++$#array;
$array[$#array] = qw/4/;

print "@array\n"
</code>```

And even, for extra fun, this:

```<code>my @array = qw/1 2 3/;

$#array += 5;

foreach my $wtf (@array) {
  if (defined $wtf) {
    print "$wtf\n";
  }
  else {
    print "undef\n";
  }
}
</code>```

And, yeah, the Perl Cookbook is happy to mess with $#array to grow or truncate arrays (Chapter 4, recipe 3). I still find it ugly, but maybe that's just a lingering "but it's a number" prejudice.

OwnerDisplayName: Paul Beckingham

ContentLicense: CC BY-SA 2.5

Body:
I've come across the following line of code.  It has issues:

it is intended to do the same as push

it ought to have used push

it's hard to read, understand

I've since changed it to use push

it does something I thought was illegal, but clearly isn't

here it is:

$array [++$#array] = 'data';

My question is: what does it mean to pre-increment $#array?  I always considered $#array to be an attribute of an array, and not writable.

LastEditorDisplayName: brian d foy

Body:
First of all, that's foul.

That said, I'm also surprised that it works. I would have guessed that ++$#array would have gotten the "Can't modify constant" error you get when trying to increment a number. (Not that I ever accidentally do that, of course.) But, I guess that's exactly where we were wrong: $#array isn't a constant (a number); it's a variable expression. As such you can mess with it. Consider the following:

my @array = qw/1 2 3/;

++$#array;
$array[$#array] = qw/4/;

print "@array\n"

And even, for extra fun, this:

my @array = qw/1 2 3/;

$#array += 5;

foreach my $wtf (@array) {
  if (defined $wtf) {
    print "$wtf\n";
  }
  else {
    print "undef\n";
  }
}

And, yeah, the Perl Cookbook is happy to mess with $#array to grow or truncate arrays (Chapter 4, recipe 3). I still find it ugly, but maybe that's just a lingering "but it's a number" prejudice.

OwnerDisplayName: Telemachus


问:
Word Cloud making error in Python: string indices must be integers
I'm trying to make a Word Cloud out of a txt file with this code:

```<code>import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from wordcloud import WordCloud, STOPWORDS
from IPython.display import Image as im

file = open("T.txt", encoding='utf-8')
FR = file.read()

raw_file = []

for line in FR:
    raw_file.append(line['text'])

words = raw_file.split(" ")
words = [w for w in words if len(w) > 2]
words = [w.lower() for w in words]
words = [w for w in words if w not in STOPWORDS]

word_list = (words)
word_counter = {}
for word in word_list:
     if word in word_counter:
         word_counter[word] += 1
     else:
         word_counter[word] = 1

popular_words = sorted(word_counter, key = word_counter.get, reverse = True)

topp = popular_words

topp.remove('https')

mask = np.array(Image.open('/Users/x/Downloads/B.png'))

wc = WordCloud(background_color="black", max_words=2000, mask=mask)
clean_string = ','.join(topp)
wc.generate(clean_string)

plt.imshow(wc, interpolation='bilinear')
plt.title("Title", size=40)
plt.axis("off")
plt.show()
</code>```

As in the title, it gives me Error: string indices must be integers on raw_file.append(line['text']).
I tried a few different methods to make it work but it didn't, so I'm asking here for help.

Thanks in advance.

答:
You are doing a few unnecessary things, without which you can make your code a bit simpler. The actual problem is how you are indexing line['text'], but there is also a problem with how you then turn raw_file into words.

You don't actually need FR = file.read() (of file.readlines()). for line in file: does the same thing for you.

Appending the lines then to raw_file and then using .split(" ") on that, will try to split on a list of lines, giving you your next error. You can just split the line directly and add that to your list of words.

You also don't need to change words into word_list or popular_words into topp. IMHO this only just creates more variables and makes the code less readable.

```<code>import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from wordcloud import WordCloud, STOPWORDS
from IPython.display import Image as im

file = open("T.txt", encoding='utf-8')

words = []

for line in file:
    words += line.split()

words = [w for w in words if len(w) > 2]
words = [w.lower() for w in words]
words = [w for w in words if w not in STOPWORDS]

word_counter = {}
for word in words:
     if word in word_counter:
         word_counter[word] += 1
     else:
         word_counter[word] = 1

popular_words = sorted(word_counter, key = word_counter.get, reverse = True)

popular_words.remove('https')

mask = np.array(Image.open('/Users/x/Downloads/B.png'))

wc = WordCloud(background_color="black", max_words=2000, mask=mask)
clean_string = ','.join(popular_words)
wc.generate(clean_string)

plt.imshow(wc, interpolation='bilinear')
plt.title("Title", size=40)
plt.axis("off")
plt.show()
</code>```

Body:
I'm trying to make a Word Cloud out of a txt file with this code:

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from wordcloud import WordCloud, STOPWORDS
from IPython.display import Image as im

file = open("T.txt", encoding='utf-8')
FR = file.read()

raw_file = []

for line in FR:
    raw_file.append(line['text'])

words = raw_file.split(" ")
words = [w for w in words if len(w) > 2]
words = [w.lower() for w in words]
words = [w for w in words if w not in STOPWORDS]

word_list = (words)
word_counter = {}
for word in word_list:
     if word in word_counter:
         word_counter[word] += 1
     else:
         word_counter[word] = 1

popular_words = sorted(word_counter, key = word_counter.get, reverse = True)

topp = popular_words

topp.remove('https')

mask = np.array(Image.open('/Users/x/Downloads/B.png'))

wc = WordCloud(background_color="black", max_words=2000, mask=mask)
clean_string = ','.join(topp)
wc.generate(clean_string)

plt.imshow(wc, interpolation='bilinear')
plt.title("Title", size=40)
plt.axis("off")
plt.show()

As in the title, it gives me Error: string indices must be integers on raw_file.append(line['text']).
I tried a few different methods to make it work but it didn't, so I'm asking here for help.

Thanks in advance.

Body:
You are doing a few unnecessary things, without which you can make your code a bit simpler. The actual problem is how you are indexing line['text'], but there is also a problem with how you then turn raw_file into words.

You don't actually need FR = file.read() (of file.readlines()). for line in file: does the same thing for you.

Appending the lines then to raw_file and then using .split(" ") on that, will try to split on a list of lines, giving you your next error. You can just split the line directly and add that to your list of words.

You also don't need to change words into word_list or popular_words into topp. IMHO this only just creates more variables and makes the code less readable.

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from wordcloud import WordCloud, STOPWORDS
from IPython.display import Image as im

file = open("T.txt", encoding='utf-8')

words = []

for line in file:
    words += line.split()

words = [w for w in words if len(w) > 2]
words = [w.lower() for w in words]
words = [w for w in words if w not in STOPWORDS]

word_counter = {}
for word in words:
     if word in word_counter:
         word_counter[word] += 1
     else:
         word_counter[word] = 1

popular_words = sorted(word_counter, key = word_counter.get, reverse = True)

popular_words.remove('https')

mask = np.array(Image.open('/Users/x/Downloads/B.png'))

wc = WordCloud(background_color="black", max_words=2000, mask=mask)
clean_string = ','.join(popular_words)
wc.generate(clean_string)

plt.imshow(wc, interpolation='bilinear')
plt.title("Title", size=40)
plt.axis("off")
plt.show()


问:
Multi-Line link with image
I have not developed web pages/apps in over 15 years and a lot has changed.  I am working in Visual Studio 2019, ASP.NET, and razor pages...

I'd like to create a set of links that are have a border and wrap if the screen is not wide enough.  I thought this would be something simple, but I cannot figure it out.  I've spent all week on this and perhaps I am not searching for the correct terms or I don't really know what I am looking for.

I can get close with a table, something like (1 row, multiple cells):

```<code><td style="
                width:128px;
                height:80px;
                border:2px solid black;
                font-size:xx-small;
                background-repeat:no-repeat;
                background-size:64px;
                background-image:url(/Icons/@item.Icon);
            ">
    <table>
        <tr><td style="text-align:right; width:120px"><b>A1: @item.Test1</b></td></tr>
        <tr><td style="text-align:right;"><b>A2: @item.Test2</b></td></tr>
        <tr><td style="text-align:right;"><b>@item.Note1</b>  <img src="/Icons/@item.State1a" height="8" width="8" /> <img src="/Icons/@item.State2a" height="8" width="8" /></td></tr>
        <tr><td style="text-align:right;"><b>@item.Note2</b>  <img src="/Icons/@item.State1b" height="8" width="8" /> <img src="/Icons/@item.State2b" height="8" width="8" /></td></tr>
    </table>
    <a href="/Details?item=@item.Id">
        @item.Description
    </a>
</td>
</code>```

There are 2 issues with the current approach...

It does not wrap when the screen width is too small

Only the item description is clickable

I put the image in the background because some of the values in the text (item.Test1, item.Test2), push the text to the left overlaying the image.

Any suggestions?

Perhaps point me to come code to dynamically generate an image of what I am looking for (I'd prefer a CSS solution, but creating an image would be acceptable).

答:
The answer I finally came up with was to drop the table, wrap the links (buttons) in a paragraph, replace the td tag with button give it an onclick='location', and keep the same style and sub-table layout.

Now the buttons wrap for different screen sizes and have the same look and feel as the old ones that were wrapped in a table.

Title: Multi-Line link with image

Body:
I have not developed web pages/apps in over 15 years and a lot has changed.  I am working in Visual Studio 2019, ASP.NET, and razor pages...

I'd like to create a set of links that are have a border and wrap if the screen is not wide enough.  I thought this would be something simple, but I cannot figure it out.  I've spent all week on this and perhaps I am not searching for the correct terms or I don't really know what I am looking for.

I can get close with a table, something like (1 row, multiple cells):

A1: @item.Test1

A2: @item.Test2

@item.Note1

@item.Note2

        @item.Description

There are 2 issues with the current approach...

It does not wrap when the screen width is too small

Only the item description is clickable

I put the image in the background because some of the values in the text (item.Test1, item.Test2), push the text to the left overlaying the image.

Any suggestions?

Perhaps point me to come code to dynamically generate an image of what I am looking for (I'd prefer a CSS solution, but creating an image would be acceptable).


问:
React - toggle class: useState hook form several button
I have some buttons and I'm trying to add active class for clicked button. But when I click one of the buttons, all buttons are getting active class.

```<code>const { useState } = React;
const { render } = ReactDOM;
const node = document.getElementById("root");

const Button = ({ message }) => {
  const [condition, setCondition] = useState(false);
  return (
    <div>
    {
    Object.keys(res).map((data) => (
    <Button className={condition ? "button toggled" : "button"} onClick=.
     {() => {
      setCondition(!condition)}
     }}
     ))
      }
    </div>
  );
   //Updated
   Object.keys(res).map((data) => (
    <Button className={condition ? "button toggled" : "button"} onClick=.
     {() => {
      setCondition(condition === "off" ? "on" : "off")}
     }}
     ))
      }
    </div>
  ); //This can be modified to work for button clicked. Because active class is added to all buttons, if one of them is clicked
};
render(<Button message="Click me if you dare!" />, node);
</code>```

This is working if I click the first button, but if I click again the same button, this active class should be removed

答:
Here is a very naive solution, but it will help you understand the problem.

If you're on a real project, I suggest you to use an existing library (that can be found by searching react toggle button group)

```<code>import React, {useState} from "react";

const defaultButtons = [
    {id: 1},
    {id: 2},
    {id: 3},
    {id: 4}
];

export default function App() {
    const [toggledButtonId, setToggledButtonId] = useState(null);

    function toggleButton(button) {
        setToggledButtonId(button.id);
    }

    return (
        <div>
            {defaultButtons.map(button => {
                const isToggled = button.id === toggledButtonId;
                return (
                    <button
                        key={button.id}
                        className={isToggled ? "toggledButtonId toggled" : "toggledButtonId"}
                        onClick={() => toggleButton(button)}>
                        {String(isToggled)}
                    </button>
                )
            })}
        </div>
    )
}
</code>```

Body:
I have some buttons and I'm trying to add active class for clicked button. But when I click one of the buttons, all buttons are getting active class.

const { useState } = React;
const { render } = ReactDOM;
const node = document.getElementById("root");

const Button = ({ message }) => {
  const [condition, setCondition] = useState(false);
  return (

    {
    Object.keys(res).map((data) => (
    <Button className={condition ? "button toggled" : "button"} onClick=.
     {() => {
      setCondition(!condition)}
     }}
     ))
      }

  );
   //Updated
   Object.keys(res).map((data) => (
    <Button className={condition ? "button toggled" : "button"} onClick=.
     {() => {
      setCondition(condition === "off" ? "on" : "off")}
     }}
     ))
      }

  ); //This can be modified to work for button clicked. Because active class is added to all buttons, if one of them is clicked
};
render(<Button message="Click me if you dare!" />, node);

This is working if I click the first button, but if I click again the same button, this active class should be removed

Body:
Here is a very naive solution, but it will help you understand the problem.

If you're on a real project, I suggest you to use an existing library (that can be found by searching react toggle button group)

import React, {useState} from "react";

const defaultButtons = [
    {id: 1},
    {id: 2},
    {id: 3},
    {id: 4}
];

export default function App() {
    const [toggledButtonId, setToggledButtonId] = useState(null);

    function toggleButton(button) {
        setToggledButtonId(button.id);
    }

    return (
        <div>
            {defaultButtons.map(button => {
                const isToggled = button.id === toggledButtonId;
                return (
                    <button
                        key={button.id}
                        className={isToggled ? "toggledButtonId toggled" : "toggledButtonId"}
                        onClick={() => toggleButton(button)}>
                        {String(isToggled)}
                    </button>
                )
            })}
        </div>
    )
}


问:
Unable to connect to Kafka from outside application
I have two docker machines  and I want to create a kafka cluster inside docker swarm. My docker-compose.yml looks like this:

```<code>version: '3.2'
services:
  zookeeper:
    image: wurstmeister/zookeeper
    ports:
      - "2181:2181"
  kafka:
    image: wurstmeister/kafka:latest
    ports:
      - "9092:9092"
      - "29092:29092"
    environment:
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_LISTENERS: PLAINTEXT://:9092,PLAINTEXT_HOST://:29092
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092
</code>```

I followed this question: Unable to connect to Kafka run in container from Spring Boot app run outside container and I am trying to access kafka from outside using localhost:29092.

I have already create the topic mytesttopic inside kafka. The below python code:

```<code>from kafka import KafkaConsumer, SimpleProducer, TopicPartition, KafkaClient

def consume_from_topic():
    try:
        consumer = KafkaConsumer('mytesttopic',
                                 group_id= None,
                                 bootstrap_servers=['localhost:29092'],
                                 auto_offset_reset='earliest')

        for message in consumer:
            #consumer.commit()
            print ("%s:%d:%d: key=%s value=%s" % (message.topic, message.partition,
                                                  message.offset, message.key,
                                                  message.value))
    except Exception as e:
        print(e)
        pass

if __name__ == '__main__':
    consume_from_topic()
</code>```

returns:

NoBrokersAvailable

Does anyone know what I am missing here?

答:
Your listeners are the exact same.

You need to set PLAINTEXT_HOST://0.0.0.0:29092 to bind the listener to all interfaces

Body:
I have two docker machines  and I want to create a kafka cluster inside docker swarm. My docker-compose.yml looks like this:

version: '3.2'
services:
  zookeeper:
    image: wurstmeister/zookeeper
    ports:
      - "2181:2181"
  kafka:
    image: wurstmeister/kafka:latest
    ports:
      - "9092:9092"
      - "29092:29092"
    environment:
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_LISTENERS: PLAINTEXT://:9092,PLAINTEXT_HOST://:29092
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092

I followed this question: Unable to connect to Kafka run in container from Spring Boot app run outside container and I am trying to access kafka from outside using localhost:29092.

I have already create the topic mytesttopic inside kafka. The below python code:

from kafka import KafkaConsumer, SimpleProducer, TopicPartition, KafkaClient

def consume_from_topic():
    try:
        consumer = KafkaConsumer('mytesttopic',
                                 group_id= None,
                                 bootstrap_servers=['localhost:29092'],
                                 auto_offset_reset='earliest')

        for message in consumer:
            #consumer.commit()
            print ("%s:%d:%d: key=%s value=%s" % (message.topic, message.partition,
                                                  message.offset, message.key,
                                                  message.value))
    except Exception as e:
        print(e)
        pass

if __name__ == '__main__':
    consume_from_topic()

returns:

NoBrokersAvailable

Does anyone know what I am missing here?


问:
Print option for each item in array
I have an array and for each item in the array, I'm trying to add in a new <option>.

To do so, I've tried the following:

```<code> array.forEach(function(arr) {
   console.log(array);
   $(".filterSection .department").append('<option value="'+array+'">'+array+'</option>');
 });
</code>```

However, the option is just printing with all the array values in the <option>. It creates new option tags, but their value and text is all the items in the array.

Full demo:

var array = ["Value 1", "Value 2", "Value 3"];

array.forEach(function(arr) {
  console.log(array);
  $(".department").append('<option value="' + array + '">' + array + '</option>');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select class="department" name="department" id="department"></select></code>```

Where am I going wrong?

答:
Why don't you do it like this:

```<code>var options = array.map(function(arr) {
  return '<option value="' + arr + '">' + arr + '</option>'
});

$(".department").html(options.join(''))
</code>```

This method has performance benefits because accessing the DOM is expensive, more if you access it in every iteration of a loop

Title: Print option for each item in array

Body:
I have an array and for each item in the array, I'm trying to add in a new <option>.

To do so, I've tried the following:

 array.forEach(function(arr) {
   console.log(array);
   $(".filterSection .department").append('<option value="'+array+'">'+array+'</option>');
 });

However, the option is just printing with all the array values in the <option>. It creates new option tags, but their value and text is all the items in the array.

Full demo:

var array = ["Value 1", "Value 2", "Value 3"];

array.forEach(function(arr) {
  console.log(array);
  $(".department").append('<option value="' + array + '">' + array + '</option>');
});

<select class="department" name="department" id="department"></select>

Where am I going wrong?

Body:
Why don't you do it like this:

var options = array.map(function(arr) {
  return '<option value="' + arr + '">' + arr + '</option>'
});

$(".department").html(options.join(''))

This method has performance benefits because accessing the DOM is expensive, more if you access it in every iteration of a loop


问:
Merge Pandas Dataframe based on boolean function
I am looking for an efficient way to merge two pandas data frames based on a function that takes as input columns from both data frames and returns True or False. E.g. Assume I have the following "tables":

```<code>import pandas as pd

df_1 = pd.DataFrame(data=[1, 2, 3])
df_2 = pd.DataFrame(data=[4, 5, 6])

def validation(a, b):
    return ((a + b) % 2) == 0
</code>```

I would like to join df1 and df2 on each row where the sum of the first column is an even number. The resulting table would be

```<code>       1 5
df_3 = 2 4
       2 6
       3 5
</code>```

Please think of it as a general problem not as a task to return just df_3. The solution should accept any function that validates a combination of columns and return True or False.

THX Lazloo

答:
This is a basic solution but not very efficient if you are working on large dataframes </p>

```<code>df_1.index *= 0
df_2.index *= 0
df = df_1.join(df_2, lsuffix='_2')
df = df[df.sum(axis=1) % 2 == 0]
</code>```

<p>Edit,
here is a better solution </p>

```<code>df_1.index = df_1.iloc[:,0] % 2
df_2.index = df_2.iloc[:,0] % 2
df = df_1.join(df_2, lsuffix='_2')
</code>```

Body:
I am looking for an efficient way to merge two pandas data frames based on a function that takes as input columns from both data frames and returns True or False. E.g. Assume I have the following "tables":

import pandas as pd

df_1 = pd.DataFrame(data=[1, 2, 3])
df_2 = pd.DataFrame(data=[4, 5, 6])

def validation(a, b):
    return ((a + b) % 2) == 0

I would like to join df1 and df2 on each row where the sum of the first column is an even number. The resulting table would be

       1 5
df_3 = 2 4
       2 6
       3 5

Please think of it as a general problem not as a task to return just df_3. The solution should accept any function that validates a combination of columns and return True or False.

THX Lazloo

Body:
This is a basic solution but not very efficient if you are working on large dataframes

df_1.index *= 0
df_2.index *= 0
df = df_1.join(df_2, lsuffix='_2')
df = df[df.sum(axis=1) % 2 == 0]

Edit,
here is a better solution

df_1.index = df_1.iloc[:,0] % 2
df_2.index = df_2.iloc[:,0] % 2
df = df_1.join(df_2, lsuffix='_2')


问:
OnCreate is called multiply when app is started from Play Store App first and then from home screen
It occurred to me that under some circumstances our app seems to be restarted from scratch after being backgrounded. I managed to track to issue down to MainActivity.OnCreate being called multiply under the following circumstances

App is installed from APK and then ran from the installer, after backgrounding the app and starting it from the home screen it's reset to scratch

This behavior persists until the app is killed and then restarted from the home screen

App is run from Google Play app, after backgrounding the app and starting it from the home screen it's reset to scratch

If the app is backgrounded and then started from Play Store it's started correctly

App is run from home screen, after backgrounding the app and starting it from Google Play it's reset to scratch

When the app is foregrounded from the same launcher it has been started initially, OnCreate is not called again. There is at least one question reporting a similar behavior, unfortunately there is no answer providing a solution for the behavior.

When MainActivity.OnCreate is called, the instance of MainActivity seems to be a different instance than the initial one, since private members that are set in OnCreate are null when I'm trying to log them, anyway, the application context does not seem to be recreated from scratch, because AppCenter seems to be initialized right away on the second run, Xamarin.Forms starts up way quicker and static variables keep their values.

Is there any way to prevent this behavior and just keep a single instance of MainActivity active?

答:
Congratulations! You've been bit by a long-standing, nasty Android bug which has been around since the dawn of time and is still broken, even though countless issues have been opened about it and the behaviour is reproducible and well-documented.

See the following:

https://issuetracker.google.com/issues/36907463

https://issuetracker.google.com/issues/36941942

https://issuetracker.google.com/issues/64108432

Re-launch of Activity on Home button, but...only the first time

App restarts rather than resumes

In September 2019, one of these issues was marked "fixed" with this comment:

Thanks for reporting this issue. The issue has been fixed and it will
  become available in a future Android release.

So hopefully we will no longer be seeing this in Android Z ;-)

There is a workaround documented in my answer to
Re-launch of Activity on Home button, but...only the first time


问:
Using javascript variables from another function

Possible Duplicate:

  How to know variables from different…“namespaces” ?

I have a webphone integrated into our webpage, and when a call comes in, a javascript function records the caller's number (e.g. 01234 123456) and saves it as the variable inCallingNum.

I need to use this variable in a different function which sends information to a php page and stores it on our database.

Is it possible to access the javascript variable from another function at all, and if not what is the easiest way to get around it?

Edit: This is the code I have, which currently captures the inCallingNum variable

```<code>    function webphonetojs(varr)
        {
            var eventNotify = '' + varr;
            //alert("eventNotify = "+eventNotify);
            displaystatus('WEBPHONE SAY: '+eventNotify);

            initcheck();
            var chanelStat = applethandle.API_GetStatus(1); //  get line status
            var chanelStatus = chanelStat.replace(/\s+/g,'');
            if (chanelStatus == 'Ringing')
            {
                var incomming = eventNotify.slice(eventNotify.lastIndexOf(",")+1, eventNotify.length);
                if (incomming == '2')
                {
                    var inCallingNum = eventNotify.split(",", 4); inCallingNum = inCallingNum.toString();
                    inCallingNum = inCallingNum.slice(inCallingNum.lastIndexOf(",")+1, inCallingNum.length);
                    displaystatus('CALLER IS: '+inCallingNum);

}
}
}
</code>```

答: You access the variable if you declare it in global scope and just use it in both funstions.</p>

Body:
Possible Duplicate:

  How to know variables from different…“namespaces” ?

I have a webphone integrated into our webpage, and when a call comes in, a javascript function records the caller's number (e.g. 01234 123456) and saves it as the variable inCallingNum.

I need to use this variable in a different function which sends information to a php page and stores it on our database.

Is it possible to access the javascript variable from another function at all, and if not what is the easiest way to get around it?

Edit: This is the code I have, which currently captures the inCallingNum variable

    function webphonetojs(varr)
        {
            var eventNotify = '' + varr;
            //alert("eventNotify = "+eventNotify);
            displaystatus('WEBPHONE SAY: '+eventNotify);

            initcheck();
            var chanelStat = applethandle.API_GetStatus(1); //  get line status
            var chanelStatus = chanelStat.replace(/\s+/g,'');
            if (chanelStatus == 'Ringing')
            {
                var incomming = eventNotify.slice(eventNotify.lastIndexOf(",")+1, eventNotify.length);
                if (incomming == '2')
                {
                    var inCallingNum = eventNotify.split(",", 4); inCallingNum = inCallingNum.toString();
                    inCallingNum = inCallingNum.slice(inCallingNum.lastIndexOf(",")+1, inCallingNum.length);
                    displaystatus('CALLER IS: '+inCallingNum);

}
}
}


问:
Theme crocal - link menu problem : still redirect to homepage
I try to search a solution but I have no answer. My links menu don't work at all. When I click on it, they redirect always to the homepage. Only when I'm logged as admin they works.

I tried to deactivate all my plugins, recreate a menu from scratch, another from the administration and change the permalinks but the problem still in. I took a look on .htaccess but it's the basic one, so it's not this.

Here the website : primmoconseil.fr .

Please help me for this :)

答:
Thank you for your answers! :)

To answer you mw509, I know how to create a WordPress Menu and I've already tried to recreate one and another from scratch.
I just found few minutes ago, it's because of my theme used. When I changed, it's work. But I have no choice to use this theme (my client want this one absolutely).
So how can I do...?

Here my permalinks configuration :https://primmoconseil.fr/%postname%/%post_id%/.

And here my htaccess page :

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
</code>```

Thank you again to help me :)

Body:
Thank you for your answers! :)

To answer you mw509, I know how to create a WordPress Menu and I've already tried to recreate one and another from scratch.
I just found few minutes ago, it's because of my theme used. When I changed, it's work. But I have no choice to use this theme (my client want this one absolutely).
So how can I do...?

Here my permalinks configuration :https://primmoconseil.fr/%postname%/%post_id%/.

And here my htaccess page :

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Thank you again to help me :)


问:
Correctly upload an image to database. Laravel vue.js
I'm trying to upload an image to the database but no matter what I try I either get this error

Call to a member function getClientOriginalExtension() on null

or it says it saved correctly but it doesn't save anything

The following code is in the vue.js file in the submit function for the form where this the image is being uploaded. This is what I've tried to send the file to the controller

This gives me the error above

```<code>if (this.form.file && this.form.imageUrl) {
    this.form.file = this.form.imageUrl;
} else {
}

var data = Converter.objectToFormData(this.form);

this.$refs.form.validate((valid) => {
    if (valid) {
        this.loading = true;
        if (!this.form.id) {
            //send code
        } else {
            //send updated
        }
    }

</code>```

This also gives me the error above

```<code>let data = Object.assign({}, this.form);

this.$refs.form.validate((valid) => {
    if (valid) {
        this.loading = true;
        if (!this.form.id) {
            //send code
        } else {
            //send updated
        }
    }
</code>```

This doesn't give me any errors, but nothing gets saved

```<code>var data = new FormData();
data.append('question', this.form.question);
data.append('instruction', this.form.instruction);
data.append('survey_section_id', this.form.survey_section_id);
data.append('response_type_id', this.form.response_type_id);
data.append('questionOptions', this.form.questionOptions);
data.append('rank', this.form.rank);
data.append('num', this.form.num);
data.append('show_text', this.form.show_text);
data.append('file', this.form.file);

this.$refs.form.validate((valid) => {
    if (valid) {
        this.loading = true;
        if (!this.form.id) {
            //send code
        } else {
            //send updated
        }
    }
</code>```

This is the code in the controller where the error gets triggered

```<code>$destino = 'img/questions';
$image = $request->has('file');
if ($image) {
    $imageFile = $request->file('file');
    $filename = Uuid::generate(4)->string . '.' . $imageFile->getClientOriginalExtension();
    $imageFile->move($destino, $filename);
    $preg->image = $destino . '/' . $filename;
}
</code>```

if I dd($imageFile) it always returns null or false, my guess is that the file isn't being sent as a file but I'm not sure what I'm doing wrong or why this is happening, the $image returns true so it does go into that if statement.

答:
Assuming you have put enctype="multipart/form-data" on your form, there was an error in a laravel 6  that forced me to do this before getting the image:

```<code>$destino = 'img/questions';
$image = $request->has('file');
if ($image) {
    $size = $request->file('file')->getSize();
    $imageFile = $request->file('file');
    $filename = Uuid::generate(4)->string . '.' . $imageFile->getClientOriginalExtension();
    $imageFile->move($destino, $filename);
    $preg->image = $destino . '/' . $filename;
}
</code>```

I'm not sure if it gave me the same error, but the file was always null if you didn't get the size before,

Hope it helps!

Body:
I'm trying to upload an image to the database but no matter what I try I either get this error

Call to a member function getClientOriginalExtension() on null

or it says it saved correctly but it doesn't save anything

The following code is in the vue.js file in the submit function for the form where this the image is being uploaded. This is what I've tried to send the file to the controller

This gives me the error above

if (this.form.file && this.form.imageUrl) {
    this.form.file = this.form.imageUrl;
} else {
}

var data = Converter.objectToFormData(this.form);

this.$refs.form.validate((valid) => {
    if (valid) {
        this.loading = true;
        if (!this.form.id) {
            //send code
        } else {
            //send updated
        }
    }

This also gives me the error above

let data = Object.assign({}, this.form);

this.$refs.form.validate((valid) => {
    if (valid) {
        this.loading = true;
        if (!this.form.id) {
            //send code
        } else {
            //send updated
        }
    }

This doesn't give me any errors, but nothing gets saved

var data = new FormData();
data.append('question', this.form.question);
data.append('instruction', this.form.instruction);
data.append('survey_section_id', this.form.survey_section_id);
data.append('response_type_id', this.form.response_type_id);
data.append('questionOptions', this.form.questionOptions);
data.append('rank', this.form.rank);
data.append('num', this.form.num);
data.append('show_text', this.form.show_text);
data.append('file', this.form.file);

this.$refs.form.validate((valid) => {
    if (valid) {
        this.loading = true;
        if (!this.form.id) {
            //send code
        } else {
            //send updated
        }
    }

This is the code in the controller where the error gets triggered

$destino = 'img/questions';
$image = $request->has('file');
if ($image) {
    $imageFile = $request->file('file');
    $filename = Uuid::generate(4)->string . '.' . $imageFile->getClientOriginalExtension();
    $imageFile->move($destino, $filename);
    $preg->image = $destino . '/' . $filename;
}

if I dd($imageFile) it always returns null or false, my guess is that the file isn't being sent as a file but I'm not sure what I'm doing wrong or why this is happening, the $image returns true so it does go into that if statement.

Body:
Assuming you have put enctype="multipart/form-data" on your form, there was an error in a laravel 6  that forced me to do this before getting the image:

$destino = 'img/questions';
$image = $request->has('file');
if ($image) {
    $size = $request->file('file')->getSize();
    $imageFile = $request->file('file');
    $filename = Uuid::generate(4)->string . '.' . $imageFile->getClientOriginalExtension();
    $imageFile->move($destino, $filename);
    $preg->image = $destino . '/' . $filename;
}

I'm not sure if it gave me the same error, but the file was always null if you didn't get the size before,

Hope it helps!


问:
how to traverse inside a xml node and check for an attribute value?
I have this xml, i took it in xml a GPathResult object how can I get Microsoft(R) Windows(R) Server 2003 Enterprise x64 Edition based on checking with the field value as  OS Name using groovy xml slurping

```<code><client productname="abp">
<machine>
  <env>
   <variable name='ALLUSERSPROFILE' value='C:\Documents and Settings\All Users' />
   <variable name='APPDATA' value='C:\Documents and Settings\Administrator\Application Data' />
   <variable name='OS' value='Windows_NT' />
   <variable name='COMPUTERNAME' value='AbhishekPC' />
 </env>
 <osinfo>
    <osinfo field='OS Name' information='Microsoft(R) Windows(R) Server 2003 Enterprise x64 Edition' />
    <osinfo field='OS Version' information='5.2.3790 Service Pack 2 Build 3790' />
    <osinfo field='OS Manufacturer' information='Microsoft Corporation' />
    <osinfo field='OS Configuration' information='Standalone Server' />
    <osinfo field='OS Build Type' information='Multiprocessor Free' />
 </osinfo>
</machine>
</client>
</code>```

Here is the parsing code

```<code>def file = new File(filepath)
def gpathResult = new XmlSlurper().parse(file)

summary.productname=gpathResult.@product.text()
            log.info gpathResult.system.osinfo.osinfo.@field.text()

            System.out.println("HI 1"+gpathResult.machine.environment.variable.@name.text());
            System.out.println("HI 2"+gpathResult.machine.osinfo.osinfo.@field.text());

            if(gpathResult.machine.environment.variable.@name.text().equals("OS"))
            {
                summary.osname=gpathResult.machine.environment.variable.@value.text()

            }
            if(gpathResult.machine.environment.variable.@name.text().equals("COMPUTERNAME"))
            {
                summary.hostname=gpathResult.machine.environment.variable.@value.text()
            }
</code>```

Here HI 1 prints all the environments name attribut values but HI 2 only prints HI 2

here is the snapshot

here is what solved after i traversed

```<code>      def    vals1=gpathResult.machine.env.variable.findAll{it.@name=='COMPUTERNAME'}.@value.text()
            println vals1
            csmSummary.hostname=vals1
            def vals2=gpathResult.machine.env.variable.findAll{it.@name=='OS'}.@value.text()
            println vals2
            csmSummary.osname=vals2
</code>```

答:
Strange... if I do this (with Groovy 1.8)

```<code>def gpathResult = new XmlSlurper().parseText( $/<client productname="abp">
<machine>
  <env>
   <variable name='ALLUSERSPROFILE' value='C:\Documents and Settings\All Users' />
   <variable name='APPDATA' value='C:\Documents and Settings\Administrator\Application Data' />
   <variable name='OS' value='Windows_NT' />
   <variable name='COMPUTERNAME' value='AbhishekPC' />
 </env>
 <osinfo>
    <osinfo field='OS Name' information='Microsoft(R) Windows(R) Server 2003 Enterprise x64 Edition' />
    <osinfo field='OS Version' information='5.2.3790 Service Pack 2 Build 3790' />
    <osinfo field='OS Manufacturer' information='Microsoft Corporation' />
    <osinfo field='OS Configuration' information='Standalone Server' />
    <osinfo field='OS Build Type' information='Multiprocessor Free' />
 </osinfo>
</machine>
</client>/$ )

println "HI 1 ${gpathResult.machine.env.variable.@name*.text()}"
println "HI 2 ${gpathResult.machine.osinfo.osinfo.@field*.text()}"
</code>```

it prints out:

```<code>HI 1 [ALLUSERSPROFILE, APPDATA, OS, COMPUTERNAME]
HI 2 [OS Name, OS Version, OS Manufacturer, OS Configuration, OS Build Type]
</code>```

Can you try that code (assuming you are using 1.8, the latest version of Groovy -- if not, you will need to use """ instead of $/ for the string delimiters, and escape the \ chars)

[edit] It's probably just because you are using gpathResult.machine.environment.variable instead of gpathResult.machine.env.variable

to traverse the env nodes, you'd do something like:

```<code>gpathResult.machine.env.variable.each { node ->
  println "${node.@name.text()} contains ${node.@value.text()}"
}
</code>```

Body:
I have this xml, i took it in xml a GPathResult object how can I get Microsoft(R) Windows(R) Server 2003 Enterprise x64 Edition based on checking with the field value as  OS Name using groovy xml slurping

<client productname="abp">
<machine>
  <env>
   <variable name='ALLUSERSPROFILE' value='C:\Documents and Settings\All Users' />
   <variable name='APPDATA' value='C:\Documents and Settings\Administrator\Application Data' />
   <variable name='OS' value='Windows_NT' />
   <variable name='COMPUTERNAME' value='AbhishekPC' />
 </env>
 <osinfo>
    <osinfo field='OS Name' information='Microsoft(R) Windows(R) Server 2003 Enterprise x64 Edition' />
    <osinfo field='OS Version' information='5.2.3790 Service Pack 2 Build 3790' />
    <osinfo field='OS Manufacturer' information='Microsoft Corporation' />
    <osinfo field='OS Configuration' information='Standalone Server' />
    <osinfo field='OS Build Type' information='Multiprocessor Free' />
 </osinfo>
</machine>
</client>

Here is the parsing code

def file = new File(filepath)
def gpathResult = new XmlSlurper().parse(file)

summary.productname=gpathResult.@product.text()
            log.info gpathResult.system.osinfo.osinfo.@field.text()

            System.out.println("HI 1"+gpathResult.machine.environment.variable.@name.text());
            System.out.println("HI 2"+gpathResult.machine.osinfo.osinfo.@field.text());

            if(gpathResult.machine.environment.variable.@name.text().equals("OS"))
            {
                summary.osname=gpathResult.machine.environment.variable.@value.text()

            }
            if(gpathResult.machine.environment.variable.@name.text().equals("COMPUTERNAME"))
            {
                summary.hostname=gpathResult.machine.environment.variable.@value.text()
            }

Here HI 1 prints all the environments name attribut values but HI 2 only prints HI 2

here is the snapshot

here is what solved after i traversed

      def    vals1=gpathResult.machine.env.variable.findAll{it.@name=='COMPUTERNAME'}.@value.text()
            println vals1
            csmSummary.hostname=vals1
            def vals2=gpathResult.machine.env.variable.findAll{it.@name=='OS'}.@value.text()
            println vals2
            csmSummary.osname=vals2

Body:
Strange... if I do this (with Groovy 1.8)

def gpathResult = new XmlSlurper().parseText( $/<client productname="abp">
<machine>
  <env>
   <variable name='ALLUSERSPROFILE' value='C:\Documents and Settings\All Users' />
   <variable name='APPDATA' value='C:\Documents and Settings\Administrator\Application Data' />
   <variable name='OS' value='Windows_NT' />
   <variable name='COMPUTERNAME' value='AbhishekPC' />
 </env>
 <osinfo>
    <osinfo field='OS Name' information='Microsoft(R) Windows(R) Server 2003 Enterprise x64 Edition' />
    <osinfo field='OS Version' information='5.2.3790 Service Pack 2 Build 3790' />
    <osinfo field='OS Manufacturer' information='Microsoft Corporation' />
    <osinfo field='OS Configuration' information='Standalone Server' />
    <osinfo field='OS Build Type' information='Multiprocessor Free' />
 </osinfo>
</machine>
</client>/$ )

println "HI 1 ${gpathResult.machine.env.variable.@name*.text()}"
println "HI 2 ${gpathResult.machine.osinfo.osinfo.@field*.text()}"

it prints out:

HI 1 [ALLUSERSPROFILE, APPDATA, OS, COMPUTERNAME]
HI 2 [OS Name, OS Version, OS Manufacturer, OS Configuration, OS Build Type]

Can you try that code (assuming you are using 1.8, the latest version of Groovy -- if not, you will need to use """ instead of $/ for the string delimiters, and escape the \ chars)

[edit] It's probably just because you are using gpathResult.machine.environment.variable instead of gpathResult.machine.env.variable

to traverse the env nodes, you'd do something like:

gpathResult.machine.env.variable.each { node ->
  println "${node.@name.text()} contains ${node.@value.text()}"
}


答:
I suspect that you want window functions here:

```<code>select distinct id
from (
    select
        t.*,
        sum(total) over(partition by id order by day rows between 2 preceding and current row) sum_total,
        count(*)   over(partition by id order by day rows between 2 preceding and current row) cnt
    from mytable t
) t
where cnt = 3 and sum_total >= 150
</code>```

This gives you the ids that have a total greater than the given threshold over 3 consecutive days - which is how I understood your question.

Title: With Oracle SQL how can I find 3 days where total sum >= 150

Body:
I have a report that needs to list activity where total is >= 150 over 3 consecutive days.

Let's say I've created a temp table foo, to summarize daily totals.

| ID | Day        | Total |
| -- | ---------- | ----- |
| 01 | 2020-01-01 |   10  |
| 01 | 2020-01-02 |   50  |
| 01 | 2020-01-03 |   50  |
| 01 | 2020-01-04 |   50  |
| 01 | 2020-01-05 |   20  |
| 02 | 2020-01-01 |   10  |
| 02 | 2020-01-02 |   10  |
| 02 | 2020-01-03 |   10  |
| 02 | 2020-01-04 |   10  |
| 02 | 2020-01-05 |   10  |

How Would I write SQL to return ID 01, but not 02?

Example Result:

| ID |
| -- |
| 01 |

Body:
I suspect that you want window functions here:

select distinct id
from (
    select
        t.*,
        sum(total) over(partition by id order by day rows between 2 preceding and current row) sum_total,
        count(*)   over(partition by id order by day rows between 2 preceding and current row) cnt
    from mytable t
) t
where cnt = 3 and sum_total >= 150

This gives you the ids that have a total greater than the given threshold over 3 consecutive days - which is how I understood your question.


问:
Get the all GET requests for a time range by the grep from the logs
How can I get all GET requests for the some time range from the log file?
As an example here is the record from log:

```<code>41.201.181.27 - [2019-04-06 18:20:13] "GET /popup.php?choix=2 HTTP/1.1" 200 1692 "http://example.com/popup.php?choix=1" "Mozilla/4.0" "-"
</code>```

I need extract all GET records for the 17th February from the 14:00 to 23:00

答:
I think this answer may help.

To filter for only GET requests, adding .*GET to whatever your regex is should work.

Body:
How can I get all GET requests for the some time range from the log file?
As an example here is the record from log:

41.201.181.27 - [2019-04-06 18:20:13] "GET /popup.php?choix=2 HTTP/1.1" 200 1692 "http://example.com/popup.php?choix=1" "Mozilla/4.0" "-"

I need extract all GET records for the 17th February from the 14:00 to 23:00


问:
Mock exported const arrow functions with Jest
Given the following example with a basic test, I'd expect bar to be returned when sendMessage.message is mocked with Jest. Instead, when called, it returns the original value of "Hello World".

serviceBus.js

export const message = () => {
  return "Hello world";
};

export const foo = () => {
  return message();
};
```

<h3>mockDemo.test.js</h3>

<pre class="lang-js prettyprint-override"><code>import * as sendMessage from "../src/services/serviceBus";

describe("sendMessage", () => {
  sendMessage.message = jest.fn(() => {
    return "bar";
  });

  it(`message should return bar`, async () => {
    expect(sendMessage.message()).toBe("bar");
    expect(sendMessage.foo()).toBe("bar");
  });
});
</code>```

And the results as follows:

$ ./node_modules/.bin/jest ./__tests__/mockDemo.test.js
 FAIL  __tests__/mockDemo.test.js
  MessageReceiver Router
    ✕ message should return bar (9ms)

  ● MessageReceiver Router › message should return bar

    expect(received).toBe(expected) // Object.is equality

    Expected: "bar"
    Received: "Hello world"

       9 |   it(`message should return bar`, async () => {
      10 |     expect(sendMessage.message()).toBe("bar");
    > 11 |     expect(sendMessage.foo()).toBe("bar");
         |                               ^
      12 |   });
      13 | });
      14 |

      at Object.<anonymous> (__tests__/mockDemo.test.js:11:31)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
```

<p>It looks as if <code>sendMessage.foo</code> is calling the bound function once imported of <code>message</code>, which by default returns <code>Hello World</code>.</p>

<p>How would one mock <code>message</code> in this context? </p>

<h3>Update</h3>

<p>Using <code>jest.fn().mockImplementation(() => "bar");</code> results in the same behaviour:</p>

<pre class="lang-js prettyprint-override"><code>describe("MessageReceiver Router", () => {
  //   sendMessage.message.mockImplementation = jest.fn(() => {
  //     return "bar";
  //   });

  sendMessage.message = jest.fn().mockImplementation(() => "bar");

  it(`message should return bar`, async () => {
    expect(sendMessage.message()).toBe("bar");
    expect(sendMessage.foo()).toBe("bar");
  });
});
</code>```

Results:

```<code>$ ./node_modules/.bin/jest ./__tests__/mockDemo.test.js
 FAIL  __tests__/mockDemo.test.js
  MessageReceiver Router
    ✕ message should return bar (10ms)

  ● MessageReceiver Router › message should return bar

    expect(received).toBe(expected) // Object.is equality

    Expected: "bar"
    Received: "Hello world"

      11 |   it(`message should return bar`, async () => {
      12 |     expect(sendMessage.message()).toBe("bar");
    > 13 |     expect(sendMessage.foo()).toBe("bar");
         |                               ^
      14 |   });
      15 | });
      16 |

      at Object.<anonymous> (__tests__/mockDemo.test.js:13:31)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.175s
</code>```

答:
So internal functions called cannot be mocked or spyed on. To fix this, you need to create an object of services, and export that instead.

serviceBus.js

const message = () => {
  return "Hello world";
};

const foo = () => {
  return services.message();
};

const services = {
  message,
  foo
};

export default services;
```

<h3>mockDemo.test.js</h3>

<pre class="lang-js prettyprint-override"><code>import sendMessage from "../src/services/serviceBus";

describe("MessageReceiver Router", () => {
  sendMessage.message = jest.fn(() => {
    return "bar";
  });

  it(`message should return bar`, async () => {
    expect(sendMessage.message()).toBe("bar");
    expect(sendMessage.foo()).toBe("bar");
  });
});
</code>```

Body:
Given the following example with a basic test, I'd expect bar to be returned when sendMessage.message is mocked with Jest. Instead, when called, it returns the original value of "Hello World".

serviceBus.js

export const message = () => {
  return "Hello world";
};

export const foo = () => {
  return message();
};

mockDemo.test.js

import * as sendMessage from "../src/services/serviceBus";

describe("sendMessage", () => {
  sendMessage.message = jest.fn(() => {
    return "bar";
  });

  it(`message should return bar`, async () => {
    expect(sendMessage.message()).toBe("bar");
    expect(sendMessage.foo()).toBe("bar");
  });
});

And the results as follows:

$ ./node_modules/.bin/jest ./__tests__/mockDemo.test.js
 FAIL  __tests__/mockDemo.test.js
  MessageReceiver Router
    ✕ message should return bar (9ms)

  ● MessageReceiver Router › message should return bar

    expect(received).toBe(expected) // Object.is equality

    Expected: "bar"
    Received: "Hello world"

       9 |   it(`message should return bar`, async () => {
      10 |     expect(sendMessage.message()).toBe("bar");
    > 11 |     expect(sendMessage.foo()).toBe("bar");
         |                               ^
      12 |   });
      13 | });
      14 |

      at Object.<anonymous> (__tests__/mockDemo.test.js:11:31)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total

It looks as if sendMessage.foo is calling the bound function once imported of message, which by default returns Hello World.

How would one mock message in this context?

Update

Using jest.fn().mockImplementation(() => "bar"); results in the same behaviour:

describe("MessageReceiver Router", () => {
  //   sendMessage.message.mockImplementation = jest.fn(() => {
  //     return "bar";
  //   });

  sendMessage.message = jest.fn().mockImplementation(() => "bar");

  it(`message should return bar`, async () => {
    expect(sendMessage.message()).toBe("bar");
    expect(sendMessage.foo()).toBe("bar");
  });
});

Results:

$ ./node_modules/.bin/jest ./__tests__/mockDemo.test.js
 FAIL  __tests__/mockDemo.test.js
  MessageReceiver Router
    ✕ message should return bar (10ms)

  ● MessageReceiver Router › message should return bar

    expect(received).toBe(expected) // Object.is equality

    Expected: "bar"
    Received: "Hello world"

      11 |   it(`message should return bar`, async () => {
      12 |     expect(sendMessage.message()).toBe("bar");
    > 13 |     expect(sendMessage.foo()).toBe("bar");
         |                               ^
      14 |   });
      15 | });
      16 |

      at Object.<anonymous> (__tests__/mockDemo.test.js:13:31)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.175s

Body:
So internal functions called cannot be mocked or spyed on. To fix this, you need to create an object of services, and export that instead.

serviceBus.js

const message = () => {
  return "Hello world";
};

const foo = () => {
  return services.message();
};

const services = {
  message,
  foo
};

export default services;

mockDemo.test.js

import sendMessage from "../src/services/serviceBus";

describe("MessageReceiver Router", () => {
  sendMessage.message = jest.fn(() => {
    return "bar";
  });

  it(`message should return bar`, async () => {
    expect(sendMessage.message()).toBe("bar");
    expect(sendMessage.foo()).toBe("bar");
  });
});


问:
ASP.NET MVC authorization without connection to DB, in code only validation
Every sample I found for authorization in the MVC model in ASP.NET framework required connection to DB. And looks like:

```<code>  public ActionResult LogOn(LogOnViewModel model, string returnUrl) {
    if (ModelState.IsValid) {
        if (Membership.ValidateUser(model.UserName, string.Empty)) {
</code>```

where Membership relate to corresponding DB, is there any way to authenticate user in the backend without connection to DB, in code only?

Thank you!

答:
You have to validate your users against some known record source.  This can be in memory, in a database, through another service, or using an external Identity Provider like Auth0.

If you just wanting to test with a few predefined static users, then in memory is probably your best approach.  You can create a custom membership provider to do this by inheriting from the existing membership objects and overriding the methods that load the data.

Here’s a great example of how this is accomplished.

https://www.spiria.com/en/blog/web-applications/how-create-your-own-membership-provider-instead-using-sqlmembershipprovider/

Body:
Every sample I found for authorization in the MVC model in ASP.NET framework required connection to DB. And looks like:

  public ActionResult LogOn(LogOnViewModel model, string returnUrl) {
    if (ModelState.IsValid) {
        if (Membership.ValidateUser(model.UserName, string.Empty)) {

where Membership relate to corresponding DB, is there any way to authenticate user in the backend without connection to DB, in code only?

Thank you!


问:
Which Scripting Language Should I Choose?
I need such a scripting language which is:

good at string operation;

easy to write/read test files;

easy to learn.

Any recommendations?

答:
I'd say Python. It's easy to learn, has lovely clear syntax, tonnes of modules that extend its functionality and - should you want to develop for the web - there's Django, which I've been learning recently. It's a great webapp framework.
I don't regret learning Python one bit and does everything I'd want. The error handling is fantastic too - I feel much safer programming in Python than I do in PHP, where the error handling is pretty poor, in my opinion.
I wouldn't go with Perl, but it is an option. I find Perl looks like someone vomitted code into a file. Ruby is popular among web-people, but it's not fantastic performance-wise and if you want something very much for the web - PHP is the way to go (though as I said above, Django is amazing with Python).

Overall, I'd go with Python but there are pros and cons of each.


问:
How to increment a value in ngfor angular 6 for every third iteration
How to increment a value for every 3rd iteration in ngFor.

 I want to achieve like this in angular ngfor, how to do this

I am using array of objects like below and I am looping tempArr[] using ngFor

  tempArrA = ['item a', 'item b', 'item c', 'item d', 'item e', 'item f', 'item g', 'item h','item i', 'item j', 'item k', 'item l','item m', 'item n', 'item o', 'item p'];
  tempArrB = ['item f', 'item g', 'item h','item i', 'item j'];
  tempArrC = [ 'item j', 'item k', 'item l','item m', 'item n', 'item o', 'item p'];
  tempArr:any = [
    {
      name: "one",
      items: this.tempArrA
      },
       {
      name: "two",
      items: this.tempArrB
      },
       {
      name: "three",
      items: this.tempArrC
      },
      ];```

item a -- 1

item b -- 1

item c -- 1

item d -- 2

item e -- 2

item f -- 2

item g -- 3

item h -- 3

item i -- 3

and so on....

答:
Typically in angular, you want to map your model data into a view friendly view-model, like so:

```<code>interface MyItemVm {
  value: string;
  viewIndex: number;
}

tempArrAVm: MyItemVm[] = tempArrA.map((value, idx) => ({value, viewIndex: Math.floor(idx / 3) + 1}))
</code>```

then just loop it:

```<code><div *ngFor="let itm of tempArrAVm">
  {{itm.value}} -- {{itm.viewIndex}}
</div>
</code>```

this may be a bit heavy duty for your use case but it is the general solution to these sorts of problems. A modified version of the pipe solution posted before may work for your specific case.

Body:
How to increment a value for every 3rd iteration in ngFor.

 I want to achieve like this in angular ngfor, how to do this

I am using array of objects like below and I am looping tempArr[] using ngFor

  tempArrA = ['item a', 'item b', 'item c', 'item d', 'item e', 'item f', 'item g', 'item h','item i', 'item j', 'item k', 'item l','item m', 'item n', 'item o', 'item p'];
  tempArrB = ['item f', 'item g', 'item h','item i', 'item j'];
  tempArrC = [ 'item j', 'item k', 'item l','item m', 'item n', 'item o', 'item p'];
  tempArr:any = [
    {
      name: "one",
      items: this.tempArrA
      },
       {
      name: "two",
      items: this.tempArrB
      },
       {
      name: "three",
      items: this.tempArrC
      },
      ];

item a -- 1

item b -- 1

item c -- 1

item d -- 2

item e -- 2

item f -- 2

item g -- 3

item h -- 3

item i -- 3

and so on....

Body:
Typically in angular, you want to map your model data into a view friendly view-model, like so:

interface MyItemVm {
  value: string;
  viewIndex: number;
}

tempArrAVm: MyItemVm[] = tempArrA.map((value, idx) => ({value, viewIndex: Math.floor(idx / 3) + 1}))

then just loop it:

<div *ngFor="let itm of tempArrAVm">
  {{itm.value}} -- {{itm.viewIndex}}
</div>

this may be a bit heavy duty for your use case but it is the general solution to these sorts of problems. A modified version of the pipe solution posted before may work for your specific case.


问:
Can not retrieve the id of a foreign key [Laravel]
I have 2 tables: User and demands. A User can have as many demands as he wants. Inside the demands table, there is the User foreign key.

When the User completes the form, I put the User & demands information inside those 2 tables.

But I do not know how to have the User id to put it inside the demands table.

Here is the function inside my Controller:

```<code>    public function store(Request $request){
        $demand = new Demand;
        $user = new user ;
        $user ->numStudent= $request->NumStudent;
        $user ->role_id = "3";
        $user ->Lastname = $request->LastName;
        $user ->FirstName= $request->FirstName;
        $user ->numero_etudiant = "12345678";
        $user ->email = $request->Email;
        $user ->password = bcrypt('idk');
        $user ->adress= $request->Adress;
        $user ->phone = $request->Phone;
        $user ->parcours = $request->Parcours;

        $demand->status_id= "3";
        //problem below
        $demand->User_id= $User;
        //
        $demand->time_id = $request->LoanTime;
        $demand->creation_date = $request->CreationDate;
        $demand->comments = "";

        $user ->save();
        $demand->save();

        return redirect('/demands_list');

    }

</code>```

But it says "Can't use method return value in write context".

Cordially

答:
You have to save first the instance of your user before using its properties. Your code should look like this.</p>

```<code>public function store(Request $request){
        $demand = new Demand;
        $user = new user ;
        $user->numStudent= $request->NumStudent;
        $user->role_id = "3";
        $user->Lastname = $request->LastName;
        $user->FirstName= $request->FirstName;
        $user->numero_etudiant = "12345678";
        $user->email = $request->Email;
        $user->password = bcrypt('idk');
        $user->adress= $request->Adress;
        $user->phone = $request->Phone;
        $user->parcours = $request->Parcours;
        $user->save();

        $demand->status_id= "3";
        //problem below
        $demand->User_id= $user->id;
        //
        $demand->time_id = $request->LoanTime;
        $demand->creation_date = $request->CreationDate;
        $demand->comments = "";

        $demand->save();

        return redirect('/demands_list');

    }
</code>```

Body:
I have 2 tables: User and demands. A User can have as many demands as he wants. Inside the demands table, there is the User foreign key.

When the User completes the form, I put the User & demands information inside those 2 tables.

But I do not know how to have the User id to put it inside the demands table.

Here is the function inside my Controller:

    public function store(Request $request){
        $demand = new Demand;
        $user = new user ;
        $user ->numStudent= $request->NumStudent;
        $user ->role_id = "3";
        $user ->Lastname = $request->LastName;
        $user ->FirstName= $request->FirstName;
        $user ->numero_etudiant = "12345678";
        $user ->email = $request->Email;
        $user ->password = bcrypt('idk');
        $user ->adress= $request->Adress;
        $user ->phone = $request->Phone;
        $user ->parcours = $request->Parcours;

        $demand->status_id= "3";
        //problem below
        $demand->User_id= $User;
        //
        $demand->time_id = $request->LoanTime;
        $demand->creation_date = $request->CreationDate;
        $demand->comments = "";

        $user ->save();
        $demand->save();

        return redirect('/demands_list');

    }

But it says "Can't use method return value in write context".

Cordially

Body:
You have to save first the instance of your user before using its properties. Your code should look like this.

public function store(Request $request){
        $demand = new Demand;
        $user = new user ;
        $user->numStudent= $request->NumStudent;
        $user->role_id = "3";
        $user->Lastname = $request->LastName;
        $user->FirstName= $request->FirstName;
        $user->numero_etudiant = "12345678";
        $user->email = $request->Email;
        $user->password = bcrypt('idk');
        $user->adress= $request->Adress;
        $user->phone = $request->Phone;
        $user->parcours = $request->Parcours;
        $user->save();

        $demand->status_id= "3";
        //problem below
        $demand->User_id= $user->id;
        //
        $demand->time_id = $request->LoanTime;
        $demand->creation_date = $request->CreationDate;
        $demand->comments = "";

        $demand->save();

        return redirect('/demands_list');

    }


问:
In python is there an best practice way to clean regex search strings containing characters that need to be escaped?
In the below example I want to only return True for the last string in the Series. This means I have to add a conditional escaping any plus symbols so that they actually get searched and it doesn't take on its special regex function.

```<code>import pandas as pd
testseries=pd.Series(["product a basic","product a","product a+","product b basic","product b","product b+"])

#this string will be unknown in practice
searchstring="b+"

# Necessary cleaning conditional
if "+" in searchstring:
    searchstring = searchstring.replace("+","\\+")

#Search is actually performed
print(searchstring)
testseries.str.contains(searchstring)
</code>```

In practice I am not going to know what searchstring is going to be. Is there a function or different approach for ensuring that any characters that need to be escaped are correctly escaped?

I don't want to keep having to create a ever increasing chain of conditionals that clean the searchstring or is this inevitable?

答:
The python re module has an escape() function.
Here is an example how to use it:

```<code>>>> import re
>>> re.escape('b+')
'b\\+'
</code>```

Body:
In the below example I want to only return True for the last string in the Series. This means I have to add a conditional escaping any plus symbols so that they actually get searched and it doesn't take on its special regex function.

import pandas as pd
testseries=pd.Series(["product a basic","product a","product a+","product b basic","product b","product b+"])

#this string will be unknown in practice
searchstring="b+"

# Necessary cleaning conditional
if "+" in searchstring:
    searchstring = searchstring.replace("+","\\+")

#Search is actually performed
print(searchstring)
testseries.str.contains(searchstring)

In practice I am not going to know what searchstring is going to be. Is there a function or different approach for ensuring that any characters that need to be escaped are correctly escaped?

I don't want to keep having to create a ever increasing chain of conditionals that clean the searchstring or is this inevitable?

Body:
The python re module has an escape() function.
Here is an example how to use it:

>>> import re
>>> re.escape('b+')
'b\\+'


问:
How to serially loop through multiple csv files from two directories and append them accordingly and plot from them in python?
I am trying make comparison bar plot for two types of variable and their count from csv files in python using pandas and matplotlib. Each type of variable data is stored in different directories.
I have created two loops for both different data and concate them and plot them But there is a problem in looping and appending data. First type of variable data is not appending with next file and it is taking 1st file always and concatenate with 2nd variable type data (which is appending correctly).
Here is the code I am using

```<code>path = '/scratch/plots/'
A_files = sorted(glob.glob(os.path.join(path, "*table.csv")))
path = '/scratch/plots/B/'

B_files = sorted(glob.glob(os.path.join(path, "*table.csv")))

# loop through the files and read them in with pandas
dataframes = []  # a list to hold all the individual pandas DataFrames
for csvfile in A_files:
    df = pd.read_csv(csvfile,usecols = ['COUNT','CLASS'])
    dataframes.append(df) #this case it is taking only first file to concate. Loop doest not appending correctly

dataframes2 = []
for x in B_files:
    fn= os.path.splitext(x)[0]
    df2 = pd.read_csv(x,usecols = ['COUNT','CLASS'])
    dataframes2.append(df2)

    A_df=df.iloc[2:12]
    B_df=df2.iloc[2:12]
    a= pd.concat([A_df,B_df], axis=1)
    ax=a.set_index('CLASS').plot(kind='bar',rot=0, figsize=(15,10), fontsize=12)

    ax.legend(["A", "B"]);

    plt.savefig(''  + fn[:-32]+'_bargraph' + '.png', dpi=300)

    plt.show()
</code>```

How can I append through each file though 1st loop from the dictionary  ? I have attached one example of concatenated data frame and plots enter image description here

答:
Consider looping through both directories at same time elementwise with zip (assuming equal amount of csv files in both directories) which may avoid the need to append data frames. Below makes no change to plotting:

```<code>for f1, f2 in zip(A_files, B_files):
    fn = os.path.splitext(f2)[0]

    # HORIZONTAL CONCATENATION
    df = pd.concat([pd.read_csv(f1, usecols = ['COUNT','CLASS']).iloc[2:12],
                    pd.read_csv(f2, usecols = ['COUNT','CLASS']).iloc[2:12]],
                   axis = 1)

    # PLOT
    ax = df.set_index('CLASS').plot(kind='bar', rot=0, figsize=(15,10), fontsize=12)
    ax.legend(["A", "B"]);

    plt.savefig(fn[:-32]+'_bargraph' + '.png', dpi=300)
    plt.show()
</code>```

Body:
I am trying make comparison bar plot for two types of variable and their count from csv files in python using pandas and matplotlib. Each type of variable data is stored in different directories.
I have created two loops for both different data and concate them and plot them But there is a problem in looping and appending data. First type of variable data is not appending with next file and it is taking 1st file always and concatenate with 2nd variable type data (which is appending correctly).
Here is the code I am using

path = '/scratch/plots/'
A_files = sorted(glob.glob(os.path.join(path, "*table.csv")))
path = '/scratch/plots/B/'

B_files = sorted(glob.glob(os.path.join(path, "*table.csv")))

# loop through the files and read them in with pandas
dataframes = []  # a list to hold all the individual pandas DataFrames
for csvfile in A_files:
    df = pd.read_csv(csvfile,usecols = ['COUNT','CLASS'])
    dataframes.append(df) #this case it is taking only first file to concate. Loop doest not appending correctly

dataframes2 = []
for x in B_files:
    fn= os.path.splitext(x)[0]
    df2 = pd.read_csv(x,usecols = ['COUNT','CLASS'])
    dataframes2.append(df2)

    A_df=df.iloc[2:12]
    B_df=df2.iloc[2:12]
    a= pd.concat([A_df,B_df], axis=1)
    ax=a.set_index('CLASS').plot(kind='bar',rot=0, figsize=(15,10), fontsize=12)

    ax.legend(["A", "B"]);

    plt.savefig(''  + fn[:-32]+'_bargraph' + '.png', dpi=300)

    plt.show()

How can I append through each file though 1st loop from the dictionary  ? I have attached one example of concatenated data frame and plots enter image description here

Body:
Consider looping through both directories at same time elementwise with zip (assuming equal amount of csv files in both directories) which may avoid the need to append data frames. Below makes no change to plotting:

for f1, f2 in zip(A_files, B_files):
    fn = os.path.splitext(f2)[0]

    # HORIZONTAL CONCATENATION
    df = pd.concat([pd.read_csv(f1, usecols = ['COUNT','CLASS']).iloc[2:12],
                    pd.read_csv(f2, usecols = ['COUNT','CLASS']).iloc[2:12]],
                   axis = 1)

    # PLOT
    ax = df.set_index('CLASS').plot(kind='bar', rot=0, figsize=(15,10), fontsize=12)
    ax.legend(["A", "B"]);

    plt.savefig(fn[:-32]+'_bargraph' + '.png', dpi=300)
    plt.show()