问:
oracle sql request column ambiguously defined
I am working on oracle 11g and tried to execute this request

```<code>select code_mod,INTITULE,code_et,nom ,avg(note)
from note,exam,module,etudiant
where note.CODE_EX = exam.CODE_EX
and EXAM.CODE_MOD=MODULE.CODE_MOD
and NOTE.CODE_ET = ETUDIANT.CODE_ET
group by code_mod,code_et
order by code_mod;
</code>```

but it says!

```<code> ORA-00918: column ambiguously defined
00918. 00000 -  "column ambiguously defined"
*Cause:
*Action:
Error on line 6, colunn 19
</code>```

what is wrong in it? if I execute this request, it works

```<code>select *
from note,exam,module,etudiant
where note.CODE_EX = exam.CODE_EX
and EXAM.CODE_MOD=MODULE.CODE_MOD
and NOTE.CODE_ET = ETUDIANT.CODE_ET;
</code>```

答:
you have at least two of code_mod,INTITULE,code_et,nom columns in note,exam,module,etudiant tables, and put them without aliases.

As an example both module and exam table include code_mod column, and in the select list you didn't show where it comes from

Use like this :

```<code>select m.code_mod,intitule,et.code_et,nom ,avg(note)
  from note n
 inner join exam e on ( n.code_ex = e.code_ex )
 inner join module m on ( e.code_mod=m.code_mod )
 inner join etudiant et on ( et.code_et = n.code_et )
group by m.code_mod,intitule,et.code_et,nom
order by m.code_mod;
</code>```

and you should include all columns in group by expression without grouping functions.

Body:
I am working on oracle 11g and tried to execute this request

select code_mod,INTITULE,code_et,nom ,avg(note)
from note,exam,module,etudiant
where note.CODE_EX = exam.CODE_EX
and EXAM.CODE_MOD=MODULE.CODE_MOD
and NOTE.CODE_ET = ETUDIANT.CODE_ET
group by code_mod,code_et
order by code_mod;

but it says!

 ORA-00918: column ambiguously defined
00918. 00000 -  "column ambiguously defined"
*Cause:
*Action:
Error on line 6, colunn 19

what is wrong in it? if I execute this request, it works

select *
from note,exam,module,etudiant
where note.CODE_EX = exam.CODE_EX
and EXAM.CODE_MOD=MODULE.CODE_MOD
and NOTE.CODE_ET = ETUDIANT.CODE_ET;

Body:
you have at least two of code_mod,INTITULE,code_et,nom columns in note,exam,module,etudiant tables, and put them without aliases.

As an example both module and exam table include code_mod column, and in the select list you didn't show where it comes from

Use like this :

select m.code_mod,intitule,et.code_et,nom ,avg(note)
  from note n
 inner join exam e on ( n.code_ex = e.code_ex )
 inner join module m on ( e.code_mod=m.code_mod )
 inner join etudiant et on ( et.code_et = n.code_et )
group by m.code_mod,intitule,et.code_et,nom
order by m.code_mod;

and you should include all columns in group by expression without grouping functions.


来源: stackexchange

问:
Send message from unknown type
I want to have my iOS project send a message and have it handled by the common project.

However, the MessagingCenter.Subscribe needs to the know the sending type in order to subscribe.

Given this constraint, is this possible?

答: Yes, just use Object as the type.  Everything in C# inherits from Object

ContentLicense: CC BY-SA 3.0

Title: Send message from unknown type


问:
Adding sublist to list in python3 not working
I have a really weird issue in Python3. I have some code that generates some different list from a list of integers (what this does exactly is not relevant).

```<code>def get_next_state(state):

    max_val = max(state)
    max_index = state.index(max_val)
    new_state = state

    for n in range(max_val + 1):
        new_state[max_index] -= 1
        new_state[(n + max_index) % len(state)] += 1

    return new_state
</code>```

Now all I want to do is add a next state to some list that keeps the states. This is my code:

```<code>l = [0, 2, 7, 0]
seen_states = []

for _ in range(10):
    print(l)
    seen_states += [l]
    l = get_next_state(l)

print(seen_states)
</code>```

For some reason list l is assigned correctly when I print it, but it is not added correctly to the list of seen states. Note that I have also tried seen_states.append(l) instead of using += [l]. Does anyone know why this happend?

答:
To prevent these problems use copy, deepcopy or list[:]

```<code>import copy

def get_next_state(state):

    max_val = max(state)
    max_index = state.index(max_val)
    new_state = copy.deepcopy(state)

    for n in range(max_val + 1):
        new_state[max_index] -= 1
        new_state[(n + max_index) % len(state)] += 1

    return new_state
</code>```

You are sending your list l inside the function. When you assign it to another name, you are not making a copy but referencing the original object. Any modification on these lists is a change in the original object.

Body:
I have a really weird issue in Python3. I have some code that generates some different list from a list of integers (what this does exactly is not relevant).

def get_next_state(state):

    max_val = max(state)
    max_index = state.index(max_val)
    new_state = state

    for n in range(max_val + 1):
        new_state[max_index] -= 1
        new_state[(n + max_index) % len(state)] += 1

    return new_state

Now all I want to do is add a next state to some list that keeps the states. This is my code:

l = [0, 2, 7, 0]
seen_states = []

for _ in range(10):
    print(l)
    seen_states += [l]
    l = get_next_state(l)

print(seen_states)

For some reason list l is assigned correctly when I print it, but it is not added correctly to the list of seen states. Note that I have also tried seen_states.append(l) instead of using += [l]. Does anyone know why this happend?

Body:
To prevent these problems use copy, deepcopy or list[:]

import copy

def get_next_state(state):

    max_val = max(state)
    max_index = state.index(max_val)
    new_state = copy.deepcopy(state)

    for n in range(max_val + 1):
        new_state[max_index] -= 1
        new_state[(n + max_index) % len(state)] += 1

    return new_state

You are sending your list l inside the function. When you assign it to another name, you are not making a copy but referencing the original object. Any modification on these lists is a change in the original object.


问:
SSIS for project online with ODATA Connection does not work
We are working on an SSIS package to get data from project online with ODATA connection.

Steps to recreate:
1)  Create a new SSIS project in Visual Studio
2)  Create a new Data Connection with ODATA Data source. The test connection is successful.
3)  Create a new Data source and select the Data Connection created in the above step. This is where the Visual  Studio just spins and does not respond.

How would I see what the error log is, the visual studio just hangs and does not give out any output.

The ODATA endpoint URL is:
https://XXXXXXXXX.sharepoint.com/sites/pwatest/_api/ProjectData/

With the same credentials if get the data from excel or even browser the data comes up correctly.

I am out of ideas on how to debug this, any help would be appreciated.

答: Turns out it was an issue with the network. Running fiddler and enabling the listening on fiddler helped us proceed, we were still not able to run the package though, until the inbound connections were enabled in the network.</p>


问:
setInterval code not working
I have this HTML:

```<code><body onclick = 'myMove(event)'>
    <p>
    <button onclick="myMove(event)">Go Right</button>
    </p>
    <div id ="animate"></div>
    <p id='para'>HI</p>
</body>
</code>```

This JavaScript:

```<code>function myMove(event) {
  let elem = document.getElementById("animate");
  document.getElementById('para').innerHTML = event.clientX;
  let id = setInterval(frame, 5);
  let pos = elem.style.marginLeft;

  function frame() {
    if (pos === event.clientX) {
      clearInterval(id);
    } else {
      pos++;
      elem.style.left = pos + 'px';
    }
  }
</code>```

But every time it runs, the box goes to the start and then moves to my mouse position. Is there a way to make it go to the mouse position from wherever it is and not go back to the start?

答:
Your code has two problems.
1. Function frame must be declared before calling setinterval
2. The variables id and pos are not in scope for frame. So they too should be declared globally within the main function myMove.

```<code>function myMove(event) {
    let id;
    let pos;
    let frame = function() {
        if (pos === event.clientX) {
          clearInterval(id);
        } else {
          pos++;
          elem.style.left = pos + 'px';
        }
      }
    let elem = document.getElementById("animate");
    document.getElementById('para').innerHTML = event.clientX;
    let id = setInterval(frame, 5);
    let pos = elem.style.marginLeft;
}
</code>```

Title: setInterval code not working

Body:
I have this HTML:

    <button onclick="myMove(event)">Go Right</button>

HI

This JavaScript:

