问:
Azure | ADF | How to use a String variable to lookup a Key in an Object type Parameter and retrieve its Value
I am using Azure Data Factory. I'm trying to use a String variable to lookup a Key in a JSON array and retrieve its Value. I can't seem to figure out how to do this in ADF.

Details:

I have defined a Pipeline Parameter named "obj", type "Object" and content:
{"values":{"key1":"value1","key2":"value2"}}

Parameter definition

I need to use this pipeline to find a value named "key1" and return it as "value1"; "key2" and return it as "value2"... and so on. I'm planning to use my "obj" as a dictionary, to accomplish this.

Technically speaking, If i want to find the value for key2, I can use the code below, and it will be returned "value2":

```<code>@pipeline().parameters.obj.values.key2
</code>```

What i can't figure out is how to do it using a variable (instead of hardcoded "key2").

To clear things out: I have a for-loop and, inside it, i have just a copy activity: for-each contents
The purpose of the copy activity is to copy the file named item().name, but save it in ADLS as whatever item().name translates to, according to "obj"

This is how the for-loop could be built, using Python: python-for-loop

In ADF, I tried a lot of things (using concat, replace...), but none worked. The simpliest woult be this:

```<code>@pipeline().parameters.obj.values.item().name
</code>```

but it throws the following error:

{"code":"BadRequest","message":"ErrorCode=InvalidTemplate, ErrorMessage=Unable to parse expression 'pipeline().parameters.obj.values.item().name'","target":"pipeline/name_of_the_pipeline/runid/run_id","details":null,"error":null}

So, can you please give any ideas how to define my expression?
I feel this must be really obvious, but I'm not getting there.....
Thanks.

答:
Hello fellow Pythonista!

The solution in ADF is actually to reference just as you would in Python by enclosing the 'variable' in square brackets.

I created a pipeline with a parameter obj like yours

and, as a demo, the pipeline has a single Set Variable activity that got the value for key2 into a variable.

This is documented but you need X-ray vision to spot it here.

Body:
I am using Azure Data Factory. I'm trying to use a String variable to lookup a Key in a JSON array and retrieve its Value. I can't seem to figure out how to do this in ADF.

Details:

I have defined a Pipeline Parameter named "obj", type "Object" and content:
{"values":{"key1":"value1","key2":"value2"}}

Parameter definition

I need to use this pipeline to find a value named "key1" and return it as "value1"; "key2" and return it as "value2"... and so on. I'm planning to use my "obj" as a dictionary, to accomplish this.

Technically speaking, If i want to find the value for key2, I can use the code below, and it will be returned "value2":

@pipeline().parameters.obj.values.key2

What i can't figure out is how to do it using a variable (instead of hardcoded "key2").

To clear things out: I have a for-loop and, inside it, i have just a copy activity: for-each contents
The purpose of the copy activity is to copy the file named item().name, but save it in ADLS as whatever item().name translates to, according to "obj"

This is how the for-loop could be built, using Python: python-for-loop

In ADF, I tried a lot of things (using concat, replace...), but none worked. The simpliest woult be this:

@pipeline().parameters.obj.values.item().name

but it throws the following error:

{"code":"BadRequest","message":"ErrorCode=InvalidTemplate, ErrorMessage=Unable to parse expression 'pipeline().parameters.obj.values.item().name'","target":"pipeline/name_of_the_pipeline/runid/run_id","details":null,"error":null}

So, can you please give any ideas how to define my expression?
I feel this must be really obvious, but I'm not getting there.....
Thanks.


来源: stackexchange

问:
Json to csv in Node Js
I have a JSON data which want to download it as csv file. How to achieve this in node js? Does NodeJs has some predefined modules for this?

P.S. I also want to add some formatting such as adding Headers like MONTHLY REPORT etc. adding row colors etc.

答:
I don't know about you guys, but i like small packages that just work as expected without a lot of extra configuration, try using jsonexport, works really well with objects, arrays, .. and its fast!

Install

```<code>npm i --save jsonexport
</code>```

Usage

```<code>const jsonexport = require('jsonexport');

jsonexport({lang: 'Node.js', module: 'jsonexport'}, function(err, csv){
    if (err) return console.error(err);
    console.log(csv);
});
</code>```

https://github.com/kauegimenes/jsonexport

ContentLicense: CC BY-SA 4.0

Title: Json to csv in Node Js

Body:
I don't know about you guys, but i like small packages that just work as expected without a lot of extra configuration, try using jsonexport, works really well with objects, arrays, .. and its fast!

Install

npm i --save jsonexport

Usage

const jsonexport = require('jsonexport');

jsonexport({lang: 'Node.js', module: 'jsonexport'}, function(err, csv){
    if (err) return console.error(err);
    console.log(csv);
});

https://github.com/kauegimenes/jsonexport


问:
Working with shared folders and printers in AD with PowerShell
Is there a way to manipulate permissions for using shared folders and/or printers for Active Directory Users and Groups using PowerShell ?

I've been reading about Get/Remove/Set-QADPermission but i can't seem to find an example for shared folders or printers.

Edit

Lets say I have a group witch has access to a couple of shared folders and printers. When i create another group, how can i get the access to the same folders/printers from the previous group?

Empo answered how to get access to folders (thanks again), can somebody please help me with getting access to a shared printer as well?

答:
You should work with the cmdlets Get-ACL and Set-ACL. The former returns the security descriptor of the selected provider in terms of System.Security.AccessControl. You can use the returned object to manipulate permissions and then reset the security descriptor back using the latter cmdlet.

For examples of using the cmdlet you can see:

```<code>get-help Get-ACL -examples
</code>```

You might be interested also in reading this blog post.

ContentLicense: CC BY-SA 3.0

Body:
You should work with the cmdlets Get-ACL and Set-ACL. The former returns the security descriptor of the selected provider in terms of System.Security.AccessControl. You can use the returned object to manipulate permissions and then reset the security descriptor back using the latter cmdlet.

For examples of using the cmdlet you can see:

get-help Get-ACL -examples

You might be interested also in reading this blog post.


问:
How to let a java program comunicate with a different java program
I am trying to build a system that loadbalances minecraft players across multiple servers and creates new minecraft servers. I made a plugin to loadbalance players and it works like a charm. But now I want to make a system that creates new servers based on the data it receives from the plugin.

This system is completely seperate from the plugin. But how do I make it so the plugin sends some sort of command to the server system so it knows to create a new server. I have looked into Sockets but was wondering if this is the best solution. Maybe a Rest api will work aswell?

答:
You could solve this by having one java program write to a .txt file and another program read the line then delete the command using java.io.FileWriter and java.util.Scanner. I have a github project that does this here:

https://github.com/DPS100/Diego-s-Project-Euler/blob/master/Main.java


问:
Java, convert(cast) Serializable objects to other objects
I'm using Session.save() method (in Hibernate) to persist my entity objects which returns an object of type java.io.Serializable.

The returned value is the generated primary key for the entity.

The generated primary key is of type long (or bigint).

The question is that: How can I convert or cast the returned value to long?

```<code>Serializable result = session.save(myEntityObject);

//This line of code fails.
long r = (long)result;
</code>```

答:
Above answer not worked for me.

I misunderstood the function of statelessSession.get(...).
The second parameter should be the primitive value of the primary-key if it is a non-composte key.

If the Entity has a composite key you should pass the entity itself (with filled pk) as second argument.

I was confused, because I thought that I need to pass always an entity as second argument to statelessSession.get (because it works for multi-key-entitys).

Body:
I'm using Session.save() method (in Hibernate) to persist my entity objects which returns an object of type java.io.Serializable.

The returned value is the generated primary key for the entity.

The generated primary key is of type long (or bigint).

The question is that: How can I convert or cast the returned value to long?

Serializable result = session.save(myEntityObject);

//This line of code fails.
long r = (long)result;


问:
Java8 stream with nested objects
So I'm new to Java8.  I've read about streams, but most examples are very basic.  I was wondering how it'd be done with nested objects.  Here is an example from my code:

```<code>for (Gas gas : gases) {
  resourceNodes.add(gas.getRefinery().unit());
}
</code>```

It seems like I should be able to one-line this with a stream, but I can't quite figure it out.  Could someone provide an answer with a stream.  Is there a way to use :: syntax with nested methods too?

Edit:
To clarify the example, getRefinery() returns an object of type: UnitInPool, whose method unit() returns an object of type: Unit.  resourceNodes is an ArrayList of Unit.

答:
You need to provide more code for a reasonable answer, but I'm guessing you can get a stream of units, whetever these are (and whatever getRefinery returns) this way:

```<code>gases.stream().map(Gas::getRefinery).map(???::unit)
</code>```

then you can for example collect the result with collect(Collectors.toList()) and just call resourceNodes.addAll with the collected result as parameter

Title: Java8 stream with nested objects

Body:
So I'm new to Java8.  I've read about streams, but most examples are very basic.  I was wondering how it'd be done with nested objects.  Here is an example from my code:

for (Gas gas : gases) {
  resourceNodes.add(gas.getRefinery().unit());
}

It seems like I should be able to one-line this with a stream, but I can't quite figure it out.  Could someone provide an answer with a stream.  Is there a way to use :: syntax with nested methods too?

Edit:
To clarify the example, getRefinery() returns an object of type: UnitInPool, whose method unit() returns an object of type: Unit.  resourceNodes is an ArrayList of Unit.

Body:
You need to provide more code for a reasonable answer, but I'm guessing you can get a stream of units, whetever these are (and whatever getRefinery returns) this way:

gases.stream().map(Gas::getRefinery).map(???::unit)

then you can for example collect the result with collect(Collectors.toList()) and just call resourceNodes.addAll with the collected result as parameter


问:
Optimize shuffled array - do I need to go through the whole array?
I will try to explain my issue. I'm trying to create a chessengine in PHP (just for fun :-)) The integers in the code simply returns valid moves (for simplicity - in real code it's objects and movement pattern depending on which piece it's about)

