问:
how to list out only specific files in S3 bucket
I have n-number of files in a s3-bucket, where I want to download only specific pattern type of files w.r.t their naming conventions

Code:

```<code>BUCKET_NAME = "MYBucket"
s3_conn  = boto.connect_s3(AWS_keys)
bucket = s3_conn.get_bucket(BUCKET_NAME)

#goto through the list of files
bucket_list = bucket.list(prefix='Test_folder/OUT/abc_')

for l in bucket_list:
    key_string = str(l.key)
    s3_path = DOWNLOAD_LOCATION_PATH + key_string
    try:
       print ("Current File is ", s3_path)
       l.get_contents_to_filename(s3_path)
    except (OSError,S3ResponseError) as e:
         pass
</code>```

Above code works fine for only one type of File Naming ie: abc_

What if I want list of files with pattern like: abc_, axy_, xa_ya_zf_, gelnique_

Any Suggestion?

答:
Instead this Simple looping worked fine for me</p>

```<code>pattern_list = ['abc_', 'axy_', 'xa_ya_zf_', 'gelnique_']
for p in pattern_list:
    prefix ='AB_Test/OUT/' + str(p)
    for k in src_bucket.list(prefix):
          # Do your work!
</code>```

Body:
I have n-number of files in a s3-bucket, where I want to download only specific pattern type of files w.r.t their naming conventions

Code:

BUCKET_NAME = "MYBucket"
s3_conn  = boto.connect_s3(AWS_keys)
bucket = s3_conn.get_bucket(BUCKET_NAME)

#goto through the list of files
bucket_list = bucket.list(prefix='Test_folder/OUT/abc_')

for l in bucket_list:
    key_string = str(l.key)
    s3_path = DOWNLOAD_LOCATION_PATH + key_string
    try:
       print ("Current File is ", s3_path)
       l.get_contents_to_filename(s3_path)
    except (OSError,S3ResponseError) as e:
         pass

Above code works fine for only one type of File Naming ie: abc_

What if I want list of files with pattern like: abc_, axy_, xa_ya_zf_, gelnique_

Any Suggestion?

Body:
Instead this Simple looping worked fine for me

pattern_list = ['abc_', 'axy_', 'xa_ya_zf_', 'gelnique_']
for p in pattern_list:
    prefix ='AB_Test/OUT/' + str(p)
    for k in src_bucket.list(prefix):
          # Do your work!


来源: stackexchange

问:
QSlider increase handle size
I need badly to increase size of handle for my slider, but no css options can do this(styleSheet()).
The default example from Qt docs didn't help me as well.

I have a slider like this:

I wish to increase the height of its handle, as shown on explanation image below, but I can't guess how to do it. Probably the only way is to subclass QAbstractSlider?

Here is the stylesheet from my code:

```<code>                "QSlider::groove:horizontal {"
                "border: 1px solid #999999;"
                "height: 32px;" /* the groove expands to the size of the slider by default. by giving it a height, it has a fixed size */
                "background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #B1B1B1, stop:1 #c4c4c4);"
                "margin: 2px 0; }"
            "QSlider::handle:horizontal {"
                "background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #b4b4b4, stop:1 #8f8f8f);"
                "border: 1px solid #5c5c5c;"
                "width: 40px;"
                "margin: -20px 0;" /* handle is placed by default on the contents rect of the groove. Expand outside the groove */
                "border-radius: 3px;}"
            );
</code>```

答:
Use this stylesheet:

```<code>.QSlider {
    min-height: 68px;
    max-height: 68px;
    background: #5F4141;
}

.QSlider::groove:horizontal {
    border: 1px solid #262626;
    height: 5px;
    background: #393939;
    margin: 0 12px;
}

.QSlider::handle:horizontal {
    background: #22B14C;
    border: 5px solid #B5E61D;
    width: 23px;
    height: 100px;
    margin: -24px -12px;
}
</code>```

It will produce the following:

Please note the the height of the slider is made constant by setting both min-height and max-height to the same value.

ContentLicense: CC BY-SA 3.0

Title: QSlider increase handle size

Body:
I need badly to increase size of handle for my slider, but no css options can do this(styleSheet()).
The default example from Qt docs didn't help me as well.

I have a slider like this:

I wish to increase the height of its handle, as shown on explanation image below, but I can't guess how to do it. Probably the only way is to subclass QAbstractSlider?

Here is the stylesheet from my code:

                "QSlider::groove:horizontal {"
                "border: 1px solid #999999;"
                "height: 32px;" /* the groove expands to the size of the slider by default. by giving it a height, it has a fixed size */
                "background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #B1B1B1, stop:1 #c4c4c4);"
                "margin: 2px 0; }"
            "QSlider::handle:horizontal {"
                "background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #b4b4b4, stop:1 #8f8f8f);"
                "border: 1px solid #5c5c5c;"
                "width: 40px;"
                "margin: -20px 0;" /* handle is placed by default on the contents rect of the groove. Expand outside the groove */
                "border-radius: 3px;}"
            );

Body:
Use this stylesheet:

.QSlider {
    min-height: 68px;
    max-height: 68px;
    background: #5F4141;
}

.QSlider::groove:horizontal {
    border: 1px solid #262626;
    height: 5px;
    background: #393939;
    margin: 0 12px;
}

.QSlider::handle:horizontal {
    background: #22B14C;
    border: 5px solid #B5E61D;
    width: 23px;
    height: 100px;
    margin: -24px -12px;
}

It will produce the following:

Please note the the height of the slider is made constant by setting both min-height and max-height to the same value.


问:
Pandas - Fill column depending on date in dictionary
I am trying to fill a dataframe column with the value of two other columns depending on a date i have in a dictionary. It looks like this:

```<code># the input date
input_date = pd.to_datetime('04.12.2017 12:00:00', format='%d.%m.%Y %H:%M:%S')

# the dict
dict = {'A': pd.to_datetime('06.12.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),
        'B': pd.to_datetime('08.11.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),
        'C': pd.to_datetime('15.10.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),

# the df
d = {'result':[None,None,None],
     'id_1':[1,2,3], 'id_2':[10,20,30],
     'dict_key':['A', 'B', 'A']}
df = pd.DataFrame(d)
</code>```

My criteria is: If the input date is after the date in the dictonary, take id_1, else take id_2

The result would like this:

```<code>    dict_key    id_1    id_2    result
0   A           1       10      10
1   B           2       20      2
2   A           3       30      30
</code>```

Body:
I am trying to fill a dataframe column with the value of two other columns depending on a date i have in a dictionary. It looks like this:

# the input date
input_date = pd.to_datetime('04.12.2017 12:00:00', format='%d.%m.%Y %H:%M:%S')