function myMove(event) {
  let elem = document.getElementById("animate");
  document.getElementById('para').innerHTML = event.clientX;
  let id = setInterval(frame, 5);
  let pos = elem.style.marginLeft;

  function frame() {
    if (pos === event.clientX) {
      clearInterval(id);
    } else {
      pos++;
      elem.style.left = pos + 'px';
    }
  }

But every time it runs, the box goes to the start and then moves to my mouse position. Is there a way to make it go to the mouse position from wherever it is and not go back to the start?

Body:
Your code has two problems.
1. Function frame must be declared before calling setinterval
2. The variables id and pos are not in scope for frame. So they too should be declared globally within the main function myMove.

function myMove(event) {
    let id;
    let pos;
    let frame = function() {
        if (pos === event.clientX) {
          clearInterval(id);
        } else {
          pos++;
          elem.style.left = pos + 'px';
        }
      }
    let elem = document.getElementById("animate");
    document.getElementById('para').innerHTML = event.clientX;
    let id = setInterval(frame, 5);
    let pos = elem.style.marginLeft;
}


问:
No class named AppDelegate is loaded
We have a Xamarin.iOS project that shares a code backend with a WPF project that has been going through a refactor.  All the shared code libraries have been converted to be .net standard.

The Xamarin project builds, but the simulator throws an exception on startup as such :

Foundation.MonoTouchException has been thrown

Objective-C exception thrown.  Name: NSInternalInconsistencyException Reason: Unable to instantiate the UIApplication delegate instance. No class named AppDelegate is loaded.

Just for testing purposes, I added an empty UIApplicationDelegate to Main.cs and I'll still get the exception (only now referring to TestDelegate).

Main.cs

```<code>using Foundation;
using UIKit;

namespace App.IOS
{
    public class Application
    {
        static void Main (string[] args)
        {
            UIApplication.Main (args, null, nameof(AppDelegate));
        }
    }
}
</code>```

Appdelegate.cs (very large file, so just the declarations here).

```<code>namespace App.IOS
{
    public class MiniSetup
    {
        public static readonly MiniSetup Instance = new MiniSetup ();
        public void EnsureInit()
        {
            //Setting up Binding and Dependency Injection Here.
        }
    }

    [Register (nameof(AppDelegate))]
    public partial class AppDelegate : UIApplicationDelegate
    {
        public override bool FinishedLaunching (UIApplication app, NSDictionary options)
        {
            //Invoke Minisetup here
        }
        public override void WillEnterForeground (UIApplication application)
        {
            //snip
        }
        public override void DidEnterBackground (UIApplication

application)
            {
                //snip
            }

// snip other code for setting UI controls and other app logic.
        }
</code>```

It seems apparent that I've goofed up the project in some way, but I haven't found any leads as to where to look for a solution.  Any ideas on how to troubleshoot this?

答:
I don't have a smoking gun here, but near as I was able to figure out, an incompatible (with xamarin) reference or nuget package was added to the IOS project.  While the native code was throwing a native assembly, I'd imagine that AppDelegate was actually throwing a NotSupportedException or an AssemblyLoader Exception or similar.

So removing all references and nuget packages, then re-adding just the bare minimum seems to have resolved this issue.

Title: No class named AppDelegate is loaded

Body:
We have a Xamarin.iOS project that shares a code backend with a WPF project that has been going through a refactor.  All the shared code libraries have been converted to be .net standard.

The Xamarin project builds, but the simulator throws an exception on startup as such :

Foundation.MonoTouchException has been thrown

Objective-C exception thrown.  Name: NSInternalInconsistencyException Reason: Unable to instantiate the UIApplication delegate instance. No class named AppDelegate is loaded.

Just for testing purposes, I added an empty UIApplicationDelegate to Main.cs and I'll still get the exception (only now referring to TestDelegate).

Main.cs

using Foundation;
using UIKit;

namespace App.IOS
{
    public class Application
    {
        static void Main (string[] args)
        {
            UIApplication.Main (args, null, nameof(AppDelegate));
        }
    }
}

Appdelegate.cs (very large file, so just the declarations here).

namespace App.IOS
{
    public class MiniSetup
    {
        public static readonly MiniSetup Instance = new MiniSetup ();
        public void EnsureInit()
        {
            //Setting up Binding and Dependency Injection Here.
        }
    }

    [Register (nameof(AppDelegate))]
    public partial class AppDelegate : UIApplicationDelegate
    {
        public override bool FinishedLaunching (UIApplication app, NSDictionary options)
        {
            //Invoke Minisetup here
        }
        public override void WillEnterForeground (UIApplication application)
        {
            //snip
        }
        public override void DidEnterBackground (UIApplication

application)
            {
                //snip
            }

// snip other code for setting UI controls and other app logic.
        }

It seems apparent that I've goofed up the project in some way, but I haven't found any leads as to where to look for a solution.  Any ideas on how to troubleshoot this?


问:
Why aren't variable-length arrays part of the C++ standard?
I haven't used C very much in the last few years. When I read this question today I came across some C syntax which I wasn't familiar with.

Apparently in C99 the following syntax is valid:

```<code>void foo(int n) {
    int values[n]; //Declare a variable length array
}
</code>```

This seems like a pretty useful feature. Was there ever a discussion about adding it to the C++ standard, and if so, why it was omitted?

Some potential reasons:

Hairy for compiler vendors to implement

Incompatible with some other part of the standard

Functionality can be emulated with other C++ constructs

The C++ standard states that array size must be a constant expression (8.3.4.1).

Yes, of course I realize that in the toy example one could use std::vector<int> values(m);, but this allocates memory from the heap and not the stack. And if I want a multidimensional array like:

```<code>void foo(int x, int y, int z) {
    int values[x][y][z]; // Declare a variable length array
}
</code>```

the vector version becomes pretty clumsy:

```<code>void foo(int x, int y, int z) {
    vector< vector< vector<int> > > values( /* Really painful expression here. */);
}
</code>```

The slices, rows and columns will also potentially be spread all over memory.

Looking at the discussion at comp.std.c++ it's clear that this question is pretty controversial with some very heavyweight names on both sides of the argument. It's certainly not obvious that a std::vector is always a better solution.

答:
There are situations where allocating heap memory is very expensive compared to the operations performed. An example is matrix math. If you work with smallish matrices say 5 to 10 elements  and do a lot of arithmetics the malloc overhead will be really significant. At the same time making the size a compile time constant does seem very wasteful and inflexible.

I think that C++ is so unsafe in itself that the argument to "try to not add more unsafe features" is not very strong. On the other hand, as C++ is arguably the most runtime efficient programming language features which makes it more so are always useful: People who write performance critical programs will to a large extent use C++, and they need as much performance as possible. Moving stuff from heap to stack is one such possibility. Reducing the number of heap blocks is another. Allowing VLAs as object members would one way to achieve this. I'm working on such a suggestion. It is a bit complicated to implement, admittedly, but it seems quite doable.

Body:
I haven't used C very much in the last few years. When I read this question today I came across some C syntax which I wasn't familiar with.

Apparently in C99 the following syntax is valid:

void foo(int n) {
    int values[n]; //Declare a variable length array
}

This seems like a pretty useful feature. Was there ever a discussion about adding it to the C++ standard, and if so, why it was omitted?

Some potential reasons:

Hairy for compiler vendors to implement

Incompatible with some other part of the standard

Functionality can be emulated with other C++ constructs

The C++ standard states that array size must be a constant expression (8.3.4.1).

Yes, of course I realize that in the toy example one could use std::vector<int> values(m);, but this allocates memory from the heap and not the stack. And if I want a multidimensional array like:

void foo(int x, int y, int z) {
    int values[x][y][z]; // Declare a variable length array
}

the vector version becomes pretty clumsy:

void foo(int x, int y, int z) {
    vector< vector< vector<int> > > values( /* Really painful expression here. */);
}

The slices, rows and columns will also potentially be spread all over memory.

Looking at the discussion at comp.std.c++ it's clear that this question is pretty controversial with some very heavyweight names on both sides of the argument. It's certainly not obvious that a std::vector is always a better solution.

ContentLicense: CC BY-SA 2.5


问:
Implementing Custom EhCache
We have a requirement to Cache requests to a max of upto 2 categories per userId-sessionID pair. We are planning to use EhCache for this approach. The project is a spring boot application.

```<code>@Cacheable(value="products")
ProductList getProducts(String userID, String sessionID, String categoryID) {
   return getProductListForThisUserAndSessionAndCategory(userId, sessionId, categoryId;)
}
</code>```

The problem is how can I set the limit to a max of 2 cache elements per userID-sessionId when there could be more than one categories per user and session id pair?

One approach:
Setting a partial key of sessionId and userID and create a custom cache which can accept a max two values per sessionID-userID key. How does EhCache support custom Caches?

Any other approaches?

答:
If I got your question right you will change the maximum number of mappings to cache you can config like this </p>

```<code>import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;
import org.ehcache.jsr107.Eh107Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
public class CacheConfiguration {

    private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class);
    private final javax.cache.configuration.Configuration<Object, Object> jcacheConfiguration;

    @PreDestroy
    public void destroy() {
        log.info("Remove Cache Manager metrics");
        log.info("Closing Cache Manager");
    }

    public CacheConfiguration(JHipsterProperties jHipsterProperties) {

        jcacheConfiguration = Eh107Configuration.fromEhcacheCacheConfiguration(
                CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class,
                        ResourcePoolsBuilder.heap(2))
                        .withExpiry(Expirations.timeToLiveExpiration(Duration.of(3600, TimeUnit.SECONDS)))
                        .build()
        );
    }

    @Bean
    public JCacheManagerCustomizer cacheManagerCustomizer() {
        log.debug("Starting Ehcache");

        return cm -> {
            cm.createCache("products", jcacheConfiguration);
        };
    }

}
</code>```

Title: Implementing Custom EhCache

Body:
We have a requirement to Cache requests to a max of upto 2 categories per userId-sessionID pair. We are planning to use EhCache for this approach. The project is a spring boot application.

@Cacheable(value="products")
ProductList getProducts(String userID, String sessionID, String categoryID) {
   return getProductListForThisUserAndSessionAndCategory(userId, sessionId, categoryId;)
}

The problem is how can I set the limit to a max of 2 cache elements per userID-sessionId when there could be more than one categories per user and session id pair?

One approach:
Setting a partial key of sessionId and userID and create a custom cache which can accept a max two values per sessionID-userID key. How does EhCache support custom Caches?

Any other approaches?

Body:
If I got your question right you will change the maximum number of mappings to cache you can config like this

import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;
import org.ehcache.jsr107.Eh107Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
public class CacheConfiguration {

    private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class);
    private final javax.cache.configuration.Configuration<Object, Object> jcacheConfiguration;

    @PreDestroy
    public void destroy() {
        log.info("Remove Cache Manager metrics");
        log.info("Closing Cache Manager");
    }

    public CacheConfiguration(JHipsterProperties jHipsterProperties) {

        jcacheConfiguration = Eh107Configuration.fromEhcacheCacheConfiguration(
                CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class,
                        ResourcePoolsBuilder.heap(2))
                        .withExpiry(Expirations.timeToLiveExpiration(Duration.of(3600, TimeUnit.SECONDS)))
                        .build()
        );
    }

    @Bean
    public JCacheManagerCustomizer cacheManagerCustomizer() {
        log.debug("Starting Ehcache");

        return cm -> {
            cm.createCache("products", jcacheConfiguration);
        };
    }

}