I'm looking for a way to effectively search through an array. By effectively I mean as fast as possible. Look at my comment in code below "IS it possible to break out of loop without going through all 1000 values?" I hope the comments would try to explain what I want to achieve. I'm just looking for ideas to optimize below code, not full code :-)

```<code>//This is for demonstrating
//1000 values to go through
$moves_maybe_valid = range(1,1000);
shuffle($moves_maybe_valid);

//Go through possible values
$move_checked = [];
$nr=0;
foreach($moves_maybe_valid as $mmv) {
    $move_is_valid = check_move($mmv);

    //Check if not in checked array
    if ($move_is_valid === false && !in_array($mmv, $move_checked)) {

        //Add to checked move array
        $move_checked[] = $mmv;
    }

    //IS it possible to break out of loop without
    //going through all 1000 values?
    //When all valid moves are true I want to break here
    //but I don't know when that is.

}

//for demonstration purpose only
//numbers (5,6) that returns true are unknown until an
//an actual check is done in this function
function check_move($nr) {
    if ($nr == 5 || $nr == 6) {
        return true;
    }
    return false;
}
</code>```

If I say I would generate valid moves from the beginning (based on comments below)

```<code>$valid_moves = [5,6];
</code>```

What would be the best way to break out from the loop?

答:
Under normal circumstances, the maximum number of valid moves you are likely to encounter is around 100. It can go a little higher with promotions, so if you have 9 queens maybe you get up to 200. Still, 1000 is too big.

Generating your lists of valid moves should mean you don't even need to check if they are valid. But, I imagine you are generating a list of all combinations, even if they involve passing another piece, landing on a square with your own piece, or landing outside the board domain.

I'd say, do those checks in your initial generation:

For each pawn, check the 4 possible moves and store the valid ones

For each castle or bishop, check the 14 possible in order, starting
at the piece position, go in the 4 directions until you hit an
invalid space (hitting your own piece means you've gone one too far.
Hitting opponent piece means you've hit last possible)

For queens, same as castle or bishop, but 8 directions instead of 4

For knights check the 8 possible moves for validity

For king, check the 8
possible moves for validity

Check if either of the two castle moves
are possible

For each move, you also need to make sure it doesn't leave you in check. That feature can probably be optimized so you look only from the king position out.

Once you go through all the pieces, maximum of 16, your list of moves should only contain valid moves.

Where things get expensive is your look-ahead. How many moves into the future do you want to simulate? How do you measure the value/risk of each move?

Then profile. You need a good sampling profiler to optimize and find your hotspots. Pay attention to expensive convenience functions like in_array and avoid if you can.  Loops in loops will kill performance.

Body:
I will try to explain my issue. I'm trying to create a chessengine in PHP (just for fun :-)) The integers in the code simply returns valid moves (for simplicity - in real code it's objects and movement pattern depending on which piece it's about)

I'm looking for a way to effectively search through an array. By effectively I mean as fast as possible. Look at my comment in code below "IS it possible to break out of loop without going through all 1000 values?" I hope the comments would try to explain what I want to achieve. I'm just looking for ideas to optimize below code, not full code :-)

//This is for demonstrating
//1000 values to go through
$moves_maybe_valid = range(1,1000);
shuffle($moves_maybe_valid);

//Go through possible values
$move_checked = [];
$nr=0;
foreach($moves_maybe_valid as $mmv) {
    $move_is_valid = check_move($mmv);

    //Check if not in checked array
    if ($move_is_valid === false && !in_array($mmv, $move_checked)) {

        //Add to checked move array
        $move_checked[] = $mmv;
    }

    //IS it possible to break out of loop without
    //going through all 1000 values?
    //When all valid moves are true I want to break here
    //but I don't know when that is.

}

//for demonstration purpose only
//numbers (5,6) that returns true are unknown until an
//an actual check is done in this function
function check_move($nr) {
    if ($nr == 5 || $nr == 6) {
        return true;
    }
    return false;
}

If I say I would generate valid moves from the beginning (based on comments below)

$valid_moves = [5,6];

What would be the best way to break out from the loop?


问:
How can I pass POST parameters in a URL?
Basically, I think that I can't, but I would be very happy to be proven wrong.

I am generating an HTML menu dynamically in PHP, adding one item for each current user, so that I get something like >, but I have a preference for POST over GET.

Is there a way to pass the information as a POST parameter, rather than GET from a clickable HREF link?

I am not allowed to use JavaScript.

It looks like href="https://stackoverflow.com/questions/6210900/how-to-pass-post-parameters-in-a-url#comment7231173_6210900">Rob is on to something with "You could use a button instead of an anchor and just style the button to look like a link. That way you could have your values in hidden fields inside the same form to be sent via POST"

答: This could work if the PHP script generates a form for each entry with hidden fields and the href uses JavaScript to post the form.</p>

Body:
Basically, I think that I can't, but I would be very happy to be proven wrong.

I am generating an HTML menu dynamically in PHP, adding one item for each current user, so that I get something like <a href="process_user.php?user=<user>>, but I have a preference for POST over GET.

Is there a way to pass the information as a POST parameter, rather than GET from a clickable HREF link?

I am not allowed to use JavaScript.

It looks like Rob is on to something with "You could use a button instead of an anchor and just style the button to look like a link. That way you could have your values in hidden fields inside the same form to be sent via POST"


答:
The :: syntax that you refer to is what's known as a method reference.

Assuming resourceNodes is unassigned (or empty, in which case you can remove any previous assignment) prior to the for-loop, then you'd want to first map each Gas to whatever type unit() returns, and then collect the Stream to a List:

```<code>resourceNodes = gases.stream()
                     .map(Gas::getRefinery)
                     .map(GasRefinery::unit)
                     .collect(Collectors.toList());
</code>```

Otherwise, if your goal is to simply add to resourceNodes, then it would be very similar:

```<code>resourceNodes.addAll(gases.stream()
                          .map(Gas::getRefinery)
                          .map(GasRefinery::unit)
                          .collect(Collectors.toList()));
</code>```

Title: Java8 stream with nested objects

Body:
The :: syntax that you refer to is what's known as a method reference.

Assuming resourceNodes is unassigned (or empty, in which case you can remove any previous assignment) prior to the for-loop, then you'd want to first map each Gas to whatever type unit() returns, and then collect the Stream to a List:

resourceNodes = gases.stream()
                     .map(Gas::getRefinery)
                     .map(GasRefinery::unit)
                     .collect(Collectors.toList());

Otherwise, if your goal is to simply add to resourceNodes, then it would be very similar:

resourceNodes.addAll(gases.stream()
                          .map(Gas::getRefinery)
                          .map(GasRefinery::unit)
                          .collect(Collectors.toList()));


问:
Compare column values of two dataframes using pandas
I am new to python so please go easy. I have been looking up similar threads but unable to find a neat solution for my problem:

I want to compare column values of two data frames and put the values where different in a new data frame
my data frames are below and are different in lenghth(i.e. number of rows). I want to compare Status for each SKU:

```<code>df1

SKU PRICE   Status
A   1798    0
C   1798    1
D   999     0
E   1299    1
F   999     0

df2

SKU PRICE   Status
A   1798    1
B   2997    1
C   1798    1
D   999     0
</code>```

Comparing df2 with df1 I am want to get following df3

```<code>SKU PRICE Status
A   1798  0
</code>```

I know it can be done via loops but I am hoping there is a better solution via pandas or itertools out there?

Thanks for your help

df1:

df2:

答:
This is a simple merge and filtering operation:

```<code>df1.merge(df2, on=['SKU', 'PRICE']).query('Status_x != Status_y')

  SKU  PRICE  Status_x  Status_y
0   A   1798         0         1
</code>```

Or, more accurately:

```<code>(df1.merge(df2, on=['SKU', 'PRICE'], suffixes=('', '_y'))
    .query('Status != Status_y')
    .drop('Status_y', 1))

  SKU  PRICE  Status
0   A   1798       0
</code>```

Body:
I am new to python so please go easy. I have been looking up similar threads but unable to find a neat solution for my problem:

I want to compare column values of two data frames and put the values where different in a new data frame
my data frames are below and are different in lenghth(i.e. number of rows). I want to compare Status for each SKU:

df1

SKU PRICE   Status
A   1798    0
C   1798    1
D   999     0
E   1299    1
F   999     0

df2

SKU PRICE   Status
A   1798    1
B   2997    1
C   1798    1
D   999     0

Comparing df2 with df1 I am want to get following df3

SKU PRICE Status
A   1798  0

I know it can be done via loops but I am hoping there is a better solution via pandas or itertools out there?

Thanks for your help

df1:

df2:

Body:
This is a simple merge and filtering operation:

df1.merge(df2, on=['SKU', 'PRICE']).query('Status_x != Status_y')

  SKU  PRICE  Status_x  Status_y
0   A   1798         0         1

Or, more accurately:

(df1.merge(df2, on=['SKU', 'PRICE'], suffixes=('', '_y'))
    .query('Status != Status_y')
    .drop('Status_y', 1))

  SKU  PRICE  Status
0   A   1798       0


问:
Maintain Firebase Authentication state after exiting app on iOS
I am using the following class to handle the authentication state and login for users:

```<code>class AuthenticationState: NSObject, ObservableObject {

     // MARK: Properties
    let db = Firestore.firestore()

    @Published var loggedInUser: FirebaseAuth.User?
    @Published var isAuthenticating = false
    @Published var error: NSError?

    static let shared = AuthenticationState()

    private let authState = Auth.auth()
    fileprivate var currentNonce: String?

    // MARK: Methods
    func login(with loginOption: LoginOption) {
        self.isAuthenticating = true
        self.error = nil

        switch loginOption {
            case .signInWithApple:
                handleSignInWithApple()

            case let .emailAndPassword(email, password):
                handleSignInWith(email: email, password: password)
        }
    }

    private func handleSignInWith(email: String, password: String) {
        authState.signIn(withEmail: email, password: password, completion: handleAuthResultCompletion)
    }

    func signup(email: String, password: String, passwordConfirmation: String) {
        guard password == passwordConfirmation else {
            self.error = NSError(domain: "", code: 9210, userInfo: [NSLocalizedDescriptionKey: "Password and confirmation does not match"])
            return
        }

        self.isAuthenticating = true
        self.error = nil

        authState.createUser(withEmail: email, password: password, completion: handleAuthResultCompletion)
    }

    private func handleAuthResultCompletion(auth: AuthDataResult?, error: Error?) {
        DispatchQueue.main.async {
        self.isAuthenticating = false
            if let user = auth?.user {
                self.loggedInUser = user
            } else if let error = error {
                self.error = error as NSError
            }
        }
    }

    func signout() {
        try? authState.signOut()
        self.loggedInUser = nil
    }
}

// Extension Below that handles sign in with apple, etc.
</code>```