# the dict
dict = {'A': pd.to_datetime('06.12.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),
        'B': pd.to_datetime('08.11.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),
        'C': pd.to_datetime('15.10.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),

# the df
d = {'result':[None,None,None],
     'id_1':[1,2,3], 'id_2':[10,20,30],
     'dict_key':['A', 'B', 'A']}
df = pd.DataFrame(d)

My criteria is: If the input date is after the date in the dictonary, take id_1, else take id_2

The result would like this:

    dict_key    id_1    id_2    result
0   A           1       10      10
1   B           2       20      2
2   A           3       30      30

Body:
Use:

d1 = {'A': pd.to_datetime('06.12.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),
        'B': pd.to_datetime('08.11.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),
        'C': pd.to_datetime('15.10.2017 12:00:00', format='%d.%m.%Y %H:%M:%S')}

d2 = {k:v for k,v in d1.items() if v > input_date}
print (d2)
{'A': Timestamp('2017-12-06 12:00:00')}

df['result'] = np.where(df.dict_key.isin(d2.keys()), df.id_2, df.id_1)
print (df)
  dict_key  id_1  id_2  result
0        A     1    10      10
1        B     2    20       2
2        A     3    30      30


问:
Do processes need to be stopped manually
I'm new to multiprocessing in Python so I'm in doubt. My first idea was to use threads, but then I read about GIL and moved to multiprocessing.

My question is, when I start a process like this:

```<code>t1 = Process(target=run, args=lot)
t1.start()
</code>```

do I need to stop it somehow from the main process, or they shutdown when the run() method is finished?

I know that things like join() exist, but I'm scheduling a job every n minutes and start a couple of processes in parallel, and this procedure goes until stopped, so I don't really need to wait for processes to finish.

答:
Yes when t1.start() happens it executes the method which is specified in target(i.e run). Once its completed it exits automatically.

You can check this by checking the running process eg in linux use below command,

```<code>"ps -aux |grep python" or "ps -aux |grep "program_name.py"
</code>```

when your target is running count will be more.

To wait until a process has completed its work and exited, use the join() method. But in your case its not required

more example are here : https://pymotw.com/2/multiprocessing/basics.html

Body:
I'm new to multiprocessing in Python so I'm in doubt. My first idea was to use threads, but then I read about GIL and moved to multiprocessing.

My question is, when I start a process like this:

t1 = Process(target=run, args=lot)
t1.start()

do I need to stop it somehow from the main process, or they shutdown when the run() method is finished?

I know that things like join() exist, but I'm scheduling a job every n minutes and start a couple of processes in parallel, and this procedure goes until stopped, so I don't really need to wait for processes to finish.

Body:
Yes when t1.start() happens it executes the method which is specified in target(i.e run). Once its completed it exits automatically.

You can check this by checking the running process eg in linux use below command,

"ps -aux |grep python" or "ps -aux |grep "program_name.py"

when your target is running count will be more.

To wait until a process has completed its work and exited, use the join() method. But in your case its not required

more example are here : https://pymotw.com/2/multiprocessing/basics.html


问:
Is it possible in TFS NOT to trigger a CI build when the content of an active (i.e. NOT cloaked) directory changes?
My scenario is as follows:

Developers check-in SQL changes to directory ClientDB

A dedicated build wakes up, extracts the metadata from the checked-in files, processes it and checks the result in into a sibling directory ClientMetadata

(Developers are not allowed to check-in under ClientMetadata)

The annoying side effect, is that because the dedicated build is a CI build it wakes up twice:

Once for the changes in ClientDB, which makes it update ClientMetadata

Second time, because of its own changes in the ClientMetadata - after all, this directory appears as an Active directory in the Source Settings section of the build:

Ideally, I would like the ClientMetadata directory to be available in the workspace, but I do not want changes there to trigger the build.

Is it possible?

答:
When you select this trigger (CI)  whenever someone checks in code, the build will run.

Actually check in files to source control during a build pipeline is not a recommended suggestion.

If you don't want to cloaked the ClientMetadata folder and still want this be pulled down on build agent during get source. Please try below workaround:

You could remove the active status for this folder and add a customize activity to only get files from TFS server path($/../../ClientMetadata) to the agent $(BuildDir).


问:
C#: How to set default value if input is empty
If I have a method like this:

```<code>public void AddSomething(string ice = "10", string sweet = "20")
{
    Console.Write(ice);
    Console.Write(sweet);
}
</code>```

so if I input a string, it will write the string. If not, it will write the default string(10,20).

But I want something like this:

```<code>public void AddSomething(string ice = "10", string sweet = "20")
{
    if(ice = "")
        ice = default_vaule;    //which is 10
    if(sweet = "")
        sweet = default_vaule;  //which is 20
    Console.Write(ice);
    Console.Write(sweet);
}
</code>```

so if user input a empty string "", I can write the default value to user, so I can do not only this:

```<code>AddSomething("5");
</code>```

Also both of these:

```<code>AddSomething("5","");
AddSomething("","5");
</code>```

Anyone knows how to do that? THX!

答:
So you want to get the default value of a method-parameter at runtime without repeating yourself, so without typing that value again(f.e. to prevent that have you change it there too if you change the default value of the parameter)?

That's not easy because there is no defaultof(parameter)-operator (similar to the nameof-operator). You had to use reflection.

You could use this extension:

```<code>public static class MethodExtensions
{
    public static Result<T> ParameterDefault<T>(this MethodBase m, string paramName)
    {
        ParameterInfo parameter = m.GetParameters()
            .FirstOrDefault(p => p.Name == paramName);
        if (parameter == null)
            throw new ArgumentException($"No parameter with given name '{paramName}' found", nameof(paramName));
        if (parameter.ParameterType != typeof(T))
            throw new ArgumentException($"Parametertype is not '{typeof(T)}' but '{parameter.ParameterType}'");

        if(parameter.HasDefaultValue)
            return new Result<T>((T)parameter.DefaultValue, true);
        else
            return new Result<T>(default(T), false);
    }
}
</code>```

which returns an instance of following class, which is just a wrapper to enable to also return  the information if the default value could be determined:

```<code>public class Result<T>
{
    public Result(T value, bool success)
    {
        Value = value;
        Success = success;
    }
    public T Value { get; private set; }
    public bool Success { get; private set; }
}
</code>```

Now your method looks like:

```<code>public void AddSomething(string ice = "10", string sweet = "20")
{
    MethodBase m = MethodBase.GetCurrentMethod();
    if (ice == "")
        ice = m.ParameterDefault<string>(nameof(ice)).Value;
    if (sweet == "")
        sweet = m.ParameterDefault<string>(nameof(sweet)).Value;
    Console.Write(ice);
    Console.Write(sweet);
}
</code>```

and you don't need to repeat the parameter value.

Body:
If I have a method like this:

public void AddSomething(string ice = "10", string sweet = "20")
{
    Console.Write(ice);
    Console.Write(sweet);
}

so if I input a string, it will write the string. If not, it will write the default string(10,20).

But I want something like this:

public void AddSomething(string ice = "10", string sweet = "20")
{
    if(ice = "")
        ice = default_vaule;    //which is 10
    if(sweet = "")
        sweet = default_vaule;  //which is 20
    Console.Write(ice);
    Console.Write(sweet);
}

so if user input a empty string "", I can write the default value to user, so I can do not only this:

AddSomething("5");

Also both of these:

AddSomething("5","");
AddSomething("","5");

Anyone knows how to do that? THX!

Body:
So you want to get the default value of a method-parameter at runtime without repeating yourself, so without typing that value again(f.e. to prevent that have you change it there too if you change the default value of the parameter)?

That's not easy because there is no defaultof(parameter)-operator (similar to the nameof-operator). You had to use reflection.

You could use this extension:

public static class MethodExtensions
{
    public static Result<T> ParameterDefault<T>(this MethodBase m, string paramName)
    {
        ParameterInfo parameter = m.GetParameters()
            .FirstOrDefault(p => p.Name == paramName);
        if (parameter == null)
            throw new ArgumentException($"No parameter with given name '{paramName}' found", nameof(paramName));
        if (parameter.ParameterType != typeof(T))
            throw new ArgumentException($"Parametertype is not '{typeof(T)}' but '{parameter.ParameterType}'");

        if(parameter.HasDefaultValue)
            return new Result<T>((T)parameter.DefaultValue, true);
        else
            return new Result<T>(default(T), false);
    }
}

which returns an instance of following class, which is just a wrapper to enable to also return  the information if the default value could be determined:

public class Result<T>
{
    public Result(T value, bool success)
    {
        Value = value;
        Success = success;
    }
    public T Value { get; private set; }
    public bool Success { get; private set; }
}

Now your method looks like:

public void AddSomething(string ice = "10", string sweet = "20")
{
    MethodBase m = MethodBase.GetCurrentMethod();
    if (ice == "")
        ice = m.ParameterDefault<string>(nameof(ice)).Value;
    if (sweet == "")
        sweet = m.ParameterDefault<string>(nameof(sweet)).Value;
    Console.Write(ice);
    Console.Write(sweet);
}

and you don't need to repeat the parameter value.


问:
UNIX System Call Listing?
I have an assignment where I need to use some system calls in UNIX, like mktime() and fnmatch(), to complete some operations. We're given only the names of the man pages to look up to find the functions.

Now, this is fine for the purpose of the assignment. But in the future when I do UNIX programming, I may not know the exact name (I never would have known fnmatch exists without knowing its name first).

So the question is: how can I get a comprehensive list of ALL UNIX system functions? I really don't care if it's categorized or sorted (though it would be nice), but I'd like to have the list include the descriptions so it's searchable. That way when I need a function, I can do a few searches to locate potential candidates, then I can man them to find the exact usage.

答: I used to keep a printed copy of part of "The Authorized Guide to Version 3 of the Single UNIX Specification" lying around - the table shows availability of calls in a variety of different standards, which was extremely useful for supporting multiple targets. </p>

ContentLicense: CC BY-SA 2.5

Title: UNIX System Call Listing?


问:
Performance dynamic vs Reflection
I have the following possibilities to retrieve values in a list:

using reflection:

```<code>foreach (var item in items) {
  var property=item.Fields[fieldName].GetType().GetProperty("Id");
  var value=property.GetValue(item.Fields[fieldName]);
  if (value==searchValue) {
      filtered.Add(item);
   }
}
</code>```

using dynamic:

```<code>foreach (var item in items) {
   dynamic itemProperty=item.Fields[fieldName];
   if (itemProperty.Id==searchValue) {
      filtered.Add(item);
   }
}
</code>```

Both loops do the same. They filter the IEnumerable (or List) by Field[fieldName] which can be of different types but which all contain a int-property called "Id".

I wonder, which one would have a better performance.
In addition: Would changing one of those to a LinQ-Query increase the performance?

答:
The easiest way to do this IMO is to define an interface that has an int Id {get;} property and have your types implement it. Then code to the interface. If your existing code is generic you might even be able to add awhere T : IYourInterface constraint, but you can cast to IYourInterface either way (assuming T actually does implement the interface).

If interfaces aren't an option:

Reflection and dynamic both have overheads; dynamic has better optimization (re-using a cached strategy).

If your items list is strongly typed to a specific T (where T is unknown here), then you can possibly further optimize this concept using LINQ expressions to compile delegates:

```<code>static class IdFetcher
{
    public static int Fetch<T>(T item) => IdFetcher<T>.Fetch(item);
}
static class IdFetcher<T>
{
    public static int Fetch(T item) => fetch(item);
    static readonly Func<T, int> fetch;
    static IdFetcher()
    {
        var p = Expression.Parameter(typeof(T), "item");
        fetch = Expression.Lambda<Func<T, int>>(
            Expression.PropertyOrField(p, "Id"), p).Compile();
    }
}
</code>```

Then just use IdFetcher<T>.Fetch(obj) or IdFetcher.Fetch(obj) (the first is more direct; the second is useful for anonymous types where you can't specify the T)

Other than that: if you want to know which is faster: time them (for large numbers of iterations).

Title: Performance dynamic vs Reflection

Body:
I have the following possibilities to retrieve values in a list:

using reflection:

foreach (var item in items) {
  var property=item.Fields[fieldName].GetType().GetProperty("Id");
  var value=property.GetValue(item.Fields[fieldName]);
  if (value==searchValue) {
      filtered.Add(item);
   }
}

using dynamic:

foreach (var item in items) {
   dynamic itemProperty=item.Fields[fieldName];
   if (itemProperty.Id==searchValue) {
      filtered.Add(item);
   }
}

Both loops do the same. They filter the IEnumerable (or List) by Field[fieldName] which can be of different types but which all contain a int-property called "Id".

I wonder, which one would have a better performance.
In addition: Would changing one of those to a LinQ-Query increase the performance?

Body:
The easiest way to do this IMO is to define an interface that has an int Id {get;} property and have your types implement it. Then code to the interface. If your existing code is generic you might even be able to add awhere T : IYourInterface constraint, but you can cast to IYourInterface either way (assuming T actually does implement the interface).

If interfaces aren't an option:

Reflection and dynamic both have overheads; dynamic has better optimization (re-using a cached strategy).

If your items list is strongly typed to a specific T (where T is unknown here), then you can possibly further optimize this concept using LINQ expressions to compile delegates:

static class IdFetcher
{
    public static int Fetch<T>(T item) => IdFetcher<T>.Fetch(item);
}
static class IdFetcher<T>
{
    public static int Fetch(T item) => fetch(item);
    static readonly Func<T, int> fetch;
    static IdFetcher()
    {
        var p = Expression.Parameter(typeof(T), "item");
        fetch = Expression.Lambda<Func<T, int>>(
            Expression.PropertyOrField(p, "Id"), p).Compile();
    }
}

Then just use IdFetcher<T>.Fetch(obj) or IdFetcher.Fetch(obj) (the first is more direct; the second is useful for anonymous types where you can't specify the T)

Other than that: if you want to know which is faster: time them (for large numbers of iterations).


问:
Access Vuex $store.getters in component method()
I am trying to populate a dropdown Asynchronously (https://vuetifyjs.com/components/selects) using Vuex and Vuetify for a search box. My problem is that I cannot access the $store using the method(), only computed() of course.

Here are my getters/state:

```<code>loadedTours:Array[9]
0:Object
1:Object
2:Object
3:Object
4:Object
5:Object
6:Object
7:Object
8:Object
9:Object
</code>```

which can be returned using v-for from the computed()

```<code>tours () {
    return this.$store.getters.loadedTours
},
</code>```

Here is a method() that works only if the list is in the data():

```<code>methods: {
    querySelections (v) {
        this.loading = true
            setTimeout(() => {
                this.items = this.tours.filter(e => {
                    return (e || '').toLowerCase().indexOf((v || '').toLowerCase()) > -1
                })
            this.loading = false
        }, 500)
    }
}
</code>```

The result should return the tour titles listed in each object.

Current solution:

added created():

```<code>created () {
    this.loadedTours = this.$store.getters.loadedTours
},
</code>```

changed method() to:

```<code>querySelections (v) {
    let that = this;
    setTimeout(() => {
        that.items = that.loadedTours
    }, 500)
}
</code>```

Removed the arrow function at the data property.

Now need to return the tourTitle, then filter by the input.

答:
In addition to what I mentioned in the comments, your main error is probably because you are using this inside the arrow function, because this will not refer to the right (vuejs) context,

From the documentation:

Note that you should not use an arrow function with the data property (e.g. data: () => { return { a: this.myProp }}). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.myProp will be undefined.

instead do something like this:

```<code>  let that = this;
  setTimeout(() => callback(that.name), 15);
</code>```

Now, that will refer to use vuejs this object

Body:
I am trying to populate a dropdown Asynchronously (https://vuetifyjs.com/components/selects) using Vuex and Vuetify for a search box. My problem is that I cannot access the $store using the method(), only computed() of course.

Here are my getters/state:

loadedTours:Array[9]
0:Object
1:Object
2:Object
3:Object
4:Object
5:Object
6:Object
7:Object
8:Object
9:Object

which can be returned using v-for from the computed()

tours () {
    return this.$store.getters.loadedTours
},

Here is a method() that works only if the list is in the data():

methods: {
    querySelections (v) {
        this.loading = true
            setTimeout(() => {
                this.items = this.tours.filter(e => {
                    return (e || '').toLowerCase().indexOf((v || '').toLowerCase()) > -1
                })
            this.loading = false
        }, 500)
    }
}

The result should return the tour titles listed in each object.

Current solution:

added created():

created () {
    this.loadedTours = this.$store.getters.loadedTours
},

changed method() to:

querySelections (v) {
    let that = this;
    setTimeout(() => {
        that.items = that.loadedTours
    }, 500)
}

Removed the arrow function at the data property.

Now need to return the tourTitle, then filter by the input.

Body:
In addition to what I mentioned in the comments, your main error is probably because you are using this inside the arrow function, because this will not refer to the right (vuejs) context,

From the documentation:

Note that you should not use an arrow function with the data property (e.g. data: () => { return { a: this.myProp }}). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.myProp will be undefined.

instead do something like this:

  let that = this;
  setTimeout(() => callback(that.name), 15);

Now, that will refer to use vuejs this object

ContentLicense: CC BY-SA 4.0


问:
Print a file saved in C #
I'm trying to print in winform, it turns out that when I print the document, I get the blank sheet.
This is the code with which I try to print:

```<code>    private PrintDocument printDocument1 = new PrintDocument();
    private string stringToPrint;
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ReadPrint();
        printDocument1.Print();
    }

    private void ReadPrint()
    {
        string docName = "ejemplo.pdf";
        string docPath = @"C:\dir1\";
        printDocument1.DocumentName = docName;
        using (FileStream stream = new FileStream(docPath + docName, FileMode.Open, FileAccess.Read))
        using (StreamReader reader = new StreamReader(stream))
        {
            stringToPrint = reader.ReadToEnd();
        }
    }

    private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
    {
        int charactersOnPage = 0;
        int linesPerPage = 0;

        e.Graphics.MeasureString(stringToPrint, this.Font,
            e.MarginBounds.Size, StringFormat.GenericTypographic,
            out charactersOnPage, out linesPerPage);

        e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black,
            e.MarginBounds, StringFormat.GenericTypographic);

        stringToPrint = stringToPrint.Substring(charactersOnPage);

        e.HasMorePages = (stringToPrint.Length > 0);
    }

    private void printButton_Click(object sender, EventArgs e)
    {
        LeerArchivo();
        printDocument1.Print();
    }
</code>```

I would like to know if there is a way to correct it or some other way to print the file?Or some example code?
regards

In stringToPrint:

答:
Vb.net has a PrintForm method but C# does not have inbuilt method for printing a Windows Form.

To print a windows form at runtime in C#.net. The base concept involves the capture of  the screen image of a Form in jpeg format during runtime and printing the same on a event like Print button click.

print

Title: Print a file saved in C #

Body:
I'm trying to print in winform, it turns out that when I print the document, I get the blank sheet.
This is the code with which I try to print:

    private PrintDocument printDocument1 = new PrintDocument();
    private string stringToPrint;
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ReadPrint();
        printDocument1.Print();
    }

    private void ReadPrint()
    {
        string docName = "ejemplo.pdf";
        string docPath = @"C:\dir1\";
        printDocument1.DocumentName = docName;
        using (FileStream stream = new FileStream(docPath + docName, FileMode.Open, FileAccess.Read))
        using (StreamReader reader = new StreamReader(stream))
        {
            stringToPrint = reader.ReadToEnd();
        }
    }

    private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
    {
        int charactersOnPage = 0;
        int linesPerPage = 0;

        e.Graphics.MeasureString(stringToPrint, this.Font,
            e.MarginBounds.Size, StringFormat.GenericTypographic,
            out charactersOnPage, out linesPerPage);

        e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black,
            e.MarginBounds, StringFormat.GenericTypographic);

        stringToPrint = stringToPrint.Substring(charactersOnPage);

        e.HasMorePages = (stringToPrint.Length > 0);
    }

    private void printButton_Click(object sender, EventArgs e)
    {
        LeerArchivo();
        printDocument1.Print();
    }

I would like to know if there is a way to correct it or some other way to print the file?Or some example code?
regards

In stringToPrint:


问:
Python from Windows to Centos -> import msvcrt getch issue
I have a stupid question I think.

I have a script develloped on Windows but the goal is to run it on a Centos Server 7. The script work well on windows but not on Centos.

I have this error :

```<code>[root@114697 scripts]# python3.6 synch.py
Traceback (most recent call last):
File "synch.py", line 9, in <module>
from msvcrt import getch
ModuleNotFoundError: No module named 'msvcrt'
</code>```

My script start with this :

```<code>from __future__ import division
import websocket
import thread
import time
import random
import sys
import json
import pymysql
import datetime
from time import ctime
from time import sleep
from msvcrt import getch
from pprint import pprint
import os
</code>```

Seems msvcrt import getchcome from Microsoft ...
Can some one help to solve this problem please ?

Note : Python 3.6 is not involved, it was compiled in a clean way on the server.
Seems

Yoki

答:
Solved ! I just remove

```<code>from msvcrt import getch
</code>```

In fact in don't need to interact with the script on Centos ... it is a deamon :)

Body:
I have a stupid question I think.

I have a script develloped on Windows but the goal is to run it on a Centos Server 7. The script work well on windows but not on Centos.

I have this error :

[root@114697 scripts]# python3.6 synch.py
Traceback (most recent call last):
File "synch.py", line 9, in <module>
from msvcrt import getch
ModuleNotFoundError: No module named 'msvcrt'

My script start with this :

from __future__ import division
import websocket
import thread
import time
import random
import sys
import json
import pymysql
import datetime
from time import ctime
from time import sleep
from msvcrt import getch
from pprint import pprint
import os

Seems msvcrt import getchcome from Microsoft ...
Can some one help to solve this problem please ?

Note : Python 3.6 is not involved, it was compiled in a clean way on the server.
Seems

Yoki

Body:
Solved ! I just remove

from msvcrt import getch

In fact in don't need to interact with the script on Centos ... it is a deamon :)


问:
Navigation Drawer can't navigate
i'm trying to make a navigation to one of my fragment but I can't seem to invoke that fragment here's my code

MainActivity.java

package ics115_4ite_lim.bookings;

import android.app.Fragment;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import ics115_4ite_lim.bookings.Fragments.ScheduleFragment;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.

        Fragment fragment = null;
        int id = item.getItemId();

        if (id == R.id.schedule_fragment) {
            fragment = new ScheduleFragment();
        } else if (id == R.id.driver_fragment) {

        } else if (id == R.id.transaction_fragment) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}```
</div>
</div>
</p>

<p>and this is the fragment I want to go to</p>

<p><strong>ScheduleFragment.java</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>package ics115_4ite_lim.bookings.Fragments;

import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.daimajia.swipe.SwipeLayout;
import com.daimajia.swipe.adapters.RecyclerSwipeAdapter;
import com.daimajia.swipe.util.Attributes;

import java.util.ArrayList;

import ics115_4ite_lim.bookings.DividerItemDecoration;
import ics115_4ite_lim.bookings.R;
import ics115_4ite_lim.bookings.Student;

/**
 * Created by Mark Terrance on 12/7/2017.
 */

public class ScheduleFragment extends Fragment {

    private ArrayList<Student> mDataSet;
    private Toolbar toolbar;
    private TextView tvEmptyView;
    private RecyclerView mRecyclerView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //Inflate the layout for this fragment_packages
        final View view = inflater.inflate(R.layout.schedule_fragment, container, false);
        initScheduleView(view);

        return view;
    }

    private void initScheduleView(View view){

        mRecyclerView = view.findViewById(R.id.recycleView);

        // Layout Managers:
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        // Item Decorator:
        //mRecyclerView.addItemDecoration(new DividerItemDecoration(getResources().getDrawable(R.drawable.divider)));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getResources().getDrawable(R.drawable.divider)));

        mDataSet = new ArrayList<Student>();

        loadData();

        if (mDataSet.isEmpty()) {
            mRecyclerView.setVisibility(View.GONE);
            tvEmptyView.setVisibility(View.VISIBLE);

        } else {
            mRecyclerView.setVisibility(View.VISIBLE);
            tvEmptyView.setVisibility(View.GONE);
        }

        // Creating Adapter object
        SwipeRecyclerViewAdapter mAdapter = new SwipeRecyclerViewAdapter(getActivity(), mDataSet);

        // Setting Mode to Single to reveal bottom View for one item in List
        // Setting Mode to Mutliple to reveal bottom Views for multile items in List
        ((SwipeRecyclerViewAdapter) mAdapter).setMode(Attributes.Mode.Single);

        mRecyclerView.setAdapter(mAdapter);

        /* Scroll Listeners */
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.e("RecyclerView", "onScrollStateChanged");
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    // load initial data
    public void loadData() {

        for (int i = 0; i <= 20; i++) {
            mDataSet.add(new Student("Student " + i, "androidstudent" + i + "@gmail.com"));

        }

    }

    private class SwipeRecyclerViewAdapter extends RecyclerSwipeAdapter<SwipeRecyclerViewAdapter.SimpleViewHolder> {

        private Context mContext;
        private ArrayList<Student> studentList;

        public SwipeRecyclerViewAdapter(Context context, ArrayList<Student> objects) {
            this.mContext = context;
            this.studentList = objects;
        }

        @Override
        public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.swipe_row_item, parent, false);
            return new SimpleViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final SimpleViewHolder viewHolder, final int position) {
            final Student item = studentList.get(position);

            viewHolder.tvName.setText((item.getName()) + "  -  Row Position " + position);
            viewHolder.tvEmailId.setText(item.getEmailId());

            viewHolder.swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);

            // Drag From Left
            viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Left, viewHolder.swipeLayout.findViewById(R.id.bottom_wrapper1));

            // Drag From Right
            viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Right, viewHolder.swipeLayout.findViewById(R.id.bottom_wrapper));

            // Handling different events when swiping
            viewHolder.swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
                @Override
                public void onClose(SwipeLayout layout) {
                    //when the SurfaceView totally cover the BottomView.
                }

                @Override
                public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
                    //you are swiping.
                }

                @Override
                public void onStartOpen(SwipeLayout layout) {

                }

                @Override
                public void onOpen(SwipeLayout layout) {
                    //when the BottomView totally show.
                }

                @Override
                public void onStartClose(SwipeLayout layout) {

                }

                @Override
                public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
                    //when user's hand released.
                }
            });

        /*viewHolder.swipeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if ((((SwipeLayout) v).getOpenStatus() == SwipeLayout.Status.Close)) {
                    //Start your activity

                    Toast.makeText(mContext, " onClick : " + item.getName() + " \n" + item.getEmailId(), Toast.LENGTH_SHORT).show();
                }

            }
        });*/

            viewHolder.swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(mContext, " onClick : " + item.getName() + " \n" + item.getEmailId(), Toast.LENGTH_SHORT).show();
                }
            });

            viewHolder.btnLocation.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Toast.makeText(v.getContext(), "Clicked on Map " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
                }
            });

            viewHolder.tvShare.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Toast.makeText(view.getContext(), "Clicked on Share " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
                }
            });

            viewHolder.tvEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Toast.makeText(view.getContext(), "Clicked on Edit  " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
                }
            });

            viewHolder.tvDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mItemManger.removeShownLayouts(viewHolder.swipeLayout);
                    studentList.remove(position);
                    notifyItemRemoved(position);
                    notifyItemRangeChanged(position, studentList.size());
                    mItemManger.closeAllItems();
                    Toast.makeText(view.getContext(), "Deleted " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
                }
            });

            // mItemManger is member in RecyclerSwipeAdapter Class
            mItemManger.bindView(viewHolder.itemView, position);

        }

        @Override
        public int getItemCount() {
            return studentList.size();
        }

        @Override
        public int getSwipeLayoutResourceId(int position) {
            return R.id.swipe;
        }

        //  ViewHolder Class

        public class SimpleViewHolder extends RecyclerView.ViewHolder {
            SwipeLayout swipeLayout;
            TextView tvName;
            TextView tvEmailId;
            TextView tvDelete;
            TextView tvEdit;
            TextView tvShare;
            ImageButton btnLocation;

            public SimpleViewHolder(View itemView) {
                super(itemView);
                swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
                tvName = (TextView) itemView.findViewById(R.id.tvName);
                tvEmailId = (TextView) itemView.findViewById(R.id.tvEmailId);
                tvDelete = (TextView) itemView.findViewById(R.id.tvDelete);
                tvEdit = (TextView) itemView.findViewById(R.id.tvEdit);
                tvShare = (TextView) itemView.findViewById(R.id.tvShare);
                btnLocation = (ImageButton) itemView.findViewById(R.id.btnLocation);

            }
        }
    }
}</code>```

I have tried debugging it and I ended up on a null fragment

I don't know what's wrong because I just followed a tutorial

Help pls ? thanks :D

edit:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="ics115_4ite_lim.bookings.MainActivity"
    tools:showIn="@layout/app_bar_main">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</RelativeLayout>```

答:
You need to actually do something with the Fragment you created.

```<code>@SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.

        Fragment fragment = null;
        int id = item.getItemId();

        if (id == R.id.schedule_fragment) {
            fragment = new ScheduleFragment();
        } else if (id == R.id.driver_fragment) {

        } else if (id == R.id.transaction_fragment) {

        }

        getSupportFragmentManager().beginTransaction()
            .replace(R.id.container_id, fragment).commit();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
</code>```

Make sure your fragment is not null, all your if branches should
initialize it to something

R.id.container_id should be an id of a ViewGroup in your layout that is empty and this is where the fragment will be placed.

Title: Navigation Drawer can't navigate

Body:
i'm trying to make a navigation to one of my fragment but I can't seem to invoke that fragment here's my code

MainActivity.java

package ics115_4ite_lim.bookings;

import android.app.Fragment;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import ics115_4ite_lim.bookings.Fragments.ScheduleFragment;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.

        Fragment fragment = null;
        int id = item.getItemId();

        if (id == R.id.schedule_fragment) {
            fragment = new ScheduleFragment();
        } else if (id == R.id.driver_fragment) {

        } else if (id == R.id.transaction_fragment) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

and this is the fragment I want to go to

ScheduleFragment.java

package ics115_4ite_lim.bookings.Fragments;

import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.daimajia.swipe.SwipeLayout;
import com.daimajia.swipe.adapters.RecyclerSwipeAdapter;
import com.daimajia.swipe.util.Attributes;

import java.util.ArrayList;

import ics115_4ite_lim.bookings.DividerItemDecoration;
import ics115_4ite_lim.bookings.R;
import ics115_4ite_lim.bookings.Student;

/**
 * Created by Mark Terrance on 12/7/2017.
 */

public class ScheduleFragment extends Fragment {

    private ArrayList<Student> mDataSet;
    private Toolbar toolbar;
    private TextView tvEmptyView;
    private RecyclerView mRecyclerView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //Inflate the layout for this fragment_packages
        final View view = inflater.inflate(R.layout.schedule_fragment, container, false);
        initScheduleView(view);

        return view;
    }

    private void initScheduleView(View view){

        mRecyclerView = view.findViewById(R.id.recycleView);

        // Layout Managers:
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        // Item Decorator:
        //mRecyclerView.addItemDecoration(new DividerItemDecoration(getResources().getDrawable(R.drawable.divider)));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getResources().getDrawable(R.drawable.divider)));

        mDataSet = new ArrayList<Student>();

        loadData();

        if (mDataSet.isEmpty()) {
            mRecyclerView.setVisibility(View.GONE);
            tvEmptyView.setVisibility(View.VISIBLE);

        } else {
            mRecyclerView.setVisibility(View.VISIBLE);
            tvEmptyView.setVisibility(View.GONE);
        }

        // Creating Adapter object
        SwipeRecyclerViewAdapter mAdapter = new SwipeRecyclerViewAdapter(getActivity(), mDataSet);

        // Setting Mode to Single to reveal bottom View for one item in List
        // Setting Mode to Mutliple to reveal bottom Views for multile items in List
        ((SwipeRecyclerViewAdapter) mAdapter).setMode(Attributes.Mode.Single);

        mRecyclerView.setAdapter(mAdapter);

        /* Scroll Listeners */
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.e("RecyclerView", "onScrollStateChanged");
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    // load initial data
    public void loadData() {

        for (int i = 0; i <= 20; i++) {
            mDataSet.add(new Student("Student " + i, "androidstudent" + i + "@gmail.com"));

        }

    }

    private class SwipeRecyclerViewAdapter extends RecyclerSwipeAdapter<SwipeRecyclerViewAdapter.SimpleViewHolder> {

        private Context mContext;
        private ArrayList<Student> studentList;

        public SwipeRecyclerViewAdapter(Context context, ArrayList<Student> objects) {
            this.mContext = context;
            this.studentList = objects;
        }

        @Override
        public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.swipe_row_item, parent, false);
            return new SimpleViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final SimpleViewHolder viewHolder, final int position) {
            final Student item = studentList.get(position);

            viewHolder.tvName.setText((item.getName()) + "  -  Row Position " + position);
            viewHolder.tvEmailId.setText(item.getEmailId());

            viewHolder.swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);

            // Drag From Left
            viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Left, viewHolder.swipeLayout.findViewById(R.id.bottom_wrapper1));

            // Drag From Right
            viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Right, viewHolder.swipeLayout.findViewById(R.id.bottom_wrapper));

            // Handling different events when swiping
            viewHolder.swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
                @Override
                public void onClose(SwipeLayout layout) {
                    //when the SurfaceView totally cover the BottomView.
                }

                @Override
                public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
                    //you are swiping.
                }

                @Override
                public void onStartOpen(SwipeLayout layout) {

                }

                @Override
                public void onOpen(SwipeLayout layout) {
                    //when the BottomView totally show.
                }

                @Override
                public void onStartClose(SwipeLayout layout) {

                }

                @Override
                public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
                    //when user's hand released.
                }
            });

        /*viewHolder.swipeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if ((((SwipeLayout) v).getOpenStatus() == SwipeLayout.Status.Close)) {
                    //Start your activity

                    Toast.makeText(mContext, " onClick : " + item.getName() + " \n" + item.getEmailId(), Toast.LENGTH_SHORT).show();
                }

            }
        });*/

            viewHolder.swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(mContext, " onClick : " + item.getName() + " \n" + item.getEmailId(), Toast.LENGTH_SHORT).show();
                }
            });

            viewHolder.btnLocation.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Toast.makeText(v.getContext(), "Clicked on Map " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
                }
            });

            viewHolder.tvShare.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Toast.makeText(view.getContext(), "Clicked on Share " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
                }
            });

            viewHolder.tvEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Toast.makeText(view.getContext(), "Clicked on Edit  " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
                }
            });

            viewHolder.tvDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mItemManger.removeShownLayouts(viewHolder.swipeLayout);
                    studentList.remove(position);
                    notifyItemRemoved(position);
                    notifyItemRangeChanged(position, studentList.size());
                    mItemManger.closeAllItems();
                    Toast.makeText(view.getContext(), "Deleted " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
                }
            });

            // mItemManger is member in RecyclerSwipeAdapter Class
            mItemManger.bindView(viewHolder.itemView, position);

        }

        @Override
        public int getItemCount() {
            return studentList.size();
        }

        @Override
        public int getSwipeLayoutResourceId(int position) {
            return R.id.swipe;
        }

        //  ViewHolder Class

        public class SimpleViewHolder extends RecyclerView.ViewHolder {
            SwipeLayout swipeLayout;
            TextView tvName;
            TextView tvEmailId;
            TextView tvDelete;
            TextView tvEdit;
            TextView tvShare;
            ImageButton btnLocation;

            public SimpleViewHolder(View itemView) {
                super(itemView);
                swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
                tvName = (TextView) itemView.findViewById(R.id.tvName);
                tvEmailId = (TextView) itemView.findViewById(R.id.tvEmailId);
                tvDelete = (TextView) itemView.findViewById(R.id.tvDelete);
                tvEdit = (TextView) itemView.findViewById(R.id.tvEdit);
                tvShare = (TextView) itemView.findViewById(R.id.tvShare);
                btnLocation = (ImageButton) itemView.findViewById(R.id.btnLocation);

            }
        }
    }
}

I have tried debugging it and I ended up on a null fragment

I don't know what's wrong because I just followed a tutorial

Help pls ? thanks :D

edit:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="ics115_4ite_lim.bookings.MainActivity"
    tools:showIn="@layout/app_bar_main">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</RelativeLayout>

Body:
You need to actually do something with the Fragment you created.

@SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.

        Fragment fragment = null;
        int id = item.getItemId();

        if (id == R.id.schedule_fragment) {
            fragment = new ScheduleFragment();
        } else if (id == R.id.driver_fragment) {

        } else if (id == R.id.transaction_fragment) {

        }

        getSupportFragmentManager().beginTransaction()
            .replace(R.id.container_id, fragment).commit();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

Make sure your fragment is not null, all your if branches should
initialize it to something

R.id.container_id should be an id of a ViewGroup in your layout that is empty and this is where the fragment will be placed.


问:
LEFT JOIN confusion -- I need to retrieve a student count
I have four tables:

```<code>students
classes
teachers
teacher_assignments
</code>```

classes and teachers has a many-to-many relationship and so teacher_assignments acts as the xref table (with fields teacher_id and class_id).

Each student in students has a class_id (many-to-one -- many students to one class).

I should also mention that teacher_assignments has an active column (BOOL) which indicates whether that assignment is currently active

What I want to do:

I want to retrieve the following:

class_name -- a concat of its level and sub_level, e.g. 3 and A

teacher_names -- the names of the teachers currently assigned to that class

student_count -- a count of the students in each class

At first, I tried retrieving just the class_name and teacher_names, like so:

```<code>SELECT
    CONCAT(CONVERT(classes.level, CHAR(8)), classes.sub_level) AS class_name,
    GROUP_CONCAT(DISTINCT teachers.name SEPARATOR ',') AS teacher_names

FROM
    teacher_assignments
        LEFT JOIN teachers
            ON teachers.id = teacher_assignments.teacher_id
            AND teacher_assignments.active = TRUE
        LEFT JOIN classes
            ON classes.id = teacher_assignments.class_id

GROUP BY classes.id
</code>```

This works fine and outputs:

```<code> class_name | teacher_names
 --------------------------------------
 1A         | NULL
 2A         | John, Sam
 3B         | Sam, Sarah
</code>```

(Class 1A has no teachers currently, and so the NULL is expected)

... BUT, now I have no idea how to work the student_count into this.

My question:

How exactly should the students table be joined with the others in the above query so I can produce a student_count column?

答:
I dont think I would use a join but instead would use an inline column select on student like this:</p>

```<code>SELECT
  CONCAT(CONVERT(classes.level, CHAR(8)), classes.sub_level) AS class_name,
  GROUP_CONCAT(DISTINCT teachers.name SEPARATOR ',') AS teacher_names,
  ( SELECT COUNT(*) FROM students WHERE students.class_id = classes.id ) AS student_count
FROM ...
</code>```

Body:
I have four tables:

students
classes
teachers
teacher_assignments

classes and teachers has a many-to-many relationship and so teacher_assignments acts as the xref table (with fields teacher_id and class_id).

Each student in students has a class_id (many-to-one -- many students to one class).

I should also mention that teacher_assignments has an active column (BOOL) which indicates whether that assignment is currently active

What I want to do:

I want to retrieve the following:

class_name -- a concat of its level and sub_level, e.g. 3 and A

teacher_names -- the names of the teachers currently assigned to that class

student_count -- a count of the students in each class

At first, I tried retrieving just the class_name and teacher_names, like so:

SELECT
    CONCAT(CONVERT(classes.level, CHAR(8)), classes.sub_level) AS class_name,
    GROUP_CONCAT(DISTINCT teachers.name SEPARATOR ',') AS teacher_names

FROM
    teacher_assignments
        LEFT JOIN teachers
            ON teachers.id = teacher_assignments.teacher_id
            AND teacher_assignments.active = TRUE
        LEFT JOIN classes
            ON classes.id = teacher_assignments.class_id

GROUP BY classes.id

This works fine and outputs:

 class_name | teacher_names
 --------------------------------------
 1A         | NULL
 2A         | John, Sam
 3B         | Sam, Sarah

(Class 1A has no teachers currently, and so the NULL is expected)

... BUT, now I have no idea how to work the student_count into this.

My question:

How exactly should the students table be joined with the others in the above query so I can produce a student_count column?

Body:
I dont think I would use a join but instead would use an inline column select on student like this:

SELECT
  CONCAT(CONVERT(classes.level, CHAR(8)), classes.sub_level) AS class_name,
  GROUP_CONCAT(DISTINCT teachers.name SEPARATOR ',') AS teacher_names,
  ( SELECT COUNT(*) FROM students WHERE students.class_id = classes.id ) AS student_count
FROM ...


问:
Should you separate matrix data and math?
I am trying to make some simple classes to do the math necessary for OpenGL transformations. However, now that I am about halfway and while looking through different examples I find that most libraries keep the math separate of the matrix class itself (most of the times in math class with static methods). What exactly is the reason for this?

Is it when you're creating multiple of the matrix objects that the functions are also created multiple times, which impacts performance or something else entirely?

Example:
I find it much easier to add the math functions to the matrix class so I dont need to pass the matrix itself to the functions: e.g.

```<code>class Matrix4f {

    //constructor...

    public void rotate(double theta) {
        setValue(0, 0, (float) Math.cos(theta));
        setValue(1, 0, (float) Math.sin(theta));
        setValue(0, 1, (float) Math.sin(theta));
        setValue(1, 1, (float) Math.cos(theta));
    }

    //getters and setters...
}
</code>```

instead of

```<code>public class LinearAlgebraMath {
    public static Matrix4f rotate(Matrix4f target, double theta) {
        target.setValue(0, 0, (float) Math.cos(theta));
        target.setValue(1, 0, (float) Math.sin(theta));
        target.setValue(0, 1, (float) Math.sin(theta));
        target.setValue(1, 1, (float) Math.cos(theta));
        return target;
    }
}

public class Matrix4f {

    //constructor...

    //getters and setters...
}
</code>```

So, in the end I like adding the math functions to the matrix class because it's easier for me (especially when dealing with dealing with math operations that use multiple data structures) but I don't want to have my preferences lower performance, so my question is: Does example below outperform the example above and if yes, why?

答:
Nonmembers come with the practical benefit that they have looser coupling. They can't modify the internals of the class, so to speak.

As an example, if you ever come across a user-reported bug where the application threw a general array access out of bounds exception (not one specific to your matrix class) with code relating to matrices, then if you have a very simple matrix class that only has a few methods that can possibly mess with its genitalia (privates) and give it STDs, your list of suspects that your matrix has slept with is very narrow. Meanwhile if you have a matrix class with 200 methods where it's partying and getting drunk and sleeping with everything that has a hole, your list of suspects to investigate is huge.

It also comes with the benefit that you can achieve code stability (as in cemented in concrete, lacking reasons to change further) faster with your matrix class if it doesn't aim to provide every matrix-related operation known to man. That's very useful when designing anything to make sure the public interface has a point where it is truly "done" where you don't feel the temptation to go back and add more and more indefinitely to the point where you have some beast of a class that has 100+ methods with documentation that has to span 20 pages. It's good to be able to section off your codebase into stable (unchanging) vs. unstable (changing) parts, so with any design you should be able to achieve a state of "completeness" as far as what functionality it provides in a very finite
amount of time.

Aiming to add every possible operation you can ever do with a class into the class itself will often make achieving such a goal impossible. The more and more you add to a class, the more and more you'll find reasons to add more. There's a vicious cycle there where the more you add, the more incomplete your design will seem. Minimalism is the way to counter that goal.

And finally it makes your matrix class easier to understand how to use when there's less things you can do with it off the bat. Some people might not be interested in eigenvectors/values and so it might help to make your interface more comprehensible if it provides fewer functions.

A pragmatic kind of approach is to include the basic operations into your design that people of all backgrounds do all the time, like matrix/matrix and matrix/vector multiplication. There you can still have a checklist where you can call the design "done" at some point without designing a god class/monolith that aims to do everything imaginable in the world. Then put the exotic stuff into separate interfaces, like separate classes with static methods which can only operate through the public interface of the matrix. Those separate static methods don't have access to the internals so they can go through, say, a layer of safety where your matrix class can impose invariants that disallow its internal data from being accessed out of bounds without throwing a MatrixOutOfBounds exception or something to this effect.

In your case I imagine it's just a more one-to-one translation with OpenGL which is a C API where methods are impossible, but it's worth noting that nonmembers are superior from a general software engineering standpoint of coupling and cohesion. They might be syntactically more cumbersome but the less things there are that can access your class's privates, the better from a maintenance and debugging standpoint. Too many methods and your privates become analogous to global variables because they have such an epic scope/visibility where so many things can potentially tamper with them. It's something to keep in mind when designing classes in any language -- to look for reasons to omit adding something directly to a class if it can be implemented elsewhere using only the public interface of that class. For similar reasons, if you can avoid inheriting from a class to access its protected members, composition is superior to inheritance in these contexts from an SE standpoint as it produces looser coupling.

From a performance standpoint there tend to be more reasons to add methods directly to a class since the most efficient solutions might require access to the class's internals. Still it's better to err on the side of adding a new method in hindsight when there's a strong perceived need for it than to add a boatload of needless methods to a class in advance. I like to go with the simple rule of "when in doubt, leave it out" when it comes to whether I should add a method to an interface or not.

Body:
I am trying to make some simple classes to do the math necessary for OpenGL transformations. However, now that I am about halfway and while looking through different examples I find that most libraries keep the math separate of the matrix class itself (most of the times in math class with static methods). What exactly is the reason for this?

Is it when you're creating multiple of the matrix objects that the functions are also created multiple times, which impacts performance or something else entirely?

Example:
I find it much easier to add the math functions to the matrix class so I dont need to pass the matrix itself to the functions: e.g.

class Matrix4f {

    //constructor...

    public void rotate(double theta) {
        setValue(0, 0, (float) Math.cos(theta));
        setValue(1, 0, (float) Math.sin(theta));
        setValue(0, 1, (float) Math.sin(theta));
        setValue(1, 1, (float) Math.cos(theta));
    }

    //getters and setters...
}

instead of

public class LinearAlgebraMath {
    public static Matrix4f rotate(Matrix4f target, double theta) {
        target.setValue(0, 0, (float) Math.cos(theta));
        target.setValue(1, 0, (float) Math.sin(theta));
        target.setValue(0, 1, (float) Math.sin(theta));
        target.setValue(1, 1, (float) Math.cos(theta));
        return target;
    }
}

public class Matrix4f {

    //constructor...

    //getters and setters...
}

So, in the end I like adding the math functions to the matrix class because it's easier for me (especially when dealing with dealing with math operations that use multiple data structures) but I don't want to have my preferences lower performance, so my question is: Does example below outperform the example above and if yes, why?


问:
React Native AsyncStorage not getting data
I am using following code for storing and retrieving data. But it isn't working as I want.

Setting data:

```<code>async setDataFromApi(token, json) {
const {goBack} = this.props.navigation; // Navigation
let iext_inf = {
  token: token,
  userid: json.data.id,
  username: json.data.username,
  image: json.data.profile_picture,
};
console.log(iext_inf);
try {
  await AsyncStorage.setItem('iext_inf', JSON.stringify(iext_inf) ); // Stuck here
  goBack();
} catch (error) {
  console.log("Error");
}
}
</code>```

Getting data:

```<code>async componentWillMount() {
    try {
      const value = await AsyncStorage.getItem("iext_inf"); //Stuck here
console.log(value);

  if (value !== null){
    this.setState({
      data : value
    })
  }

  if ( this.state.data !== null ) {
    this.props.navigation.navigate('Home', {'access_token': value});
  }

} catch (error) {
  console.log(error);
}
}
</code>```

What am I doing wrong? I tried adding single data and retrieving it and it worked for some reason. Now it's not.
Thank you in advance.

答:
AsyncStorage only takes string as a value and key.

You are passing an object try to set string not an object. I am not sure JSON.stringfy() works for AsyncStorage.

Body:
I am using following code for storing and retrieving data. But it isn't working as I want.

Setting data:

async setDataFromApi(token, json) {
const {goBack} = this.props.navigation; // Navigation
let iext_inf = {
  token: token,
  userid: json.data.id,
  username: json.data.username,
  image: json.data.profile_picture,
};
console.log(iext_inf);
try {
  await AsyncStorage.setItem('iext_inf', JSON.stringify(iext_inf) ); // Stuck here
  goBack();
} catch (error) {
  console.log("Error");
}
}

Getting data:

async componentWillMount() {
    try {
      const value = await AsyncStorage.getItem("iext_inf"); //Stuck here
console.log(value);

  if (value !== null){
    this.setState({
      data : value
    })
  }

  if ( this.state.data !== null ) {
    this.props.navigation.navigate('Home', {'access_token': value});
  }

} catch (error) {
  console.log(error);
}
}

What am I doing wrong? I tried adding single data and retrieving it and it worked for some reason. Now it's not.
Thank you in advance.


Title: Changing time format in an array using moment and angularjs and lodash

Body:
I have Json data which has timings based on dates.

obj = {
"2017-12-08": [
    "2017-12-08T13:00:00+0530",
    "2017-12-08T15:00:00+0530",
    "2017-12-08T15:30:00+0530",
    "2017-12-08T16:00:00+0530"
],
"2017-12-09": [
    "2017-12-09T09:00:00+0530",
    "2017-12-09T09:30:00+0530",
    "2017-12-09T10:00:00+0530"
],
"2017-12-10": [
    "2017-12-10T09:00:00+0530",
    "2017-12-10T09:30:00+0530",
    "2017-12-10T10:00:00+0530",
    "2017-12-10T10:30:00+0530"
]
}

I want to convert this json object into the format below:

obj = {
"2017-12-08": ["13:00","15:00","15:30","16:00"],
"2017-12-09": ["09:00","09:30","10:00"],
"2017-12-10": ["09:00","09:30","10:00","10:30"]
}

Currently I'm using a for loop to traverse through each element in the array and then replace each element using

obj[Object.keys(obj)[date]][time]=moment(obj[Object.keys(obj)[date]][time]).format(HH:mm);

how do i accomplish this using lodash , moment and angularjs?

Body:
You only need momentjs for this, just to format the date in desired format. AngularJS and lodash are not required.

var obj = {
  "2017-12-08": [
    "2017-12-08T13:00:00+0530",
    "2017-12-08T15:00:00+0530",
    "2017-12-08T15:30:00+0530",
    "2017-12-08T16:00:00+0530"
  ],
  "2017-12-09": [
    "2017-12-09T09:00:00+0530",
    "2017-12-09T09:30:00+0530",
    "2017-12-09T10:00:00+0530"
  ],
  "2017-12-10": [
    "2017-12-10T09:00:00+0530",
    "2017-12-10T09:30:00+0530",
    "2017-12-10T10:00:00+0530",
    "2017-12-10T10:30:00+0530"
  ]
};

Object.keys(obj).forEach(key => {
  obj[key] = obj[key].map(item => {
    return moment(item).format("HH:mm");
  });
});

console.log(obj);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js"></script>

This modifies the object in-place. If you don't want that, clone the object first, and then transform the clone.


问:
Why are the referenced array's values not changed?
I'm trying to multiply the each component of an array with a scalar, and to do this, have tried the followings;

1-)

```<code>@foo = (1, 2, 3, 5, 6);
vectorScalarMultiply(\@foo);
print @foo, "\n";

sub vectorScalarMultiply
{
    my $l_vectorRef = $_[0];
    for (my $var = 0; $var < scalar(@temp); $var++) {
        $l_vectorRef->[$var] = $l_vectorRef->[$var] * 5;
    }
}
</code>```

1's Output;

12356

2-)

```<code>@foo = (1, 2, 3, 5, 6);
vectorScalarMultiply(\@foo);
print @foo, "\n";
sub vectorScalarMultiply
{

    my $l_vectorRef = $_[0];
    map { $l_vectorRef->[$_] * 5 } { $l_vectorRef->[$_] };
}
</code>```

2's Output;

123456

3-)

```<code>@foo = (1, 2, 3, 5, 6);
@temp = @{$l_vectorRef};
vectorScalarMultiply(\@foo);
print @foo, "\n";
$l_vectorRef = map { $temp[$_] * 5; } @temp;
</code>```

3's Output;

12356

And I haven't been able to figure out what is the problem, and why are they not working, so my main question is that what is the problem with these code ?Secondly, how can we solve it ?

答:
The first one doesn't work because your loop condition is $var < scalar(@temp), but there is no @temp, so the loop never executes.

The second one doesn't work because map doesn't modify anything, and you're not assigning the result of the map to anything.

The third one doesn't work because you're modifying the variable $l_vectorRef inside the sub, and not modifying the array that that variable holds a reference to.

Here is a more idiomatic working version:

```<code>sub vectorScalarMultiply {
    my ($aref) = @_;
    $_ *= 5 for @$aref;
}
</code>```

Body:
I'm trying to multiply the each component of an array with a scalar, and to do this, have tried the followings;

1-)

@foo = (1, 2, 3, 5, 6);
vectorScalarMultiply(\@foo);
print @foo, "\n";

sub vectorScalarMultiply
{
    my $l_vectorRef = $_[0];
    for (my $var = 0; $var < scalar(@temp); $var++) {
        $l_vectorRef->[$var] = $l_vectorRef->[$var] * 5;
    }
}

1's Output;

12356

2-)

@foo = (1, 2, 3, 5, 6);
vectorScalarMultiply(\@foo);
print @foo, "\n";
sub vectorScalarMultiply
{

    my $l_vectorRef = $_[0];
    map { $l_vectorRef->[$_] * 5 } { $l_vectorRef->[$_] };
}

2's Output;

123456

3-)

@foo = (1, 2, 3, 5, 6);
@temp = @{$l_vectorRef};
vectorScalarMultiply(\@foo);
print @foo, "\n";
$l_vectorRef = map { $temp[$_] * 5; } @temp;

3's Output;

12356

And I haven't been able to figure out what is the problem, and why are they not working, so my main question is that what is the problem with these code ?Secondly, how can we solve it ?

Body:
The first one doesn't work because your loop condition is $var < scalar(@temp), but there is no @temp, so the loop never executes.

The second one doesn't work because map doesn't modify anything, and you're not assigning the result of the map to anything.

The third one doesn't work because you're modifying the variable $l_vectorRef inside the sub, and not modifying the array that that variable holds a reference to.

Here is a more idiomatic working version:

sub vectorScalarMultiply {
    my ($aref) = @_;
    $_ *= 5 for @$aref;
}


问:
Google Invisible reCAPTCHA breaks Firefox JavaScript
I have tried pretty much every which way to configure the Google Invisible reCAPTCHA widget, but there is always an issue with the latest Firefox browser, detailed as follows:

add the plugin to a web page, which has other JS such as a dropdown menu

load the web page

keep loading the web page over and over, in an attempt to catch it 'half loaded'

eventually you will see for a split second an alert "The page at https://www.google.com says: Cannot contact reCAPTCHA. Check your connection and try again"

from now on, JavaScript is entirely broken until you restart the Firefox window

This never happens in Chrome, and appears to be Firefox only. I am surprised to not find any reports of this major issue with vendors Google and Firefox (unsure which party is to blame), so created this ticket.

This issue can be replicated on the official Google Invisible reCAPTCHA Demo by quickly reloading the page. This will eventually show the alert and break the entire demo, making all form inputs unresponsive until the Firefox window is closed and re-opened.

At the time of writing, I am using OSX Firefox 57.0.1 (64-bit) to replicate this issue, but has also been replicated on the same Firefox under Windows 10.

Update after valid comment from Federico, as this is being reported a lot but no solutions or workarounds that I can find: Google Groups Search

Is this a known issue and are there any plans to resolve from either Firefox or Google, or more importantly has anybody managed to put a workaround in place in the meantime?

答: I think the issue is resolved now. Try again and it is giving successful verification. I guess it was a bug which they fixed. If the problem still persists please try upgrading Firefox to the latest version.


问:
Bootstrap Simple Navigation bar not working in my page
I have a Simple Bootstrap navigation bar in my page, but it is not working. the JavaScript and CSS Files are working properly. i checked it. when i copy the navigation code from  to  and pasts it in a new file, then it is working fine, but not working in my actual file . and looks something like This
and I am expecting some thing like This

My Page Source Code is here  .....

```<code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Information Panel for Students</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="../include/css/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="../include/css/footer.css" rel="stylesheet" type="text/css">
</head>

<body>
<div class="container">

<!--    header start from here -->

    <header>
      <nav class="navbar navbar-default">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a href="index.php" class="navbar-brand">Department Dashboard</a>
        </div>
        <!-- Collection of nav links and other content for toggling -->
        <div id="navbarCollapse" class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="index.php">Home</a></li>
            <li><a href="update_password.php">Update Password</a></li>
            </ul>
          <ul class="nav navbar-nav navbar-right">
            <li><a href="logout.php">Logout</a></li>
            </ul>
        </div>
        </nav>
  </header>

    <h3>Teachers:</h3>
  <div class="row">
    <div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../teacher/images/resized_1512541379-5412-5a278cc30963e-NOKIA_RM-1030_206834512-206835569_000.JPG" width="180" height="220"/><br>Person Name : Shaida Khan<br>Current Place : Default<br>Status Date : 00-00-0000<br>Status Time : 12:00:00 AM<br><br></div><div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../teacher/images/resized_1512541601-6654-5a278da1bf564-NOKIA_X2-02_215986488-215987862_000.JPG" width="180" height="220"/><br>Person Name : Nausheen Fayaz<br>Current Place : Default<br>Status Date : 00-00-0000<br>Status Time : 12:00:00 AM<br><br></div><div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../teacher/images/resized_1512541663-4311-5a278ddfa5374-NOKIA_X2-02_215461832-215462529_000.JPG" width="180" height="220"/><br>Person Name : Javed Chaudry<br>Current Place : Default<br>Status Date : 00-00-0000<br>Status Time : 12:00:00 AM<br><br></div><div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../teacher/images/resized_1512541718-9653-5a278e1617035-NOKIA_RM-1030_206827192-206828288_000.JPG" width="180" height="220"/><br>Person Name : Khan Khan<br>Current Place : Default<br>Status Date : 00-00-0000<br>Status Time : 12:00:00 AM<br><br></div><div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../teacher/images/resized_1512563517-6727-5a27e33d9dc39-NOKIA_E5-00_202194584-202196971_000.JPG" width="180" height="220"/><br>Person Name : Farsil Khan<br>Current Place : Default<br>Status Date : 00-00-0000<br>Status Time : 12:00:00 AM<br><br></div><div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../teacher/images/resized_1512563572-2715-5a27e374a3c1d-NOKIA_RM-1030_202261216-202265107_000.JPG" width="180" height="220"/><br>Person Name : Ek Aur Teacher Ke Data<br>Current Place : Default<br>Status Date : 00-00-0000<br>Status Time : 12:00:00 AM<br><br></div><div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../teacher/images/resized_1512216690-8783-5a229872e2564-NOKIA_5233_244851632-244851959_000.JPG" width="180" height="220"/><br>Person Name : Azhar Rauf<br>Current Place : Class Room<br>Status Date : 02-12-2017<br>Status Time : 05:15:21 PM<br><br></div><div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../teacher/images/resized_1512217027-6925-5a2299c3d363f-NOKIA_E5-00_202038176-202041197_000.JPG" width="180" height="220"/><br>Person Name : Fatima Zuhra<br>Current Place : Class Room<br>Status Date : 02-12-2017<br>Status Time : 05:19:28 PM<br><br></div><div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../teacher/images/resized_1512217504-2845-5a229ba0c8635-NOKIA_E5-00_202201816-202204433_000.JPG" width="180" height="220"/><br>Person Name : Khan Lala<br>Current Place : Class Room<br>Status Date : 02-12-2017<br>Status Time : 05:33:17 PM<br><br></div>  </div>

    <h3>Chairman:</h3>
    <div class="row">
      <div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../chairman/images/resized_1512141619-1363-5a2173335d788-NOKIA_5233_244851632-244851959_000.JPG" width="180" height="220"/><br>Person Name : Shah Khusro<br>Current Place : Chairman Office<br>Status Date : 01-12-2017<br>Status Time : 08:26:40 PM<br><br></div>    </div>

    <h3>Clerks:</h3>
    <div class="row">
      <div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../clerk/images/resized_1512562768-5527-5a27e0506acd1-HUAWEI_HUAWEI_611272384-611272979_000.JPG" width="180" height="220"/><br>Person Name : Demo Khan<br>Current Place : Default<br>Status Date : 00-00-0000<br>Status Time : 12:00:00 AM<br><br></div><div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../clerk/images/resized_1512562854-8274-5a27e0a675bb8-HUAWEI_CHM-U01_183017224-183021314_000.JPG" width="180" height="220"/><br>Person Name : Galaxy Khan<br>Current Place : Default<br>Status Date : 00-00-0000<br>Status Time : 12:00:00 AM<br><br></div><div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../clerk/images/resized_1512563316-1142-5a27e2744dc95-NOKIA_5233_244851632-244851959_000.JPG" width="180" height="220"/><br>Person Name : Asdf Adf<br>Current Place : Default<br>Status Date : 00-00-0000<br>Status Time : 12:00:00 AM<br><br></div><div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../clerk/images/resized_1512563366-8649-5a27e2a6bb78c-NOKIA_E5-00_202083984-202086713_000.JPG" width="180" height="220"/><br>Person Name : Sdfasd Adfdsf<br>Current Place : Default<br>Status Date : 00-00-0000<br>Status Time : 12:00:00 AM<br><br></div><div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../clerk/images/resized_1512563389-3596-5a27e2bdc3ff7-NOKIA_E5-00_202186392-202189391_000.JPG" width="180" height="220"/><br>Person Name : Sdf Fsd<br>Current Place : Default<br>Status Date : 00-00-0000<br>Status Time : 12:00:00 AM<br><br></div><div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../clerk/images/resized_1512563480-2752-5a27e3185f05f-NOKIA_RM-1030_194996488-194998710_000.JPG" width="180" height="220"/><br>Person Name : Dfasdf Sdalfksd<br>Current Place : Default<br>Status Date : 00-00-0000<br>Status Time : 12:00:00 AM<br><br></div><div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../clerk/images/resized_1512145551-9397-5a21828fc4953-NOKIA_E5-00_202038176-202041197_000.JPG" width="180" height="220"/><br>Person Name : Faris Khan<br>Current Place : Clerk Office<br>Status Date : 02-12-2017<br>Status Time : 09:46:40 AM<br><br></div>    </div>

    <h3>Lab Staff:</h3>
    <div class="row">
      <div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../lab_staff/images/resized_1512218344-7079-5a229ee8b9e5a-NOKIA_RM-1030_206846160-206847834_000.JPG" width="180" height="220"/><br>Person Name : Samin Jan<br>Current Place : Laboratory<br>Status Date : 02-12-2017<br>Status Time : 05:39:47 PM<br><br></div>    </div>

    <h3>PN Staff:</h3>
    <div class="row">
      <div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"><img src="../pn/images/resized_1512145738-2830-5a21834a6d1d7-NOKIA_E5-00_202048056-202051887_000.JPG" width="180" height="220"/><br>Person Name : Penis Khan<br>Current Place : Outside<br>Status Date : 02-12-2017<br>Status Time : 06:09:47 PM<br><br></div>    </div>
    <footer>
        <div class="container">
            <div class="row">
                <div class="col-sm-4">
                    <div class="footer-block">
                        <ul class="list-inline footer-menu">
                            <li><a href="">Term of Use</a></li>
                            <li><a href="">Privacy Policy</a></li>
                        </ul>
                    </div>
                </div>
                <div class="col-sm-4">
                  <div class="footer-block text-center">
                    <p class="copyright">
                        © 2018 Department Dashboard.<br>
                        All rights reserved.<br>
                        Developed By:<br>
                        Shaida Muhammad Sherpao
                      </p>
                    </div>
                </div>
                <div class="col-sm-4">
                    <div class="footer-block">
                        <ul class="list-inline pull-right social-icon">
                            <li><a href="https://facebook.com/sh3rpao"><i class="fa fa-facebook"></i></a></li>
                            <li><a href="https://twitter.com/shaidasherpao"><i class="fa fa-twitter"></i></a></li>
                            <li><a href="https://pk.linkedin.com/in/shaida-muhammad-sherpao-a3388a103"><i class="fa fa-linkedin"></i></a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </footer>
</div>
<script src="../include/js/jquery-1.11.3.min.js"></script>
<script src="../include/js/bootstrap.js"></script>
</body>
</html>
</code>```

答:
maybe it's the css. in the head, write this

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

instead of importing your .css files

EDIT
write this instead of what you written

```<code><button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
</button>
</code>```

Body:
I have a Simple Bootstrap navigation bar in my page, but it is not working. the JavaScript and CSS Files are working properly. i checked it. when i copy the navigation code from  to  and pasts it in a new file, then it is working fine, but not working in my actual file . and looks something like This
and I am expecting some thing like This

My Page Source Code is here  .....

<!doctype html>

<meta charset="utf-8">
<title>Information Panel for Students</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="../include/css/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="../include/css/footer.css" rel="stylesheet" type="text/css">

          <button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle">
            Toggle navigation

          </button>
          Department Dashboard

Home

Update Password

Logout

Teachers:

Person Name : Shaida Khan
Current Place : Default
Status Date : 00-00-0000
Status Time : 12:00:00 AM

Person Name : Nausheen Fayaz
Current Place : Default
Status Date : 00-00-0000
Status Time : 12:00:00 AM

Person Name : Javed Chaudry
Current Place : Default
Status Date : 00-00-0000
Status Time : 12:00:00 AM

Person Name : Khan Khan
Current Place : Default
Status Date : 00-00-0000
Status Time : 12:00:00 AM

Person Name : Farsil Khan
Current Place : Default
Status Date : 00-00-0000
Status Time : 12:00:00 AM

Person Name : Ek Aur Teacher Ke Data
Current Place : Default
Status Date : 00-00-0000
Status Time : 12:00:00 AM

Person Name : Azhar Rauf
Current Place : Class Room
Status Date : 02-12-2017
Status Time : 05:15:21 PM

Person Name : Fatima Zuhra
Current Place : Class Room
Status Date : 02-12-2017
Status Time : 05:19:28 PM

Person Name : Khan Lala
Current Place : Class Room
Status Date : 02-12-2017
Status Time : 05:33:17 PM

Chairman:

Person Name : Shah Khusro
Current Place : Chairman Office
Status Date : 01-12-2017
Status Time : 08:26:40 PM

Clerks:

Person Name : Demo Khan
Current Place : Default
Status Date : 00-00-0000
Status Time : 12:00:00 AM

Person Name : Galaxy Khan
Current Place : Default
Status Date : 00-00-0000
Status Time : 12:00:00 AM

Person Name : Asdf Adf
Current Place : Default
Status Date : 00-00-0000
Status Time : 12:00:00 AM

Person Name : Sdfasd Adfdsf
Current Place : Default
Status Date : 00-00-0000
Status Time : 12:00:00 AM

Person Name : Sdf Fsd
Current Place : Default
Status Date : 00-00-0000
Status Time : 12:00:00 AM

Person Name : Dfasdf Sdalfksd
Current Place : Default
Status Date : 00-00-0000
Status Time : 12:00:00 AM

Person Name : Faris Khan
Current Place : Clerk Office
Status Date : 02-12-2017
Status Time : 09:46:40 AM

Lab Staff:

Person Name : Samin Jan
Current Place : Laboratory
Status Date : 02-12-2017
Status Time : 05:39:47 PM

PN Staff:

Person Name : Penis Khan
Current Place : Outside
Status Date : 02-12-2017
Status Time : 06:09:47 PM

Term of Use

Privacy Policy

                        © 2018 Department Dashboard.

                        All rights reserved.

                        Developed By:

                        Shaida Muhammad Sherpao

Body:
maybe it's the css. in the head, write this

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

instead of importing your .css files

EDIT
write this instead of what you written

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
</button>