问:
SharedPreferances in Spinners
i have a probleme with sharedpreferances in spinners, i have 2 spinners, i want to save my spinners with shared preferances i can save the first spinner but i can't save the second one, sombody can help me please
thanks to all.
i have a probleme with sharedpreferances in spinners, i have 2 spinners, i want to save my spinners with shared preferances i can save the first spinner but i can't save the second one, sombody can help me please
thanks to all.</p>

```<code>public class MyAndroidAppActivity extends AppCompatActivity {

    String india[]={"humains","elfes","hobbits"};
    String m[]={"PUNE","Mumbai","yoo"};
    String b[]={"Arwen","Elrond","Galadriel","Legolas"};
    String u[]={"sup","trankill","Conor","Mcgregor","Nate Diaz"};

    Spinner s,s1,s2;
    private Button btnSubmit;
   SharedPreferences mypref;
    final String KEY_SavedSel = "Saved Selection";
    final String KEY_SavedSe2 = "Saved Selection";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_android_app);
        s=(Spinner)findViewById(R.id.spinner1);
        s1=(Spinner)findViewById(R.id.spinner2);
        btnSubmit = (Button) findViewById(R.id.btnSubmit);

        final ArrayAdapter<String>ia=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,india);

        final ArrayAdapter<String>ma=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,m);

        final ArrayAdapter<String>ba=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,b);

        final ArrayAdapter<String>ua=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,u);

        ia.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s.setAdapter(ia);
        mypref = getPreferences(MODE_PRIVATE);
        int prefsInt = mypref.getInt(KEY_SavedSel, -1);
        int prefsInt1 = mypref.getInt(KEY_SavedSe2,-1);
        if(prefsInt != -1){
            s.setSelection(prefsInt);

        }

        if(prefsInt1 != -1){
            s1.setSelection(prefsInt1);
        }

        s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                switch (parent.getId()){
                    case R.id.spinner1:{
                        SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
                        editor.putInt(KEY_SavedSel, position);
                        editor.putInt(KEY_SavedSe2, position);
                        editor.commit();
                        if(india[position].equals("humains")){
                            ma.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            s1.setAdapter(ma);

                        }
                        if(india[position].equals("elfes")){

                            ba.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            s1.setAdapter(ba);

                        }
                        if(india[position].equals("hobbits")){

                            ua.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            s1.setAdapter(ua);

                        }

                    }

                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        btnSubmit.setOnClickListener(new OnClickListener() {

            @Override

            public void onClick(View v) {

                Toast.makeText(MyAndroidAppActivity.this,

                        "Resultat : " +

                                "\nSpinner 1 : "+ String.valueOf(s.getSelectedItem()) +

                                "\nSpinner 2 : "+ String.valueOf(s1.getSelectedItem()),

                        Toast.LENGTH_SHORT).show();

            }

        });

    }

}
</code>```

答:
The SharedPreferences keys must be different otherwise the second spinner will override the value saved from the first spinner

eg.

```<code>final String KEY_SavedSel = "Saved Selection";
final String KEY_SavedSe2 = "Saved Selection2";
</code>```

and then you can use it as below and retrieve the values later on in your code

```<code>    s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
            editor.putInt(KEY_SavedSel, position);
            editor.commit();

            if (india[position].equals("humains")) {
                ma.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                s1.setAdapter(ma);

            }
            if (india[position].equals("elfes")) {

                ba.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                s1.setAdapter(ba);

            }
            if (india[position].equals("hobbits")) {

                ua.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                s1.setAdapter(ua);

            }

            s1.setSelection(mypref.getInt(KEY_SavedSe2, -1));

        }

        @Override
        public void onNothingSelected(final AdapterView<?> adapterView) {

        }

    });

    s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
            editor.putInt(KEY_SavedSe2, position);
            editor.commit();

            if (b[position].equals("Arwen")) {
                // TODO: Do something

            }
            if (b[position].equals("Elrond")) {
                // TODO: Do something

            }
            if (b[position].equals("Galadriel")) {
                // TODO: Do something

            }
            if (b[position].equals("Legolas")) {
               // TODO: Do something

            }

        }

        @Override
        public void onNothingSelected(final AdapterView<?> adapterView) {

        }

    });

}
</code>```

And also you should add the following line

s1.setSelection(mypref.getInt(KEY_SavedSe2, -1));

inside your s.setOnItemSelectedListener as showed above because everytime the app restarts s.setOnItemSelectedListener is being called and it's not setting the second spinner selected item appropriately and by adding that there it will fix your initial issue.

Title: SharedPreferances in Spinners

Body:
i have a probleme with sharedpreferances in spinners, i have 2 spinners, i want to save my spinners with shared preferances i can save the first spinner but i can't save the second one, sombody can help me please
thanks to all.
i have a probleme with sharedpreferances in spinners, i have 2 spinners, i want to save my spinners with shared preferances i can save the first spinner but i can't save the second one, sombody can help me please
thanks to all.

public class MyAndroidAppActivity extends AppCompatActivity {

    String india[]={"humains","elfes","hobbits"};
    String m[]={"PUNE","Mumbai","yoo"};
    String b[]={"Arwen","Elrond","Galadriel","Legolas"};
    String u[]={"sup","trankill","Conor","Mcgregor","Nate Diaz"};

    Spinner s,s1,s2;
    private Button btnSubmit;
   SharedPreferences mypref;
    final String KEY_SavedSel = "Saved Selection";
    final String KEY_SavedSe2 = "Saved Selection";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_android_app);
        s=(Spinner)findViewById(R.id.spinner1);
        s1=(Spinner)findViewById(R.id.spinner2);
        btnSubmit = (Button) findViewById(R.id.btnSubmit);

        final ArrayAdapter<String>ia=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,india);

        final ArrayAdapter<String>ma=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,m);

        final ArrayAdapter<String>ba=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,b);

        final ArrayAdapter<String>ua=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,u);

        ia.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s.setAdapter(ia);
        mypref = getPreferences(MODE_PRIVATE);
        int prefsInt = mypref.getInt(KEY_SavedSel, -1);
        int prefsInt1 = mypref.getInt(KEY_SavedSe2,-1);
        if(prefsInt != -1){
            s.setSelection(prefsInt);

        }

        if(prefsInt1 != -1){
            s1.setSelection(prefsInt1);
        }

        s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                switch (parent.getId()){
                    case R.id.spinner1:{
                        SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
                        editor.putInt(KEY_SavedSel, position);
                        editor.putInt(KEY_SavedSe2, position);
                        editor.commit();
                        if(india[position].equals("humains")){
                            ma.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            s1.setAdapter(ma);

                        }
                        if(india[position].equals("elfes")){

                            ba.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            s1.setAdapter(ba);

                        }
                        if(india[position].equals("hobbits")){

                            ua.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            s1.setAdapter(ua);

                        }

                    }

                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        btnSubmit.setOnClickListener(new OnClickListener() {

            @Override

            public void onClick(View v) {

                Toast.makeText(MyAndroidAppActivity.this,

                        "Resultat : " +

                                "\nSpinner 1 : "+ String.valueOf(s.getSelectedItem()) +

                                "\nSpinner 2 : "+ String.valueOf(s1.getSelectedItem()),

                        Toast.LENGTH_SHORT).show();

            }

        });

    }

}

Body:
The SharedPreferences keys must be different otherwise the second spinner will override the value saved from the first spinner

eg.

final String KEY_SavedSel = "Saved Selection";
final String KEY_SavedSe2 = "Saved Selection2";

and then you can use it as below and retrieve the values later on in your code

    s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
            editor.putInt(KEY_SavedSel, position);
            editor.commit();

            if (india[position].equals("humains")) {
                ma.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                s1.setAdapter(ma);

            }
            if (india[position].equals("elfes")) {

                ba.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                s1.setAdapter(ba);

            }
            if (india[position].equals("hobbits")) {

                ua.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                s1.setAdapter(ua);

            }

            s1.setSelection(mypref.getInt(KEY_SavedSe2, -1));

        }

        @Override
        public void onNothingSelected(final AdapterView<?> adapterView) {

        }

    });

    s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
            editor.putInt(KEY_SavedSe2, position);
            editor.commit();

            if (b[position].equals("Arwen")) {
                // TODO: Do something

            }
            if (b[position].equals("Elrond")) {
                // TODO: Do something

            }
            if (b[position].equals("Galadriel")) {
                // TODO: Do something

            }
            if (b[position].equals("Legolas")) {
               // TODO: Do something

            }

        }

        @Override
        public void onNothingSelected(final AdapterView<?> adapterView) {

        }

    });

}

And also you should add the following line

s1.setSelection(mypref.getInt(KEY_SavedSe2, -1));

inside your s.setOnItemSelectedListener as showed above because everytime the app restarts s.setOnItemSelectedListener is being called and it's not setting the second spinner selected item appropriately and by adding that there it will fix your initial issue.


问:
I think I need a loop in an MS Access Query
I have a table of login and logout times for users, table looks something like below:

```<code>| ID | User |    WorkDate    |  Start   |  Finish  |
|  1 | Bill |     07/12/2017 | 09:00:00 | 17:00:00 |
|  2 | John |     07/12/2017 | 09:00:00 | 12:00:00 |
|  3 | John |     07/12/2017 | 12:30:00 | 17:00:00 |
|  4 | Mary |     07/12/2017 | 09:00:00 | 10:00:00 |
|  5 | Mary |     07/12/2017 | 10:10:00 | 12:00:00 |
|  6 | Mary |     07/12/2017 | 12:10:00 | 17:00:00 |
</code>```