This works great for handling a variety of sign in methods, however when the user exits the app, the logged in state no longer persists. What would be the best way to keep the user logged in after exiting the application?

答:
Firebase Authentication automatically persists the user's authentication state to their keychain, and tries to restore that state when the app is restarted.

To restore the authentication state, it needs to recheck the credentials with the server, which may take some time. That's why you need to use an auth state listener to pick up this restored state, as shown in the documentation on getting the currently signed in user:

```<code>handle = Auth.auth().addStateDidChangeListener { (auth, user) in
  // ...
}
</code>```

Body:
I am using the following class to handle the authentication state and login for users:

class AuthenticationState: NSObject, ObservableObject {

     // MARK: Properties
    let db = Firestore.firestore()

    @Published var loggedInUser: FirebaseAuth.User?
    @Published var isAuthenticating = false
    @Published var error: NSError?

    static let shared = AuthenticationState()

    private let authState = Auth.auth()
    fileprivate var currentNonce: String?

    // MARK: Methods
    func login(with loginOption: LoginOption) {
        self.isAuthenticating = true
        self.error = nil

        switch loginOption {
            case .signInWithApple:
                handleSignInWithApple()

            case let .emailAndPassword(email, password):
                handleSignInWith(email: email, password: password)
        }
    }

    private func handleSignInWith(email: String, password: String) {
        authState.signIn(withEmail: email, password: password, completion: handleAuthResultCompletion)
    }

    func signup(email: String, password: String, passwordConfirmation: String) {
        guard password == passwordConfirmation else {
            self.error = NSError(domain: "", code: 9210, userInfo: [NSLocalizedDescriptionKey: "Password and confirmation does not match"])
            return
        }

        self.isAuthenticating = true
        self.error = nil

        authState.createUser(withEmail: email, password: password, completion: handleAuthResultCompletion)
    }

    private func handleAuthResultCompletion(auth: AuthDataResult?, error: Error?) {
        DispatchQueue.main.async {
        self.isAuthenticating = false
            if let user = auth?.user {
                self.loggedInUser = user
            } else if let error = error {
                self.error = error as NSError
            }
        }
    }

    func signout() {
        try? authState.signOut()
        self.loggedInUser = nil
    }
}

// Extension Below that handles sign in with apple, etc.

This works great for handling a variety of sign in methods, however when the user exits the app, the logged in state no longer persists. What would be the best way to keep the user logged in after exiting the application?

Body:
Firebase Authentication automatically persists the user's authentication state to their keychain, and tries to restore that state when the app is restarted.

To restore the authentication state, it needs to recheck the credentials with the server, which may take some time. That's why you need to use an auth state listener to pick up this restored state, as shown in the documentation on getting the currently signed in user:

handle = Auth.auth().addStateDidChangeListener { (auth, user) in
  // ...
}


问:
How do I index through a dictionary within a dictionary?
I have a dictionary within a dictionary with this default structure:

```<code>meta_data.setdefault(date_str, {'games': 0, 'wins': 0})
</code>```

After indexing through a spreadsheet to calculate the totals per date I get a dictionary with key,values like so:

```<code>'04/01/2020': {'games': 7, 'wins': 2.0}
</code>```

I want to calculate the win ratio, and so I (think I) need to index through each date.  The calculation needs to access both key,values from the sub-dictionary.  I know this is super basic....thanks for the help.

答:
meta_data.values() returns a list of the dictionary values. In your case, this will be a list of dictionaries of the form {'games': 0, 'wins': 0}. The key is to iterate through this list of dictionaries and sum the fields you want.

You can do the iteration using a standard "C" style loop, but python prioritizes clarity and readability. Here's the pythonic (and more concise) approach:

def sum_field(field: str):
   return sum(entry[field] for entry in meta_data.values())

win_ratio = sum_field('wins') / sum_field('games')
```

Body:
I have a dictionary within a dictionary with this default structure:

meta_data.setdefault(date_str, {'games': 0, 'wins': 0})

After indexing through a spreadsheet to calculate the totals per date I get a dictionary with key,values like so:

'04/01/2020': {'games': 7, 'wins': 2.0}

I want to calculate the win ratio, and so I (think I) need to index through each date.  The calculation needs to access both key,values from the sub-dictionary.  I know this is super basic....thanks for the help.


问:
best approch among EXE and MSI
I have an application that needs to be delivered as a package.

What are the best among EXE and MSI Installers, and why?

Is there any open source tool to decompile the EXE or MSI?

答:
Many installers these days use MSI internally although they're distributed as EXE. You need an EXE to ensure all the prerequisites are installed: .NET framework, for example; and it installs the prerequisites if they're not. Then it extracts the MSI package which handles the rest of the installation.

MSI provides some advanced install features:

rollback support: if something failed during installation, it returns the system to the state before installation started.

repair: if your application stopped functioning correctly, users can use this feature to reinstall the application. It restores missing files, registry entries.

updates/upgrades: MSI handles application updates/upgrades. MSI package can be configured to automatically the previous version of the application when user starts installation of a newer version. This happens transparently to user: it looks as if only the new version is installed.

patches: MSI supports patches. When only several files of your application are modified, you can update them using a patch package (MSP). The patch will be smaller than the full package.

advertised shortcuts: you can allow users to not install some features of your application unless they're used. When users access such a feature, MSI installs the necessary files.

Though it takes some time to learn the technology.

You can do anything from an EXE file, while MSI is for installation only. Inno Setup and NSIS installation packages are distributed as exe files. They have a scripting language which describes installation steps.

WiX toolset has MSI decompiler called dark.

Title: best approch among EXE and MSI


问:
Laravel: Using only password auth for intranet app
I am trying to build password protection for my app that requires only a predefined password then would create a session that will last for 4 hours "work shift hours" before expiring.. it is intranet project that I just need to provide some level of protection..
So I will basically use DB to store the password and sessions.

All laravel docs require the laravel ui/auh to be implemented to work.. and I would like to build one of my own but I can't find where to start..

答:
I would suggest using the default Laravel authentication mechanism so you don't have to mess with session handling etc.

You can remove all the default authentication routes and views. (If you've already scaffolded your application with the auth routes, remove Auth::routes() from your routes file.)

Then add one user to the database, perhaps called "Intranet user". It doesn't matter what you set as password/email. You can create this user with artisan tinker (like this).

Create a view with a form that only asks for the password and makes a POST request to a custom controller (for example LoginController). This controller simply checks if the password is correct, and logs in the user with: Auth::login($user).

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\User;

class LoginController extends Controller
{
    public function showLoginForm()
    {
      return view("auth.login"); // Path to your login view (login form)
    }

    public function login($id)
    {
        $password = $request->input('password');

        if ($password === "your-predefined-password") {
          $user = User::findOrFail(1); // The ID of the only user in the system

          Auth::login($user); // Log the user in

          // Redirect somewhere
          return redirect()->intended('dashboard');
        }

        // If the password didn't match, redirect back the the login page
        return redirect('login')->with('error', 'Wrong password!');
    }
}
```

<p>routes.php:</p>

<pre class="lang-php prettyprint-override"><code>Route::get('/login', 'LoginController@showLoginForm');
Route::post('/user', 'LoginController@login');
</code>```

To limit the session lifetime, open up config/sessions.php and adjust the lifetime to 240 minutes (= 4 hours):

```<code>'lifetime' => env('SESSION_LIFETIME', 240),
</code>```

Alternative solution:

Instead of hardcoding the password in LoginController, create a password and email for the user. Then make a login attempt like this:

$credentials = [
  'email' => 'intranet@intranet',
  'password' => $request->input('password')
];

if (Auth::attempt($credentials)) {
  return redirect()->intended('dashboard');
}
```

Body:
I would suggest using the default Laravel authentication mechanism so you don't have to mess with session handling etc.

