问:
fetch local GIT branch on jenkins build
We are working on multiple feature, one develop, release and master GIT branches. We create separate feature branches for all JIRA development task. I need to have Jenkins build job to poll all feature branch, and build those specific ones which have recent PUSH events. After the build job is initiated, I want that specific GIT feature branch name (i.e. JIRA-1234, not origin/feature/JIRA-1234) to be picked up, included this in artifact file name as APP-0.0.1-JIRA-1234-SNAPSHOT, and save this to Nexus.

NB: POM.XML file is configured with APP-0.0.1-SNAPSHOT.

For each feature branch build, we want separate jar files saved to Nexus. For ex: Development task under JIRA-0101 would build and save jar in nexus as APP-0.0.1-JIRA-0101-SNAPSHOT

I have included ${branch} parameter in POM.xml as shown below:
APP-0.0.1${branch}-SNAPSHOT

and pass this value from Jenkins build command as - mvn clean install -Dbranch=-JIRA-0101

I then parametrised the jenkins build task, after which I can get feature branch name as "origin/feature/JIRA-0101", but I cannot parse this whole string in Jenkins to pick only JIRA task.

Secondly, mvn jgitflow:release-start and mvn jgitflow:release-finish commands would create complications having "APP-0.0.1${branch}-SNAPSHOT" in POM.xml. So, using ${branch} in POM is not effective.

答:
If I get it right you want your Jenkins to automatically build on push events, and on success to publish the target folder to your nexus. If that is the case I would suggest looking into something a bit more advanced called JenkinsFile (https://jenkins.io/doc/book/pipeline/jenkinsfile/) with a couple of jenkins plugins as Multibranch pipeline https://wiki.jenkins.io/display/JENKINS/Pipeline+Multibranch+Plugin which can automatically detect all the branches in your repository and setup a job for each one.
Then you would need webhooks (both bitbucket and github have them) and those hooks would inform your jenkins about the push events ( or any other event you want. like commit / comment etc. ) which will trigger the build job. Some plugins ( like Bitbucket branch source plugin https://wiki.jenkins.io/display/JENKINS/Bitbucket+Branch+Source+Plugin ) offer a service that handle those webhooks so you wont have to do it manually ( manual : you have to type the job url and the execute command like ci:port/yourJob/?build [can't recall the whole url been ages since I used it ], automatic POST ci:port/bitbucket-scmsource-hook/notify/ which is universal and the plugin will redirect the hook to the appropriate job. ). As a last step of your jenkinsfile pipeline you can add the push command to your nexus which will add the file / files you want in your nexus. !

I hope my answer helped :)

Title: fetch local GIT branch on jenkins build


来源: stackexchange

问:
How can I delete multipe lines in a text by Python?
I have a similar question to delete multiple line

I want to delete the line and the next 4 lines. This is my code:

```<code>bind = open('/etc/bind/named.conf.local','r')
a = dict['name']
for line in bind:
        if a in line:
            print('line  exist')
            ''' and delete this line and 4 line after it'''
        else:
            print('line does not exist')
</code>```

I want to save modify text in /etc/bind/named.conf.local in place, without fileinput. I do not want skip 4 line I want to delete them from the file. I do not want to read it and write it again and skip 4 lines.

What should I do?

答:
I think the following code does what you're looking for. You will have to adjust settings filename, keyword and delete to your needs. The code will delete delete lines from file filename every time keyword is found in a line. (Including the keyword line.)

```<code># Settings
filename = "test.txt"
keyword = "def"
delete = 2

# Read lines from file
with open(filename) as f:
    lines = f.readlines()

# Process lines
for i, line in enumerate(lines):
    if keyword in line:
        del lines[i:i + delete]

# Save modified lines to file
with open(filename, "w") as f:
    f.writelines(lines)
</code>```

Example test.txt before:

```<code>abc
def
ghi
jkl
</code>```

Example test.txt afterwards:

```<code>abc
jkl
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a similar question to delete multiple line

I want to delete the line and the next 4 lines. This is my code:

bind = open('/etc/bind/named.conf.local','r')
a = dict['name']
for line in bind:
        if a in line:
            print('line  exist')
            ''' and delete this line and 4 line after it'''
        else:
            print('line does not exist')

I want to save modify text in /etc/bind/named.conf.local in place, without fileinput. I do not want skip 4 line I want to delete them from the file. I do not want to read it and write it again and skip 4 lines.

What should I do?

Body:
I think the following code does what you're looking for. You will have to adjust settings filename, keyword and delete to your needs. The code will delete delete lines from file filename every time keyword is found in a line. (Including the keyword line.)

# Settings
filename = "test.txt"
keyword = "def"
delete = 2

# Read lines from file
with open(filename) as f:
    lines = f.readlines()

# Process lines
for i, line in enumerate(lines):
    if keyword in line:
        del lines[i:i + delete]

# Save modified lines to file
with open(filename, "w") as f:
    f.writelines(lines)

Example test.txt before:

abc
def
ghi
jkl

Example test.txt afterwards:

abc
jkl


答:
```<code>bind = open('/etc/bind/named.conf.local','r')
textfile = bind.readlines()
a = 'some text'
for line_num in range(len(textfile)):
    try:
        if a in textfile[line_num]:
            print('line exists')
            del textfile[line_num:line_num+5]
    except IndexError:
        break
writer = open("/etc/bind/named.conf.local","w")
writer.write(''.join(textfile))
writer.close()
</code>```

Title: How can I delete multipe lines in a text by Python?


问:
Definition com.adobe.cairngorm.vo.IValueObject could not found
i am unable to include external ".swc" files in compilation time.
Please help me? or suggest alternative ways? i am using sevaral 3rd party swc files , so is right choice to migrate my application to apache royale ?</p>

答:
Royale is not 100% compatible with Flex so you'll need to do some research on the libraries you use and what they're counterparts in Royale are.

Cairngorm for instance, has not been ported to Royale, but PureMVC has.


问:
How can I tell which login is being used to connect to a SQL Server linked server?
I can get information about a linked server using the sp_linked_servers stored procedure.  What the SP does not give me, however, is login info entered via sp_addlinkedsrvlogin.

How can I tell which login is being used to connect to the linked server?

答:
my favourite</p>

```<code>SELECT * FROM OPENQUERY(MyLinkedServer, 'SELECT SUSER_SNAME() AS Who')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
my favourite

SELECT * FROM OPENQUERY(MyLinkedServer, 'SELECT SUSER_SNAME() AS Who')


问:
NativeScript vue, vuex and urlhandler
Edit

I'm using https://github.com/hypery2k/nativescript-urlhandler to open a deep link within my app - using NativeScript vue, and vuex. It seems that in order to get at the methods needed to do routing [$navigateTo etc] this plugin needs to be set up slightly differently from the examples given in docs.

```<code>import Vue from "nativescript-vue";
import Vuex from "vuex";
Vue.use(Vuex);

import { handleOpenURL } from 'nativescript-urlhandler';

new Vue({
    mounted() {
        handleOpenURL( (appURL) => {
            console.log(appURL)
            // Settings is the variable that equals the component - in this case settings.
            this.$navigateTo(Settings);
        });
    },
    render: h => h("frame", [h(Home)]),
    store: ccStore
}).$start();
</code>```

handleOpenURL needs to be called within Mounted - then you can parse out the appURL and reference the page (component) that you wish to navigate to. I have been advised against calling handleOpenURL from within router - but I'm not sure why, and it works without error - and I have access to the methods for routing... so if anyone knows if this is a bad idea - please let me know :) Thanks!

All the stuff below that I wrote before has probably confused things - I'm referencing components within my vuex store to make them easily available from the router.

This is based on a solution by https://github.com/Spacarar - it can be found here: https://github.com/geodav-tech/vue-nativescript-router-example. It's a great solution because you don't have to include every single component within each component to use in navigation - it gives an almost vue router like experience.

I'm using https://github.com/hypery2k/nativescript-urlhandler to open a deep link within my app - however, I'm having problems opening the link.

In my app.js file, I have the following:

```<code>import Vue from "nativescript-vue";
import Vuex from "vuex";
Vue.use(Vuex);
....
import { handleOpenURL } from 'nativescript-urlhandler';
import ccStore  from './store/store';

handleOpenURL(function(appURL) {
// I have hardwired 'Settings' in for testing purposes - but this would be the appURL
    ccStore.dispatch('openAppURL', 'Settings');
});

....

new Vue({
    render: h => h("frame", [h(Home)]),
    store: ccStore
}).$start();
</code>```

I'm storing the route state within vuex, and have various methods which work (clicking on a link loads the component). However, handleOpenURL exists outside of vue... so I've had to access vuex directly from within the handleOpenURL method. I've created an action specifically for this case - openAppURL.. it does exactly the same thing as my other methods (although I've consolidated it).

When clicking on an app link, I am NOT taken to the page within the app. I have put a console log within openAppURL and can see it is being called, and the correct route object is returned... it just doesn't open the page. The SetTimeOut is used because nextTick isn't available from within vuex.

I am at a loss on how to get the page to appear...

```<code>const ccStore = new Vuex.Store({
    state: {
        user: {
            authToken: null,
            refreshToken: null,
        },
        routes: [
            {
                name: "Home",
                component: Home
            },
            {
                name: "Log In",
                component: Login
            },
            ...
        ],
        currentRoute: {
            //INITIALIZE THIS WITH YOUR HOME PAGE
            name: "Home",
            component: Home //COMPONENT
        },
        history: [],
    },
    mutations: {
        navigateTo(state, newRoute, options) {
            state.history.push({
                route: newRoute,
                options
            });
       },
    },
    actions: {
        openAppURL({state, commit}, routeName ) {
            const URL =  state.routes[state.routes.map( (route) => {
                return route.name;
            }).indexOf(routeName)];

            return setTimeout(() => {
                commit('navigateTo', URL, { animated: false, clearHistory: true });
        }, 10000);
       },
       ....
     }
   etc....
</code>```

答:
I have been advised to post my findings as the answer and mark it as correct. In order to use nativescript-urlhandler with vue, you must initialise the handler from within vue's mounted life cycle hook. Please see above for greater detail.</p>

```<code>import Vue from "nativescript-vue";
import Vuex from "vuex";
Vue.use(Vuex);

import Settings from "~/components/Settings";

import { handleOpenURL } from 'nativescript-urlhandler';

new Vue({
    mounted() {
        handleOpenURL( (appURL) => {
            console.log(appURL) // here you can get your appURL path etc and map it to a component... eg path === 'Settings. In this example I've just hardwired it in.
            this.$navigateTo(Settings);
        });
    },
    render: h => h("frame", [h(Home)]),
    store: ccStore
}).$start();
</code>```

Title: NativeScript vue, vuex and urlhandler

Body:
Edit

I'm using https://github.com/hypery2k/nativescript-urlhandler to open a deep link within my app - using NativeScript vue, and vuex. It seems that in order to get at the methods needed to do routing [$navigateTo etc] this plugin needs to be set up slightly differently from the examples given in docs.

import Vue from "nativescript-vue";
import Vuex from "vuex";
Vue.use(Vuex);

import { handleOpenURL } from 'nativescript-urlhandler';