I'm running a query to find out the length of the breaks that each user took by running a date diff between the Min of Finish, and Max of Start, then doing some other sums/queries to find out their break length.

This works where i have a maximum of two rows per User per WorkDate, so rows 1,2,3 give me workable data.

Rows 4,5,6 do not.

So long story short, how can i calculate the break times based on the above data in MS Access in a query. I'm assuming i'm going to need some looping statement but have no idea where to begin.

答:
Here is a solution that comes to mind first.

First query to get the min/max start and end times.

Second query to calculate the total time worked for each day by using your Min(start time) and max(end time) query.

Third query to calculate the total time worked for each shift (time difference between start and end times) and then do a daily sum.

Forth query to calculate the difference between total time from the second query and the total time from the third query. The difference gives you the amount of break time they took.

If you need additional help, I can provide some screenshots of example queries.

Body:
I have a table of login and logout times for users, table looks something like below:

| ID | User |    WorkDate    |  Start   |  Finish  |
|  1 | Bill |     07/12/2017 | 09:00:00 | 17:00:00 |
|  2 | John |     07/12/2017 | 09:00:00 | 12:00:00 |
|  3 | John |     07/12/2017 | 12:30:00 | 17:00:00 |
|  4 | Mary |     07/12/2017 | 09:00:00 | 10:00:00 |
|  5 | Mary |     07/12/2017 | 10:10:00 | 12:00:00 |
|  6 | Mary |     07/12/2017 | 12:10:00 | 17:00:00 |

I'm running a query to find out the length of the breaks that each user took by running a date diff between the Min of Finish, and Max of Start, then doing some other sums/queries to find out their break length.

This works where i have a maximum of two rows per User per WorkDate, so rows 1,2,3 give me workable data.

Rows 4,5,6 do not.

So long story short, how can i calculate the break times based on the above data in MS Access in a query. I'm assuming i'm going to need some looping statement but have no idea where to begin.


问:
How to get user data from the access token without JWT
I am getting Access token from the Azure AD Login.
But i don't want to use JWT dll for extract data from the Access Token.
So i need a alternative solution for this.
This is my Sample code  in JWT

```<code> var handler = new JwtSecurityTokenHandler();
            JwtSecurityToken tokenS = handler.ReadToken(data.AccessToken) as JwtSecurityToken;
            var claims = tokenS.Claims;
            var username = claims.FirstOrDefault(s => s.Type == "email").Value;
</code>```

used dlls: using System.IdentityModel.Tokens.Jwt;
I don't want this dll for extract data. I need another solution without using dll.

答:
I will not ask why you dont want to use the library you have for the exact purpose its intended for. Anyway a JWT is just  3 base 64 encoded strings concatenated with '.', (assuming its signed but not encrypted)

So:

```<code>var split = jwt.Split('.')
var token = Convert.FromBase64String(split([1]))
</code>```

the middle bit is the token in json, use newtonsoft to read it

Body:
I am getting Access token from the Azure AD Login.
But i don't want to use JWT dll for extract data from the Access Token.
So i need a alternative solution for this.
This is my Sample code  in JWT

 var handler = new JwtSecurityTokenHandler();
            JwtSecurityToken tokenS = handler.ReadToken(data.AccessToken) as JwtSecurityToken;
            var claims = tokenS.Claims;
            var username = claims.FirstOrDefault(s => s.Type == "email").Value;

used dlls: using System.IdentityModel.Tokens.Jwt;
I don't want this dll for extract data. I need another solution without using dll.

Body:
I will not ask why you dont want to use the library you have for the exact purpose its intended for. Anyway a JWT is just  3 base 64 encoded strings concatenated with '.', (assuming its signed but not encrypted)

So:

var split = jwt.Split('.')
var token = Convert.FromBase64String(split([1]))

the middle bit is the token in json, use newtonsoft to read it


问:
How to download images that are in links in a dataframe?
I have a dataframe with image links:

```<code>deputados_sites.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 512 entries, 0 to 511
Data columns (total 4 columns):
Nome              512 non-null object
Num_referencia    512 non-null object
Link              512 non-null object
Link_foto         512 non-null object
dtypes: object(4)
memory usage: 16.1+ KB
</code>```

It is the "Link_foto" column. Data example in the column: "http://www.camara.gov.br/internet/deputado/bandep/160600.jpg" / "http://www.camara.gov.br/internet/deputado/bandep/178995.jpg"

I'm using Python3 and pandas. Please, is there a way to download these images using Python?

答:
Something like this will probably work</p>

```<code>import urllib.request

urllib.request.urlretrieve("http://www.camara.gov.br/internet/deputado/bandep/160600.jpg", "local-filename.jpg")
</code>```

Body:
I have a dataframe with image links:

deputados_sites.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 512 entries, 0 to 511
Data columns (total 4 columns):
Nome              512 non-null object
Num_referencia    512 non-null object
Link              512 non-null object
Link_foto         512 non-null object
dtypes: object(4)
memory usage: 16.1+ KB

It is the "Link_foto" column. Data example in the column: "http://www.camara.gov.br/internet/deputado/bandep/160600.jpg" / "http://www.camara.gov.br/internet/deputado/bandep/178995.jpg"

I'm using Python3 and pandas. Please, is there a way to download these images using Python?

Body:
Something like this will probably work

import urllib.request

urllib.request.urlretrieve("http://www.camara.gov.br/internet/deputado/bandep/160600.jpg", "local-filename.jpg")


问:
Rewrite foreach loops into linq query?
I tried to rewrite the following loops in one "elegant" linq query but no success!

```<code>foreach (Obj1 om in List1)
            {
                foreach (Obj2 ol in List2)
                {
                    if (ol.prop == value)
                    {
                       return om.prop
                    }
                }
            }
</code>```

Could anyone suggest a query (if even possible)?

Thanks in advance

答:
this code doesn't benefit from using nested loop and can increase app execution time if you didn't hit the condition in first iteration,

what you are trying to do can be summarized in this line (based on your code)

you want to return the first element in List1 if list2 has ol.prop==value

based on that i would do this:

```<code>return List1.FirstOrDefault(om=> List2.Any(ol=>ol.prop == value))?.prop
</code>```

Title: Rewrite foreach loops into linq query?

Body:
I tried to rewrite the following loops in one "elegant" linq query but no success!

foreach (Obj1 om in List1)
            {
                foreach (Obj2 ol in List2)
                {
                    if (ol.prop == value)
                    {
                       return om.prop
                    }
                }
            }

Could anyone suggest a query (if even possible)?

Thanks in advance

Body:
this code doesn't benefit from using nested loop and can increase app execution time if you didn't hit the condition in first iteration,

what you are trying to do can be summarized in this line (based on your code)

you want to return the first element in List1 if list2 has ol.prop==value

based on that i would do this:

return List1.FirstOrDefault(om=> List2.Any(ol=>ol.prop == value))?.prop


问:
Align TextView on left and center
How do I exactly achieve this? I tried messing around with android:layout_gravity center|left and android:gravity center|left and none seems to work. Does it make any difference that I am using a spannable string?

Here is what I have right now and what I want to achive. I want my Text to align to the red line

Thanks in advance.

My Layout.. It is the TextView with the ID status

```<code><android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <!-- Main layout -->

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <FrameLayout
        android:id="@+id/main_fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#f2f2f2">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center_horizontal"

                >

                <android.support.v4.widget.SwipeRefreshLayout
                    android:id="@+id/swiperefresh"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"

                    >

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_gravity="center"
                        android:orientation="vertical"><![CDATA[
                        >

                        ]]>

                        <include
                            layout="@layout/actionbarmenu"
                            android:layout_width="match_parent"
                            android:layout_height="40dp"
                            android:layout_weight="0.64" />

                        <TextView
                            android:id="@+id/textView3"
                            android:layout_width="match_parent"
                            android:layout_height="30dp"
                            android:layout_marginLeft="5dp"
                            android:background="#FAFAFA"
                            android:gravity="center|left"
                            android:text="Notfallübersicht"
                            android:textColor="#c9c9c9"
                            android:textSize="18sp" />

                        <EditText
                            android:id="@+id/Notfall"
                            android:layout_width="match_parent"
                            android:layout_height="70dp"
                            android:layout_weight="0.36"
                            android:background="@drawable/round_grey"
                            android:ellipsize="end"
                            android:gravity="center"
                            android:hint="Notfall-Code Eingabe"
                            android:inputType="text"
                            android:paddingLeft="6dp"
                            android:singleLine="true"
                            android:textAllCaps="false"
                            android:textColor="#585858"
                            android:textColorHint="#c9c9c9"
                            android:textCursorDrawable="@drawable/black_cursor" />

                        <TextView
                            android:id="@+id/textView7"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.70" />

                        <TextView
                            android:id="@+id/status"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="3.63"
                            android:gravity="center"
                            android:textColor="#6f7070"
                            android:textSize="20sp"
                            android:visibility="visible" />

                        <TextView
                            android:id="@+id/abgemeldet"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="10.08"
                            android:text="Bitte melde dich mit deinen Pengueen Log-In Daten an, um die App zu aktivieren.  "
                            android:textSize="24sp" />

                        <TextView
                            android:id="@+id/user"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="5dp"
                            android:layout_weight="0.60"
                            android:text="Angemeldet als :"
                            android:textSize="14sp"
                            android:visibility="invisible" />

                        <TextView
                            android:id="@+id/angemeldet"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="5dp"
                            android:layout_weight="1.09"
                            android:text="Letzte Abfrage vor  1 Minute"
                            android:textSize="14sp"
                            android:textStyle="bold"
                            android:visibility="invisible" />

                        <Button
                            android:id="@+id/button"
                            style="@style/Widget.AppCompat.Button"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:background="#4697c4"
                            android:text="Anmleden"
                            android:textColor="#ffffff"
                            android:visibility="gone" />

                        <RelativeLayout
                            android:layout_width="match_parent"
                            android:layout_height="50dp"
                            android:layout_weight="0.74">

                            <!-- This could be your fragment container, or something -->
                            <FrameLayout
                                android:id="@+id/contentContainer"
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:layout_above="@+id/bottomBar" />

                            <com.roughike.bottombar.BottomBar
                                android:id="@+id/bottomBar"
                                android:layout_width="match_parent"
                                android:layout_height="60dp"
                                android:layout_alignParentBottom="true"
                                android:layout_gravity="bottom"
                                app2:bb_activeTabAlpha="1"
                                app2:bb_activeTabColor="#ffffff"
                                app2:bb_inActiveTabAlpha="0.6"
                                app2:bb_inActiveTabColor="#ffffff"
                                app2:bb_tabXmlResource="@xml/bottombar_tabs" />

                        </RelativeLayout>

                    </LinearLayout>
                </android.support.v4.widget.SwipeRefreshLayout>
            </LinearLayout>

    </FrameLayout>

    <!-- The navigation drawer -->

    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#51aadd"
        android:choiceMode="singleChoice"
        android:divider="@drawable/list_divider"
        android:footerDividersEnabled="false"
        android:headerDividersEnabled="true"
        android:scrollbars="none" />

</android.support.v4.widget.DrawerLayout>
</code>```