You can remove all the default authentication routes and views. (If you've already scaffolded your application with the auth routes, remove Auth::routes() from your routes file.)

Then add one user to the database, perhaps called "Intranet user". It doesn't matter what you set as password/email. You can create this user with artisan tinker (like this).

Create a view with a form that only asks for the password and makes a POST request to a custom controller (for example LoginController). This controller simply checks if the password is correct, and logs in the user with: Auth::login($user).

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\User;

class LoginController extends Controller
{
    public function showLoginForm()
    {
      return view("auth.login"); // Path to your login view (login form)
    }

    public function login($id)
    {
        $password = $request->input('password');

        if ($password === "your-predefined-password") {
          $user = User::findOrFail(1); // The ID of the only user in the system

          Auth::login($user); // Log the user in

          // Redirect somewhere
          return redirect()->intended('dashboard');
        }

        // If the password didn't match, redirect back the the login page
        return redirect('login')->with('error', 'Wrong password!');
    }
}

routes.php:

Route::get('/login', 'LoginController@showLoginForm');
Route::post('/user', 'LoginController@login');

To limit the session lifetime, open up config/sessions.php and adjust the lifetime to 240 minutes (= 4 hours):

'lifetime' => env('SESSION_LIFETIME', 240),

Alternative solution:

Instead of hardcoding the password in LoginController, create a password and email for the user. Then make a login attempt like this:

$credentials = [
  'email' => 'intranet@intranet',
  'password' => $request->input('password')
];

if (Auth::attempt($credentials)) {
  return redirect()->intended('dashboard');
}


答:
```<code>resourceNodes = gases.stream().map(gas -> gas.getRefinery().unit()).collect(Collectors.toList());
</code>```

Title: Java8 stream with nested objects


问:
Cron not running shell program stored on desktop
I am trying to run a shell (.sh file) program that will then run a python script making requests from a website. The python program outputs a file containing json data to my desktop and I would like this to run at 10AM Monday-Friday.

This is my .sh shell file. It runs correctly when executed manually from from terminal:

```<code>#!/bin/sh
python tester.py
</code>```

This is what I have been using to test the shell. This would run every minute and produce my output file but it is not working:

```<code>* * * * * /path/to/file/test.sh && ./test.sh
</code>```

I have tried a couple other syntax combinations as follows:

```<code>* * * * * sh /path/to/file
* * * * * sh /path/to/file/test.sh && sh test.sh
</code>```

I am aware the correct notation for a program running at 10am mon-fri would be:

```<code>0 10 * * 1-5
</code>```

Nothing seems to be working and I am at a complete loss.. Any help would be greatly appreciated.

答: It ended up being my cron did not have full disk access. I was able to change this in </p>

Body:
I am trying to run a shell (.sh file) program that will then run a python script making requests from a website. The python program outputs a file containing json data to my desktop and I would like this to run at 10AM Monday-Friday.

This is my .sh shell file. It runs correctly when executed manually from from terminal:

#!/bin/sh
python tester.py

This is what I have been using to test the shell. This would run every minute and produce my output file but it is not working:

* * * * * /path/to/file/test.sh && ./test.sh

I have tried a couple other syntax combinations as follows:

* * * * * sh /path/to/file
* * * * * sh /path/to/file/test.sh && sh test.sh

I am aware the correct notation for a program running at 10am mon-fri would be:

0 10 * * 1-5

Nothing seems to be working and I am at a complete loss.. Any help would be greatly appreciated.


问:
How to define getter and setter for an image in spring mvc
Im trying to upload an image to mysql database using spring mvc. Im able to insert the string and integer values but while uploading image it is throwing field error

Code:

dao.java file:

```<code>import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.skillsoft.model.Book;

public class BookDao {
    JdbcTemplate template;

    public void setTemplate(JdbcTemplate template) {
        this.template = template;
    }

    public List<Book> getExhibitionDetails() {
        return template.query("select * from ExhibitionDetails", new RowMapper<Book>() {
            public Book mapRow(ResultSet rs, int row) throws SQLException {
                Book book = new Book();
                book.setStudentId(rs.getInt(1));
                book.setName(rs.getString(2));
                book.setProjectName(rs.getString(3));
                book.setPhoto(rs.getBytes(4));
                return book;
            }
        });
    }

    public int save(Book p) {
        String sql = "insert into ExhibitionDetails(StudentId, Name, ProjectName, Photo) values(" + p.getStudentId() + ",'"
                + p.getName() + "','" + p.getProjectName() + "','" + p.getPhoto() + "')" ;
        return template.update(sql);
    }

</code>```

Is it right to use p.getPhoto() to get the image and insert it into the database? If not what is the alternative

Model class:

```<code>
package com.skillsoft.model;

import java.util.List;

import org.springframework.web.multipart.MultipartFile;

public class Book {

    private int studentId;
    private String name;
    private String projectName;
    private byte[] photo;

    public byte[] getPhoto() {
        return photo;
    }

    public void setPhoto(byte[] photo) {
        this.photo = photo;
    }

    public String getProjectName() {
        return projectName;
    }

    public void setProjectName(String projectName) {
        this.projectName = projectName;
    }

    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

</code>```

Controller:

import com.skillsoft.dao.BookDao;
import com.skillsoft.model.Book;

@Controller
public class BookController {

```<code>@Autowired
BookDao bookdao;

@RequestMapping("/viewbook")
public String viewbook(Model m) {
    List<Book> list = bookdao.getExhibitionDetails();
    m.addAttribute("list", list);
    return "viewbook";
}

@RequestMapping("/addform")
public String showform(Model m) {
    m.addAttribute("command", new Book());
    return "addform";
}

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@ModelAttribute("book") Book book) {
    bookdao.save(book);
    return "redirect:/viewbook";
}
</code>```

```<code>Error:

Field error in object 'book' on field 'photo': rejected value [org.springframework.web.multipart.commons.CommonsMultipartFile@2e5c8975]; codes [typeMismatch.book.photo,typeMismatch.photo,typeMismatch.[B,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [book.photo,photo]; arguments []; default message [photo]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.commons.CommonsMultipartFile' to required type 'byte[]' for property 'photo'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type 'org.springframework.web.multipart.commons.CommonsMultipartFile' to required type 'byte' for property 'photo[0]': PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor] returned inappropriate value of type 'org.springframework.web.multipart.commons.CommonsMultipartFile']]
</code>```

答:
Thanks. From the error message, it looks like you're passing a variable of type org.springframework.web.multipart.commons.CommonsMultipartFile to setPhoto(), which expects byte[]. CommonsMultipartFile has a getBytes() method, so you might try calling that to get the byte array that your model expects.

Regarding my previous comment: my instinct is that storing images in a relational database column is probably not the right design choice. If you're planning on displaying these images in a web page, it's almost certainly not the right design choice. You might consider storing the uploaded file on the file system (or a cloud service such as S3) and then just storing the path or URL to the file in your model.

Body:
Im trying to upload an image to mysql database using spring mvc. Im able to insert the string and integer values but while uploading image it is throwing field error

Code:

dao.java file:

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.skillsoft.model.Book;

public class BookDao {
    JdbcTemplate template;

    public void setTemplate(JdbcTemplate template) {
        this.template = template;
    }

    public List<Book> getExhibitionDetails() {
        return template.query("select * from ExhibitionDetails", new RowMapper<Book>() {
            public Book mapRow(ResultSet rs, int row) throws SQLException {
                Book book = new Book();
                book.setStudentId(rs.getInt(1));
                book.setName(rs.getString(2));
                book.setProjectName(rs.getString(3));
                book.setPhoto(rs.getBytes(4));
                return book;
            }
        });
    }

    public int save(Book p) {
        String sql = "insert into ExhibitionDetails(StudentId, Name, ProjectName, Photo) values(" + p.getStudentId() + ",'"
                + p.getName() + "','" + p.getProjectName() + "','" + p.getPhoto() + "')" ;
        return template.update(sql);
    }

Is it right to use p.getPhoto() to get the image and insert it into the database? If not what is the alternative

Model class:

package com.skillsoft.model;

import java.util.List;

import org.springframework.web.multipart.MultipartFile;

public class Book {

    private int studentId;
    private String name;
    private String projectName;
    private byte[] photo;

    public byte[] getPhoto() {
        return photo;
    }

    public void setPhoto(byte[] photo) {
        this.photo = photo;
    }

    public String getProjectName() {
        return projectName;
    }

    public void setProjectName(String projectName) {
        this.projectName = projectName;
    }

    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Controller:

import com.skillsoft.dao.BookDao;
import com.skillsoft.model.Book;

@Controller
public class BookController {

@Autowired
BookDao bookdao;

@RequestMapping("/viewbook")
public String viewbook(Model m) {
    List<Book> list = bookdao.getExhibitionDetails();
    m.addAttribute("list", list);
    return "viewbook";
}

@RequestMapping("/addform")
public String showform(Model m) {
    m.addAttribute("command", new Book());
    return "addform";
}

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@ModelAttribute("book") Book book) {
    bookdao.save(book);
    return "redirect:/viewbook";
}

Error:

Field error in object 'book' on field 'photo': rejected value [org.springframework.web.multipart.commons.CommonsMultipartFile@2e5c8975]; codes [typeMismatch.book.photo,typeMismatch.photo,typeMismatch.[B,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [book.photo,photo]; arguments []; default message [photo]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.commons.CommonsMultipartFile' to required type 'byte[]' for property 'photo'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type 'org.springframework.web.multipart.commons.CommonsMultipartFile' to required type 'byte' for property 'photo[0]': PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor] returned inappropriate value of type 'org.springframework.web.multipart.commons.CommonsMultipartFile']]


问:
How to execute parallel queries with PyGreSQL?
I am trying to run multiple queries in parallel with PyGreSQL and multiprocessing, but below code hangs without returning:

```<code>from pg import DB
from multiprocessing import Pool
from functools import partial

def create_query(table_name):
  return f"""create table {table_name} (id integer);
  CREATE INDEX ON {table_name} USING BTREE (id);"""

my_queries = [ create_query('foo'), create_query('bar'), create_query('baz') ]

def execute_query(conn_string, query):
  con = DB(conn_string)
  con.query(query)
  con.close()

rs_conn_string = "host=localhost port=5432 dbname=postgres user=postgres password="
pool = Pool(processes=len(my_queries))
pool.map(partial(execute_query,rs_conn_string), my_queries)
</code>```

Is there any way to make it work? Also is it possible make the 3 running queries in same "transaction" in case one query fails and the other get rolled back?

答:
One obvious problem is that you always run the pool.map, not only in the main process, but also when the interpreters used in the parallel sub-processes import the script. You should do something like this instead:

def run_all():
    with Pool(processes=len(my_queries)) as pool:
        pool.map(partial(execute_query,rs_conn_string), my_queries)

if __name__ == '__main__':
    run_all()
```

Regarding your second question, that's not possible since the transaction are per connection, which live in separate processes if you do it like that.

Asynchronous command processing might be what you want, but it is not yet supported by PyGreSQL. Psygopg + aiopg is probably better suited for doing things like that.

Body:
I am trying to run multiple queries in parallel with PyGreSQL and multiprocessing, but below code hangs without returning:

from pg import DB
from multiprocessing import Pool
from functools import partial

def create_query(table_name):
  return f"""create table {table_name} (id integer);
  CREATE INDEX ON {table_name} USING BTREE (id);"""

my_queries = [ create_query('foo'), create_query('bar'), create_query('baz') ]

def execute_query(conn_string, query):
  con = DB(conn_string)
  con.query(query)
  con.close()

rs_conn_string = "host=localhost port=5432 dbname=postgres user=postgres password="
pool = Pool(processes=len(my_queries))
pool.map(partial(execute_query,rs_conn_string), my_queries)

Is there any way to make it work? Also is it possible make the 3 running queries in same "transaction" in case one query fails and the other get rolled back?

Body:
One obvious problem is that you always run the pool.map, not only in the main process, but also when the interpreters used in the parallel sub-processes import the script. You should do something like this instead:

def run_all():
    with Pool(processes=len(my_queries)) as pool:
        pool.map(partial(execute_query,rs_conn_string), my_queries)

if __name__ == '__main__':
    run_all()

Regarding your second question, that's not possible since the transaction are per connection, which live in separate processes if you do it like that.

Asynchronous command processing might be what you want, but it is not yet supported by PyGreSQL. Psygopg + aiopg is probably better suited for doing things like that.


问:
update row striping after removing element
I am making a todo-list. And I added row striping on it, which worked.

Now when I delete a task it should update the row striping, which it does not.
After deleting an element instead of being eg. white white beige it should update to white beige white.

I have a tried a lot of things but I couldn't get anything to work. To be fair I am new to all of this and not quite experienced in working with row striping.

Is there even a way to do it?

Here is what I have so far:

loadEvents();

function loadEvents() {
  document.querySelector('form').addEventListener('submit', submit);
  document.querySelector('ul').addEventListener('click', deleteOrTick);
}

function submit(a) {
  a.preventDefault();
  let input = document.querySelector('input');
  if (input.value != '')
    addTask(input.value);
  input.value = '';
}

function addTask(task) {
  let ul = document.querySelector('ul');
  let li = document.createElement('li');
  li.innerHTML = `

${task}

    x
`;
  ul.appendChild(li);
  document.querySelector('.allToDos').style.display = 'block';
}

function deleteOrTick(a) {
  if (a.target.className == 'delete')
    deleteTask(a);
}

function deleteTask(a) {
  let remove = a.target.parentNode;
  let parentNode = remove.parentNode;
  parentNode.removeChild(remove);
  event.stopPropagation();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  list-style-type: none;
}

li {
  font-size: 1.3em;
  color: #2f4f4f;
}

.todo li:nth-child(2n) {
  background: #e0d9c3;
}

.todo {
  width: 500px;
}

.delete {
  cursor: pointer;
}</code>```

  <form action="index.html" method="post">

ToDo-List

Do what you do

      <input type="text" class="form-control" name="task" placeholder="Add a todo" aria-describedby="basic-addon2">

        <button class="btn btn-outline-secondary" type="submit">Add</button>

  </form>

            hi was geht ab

          x

```

答:
```<code>document.querySelector('li').addEventListener('click',deleteOrTick); // not ul

function deleteTask(a){
    let remove = a.currentTarget;
    let parentNode = remove.parentNode;
    parentNode.removeChild(remove);
    a.stopPropagation(); //not event
}
</code>```

Body:
I am making a todo-list. And I added row striping on it, which worked.

Now when I delete a task it should update the row striping, which it does not.
After deleting an element instead of being eg. white white beige it should update to white beige white.

I have a tried a lot of things but I couldn't get anything to work. To be fair I am new to all of this and not quite experienced in working with row striping.

Is there even a way to do it?

Here is what I have so far:

loadEvents();

function loadEvents() {
  document.querySelector('form').addEventListener('submit', submit);
  document.querySelector('ul').addEventListener('click', deleteOrTick);
}

function submit(a) {
  a.preventDefault();
  let input = document.querySelector('input');
  if (input.value != '')
    addTask(input.value);
  input.value = '';
}

function addTask(task) {
  let ul = document.querySelector('ul');
  let li = document.createElement('li');
  li.innerHTML = `

${task}

    x
`;
  ul.appendChild(li);
  document.querySelector('.allToDos').style.display = 'block';
}

function deleteOrTick(a) {
  if (a.target.className == 'delete')
    deleteTask(a);
}

function deleteTask(a) {
  let remove = a.target.parentNode;
  let parentNode = remove.parentNode;
  parentNode.removeChild(remove);
  event.stopPropagation();
}

ul {
  list-style-type: none;
}

li {
  font-size: 1.3em;
  color: #2f4f4f;
}

.todo li:nth-child(2n) {
  background: #e0d9c3;
}

.todo {
  width: 500px;
}

.delete {
  cursor: pointer;
}

  <form action="index.html" method="post">

ToDo-List

Do what you do

      <input type="text" class="form-control" name="task" placeholder="Add a todo" aria-describedby="basic-addon2">

        <button class="btn btn-outline-secondary" type="submit">Add</button>

  </form>

            hi was geht ab

          x


问:
Getting the orginal value of variable after entering a for loop
I'm making a simple script that iterates through the files in the current directories,
the $1 is for a size parameter and the others $1,$2 ..... are for the manipulated files and set for the file names.
the problem is after using the for loop the variable are losing their value and start with integers like 1,2,3, and the script doesn't work unless I use files named as 1,2,3,....
How can I keep the original values?
ex:
 ./script 50 my_first_file .....

```<code>#!/bin/bash
size=$1
allfiles=$#
shift
#here the value of the $1 is "my_first_file"
  for ((i = 1 ; i < allfiles ; i++))
  do
  #here the value of the $1 = 1
  done
</code>```

答:
Another option is just use a short hand of looping through the files.

#!/usr/bin/env bash

size=$1
shift

counter=1

for f; do
  printf '%d. %s\n' "$((counter++))" "$f"
done

printf 'size=%s\n' "$size"

```

Body:
I'm making a simple script that iterates through the files in the current directories,
the $1 is for a size parameter and the others $1,$2 ..... are for the manipulated files and set for the file names.
the problem is after using the for loop the variable are losing their value and start with integers like 1,2,3, and the script doesn't work unless I use files named as 1,2,3,....
How can I keep the original values?
ex:
 ./script 50 my_first_file .....

#!/bin/bash
size=$1
allfiles=$#
shift
#here the value of the $1 is "my_first_file"
  for ((i = 1 ; i < allfiles ; i++))
  do
  #here the value of the $1 = 1
  done


问:
Telegram bot pin a message automatically
```<code>send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage? chat_id=' + group_name + '&parse_mode=Markdown&text=' + text_to_send_in_the_group

response = requests.get(send_text)
</code>```

This code works well and I am able to forward a message into my chat. But how can I pin this latter message ? I would like to pin it to make it even more visible.

Best regards

答: When you send a message on success a message object is returned, save the message_id and the chat.id and use those values to pin the message with pinChatMessage

Body:
send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage? chat_id=' + group_name + '&parse_mode=Markdown&text=' + text_to_send_in_the_group

response = requests.get(send_text)

This code works well and I am able to forward a message into my chat. But how can I pin this latter message ? I would like to pin it to make it even more visible.

Best regards


问:
CSS align text to the right but align left on line break
I am trying to align a text to the right but when the text is to long, it should make a line break and align it to the left of the text. It's hard for me to explain, that's why I have an image of what I'm trying to do:

As you can see, the text is aligned to the right of this small div. But when a line break occurs, it is logically also aligned to the right.

I tried to wrap it in a div, where the parent is aligned to the right and the child with the text to the left. The thing is I get a result like this:

which is still wrong, since the text isn't aligned to the right then, when it breaks. Is there a way to do that?
And I don't wanna have a max width or something for the text, since if there is enough space, it should take the whole width that is available for a line.

body {
    background: #cccccc;
}

.parentDiv {
  width: 100px;
  height: 100px;
  background-color: white;
  display: flex;
  flex-direction: column;
}

.alignRight {
  margin-left: auto;
}

.alignLeft {
  text-align: left;
  padding-bottom: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parentDiv">
  <div class="alignRight">
    <div class="alignLeft">
      bla
    </div>
  </div>
  <div class="alignRight">
    <div class="alignLeft">
      testing cool text
    </div>
  </div>
</div></code>```

答:
You may need padding.

body {
    background: #cccccc;
}

.parentDiv {
  width: 200px;
  height: 100px;
  background-color: white;
  display: flex;
  flex-direction: column;
}

.alignRight {
  padding-right:50px;
  padding-left:50px;
  margin-left: auto;
}

.alignLeft {
  text-align: left;
  padding-bottom: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parentDiv">
  <div class="alignRight">
    <div class="alignLeft">
      bla
    </div>
  </div>
  <div class="alignRight">
    <div class="alignLeft">
      testing cool text
    </div>
  </div>
</div></code>```

I hope that helps! This is a very, very, very late answer.

Tip: Use the padding to help you get what you want.

Body:
I am trying to align a text to the right but when the text is to long, it should make a line break and align it to the left of the text. It's hard for me to explain, that's why I have an image of what I'm trying to do:

As you can see, the text is aligned to the right of this small div. But when a line break occurs, it is logically also aligned to the right.

I tried to wrap it in a div, where the parent is aligned to the right and the child with the text to the left. The thing is I get a result like this:

which is still wrong, since the text isn't aligned to the right then, when it breaks. Is there a way to do that?
And I don't wanna have a max width or something for the text, since if there is enough space, it should take the whole width that is available for a line.

body {
    background: #cccccc;
}

.parentDiv {
  width: 100px;
  height: 100px;
  background-color: white;
  display: flex;
  flex-direction: column;
}

.alignRight {
  margin-left: auto;
}

.alignLeft {
  text-align: left;
  padding-bottom: 5px;
}

      bla

      testing cool text

Body:
You may need padding.

body {
    background: #cccccc;
}

.parentDiv {
  width: 200px;
  height: 100px;
  background-color: white;
  display: flex;
  flex-direction: column;
}

.alignRight {
  padding-right:50px;
  padding-left:50px;
  margin-left: auto;
}

.alignLeft {
  text-align: left;
  padding-bottom: 5px;
}

<div class="parentDiv">
  <div class="alignRight">
    <div class="alignLeft">
      bla
    </div>
  </div>
  <div class="alignRight">
    <div class="alignLeft">
      testing cool text
    </div>
  </div>
</div>

I hope that helps! This is a very, very, very late answer.

Tip: Use the padding to help you get what you want.


问:
Does returned struct of localtime() need to be freed?
```<code>struct tm *localtime(const time_t *timep);
</code>```

I checked man localtime but there's no words on whether it's my duty to clean it after using.

And in fact I have many similar doubts on functions returning a pointer, how do you determine it should be freed or not ?

答:
This information should be in the man page - my localtime man page says:

The return value points to a
  statically allocated struct...

Statically allocated objects should not be passed to free(), so this is your answer - no, you should not free the return value of localtime().

The only way to tell in the general case is to consult the documentation or implementation of the function in question.

Body:
struct tm *localtime(const time_t *timep);

I checked man localtime but there's no words on whether it's my duty to clean it after using.

And in fact I have many similar doubts on functions returning a pointer, how do you determine it should be freed or not ?


问:
Reliably check if there are dirty or untracked files in working set
I'm trying to write some scripts for doing some simple housekeeping tasks in mercurial and one of the things I frequently need to do is check if the working set is "empty" (depending on context, that could mean untracked files or modified tracked files).

The hg status command exits with exit status 0 unless there was an internal error, in which case it exits with exit status 255.

If a few of my scripts, I'm doing something silly like capturing the output of the hg status command and checking whether it's empty or not.

In other cases I'm checking the exit status of hg id -i | grep -qvF + to check whether there are dirty tracked files.

Both of these seem a little brittle. Are there dedicated subcommands for "querying" the repository to see if there are "untracked files" or "dirty tracked files" or "removed files" or various other interesting things in the working set?

答:
```<code>test -z "$(hg status -mard --template x)" && echo clean || echo dirty
</code>```

Seems to work

Body:
test -z "$(hg status -mard --template x)" && echo clean || echo dirty

Seems to work


问:
many functions and many variables
for the seek of simplicity I will only use three functions as follows. I need to evaluate the functions at first and later on use these results for other calculations. I would like to create an interface such that I only provide the value of input variable x and then easily calculate all the functions. I would like to use a class for this purpose. How can I do this with OOP?</p>

```<code>def function1(x):
    y=x+2
    z= x-2
    return y,z

value1=function1(x)
def function2 (x):
    y1= value1[0] *10 # value1 can be replaced by function1(x)
    z1= value1[1] +5  # but the aim and it will work but i have so many functions
    return y1,z1
def main(x):
    print(f1(x),f2(x))

main(2)
</code>```

答:
function2 can be simplified a little bit by unpacking the tuple from function1 into two variables.

```<code>def function2(x):
    y, z = function1(x)
    return y * 10, z + 5
</code>```

Title: many functions and many variables

Body:
for the seek of simplicity I will only use three functions as follows. I need to evaluate the functions at first and later on use these results for other calculations. I would like to create an interface such that I only provide the value of input variable x and then easily calculate all the functions. I would like to use a class for this purpose. How can I do this with OOP?

def function1(x):
    y=x+2
    z= x-2
    return y,z

value1=function1(x)
def function2 (x):
    y1= value1[0] *10 # value1 can be replaced by function1(x)
    z1= value1[1] +5  # but the aim and it will work but i have so many functions
    return y1,z1
def main(x):
    print(f1(x),f2(x))

main(2)

Body:
function2 can be simplified a little bit by unpacking the tuple from function1 into two variables.

def function2(x):
    y, z = function1(x)
    return y * 10, z + 5


问:
How do you make a countdown bot in discord using python
I am trying to make a bot that if you told it to make a countdown to e.g. 7:00 pm, it would make a countdown to that time, then send a message e.g. @everyone countdown finished and I want it if the user typed cancel, the countdown cancels

Please note that I want it to be like an alarm clock, not a timer

I already made everything except the countdown and the message after the countdown

here is the code for now

```<code>import discord
from discord.ext import commands
from discord.ext import tasks

client = commands.Bot(command_prefix = "m!")

@client.command(aliases = ["countdown"])
async def countdown_at(ctx, time):
    await ctx.send(f"OK\countdown made to {time}")
</code>```

答:
I figured out how to make it,
here it is:

```<code>@bot.command()
async def alarm(ctx, time)
    now = datetime.now()
    mtimeA = time
    mtimeB = mtimeA.split(":")
    hr = int(mtimeB[0])
    min = int(mtimeB[1])
    secsleft = int((timedelta(hours=24) - (now - now.replace(hour=hr, minute=min, second=0, microsecond=0))).total_seconds() % (24 * 3600))
    await ctx.send(f"OK\nAlarm set to {time}")
    def check(message):
        return message.author == ctx.author and message.content.lower() == "cancel alarm"
    try:
        await bot.wait_for("message", check=check, timeout=secsleft)
        await ctx.send("Alarm cancelled")
    except:
        await ctx.send(f"{ctx.author.mention} alarm finished")

</code>```

All this does is it takes the time, ex. "19:20", and splits it into 2 values "[19, 20]". Then it converts the time given into seconds with timedelta. Lastly, it waits for "cancel alarm", if it didn't get this message and the alarm is done, it sends a message notifying the user that his alarm is done

Body:
I am trying to make a bot that if you told it to make a countdown to e.g. 7:00 pm, it would make a countdown to that time, then send a message e.g. @everyone countdown finished and I want it if the user typed cancel, the countdown cancels

Please note that I want it to be like an alarm clock, not a timer

I already made everything except the countdown and the message after the countdown

here is the code for now

import discord
from discord.ext import commands
from discord.ext import tasks

client = commands.Bot(command_prefix = "m!")

@client.command(aliases = ["countdown"])
async def countdown_at(ctx, time):
    await ctx.send(f"OK\countdown made to {time}")

Body:
I figured out how to make it,
here it is:

@bot.command()
async def alarm(ctx, time)
    now = datetime.now()
    mtimeA = time
    mtimeB = mtimeA.split(":")
    hr = int(mtimeB[0])
    min = int(mtimeB[1])
    secsleft = int((timedelta(hours=24) - (now - now.replace(hour=hr, minute=min, second=0, microsecond=0))).total_seconds() % (24 * 3600))
    await ctx.send(f"OK\nAlarm set to {time}")
    def check(message):
        return message.author == ctx.author and message.content.lower() == "cancel alarm"
    try:
        await bot.wait_for("message", check=check, timeout=secsleft)
        await ctx.send("Alarm cancelled")
    except:
        await ctx.send(f"{ctx.author.mention} alarm finished")

All this does is it takes the time, ex. "19:20", and splits it into 2 values "[19, 20]". Then it converts the time given into seconds with timedelta. Lastly, it waits for "cancel alarm", if it didn't get this message and the alarm is done, it sends a message notifying the user that his alarm is done


问:
Error in retrieving collection from firebase react native
Hi i am new to react native and having trouble in retrieving the list from firebase collection. but when i use the following code it returns an error:

 Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of children, use an array instead.
Please help me with the solution as i know am i doing something wrong here to this.state.items

```<code>firebase.firestore().collection('myCollection').get().then(x => {
              x.docs.map(doc => {
                this.state.items.push(doc.data());
              });
              this.state.items.map(value => {
                console.log('my val',value);

              })
            })
</code>```

答:
To manipulate your state, you need to call this.setState() and set its new value. Something like :

this.setState({...doc.data()});

Now, this error often come from the fact that the higher parent node of your jsx (the 'html' returned by your component) have more than 1 child. something like :

```<code>const App = () => {

return (
  <div>a node</div>
  <div>another node</div>
}
</code>```

if it's the case (happen because of a map sometimes), then just wrap your content with a div, like :

```<code>const App = () => {

return (
 <div>
  <div>a node</div>
  <div>another node</div>
 </div>
}
</code>```

Body:
Hi i am new to react native and having trouble in retrieving the list from firebase collection. but when i use the following code it returns an error:

 Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of children, use an array instead.
Please help me with the solution as i know am i doing something wrong here to this.state.items

firebase.firestore().collection('myCollection').get().then(x => {
              x.docs.map(doc => {
                this.state.items.push(doc.data());
              });
              this.state.items.map(value => {
                console.log('my val',value);

              })
            })

Body:
To manipulate your state, you need to call this.setState() and set its new value. Something like :

this.setState({...doc.data()});

Now, this error often come from the fact that the higher parent node of your jsx (the 'html' returned by your component) have more than 1 child. something like :

const App = () => {

return (
  <div>a node</div>
  <div>another node</div>
}

if it's the case (happen because of a map sometimes), then just wrap your content with a div, like :

const App = () => {

return (
 <div>
  <div>a node</div>
  <div>another node</div>
 </div>
}


问:
Display paragraph
I insert the below paragraph into the database .However while displaying it is displayed as (which is not desired one):

The use of this website is subject to the following terms of use: • The content of the pages of this website is for your general information and use only. It is subject to change without notice. • Neither we nor any third parties provide any warranty or guarantee as to the accuracy,

Desired paragraph view:
The use of this website is subject to the following terms of use:

•   The content of the pages of this website is for your general information and use only. It is subject to change without notice.
•   Neither we nor any third parties provide any warranty or guarantee as to the accuracy.

How can we achieve this in asp.net/C#

答:
Use the paragraph tag.</p>

```<code><p>The use of this website is subject to the following terms of use:</p>

<p>• The content of the pages of this website is for your general information and use only. It is subject to change without notice. • Neither we nor any third parties provide any warranty or guarantee as to the accuracy.</p>
</code>```

Title: Display paragraph

Body:
Use the paragraph tag.

<p>The use of this website is subject to the following terms of use:</p>

<p>• The content of the pages of this website is for your general information and use only. It is subject to change without notice. • Neither we nor any third parties provide any warranty or guarantee as to the accuracy.</p>


问:
Nan in summary histogram
My program will face this some times(not every run will face this..), then if face this I can always reproduce this error loading from the last model I have saved before program crash due to nan.
When rerun from this model, first train process seems fine using the model to generate loss(I have printed loss and shows no problem), but after applying gradients, the values of embedding variables will turn to Nan.

So what is the root cause of the nan problem? Confused as not know how to debug further and this program with same data and params will mostly run ok and only face this problem during some run..

```<code>Loading existing model from: /home/gezi/temp/image-caption//model.flickr.rnn2.nan/model.ckpt-18000
Train from restored model: /home/gezi/temp/image-caption//model.flickr.rnn2.nan/model.ckpt-18000
I tensorflow/core/common_runtime/gpu/pool_allocator.cc:245] PoolAllocator: After 5235 get requests, put_count=4729 evicted_count=1000 eviction_rate=0.211461 and unsatisfied allocation rate=0.306781
I tensorflow/core/common_runtime/gpu/pool_allocator.cc:257] Raising pool_size_limit_ from 100 to 110
2016-10-04 21:45:39 epoch:1.87 train_step:18001 duration:0.947 elapsed:0.947 train_avg_metrics:['loss:0.527']  ['loss:0.527']
2016-10-04 21:45:39 epoch:1.87 eval_step: 18001 duration:0.001 elapsed:0.948 ratio:0.001
W tensorflow/core/framework/op_kernel.cc:968] Invalid argument: Nan in summary histogram for: rnn/HistogramSummary_1
     [[Node: rnn/HistogramSummary_1 = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](rnn/HistogramSummary_1/tag, rnn/image_text_sim/image_mlp/w_h/read/_309)]]
W tensorflow/core/framework/op_kernel.cc:968] Invalid argument: Nan in summary histogram for: rnn/HistogramSummary_1
     [[Node: rnn/HistogramSummary_1 = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](rnn/HistogramSummary_1/tag, rnn/image_text_sim/image_mlp/w_h/read/_309)]]
W tensorflow/core/framework/op_kernel.cc:968] Invalid argument: Nan in summary histogram for: rnn/HistogramSummary_1
     [[Node: rnn/HistogramSummary_1 = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](rnn/HistogramSummary_1/tag, rnn/image_text_sim/image_mlp/w_h/read/_309)]]
W tensorflow/core/framework/op_kernel.cc:968] Invalid argument: Nan in summary histogram for: rnn/HistogramSummary_1
     [[Node: rnn/HistogramSummary_1 = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](rnn/HistogramSummary_1/tag, rnn/image_text_sim/image_mlp/w_h/read/_309)]]
W tensorflow/core/framework/op_kernel.cc:968] Invalid argument: Nan in summary histogram for: rnn/HistogramSummary_1
     [[Node: rnn/HistogramSummary_1 = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](rnn/HistogramSummary_1/tag, rnn/image_text_sim/image_mlp/w_h/read/_309)]]
Traceback (most recent call last):
  File "./train.py", line 308, in <module>
    tf.app.run()
</code>```

答:
If you are using tensorflow.keras.layers.Masking and one or more input features happen to be masked for all inputs in a batch, then you can get this error.

Similar to najeeb khan's case, but triggered differently.

This makes sense because when tensorflow calls _log_weights from on_epoch_end, some weights related to the input features that were always masked are actually still NaN.

For me the solution was to explicitly load weights (via tensorflow.keras.models.load_model)

Title: Nan in summary histogram

Body:
My program will face this some times(not every run will face this..), then if face this I can always reproduce this error loading from the last model I have saved before program crash due to nan.
When rerun from this model, first train process seems fine using the model to generate loss(I have printed loss and shows no problem), but after applying gradients, the values of embedding variables will turn to Nan.

So what is the root cause of the nan problem? Confused as not know how to debug further and this program with same data and params will mostly run ok and only face this problem during some run..

Loading existing model from: /home/gezi/temp/image-caption//model.flickr.rnn2.nan/model.ckpt-18000
Train from restored model: /home/gezi/temp/image-caption//model.flickr.rnn2.nan/model.ckpt-18000
I tensorflow/core/common_runtime/gpu/pool_allocator.cc:245] PoolAllocator: After 5235 get requests, put_count=4729 evicted_count=1000 eviction_rate=0.211461 and unsatisfied allocation rate=0.306781
I tensorflow/core/common_runtime/gpu/pool_allocator.cc:257] Raising pool_size_limit_ from 100 to 110
2016-10-04 21:45:39 epoch:1.87 train_step:18001 duration:0.947 elapsed:0.947 train_avg_metrics:['loss:0.527']  ['loss:0.527']
2016-10-04 21:45:39 epoch:1.87 eval_step: 18001 duration:0.001 elapsed:0.948 ratio:0.001
W tensorflow/core/framework/op_kernel.cc:968] Invalid argument: Nan in summary histogram for: rnn/HistogramSummary_1
     [[Node: rnn/HistogramSummary_1 = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](rnn/HistogramSummary_1/tag, rnn/image_text_sim/image_mlp/w_h/read/_309)]]
W tensorflow/core/framework/op_kernel.cc:968] Invalid argument: Nan in summary histogram for: rnn/HistogramSummary_1
     [[Node: rnn/HistogramSummary_1 = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](rnn/HistogramSummary_1/tag, rnn/image_text_sim/image_mlp/w_h/read/_309)]]
W tensorflow/core/framework/op_kernel.cc:968] Invalid argument: Nan in summary histogram for: rnn/HistogramSummary_1
     [[Node: rnn/HistogramSummary_1 = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](rnn/HistogramSummary_1/tag, rnn/image_text_sim/image_mlp/w_h/read/_309)]]
W tensorflow/core/framework/op_kernel.cc:968] Invalid argument: Nan in summary histogram for: rnn/HistogramSummary_1
     [[Node: rnn/HistogramSummary_1 = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](rnn/HistogramSummary_1/tag, rnn/image_text_sim/image_mlp/w_h/read/_309)]]