new Vue({
    mounted() {
        handleOpenURL( (appURL) => {
            console.log(appURL)
            // Settings is the variable that equals the component - in this case settings.
            this.$navigateTo(Settings);
        });
    },
    render: h => h("frame", [h(Home)]),
    store: ccStore
}).$start();

handleOpenURL needs to be called within Mounted - then you can parse out the appURL and reference the page (component) that you wish to navigate to. I have been advised against calling handleOpenURL from within router - but I'm not sure why, and it works without error - and I have access to the methods for routing... so if anyone knows if this is a bad idea - please let me know :) Thanks!

All the stuff below that I wrote before has probably confused things - I'm referencing components within my vuex store to make them easily available from the router.

This is based on a solution by https://github.com/Spacarar - it can be found here: https://github.com/geodav-tech/vue-nativescript-router-example. It's a great solution because you don't have to include every single component within each component to use in navigation - it gives an almost vue router like experience.

I'm using https://github.com/hypery2k/nativescript-urlhandler to open a deep link within my app - however, I'm having problems opening the link.

In my app.js file, I have the following:

import Vue from "nativescript-vue";
import Vuex from "vuex";
Vue.use(Vuex);
....
import { handleOpenURL } from 'nativescript-urlhandler';
import ccStore  from './store/store';

handleOpenURL(function(appURL) {
// I have hardwired 'Settings' in for testing purposes - but this would be the appURL
    ccStore.dispatch('openAppURL', 'Settings');
});

....

new Vue({
    render: h => h("frame", [h(Home)]),
    store: ccStore
}).$start();

I'm storing the route state within vuex, and have various methods which work (clicking on a link loads the component). However, handleOpenURL exists outside of vue... so I've had to access vuex directly from within the handleOpenURL method. I've created an action specifically for this case - openAppURL.. it does exactly the same thing as my other methods (although I've consolidated it).

When clicking on an app link, I am NOT taken to the page within the app. I have put a console log within openAppURL and can see it is being called, and the correct route object is returned... it just doesn't open the page. The SetTimeOut is used because nextTick isn't available from within vuex.

I am at a loss on how to get the page to appear...