答:
You  will need this inside the desired textviews :</p>

```<code>android:layout_width="wrap_content"
android:gravity="left"
android:layout_gravity="center_horizontal"
</code>```

Title: Align TextView on left and center

Body:
How do I exactly achieve this? I tried messing around with android:layout_gravity center|left and android:gravity center|left and none seems to work. Does it make any difference that I am using a spannable string?

Here is what I have right now and what I want to achive. I want my Text to align to the red line

Thanks in advance.

My Layout.. It is the TextView with the ID status

<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <FrameLayout
        android:id="@+id/main_fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#f2f2f2">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center_horizontal"

                >

                <android.support.v4.widget.SwipeRefreshLayout
                    android:id="@+id/swiperefresh"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"

                    >

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_gravity="center"
                        android:orientation="vertical"><![CDATA[
                        >

                        ]]>

                        <include
                            layout="@layout/actionbarmenu"
                            android:layout_width="match_parent"
                            android:layout_height="40dp"
                            android:layout_weight="0.64" />

                        <TextView
                            android:id="@+id/textView3"
                            android:layout_width="match_parent"
                            android:layout_height="30dp"
                            android:layout_marginLeft="5dp"
                            android:background="#FAFAFA"
                            android:gravity="center|left"
                            android:text="Notfallübersicht"
                            android:textColor="#c9c9c9"
                            android:textSize="18sp" />

                        <EditText
                            android:id="@+id/Notfall"
                            android:layout_width="match_parent"
                            android:layout_height="70dp"
                            android:layout_weight="0.36"
                            android:background="@drawable/round_grey"
                            android:ellipsize="end"
                            android:gravity="center"
                            android:hint="Notfall-Code Eingabe"
                            android:inputType="text"
                            android:paddingLeft="6dp"
                            android:singleLine="true"
                            android:textAllCaps="false"
                            android:textColor="#585858"
                            android:textColorHint="#c9c9c9"
                            android:textCursorDrawable="@drawable/black_cursor" />

                        <TextView
                            android:id="@+id/textView7"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.70" />

                        <TextView
                            android:id="@+id/status"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="3.63"
                            android:gravity="center"
                            android:textColor="#6f7070"
                            android:textSize="20sp"
                            android:visibility="visible" />

                        <TextView
                            android:id="@+id/abgemeldet"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="10.08"
                            android:text="Bitte melde dich mit deinen Pengueen Log-In Daten an, um die App zu aktivieren.  "
                            android:textSize="24sp" />

                        <TextView
                            android:id="@+id/user"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="5dp"
                            android:layout_weight="0.60"
                            android:text="Angemeldet als :"
                            android:textSize="14sp"
                            android:visibility="invisible" />

                        <TextView
                            android:id="@+id/angemeldet"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="5dp"
                            android:layout_weight="1.09"
                            android:text="Letzte Abfrage vor  1 Minute"
                            android:textSize="14sp"
                            android:textStyle="bold"
                            android:visibility="invisible" />

                        <Button
                            android:id="@+id/button"
                            style="@style/Widget.AppCompat.Button"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:background="#4697c4"
                            android:text="Anmleden"
                            android:textColor="#ffffff"
                            android:visibility="gone" />

                        <RelativeLayout
                            android:layout_width="match_parent"
                            android:layout_height="50dp"
                            android:layout_weight="0.74">

                            <FrameLayout
                                android:id="@+id/contentContainer"
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:layout_above="@+id/bottomBar" />

                            <com.roughike.bottombar.BottomBar
                                android:id="@+id/bottomBar"
                                android:layout_width="match_parent"
                                android:layout_height="60dp"
                                android:layout_alignParentBottom="true"
                                android:layout_gravity="bottom"
                                app2:bb_activeTabAlpha="1"
                                app2:bb_activeTabColor="#ffffff"
                                app2:bb_inActiveTabAlpha="0.6"
                                app2:bb_inActiveTabColor="#ffffff"
                                app2:bb_tabXmlResource="@xml/bottombar_tabs" />

                        </RelativeLayout>

                    </LinearLayout>
                </android.support.v4.widget.SwipeRefreshLayout>
            </LinearLayout>

    </FrameLayout>

    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#51aadd"
        android:choiceMode="singleChoice"
        android:divider="@drawable/list_divider"
        android:footerDividersEnabled="false"
        android:headerDividersEnabled="true"
        android:scrollbars="none" />

</android.support.v4.widget.DrawerLayout>

Body:
You  will need this inside the desired textviews :

android:layout_width="wrap_content"
android:gravity="left"
android:layout_gravity="center_horizontal"


问:
How to generate gRPC services and reuse existed DTOs in java with gradle?
Is it possible to describe some services in .proto files which use the existed DTOs & generate the service classes with gradle?

I'm developing client SDK for some server. The current communication layer based on gRPC but I don't want to expose the implementation details (those ugly gRPC messages classes) to the end user. So the public API represented with POJOs.

The existed solution make some conversions between two types of DTOs with custom converters. And this is quite annoying - copy tones of properties just to beautify the public API. So I'm looking a way to reuse the POJO on gRPC layer. Is it possible?

答: Protobuf really needs those messages in order to be told what to serialize. So while there are some ways to serialize your own message types (like MethodDescriptor.Marshaller), if you want to use Protobuf you'll need to copy between the different types of objects.</p>


问:
path for cq.foundation-main library in aem
i am looking for cq.foundation-main client library path.
I would like to disable granite.jquery client lib on aem 6.3

Thanks.

答:
DISCLAIMER: I would not disable granite.jquery clientlib as it is a dependency for many other clientlibs and might break the UI in your AEM instance. Do this at your own risk.

here is the answer to your question:

to find the location of any clientlib, you can go to: http://localhost:4502/libs/granite/ui/content/dumplibs.html

then search for the clientlib category, in your case: cq.foundation-main and the path will be listed.

on my 6.3 instances, that path is /etc/clientlibs/foundation/main


问:
Disable/Enable Html element based on Role Springboot+Thymeleaf
i have a secured springboot application with multiple roles (ROLE1,ROLE2). One user has both roles and the other one has only one. On successful login user is sent to the landing page, over there i want to disable  element if user has only one role.

I've tried with thymeleaf-extras-springsecurity3 but with no success. This is my code:

Pom.xml

```<code>...
<dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity3</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
...
</code>```

landing.html (tried with all of the options)

```<code>!${currentUser.user.hasAuthority('ROLE1')}
!${#authorization.expression('hasRole('ROLE1')')}
${#authentication.getPrincipal().getUser().getRoles()}
${#authentication.getPrincipal().getRoles()}
</code>```

But with no success, i always get null error for that object like this

```<code>org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method getPrincipal() on null context object
</code>```

Any help would be much appreciated! Thanks!

答:
I think the recommended way is to use xmlns:sec="http://www.thymeleaf.org/extras/spring-security" namespace to achieve the result you want sec:authorize="hasRole('ROLE_ADMIN')"

```<code><html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>...</head>
<body>
    <div sec:authorize="hasRole('ROLE_ADMIN')">...</div>

    // or use #authorization, but use escape quote 'hasRole(''ROLE_USER'')'
    <div th:if="${#authorization.expression('hasRole(''ROLE_USER'')')}">...</div>
</body>
</code>```

You will probably (I think spring-boot does it by default) also have to configure SpringSecurityDialect to make it work.

```<code> @Bean
public TemplateEngine templateEngine() {
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setTemplateResolver(templateResolver());
    engine.addDialect(securityDialect());
    return engine;
}

private IDialect securityDialect(){
    SpringSecurityDialect dialect = new SpringSecurityDialect();
    return dialect;
}
</code>```

Also take a look at similar question: Spring Security hasRole() not working

Body:
i have a secured springboot application with multiple roles (ROLE1,ROLE2). One user has both roles and the other one has only one. On successful login user is sent to the landing page, over there i want to disable  element if user has only one role.

I've tried with thymeleaf-extras-springsecurity3 but with no success. This is my code:

Pom.xml

...
<dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity3</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
...

landing.html (tried with all of the options)