W tensorflow/core/framework/op_kernel.cc:968] Invalid argument: Nan in summary histogram for: rnn/HistogramSummary_1
     [[Node: rnn/HistogramSummary_1 = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](rnn/HistogramSummary_1/tag, rnn/image_text_sim/image_mlp/w_h/read/_309)]]
Traceback (most recent call last):
  File "./train.py", line 308, in <module>
    tf.app.run()


问:
Border Gradient with transperent end
I have 4 div with border-radius 50%. They are circles. Between second and third I need to make such as speedometer with gradient. The end of gradient must be transperent and all circles must be transperent too.

Code.

.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.circle {
  border-radius: 50%;
  display: flex;
}

.first-circle {
  height: 400px;
  width: 400px;
  border: 2px solid gray;
}

.second-circle {
  height: 350px;
  width: 350px;
}

.third-circle {
  height: 300px;
  width: 300px;
  border: 29px solid gray;
}

.forth-circle {
  height: 250px;
  width: 250px;
  border: 2px solid gray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="background-color: aqua;" clss="flex-center">
  <div class="first-circle circle flex-center">
    <div class="second-circle circle flex-center">
      <div class="third-circle circle flex-center">
        <div class="forth-circle circle flex-center">
        </div>
      </div>
    </div>
  </div>
</div></code>```

How the gray border to make the color gradient with transperent in the end(for example end on 3 hours by clock board)?

答:
Basically for doing things that end transparently you can use somthing like this background-image: linear-gradient(to right, red , #ffffff00);,
about the circles check this link

Title: Border Gradient with transperent end

Body:
I have 4 div with border-radius 50%. They are circles. Between second and third I need to make such as speedometer with gradient. The end of gradient must be transperent and all circles must be transperent too.

Code.

.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.circle {
  border-radius: 50%;
  display: flex;
}

.first-circle {
  height: 400px;
  width: 400px;
  border: 2px solid gray;
}

.second-circle {
  height: 350px;
  width: 350px;
}

.third-circle {
  height: 300px;
  width: 300px;
  border: 29px solid gray;
}

.forth-circle {
  height: 250px;
  width: 250px;
  border: 2px solid gray;
}

How the gray border to make the color gradient with transperent in the end(for example end on 3 hours by clock board)?


问:
How to implement fancy scroll bar for multiline textbox?
I want to implement a fancy scroll bar for a multiline textbox like the picture below:

Any ideas for that fancy scroll bar?

P/S: I want vb.net solution.

答:
This code is very chunky and frustrating to work with but it's working

This is a fully drawn GDI+ custom
  scrollbar control class. All of its
  drawing methods are overrideable,
  allowing developers to paint it
  however they choose.

http://www.codeproject.com/KB/miscctrl/corescrollbar.aspx


问:
Gatsby markdown blockquote looks the same, isn't working, isn't quoted, isn't a block
I have my markdown file, and apparently this is how you're supposed to style blockquotes, with a > in front

```<code>-----------------------
title: some title
img: some img
-------------------------

A paragraph

> This is an example of a block quote

This is an example of some **bolded text**
</code>```

But the block-quote looks just like all the other regular text

How can I get my block-quote to look like it does in the link I provided?

I included my gatsby-config.js and gatsby-node.js file in case they provide any helpful information

gatsby-config.js

const path = require(`path`)

module.exports = {
  siteMetadata: {
    title: `my title`,
    description: `My description`,
    author: `Me`,
    authorDescription: "Me",
    themeColor: "#111111",
    siteUrl: "example.com",
    image: "my_image.png"
  },
  plugins: [
    {
      resolve: "gatsby-plugin-web-font-loader",
      options: {
        google: {
          families: ["Mansalva", "Playfair Display", "Source Sans Pro"],
        },
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/assets/images`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: path.join(__dirname, `src/assets/images`),
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/content/markdown/`,
        name: `markdown-pages`,
      },
    },
    {
      resolve: `gatsby-plugin-create-client-paths`,
      options: { prefixes: [
        `/contact/*`,
        `/partners/*`,
        `/publications/*`
      ] },
    },
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#fff`,
        theme_color: `#542C85`,
        display: `minimal-ui`,
        icon: `src/assets/images/gatsby-icon.png`,
      },
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          'gatsby-remark-relative-images',
          {
            resolve: `gatsby-remark-images`,
            options: {
              linkImagesToOriginal: false,
            },
          },
        ],
      },
    },
    {
      resolve: 'gatsby-plugin-root-import',
      options: {
        "components": path.join(__dirname, "src/components"),
        // "layouts": path.join(__dirname, "src/layouts"),
        "styles": path.join(__dirname, "src/assets/styles"),
        "types": path.join(__dirname, "src/types"),
        "enums": path.join(__dirname, "src/enums"),
        "interfaces": path.join(__dirname, "src/interfaces"),
        "data": path.join(__dirname, 'src/data'),
        "pages": path.join(__dirname, 'src/pages')
      }
    },
    `gatsby-plugin-react-helmet`,
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    `gatsby-plugin-typescript`,
    `gatsby-plugin-sass`,
    `gatsby-plugin-offline`,
    `gatsby-plugin-graphql-loader`
  ],
}```
</div>
</div>
</p>

<p><strong>gatsby-node.js</strong></p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const { createFilePath } = require(`gatsby-source-filesystem`)
const { fmImagesToRelative } = require('gatsby-remark-relative-images');
const path = require("path")

const replacePath = path => (path === `/` ? path : path.replace(/\/$/, ``))

exports.createPages = async ({ actions: { createPage }, graphql }) => {
  const postTemplate = path.resolve(`src/components/Article/index.tsx`)

  const result = await graphql(`
    {
      allMarkdownRemark(
        sort: { order: DESC, fields: [frontmatter___date] }

      ) {
        edges {
          node {
            fields {
              slug
            }
          }
        }
      }
    }
  `)

  if (result.errors) {
    return Promise.reject(result.errors)
  }

  result.data.allMarkdownRemark.edges.forEach(({ node }) => {
    createPage({
      path: replacePath(node.fields.slug),
      component: postTemplate,
    })
  })
}

exports.onCreateNode = ({ node, getNode, actions }) => {
  fmImagesToRelative(node)
  if (node.internal.type === `MarkdownRemark`)
    actions.createNodeField({
      node,
      name: `slug`,
      value: replacePath(createFilePath({ node, getNode, basePath: `pages` })),
    })

}</code>```

答:
The example has css styles applied. Specifically:

```<code>blockquote {
    background: #f9f9f9;
    border-left: 10px solid #ccc;
    margin: 1.5em 10px;
    padding: 1em 10px .1em 10px;
    quotes: "\201C""\201D""\2018""\2019";
}
</code>```

Use similar css to make blockquotes look the same where you display it.

Body:
I have my markdown file, and apparently this is how you're supposed to style blockquotes, with a > in front

-----------------------
title: some title
img: some img
-------------------------

A paragraph

> This is an example of a block quote

This is an example of some **bolded text**

But the block-quote looks just like all the other regular text

How can I get my block-quote to look like it does in the link I provided?

I included my gatsby-config.js and gatsby-node.js file in case they provide any helpful information

gatsby-config.js

const path = require(`path`)

module.exports = {
  siteMetadata: {
    title: `my title`,
    description: `My description`,
    author: `Me`,
    authorDescription: "Me",
    themeColor: "#111111",
    siteUrl: "example.com",
    image: "my_image.png"
  },
  plugins: [
    {
      resolve: "gatsby-plugin-web-font-loader",
      options: {
        google: {
          families: ["Mansalva", "Playfair Display", "Source Sans Pro"],
        },
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/assets/images`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: path.join(__dirname, `src/assets/images`),
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/content/markdown/`,
        name: `markdown-pages`,
      },
    },
    {
      resolve: `gatsby-plugin-create-client-paths`,
      options: { prefixes: [
        `/contact/*`,
        `/partners/*`,
        `/publications/*`
      ] },
    },
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#fff`,
        theme_color: `#542C85`,
        display: `minimal-ui`,
        icon: `src/assets/images/gatsby-icon.png`,
      },
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          'gatsby-remark-relative-images',
          {
            resolve: `gatsby-remark-images`,
            options: {
              linkImagesToOriginal: false,
            },
          },
        ],
      },
    },
    {
      resolve: 'gatsby-plugin-root-import',
      options: {
        "components": path.join(__dirname, "src/components"),
        // "layouts": path.join(__dirname, "src/layouts"),
        "styles": path.join(__dirname, "src/assets/styles"),
        "types": path.join(__dirname, "src/types"),
        "enums": path.join(__dirname, "src/enums"),
        "interfaces": path.join(__dirname, "src/interfaces"),
        "data": path.join(__dirname, 'src/data'),
        "pages": path.join(__dirname, 'src/pages')
      }
    },
    `gatsby-plugin-react-helmet`,
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    `gatsby-plugin-typescript`,
    `gatsby-plugin-sass`,
    `gatsby-plugin-offline`,
    `gatsby-plugin-graphql-loader`
  ],
}

gatsby-node.js

const { createFilePath } = require(`gatsby-source-filesystem`)
const { fmImagesToRelative } = require('gatsby-remark-relative-images');
const path = require("path")

const replacePath = path => (path === `/` ? path : path.replace(/\/$/, ``))

exports.createPages = async ({ actions: { createPage }, graphql }) => {
  const postTemplate = path.resolve(`src/components/Article/index.tsx`)

  const result = await graphql(`
    {
      allMarkdownRemark(
        sort: { order: DESC, fields: [frontmatter___date] }

      ) {
        edges {
          node {
            fields {
              slug
            }
          }
        }
      }
    }
  `)

  if (result.errors) {
    return Promise.reject(result.errors)
  }

  result.data.allMarkdownRemark.edges.forEach(({ node }) => {
    createPage({
      path: replacePath(node.fields.slug),
      component: postTemplate,
    })
  })
}

exports.onCreateNode = ({ node, getNode, actions }) => {
  fmImagesToRelative(node)
  if (node.internal.type === `MarkdownRemark`)
    actions.createNodeField({
      node,
      name: `slug`,
      value: replacePath(createFilePath({ node, getNode, basePath: `pages` })),
    })

}

Body:
The example has css styles applied. Specifically:

blockquote {
    background: #f9f9f9;
    border-left: 10px solid #ccc;
    margin: 1.5em 10px;
    padding: 1em 10px .1em 10px;
    quotes: "\201C""\201D""\2018""\2019";
}

Use similar css to make blockquotes look the same where you display it.


问:
denied: requested access to the resource is denied: docker
I am following this link to create my first docker Image and it went successfully and now I am trying to push this Image into my docker repository from this link. But whenever I am trying to push this Image into repository, I  got this type of error.

```<code>denied: requested access to the resource is denied
</code>```

Note: I have successfully login into docker

答:
I had the same issue. In my case, I was login in index.docker.io and push the image to docker.io/username/image:tag.

The solution is login in the docker.io by run this command:

```<code>export CI_REGISTRY=docker.io
docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
docker push USERNAME/IMAGE:TAG
</code>```

and the outputs are:

```<code> The push refers to repository [docker.io/USERNAME/IMAGE:TAG]
 eeb7e16c6369: Preparing
 6bd09f46d0ae: Preparing
 f5a7f7a3fb28: Preparing
 07952c1df7f6: Preparing
 a4522c0d203b: Preparing
 3e207b409db3: Preparing
 3e207b409db3: Waiting
 a4522c0d203b: Layer already exists
 3e207b409db3: Layer already exists
 f5a7f7a3fb28: Pushed
 6bd09f46d0ae: Pushed
 07952c1df7f6: Pushed
 eeb7e16c6369: Pushed
 latest: digest: sha256:7ce256fa83ef1eebcaaaa460c4d73f87f2adf304bc6e6c1b83a19d987cd61ad5
size: 1579
Running after_script
00:02
Saving cache
00:01
Uploading artifacts for successful job
00:02
 Job succeeded
</code>```

Regards.

Body:
I am following this link to create my first docker Image and it went successfully and now I am trying to push this Image into my docker repository from this link. But whenever I am trying to push this Image into repository, I  got this type of error.

denied: requested access to the resource is denied

Note: I have successfully login into docker

Body:
I had the same issue. In my case, I was login in index.docker.io and push the image to docker.io/username/image:tag.

The solution is login in the docker.io by run this command:

export CI_REGISTRY=docker.io
docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
docker push USERNAME/IMAGE:TAG

and the outputs are:

 The push refers to repository [docker.io/USERNAME/IMAGE:TAG]
 eeb7e16c6369: Preparing
 6bd09f46d0ae: Preparing
 f5a7f7a3fb28: Preparing
 07952c1df7f6: Preparing
 a4522c0d203b: Preparing
 3e207b409db3: Preparing
 3e207b409db3: Waiting
 a4522c0d203b: Layer already exists
 3e207b409db3: Layer already exists
 f5a7f7a3fb28: Pushed
 6bd09f46d0ae: Pushed
 07952c1df7f6: Pushed
 eeb7e16c6369: Pushed
 latest: digest: sha256:7ce256fa83ef1eebcaaaa460c4d73f87f2adf304bc6e6c1b83a19d987cd61ad5
size: 1579
Running after_script
00:02
Saving cache
00:01
Uploading artifacts for successful job
00:02
 Job succeeded

Regards.


答:
It would be better to do this :

```<code>def function1(x):
y=x+2
z= x-2
return y,z

def function2 (x):
v1,v2 = function1(x)
y1= v1 *10
z1= v2 +5
return y1,z1

def main(x):
print(function1(x),function2(x))

main(2)
</code>```

This is how you can use them in a class :

```<code>class Functions :

def function1 :
# ....

def function2 :
# ....
</code>```

And you can use it in other page like this :

```<code>from page2 import Functions

Functions.function1(..)
Functions.function2(..)
</code>```

Title: many functions and many variables

Body:
It would be better to do this :

def function1(x):
y=x+2
z= x-2
return y,z

def function2 (x):
v1,v2 = function1(x)
y1= v1 *10
z1= v2 +5
return y1,z1

def main(x):
print(function1(x),function2(x))

main(2)

This is how you can use them in a class :

class Functions :

def function1 :
# ....

def function2 :
# ....

And you can use it in other page like this :

from page2 import Functions

Functions.function1(..)
Functions.function2(..)