const ccStore = new Vuex.Store({
    state: {
        user: {
            authToken: null,
            refreshToken: null,
        },
        routes: [
            {
                name: "Home",
                component: Home
            },
            {
                name: "Log In",
                component: Login
            },
            ...
        ],
        currentRoute: {
            //INITIALIZE THIS WITH YOUR HOME PAGE
            name: "Home",
            component: Home //COMPONENT
        },
        history: [],
    },
    mutations: {
        navigateTo(state, newRoute, options) {
            state.history.push({
                route: newRoute,
                options
            });
       },
    },
    actions: {
        openAppURL({state, commit}, routeName ) {
            const URL =  state.routes[state.routes.map( (route) => {
                return route.name;
            }).indexOf(routeName)];

            return setTimeout(() => {
                commit('navigateTo', URL, { animated: false, clearHistory: true });
        }, 10000);
       },
       ....
     }
   etc....

Body:
I have been advised to post my findings as the answer and mark it as correct. In order to use nativescript-urlhandler with vue, you must initialise the handler from within vue's mounted life cycle hook. Please see above for greater detail.

import Vue from "nativescript-vue";
import Vuex from "vuex";
Vue.use(Vuex);

import Settings from "~/components/Settings";

import { handleOpenURL } from 'nativescript-urlhandler';

new Vue({
    mounted() {
        handleOpenURL( (appURL) => {
            console.log(appURL) // here you can get your appURL path etc and map it to a component... eg path === 'Settings. In this example I've just hardwired it in.
            this.$navigateTo(Settings);
        });
    },
    render: h => h("frame", [h(Home)]),
    store: ccStore
}).$start();


问:
How to fix? Discord.js Bot keeps going offline because of Value error
I keep getting this error

```<code>TypeError: Cannot read property 'size' of undefined
at Client.client.on.message
(/home/colter/Code/groundskeeper/index.js:38:30)
at emitOne (events.js:116:13)
at Client.emit (events.js:211:7)
at MessageCreateHandler.handle
</code>```

I have checked for errors and compared it to the sample code. It all looks right to me.

```<code>client.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot)
return;

const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();

// Here is my syntax for adding commands. So far simple ones, but commands non the less!
if (command === 'ping') {
    message.channel.send('Pong');
}
else if (command === 'beep') {
    message.channel.send('Boop');
}
else if (command === 'server') {
    message.channel.send(`Server name: ${message.guild.name}\nTotal members: ${message.guild.memberCount}`);
}
else if (command === 'user-info') {
    message.channel.send(`Your username: ${message.author.username}\nYour ID: ${message.author.id}`);
}
else if (command === 'args-info') {
    if (!args.length) {
        return message.channel.send(`Your didnt provide any arguments, ${message.author}!`);
    }
    else if (args[0] === 'foo') {
        return message.channel.send('bar');
    }
    message.channel.send(`first argument: ${args[0]}`);
}
else if (command === 'kick') {
    if (!message.mentions.user.size) {
        return message.reply('you need to tag a user in order to kick them');
    }

    const taggedUser = message.mentions.users.first();

    message.channel.send(`You wanted to kick: ${taggedUser}`);
}
});

client.login(token);
</code>```

the expected output should be you need to tag a user in order to kick them from my bot when I use the ?kick command.

答:
Perhaps you could use this, if you only need to kick one person at a time.

if(!message.guild) return; // Only runs if in a server
const member = message.mentions.members.first(); // This gets the first guild member, not user.
if (member && message.member.hasPermission('KICK_MEMBERS')) {  // Only tries to kick them if they exist and have permission
  try {
    member.kick(args.slice(1).join(' '); // Gives reason, if any and kicks them.
  } catch (err) {
    console.error(err);
  }
} else {
  message.channel.send(`You tried to kick: ${args[0]}`);
}
```

Body:
I keep getting this error

TypeError: Cannot read property 'size' of undefined
at Client.client.on.message
(/home/colter/Code/groundskeeper/index.js:38:30)
at emitOne (events.js:116:13)
at Client.emit (events.js:211:7)
at MessageCreateHandler.handle

I have checked for errors and compared it to the sample code. It all looks right to me.

client.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot)
return;

const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();

// Here is my syntax for adding commands. So far simple ones, but commands non the less!
if (command === 'ping') {
    message.channel.send('Pong');
}
else if (command === 'beep') {
    message.channel.send('Boop');
}
else if (command === 'server') {
    message.channel.send(`Server name: ${message.guild.name}\nTotal members: ${message.guild.memberCount}`);
}
else if (command === 'user-info') {
    message.channel.send(`Your username: ${message.author.username}\nYour ID: ${message.author.id}`);
}
else if (command === 'args-info') {
    if (!args.length) {
        return message.channel.send(`Your didnt provide any arguments, ${message.author}!`);
    }
    else if (args[0] === 'foo') {
        return message.channel.send('bar');
    }
    message.channel.send(`first argument: ${args[0]}`);
}
else if (command === 'kick') {
    if (!message.mentions.user.size) {
        return message.reply('you need to tag a user in order to kick them');
    }

    const taggedUser = message.mentions.users.first();

    message.channel.send(`You wanted to kick: ${taggedUser}`);
}
});

client.login(token);

the expected output should be you need to tag a user in order to kick them from my bot when I use the ?kick command.


问:
How to deprecate a method in Objective-C
We have our library we ship to our customers, and I'd like to mark some methods as "deprecated" because we changed them (like Apple does in the iPhone SDK).

I've seen the __OSX_AVAILABLE_BUT_DEPRECATED pre-processor macro, which is mapped to __AVAILABILITY_INTERNAL, which is mapped to __attribute__((deprecated))...

Well i'm a bit confused with this stuff!

Anybody knows something about that ?

答:
Swift 5.0

Deprecate any method/class/struct/protocols using @available

```<code>@available(*, deprecated, message: "Parse your data by hand instead")
func parseData() { }

@available(*, deprecated, renamed: "loadData")
func fetchData() { }

@available(swift, obsoleted: 4.1, renamed: "attemptConnection")
func testConnection() { }

@available(swift, deprecated: 4.0, obsoleted: 5.0, message: "This will be removed in v5.0; please migrate to a different API.")
</code>```

Possible params:

introduced

deprecated

obsoleted

message

renamed

For more info see apple doc: Attributes

Body:
Swift 5.0

Deprecate any method/class/struct/protocols using @available

@available(*, deprecated, message: "Parse your data by hand instead")
func parseData() { }

@available(*, deprecated, renamed: "loadData")
func fetchData() { }

@available(swift, obsoleted: 4.1, renamed: "attemptConnection")
func testConnection() { }

@available(swift, deprecated: 4.0, obsoleted: 5.0, message: "This will be removed in v5.0; please migrate to a different API.")

Possible params:

introduced

deprecated

obsoleted

message

renamed

For more info see apple doc: Attributes


问:
RabbitMQ LDAP on the Management Plugin
I am new to RabbitMQ.  I have it installed on Windows 10 Enterpise for development purposes.  We have Active Directory running.  Trying to set up LDAP for the management plugin, so that any user with the right password can login as administrator.

My latest config:

```<code>[
{
    rabbit,
    [
        {
            auth_backends, [
                {rabbit_auth_backend_ldap, rabbit_auth_backend_internal},
                rabbit_auth_backend_internal
            ]
        }
    ]
},
{
  rabbitmq_auth_backend_ldap,
  [
    {
        servers, [
            "WLNC0DS23N.na.mycompany.com","WBRD0DS21N.na.mycompany.com"
        ]
    },
    {
        dn_lookup_attribute, "userPrincipalName"
    },
    {
        dn_lookup_base, "DC=na,DC=mycompany,DC=com"
    },
    {
        user_dn_pattern, "${username}@mycompany.com"
    },
    {
        use_ssl, false
    },
    {
        port, 389
    },
    {
        log, true
    },
    {
        vhost_access_query, {in_group_nested, "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
    },
    {
        resource_access_query, {in_group_nested, "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
    },
    {
        topic_access_query, {in_group_nested, "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
    },
    {
        tag_queries, [
            {
                administrator, {in_group_nested,"CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
            }
        ]
    }
  ]
}
</code>```

].

Unfortunately, while LDAP seems to check me out ok, I am not able to login in and get this error in the log:

```<code>2019-05-28 16:04:14.662 [info] <0.678.0> LDAP CHECK: login for perryda
2019-05-28 16:04:14.663 [info] <0.678.0>         LDAP filling template "${username}@mycompany.com" with
        [{username,<<"perryda">>}]
2019-05-28 16:04:14.663 [info] <0.678.0>         LDAP template result: "perryda@mycompany.com"
2019-05-28 16:04:14.750 [info] <0.317.0>     LDAP bind succeeded: xxxx
2019-05-28 16:04:14.750 [info] <0.317.0>         LDAP filling template "${username}@mycompany.com" with
        [{username,<<"perryda">>}]
2019-05-28 16:04:14.751 [info] <0.317.0>         LDAP template result: "perryda@mycompany.com"
2019-05-28 16:04:14.753 [info] <0.317.0>     LDAP DN lookup: perryda -> CN=Perry\, David,OU=Users,OU=WLNC-Wilmington,OU=OC,OU=IT-SD,DC=na,DC=mycompany,DC=com
2019-05-28 16:04:14.753 [info] <0.317.0>     LDAP CHECK: does perryda have tag administrator?
2019-05-28 16:04:14.753 [info] <0.317.0>     LDAP evaluating query: {in_group_nested,"CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
2019-05-28 16:04:14.753 [info] <0.317.0>     LDAP evaluating query: {in_group_nested,"CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member",subtree}
2019-05-28 16:04:14.754 [info] <0.317.0>         LDAP filling template "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com" with
        [{username,<<"perryda">>},{user_dn,"CN=Perry\\, David,OU=Users,OU=WLNC-Wilmington,OU=OC,OU=IT-SD,DC=na,DC=mycompany,DC=com"}]
2019-05-28 16:04:14.754 [info] <0.317.0>         LDAP template result: "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com"
2019-05-28 16:04:14.759 [info] <0.317.0>     LDAP DECISION: does perryda have tag administrator? true
2019-05-28 16:04:14.759 [info] <0.678.0> LDAP DECISION: login for perryda: ok
2019-05-28 16:04:14.759 [warning] <0.678.0> HTTP access denied: user 'perryda' - invalid credentials
</code>```

Does anyone have a clueon what the problem is, and how to fix?

答:
This answer was posted by Daniil Fedotov in the RabbitMQ Google Group. It worked great!

Hi,

Your auth backend configuration line "{rabbit_auth_backend_ldap, rabbit_auth_backend_internal}," means that the LDAP backend is used only for authentication (checking that the user exists) but not authorization (checking that the user has access to resources), and internal backend is used for authorization.
This means that you should have permissions and tags configured for the internal user.
If you want authorization to happen via LDAP you should replace this tuple: "{rabbit_auth_backend_ldap, rabbit_auth_backend_internal}" with: "rabbit_auth_backend_ldap".
Or create user permissions in the internal database, but I guess that's not what you're trying to achieve.

Title: RabbitMQ LDAP on the Management Plugin

Body:
I am new to RabbitMQ.  I have it installed on Windows 10 Enterpise for development purposes.  We have Active Directory running.  Trying to set up LDAP for the management plugin, so that any user with the right password can login as administrator.

My latest config:

[
{
    rabbit,
    [
        {
            auth_backends, [
                {rabbit_auth_backend_ldap, rabbit_auth_backend_internal},
                rabbit_auth_backend_internal
            ]
        }
    ]
},
{
  rabbitmq_auth_backend_ldap,
  [
    {
        servers, [
            "WLNC0DS23N.na.mycompany.com","WBRD0DS21N.na.mycompany.com"
        ]
    },
    {
        dn_lookup_attribute, "userPrincipalName"
    },
    {
        dn_lookup_base, "DC=na,DC=mycompany,DC=com"
    },
    {
        user_dn_pattern, "${username}@mycompany.com"
    },
    {
        use_ssl, false
    },
    {
        port, 389
    },
    {
        log, true
    },
    {
        vhost_access_query, {in_group_nested, "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
    },
    {
        resource_access_query, {in_group_nested, "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
    },
    {
        topic_access_query, {in_group_nested, "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
    },
    {
        tag_queries, [
            {
                administrator, {in_group_nested,"CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
            }
        ]
    }
  ]
}

].

Unfortunately, while LDAP seems to check me out ok, I am not able to login in and get this error in the log:

2019-05-28 16:04:14.662 [info] <0.678.0> LDAP CHECK: login for perryda
2019-05-28 16:04:14.663 [info] <0.678.0>         LDAP filling template "${username}@mycompany.com" with
        [{username,<<"perryda">>}]
2019-05-28 16:04:14.663 [info] <0.678.0>         LDAP template result: "perryda@mycompany.com"
2019-05-28 16:04:14.750 [info] <0.317.0>     LDAP bind succeeded: xxxx
2019-05-28 16:04:14.750 [info] <0.317.0>         LDAP filling template "${username}@mycompany.com" with
        [{username,<<"perryda">>}]
2019-05-28 16:04:14.751 [info] <0.317.0>         LDAP template result: "perryda@mycompany.com"
2019-05-28 16:04:14.753 [info] <0.317.0>     LDAP DN lookup: perryda -> CN=Perry\, David,OU=Users,OU=WLNC-Wilmington,OU=OC,OU=IT-SD,DC=na,DC=mycompany,DC=com
2019-05-28 16:04:14.753 [info] <0.317.0>     LDAP CHECK: does perryda have tag administrator?
2019-05-28 16:04:14.753 [info] <0.317.0>     LDAP evaluating query: {in_group_nested,"CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
2019-05-28 16:04:14.753 [info] <0.317.0>     LDAP evaluating query: {in_group_nested,"CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member",subtree}
2019-05-28 16:04:14.754 [info] <0.317.0>         LDAP filling template "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com" with
        [{username,<<"perryda">>},{user_dn,"CN=Perry\\, David,OU=Users,OU=WLNC-Wilmington,OU=OC,OU=IT-SD,DC=na,DC=mycompany,DC=com"}]
2019-05-28 16:04:14.754 [info] <0.317.0>         LDAP template result: "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com"
2019-05-28 16:04:14.759 [info] <0.317.0>     LDAP DECISION: does perryda have tag administrator? true
2019-05-28 16:04:14.759 [info] <0.678.0> LDAP DECISION: login for perryda: ok
2019-05-28 16:04:14.759 [warning] <0.678.0> HTTP access denied: user 'perryda' - invalid credentials

Does anyone have a clueon what the problem is, and how to fix?


问:
How to test observable which belongs to another service in angular
```<code>$loggedIn = new BehaviorSubject<boolean>(false);

constructor(private authHttp: AuthenticatedHttp, private httpResponseHandlerService: HttpResponseHandlerService) {
    this.$loggedIn.next(!this.jwtHelper.isTokenExpired(this.getToken()));
    if (this.$loggedIn.getValue()) {
      this.checkAuth().subscribe((response) => {
        if (!response) {
          this.logout();
        }
      });
    }
  }
</code>```

There is $loggedIn value which is observable and i need to create a stub value which should be this.$loggedIn.next(true) in my .spec.ts.

答:
You could spy on this.jwtHelper.isTokenExpired() in order to return the value you want for your test. The only gotcha you might have is that this.jwtHelper is a private member of your service class, so it won't be that easy to spy on. In that case, the test might be suggesting you to redesign your class by creating another private method:

```<code>private isTokenExpired(): boolean {
    return this.jwtHelper.isTokenExpired(this.getToken());
}
</code>```

So then you can spy on that in your test:

```<code>spyOn(yourService, 'isTokenExpired').and.returnValue(false);
</code>```

Body:
$loggedIn = new BehaviorSubject<boolean>(false);

constructor(private authHttp: AuthenticatedHttp, private httpResponseHandlerService: HttpResponseHandlerService) {
    this.$loggedIn.next(!this.jwtHelper.isTokenExpired(this.getToken()));
    if (this.$loggedIn.getValue()) {
      this.checkAuth().subscribe((response) => {
        if (!response) {
          this.logout();
        }
      });
    }
  }

There is $loggedIn value which is observable and i need to create a stub value which should be this.$loggedIn.next(true) in my .spec.ts.

Body:
You could spy on this.jwtHelper.isTokenExpired() in order to return the value you want for your test. The only gotcha you might have is that this.jwtHelper is a private member of your service class, so it won't be that easy to spy on. In that case, the test might be suggesting you to redesign your class by creating another private method:

private isTokenExpired(): boolean {
    return this.jwtHelper.isTokenExpired(this.getToken());
}

So then you can spy on that in your test:

spyOn(yourService, 'isTokenExpired').and.returnValue(false);


问:
model/sql joins in rails 3
How can I join the objects with the models below?

```
User
has_many messages

Message
belongs_to user

Thread
has_many messages
```

I'm trying to get all threads that belong to user X. I would like to join on message.user_id = user.user_id and thread.message_id = message.message_id. I can do this using find_by_sql but I'm trying to avoid that.

Thanks

答: Assuming your Message model also belongs_to :thread, then you should be able to put a has_many :threads, :through => :messages in your User model. Then you could just do user.threads to get all the associated threads.

Title: model/sql joins in rails 3

Body:
How can I join the objects with the models below?

User
has_many messages

Message
belongs_to user

Thread
has_many messages

I'm trying to get all threads that belong to user X. I would like to join on message.user_id = user.user_id and thread.message_id = message.message_id. I can do this using find_by_sql but I'm trying to avoid that.

Thanks


问:
Apply a function to all pairs in the same group
I want to apply a function to all pairs of items in the same group e.g.

Example input:

```<code>Group  Item   Value
A      1       89
A      2       76
A      3       2
B      4       21
B      5       10
</code>```

The desired output is a vector of the function output for all items in the same group.

e.g. for arguments sake if the function was:

```<code>addnums=function(x,y){
  x+y
}
</code>```

Then the desired output would be:

165, 91, 78, 31

I have tried to do this using summarize in the dplyr package but this can only be used if the output is a single value.

答:
We can use a group by option with data.table

```<code>library(data.table)
setDT(df1)[, combn(Value, 2, FUN = sum), Group]
#   Group  V1
#1:     A 165
#2:     A  91
#3:     A  78
#4:     B  31
</code>```

If we want to use addnums from the OP's post

```<code>setDT(df1)[, combn(Value, 2, FUN = function(x) addnums(x[1], x[2])), Group]
 #  Group  V1
#1:     A 165
#2:     A  91
#3:     A  78
#4:     B  31
</code>```

Or using tidyverse

```<code>library(dplyr)
library(tidyr)
df1 %>%
  group_by(Group) %>%
  summarise(Sum = list(combn(Value, 2, FUN = sum)))  %>%
  unnest
# A tibble: 4 x 2
#  Group   Sum
#  <chr> <int>
#1 A       165
#2 A        91
#3 A        78
#4 B        31
</code>```

Using addnums

```<code>df1 %>%
 group_by(Group) %>%
 summarise(Sum = list(combn(Value, 2, FUN =
         function(x) addnums(x[1], x[2])))) %>%
 unnest
</code>```

Or using base R with aggregate

```<code>aggregate(Value ~ Group, df1, FUN = function(x) combn(x, 2, FUN = sum))
</code>```

data

```<code>df1 <- structure(list(Group = c("A", "A", "A", "B", "B"), Item = 1:5,
    Value = c(89L, 76L, 2L, 21L, 10L)), class = "data.frame", row.names = c(NA,
-5L))
</code>```

Body:
I want to apply a function to all pairs of items in the same group e.g.

Example input:

Group  Item   Value
A      1       89
A      2       76
A      3       2
B      4       21
B      5       10

The desired output is a vector of the function output for all items in the same group.

e.g. for arguments sake if the function was:

addnums=function(x,y){
  x+y
}

Then the desired output would be:

165, 91, 78, 31

I have tried to do this using summarize in the dplyr package but this can only be used if the output is a single value.

Body:
We can use a group by option with data.table

library(data.table)
setDT(df1)[, combn(Value, 2, FUN = sum), Group]
#   Group  V1
#1:     A 165
#2:     A  91
#3:     A  78
#4:     B  31

If we want to use addnums from the OP's post

setDT(df1)[, combn(Value, 2, FUN = function(x) addnums(x[1], x[2])), Group]
 #  Group  V1
#1:     A 165
#2:     A  91
#3:     A  78
#4:     B  31

Or using tidyverse

library(dplyr)
library(tidyr)
df1 %>%
  group_by(Group) %>%
  summarise(Sum = list(combn(Value, 2, FUN = sum)))  %>%
  unnest
# A tibble: 4 x 2
#  Group   Sum
#  <chr> <int>
#1 A       165
#2 A        91
#3 A        78
#4 B        31

Using addnums

df1 %>%
 group_by(Group) %>%
 summarise(Sum = list(combn(Value, 2, FUN =
         function(x) addnums(x[1], x[2])))) %>%
 unnest

Or using base R with aggregate

aggregate(Value ~ Group, df1, FUN = function(x) combn(x, 2, FUN = sum))

data

df1 <- structure(list(Group = c("A", "A", "A", "B", "B"), Item = 1:5,
    Value = c(89L, 76L, 2L, 21L, 10L)), class = "data.frame", row.names = c(NA,
-5L))


问:
Inconsistent behavior concatenating lists and tuples in python
I noticed a surprising behavior when trying to concatenate lists and tuples.

Usually, they don't mix:

```<code>(0, 1) + [2, 3]
</code>```

results in:

TypeError: can only concatenate tuple (not "list") to tuple

and, vice versa

```<code>[0, 1] + (2, 3)
</code>```

gives:

TypeError: can only concatenate list (not "tuple") to list

So far, nothing was unexpected.
However, if you use a variable assignment via "+=", the behavior for lists changes!

```<code>l = [0, 1]
l += (2, 3)
l
</code>```

gives

[0, 1, 2, 3]

But not for tuples:

```<code>t = (0, 1)
t += [2, 3]
t
</code>```

still produces an error:

TypeError: can only concatenate tuple (not "list") to tuple

Of course, there is no practical problem here, but I'm curious:
What's going on there?

答:
+= for lists doesn't expect an actual list as its right-hand operand; it will accept any iterable value. It is effectively an operator version of list.extend (which also accepts an arbitrary iterable value).

tuple doesn't define __iadd__ at all, so t += [2, 3] is just syntactic sugar for t = t + [2,3], and we've already confirmed that tuple.__add__ can't add a tuple and a list together.

Body:
I noticed a surprising behavior when trying to concatenate lists and tuples.

Usually, they don't mix:

(0, 1) + [2, 3]

results in:

TypeError: can only concatenate tuple (not "list") to tuple

and, vice versa

[0, 1] + (2, 3)

gives:

TypeError: can only concatenate list (not "tuple") to list

So far, nothing was unexpected.
However, if you use a variable assignment via "+=", the behavior for lists changes!

l = [0, 1]
l += (2, 3)
l

gives

[0, 1, 2, 3]

But not for tuples:

t = (0, 1)
t += [2, 3]
t

still produces an error:

TypeError: can only concatenate tuple (not "list") to tuple

Of course, there is no practical problem here, but I'm curious:
What's going on there?


问:
How can I consecutively implement contradicting css classes in one javascript function to create a fade in/fade out effect on a page?
I am trying to get a web page to only have one element showing at a time when the element is completely in the window. When the element is not in the window, I want to fade out, and when it comes fully into view, I want it to fade in.

As a beginner, the only thing I could think of when doing this was removing the previous class completely and adding the opposite, but no matter how I've tried to accomplish this (mostly just moving around my elements[i].style.animation = 'none' or null and changing the syntax of if statements.)

My javascript (in HTML file):

```<code><script>
window.onscroll=function(){fade()};
    function fade(){
      var elements = document.querySelectorAll('.block1,.block2');
      for (var i = 0; i < elements.length; i++) {
        if(elements[i].offsetTop>window.pageYOffset && elements[i].offsetTop+elements[i].clientHeight<window.pageYOffset+window.innerHeight){
          elements[i].style.animation='none';
          elements[i].style.animation=null;
          elements[i].className+=" pageFade";
          elements[i].style.opacity="1";
        }
        else{
          elements[i].style.animation='none';
          elements[i].style.animation=null;
          elements[i].className+=" outFade";
          elements[i].style.opacity="0";
        }
      }
    }
</script>
</code>```

My CSS

```<code>.pageFade{
  animation:reveal 1.5s ease-in-out 1;
  -webkit-animation-name:reveal 1.5s ease-out 1;
}

@keyframes reveal{
  0%{opacity:0}
  100%{opacity:1}
}

.outFade{
  animation:unreveal 1.5s ease-in-out 1;
  -webkit-animation-name:unreveal 1.5s ease-out 1;
}

@keyframes unreveal{
  0%{opacity:1}
  100%{opacity:0}
}
</code>```

(-webkit- excluded)

Only my opacity commands are in action, my "fade" animations are not working... Any advice on what I should try?

答:
use the script to add/remove a class.

Then, inside the class put the styles you want.

BLOCK 1

BLOCK 2

```

In addition, I recommend this post in order to know how-to-check-if-any-part-of-an-element-is-out-of-the-viewport-with-vanilla-js.

Hope it helps.

Body:
I am trying to get a web page to only have one element showing at a time when the element is completely in the window. When the element is not in the window, I want to fade out, and when it comes fully into view, I want it to fade in.

As a beginner, the only thing I could think of when doing this was removing the previous class completely and adding the opposite, but no matter how I've tried to accomplish this (mostly just moving around my elements[i].style.animation = 'none' or null and changing the syntax of if statements.)

My javascript (in HTML file):

My CSS

.pageFade{
  animation:reveal 1.5s ease-in-out 1;
  -webkit-animation-name:reveal 1.5s ease-out 1;
}

@keyframes reveal{
  0%{opacity:0}
  100%{opacity:1}
}

.outFade{
  animation:unreveal 1.5s ease-in-out 1;
  -webkit-animation-name:unreveal 1.5s ease-out 1;
}

@keyframes unreveal{
  0%{opacity:1}
  100%{opacity:0}
}

(-webkit- excluded)

Only my opacity commands are in action, my "fade" animations are not working... Any advice on what I should try?

Body:
use the script to add/remove a class.

Then, inside the class put the styles you want.

<div class="block">BLOCK 1</div>
<div class="block">BLOCK 2</div>

<style>
 .block {
  width: 90px; height: 150px; background: red; margin: 6px;
  transition: opacity .9s ease-in-out;
  opacity: 1;
 }
 .fade { opacity: 0; }
</style>

<script>
    function handleFade(){
  // use const in a var that is never reasigned
  const elements = document.querySelectorAll('.block');
  // using forEach is clearer and more declarative
  elements.forEach(element => {
   // add a more expressive name to the conditions
   const condition1 = element.offsetTop > window.pageYOffset;
   const condition2 = element.offsetTop + element.clientHeight <
      window.pageYOffset + window.innerHeight;
   // clean your if condition
   if(condition1 && condition2) element.classList.remove('fade');
   else element.classList.add('fade');
  });
    }

  // execute handleFade at the beginning in case user does not scroll.
    handleFade();

 // remove redundant anonymous function
    window.onscroll = handleFade;
</script>

In addition, I recommend this post in order to know how-to-check-if-any-part-of-an-element-is-out-of-the-viewport-with-vanilla-js.

Hope it helps.


问:
Writing to a file in Google Cloud ML
Within my Tensorflow Python script, I want to write some debugging information that is too verbose for stackdriver logs, so I'd like to just write to my own file. If I do:

f.write('my_file.txt', 'w+')

I don't get any errors, which implies that I have some write permissions. However, I have 0 idea how to find this file. Is it in the JOB_DIR? How can i write to a file that is accessible once the job is complete?

答:
Use the TensorFlow API to write a file directly to Google Cloud Storage:</p>

```<code>with tf.gfile.GFile("gs://bucket/some/dir/somefile", "w") as f:
        f.write(result_str)
</code>```

Title: Writing to a file in Google Cloud ML

Body:
Use the TensorFlow API to write a file directly to Google Cloud Storage:

with tf.gfile.GFile("gs://bucket/some/dir/somefile", "w") as f:
        f.write(result_str)


问:
C++: Cloud computing library: is there such a library where I don't need to write much network stuff?
I want my server app to be able to send data to be processed by a bunch of various clients, and then have the processed data returned to the server.

Ideally, I'd have some call like some_process = send_to_client_for_calculating(connection, data)

I just need to be able to send a bunch of data to a client, tell the client what to do (preferably in the same message, which can be done with an array [command, data]), and then return the data...

I'm breaking up pieces of a neural network (tis very large), and then assembling them all later.

If I need to be clearer, let me know how.

答: I'd suggest looking at gSOAP, which implements SOAP in C++, including networking.</p>


问:
Stripe STPCustomerDeserializer unable to parse customer Swift
Customer JSON returned from Stripe API unable to be parsed by using                                 STPCustomerDeserializer(jsonResponse: data), returns nil when locating the "id" field. logging the data shows that the id is not nil.

The customer object is in the exact same format as what the Stripe API returns. Error message 'The response from Stripe failed to get parsed into valid JSON."

Debugging the deserialiser shows that it is failing here:

```<code>// required fields
NSString *stripeId = [dict stp_stringForKey:@"id"];
if (!stripeId) {
    return nil; <<< returning here
}
</code>```

at >>>

```<code>- (nullable NSString *)stp_stringForKey:(NSString *)key {
    id value = self[key];
    if (value && [value isKindOfClass:[NSString class]]) {
        return value;
    }
    return nil; << returning here
}
</code>```

I have tried passing in the customer data in different formats to no avail.

I saw someone asks a similar question here The data could not be read because it isn't in the correct format JSON & SWIFT 3

```<code>["customer": {
    "account_balance" = 0;
    address = "<null>";
    balance = 0;
    created = ***;
    currency = "<null>";
    "default_source" = “***”;
    delinquent = 0;
    description = "<null>";
    discount = "<null>";
    email = “***”;
    id = "cus_***";
    "invoice_prefix" = ***;
    "invoice_settings" =     {
        "custom_fields" = "<null>";
        "default_payment_method" = "<null>";
        footer = "<null>";
    };
    livemode = 1;
    metadata =     {
    };
    name = "<null>";
    object = customer;
    phone = "<null>";
    "preferred_locales" =     (
    );
    shipping = "<null>";
    sources =     {
        data =         (
                        {
                "address_city" = "<null>";
                "address_country" = GB;
                "address_line1" = "<null>";
                "address_line1_check" = "<null>";
                "address_line2" = "<null>";
                "address_state" = "<null>";
                "address_zip" = "<null>";
                "address_zip_check" = "<null>";
                brand = Visa;
                country = GB;
                customer = "cus_***";
                "cvc_check" = pass;
                "dynamic_last4" = "<null>";
                "exp_month" = ***;
                "exp_year" = ***;
                fingerprint = ***;
                funding = debit;
                id = "card_***";
                last4 = ***;
                metadata =                 {
                };
                name = "<null>";
                object = card;
                "tokenization_method" = "<null>";
            }
        );
        "has_more" = 0;
        object = list;
        "total_count" = 1;
        url = "/v1/customers/cus_***/sources";
    };
    subscriptions =     {
        data =         (
        );
        "has_more" = 0;
        object = list;
        "total_count" = 0;
        url = "/v1/customers/cus_***/subscriptions";
    };
    "tax_exempt" = none;
    "tax_ids" =     {
        data =         (
        );
        "has_more" = 0;
        object = list;
        "total_count" = 0;
        url = "/v1/customers/cus_***/tax_ids";
    };
    "tax_info" = "<null>";
    "tax_info_verification" = "<null>";
}]
</code>```

答: I fixed it! I just needed to subscript into the json using data["customer"] as Any.

Body:
Customer JSON returned from Stripe API unable to be parsed by using                                 STPCustomerDeserializer(jsonResponse: data), returns nil when locating the "id" field. logging the data shows that the id is not nil.

The customer object is in the exact same format as what the Stripe API returns. Error message 'The response from Stripe failed to get parsed into valid JSON."

Debugging the deserialiser shows that it is failing here:

// required fields
NSString *stripeId = [dict stp_stringForKey:@"id"];
if (!stripeId) {
    return nil; <<< returning here
}

at >>>

- (nullable NSString *)stp_stringForKey:(NSString *)key {
    id value = self[key];
    if (value && [value isKindOfClass:[NSString class]]) {
        return value;
    }
    return nil; << returning here
}

I have tried passing in the customer data in different formats to no avail.

I saw someone asks a similar question here The data could not be read because it isn't in the correct format JSON & SWIFT 3

["customer": {
    "account_balance" = 0;
    address = "<null>";
    balance = 0;
    created = ***;
    currency = "<null>";
    "default_source" = “***”;
    delinquent = 0;
    description = "<null>";
    discount = "<null>";
    email = “***”;
    id = "cus_***";
    "invoice_prefix" = ***;
    "invoice_settings" =     {
        "custom_fields" = "<null>";
        "default_payment_method" = "<null>";
        footer = "<null>";
    };
    livemode = 1;
    metadata =     {
    };
    name = "<null>";
    object = customer;
    phone = "<null>";
    "preferred_locales" =     (
    );
    shipping = "<null>";
    sources =     {
        data =         (
                        {
                "address_city" = "<null>";
                "address_country" = GB;
                "address_line1" = "<null>";
                "address_line1_check" = "<null>";
                "address_line2" = "<null>";
                "address_state" = "<null>";
                "address_zip" = "<null>";
                "address_zip_check" = "<null>";
                brand = Visa;
                country = GB;
                customer = "cus_***";
                "cvc_check" = pass;
                "dynamic_last4" = "<null>";
                "exp_month" = ***;
                "exp_year" = ***;
                fingerprint = ***;
                funding = debit;
                id = "card_***";
                last4 = ***;
                metadata =                 {
                };
                name = "<null>";
                object = card;
                "tokenization_method" = "<null>";
            }
        );
        "has_more" = 0;
        object = list;
        "total_count" = 1;
        url = "/v1/customers/cus_***/sources";
    };
    subscriptions =     {
        data =         (
        );
        "has_more" = 0;
        object = list;
        "total_count" = 0;
        url = "/v1/customers/cus_***/subscriptions";
    };
    "tax_exempt" = none;
    "tax_ids" =     {
        data =         (
        );
        "has_more" = 0;
        object = list;
        "total_count" = 0;
        url = "/v1/customers/cus_***/tax_ids";
    };
    "tax_info" = "<null>";
    "tax_info_verification" = "<null>";
}]


问:
How to Import Multiple csv files into a MySQL Database
Is there a way to import multiple csv files at the same time into a MySQL database? Some sort of batch import?

I'm on Mac OSX running a MAMP server.

I have 185 csv files that I need to import into a MySQL table. I can import them individually using phpMyAdmin's import tab, but it would take a long time. Does anyone know if there is a better way?

答:
Using following shell script:</p>

```<code>for file in /directory/*.csv
do
echo "Importing file $file"
       chown mysql $file
        mysql Fortinet -u user -p'password' <<EOF

LOAD DATA LOCAL INFILE '$file'
IGNORE
INTO TABLE tablename
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;
EOF

echo "Completed importing '"$file"' "

done
</code>```

Body:
Using following shell script:

for file in /directory/*.csv
do
echo "Importing file $file"
       chown mysql $file
        mysql Fortinet -u user -p'password' <<EOF

LOAD DATA LOCAL INFILE '$file'
IGNORE
INTO TABLE tablename
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;
EOF

echo "Completed importing '"$file"' "

done


问:
How does the format mask work in Oracle APEX?
I have just been given an assignment for University on databases where I have to use Oracle APEX. For one of my columns in a report, I need to use a format mask. The format mask I need in the form of AAAA00, where A is any letter and 0 is any number.

Trying to get this to work is an issue though. I've heard the syntax for any number is 9 and I assume it's A for the letter, so wouldn't the format mask be AAAA99?

This is what I tried

I tried using it but didn't succeed. When using the form, you can still input anything. I even tried using one of the default date options for the format mask, and that didn't work either.

Any ideas on what to do?

答:
Oracle APEX Format Mask is only for the Number and Date type objects, you can't format strings using it.

Also, Format Masks are for display only, lets say I have a mask 9G9G9G9 in an Interactive Grid column, it would display numbers like : 3,1,4,1. I could go and edit my cell putting 1337, it won't change until I save my report, it will then format itself in my mask and display my number as 1,3,3,7.

I believe you are trying to restrict your user from giving an input other than in your format, (an input mask), I believe this post could help you achieve what you are trying .


问:
Issue with hasManyThrough relationship
I created four models: Item, ItemOption, ItemSize, ItemColor. My intention is to create an online shop, I want to have an  online shop, say I create an article shirt, then I can add many variables (options) of that same shirt, particulary colors, sizes... each option with it's own stock. I set these models with a hasManyThrough relationship but then I get this error:

```<code>SQLSTATE[42S22]: Column not found: 1054 Unknown column 'item_colors.item_option_id' in 'on clause' (SQL: select `item_colors`.*, `item_options`.`item_id` as `laravel_through_key` from `item_colors` inner join `item_options` on `item_options`.`id` = `item_colors`.`item_option_id` where `item_options`.`item_id` in (1))
</code>```

These are my migrations:

```<code>Schema::create('item_options', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('item_id')->index()->nullable();
            $table->foreign('item_id')->references('id')->on('items')->nullable();
            $table->unsignedInteger('item_size_id')->index()->nullable();
            $table->foreign('item_size_id')->references('id')->on('item_sizes')->nullable();
            $table->unsignedInteger('item_color_id')->index()->nullable();
            $table->foreign('item_color_id')->references('id')->on('item_colors')->nullable();
            $table->timestamps();
        });

Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('image')->nullable();
            $table->string('title');
            $table->decimal('finalPrice', 5,2);
            $table->text('body');
            $table->timestamps();
        });

Schema::create('item_colors', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('colorCode');
            $table->timestamps();
        });

Schema::create('item_sizes', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });
</code>```

And my models:

```<code>class Item extends Model
{

    protected $table = 'items';

    public function options()
    {
        return $this->hasMany(ItemOption::class);
    }

    public function sizes()
    {
        return $this->hasManyThrough(ItemSize::class, ItemOption::class);
    }

    public function colors()
    {
        return $this->hasManyThrough(ItemColor::class, ItemOption::class);
    }

}

class ItemOption extends Model
{

    protected $fillable = ['item_id', 'item_color_id', 'item_size_id', 'stock'];

    public function color()
    {
        return $this->belongsTo(ItemColor::class);
    }

    public function size()
    {
        return $this->belongsTo(ItemSize::class);
    }

}
</code>```

答:
Try with

on item_colors.id = item_options.item_color_id

Title: Issue with hasManyThrough relationship

Body:
I created four models: Item, ItemOption, ItemSize, ItemColor. My intention is to create an online shop, I want to have an  online shop, say I create an article shirt, then I can add many variables (options) of that same shirt, particulary colors, sizes... each option with it's own stock. I set these models with a hasManyThrough relationship but then I get this error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'item_colors.item_option_id' in 'on clause' (SQL: select `item_colors`.*, `item_options`.`item_id` as `laravel_through_key` from `item_colors` inner join `item_options` on `item_options`.`id` = `item_colors`.`item_option_id` where `item_options`.`item_id` in (1))

These are my migrations:

Schema::create('item_options', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('item_id')->index()->nullable();
            $table->foreign('item_id')->references('id')->on('items')->nullable();
            $table->unsignedInteger('item_size_id')->index()->nullable();
            $table->foreign('item_size_id')->references('id')->on('item_sizes')->nullable();
            $table->unsignedInteger('item_color_id')->index()->nullable();
            $table->foreign('item_color_id')->references('id')->on('item_colors')->nullable();
            $table->timestamps();
        });

Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('image')->nullable();
            $table->string('title');
            $table->decimal('finalPrice', 5,2);
            $table->text('body');
            $table->timestamps();
        });

Schema::create('item_colors', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('colorCode');
            $table->timestamps();
        });

Schema::create('item_sizes', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });

And my models:

class Item extends Model
{

    protected $table = 'items';

    public function options()
    {
        return $this->hasMany(ItemOption::class);
    }

    public function sizes()
    {
        return $this->hasManyThrough(ItemSize::class, ItemOption::class);
    }

    public function colors()
    {
        return $this->hasManyThrough(ItemColor::class, ItemOption::class);
    }

}

class ItemOption extends Model
{

    protected $fillable = ['item_id', 'item_color_id', 'item_size_id', 'stock'];

    public function color()
    {
        return $this->belongsTo(ItemColor::class);
    }

    public function size()
    {
        return $this->belongsTo(ItemSize::class);
    }

}


问:
Replace value with the value of nearest neighbor in Pandas dataframe
I have a problem with getting nearest values for some rows in pandas dataframe and fill another column with values from those rows.

data sample I have:

```<code>id   su_id  r_value  match_v

A      A1      0        1
A      A2      0        1
A      A3      70       2
A      A4      120      100
A      A5      250      3
A      A6      250      100
B      B1      0        1
B      B2      30       2
</code>```

The thing is, wherever match_v is equal to 100, I need to replace that 100 with a value from the row where r_value is the closest to r_value from origin row(where match_v is equal to 100), but just withing group (grouped by id)

Expected output

```<code>id   su_id  r_value  match_v

A      A1      0        1
A      A2      0        1
A      A3      70       2
A      A4      120      2
A      A5      250      3
A      A6      250      3
B      B1      0        1
B      B2      30       2
</code>```

I have tried with creating lead and leg with shift and then finding differences. But doesn't work well and it somehow messed up already good values.
I haven't tried anything else cause I really don't have any idea.

Any help or hint is welcomed and I if you need any additional info, I'm here.

Thanks in advance.

答:
You could define a custom function which does the calculation and substitution, and then use it with groupby and apply.

```<code>def mysubstitution(x):
    for i in x.index[x['match_v'] == 100]:
        diff = (x['r_value'] - (x['r_value'].iloc[i])).abs()
        exclude = x.index.isin([i])
        closer_idx = diff[~exclude].idxmin()
        x['match_v'].iloc[i] = x['match_v'].iloc[closer_idx]
    return x

ddf = df.groupby('id').apply(mysubstitution)
</code>```

ddf is:

```<code>  id su_id  r_value  match_v
0  A    A1        0        1
1  A    A2        0        1
2  A    A3       70        2
3  A    A4      120        2
4  A    A5      250        3
5  A    A6      250        3
6  B    B1        0        1
7  B    B2       30        2
</code>```

Body:
I have a problem with getting nearest values for some rows in pandas dataframe and fill another column with values from those rows.

data sample I have:

id   su_id  r_value  match_v

A      A1      0        1
A      A2      0        1
A      A3      70       2
A      A4      120      100
A      A5      250      3
A      A6      250      100
B      B1      0        1
B      B2      30       2

The thing is, wherever match_v is equal to 100, I need to replace that 100 with a value from the row where r_value is the closest to r_value from origin row(where match_v is equal to 100), but just withing group (grouped by id)

Expected output

id   su_id  r_value  match_v

A      A1      0        1
A      A2      0        1
A      A3      70       2
A      A4      120      2
A      A5      250      3
A      A6      250      3
B      B1      0        1
B      B2      30       2

I have tried with creating lead and leg with shift and then finding differences. But doesn't work well and it somehow messed up already good values.
I haven't tried anything else cause I really don't have any idea.

Any help or hint is welcomed and I if you need any additional info, I'm here.

Thanks in advance.

Body:
You could define a custom function which does the calculation and substitution, and then use it with groupby and apply.

def mysubstitution(x):
    for i in x.index[x['match_v'] == 100]:
        diff = (x['r_value'] - (x['r_value'].iloc[i])).abs()
        exclude = x.index.isin([i])
        closer_idx = diff[~exclude].idxmin()
        x['match_v'].iloc[i] = x['match_v'].iloc[closer_idx]
    return x

ddf = df.groupby('id').apply(mysubstitution)

ddf is:

  id su_id  r_value  match_v
0  A    A1        0        1
1  A    A2        0        1
2  A    A3       70        2
3  A    A4      120        2
4  A    A5      250        3
5  A    A6      250        3
6  B    B1        0        1
7  B    B2       30        2


问:
WorkManager Java Android Dagger2
I NEED working Workmanager in Android app with JAVA only (without Kotlin!!!).
In a project, we use just dagger2.8 (without android-dagger!) and I need to inject or access to some Injected classes like DataBase. (it injected in AppComponent).

Already tried:
https://proandroiddev.com/dagger-2-setup-with-workmanager-a-complete-step-by-step-guild-bb9f474bde37
in kotlin and rewrite in Java. - there is doesn't work in a project.
(and all close titles on StackOverflow)

And a lot of examples around web copied to each other...(all of them in Kotlin...)

I update all libraries to actual versions, update as from 3.2.1 to 3.4.1 with everything that implies.

Use: AS 3.4.1 | gp:3.4.1 | gv: 5.1.1 libraries: Dagger2, Retrofit2, OkHttp, Gson, ButterKnife, RxJava2, Room, Rabbit, WorkManager. And it is on 28 sdk
There is my worker:

```<code>private String TAG = getClass().getSimpleName();

DBModel dbModel; // this is injected room model in appComponent

public UIUpdaterWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
    super(context, workerParams);
}

@NonNull
@Override
public Result doWork() {
    Log.d(TAG, dbModel.toString()); // here is null
    return Result.success();
</code>```

I tried it in the same component and separate. And it won't work. Have null or project doesn't build.

答:
As described in the article you linked, you need to use a WorkManager's custom configuration with a custom WorkerFactory that pass an additional parameter to your Worker class:

```<code>public class UIUpdaterWorker extends Worker {
    private String TAG = getClass().getSimpleName();

    public UIUpdaterWorker(
            @NonNull Context context,
            @NonNull WorkerParameters workerParams,
            @NonNull DBModel dbModel
    ) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        Log.d(TAG, dbModel.toString());
        return Result.success();
    }
}
</code>```

You can then injected this with Dagger (DBModel in your case).

I like the new `DelegatingWorkerFactory' functionality added in WorkManager 2.1.0-alpha02 (or you can roll your own take on a similar design). I made a PoC (in Kotlin) that create a custom configuration and register a WorkerFactory for a specific worker that needs an additional parameter injected with dagger.

You can find the code on this Plaid branch, Worker and WorkerFactory are here. To provide more guidance on your specific case it would be helpful to have some more context. I can imagine that you are already injecting the dbModel in other classes.

You can do the same when you register your custom WorkerFactory, injecting the dbModel, so that you can then pass that as a parameter to the Worker class.

Title: WorkManager Java Android Dagger2

Body:
I NEED working Workmanager in Android app with JAVA only (without Kotlin!!!).
In a project, we use just dagger2.8 (without android-dagger!) and I need to inject or access to some Injected classes like DataBase. (it injected in AppComponent).

Already tried:
https://proandroiddev.com/dagger-2-setup-with-workmanager-a-complete-step-by-step-guild-bb9f474bde37
in kotlin and rewrite in Java. - there is doesn't work in a project.
(and all close titles on StackOverflow)

And a lot of examples around web copied to each other...(all of them in Kotlin...)

I update all libraries to actual versions, update as from 3.2.1 to 3.4.1 with everything that implies.

Use: AS 3.4.1 | gp:3.4.1 | gv: 5.1.1 libraries: Dagger2, Retrofit2, OkHttp, Gson, ButterKnife, RxJava2, Room, Rabbit, WorkManager. And it is on 28 sdk
There is my worker:

private String TAG = getClass().getSimpleName();

DBModel dbModel; // this is injected room model in appComponent

public UIUpdaterWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
    super(context, workerParams);
}

@NonNull
@Override
public Result doWork() {
    Log.d(TAG, dbModel.toString()); // here is null
    return Result.success();

I tried it in the same component and separate. And it won't work. Have null or project doesn't build.

Body:
As described in the article you linked, you need to use a WorkManager's custom configuration with a custom WorkerFactory that pass an additional parameter to your Worker class:

public class UIUpdaterWorker extends Worker {
    private String TAG = getClass().getSimpleName();

    public UIUpdaterWorker(
            @NonNull Context context,
            @NonNull WorkerParameters workerParams,
            @NonNull DBModel dbModel
    ) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        Log.d(TAG, dbModel.toString());
        return Result.success();
    }
}

You can then injected this with Dagger (DBModel in your case).

I like the new `DelegatingWorkerFactory' functionality added in WorkManager 2.1.0-alpha02 (or you can roll your own take on a similar design). I made a PoC (in Kotlin) that create a custom configuration and register a WorkerFactory for a specific worker that needs an additional parameter injected with dagger.

You can find the code on this Plaid branch, Worker and WorkerFactory are here. To provide more guidance on your specific case it would be helpful to have some more context. I can imagine that you are already injecting the dbModel in other classes.

You can do the same when you register your custom WorkerFactory, injecting the dbModel, so that you can then pass that as a parameter to the Worker class.


问:
call Matlab from C++ on Ubuntu
I'm trying to call Matlab function from C++ (for NS-3) in Eclipse IDE on Ubuntu 18.04. I used Matlab Library Compiler to compile the .m file into a C++ Shared Library. How do I call the function correctly?

The corresponding MATLAB Runtime has been installed and configured. At first it can't find "mclmcrrt.h", I copied the /usr/local/MATLAB/R2018b/extern/include folder and changed the library header to include "./include/mclmcrrt.h". Then the IDE can find the header files correctly.

A C++ script to test the library as follows:

```<code>/* C = A+B */
#include <iostream>
#include "libtestAdd.h"

using namespace std;

int main(){
    double A[] = {1};
    double B[] = {2};
    int nargout = 1;

    mwArray input_A (1,1,mxDOUBLE_CLASS,mxREAL);
    input_A.SetData(M,1);
    mwArray input_B (1,1,mxDOUBLE_CLASS,mxREAL);
    input_B.SetData(K,1);
    mwArray C (1,1,mxDOUBLE_CLASS,mxREAL);

    if (!mclInitializeApplication(NULL,0)){
        std::cerr << "Could not initialize the application properly."
                  << std::endl;
        return -1;
    }
    libtestAddInitialize();
    testAdd(nargout, C, input_A, input_B);
    libtestAddTerminate();

    return 1;
}
</code>```

The Matlab function is C=A+B.

The .m file has been compiled into a C++ Shared Library ("libtestAdd.so" and "libtestAdd.h"). The C++ script try to call the "testAdd" function from the library.

Matlab Runtime has been correctly installed. /etc/profile has been changed to export the follows path to LD_LIBRARY_PATH environment variable:

```<code>/usr/local/MATLAB/MATLAB_Runtime/v95/runtime/glnxa64:/usr/local/MATLAB/MATLAB_Runtime/v95/bin/glnxa64:/usr/local/MATLAB/MATLAB_Runtime/v95/sys/os/glnxa64
</code>```

The error messages as follows:

```<code>~/Desktop/libtestAdd/for_testing$ cd "/home/csrl/Desktop/libtestAdd/for_testing/" && g++ main.cpp -o main && "/home/csrl/Desktop/libtestAdd/for_testing/"main
/tmp/ccyFn7iq.o: In function `main':
main.cpp:(.text+0xde): undefined reference to `libtestAddInitialize'
main.cpp:(.text+0xf4): undefined reference to `testAdd(int, mwArray&, mwArray const&, mwArray const&)'
main.cpp:(.text+0xf9): undefined reference to `libtestAddTerminate'
/tmp/ccyFn7iq.o: In function `mwException::mwException()':
main.cpp:(.text._ZN11mwExceptionC2Ev[_ZN11mwExceptionC5Ev]+0x46): undefined reference to `mclcppCreateError_proxy'
/tmp/ccyFn7iq.o: In function `mwException::mwException(char const*)':
main.cpp:(.text._ZN11mwExceptionC2EPKc[_ZN11mwExceptionC5EPKc]+0x5a): undefined reference to `mclcppCreateError_proxy'
/tmp/ccyFn7iq.o: In function `mwException::mwException(error_info*, bool)':
main.cpp:(.text._ZN11mwExceptionC2EP10error_infob[_ZN11mwExceptionC5EP10error_infob]+0x61): undefined reference to `ref_count_obj_addref_proxy'
main.cpp:(.text._ZN11mwExceptionC2EP10error_infob[_ZN11mwExceptionC5EP10error_infob]+0x7a): undefined reference to `mclcppCreateError_proxy'
/tmp/ccyFn7iq.o: In function `mwException::~mwException()':
main.cpp:(.text._ZN11mwExceptionD2Ev[_ZN11mwExceptionD5Ev]+0x36): undefined reference to `ref_count_obj_release_proxy'
/tmp/ccyFn7iq.o: In function `mwException::what() const':
main.cpp:(.text._ZNK11mwException4whatEv[_ZNK11mwException4whatEv]+0x25): undefined reference to `error_info_get_message_proxy'
/tmp/ccyFn7iq.o: In function `mwException::raise_error()':
main.cpp:(.text._ZN11mwException11raise_errorEv[_ZN11mwException11raise_errorEv]+0x2a): undefined reference to `mclcppGetLastError_proxy'
/tmp/ccyFn7iq.o: In function `mwArray::mwArray(unsigned long, unsigned long, mxClassID, mxComplexity)':
main.cpp:(.text._ZN7mwArrayC2Emm9mxClassID12mxComplexity[_ZN7mwArrayC5Emm9mxClassID12mxComplexity]+0x52): undefined reference to `mclGetMatrix_proxy'
/tmp/ccyFn7iq.o: In function `mwArray::~mwArray()':
main.cpp:(.text._ZN7mwArrayD2Ev[_ZN7mwArrayD5Ev]+0x26): undefined reference to `ref_count_obj_release_proxy'
/tmp/ccyFn7iq.o: In function `mwArray::SetData(double*, unsigned long)':
main.cpp:(.text._ZN7mwArray7SetDataEPdm[_ZN7mwArray7SetDataEPdm]+0x2b): undefined reference to `array_ref_set_numeric_mxDouble_proxy'
collect2: error: ld returned 1 exit status
</code>```

答: You need to link with the .so file. Add it to the end of your compile command.

Title: call Matlab from C++ on Ubuntu

Body:
I'm trying to call Matlab function from C++ (for NS-3) in Eclipse IDE on Ubuntu 18.04. I used Matlab Library Compiler to compile the .m file into a C++ Shared Library. How do I call the function correctly?

The corresponding MATLAB Runtime has been installed and configured. At first it can't find "mclmcrrt.h", I copied the /usr/local/MATLAB/R2018b/extern/include folder and changed the library header to include "./include/mclmcrrt.h". Then the IDE can find the header files correctly.

A C++ script to test the library as follows:

/* C = A+B */
#include <iostream>
#include "libtestAdd.h"

using namespace std;

int main(){
    double A[] = {1};
    double B[] = {2};
    int nargout = 1;

    mwArray input_A (1,1,mxDOUBLE_CLASS,mxREAL);
    input_A.SetData(M,1);
    mwArray input_B (1,1,mxDOUBLE_CLASS,mxREAL);
    input_B.SetData(K,1);
    mwArray C (1,1,mxDOUBLE_CLASS,mxREAL);

    if (!mclInitializeApplication(NULL,0)){
        std::cerr << "Could not initialize the application properly."
                  << std::endl;
        return -1;
    }
    libtestAddInitialize();
    testAdd(nargout, C, input_A, input_B);
    libtestAddTerminate();

    return 1;
}

The Matlab function is C=A+B.

The .m file has been compiled into a C++ Shared Library ("libtestAdd.so" and "libtestAdd.h"). The C++ script try to call the "testAdd" function from the library.

Matlab Runtime has been correctly installed. /etc/profile has been changed to export the follows path to LD_LIBRARY_PATH environment variable:

/usr/local/MATLAB/MATLAB_Runtime/v95/runtime/glnxa64:/usr/local/MATLAB/MATLAB_Runtime/v95/bin/glnxa64:/usr/local/MATLAB/MATLAB_Runtime/v95/sys/os/glnxa64

The error messages as follows:

~/Desktop/libtestAdd/for_testing$ cd "/home/csrl/Desktop/libtestAdd/for_testing/" && g++ main.cpp -o main && "/home/csrl/Desktop/libtestAdd/for_testing/"main
/tmp/ccyFn7iq.o: In function `main':
main.cpp:(.text+0xde): undefined reference to `libtestAddInitialize'
main.cpp:(.text+0xf4): undefined reference to `testAdd(int, mwArray&, mwArray const&, mwArray const&)'
main.cpp:(.text+0xf9): undefined reference to `libtestAddTerminate'
/tmp/ccyFn7iq.o: In function `mwException::mwException()':
main.cpp:(.text._ZN11mwExceptionC2Ev[_ZN11mwExceptionC5Ev]+0x46): undefined reference to `mclcppCreateError_proxy'
/tmp/ccyFn7iq.o: In function `mwException::mwException(char const*)':
main.cpp:(.text._ZN11mwExceptionC2EPKc[_ZN11mwExceptionC5EPKc]+0x5a): undefined reference to `mclcppCreateError_proxy'
/tmp/ccyFn7iq.o: In function `mwException::mwException(error_info*, bool)':
main.cpp:(.text._ZN11mwExceptionC2EP10error_infob[_ZN11mwExceptionC5EP10error_infob]+0x61): undefined reference to `ref_count_obj_addref_proxy'
main.cpp:(.text._ZN11mwExceptionC2EP10error_infob[_ZN11mwExceptionC5EP10error_infob]+0x7a): undefined reference to `mclcppCreateError_proxy'
/tmp/ccyFn7iq.o: In function `mwException::~mwException()':
main.cpp:(.text._ZN11mwExceptionD2Ev[_ZN11mwExceptionD5Ev]+0x36): undefined reference to `ref_count_obj_release_proxy'
/tmp/ccyFn7iq.o: In function `mwException::what() const':
main.cpp:(.text._ZNK11mwException4whatEv[_ZNK11mwException4whatEv]+0x25): undefined reference to `error_info_get_message_proxy'
/tmp/ccyFn7iq.o: In function `mwException::raise_error()':
main.cpp:(.text._ZN11mwException11raise_errorEv[_ZN11mwException11raise_errorEv]+0x2a): undefined reference to `mclcppGetLastError_proxy'
/tmp/ccyFn7iq.o: In function `mwArray::mwArray(unsigned long, unsigned long, mxClassID, mxComplexity)':
main.cpp:(.text._ZN7mwArrayC2Emm9mxClassID12mxComplexity[_ZN7mwArrayC5Emm9mxClassID12mxComplexity]+0x52): undefined reference to `mclGetMatrix_proxy'
/tmp/ccyFn7iq.o: In function `mwArray::~mwArray()':
main.cpp:(.text._ZN7mwArrayD2Ev[_ZN7mwArrayD5Ev]+0x26): undefined reference to `ref_count_obj_release_proxy'
/tmp/ccyFn7iq.o: In function `mwArray::SetData(double*, unsigned long)':
main.cpp:(.text._ZN7mwArray7SetDataEPdm[_ZN7mwArray7SetDataEPdm]+0x2b): undefined reference to `array_ref_set_numeric_mxDouble_proxy'
collect2: error: ld returned 1 exit status


问:
How do I pass year month and date in a function to created related directory?
I have a model:

```<code>def author_document_path(instance, filename):
    return f"documents/{ instance.author.username }/%y/%m/%d/{filename}"

def author_blog_images(instance, filename):
    return f"blog-images/{instance.author.username}/%y/%m/%d/{filename}"

class Blog(models.Model):
    title = models.CharField(max_length=255)
    # other fields
    thumbnail = models.ImageField(upload_to=author_blog_images)
    documents = models.FileField(upload_to=author_document_path)
</code>```

What is the right way of passing f"blog-images/{instance.author.username}/%y/%m/%d/{filename}" in above two functions because these functions doesn't create year folders as 2019, month folder as 5 and day folder as 30. The directories look like this after uploading respected files and images:

this is not what I want I want it to look like:

Can you help me with this. Thank you so much.

答:
You first fetch the current day, and then you can obtain the year, month and day attribute, like:

```<code>from datetime import <b>date</b>

def author_blog_images(instance, filename):
    td = <b>date.today()</b>
    return f'blog-images/{instance.author.username}/{<b>td.year</b>}/{<b>td.month</b>}/{<b>td.day</b>}/{filename}'</code>```

Here td.month and td.day will not have leading zeros (so it will be printed as 2019/5/30, not 2019/05/30). You can however use leading zeros in the format string, like:

```<code>from datetime import <b>date</b>

def author_blog_images(instance, filename):
    td = <b>date.today()</b>
    return f'blog-images/{instance.author.username}/{td.year}/{td.month<b>:02d</b>}/{td.day<b>:02d</b>}/{filename}'</code>```

or we can use a specific date formatting:

```<code>from datetime import <b>date</b>

def author_blog_images(instance, filename):
    td = date.today().<b>strftime('%y/%b/%d')</b>
    return f'blog-images/{instance.author.username}/{<b>td</b>}/{filename}'</code>```

We can also use, like @BearBrown says, Django's timezone.now [Django-doc]:

```<code>from django.utils import timezone

def author_blog_images(instance, filename):
    td = <b>timezone.now()</b>.strftime('%y/%b/%d')
    return f'blog-images/{instance.author.username}/{td}/{filename}'</code>```

we can even pas an f-string as parameter to strftime, like @chepner says to replace certain parts of the before, and then let the strftime format the time with the format string produced by the f-string:

```<code>from django.utils import timezone

def author_blog_images(instance, filename):
    return timezone.now().strftime(<b>f'</b>blog-images/{instance.author.username}/%y/%b/%d/{filename}<b>'</b>)</code>```

There is however an edge case that should be taken into account here: if the instance.author.username, or the filename contains formatting parts like %d and %b, then the strftime will replace these with the day/month/... respectively. Although that is not very common, it is something to take into account.

Another thing that you should take into account is that when the author changes, or its username, the file will not be renamed, so it will still hold the name of the old author (or the old username of that author).

Body:
I have a model:

def author_document_path(instance, filename):
    return f"documents/{ instance.author.username }/%y/%m/%d/{filename}"

def author_blog_images(instance, filename):
    return f"blog-images/{instance.author.username}/%y/%m/%d/{filename}"

class Blog(models.Model):
    title = models.CharField(max_length=255)
    # other fields
    thumbnail = models.ImageField(upload_to=author_blog_images)
    documents = models.FileField(upload_to=author_document_path)

What is the right way of passing f"blog-images/{instance.author.username}/%y/%m/%d/{filename}" in above two functions because these functions doesn't create year folders as 2019, month folder as 5 and day folder as 30. The directories look like this after uploading respected files and images:

this is not what I want I want it to look like:

Can you help me with this. Thank you so much.

Body:
You first fetch the current day, and then you can obtain the year, month and day attribute, like:

from datetime import date

def author_blog_images(instance, filename):
    td = date.today()
    return f'blog-images/{instance.author.username}/{td.year}/{td.month}/{td.day}/{filename}'

Here td.month and td.day will not have leading zeros (so it will be printed as 2019/5/30, not 2019/05/30). You can however use leading zeros in the format string, like:

from datetime import date

def author_blog_images(instance, filename):
    td = date.today()
    return f'blog-images/{instance.author.username}/{td.year}/{td.month:02d}/{td.day:02d}/{filename}'

or we can use a specific date formatting:

from datetime import date

def author_blog_images(instance, filename):
    td = date.today().strftime('%y/%b/%d')
    return f'blog-images/{instance.author.username}/{td}/{filename}'

We can also use, like @BearBrown says, Django's timezone.now [Django-doc]:

from django.utils import timezone

def author_blog_images(instance, filename):
    td = timezone.now().strftime('%y/%b/%d')
    return f'blog-images/{instance.author.username}/{td}/{filename}'

we can even pas an f-string as parameter to strftime, like @chepner says to replace certain parts of the before, and then let the strftime format the time with the format string produced by the f-string:

from django.utils import timezone

def author_blog_images(instance, filename):
    return timezone.now().strftime(f'blog-images/{instance.author.username}/%y/%b/%d/{filename}')

There is however an edge case that should be taken into account here: if the instance.author.username, or the filename contains formatting parts like %d and %b, then the strftime will replace these with the day/month/... respectively. Although that is not very common, it is something to take into account.

Another thing that you should take into account is that when the author changes, or its username, the file will not be renamed, so it will still hold the name of the old author (or the old username of that author).


问:
What's the difference between the print() and the print(paste())-functions in R?
As stated in the title.

I'm working myself through the Datacamp R tutorials and I find the instructions to be....lacking.

One of the more annoying oversights is that many of the basic functions are never defined or explained, among them the print() and paste()-functions. Some of the time I can use one and some of the time the other, right now this seems totally random to me.

I have scoured the internet in search of a clear-cut answer but come up short.

I will restate my question:

When can I use the print()-function and when do I have to insert a paste-function in the parentheis, print(paste())?

答:
print

If you are at the R console then the result of any expression you type in is automatically printed so you don't need to specify print so these are the same:

```<code># same when typed into the R console

32
## [1] 32

print(32)
## [1] 32
</code>```

however, automatic printing is not done in R scripts, in R functions or in any context where it is within the body of some larger expression such as within a for or while loop.  Thus, to have 32 print from within a function use print.  In these cases nothing would have been printed had we not used print.

```<code>f <- function() {
  print(32)
}
x <- f()
## [1] 32

for(i in 1:3) print(32)
## [1] 32
## [1] 32
## [1] 32
</code>```

Note that print prints out a single object.  If you want to print out several objects you can either use several print statements or else combine the objects into a single larger object.  For example,

```<code># print A and then print B
"A"
## [1] "A"
"B"
## [1] "B"

paste("A", "B", sep = ",")  # create single char string and print it
## [1] "A,B"

c("A", "B")  # create vector of two elements and print it out
## [1] "A" "B"
</code>```

There is also cat.

```<code>x <- "A"
y <- "B"
cat("x:", x, "y:", y, "\n")
## x: A y: B
</code>```

paste

paste has nothing to do with printing. Its function is to take its arguments and create a character string out of them so paste("A", "B") creates the character string "A B".  Of course if you enter a paste command at the R console since R prints out the value of any expression typed into it, the result of the paste will be printed out.  Here are some examples of automatic printing assuming that these expressions are typed into the R console.

```<code># assume these are typed into the R console

paste("A", "B")  # R automatically prints result of paste
## [1] "A B"

paste(32)  # 32 is converted to character; then R automatically prints it
## [1] "32"
</code>```

Body:
print

If you are at the R console then the result of any expression you type in is automatically printed so you don't need to specify print so these are the same:

# same when typed into the R console

32
## [1] 32

print(32)
## [1] 32

however, automatic printing is not done in R scripts, in R functions or in any context where it is within the body of some larger expression such as within a for or while loop.  Thus, to have 32 print from within a function use print.  In these cases nothing would have been printed had we not used print.

f <- function() {
  print(32)
}
x <- f()
## [1] 32

for(i in 1:3) print(32)
## [1] 32
## [1] 32
## [1] 32

Note that print prints out a single object.  If you want to print out several objects you can either use several print statements or else combine the objects into a single larger object.  For example,

# print A and then print B
"A"
## [1] "A"
"B"
## [1] "B"

paste("A", "B", sep = ",")  # create single char string and print it
## [1] "A,B"

c("A", "B")  # create vector of two elements and print it out
## [1] "A" "B"

There is also cat.

x <- "A"
y <- "B"
cat("x:", x, "y:", y, "\n")
## x: A y: B

paste

paste has nothing to do with printing. Its function is to take its arguments and create a character string out of them so paste("A", "B") creates the character string "A B".  Of course if you enter a paste command at the R console since R prints out the value of any expression typed into it, the result of the paste will be printed out.  Here are some examples of automatic printing assuming that these expressions are typed into the R console.

# assume these are typed into the R console

paste("A", "B")  # R automatically prints result of paste
## [1] "A B"

paste(32)  # 32 is converted to character; then R automatically prints it
## [1] "32"


问:
PHP MySQL query to find closest match in database
I have a database of dealerships who are allocated the outward element of UK postcodes as their "patch". That is, typically, 1 or 2 characters, so for example a dealership in Andover will look after any enquiry from a postcode beginning DT. However some dealerships share a patch, for example, one dealership might look after GU25 where another looks after GU26.

I need to be able to identify the correct dealership using a query.

So far I've managed to extract the outward element of the postcode from an enquiry form submission.

Now I need to search through the database. However an exact match is not going to work as I need to retain the full outward element in case a patch is split.

Examples.

1) A customer enters DT1 1XL. I extract "DT1" but I need to match this with "DT".

2) A customer enters GU25 4QF. I extract "GU25" and I need to match this with GU25.

$sql = "SELECT * FROM table WHERE outward='DT1'";
```

I'd like this to essentially return, "there's no exact match but we did find DT".

Or if we searched for GU25, "there's an exact match!".

So I need to find the closest match essentially. Any ideas would be hugely appreciated.

答:
In the end I solved it with a two stage query process.

The first stage was to look for a match of the complete outward element, if that failed to yield results I used

```<code>$outward = preg_replace('/[0-9]+/', '', $outward);
</code>```

to remove the number element of the outward and ran the search again.

It'd be good if the tech existed to find the closest match but this solution wasn't too bulky and works.

Body:
I have a database of dealerships who are allocated the outward element of UK postcodes as their "patch". That is, typically, 1 or 2 characters, so for example a dealership in Andover will look after any enquiry from a postcode beginning DT. However some dealerships share a patch, for example, one dealership might look after GU25 where another looks after GU26.

I need to be able to identify the correct dealership using a query.

So far I've managed to extract the outward element of the postcode from an enquiry form submission.

Now I need to search through the database. However an exact match is not going to work as I need to retain the full outward element in case a patch is split.

Examples.

1) A customer enters DT1 1XL. I extract "DT1" but I need to match this with "DT".

2) A customer enters GU25 4QF. I extract "GU25" and I need to match this with GU25.

$sql = "SELECT * FROM table WHERE outward='DT1'";

I'd like this to essentially return, "there's no exact match but we did find DT".

Or if we searched for GU25, "there's an exact match!".

So I need to find the closest match essentially. Any ideas would be hugely appreciated.

Body:
In the end I solved it with a two stage query process.

The first stage was to look for a match of the complete outward element, if that failed to yield results I used

$outward = preg_replace('/[0-9]+/', '', $outward);

to remove the number element of the outward and ran the search again.

It'd be good if the tech existed to find the closest match but this solution wasn't too bulky and works.


问:
Google search box only works 50% of the time
I'm writing a new tab extension for Firefox, and I'd like to have a box that you can type in and have it search Google. I really don't want to use a custom Google search, just because I feel like it's inconsistent and seems cheap.

All that it's supposed to do is add your query to the end of the google URL (in the correct formatting, of course) and redirect you to that page. I have it working sometimes, but not all of the time.

Here's the code I have:

JS:

```<code>var textstring;

//Gets the text from the form
function getQ() {
    textstring = document.forms['Search'].elements[0].value;
}

//Does a Google Search
function googleSearch() {
    window.location ="http://www.google.com/search?q="+textstring;
}

//main function to run everything
function main() {
    getQ();
    googleSearch();
}
</code>```

HTML:

```<code><form name="Search" >
<div id="test1">
    <input type="text" name="q" size="31" maxlength="255" value="" />
</div>
<div id="test2">
    <input type="button" value="Google Search" onclick="main();" />
</div>
</form>
</code>```

Not sure why that last /form isn't showing up, but that's in there just so you guys know.

It works like 25% of the time. I can't figure out what's wrong with it. Could it just be that I'm testing it locally? I've been testing it in Firefox, but it seems to have the same issue in IE or Chrome, as well.

答:
Why don't you just submit to google (and avoid all the javascript) ?

```<code><form name="Search" method="get" action="http://www.google.com/search" >
</code>```

and use a normal submit button like

```<code><input type="submit" value="Google Search" />
</code>```

Since you have named the input element q and the method of the form is get it will create the correct url.

example: http://jsfiddle.net/gaby/gxun9/

Body:
I'm writing a new tab extension for Firefox, and I'd like to have a box that you can type in and have it search Google. I really don't want to use a custom Google search, just because I feel like it's inconsistent and seems cheap.

All that it's supposed to do is add your query to the end of the google URL (in the correct formatting, of course) and redirect you to that page. I have it working sometimes, but not all of the time.

Here's the code I have:

JS:

var textstring;

//Gets the text from the form
function getQ() {
    textstring = document.forms['Search'].elements[0].value;
}

//Does a Google Search
function googleSearch() {
    window.location ="http://www.google.com/search?q="+textstring;
}

//main function to run everything
function main() {
    getQ();
    googleSearch();
}

HTML:

<form name="Search" >

    <input type="text" name="q" size="31" maxlength="255" value="" />

    <input type="button" value="Google Search" onclick="main();" />

</form>

Not sure why that last /form isn't showing up, but that's in there just so you guys know.

It works like 25% of the time. I can't figure out what's wrong with it. Could it just be that I'm testing it locally? I've been testing it in Firefox, but it seems to have the same issue in IE or Chrome, as well.

Body:
Why don't you just submit to google (and avoid all the javascript) ?

<form name="Search" method="get" action="http://www.google.com/search" >

and use a normal submit button like

<input type="submit" value="Google Search" />

Since you have named the input element q and the method of the form is get it will create the correct url.

example: http://jsfiddle.net/gaby/gxun9/


问:
How to get user information while logging in Firebase
I want to store some user information related to the user id from a firebase user. I want to do this as I log in, but for some reason the user is not created, I tried to read about this but I can not find the same problem, i added .then() to the function but it still does not work. What am i not getting right?

```<code>    e.preventDefault();
    fire.auth().signInWithEmailAndPassword(this.state.email,
    this.state.password).then((user) => {
      Username = this.state.username;
      this.sendUserinfo(Username,user.uid);
    }).
    catch((error) => {
      console.log("HJÄÄÄLP" ,error);
    });
  }
</code>```

When i console.log the result i get undefined and i do not get it.

答:
signInWithEmailAndPassword. Does not return the user object. Thats why you are not able to use it.

If you want to get the information about the logged in user. For example its id. You can check the auth state.

```<code>firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // This will trigger when user logs in.
    console.log(user.uid);
  }
});
</code>```

Body:
I want to store some user information related to the user id from a firebase user. I want to do this as I log in, but for some reason the user is not created, I tried to read about this but I can not find the same problem, i added .then() to the function but it still does not work. What am i not getting right?

    e.preventDefault();
    fire.auth().signInWithEmailAndPassword(this.state.email,
    this.state.password).then((user) => {
      Username = this.state.username;
      this.sendUserinfo(Username,user.uid);
    }).
    catch((error) => {
      console.log("HJÄÄÄLP" ,error);
    });
  }

When i console.log the result i get undefined and i do not get it.

Body:
signInWithEmailAndPassword. Does not return the user object. Thats why you are not able to use it.

If you want to get the information about the logged in user. For example its id. You can check the auth state.

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // This will trigger when user logs in.
    console.log(user.uid);
  }
});