!${currentUser.user.hasAuthority('ROLE1')}
!${#authorization.expression('hasRole('ROLE1')')}
${#authentication.getPrincipal().getUser().getRoles()}
${#authentication.getPrincipal().getRoles()}

But with no success, i always get null error for that object like this

org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method getPrincipal() on null context object

Any help would be much appreciated! Thanks!

Body:
I think the recommended way is to use xmlns:sec="http://www.thymeleaf.org/extras/spring-security" namespace to achieve the result you want sec:authorize="hasRole('ROLE_ADMIN')"

<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>...</head>
<body>
    <div sec:authorize="hasRole('ROLE_ADMIN')">...</div>

    // or use #authorization, but use escape quote 'hasRole(''ROLE_USER'')'
    <div th:if="${#authorization.expression('hasRole(''ROLE_USER'')')}">...</div>
</body>

You will probably (I think spring-boot does it by default) also have to configure SpringSecurityDialect to make it work.

 @Bean
public TemplateEngine templateEngine() {
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setTemplateResolver(templateResolver());
    engine.addDialect(securityDialect());
    return engine;
}

private IDialect securityDialect(){
    SpringSecurityDialect dialect = new SpringSecurityDialect();
    return dialect;
}

Also take a look at similar question: Spring Security hasRole() not working


问:
Matching two data tables (Vlookup, dplyr, match(), left_join) keeping number of rows
I want to include the table "tech_distance" into my "first occurrences" table.
The two data tables:

```<code>head(first_occurrences)
# A tibble: 6 x 4
# Groups:   Main, Second [6]
   year  Main Second  occurrence
   <int> <chr>  <chr>      <int>
1  1991  C09D   C08F          1
2  2002  A47C   A47D          1
3  2002  G10K   H05K          1
4  2004  G06G   C07K          1
5  2015  B64F   B64D          1
6  2015  H02G   B29C          1

head(tech_distance)
# A tibble: 6 x 2
    Main  tech_distance
   <fctr>         <dbl>
1   C09D           0.3
2   A47C           0.0
3   G10K           0.5
4   G06G           0.5
5   B64F           0.0
6   H02G           0.5
</code>```

This is the result I want to get:

```<code>head(first_occurrences)
   Main year Second occurrence tech_distance
 1 A01B 2004   E21B          1           0.7
 2 A01B 2004   E21B          1           0.5
 3 A01B 2004   E21B          1           0.7
 4 A01B 2004   E21B          1           0.5
 5 A01B 2004   E21B          1           0.5
 6 A01B 2004   E21B          1           1.0
</code>```

I have used mutate in dplyr:

```<code>first_occurrences <- data %>%
 select(year = X3,Main = X7,Second = X8) %>%
 group_by(Main,Second) %>%
 mutate(occurrence = n(), tech_distance) %>%
 filter(occurrence >= 0, occurrence <= 1, !(Main == Second))
</code>```

But I get this error:

```<code> Error in mutate_impl(.data, dots) :
 Column `tech_distance` must be length 24 (the group size) or one, not 2
</code>```

So I tried using merge():

```<code>first_occurrences <- merge(first_occurrences, tech_distance, by.x = "Main", by.y = "Main", all.x=T)
</code>```

This seems to work but I get an enormous number of rows (240,217 entries)

```<code> str(first_occurrences)
 'data.frame':  240217 obs. of  5 variables:
  $ Main         : chr  "A01B" "A01B" "A01B" "A01B" ...
  $ year         : int  2004 2004 2004 2004 2004 2004 2004 2004 2004 2004 ...
  $ Second       : chr  "E21B" "E21B" "E21B" "E21B" ...
  $ occurrence   : int  1 1 1 1 1 1 1 1 1 1 ...
  $ tech_distance: num  0.7 0.5 0.7 0.5 0.5 1 0.5 0.7 0.3 0 ...
</code>```

while the datasets before were:

```<code>str(first_occurrences)
Classes ‘grouped_df’, ‘tbl_df’, ‘tbl’ and 'data.frame': 8015 obs. of  4 variables:
 $ year      : int  1991 2002 2002 2004 2015 2015 2015 2015 2015 2015 ...
 $ Main      : chr  "C09D" "A47C" "G10K" "G06G" ...
 $ Second    : chr  "C08F" "A47D" "H05K" "C07K" ...
 $ occurrence: int  1 1 1 1 1 1 1 1 1 1 ...

str(tech_distance)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   8015 obs. of  2 variables:
 $ Main         : Factor w/ 815 levels "A01B","A01C",..: 345 62 684 651 265 749 328 735 173 788 ...
 $ tech_distance: num  0.3 0 0.5 0.5 0 0.5 0.5 0 0.5 0.5 ...
</code>```

Does anybody have any idea on how to merge two dataframes keeping the same number of rows?

答: Are the Main columns all unique? If they are, then you can get a one-to-one match and your result will have 8015 rows. If there are duplicates, then you get a one-to-many match and get more rows.

Body:
I want to include the table "tech_distance" into my "first occurrences" table.
The two data tables:

head(first_occurrences)
# A tibble: 6 x 4
# Groups:   Main, Second [6]
   year  Main Second  occurrence
   <int> <chr>  <chr>      <int>
1  1991  C09D   C08F          1
2  2002  A47C   A47D          1
3  2002  G10K   H05K          1
4  2004  G06G   C07K          1
5  2015  B64F   B64D          1
6  2015  H02G   B29C          1

head(tech_distance)
# A tibble: 6 x 2
    Main  tech_distance
   <fctr>         <dbl>
1   C09D           0.3
2   A47C           0.0
3   G10K           0.5
4   G06G           0.5
5   B64F           0.0
6   H02G           0.5

This is the result I want to get:

head(first_occurrences)
   Main year Second occurrence tech_distance
 1 A01B 2004   E21B          1           0.7
 2 A01B 2004   E21B          1           0.5
 3 A01B 2004   E21B          1           0.7
 4 A01B 2004   E21B          1           0.5
 5 A01B 2004   E21B          1           0.5
 6 A01B 2004   E21B          1           1.0

I have used mutate in dplyr:

first_occurrences <- data %>%
 select(year = X3,Main = X7,Second = X8) %>%
 group_by(Main,Second) %>%
 mutate(occurrence = n(), tech_distance) %>%
 filter(occurrence >= 0, occurrence <= 1, !(Main == Second))

But I get this error:

 Error in mutate_impl(.data, dots) :
 Column `tech_distance` must be length 24 (the group size) or one, not 2

So I tried using merge():

first_occurrences <- merge(first_occurrences, tech_distance, by.x = "Main", by.y = "Main", all.x=T)

This seems to work but I get an enormous number of rows (240,217 entries)

 str(first_occurrences)
 'data.frame':  240217 obs. of  5 variables:
  $ Main         : chr  "A01B" "A01B" "A01B" "A01B" ...
  $ year         : int  2004 2004 2004 2004 2004 2004 2004 2004 2004 2004 ...
  $ Second       : chr  "E21B" "E21B" "E21B" "E21B" ...
  $ occurrence   : int  1 1 1 1 1 1 1 1 1 1 ...
  $ tech_distance: num  0.7 0.5 0.7 0.5 0.5 1 0.5 0.7 0.3 0 ...

while the datasets before were:

str(first_occurrences)
Classes ‘grouped_df’, ‘tbl_df’, ‘tbl’ and 'data.frame': 8015 obs. of  4 variables:
 $ year      : int  1991 2002 2002 2004 2015 2015 2015 2015 2015 2015 ...
 $ Main      : chr  "C09D" "A47C" "G10K" "G06G" ...
 $ Second    : chr  "C08F" "A47D" "H05K" "C07K" ...
 $ occurrence: int  1 1 1 1 1 1 1 1 1 1 ...

str(tech_distance)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   8015 obs. of  2 variables:
 $ Main         : Factor w/ 815 levels "A01B","A01C",..: 345 62 684 651 265 749 328 735 173 788 ...
 $ tech_distance: num  0.3 0 0.5 0.5 0 0.5 0.5 0 0.5 0.5 ...

Does anybody have any idea on how to merge two dataframes keeping the same number of rows?


问:
Proper Laravel routing with absence of URI parameters
I have a form which can be saved as draft. The initial route will not have the parameter with the submitted id -- since it has not been submitted. Once it's saved, the route will contain the submitted id to retrieve the data and show it to the user.

I am currently creating multiple routes to accommodate this, which is very messy and can see how this will be an issue to maintain.

How can I account for the absence of parameters in routes, especially the form routes or controllers which throw an error with missing variables?

Routes:

```<code>Route::get('/request/{unit}/{id}',
   'RequestsController@showNewRequest')->name('request.show-new-request');

Route::get('/request/{unit}/{id}/{rid}',
   'RequestsController@showRequest')->name('request.show-request');

Route::post('/request/{unit}/{id}',
   'RequestsController@storeNew')->name('request.store-new');

Route::post('/request/{unit}/{id}/{rid}',
   'RequestsController@store')->name('request.store');
</code>```

Controllers

```<code>public function showNewRequest($unit, $id) { }

public function showRequest($unit, $id, $rid) { }
</code>```

Form/Blade:

```<code>@if(isset($rid))
  <form class="form-horizontal" method="POST" enctype="multipart/form-data"
    action="{{ route('request.store', ['unit' => $unit, 'id' =>  $id, 'rid' =>  $rid]) }}">
@else
 <form class="form-horizontal" method="POST" enctype="multipart/form-data"
    action="{{ route('request.store-new', ['unit' => $unit, 'id' =>  $id]) }}">
@endif
</code>```

答:
You can use ? in the route parameters. This will let you ignore them. Then you can change the code to something like this:

```<code>Route::get('/request/{unit}/{id}/{rid?}',
   'RequestsController@showRequest')->name('request.show-request');
</code>```

Controller:

```<code>public function showRequest($unit, $id, $rid = null) {
    if ($rid) {
        //Do something with $rid
    } else {
        //Do something considering that this is a draft.
    }
}
</code>```

This also applies to post routes.

Body:
I have a form which can be saved as draft. The initial route will not have the parameter with the submitted id -- since it has not been submitted. Once it's saved, the route will contain the submitted id to retrieve the data and show it to the user.

I am currently creating multiple routes to accommodate this, which is very messy and can see how this will be an issue to maintain.

How can I account for the absence of parameters in routes, especially the form routes or controllers which throw an error with missing variables?

Routes:

Route::get('/request/{unit}/{id}',
   'RequestsController@showNewRequest')->name('request.show-new-request');

Route::get('/request/{unit}/{id}/{rid}',
   'RequestsController@showRequest')->name('request.show-request');

Route::post('/request/{unit}/{id}',
   'RequestsController@storeNew')->name('request.store-new');

Route::post('/request/{unit}/{id}/{rid}',
   'RequestsController@store')->name('request.store');

Controllers

public function showNewRequest($unit, $id) { }

public function showRequest($unit, $id, $rid) { }

Form/Blade:

@if(isset($rid))
  <form class="form-horizontal" method="POST" enctype="multipart/form-data"
    action="{{ route('request.store', ['unit' => $unit, 'id' =>  $id, 'rid' =>  $rid]) }}">
@else
 <form class="form-horizontal" method="POST" enctype="multipart/form-data"
    action="{{ route('request.store-new', ['unit' => $unit, 'id' =>  $id]) }}">
@endif

Body:
You can use ? in the route parameters. This will let you ignore them. Then you can change the code to something like this:

Route::get('/request/{unit}/{id}/{rid?}',
   'RequestsController@showRequest')->name('request.show-request');

Controller:

public function showRequest($unit, $id, $rid = null) {
    if ($rid) {
        //Do something with $rid
    } else {
        //Do something considering that this is a draft.
    }
}

This also applies to post routes.


问:
jQuery: find the previous sibling with a class name?
I have a HTML code like this:

```<code><div class="buildExMain">
    Select An Option
        <i class="fa fa-check-circle" aria-hidden="true"></i>
        <div class="buildExDrop">
            <p class="pSelection">Number 1</p>
            <p class="pSelection">Number 2</p>
        </div>
</div>
</code>```

Now, I'm trying to show(); the .fa element when a .pSelection is clicked on.

I tried this jquery code with no luck:

```<code>$(document).on('click','.pSelection', function(e){
    //This doesn't work////
    $(this).prev(".fa").show();

    //doesn't work either///
    $(this).prevAll(".buildExMain.fa:first").show();
});
</code>```

答:
you element is child of div element and you want to locate element just above it . </p>

```<code> $(this).parent().prev(".fa").show();
</code>```

Body:
I have a HTML code like this:

    Select An Option

Number 1

Number 2

Now, I'm trying to show(); the .fa element when a .pSelection is clicked on.

I tried this jquery code with no luck:

$(document).on('click','.pSelection', function(e){
    //This doesn't work////
    $(this).prev(".fa").show();

    //doesn't work either///
    $(this).prevAll(".buildExMain.fa:first").show();
});

Body:
you element is child of div element and you want to locate element just above it .

 $(this).parent().prev(".fa").show();


问:
DataProtection - Share machine key between multiple applications
Let's suppose that we have two APIs, one for UserManagement and one for Auth.

UserManagement API is responsible for initial invitation email (where i need a ResetPasswordToken because this is my current app flow) and Auth API is responsible for password recovery (where i need a ResetPasswordToken).

Of course, i need to specify the same machine key for both applications.

Let's also suppose that those two applications will be deployed behind a load balancer. 2 apps x 3 instances.

It is sufficient to have the same shared location for persisting keys (Redis or so) in both APIs?

```<code>services.AddDataProtection().PersistKeysToRedis(/* */);
</code>```

I'm thinking that if it works for one app, multiple instances scenario, it will work for multiple apps, multiple instances scenario too.

P.S: I wasn't able to find anything about any locking mechanism (it seems that there is one just looking at how it behaves)

Another thing that i'm concerned of: race condition?!

Duc_Thuan_Nguy Jun 9, 2017

Out of curiosity, how does key rolling
  handle concurrency? For example, let's say we have a web-farm with 2
  machines and a shared network directory. There may be a race condition
  in which both machines want to roll a new key at the same time. How is
  this situation handled? Or the two machines can roll their own new
  keys and as long as they can have access to both new keys, they can
  unprotect data smoothly?

Comment reference: https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/key-management

Later edit: It looks like if you have multiple apps it isn't sufficient to specify that you want to persist keys in the same location. There is a concept of application discriminator (all apps being isolated).

You will need something like the following:

```<code>services.AddDataProtection(configure => {
                configure.ApplicationDiscriminator = "App.X";
            }).PersistKeysToRedis(/* */);
</code>```

Locking and race condition questions are still valid.

答:
No, it's not sufficient. ASP.NET Core's data protection isolates applications by default based on file paths, or IIS hosting information, so multiple apps can share a single keyring, but still not be able to read each other's data.

As the docs state

By default, the Data Protection system isolates apps from one another,
  even if they're sharing the same physical key repository. This
  prevents the apps from understanding each other's protected payloads.
  To share protected payloads between two apps, use SetApplicationName
  with the same value for each app

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddDataProtection()
        .SetApplicationName("shared app name");
}
</code>```

Body:
Let's suppose that we have two APIs, one for UserManagement and one for Auth.

UserManagement API is responsible for initial invitation email (where i need a ResetPasswordToken because this is my current app flow) and Auth API is responsible for password recovery (where i need a ResetPasswordToken).

Of course, i need to specify the same machine key for both applications.

Let's also suppose that those two applications will be deployed behind a load balancer. 2 apps x 3 instances.

It is sufficient to have the same shared location for persisting keys (Redis or so) in both APIs?

services.AddDataProtection().PersistKeysToRedis(/* */);

I'm thinking that if it works for one app, multiple instances scenario, it will work for multiple apps, multiple instances scenario too.

P.S: I wasn't able to find anything about any locking mechanism (it seems that there is one just looking at how it behaves)

Another thing that i'm concerned of: race condition?!

Duc_Thuan_Nguy Jun 9, 2017

Out of curiosity, how does key rolling
  handle concurrency? For example, let's say we have a web-farm with 2
  machines and a shared network directory. There may be a race condition
  in which both machines want to roll a new key at the same time. How is
  this situation handled? Or the two machines can roll their own new
  keys and as long as they can have access to both new keys, they can
  unprotect data smoothly?

Comment reference: https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/key-management

Later edit: It looks like if you have multiple apps it isn't sufficient to specify that you want to persist keys in the same location. There is a concept of application discriminator (all apps being isolated).

You will need something like the following:

services.AddDataProtection(configure => {
                configure.ApplicationDiscriminator = "App.X";
            }).PersistKeysToRedis(/* */);

Locking and race condition questions are still valid.

Body:
No, it's not sufficient. ASP.NET Core's data protection isolates applications by default based on file paths, or IIS hosting information, so multiple apps can share a single keyring, but still not be able to read each other's data.

As the docs state

By default, the Data Protection system isolates apps from one another,
  even if they're sharing the same physical key repository. This
  prevents the apps from understanding each other's protected payloads.
  To share protected payloads between two apps, use SetApplicationName
  with the same value for each app

public void ConfigureServices(IServiceCollection services)
{
    services.AddDataProtection()
        .SetApplicationName("shared app name");
}


问:
Recommended website resolution (width and height)?
Is there any standard on common website resolution?

We are targeting newer monitors, perhaps at least 1280px wide, but the height may varies, and each browser may have different toolbar heights too.

Is there any sort of standard to this?

答:
there are actually industry standards for widths (well according to yahoo at least).
Their supported widths are 750, 950, 974, 100%

There are advantages of these widths for their predefined grids (column layouts) which work well with standard dimensions for advertisements if you were to include any.

Interesting talk too worth watching.

see YUI Base

OwnerDisplayName: Simon


问:
Tensorflow neural network prediction is always the same
I have a deep CNN that predicts a label between "0" and "2" for every pixel in a 3d image. I have trained the model on an image where every pixel is labeled "1". Therefore, when testing the model, I believe every prediction should be "1". Instead the model only predicts "0".

Here is the repository for the whole model: https://github.com/dhasl002/Research-DeepLearning.

Since the code is almost 300 lines, I will include only the relevant code below.

```<code> x = tf.placeholder(tf.float32, shape=[None, 7168])
 y_ = tf.placeholder(tf.float32, shape=[None, 7168, 3])

 W_final = weight_variable([7168,7168,3])
 b_final = bias_variable([7168,3])

 #"final" is the result of the many convolutions
 final_conv = tf.tensordot(final, W_final, axes=[[1], [1]]) + b_final

 cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=final_conv))
 train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
 correct_prediction = tf.equal(tf.argmax(final_conv, 2), tf.argmax(y_, 2))
 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

 #a is a threshold associate with each pixel, b is the label of each pixel
 a = np.zeros((1,7168),dtype = float)
 b = np.zeros((1,7168, 3), dtype = float)

 #this is a little simplified for clarity of reader
 #TRAINING
 for line in inputFile:
   thresh, label = line.strip().split(",")
   a[0][it] = thresh
   b[0][it][label] = 1
 train_step.run(feed_dict={x: a, y_: b, keep_prob: .5})

 #TESTING
 for line in inputFile:
   thresh, label = line.strip().split(",")
   a[0][it] = thresh
   b[0][it][label] = 1
 temp = sess.run(tf.argmax(final_conv,2), feed_dict={x: a})
</code>```

I believe that "temp" from the last line should hold the correct predictions (7168 labels - one per pixel). Why does "temp" always result in all "0" labels when it is actually trained on images only with "1" labels?

答:
The data that you've provided contains not only 1 labels, but occasional 2 as well (you can skim through the text files or simply print the label values to see this). Not only does it contradict your idea to train a constant function, it also breaks the one-hot encoding and, thus, the whole algorithm.

Here's the excerpt from your script:

a = np.zeros((1,N*M*P),dtype = float)
b = np.zeros((1,N*M*P, 3), dtype = float)
[...]

with tf.Session() as sess:
   sess.run(tf.global_variables_initializer())
   parent = "..."
   with open(parent) as inf1:
     next(inf1)
     for line5 in inf1:
       line1, maxNum = line5.strip().split(",")
       path = "..."
       num = 0
       while num < maxNum:
         it = 0
         with open(path + str(num) + ".txt") as inf:
           next(inf)
           num = num + 1
           for line in inf:
             [...]
             a[0][it] = thresh
             b[0][it][label] = 1
             it = it + 1
```

Looking at your code, b is supposed to be a one-hot vector. But note that it's zeroed only when the variable is defined. After that it's assigned to 1 at different indices. The later iterations of the while loop update the same b array, hence it ends up containing several 1 in the later rows of the batch. The cross-entropy loss expects a valid probability distribution, hence with your data its output becomes completely meaningless:

Each row labels[i] must be a valid probability distribution.

Summary: the way you do data processing is too complicated and, as a result, error-prone. Try to organize your input files simpler, so that it could be read into a numpy array (or pandas dataframe) and fed to the session.

Body:
I have a deep CNN that predicts a label between "0" and "2" for every pixel in a 3d image. I have trained the model on an image where every pixel is labeled "1". Therefore, when testing the model, I believe every prediction should be "1". Instead the model only predicts "0".

Here is the repository for the whole model: https://github.com/dhasl002/Research-DeepLearning.

Since the code is almost 300 lines, I will include only the relevant code below.

 x = tf.placeholder(tf.float32, shape=[None, 7168])
 y_ = tf.placeholder(tf.float32, shape=[None, 7168, 3])

 W_final = weight_variable([7168,7168,3])
 b_final = bias_variable([7168,3])

 #"final" is the result of the many convolutions
 final_conv = tf.tensordot(final, W_final, axes=[[1], [1]]) + b_final

 cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=final_conv))
 train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
 correct_prediction = tf.equal(tf.argmax(final_conv, 2), tf.argmax(y_, 2))
 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

 #a is a threshold associate with each pixel, b is the label of each pixel
 a = np.zeros((1,7168),dtype = float)
 b = np.zeros((1,7168, 3), dtype = float)

 #this is a little simplified for clarity of reader
 #TRAINING
 for line in inputFile:
   thresh, label = line.strip().split(",")
   a[0][it] = thresh
   b[0][it][label] = 1
 train_step.run(feed_dict={x: a, y_: b, keep_prob: .5})

 #TESTING
 for line in inputFile:
   thresh, label = line.strip().split(",")
   a[0][it] = thresh
   b[0][it][label] = 1
 temp = sess.run(tf.argmax(final_conv,2), feed_dict={x: a})

I believe that "temp" from the last line should hold the correct predictions (7168 labels - one per pixel). Why does "temp" always result in all "0" labels when it is actually trained on images only with "1" labels?

Body:
The data that you've provided contains not only 1 labels, but occasional 2 as well (you can skim through the text files or simply print the label values to see this). Not only does it contradict your idea to train a constant function, it also breaks the one-hot encoding and, thus, the whole algorithm.

Here's the excerpt from your script:

a = np.zeros((1,N*M*P),dtype = float)
b = np.zeros((1,N*M*P, 3), dtype = float)
[...]

with tf.Session() as sess:
   sess.run(tf.global_variables_initializer())
   parent = "..."
   with open(parent) as inf1:
     next(inf1)
     for line5 in inf1:
       line1, maxNum = line5.strip().split(",")
       path = "..."
       num = 0
       while num < maxNum:
         it = 0
         with open(path + str(num) + ".txt") as inf:
           next(inf)
           num = num + 1
           for line in inf:
             [...]
             a[0][it] = thresh
             b[0][it][label] = 1
             it = it + 1

Looking at your code, b is supposed to be a one-hot vector. But note that it's zeroed only when the variable is defined. After that it's assigned to 1 at different indices. The later iterations of the while loop update the same b array, hence it ends up containing several 1 in the later rows of the batch. The cross-entropy loss expects a valid probability distribution, hence with your data its output becomes completely meaningless:

Each row labels[i] must be a valid probability distribution.

Summary: the way you do data processing is too complicated and, as a result, error-prone. Try to organize your input files simpler, so that it could be read into a numpy array (or pandas dataframe) and fed to the session.


问:
ListView - highlight color of a tapped row
I have a ListView with custom rows. They have different background colors set in the ArrayAdapter inside the getView() method:

row.setBackgroundColor(R.color.list_bg);

After setting the color, I'm loosing the highlight color/animation of a tapped row.
If I add some transparency to the background, I can see the highlight and the animation, but that's not how i'd like to solve this.

Is it possible, to somehow set a "highlight color"?

答:
You can set custom background on your row by creating an drawable with your colors or images. like make an drawable in res/drawable/

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="@color/colorPressEffect"/>
        </shape>
    </item>
    <item android:state_pressed="false">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/transparent"/>
        </shape>
    </item>
</selector>
</code>```

and just set this drawable as background on your row layout parent layout.like

```<code> <LinearLayout
        ...
        ...
         android:background="@drawable/background"
        >
</code>```

You can achieve any animation on click by this way, the more you put effort in drawable the more you will get on click.

Body:
You can set custom background on your row by creating an drawable with your colors or images. like make an drawable in res/drawable/

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="@color/colorPressEffect"/>
        </shape>
    </item>
    <item android:state_pressed="false">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/transparent"/>
        </shape>
    </item>
</selector>

and just set this drawable as background on your row layout parent layout.like

 <LinearLayout
        ...
        ...
         android:background="@drawable/background"
        >

You can achieve any animation on click by this way, the more you put effort in drawable the more you will get on click.


问:
How to count the length of a line in bash such that spaces for indentation are excluded?
I wish to enforce a rule that no line in a python code would be more than 80  characters in length. For this I count the length of the entire line in file using a bash script. However, I need to exclude the starting spaces used for indentation. I wish to start counting from where the first character is seen in the line, until the last character: e.g:

```<code>    this is an example line
</code>```

length() needs to return (31-8=23) rather than 31.

How do I accomplish this using a sed, awk, or grep query?

答:
With posix shell

```<code>a='        this is an example line'
echo "${#a}"
b="${a%%[^ ]*}"
echo "${#b}"
c="${a#$b*}"
echo "${#c}"
</code>```

output

```<code>31
8
23
</code>```

Body:
I wish to enforce a rule that no line in a python code would be more than 80  characters in length. For this I count the length of the entire line in file using a bash script. However, I need to exclude the starting spaces used for indentation. I wish to start counting from where the first character is seen in the line, until the last character: e.g:

    this is an example line

length() needs to return (31-8=23) rather than 31.

How do I accomplish this using a sed, awk, or grep query?

Body:
With posix shell

a='        this is an example line'
echo "${#a}"
b="${a%%[^ ]*}"
echo "${#b}"
c="${a#$b*}"
echo "${#c}"

output

31
8
23


答:
.prev() selects the previous sibling, which the  element isn't. You want:

```<code>$(this).closest("div.buildExMain").find('i.fa').show();
</code>```

or, since its parent is a sibling of the , you could use .parent() and .prev() together like:

```<code>$(this).parent().prev('i.fa').show();
</code>```

Title: jQuery: find the previous sibling with a class name?

Body:
.prev() selects the previous sibling, which the <i> element isn't. You want:

$(this).closest("div.buildExMain").find('i.fa').show();

or, since its parent is a sibling of the <i>, you could use .parent() and .prev() together like:

$(this).parent().prev('i.fa').show();


问:
applescript: set fullscreen of RealPlayer application
I'm in the process of creating a HTPC using my mac mini. I need to be able to start a RealPlayer clip and set it to fullscreen(not maximize window). I've got this so far.

```<code>tell application "RealPlayer"
 open clip with URL "<url>"
end tell
delay 5
tell application "RealPlayer"
 set is full screen of player to true
end tell
</code>```

but when I run it I get this error:

error "Can’t set «class Pfsc» of
  «class R1PC» to true." number -10006
  from «class Pfsc» of «class R1PC»

Open clip works fine, I just can't set it to fullscreen. Any help would be appreciated.

Thank you

here is the property for full screen

player n [inh. item] : A video player.

elements
contains windows; contained by application, windows.

properties

...

is full screen (boolean) : is clip playback in full screen

...

答:
Try using the appropriate keystroke. On the example, it executes Command + F. It's like pressing the command button (using command down), and then the letter F

```<code>tell application "System Events" to keystroke "f" using command down
</code>```

Body:
I'm in the process of creating a HTPC using my mac mini. I need to be able to start a RealPlayer clip and set it to fullscreen(not maximize window). I've got this so far.

tell application "RealPlayer"
 open clip with URL "<url>"
end tell
delay 5
tell application "RealPlayer"
 set is full screen of player to true
end tell

but when I run it I get this error:

error "Can’t set «class Pfsc» of
  «class R1PC» to true." number -10006
  from «class Pfsc» of «class R1PC»

Open clip works fine, I just can't set it to fullscreen. Any help would be appreciated.

Thank you

here is the property for full screen

player n [inh. item] : A video player.

elements
contains windows; contained by application, windows.

properties

...

is full screen (boolean) : is clip playback in full screen

...

Body:
Try using the appropriate keystroke. On the example, it executes Command + F. It's like pressing the command button (using command down), and then the letter F

tell application "System Events" to keystroke "f" using command down