问:
WinForm application behaves differently in different system
I have winform application with many controls but the main control is tree on form. The application is working fine in my system but when this was tested in another system this behaves differntly. Tree size got changed and overlapped other controls and hence some of the controls are not visible. This is surprising for me. What could be the issue? I verified DPI setting and msinfo32 but could not see any differnce in both the systems.</p>

答: I found the issue with DPI only. Application was developed with 125% DPI and that's why controls were overlapping in other system where default DPI was 100%.</p>


来源: stackexchange

问:
Disable Javascript after page is loaded should be detected on action page
I think i have searched already about  tags and yes i am using them already.

But here my question or Idea is:

I have a form including input to search/insert data into database (mysql) (index.php)
form action is being performed on search.php
search box searches input data in the selected tables, if it is found, then it gives the records in result.php, otherwise it inserts the data in table(sql) and then shows it in result.php

I am validating the form/input using javascript on the same page even using  tags
Now after loading the index.php page, if someone disable javascript, it shows an alert to reload the page. if someone reload the page, searchbox will hide.

but the problem is, if after loading the page, if someone disable javascript and does not reload the page, and search some restricted text using javascript regex, that text goes into mysql database and it is saved. search.php perform its action and redirect it to result.php

I want some trick in search.php that checks some condition for javascript enabled/disabled, then perform the remaining actions.

IS THERE ANY WAY, IF ACTION SHOULD BE ANOTHER PAGE, on that page is javascript is disabled then it shows nothing, and if it is enabled then redirects to search.php

答:
Use a hidden input field and set its value using javascript on form submission. Since the value will be set only using javascript, if the submitted form has an empty value for this field, it can be concluded that javascript was disabled.

Using jQuery:

In the html:

```<code><form id="myformid" action="myactionurl.php" method="POST">
   <!-- form fields here -->
   <input type="hidden" id="time" name="time" value="">
</form>
</code>```

In js:

```<code>$('#myformid').submit(function(ev) {
    $('#time').val($.now());
});
</code>```

In php:

```<code>if(!empty($_POST['time'])) {
    //code
} else {
    echo "Javascript must be enabled for this site to work.";
}
</code>```

You don't have to use time, it can be anything.

ContentLicense: CC BY-SA 3.0

Body:
Use a hidden input field and set its value using javascript on form submission. Since the value will be set only using javascript, if the submitted form has an empty value for this field, it can be concluded that javascript was disabled.

Using jQuery:

In the html:

<form id="myformid" action="myactionurl.php" method="POST">
   <!-- form fields here -->
   <input type="hidden" id="time" name="time" value="">
</form>

In js:

$('#myformid').submit(function(ev) {
    $('#time').val($.now());
});

In php:

if(!empty($_POST['time'])) {
    //code
} else {
    echo "Javascript must be enabled for this site to work.";
}

You don't have to use time, it can be anything.


问:
Remove Underline Border Materialize Input Text
I try to make the border bottom of the text box (input text) disappear.

It's working with border-bottom: none but when I write something the border appear again. I want to make the green line disappear (the image show the page when I'm writing in the input).

Any idea?

答:
In materialize.css

```<code>textarea:focus {
  border-bottom: 1px solid #03a9f4;
  -webkit-box-shadow: 0 1px 0 0 #03a9f4;
  -moz-box-shadow: 0 1px 0 0 #03a9f4;
  box-shadow: 0 1px 0 0 #03a9f4;
}
</code>```

You can replace the color code with whatever you want to change the underline.

```<code>textarea:focus {
  border-bottom: 1px solid orange;
  -webkit-box-shadow: 0 1px 0 0 orange;
  -moz-box-shadow: 0 1px 0 0 orange;
  box-shadow: 0 1px 0 0 orange;
}
</code>```

or remove it :

```<code>textarea:focus {
  border-bottom: none!important;
  box-shadow: none!important;
}
</code>```

This is code :

This is Result :

Body:
In materialize.css

textarea:focus {
  border-bottom: 1px solid #03a9f4;
  -webkit-box-shadow: 0 1px 0 0 #03a9f4;
  -moz-box-shadow: 0 1px 0 0 #03a9f4;
  box-shadow: 0 1px 0 0 #03a9f4;
}

You can replace the color code with whatever you want to change the underline.

textarea:focus {
  border-bottom: 1px solid orange;
  -webkit-box-shadow: 0 1px 0 0 orange;
  -moz-box-shadow: 0 1px 0 0 orange;
  box-shadow: 0 1px 0 0 orange;
}

or remove it :

textarea:focus {
  border-bottom: none!important;
  box-shadow: none!important;
}

This is code :

This is Result :


问:
Bottom Border Width on Swift TextField in TableView
i builded a static tableview with more Rowes than the screen has, so the user has to scroll to see all cell.

Every cell has a textfield with the following class to add a bottom border:

```<code>class TextFieldWithBottomBorder: UITextField {
   let border = CALayer()
   let width = CGFloat(1.0)

   func addBottomBorder(color: UIColor){
       self.border.borderColor = color.cgColor
       self.border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height:self.frame.size.height)

       self.border.borderWidth = self.width
       self.layer.addSublayer(self.border)
       self.layer.masksToBounds = true
   }

   func changeBorderColor(color: UIColor){
       self.border.borderColor = color.cgColor
   }
}
</code>```

And i call the method after receiving some data from the server e. g.

```<code>self.firstnameTextField.text = firstNameFromDB
self.firstnameTextField.addBottomBorder(color: .blue)
</code>```

This works fine for every cell is currently displayed. But the cells which are out of the current view the with is shorter than the textfield.
See this screenshot, for "Vorname", means firstName everything looks good, but for email, password etc. the border is to short.
http://share-your-photo.com/34b5e80253

答:
Looks like the size of the UITextField is being resized after you have called addBottomBorder and so the UIView being used at the line is now not wide enough.  It's difficult to say why this would be without seeing more code but there are several methods you could use to overcome it.

1) Switch to a UIView instead of a CALayer and use auto layout to keep the view in the correction position.

2) Override layoutSubviews to update the frame of the bottom line.

The simplest for you is probably option 2 (although I would go option 1) and it would look like this:

```<code>override func layoutSubviews() {
    super.layoutSubviews()
    self.border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height:self.frame.size.height)
}
</code>```

Now whenever the frame/size of the text field changes the frame/size of the border line CALayer will be updated appropriately.

Body:
i builded a static tableview with more Rowes than the screen has, so the user has to scroll to see all cell.

Every cell has a textfield with the following class to add a bottom border:

class TextFieldWithBottomBorder: UITextField {
   let border = CALayer()
   let width = CGFloat(1.0)

   func addBottomBorder(color: UIColor){
       self.border.borderColor = color.cgColor
       self.border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height:self.frame.size.height)

       self.border.borderWidth = self.width
       self.layer.addSublayer(self.border)
       self.layer.masksToBounds = true
   }

   func changeBorderColor(color: UIColor){
       self.border.borderColor = color.cgColor
   }
}

And i call the method after receiving some data from the server e. g.

self.firstnameTextField.text = firstNameFromDB
self.firstnameTextField.addBottomBorder(color: .blue)

This works fine for every cell is currently displayed. But the cells which are out of the current view the with is shorter than the textfield.
See this screenshot, for "Vorname", means firstName everything looks good, but for email, password etc. the border is to short.
http://share-your-photo.com/34b5e80253

Body:
Looks like the size of the UITextField is being resized after you have called addBottomBorder and so the UIView being used at the line is now not wide enough.  It's difficult to say why this would be without seeing more code but there are several methods you could use to overcome it.

1) Switch to a UIView instead of a CALayer and use auto layout to keep the view in the correction position.

2) Override layoutSubviews to update the frame of the bottom line.

The simplest for you is probably option 2 (although I would go option 1) and it would look like this:

override func layoutSubviews() {
    super.layoutSubviews()
    self.border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height:self.frame.size.height)
}

Now whenever the frame/size of the text field changes the frame/size of the border line CALayer will be updated appropriately.


问:
Type casting with type in variable
Is it possible to cast an object to a type which is stored in a member variable?

I've tried this:

```<code>let targetClass = type(of: MyTargetClass)
...

if anyObject is targetClass { // ERROR: use of undeclared type 'targetClass'
let test = anyObject as! targetClass // ERROR: use of undeclared type 'targetClass'
}
</code>```

But it doesn't work because it says "use of undeclared type 'targetClass'"

答:
No. The type cast is a compile time thing. It lets the compiler know what methods are available and how to do the linking.

You can use Mirror to gather information about your object at runtime, but it looks like invoking methods dynamically can still only be done on classes derived from NSObject.

Title: Type casting with type in variable

Body:
Is it possible to cast an object to a type which is stored in a member variable?

I've tried this:

let targetClass = type(of: MyTargetClass)
...

if anyObject is targetClass { // ERROR: use of undeclared type 'targetClass'
let test = anyObject as! targetClass // ERROR: use of undeclared type 'targetClass'
}

But it doesn't work because it says "use of undeclared type 'targetClass'"


问:
User - stamp Java MySql App
I'm coding a desktop app in Java I want to be used by many users on a local network db. I have a login frame.

The problem is that everytime i want to write a query i have to get a new connection.

First question is: How can i get my connection method somehow to remember the login username and password the user wrote to login so it would connect right away?

Second question is: (possibly answered if the first one is answered) Can i have a user-stamp for every record inserted, updated?

My thoughts are whether or a desktop app with a local db is able to handle many users correctly.

答:
For the first question:
To acquire a connection every time is expensive. Try using a connection pool. Please refer to BalusC's answer on connection pooling here:
https://stackoverflow.com/a/4209660/229634

For the second question:
Is there a reason that prevents you from tracking user activities or updates? If not, then it is wise to do so. This can even save you a lot of trouble in the long run, if ever you encounter data issues or bugs due to an update/insert in the db.

Whether your db can handle the volume/performance depends entirely on the type of database you use. Typically most DB's should be able to unless you have an exceptional volume of users. MySQL should definitely be able to handle what you throw at it.

Title: User - stamp Java MySql App


问:
Changing values when converting column type to numeric
I have a data file with the format from above.

I loaded it into R, and tried to plot a histogram with the values from the dist column and I have got the error "x must be numeric".Therefore I tried to change the format.

```<code>> head(data)

    V1        V2
1 type gene_dist
2    A     64667
3    A     76486
4    A     97416
5    A     30876
6    A     88018

> summary(data)
    V1            V2
 A   : 67   100    :  1
 B   :122   100906 :  1
 type:  1   102349 :  1
            1033   :  1
            10544  :  1
            10745  :  1
            (Other):184
</code>```

I tried to set the format for the column using sapply but the values are changed:

```<code>> data[,2]<-sapply(data[,2],as.numeric)

> head(data)
    V1  V2
1 type 190
2    A 146
3    A 166
4    A 189

summary(data)
    V1            V2
 A   : 67   Min.   :  1.00
 B   :122   1st Qu.: 48.25
 type:  1   Median : 95.50
            Mean   : 95.50
            3rd Qu.:142.75
            Max.   :190.00
</code>```

Does anyone know why is this happening?

答:
It's probably much better to fix it when reading the file than by using as.numeric() or as.character(). When reading your file, make sure to have:

header=TRUE if first row is header

NA and not Na or NaN (ctrl+H and replace by NA in your datafile)

no other character strings in your numeric columns

Then R will automatically consider them as numeric.

Body:
I have a data file with the format from above.

I loaded it into R, and tried to plot a histogram with the values from the dist column and I have got the error "x must be numeric".Therefore I tried to change the format.

> head(data)

    V1        V2
1 type gene_dist
2    A     64667
3    A     76486
4    A     97416
5    A     30876
6    A     88018

> summary(data)
    V1            V2
 A   : 67   100    :  1
 B   :122   100906 :  1
 type:  1   102349 :  1
            1033   :  1
            10544  :  1
            10745  :  1
            (Other):184

I tried to set the format for the column using sapply but the values are changed:

> data[,2]<-sapply(data[,2],as.numeric)

> head(data)
    V1  V2
1 type 190
2    A 146
3    A 166
4    A 189

summary(data)
    V1            V2
 A   : 67   Min.   :  1.00
 B   :122   1st Qu.: 48.25
 type:  1   Median : 95.50
            Mean   : 95.50
            3rd Qu.:142.75
            Max.   :190.00

Does anyone know why is this happening?

ContentLicense: CC BY-SA 4.0


问:
Run method after defined time on windows service
My Question is more about getting to the same destination, but there must be another way. Right now im creating a DateTime and compare that to another DateTime and check, if the time difference I set up might be right. So far so good but I just can't accept that I create a new propertie everytime the loop will get into that code.

Is there any possible way to get to the same destination, but in some kind of more effective way?

I got you guys some example code here:

```<code>        private void RunService()
        {
            // Runs as long as the service didn't got a stop call.
            while (!SetStop)
            {
                //Get MinutesToWait
                this.MinutesToWait = 5;

                DateTime CheckRunTime = this.LastRun;
                CheckRunTime.AddMinutes(this.MinutesToWait);

                if (DateTime.Now >= CheckRunTime)
                {
                    // Imagine some good and smart and totally runnable code?
                }
            }
        }
</code>```

答:
Use System.Timers    </p>

```<code>static void Main(string[] args) {

        Timer T = new Timer();
        T.Elapsed += Run;
        T.Interval = 100;
        T.Start();

}
static void Run(object source, ElapsedEventArgs e) {

}
</code>```

Body:
My Question is more about getting to the same destination, but there must be another way. Right now im creating a DateTime and compare that to another DateTime and check, if the time difference I set up might be right. So far so good but I just can't accept that I create a new propertie everytime the loop will get into that code.

Is there any possible way to get to the same destination, but in some kind of more effective way?

I got you guys some example code here:

        private void RunService()
        {
            // Runs as long as the service didn't got a stop call.
            while (!SetStop)
            {
                //Get MinutesToWait
                this.MinutesToWait = 5;

                DateTime CheckRunTime = this.LastRun;
                CheckRunTime.AddMinutes(this.MinutesToWait);

                if (DateTime.Now >= CheckRunTime)
                {
                    // Imagine some good and smart and totally runnable code?
                }
            }
        }

Body:
Use System.Timers

static void Main(string[] args) {

        Timer T = new Timer();
        T.Elapsed += Run;
        T.Interval = 100;
        T.Start();

}
static void Run(object source, ElapsedEventArgs e) {

}


问:
USB - autorun a web address
I currently have 2 files on it:

```<code>autorun.inf
start.url
</code>```

autorun.inf contains 3 lines:

```<code>[autorun]
ShellExecute=start.url
open=start.url
</code>```

start.url contains 5 lines:

```<code>[InternetShortcut]
URL=http://cnn.com
IDList=
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,2
</code>```

Loads ok on Vista, but does not load on XP or Windows7.

Any clue what to change?

答:
Is the autorun functionality disabled on the XP and Win7 boxes? If so you have to re-enable it.

See this article for how it was, probably, disabled in XP: How to disable the Autorun functionality in Windows

Though I think it could also have been disabled in a group policy.

Title: USB - autorun a web address

Body:
I currently have 2 files on it:

autorun.inf
start.url

autorun.inf contains 3 lines:

[autorun]
ShellExecute=start.url
open=start.url

start.url contains 5 lines:

[InternetShortcut]
URL=http://cnn.com
IDList=
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,2

Loads ok on Vista, but does not load on XP or Windows7.

Any clue what to change?

ContentLicense: CC BY-SA 2.5


问:
Lua Pattern Exclusion
I have a predefined code, e.g."12-345-6789", and wish to match the first and last portions with Lua patterns, e.g. "12-6789". An exclusion of the second number set and the hyphen should work but I am having trouble figuring that out with patterns or if it is possible.

I know I could capture each individually like so

```<code>code = "12-345-6789"
first, middle, last = string.match(code, "(%d+)-(%d+)-(%d+)")
</code>```

and use that but it would require a lot of code rewriting on my part. I would ideally like to take the current table of pattern matches and add it to be used with string.match

```<code>lcPart = { "^(%d+)", "^(%d+%-%d+)", "(%d+)$", ?new pattern here? }
code = "12-345-6789"
newCode = string.match(code, lcPart[4])
</code>```

答:
I know this is an old thread, but someone might still find this useful.

If you need only the first and last sets of digits, separated by a hyphen you could use string.gsub for that

```<code>local code = "12-345-6789"
local result = string.gsub(code, "(%d+)%-%d+%-(%d+)", "%1-%2")
</code>```

This will simply return the string "12-6789" by using the first and second captures from the pattern.

Title: Lua Pattern Exclusion

Body:
I have a predefined code, e.g."12-345-6789", and wish to match the first and last portions with Lua patterns, e.g. "12-6789". An exclusion of the second number set and the hyphen should work but I am having trouble figuring that out with patterns or if it is possible.

I know I could capture each individually like so

code = "12-345-6789"
first, middle, last = string.match(code, "(%d+)-(%d+)-(%d+)")

and use that but it would require a lot of code rewriting on my part. I would ideally like to take the current table of pattern matches and add it to be used with string.match

lcPart = { "^(%d+)", "^(%d+%-%d+)", "(%d+)$", ?new pattern here? }
code = "12-345-6789"
newCode = string.match(code, lcPart[4])

Body:
I know this is an old thread, but someone might still find this useful.

If you need only the first and last sets of digits, separated by a hyphen you could use string.gsub for that

local code = "12-345-6789"
local result = string.gsub(code, "(%d+)%-%d+%-(%d+)", "%1-%2")

This will simply return the string "12-6789" by using the first and second captures from the pattern.


问:
Send Messages without reload page using ajax in laravel
I am working on laravel and I want to send personally messages to the users using blade template. But when I press submit button it gets refreshed/reload the page every time. what to do? and please anyone tell me how to use ajax url, type, data

View file

```<code><form action="{{action('MessageController@sendmessagereply')}}" method="post">
            <div class="panel-footer">
                <div class="input-group">
                   <?php if(isset($data)){ ?>
                   <?php for($i=0;$i<count($data);$i++) {?>
                    <input type="hidden" name="_token" value="{{csrf_token()}}">
                    <input type="hidden" name="id" value="<?php echo $data[$i]->receivermsgid;?>">
                    <?php } }?>
                    <input type="text"  name="messages" class="form-control" placeholder="Enter Message" />
                    <span class="input-group-btn">
                       <button class="btn btn-info" type="submit">SEND</button>
                    </span>
                </div>
            </div>
          </form>
</code>```

Controller file

```<code> public function sendmessagereply(Request $request)
      {
            $post=$request->all();
            $id=$post['id'];
            $senderid=Session::get('login_userid');
            $receiverid = $id;
            $data=array(
                        'sendermsgid' => $senderid,
                        'receivermsgid' => $receiverid,
                        'message'=>$post['messages'],
                        'sdate'=> DB::raw('CURRENT_TIMESTAMP')
                        );
            $messages = DB::table('messages')->insert($data);
            if($messages){
                \Session::flash('msg','Your Message Has Been Sent Successfully');
                return redirect('messageschat/'.$id);
            } else {
                \Session::flash('msg','Error In Sending Message');
                return redirect('basicsearch');
            }

        }

  //i get the all messages between two users
  public function messageschat($id)
    {
       $senderid=Session::get('login_userid');
       $result=DB::table('messages')
                  ->join('user_register','messages.sendermsgid','=','user_register.id')
                  ->leftjoin('profilephoto','messages.receivermsgid','=','profilephoto.userid','messages.sendermsgid','=','profilephoto.userid')
                  ->where('sendermsgid', $senderid)->where('receivermsgid',$receivermsgid)
                  ->orwhere('sendermsgid',$receivermsgid)->where('receivermsgid',$senderid)
                  ->select('messages.message','messages.sendermsgid','messages.receivermsgid','user_register.first_name as fname','profilephoto.name')
                  ->orderby('messages.sdate')
                  ->get();

       $chatdata=DB::table('messages')
                     ->select('messages.message','messages.receivermsgid','messages.sendermsgid')
                     ->where('receivermsgid',$receivermsgid)
                     ->where('sendermsgid',$senderid)->get();

       return view('users.messageschat')->with('data',$chatdata)->with('data1',$result);
    }
</code>```

Route file

```<code>Route::any('messageschat/{id}','MessageController@messageschat');
</code>```

Javascript file

```<code><script>
$("#add").click(function() {

    $.ajax({
        type: 'post',
        url: 'messageschat/{id}',
        data: {
            '_token': $('input[name=_token]').val(),
            'messages': $('input[messages=messages]').val(),
            'id':$('input[name=_token]').val()
        },
        success: function(data) {
          alert(data)
            if ((data.errors)) {
                $('.error').removeClass('hidden');
                $('.error').text(data.errors.name);
            } else {
                $('.error').remove();
                $('#table').append("");
            }
        },
    });
    $('#name').val('');
});
    </script>
</code>```

答:
Just change the button type to avoid default form submission and use ajax

```<code><button class="btn btn-info" type="submit" id="add">SEND</button>
</code>```

to

```<code><button class="btn btn-info" type="button" id="add">SEND</button>
</code>```

Plus there's some typo in the data that you are sending

```
data: {
        '_token': $('input[<b>name="_token"</b>]').val(),
        'messages': $('input[<b>name="messages"</b>]').val(),
        'id':$('input[<b>name="id"</b>]').val()
}
```

id isn't defined in JavaScript, so the ajax url would be wrong

Body:
I am working on laravel and I want to send personally messages to the users using blade template. But when I press submit button it gets refreshed/reload the page every time. what to do? and please anyone tell me how to use ajax url, type, data

View file

<form action="{{action('MessageController@sendmessagereply')}}" method="post">

                   <?php if(isset($data)){ ?>
                   <?php for($i=0;$i<count($data);$i++) {?>
                    <input type="hidden" name="_token" value="{{csrf_token()}}">
                    <input type="hidden" name="id" value="<?php echo $data[$i]->receivermsgid;?>">
                    <?php } }?>
                    <input type="text"  name="messages" class="form-control" placeholder="Enter Message" />

                       <button class="btn btn-info" type="submit">SEND</button>

          </form>

Controller file

 public function sendmessagereply(Request $request)
      {
            $post=$request->all();
            $id=$post['id'];
            $senderid=Session::get('login_userid');
            $receiverid = $id;
            $data=array(
                        'sendermsgid' => $senderid,
                        'receivermsgid' => $receiverid,
                        'message'=>$post['messages'],
                        'sdate'=> DB::raw('CURRENT_TIMESTAMP')
                        );
            $messages = DB::table('messages')->insert($data);
            if($messages){
                \Session::flash('msg','Your Message Has Been Sent Successfully');
                return redirect('messageschat/'.$id);
            } else {
                \Session::flash('msg','Error In Sending Message');
                return redirect('basicsearch');
            }

        }

  //i get the all messages between two users
  public function messageschat($id)
    {
       $senderid=Session::get('login_userid');
       $result=DB::table('messages')
                  ->join('user_register','messages.sendermsgid','=','user_register.id')
                  ->leftjoin('profilephoto','messages.receivermsgid','=','profilephoto.userid','messages.sendermsgid','=','profilephoto.userid')
                  ->where('sendermsgid', $senderid)->where('receivermsgid',$receivermsgid)
                  ->orwhere('sendermsgid',$receivermsgid)->where('receivermsgid',$senderid)
                  ->select('messages.message','messages.sendermsgid','messages.receivermsgid','user_register.first_name as fname','profilephoto.name')
                  ->orderby('messages.sdate')
                  ->get();

       $chatdata=DB::table('messages')
                     ->select('messages.message','messages.receivermsgid','messages.sendermsgid')
                     ->where('receivermsgid',$receivermsgid)
                     ->where('sendermsgid',$senderid)->get();

       return view('users.messageschat')->with('data',$chatdata)->with('data1',$result);
    }

Route file

Route::any('messageschat/{id}','MessageController@messageschat');

Javascript file

Body:
Just change the button type to avoid default form submission and use ajax

<button class="btn btn-info" type="submit" id="add">SEND</button>

to

<button class="btn btn-info" type="button" id="add">SEND</button>

Plus there's some typo in the data that you are sending

data: {
        '_token': $('input[name="_token"]').val(),
        'messages': $('input[name="messages"]').val(),
        'id':$('input[name="id"]').val()
}

id isn't defined in JavaScript, so the ajax url would be wrong


问:
How to programmatically trigger document generation in EA
Is it possible to trigger a Document generation programmatically in EA similar to HTML generation?

Is there any way to do like below "RunHTMLReport" for document generation?

"RunHTMLReport(PackageGUID,ExportPath ,ImageFormat,Style,Extension)"

答: RTFM: Repository.CreateDocumentGenerator in EA's documentation


问:
Where do I download a precompiled version of QtWebKit for Qt 5.8 and MSVC2015
I found a link to a place to download a precompiled version of QtWebKit for Qt 5.8/MSVC2015 here on Stackoverflow a few months ago but can't seem to dig it up anymore. (Asking me to use QWebEngine won't help -- it's not working and it appears to be impossible to get it work).</p>

答: Since Qt no longer ships binaries of QtWebKit since its deprecation, probably what you had found before is the link to binaries of QtWebKit revival project - currently there are available binaries of "technology preview 5" pre-release version: https://github.com/annulen/webkit/releases/tag/qtwebkit-tp5.


问:
Streaming log(txt) viewer
Anybody in the know of a viewer (or Notepad++ plugin) that can read txt files in a streaming way?
I would like to see for example the last 10 lines of a txt file that gets appended continiously.</p>

答:
Should try Lister with Logtail_plugin.wlx / logViewer.wlx plugin.
http://www.ghisler.com/lister/</p>

OwnerDisplayName: boris callens

Title: Streaming log(txt) viewer


问:
How to define an instance of a class by user input?
I have been trying to create a program that calculates and records calories contained in certain meals, and I have a class named 'Food' which I would like to create instances of by user input. I have done a good lot of searching and haven't found any way I can do so.

Currently I have got around the problem by creating a list, like so;

```<code>ingredients.append(Food(food_name, calories, protein, fat, quantity))
</code>```

The problem is that I now have to reference food by index in that list, as opposed to by name, which may be inconvenient later in the program.

I would like to do something like this;

```<code>food_name = input("Enter the food's name: ")
food_name = Food(calories, protein, fat, quantity)
</code>```

But this just reassigns the variable food_name without the input.

Surely it is possible to create an instance by user input. Would appreciate any solutions! :)

答: Instead of appending to a list of Foods, add them to a dict.  The key will be the food name, and inserting the same name twice will be an error (you will have to code this yourself, because a dict will happily overwrite an existing item).</p>

Body:
I have been trying to create a program that calculates and records calories contained in certain meals, and I have a class named 'Food' which I would like to create instances of by user input. I have done a good lot of searching and haven't found any way I can do so.

Currently I have got around the problem by creating a list, like so;

ingredients.append(Food(food_name, calories, protein, fat, quantity))

The problem is that I now have to reference food by index in that list, as opposed to by name, which may be inconvenient later in the program.

I would like to do something like this;

food_name = input("Enter the food's name: ")
food_name = Food(calories, protein, fat, quantity)

But this just reassigns the variable food_name without the input.

Surely it is possible to create an instance by user input. Would appreciate any solutions! :)


问:
Image at center
I am coding a website in which I want the image to be in the center at all size of screens.

I tried:-

    <title></title>

    <form id="form1">

    </form>

```
</div>
</div>
</p>

<p>The above code couldn't give me success.</p>

<p>Please help me out!</p>

<p>Please share your codes for the same.</p>

<p>I am not able to center the image with my code so please help me out.</p>

<p>CSS is:-</p>

```
```

答:
if you want to display horizontally and vertically center try this:
i have put height,width and border to make it more understandable.
for different screen sizes you have to specify image width accordingly using media query.

window.onload = function () {
            var rotator = document.getElementById("rotator");
            var images = rotator.getElementsByTagName("img");
            for (var i = 1; i < images.length; i++) {
                images[i].style.display = "none";
            }
            var counter = 1;
            setInterval(function () {
                for (var i = 0; i < images.length; i++) {
                    images[i].style.display = "none";
                }
                images[counter].style.display = "block";
                counter++;
                if (counter == images.length) {
                    counter = 0;
                }
            }, 1000);
        };```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pg {
    display:flex;
    align-items:center;
    justify-content:center;
    height:200px;
    border: 1px solid red;

}
img {
       width:80px;
    }</code>```

    <form id="form1">

    </form>```

Title: Image at center

Body:
I am coding a website in which I want the image to be in the center at all size of screens.

I tried:-

    <title></title>

    <form id="form1">

    </form>

The above code couldn't give me success.

Please help me out!

Please share your codes for the same.

I am not able to center the image with my code so please help me out.

CSS is:-

Body:
if you want to display horizontally and vertically center try this:
i have put height,width and border to make it more understandable.
for different screen sizes you have to specify image width accordingly using media query.

window.onload = function () {
            var rotator = document.getElementById("rotator");
            var images = rotator.getElementsByTagName("img");
            for (var i = 1; i < images.length; i++) {
                images[i].style.display = "none";
            }
            var counter = 1;
            setInterval(function () {
                for (var i = 0; i < images.length; i++) {
                    images[i].style.display = "none";
                }
                images[counter].style.display = "block";
                counter++;
                if (counter == images.length) {
                    counter = 0;
                }
            }, 1000);
        };

.pg {
    display:flex;
    align-items:center;
    justify-content:center;
    height:200px;
    border: 1px solid red;

}
img {
       width:80px;
    }

    <form id="form1">
    <div class="pg" id="rotator">
      <div class="img" id="rotator">
        <img alt="" src="https://i.stack.imgur.com/pBxRp.png" />
        <img alt="" src="https://i.stack.imgur.com/5GIJP.png" />
      </div>
    </div>
    </form>


问:
When an ASP.NET System.Web.HttpResponse.End() is called, the current thread is aborted?
when a System.Web.HttpResponse.End() is called a System.Thread.Abort is being fired, which i'm guessing is (or fires) an exception? I've got some logging and this is being listed in the log file...

A first chance

```<code>exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll
12/14/2008 01:09:31::
Error in Path :/authenticate
Raw Url :/authenticate
Message :Thread was being aborted.
Source :mscorlib
Stack Trace :   at System.Threading.Thread.AbortInternal()
   at System.Threading.Thread.Abort(Object stateInfo)
   at System.Web.HttpResponse.End()
   at DotNetOpenId.Response.Send()
   at DotNetOpenId.RelyingParty.AuthenticationRequest.RedirectToProvider()
   at MyProject.Services.Authentication.OpenIdAuthenticationService.GetOpenIdPersonaDetails(Uri serviceUri) in C:\Users\Pure Krome\Documents\Visual Studio 2008\Projects\MyProject\Projects\Services\Authentication\OpenIdAuthenticationService.cs:line 108
   at MyProject.Mvc.Controllers.AuthenticationController.Authenticate() in C:\Users\Pure Krome\Documents\Visual Studio 2008\Projects\MyProject\Projects\MVC Application\Controllers\AuthenticationController.cs:line 69
TargetSite :Void AbortInternal()
A first chance exception of type 'System.Threading.ThreadAbortException' occurred in Ackbar.Mvc.DLL
An exception of type 'System.Threading.ThreadAbortException' occurred in Ackbar.Mvc.DLL but was not handled in user code
</code>```

Is this normal behavior and is it possible to gracefully abort instead of (what looks like) a sudden abrupt abort?

Update

So far it the common census that it's by design. So i'm wondering if it's possible we could take this question and see if we could tweak the code to make it not feel like we're ending the thread prematurely and gracefully exit ... Possible? Code examples?

答: Don't use Response.End() method because it uses Application.End() and stop the application. Further use HTTP request or response violating Page Life Cycle. Use HttpContext.Current.Response.Close() or HttpContext.Current.ApplicationInstance.CompleteRequest(); </p>

Body:
when a System.Web.HttpResponse.End() is called a System.Thread.Abort is being fired, which i'm guessing is (or fires) an exception? I've got some logging and this is being listed in the log file...

A first chance

exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll
12/14/2008 01:09:31::
Error in Path :/authenticate
Raw Url :/authenticate
Message :Thread was being aborted.
Source :mscorlib
Stack Trace :   at System.Threading.Thread.AbortInternal()
   at System.Threading.Thread.Abort(Object stateInfo)
   at System.Web.HttpResponse.End()
   at DotNetOpenId.Response.Send()
   at DotNetOpenId.RelyingParty.AuthenticationRequest.RedirectToProvider()
   at MyProject.Services.Authentication.OpenIdAuthenticationService.GetOpenIdPersonaDetails(Uri serviceUri) in C:\Users\Pure Krome\Documents\Visual Studio 2008\Projects\MyProject\Projects\Services\Authentication\OpenIdAuthenticationService.cs:line 108
   at MyProject.Mvc.Controllers.AuthenticationController.Authenticate() in C:\Users\Pure Krome\Documents\Visual Studio 2008\Projects\MyProject\Projects\MVC Application\Controllers\AuthenticationController.cs:line 69
TargetSite :Void AbortInternal()
A first chance exception of type 'System.Threading.ThreadAbortException' occurred in Ackbar.Mvc.DLL
An exception of type 'System.Threading.ThreadAbortException' occurred in Ackbar.Mvc.DLL but was not handled in user code

Is this normal behavior and is it possible to gracefully abort instead of (what looks like) a sudden abrupt abort?

Update

So far it the common census that it's by design. So i'm wondering if it's possible we could take this question and see if we could tweak the code to make it not feel like we're ending the thread prematurely and gracefully exit ... Possible? Code examples?


答:
If I understood correctly, what you want to do is execute a piece of code some time after the service starts. If that is the case, then your best bet would be to use a timer.

First off, you have to convert the amount of time you want to wait to milliseconds. For example, 5 minutes equals 300000ms. Then, you have to move the code you want to execute to a separate method. I will name this method RunCode() for the example. Finally, you create your timer like so:

```<code>private void RunService()
{
    var timer = new Timer(300000);
    timer.Elapsed += (s, e) => this.RunCode();
    timer.Start();
    Thread.Sleep(Timeout.Infinite);
}
</code>```

What we are doing here is the following.

Instantiating the timer with an interval of 300000ms

Subscribing to the timer's Elapsed event, which fires when the specified time has passed

Starting the timer

Sleeping our main thread forever. This line is optional. Whether you need it or not depends on the structure of your program. If nothing else happens in your code after you start the timer, the main thread and by extension the whole program will exit. However by sleeping it with an infinite timeout, we can prevent that.

If you're sure that this, delayed execution of code, is what you want, then the solution I have provided should work quite well. However I'm worried this may be an XY problem, meaning this is the solution you have come up with for a different issue which could be solved better. So I have to ask, why exactly do you need this in your service?

Title: Run method after defined time on windows service

Body:
If I understood correctly, what you want to do is execute a piece of code some time after the service starts. If that is the case, then your best bet would be to use a timer.

First off, you have to convert the amount of time you want to wait to milliseconds. For example, 5 minutes equals 300000ms. Then, you have to move the code you want to execute to a separate method. I will name this method RunCode() for the example. Finally, you create your timer like so:

private void RunService()
{
    var timer = new Timer(300000);
    timer.Elapsed += (s, e) => this.RunCode();
    timer.Start();
    Thread.Sleep(Timeout.Infinite);
}

What we are doing here is the following.

Instantiating the timer with an interval of 300000ms

Subscribing to the timer's Elapsed event, which fires when the specified time has passed

Starting the timer

Sleeping our main thread forever. This line is optional. Whether you need it or not depends on the structure of your program. If nothing else happens in your code after you start the timer, the main thread and by extension the whole program will exit. However by sleeping it with an infinite timeout, we can prevent that.

If you're sure that this, delayed execution of code, is what you want, then the solution I have provided should work quite well. However I'm worried this may be an XY problem, meaning this is the solution you have come up with for a different issue which could be solved better. So I have to ask, why exactly do you need this in your service?


问:
WPF App with WCF Data - EF, Linq2Sql or WCF Data Services - None Seem 'Easy'
I am doing something I consider to be pretty normal (although I personally haven't had to do it before), and I have assumed there'd be a 'no-brainer' way forward, but Im yet to find it - which is really frustrating.

I will be creating a WPF application, which is a data-oriented business application. My data will come from a remote IIS server (that I control) that has a standard SQL server 2008 database, so Web services/WCF seem to be the way forward. The remote service needs to be secure (reasonably) via a user (of the WPF client) username/password login.

I dont want to use 3rd party ORM products, but I expect the data layer (between the service and the database) to be able to cope with very simple ORM type functionality (I really dont want to hand-craft a data retrieval and persistence layer). Im not worried about concurrency very much as this will be a fairly simple app.

My options seem to be one of the following:

ADO.NET Entity Framework over WCF

Linq2Sql over WCF

WCF Data Services

On further investigation, none of the above seem to be the 'no brainer' Im after

1) ADO.NET entity Framework - Ive had a play with this and getting all sorts of issues serializing objects over WCF. Even when  I try to generate POCO entities and use them, Im having to decorate service contracts with custom attributes just to get it to not error all the time, and I seem to have to hand-crank anything more than a flat object graph. It seems to me that EF simply isn't designed to be exposed via a service.

2) Linq2Sql - This doesn't seem much better than EF. I seem to have to hand-crank too much stuff. Ive tried the designer and SQLMetal but nothing seems to 'just work' - it all needs fiddling with.

3) WCF Data Services - this seems like a good option on the face of it, but essentially it seems like I'm just exposing my SQL database tables 'in the raw' over the service layer. Im not an expert in this technology by any means but it seems like a potentially dangerous approach, and on top of that it doesnt seem to support any kind of access security as standard (you have to hack it to require authentication it seems).

As I said, this scenario feels like it should have a no-brainer solution, but Im still scratching my head. Ive done lots of things with .NET technologies, but to be honest this area represents a bit of a hole in my understanding, so I apologize if any of my comments or assumptions are naive.

Of course, it may well be that the 'hacky' long-way-round on EF or Linq2SQL may be all I can do, in which case I can roll up my sleeves, and accept the fact that I haven't missed a more elegant solution.

Any help/advice will be much appreciated.

答:
3) WCF Data Services - this seems like
  a good option on the face of it, but
  essentially it seems like I'm just
  exposing my SQL database tables 'in
  the raw' over the service layer.

That might be a first impression - but it's fundamentally wrong. What you're exposing over the web is a model - and you have full control over what gets into that model, and how consumers of your WCF Data Services might be able to see and/or even update entities in that model.

That's where Entity Framework comes in and shines (and where Linq-to-SQL miserably fails): you can grab your database (or at least parts of it) into an Entity Data Model, and then modify it. You can tweak your entity names to be totally different from your table names, you can add computed attributes, you can remove certain attributes and much more.

If you're talking about a fairly simple app, that's definitely the way I'd go:

grab your database and turn it into an Entity Data Model using EF

expose that EDM over WCF Data Services and define what can be seen read-only, and what might even be updated over the wire


答:
Use a dictionary.</p>

```<code>foods = {}
food_name = input("Enter the food's name: ")
foods[food_name] = Food(calories, protein, fat, quantity)
</code>```

Title: How to define an instance of a class by user input?

Body:
Use a dictionary.

foods = {}
food_name = input("Enter the food's name: ")
foods[food_name] = Food(calories, protein, fat, quantity)


问:
October installation
I have installed october via console interface page. Backend works fine but UI gives error:

The "Cms\Facades\Cms" extension is not enabled.

I couldn't figure out whats wrong with it.Could anybody help?

答:
Appears to be composer loading a too new version of Twig -

https://github.com/octobercms/october/issues/2908#issuecomment-306431036

fixed by opening composer.json in the root directory, adding to the require object this value:

"twig/twig": "1.33.*",

Then perform composer update to rectify the breaking package. This will be fixed in Build 420+ as we move to Twig 2.0. This upgrade won't occur for at least 1-2 months. Leaving this open until then.

Title: October installation


问:
Store a number in an integer string and recall it in a later action
I'm currently trying to get a UISlider to work.

I'm trying to set the strings value as 8 to start off with on view load.

Then when the slider changes value I want the string to update with that number, and then later on I can use the value in the string for a setDuration:## later on in another action.

Any ideas?

答:
To update the string you just get the value and do:

```<code>NSString *myString = [NSString stringWithFormat:@"%f", [slider value]];
</code>```

To get the string value back as a float you just do:

```<code>float myValue = [myString floatValue];
</code>```

LastEditorDisplayName: Chris Hanson

Body:
To update the string you just get the value and do:

NSString *myString = [NSString stringWithFormat:@"%f", [slider value]];

To get the string value back as a float you just do:

float myValue = [myString floatValue];

OwnerDisplayName: Martin Pilkington


问:
C++ time series library (analysis and processing)
I'm looking to get Stack Overflowers' advice and suggestion on time-series libraries written in C++, some of the constraints and requirements for the library:

Performance is very critical

Capable of handling very large data sets (1 MB - 100 TB range)

Various kind of discretization/grouping methodologies

Basic functionality (n-avg, EMA, smoothing, forecasting, normalization)

Suitable for use in a multi-threaded environments

Free or open source preferred, however commercial libraries are welcome

Libraries capable of delegating to GPU-based calculations are welcome

答:
Don't despair!

There is stuff out there, but your question is very general, in the sense that you might need several libraries to achieve your result.

GSL (GNU Scientific Library) has statistical functions...

FFTW (Fastest Fourier Transform in the West) lives up to its name, but if it meets your requirements... I don't know.

There are others, but don't know them. Some of the algorithms you need are in the C++ standard library, or aren't very hard to code as fast as possible like n-avg). GPU offloading is going to be difficult (especially due to the data set size, which will probably make it a bad idea, multi-threading is a possibility in the abovementioned libraries.

OwnerDisplayName: Matthieu N.

LastEditorDisplayName: Matthieu N.


问:
R function to return matrix rows that satisfy min and max ranges
Having the following matrix:

```<code>      [,1] [,2] [,3] [,4]
  [1,]  231   14  517  310
  [2,]    1  154   18   21
  [3,]  121    6  198   23
</code>```

I want to get only the rows that have a minimum range for each row between 2
   and 30.

Min range for each row:

```<code> [1] 79
 [2]  3
 [3] 17
</code>```

so we get only [2] and [3]

and a max range between 0 and 160
   Max range for each row:

```<code>  [1] 503
  [2] 153
  [3] 192
</code>```

so finally we get only [2] that satisfies the two conditions.
   Can you please provide an R language function which can generate this result?

Regards,
Dimitris

答:
Here is a solution using the function dist():

```<code>m <- matrix(
  c(231, 14, 517, 310,
    1,  154,   18,   21,
  121,    6,  198,   23 ), 3, byrow=TRUE)

mi <- apply(m, 1, function(x) min(dist(x)))
ma <- apply(m, 1, function(x) max(dist(x)))

m[mi > 2 & mi < 30 & ma > 0 & ma < 160, ]
</code>```

Body:
Having the following matrix:

      [,1] [,2] [,3] [,4]
  [1,]  231   14  517  310
  [2,]    1  154   18   21
  [3,]  121    6  198   23

I want to get only the rows that have a minimum range for each row between 2
   and 30.

Min range for each row:

 [1] 79
 [2]  3
 [3] 17

so we get only [2] and [3]

and a max range between 0 and 160
   Max range for each row:

  [1] 503
  [2] 153
  [3] 192

so finally we get only [2] that satisfies the two conditions.
   Can you please provide an R language function which can generate this result?

Regards,
Dimitris

Body:
Here is a solution using the function dist():

m <- matrix(
  c(231, 14, 517, 310,
    1,  154,   18,   21,
  121,    6,  198,   23 ), 3, byrow=TRUE)

mi <- apply(m, 1, function(x) min(dist(x)))
ma <- apply(m, 1, function(x) max(dist(x)))

m[mi > 2 & mi < 30 & ma > 0 & ma < 160, ]


问:
Debug Gatling Scala Code in Intellij with Maven Java Project
I didn't add a comment in this Debug Scala Post because in my opinion it was another setup.

I had a similiar problem with Maven instead of SBT. I used Maven because the complete Java project was built upon it and I only wanted to debug my Gatling Scala code. However I'm not able to debug the code with the IDE.

Here's what I tried:

Clean the built mvn clean install

Invalidate caches in IDEA with the menu button

Use println to see whether the code is reached - worked

Redeploy the project on the Glassfish

Delete the generated files in the Glassfish and redeploy

This is my current setup:

Maven 3.3.9

Glassfish Payara 4 build 163

IDEA 2016.3.4. built on January 31 2017

JDK 1.8.0_51

Gatling 2.2.3

Scala-Maven-Plug 3.2.2

My solution is as follows.

答:
With the help of colleague I figured out that the main class in Engine from the Gatling tutorial can be used to debug out of Intellij.

I basically built the whole archetype and moved the following files into the corresponding folders:

src/test/resources/gatling.conf

src/test/scala/Engine.scala and IDEPathHelper

That did the trick for me.


问:
Partial update REST in Spring Boot and Kotlin
I have a project with Spring Boot + Kotlin + Morphia.

I need add partial update of my entities. My actual post method:

```<code>   @PostMapping("update/")
    fun updateStudent(@RequestBody @Valid  student: Student, results: BindingResult): ResponseData<Student> {

        if (results.hasErrors())
            return ResponseData(errors = results.errors)

        if (!student.canEdit(login.user))
            return ResponseData()

        student.save()
        return ResponseData(data = student)
    }
</code>```

I need read student from database and update only the sended fields

答:
There are 2 things to implement. Reading Student from DB and copying properties from the student from request.

I post java code but it's no problem to convert to kotlin

```<code>Morphia morphia = new Morphia();
db = new Mongo();
Datastore ds = morphia.createDatastore(db, appname, user, pass.toCharArray());

morphia.map(Student.class);
Student existing= ds.find(Student.class).field("id").equal(student.id).get();
</code>```

Then you can use Apache BeanUtils

http://commons.apache.org/proper/commons-beanutils/javadocs/v1.8.3/apidocs/org/apache/commons/beanutils/BeanUtils.html#copyProperties%28java.lang.Object,%20java.lang.Object%29

```<code> BeanUtils.copyProperties(existing, student);
</code>```

then

```<code>existing.save();
</code>```

Body:
I have a project with Spring Boot + Kotlin + Morphia.

I need add partial update of my entities. My actual post method:

   @PostMapping("update/")
    fun updateStudent(@RequestBody @Valid  student: Student, results: BindingResult): ResponseData<Student> {

        if (results.hasErrors())
            return ResponseData(errors = results.errors)

        if (!student.canEdit(login.user))
            return ResponseData()

        student.save()
        return ResponseData(data = student)
    }

I need read student from database and update only the sended fields

Body:
There are 2 things to implement. Reading Student from DB and copying properties from the student from request.

I post java code but it's no problem to convert to kotlin

Morphia morphia = new Morphia();
db = new Mongo();
Datastore ds = morphia.createDatastore(db, appname, user, pass.toCharArray());

morphia.map(Student.class);
Student existing= ds.find(Student.class).field("id").equal(student.id).get();

Then you can use Apache BeanUtils

http://commons.apache.org/proper/commons-beanutils/javadocs/v1.8.3/apidocs/org/apache/commons/beanutils/BeanUtils.html#copyProperties%28java.lang.Object,%20java.lang.Object%29

 BeanUtils.copyProperties(existing, student);

then

existing.save();


问:
change viewpage swipe direction in RTL layer in android
i try use RTL layerdirection in activity with viewpager and TabLayout.but in RTL layer viewpager swipe direction reversed and with set CurrentItem to ViewPager , TabLayout also to be changed.

i try this after and before setupWithViewPager but dose not work.

any idea..!!

i try this :

```<code>    mViewPager = (ViewPager) findViewById(R.id.mViewPager );
    mViewPager.setAdapter(Adapter);
    mViewPager.setCurrentItem(mViewPager.getAdapter().getCount() - 1,false);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
</code>```

and this :

```<code>    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
    mViewPager.setCurrentItem(mViewPager.getAdapter().getCount() - 1,false);
</code>```

答:
you can create a custom pager adapter:

```<code>public class Custom_PagerAdapter extends FragmentPagerAdapter{

/*
* Attributes:
*
* the class attributes
*
* */

private ArrayList<Object> ItemList;

/*
* AutoRuns:
*
* these methods were called at startup
*
* */

/////////////
//////////////////Constructor:
//////////////
public Custom_PagerAdapter(FragmentManager fm){
    super(fm);
    ItemList = new ArrayList<>();
}

/*
* Setters:
*
* sets class attributes
*
* */

/////////////
//////////////////addItem:
//////////////
public void addItem(Object item){ItemList.add(item);}

/*
* Getters:
*
* gets class attributes
*
* */

/////////////
//////////////////getItem:
//////////////
@Override
public Fragment getItem(int position){
    return (Fragment) ItemList.get(getDirectionalPagerPosition(position));
}

/////////////
//////////////////getCount:
//////////////
@Override
public int getCount(){return ItemList.size();}

/*
* Other Functions:
*
* class other functions
*
* */

/////////////
//////////////////getDirectionalPagerPosition:
//calculates the pager position considering app direction
public int getDirectionalPagerPosition(int virtualPosition){
    int actualPosition;
    if(Core.getDirection() == Direction.LTR)//make your own if
        actualPosition = virtualPosition;
    else
        actualPosition = getCount()-1-virtualPosition;
    return actualPosition;
}

/////////////
//////////////////getDirectionalTabPosition:
//calculates the tab position considering app direction
public int getDirectionalTabPosition(int virtualPosition){
    int actualPosition;
    if(Core.getDirection() == Direction.LTR)
        actualPosition = virtualPosition;
    else{
        actualPosition = getCount()-2-virtualPosition;
        if(actualPosition < 0)
            actualPosition = 0;
        if(virtualPosition > getCount()-2)
            actualPosition = getCount()-1;
    }
    return actualPosition;
}

/////////////
//////////////////getDirectionalTabPositionOffset:
//calculates the tab position offset considering app direction
public float getDirectionalTabPositionOffset(float virtualPositionOffset){
    float actualPositionOffset;
    if(Core.getDirection() == Direction.LTR)
        actualPositionOffset = virtualPositionOffset;
    else
        actualPositionOffset = 1-virtualPositionOffset;
    return actualPositionOffset;
}
</code>```

}

and the use it:

```<code>/*
* Initializers:
*
* were initialize the components
*
* */

/////////////
//////////////////initTabBar:
//////////////
private void initTabBar(){
    Main_TabLyt = (CustomTabLayout) findViewById(R.id.Main_TabLyt);
    /** count of tabs must be equal to count of pages in {@link #initPager()} */
    Main_TabLyt.addTab(Main_TabLyt.newTab().setText("Tab 1"));
    Main_TabLyt.addTab(Main_TabLyt.newTab().setText("Tab 2"));
    Main_TabLyt.addTab(Main_TabLyt.newTab().setText("Tab 3"));
    addTabBarOnTabSelectedListener();
}

/////////////
//////////////////initPager:
//////////////
private void initPager(){
    Main_PgrAdp = new Custom_PagerAdapter(getSupportFragmentManager());
    /** count of pages must be equal to count of tabs in {@link #initTabBar()} */
    Main_PgrAdp.addItem(new View1());
    Main_PgrAdp.addItem(new View2());
    Main_PgrAdp.addItem(new View3());
    Main_ViwPgr = (ViewPager) findViewById(R.id.Main_Pager);
    Main_ViwPgr.setAdapter(Main_PgrAdp);
    Main_ViwPgr.setCurrentItem(Main_PgrAdp.getDirectionalPagerPosition(0));//first page by considering app direction
    addPagerOnPageChangeListener();
}

/*
* Listeners:
*
* these methods are called after user action
*
* */

/////////////
//////////////////addTabBarOnTabSelectedListener:
//////////////
public void addTabBarOnTabSelectedListener(){
    Main_TabLyt.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
        @Override
        public void onTabSelected(Tab tab){//selects pager item by considering app direction
            Main_ViwPgr.setCurrentItem(Main_PgrAdp.getDirectionalPagerPosition(tab.getPosition()));
        }
        @Override
        public void onTabUnselected(Tab tab){}
        @Override
        public void onTabReselected(Tab tab){}
    });
}

/////////////
//////////////////addPagerOnPageChangeListener:
//////////////
private void addPagerOnPageChangeListener(){
    Main_ViwPgr.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels){//sets tab bar scroll position by considering app direction
            Main_TabLyt.setScrollPosition(Main_PgrAdp.getDirectionalTabPosition(position), Main_PgrAdp.getDirectionalTabPositionOffset(positionOffset), false);
        }
        @Override
        public void onPageSelected(int position){
            Tab tab = Main_TabLyt.getTabAt(Main_PgrAdp.getDirectionalPagerPosition(position));
            if(tab != null) tab.select();
        }
        @Override
        public void onPageScrollStateChanged(int state){}
    });
}
</code>```

Body:
i try use RTL layerdirection in activity with viewpager and TabLayout.but in RTL layer viewpager swipe direction reversed and with set CurrentItem to ViewPager , TabLayout also to be changed.

i try this after and before setupWithViewPager but dose not work.

any idea..!!

i try this :

    mViewPager = (ViewPager) findViewById(R.id.mViewPager );
    mViewPager.setAdapter(Adapter);
    mViewPager.setCurrentItem(mViewPager.getAdapter().getCount() - 1,false);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

and this :

    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
    mViewPager.setCurrentItem(mViewPager.getAdapter().getCount() - 1,false);

Body:
you can create a custom pager adapter:

public class Custom_PagerAdapter extends FragmentPagerAdapter{

/*
* Attributes:
*
* the class attributes
*
* */

private ArrayList<Object> ItemList;

/*
* AutoRuns:
*
* these methods were called at startup
*
* */

/////////////
//////////////////Constructor:
//////////////
public Custom_PagerAdapter(FragmentManager fm){
    super(fm);
    ItemList = new ArrayList<>();
}

/*
* Setters:
*
* sets class attributes
*
* */

/////////////
//////////////////addItem:
//////////////
public void addItem(Object item){ItemList.add(item);}

/*
* Getters:
*
* gets class attributes
*
* */

/////////////
//////////////////getItem:
//////////////
@Override
public Fragment getItem(int position){
    return (Fragment) ItemList.get(getDirectionalPagerPosition(position));
}

/////////////
//////////////////getCount:
//////////////
@Override
public int getCount(){return ItemList.size();}

/*
* Other Functions:
*
* class other functions
*
* */

/////////////
//////////////////getDirectionalPagerPosition:
//calculates the pager position considering app direction
public int getDirectionalPagerPosition(int virtualPosition){
    int actualPosition;
    if(Core.getDirection() == Direction.LTR)//make your own if
        actualPosition = virtualPosition;
    else
        actualPosition = getCount()-1-virtualPosition;
    return actualPosition;
}

/////////////
//////////////////getDirectionalTabPosition:
//calculates the tab position considering app direction
public int getDirectionalTabPosition(int virtualPosition){
    int actualPosition;
    if(Core.getDirection() == Direction.LTR)
        actualPosition = virtualPosition;
    else{
        actualPosition = getCount()-2-virtualPosition;
        if(actualPosition < 0)
            actualPosition = 0;
        if(virtualPosition > getCount()-2)
            actualPosition = getCount()-1;
    }
    return actualPosition;
}

/////////////
//////////////////getDirectionalTabPositionOffset:
//calculates the tab position offset considering app direction
public float getDirectionalTabPositionOffset(float virtualPositionOffset){
    float actualPositionOffset;
    if(Core.getDirection() == Direction.LTR)
        actualPositionOffset = virtualPositionOffset;
    else
        actualPositionOffset = 1-virtualPositionOffset;
    return actualPositionOffset;
}

}

and the use it:

/*
* Initializers:
*
* were initialize the components
*
* */

/////////////
//////////////////initTabBar:
//////////////
private void initTabBar(){
    Main_TabLyt = (CustomTabLayout) findViewById(R.id.Main_TabLyt);
    /** count of tabs must be equal to count of pages in {@link #initPager()} */
    Main_TabLyt.addTab(Main_TabLyt.newTab().setText("Tab 1"));
    Main_TabLyt.addTab(Main_TabLyt.newTab().setText("Tab 2"));
    Main_TabLyt.addTab(Main_TabLyt.newTab().setText("Tab 3"));
    addTabBarOnTabSelectedListener();
}

/////////////
//////////////////initPager:
//////////////
private void initPager(){
    Main_PgrAdp = new Custom_PagerAdapter(getSupportFragmentManager());
    /** count of pages must be equal to count of tabs in {@link #initTabBar()} */
    Main_PgrAdp.addItem(new View1());
    Main_PgrAdp.addItem(new View2());
    Main_PgrAdp.addItem(new View3());
    Main_ViwPgr = (ViewPager) findViewById(R.id.Main_Pager);
    Main_ViwPgr.setAdapter(Main_PgrAdp);
    Main_ViwPgr.setCurrentItem(Main_PgrAdp.getDirectionalPagerPosition(0));//first page by considering app direction
    addPagerOnPageChangeListener();
}

/*
* Listeners:
*
* these methods are called after user action
*
* */

/////////////
//////////////////addTabBarOnTabSelectedListener:
//////////////
public void addTabBarOnTabSelectedListener(){
    Main_TabLyt.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
        @Override
        public void onTabSelected(Tab tab){//selects pager item by considering app direction
            Main_ViwPgr.setCurrentItem(Main_PgrAdp.getDirectionalPagerPosition(tab.getPosition()));
        }
        @Override
        public void onTabUnselected(Tab tab){}
        @Override
        public void onTabReselected(Tab tab){}
    });
}

/////////////
//////////////////addPagerOnPageChangeListener:
//////////////
private void addPagerOnPageChangeListener(){
    Main_ViwPgr.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels){//sets tab bar scroll position by considering app direction
            Main_TabLyt.setScrollPosition(Main_PgrAdp.getDirectionalTabPosition(position), Main_PgrAdp.getDirectionalTabPositionOffset(positionOffset), false);
        }
        @Override
        public void onPageSelected(int position){
            Tab tab = Main_TabLyt.getTabAt(Main_PgrAdp.getDirectionalPagerPosition(position));
            if(tab != null) tab.select();
        }
        @Override
        public void onPageScrollStateChanged(int state){}
    });
}


问:
How to insert row with MAX(number) + 1 in PostgreSQL transactionally without sequence
I have a PostgreSQL table that can be simplified as this:

```<code>CREATE TABLE car(
  garage_id uuid,
  number integer
);
</code>```

I need that in each garage, each car has a unique integer number (Car N°1, Car N°2).

First idea with sequence

My first idea was to create a PostgreSQL sequence for each garage thanks to a trigger, and then when I insert a car, I just need to call nextval on the sequence created for the garage. (Like seen here)

The problem is that for each garage, I need to create a sequence. My garage table will soon grow up to 1M rows, and according to this thread: Maximum number of sequences that can be created, too much PostgreSQL sequence can really hurt performance and make pgdump fails.

Second Idea

I found another idea on stackoverflow.

The second idea was to create another table like

```<code>CREATE TABLE garage_number(
  garage_id uuid,
  max_number integer
);
</code>```

This table would keep the max car number, and then at each insert we select the max_number of the garage, and update the max_number of the garage.

Problem: For the moment it does not work in terms of concurrency (2 cars can have the same number if inserted at the same time).

Do you have any idea of how I can make this be transaction-proof and work at scale? Maybe locking the garage_number table?

Thank you very much for your help,

答:
If you don't insert several cars in one transaction, maybe it's worth of trying the txid_current()?.. The number would be isolated from other transactions and would be unique. The only obvious but here - it would not be sequential (you cant predict the step, as it depends on amount of transactions while you perform yours).

smth like:

```<code>insert into car
  (garage, number)
values
  ('a0ee-bc99-9c0b-4ef8-bb6d-6bb9-bd38-0a11', txid_current());
</code>```

Of course it will not work if you run the above statement several times in same transaction, as txid_current() would be same. But if you separate each insert - this might work

https://www.postgresql.org/docs/current/static/functions-info.html

Body:
I have a PostgreSQL table that can be simplified as this:

CREATE TABLE car(
  garage_id uuid,
  number integer
);

I need that in each garage, each car has a unique integer number (Car N°1, Car N°2).

First idea with sequence

My first idea was to create a PostgreSQL sequence for each garage thanks to a trigger, and then when I insert a car, I just need to call nextval on the sequence created for the garage. (Like seen here)

The problem is that for each garage, I need to create a sequence. My garage table will soon grow up to 1M rows, and according to this thread: Maximum number of sequences that can be created, too much PostgreSQL sequence can really hurt performance and make pgdump fails.

Second Idea

I found another idea on stackoverflow.

The second idea was to create another table like

CREATE TABLE garage_number(
  garage_id uuid,
  max_number integer
);

This table would keep the max car number, and then at each insert we select the max_number of the garage, and update the max_number of the garage.

Problem: For the moment it does not work in terms of concurrency (2 cars can have the same number if inserted at the same time).

Do you have any idea of how I can make this be transaction-proof and work at scale? Maybe locking the garage_number table?

Thank you very much for your help,

Body:
If you don't insert several cars in one transaction, maybe it's worth of trying the txid_current()?.. The number would be isolated from other transactions and would be unique. The only obvious but here - it would not be sequential (you cant predict the step, as it depends on amount of transactions while you perform yours).

smth like:

insert into car
  (garage, number)
values
  ('a0ee-bc99-9c0b-4ef8-bb6d-6bb9-bd38-0a11', txid_current());

Of course it will not work if you run the above statement several times in same transaction, as txid_current() would be same. But if you separate each insert - this might work

https://www.postgresql.org/docs/current/static/functions-info.html


问:
Zend PDO error - how can I debug it?
I have a weird problem using Zend Framework and Mysql. I generated a query:

```<code>SELECT events.idUser, szForename, szLastname, readers.szName, idZoneFrom, events.dtTime FROM events, users, readers WHERE events.idUser = users.idUser AND events.idReader = readers.idReader AND dtTime >= '2010:02:15 0:00:00' AND dtTime < '2010:02:16 0:00:00' ORDER BY dtTime
</code>```

The query works ok if I run it in some console like pma, navicat or shell client but when I try to run it using a model that extends Zend_Db_Table by commend

```<code>$arResult = $this->getDefaultAdapter()->query($szQuery)->fetchAll();
</code>```

it goes with 1064 error:

```<code>enter code here

An error occurred
Application error
Exception information:

Message: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
Stack trace:

#0 C:\xampp\htdocs\projekty\doors2\library\Zend\Db\Statement.php(300): Zend_Db_Statement_Pdo->_execute(Array)
#1 C:\xampp\htdocs\projekty\doors2\library\Zend\Db\Adapter\Abstract.php(468): Zend_Db_Statement->execute(Array)
#2 C:\xampp\htdocs\projekty\doors2\library\Zend\Db\Adapter\Pdo\Abstract.php(238): Zend_Db_Adapter_Abstract->query('SELECT zoneName...', Array)
#3 C:\xampp\htdocs\projekty\doors2\application\models\Zones.php(24): Zend_Db_Adapter_Pdo_Abstract->query('SELECT zoneName...')
#4 C:\xampp\htdocs\projekty\doors2\application\models\Events.php(87): Application_Model_Zones->getZoneInfo(NULL)
#5 C:\xampp\htdocs\projekty\doors2\application\controllers\IndexController.php(52): Application_Model_Events->getEventsList(NULL, '02/15/2010')
#6 C:\xampp\htdocs\projekty\doors2\library\Zend\Controller\Action.php(513): IndexController->eventsAction()
#7 C:\xampp\htdocs\projekty\doors2\library\Zend\Controller\Dispatcher\Standard.php(295): Zend_Controller_Action->dispatch('eventsAction')
#8 C:\xampp\htdocs\projekty\doors2\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#9 C:\xampp\htdocs\projekty\doors2\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#10 C:\xampp\htdocs\projekty\doors2\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#11 C:\xampp\htdocs\projekty\doors2\public\index.php(26): Zend_Application->run()
#12 {main}

Request Parameters:

array (
  'controller' => 'index',
  'action' => 'events',
  'module' => 'default',
  'idUser' => '0',
  'dt' => '02/15/2010',
)
</code>```

How can I debug it to find the problem?? Or maybe you know what could I have done wrong?

ps. I use the same db user both for php and query testing...

答: If you are using zend, you should be at least preparing any values that are passed in. If the statement works in the command line then there should not be a problem with reserved words (unless for some reason the versions of mysql are distinct, of course).</p>

Title: Zend PDO error - how can I debug it?

Body:
I have a weird problem using Zend Framework and Mysql. I generated a query:

SELECT events.idUser, szForename, szLastname, readers.szName, idZoneFrom, events.dtTime FROM events, users, readers WHERE events.idUser = users.idUser AND events.idReader = readers.idReader AND dtTime >= '2010:02:15 0:00:00' AND dtTime < '2010:02:16 0:00:00' ORDER BY dtTime

The query works ok if I run it in some console like pma, navicat or shell client but when I try to run it using a model that extends Zend_Db_Table by commend

$arResult = $this->getDefaultAdapter()->query($szQuery)->fetchAll();

it goes with 1064 error:

enter code here

An error occurred
Application error
Exception information:

Message: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
Stack trace:

#0 C:\xampp\htdocs\projekty\doors2\library\Zend\Db\Statement.php(300): Zend_Db_Statement_Pdo->_execute(Array)
#1 C:\xampp\htdocs\projekty\doors2\library\Zend\Db\Adapter\Abstract.php(468): Zend_Db_Statement->execute(Array)
#2 C:\xampp\htdocs\projekty\doors2\library\Zend\Db\Adapter\Pdo\Abstract.php(238): Zend_Db_Adapter_Abstract->query('SELECT zoneName...', Array)
#3 C:\xampp\htdocs\projekty\doors2\application\models\Zones.php(24): Zend_Db_Adapter_Pdo_Abstract->query('SELECT zoneName...')
#4 C:\xampp\htdocs\projekty\doors2\application\models\Events.php(87): Application_Model_Zones->getZoneInfo(NULL)
#5 C:\xampp\htdocs\projekty\doors2\application\controllers\IndexController.php(52): Application_Model_Events->getEventsList(NULL, '02/15/2010')
#6 C:\xampp\htdocs\projekty\doors2\library\Zend\Controller\Action.php(513): IndexController->eventsAction()
#7 C:\xampp\htdocs\projekty\doors2\library\Zend\Controller\Dispatcher\Standard.php(295): Zend_Controller_Action->dispatch('eventsAction')
#8 C:\xampp\htdocs\projekty\doors2\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#9 C:\xampp\htdocs\projekty\doors2\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#10 C:\xampp\htdocs\projekty\doors2\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#11 C:\xampp\htdocs\projekty\doors2\public\index.php(26): Zend_Application->run()
#12 {main}

Request Parameters:

array (
  'controller' => 'index',
  'action' => 'events',
  'module' => 'default',
  'idUser' => '0',
  'dt' => '02/15/2010',
)

How can I debug it to find the problem?? Or maybe you know what could I have done wrong?

ps. I use the same db user both for php and query testing...


问:
How to read File using PDFReader
I have a method public void readFile(File inputFile, File outputFile), I want to read the File using PDFReader, but the reader reads only String values, I cant hardcode the string value because it is given by the user while exporting the file.

I used FileUtils.readFileToString(inputFile) but I get exception on the line PdfReader reader = new PdfReader(input);

Kindly suggest a way to achieve this.

Code Snippet:

```<code>public void readFile(File inputFile, File outputFile){
String input = FileUtils.readFileToString(inputFile);
PdfReader reader = new PdfReader(input);

//some more code
}
</code>```

答:
The PdfReader class has different constructors. When you create an instance using a String, you are supposed to pass a file path (e.g. myFolder/my.pdf). What you are doing is completely wrong! You are reading a binary file into a String. That String is not a file path!

You can easily create a PdfReader instance using a FileInputStream.

It is unclear which version of iText you are using. Please make sure that you are using iText 7. In iText 7, PdfReader has the following constructors:

PdfReader(InputStream is)

PdfReader(InputStream is, ReaderProperties properties)

PdfReader(IRandomAccessSource byteSource, ReaderProperties properties)

PdfReader(String filename)

PdfReader(String filename, ReaderProperties properties)

If for some reason you need to use iText 5, then this is the list of constructors you can use:

PdfReader(byte[] pdfIn)

PdfReader(byte[] pdfIn, byte[] ownerPassword)

PdfReader(byte[] pdfIn, Certificate certificate, ExternalDecryptionProcess externalDecryptionProcess)

PdfReader(InputStream is)

PdfReader(InputStream is, byte[] ownerPassword)

PdfReader(InputStream inputStream, Certificate certificate, ExternalDecryptionProcess externalDecryptionProcess)

PdfReader(PdfReader reader)

PdfReader(RandomAccessFileOrArray raf, byte[] ownerPassword)

PdfReader(RandomAccessFileOrArray raf, byte[] ownerPassword, boolean partial)

PdfReader(String filename)

PdfReader(String filename, byte[] ownerPassword)

PdfReader(String filename, byte[] ownerPassword, boolean partial)

PdfReader(String filename, Certificate certificate, ExternalDecryptionProcess externalDecryptionProcess)

PdfReader(String filename, Certificate certificate, Key certificateKey, String certificateKeyProvider)

PdfReader(URL url)

PdfReader(URL url, byte[] ownerPassword)

As you can see, iText 5 is much messier than iText 7. We have completely rewritten iText from scratch to get rid of plenty of legacy classes and methods that were no longer relevant. The API of iText 7 is much more slick now.

Title: How to read File using PDFReader

Body:
I have a method public void readFile(File inputFile, File outputFile), I want to read the File using PDFReader, but the reader reads only String values, I cant hardcode the string value because it is given by the user while exporting the file.

I used FileUtils.readFileToString(inputFile) but I get exception on the line PdfReader reader = new PdfReader(input);

Kindly suggest a way to achieve this.

Code Snippet:

public void readFile(File inputFile, File outputFile){
String input = FileUtils.readFileToString(inputFile);
PdfReader reader = new PdfReader(input);

//some more code
}


问:
How to list local video files using ionic 2(cordova) like gallery or any media player does
I want to make an app like media player. Want to list all videos available in the phone/sdcard and clicking on it will start playing. Now I am stuck to display list of local video files. I have tried with http://ionicframework.com/docs/v2/native/file/ and https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html but unable to get list of videos.

So, please help me to get resolution.
Thanks

答:
import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {Transfer, TransferObject} from '@ionic-native/transfer';
import {File} from '@ionic-native/file';
import { FilePath } from '@ionic-native/file-path';
import {Platform} from 'ionic-angular';

@Component({
  selector: 'page-contact',
  templateUrl: 'contact.html',
  providers: [FilePath, Transfer, TransferObject, File]

})
export class ContactPage {

 results: any;
 storageDirectory: string ='';

 constructor(public navCtrl: NavController, private filePath: FilePath, public platform: Platform, private transfer: Transfer, private file: File){

 this.platform.ready().then(() => {

       // code to create a new directory

       file.createDir(file.externalDataDirectory, 'newDir', true).then((result)=>{
    console.log("Directory newDir created" + result);

    // code to list the files and folder in the directory

       file.listDir(file.externalDataDirectory,'').then((result)=>{
    this.storageDirectory = file.externalDataDirectory;
    console.log("this.storageDirectory containnig "+ this.storageDirectory);
    console.log("listing taking place here" + file.externalDataDirectory);
         this.results=result;
     console.log("showing result content"+result);

 // code to print the name of files and folder on console as well as on device screen

 for(let file of result){
    if(file.isDirectory == true){
  console.log("Code if its a folder");
  let name=file.name;
  console.log("File name"+name);
 }
 else if(file.isFile == true){
  console.log("Code if its a file");
  let name=file.name;
  console.log("File name "+name);
  let path=this.storageDirectory+name;
  console.log(path);
    file.getMetadata(function (metadata) {
   let size=metadata.size;
   console.log("File size"+size);
      })
 }
 }

/*result will have an array of file objects with
file details or if its a directory:  */
    });
  });

});
 }
 }```

Please check this my running code, may can help you to get the list of files and folders from the internal storage.

Body:
import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {Transfer, TransferObject} from '@ionic-native/transfer';
import {File} from '@ionic-native/file';
import { FilePath } from '@ionic-native/file-path';
import {Platform} from 'ionic-angular';

@Component({
  selector: 'page-contact',
  templateUrl: 'contact.html',
  providers: [FilePath, Transfer, TransferObject, File]

})
export class ContactPage {

 results: any;
 storageDirectory: string ='';

 constructor(public navCtrl: NavController, private filePath: FilePath, public platform: Platform, private transfer: Transfer, private file: File){

 this.platform.ready().then(() => {

       // code to create a new directory

       file.createDir(file.externalDataDirectory, 'newDir', true).then((result)=>{
    console.log("Directory newDir created" + result);

    // code to list the files and folder in the directory

       file.listDir(file.externalDataDirectory,'').then((result)=>{
    this.storageDirectory = file.externalDataDirectory;
    console.log("this.storageDirectory containnig "+ this.storageDirectory);
    console.log("listing taking place here" + file.externalDataDirectory);
         this.results=result;
     console.log("showing result content"+result);

 // code to print the name of files and folder on console as well as on device screen

 for(let file of result){
    if(file.isDirectory == true){
  console.log("Code if its a folder");
  let name=file.name;
  console.log("File name"+name);
 }
 else if(file.isFile == true){
  console.log("Code if its a file");
  let name=file.name;
  console.log("File name "+name);
  let path=this.storageDirectory+name;
  console.log(path);
    file.getMetadata(function (metadata) {
   let size=metadata.size;
   console.log("File size"+size);
      })
 }
 }

/*result will have an array of file objects with
file details or if its a directory:  */
    });
  });

});
 }
 }

Please check this my running code, may can help you to get the list of files and folders from the internal storage.


问:
Sorting in SQL Server
I am trying to sort a week column with the datatype varchar because the weeks are in this format 2017_6, 2017_7. As we all know SQL sorts varchar numbers like 2017_1, 2017_10, 2017_11 etc.

How can I get it to sort numerically, without changing the weeks format? I tried nvarchar but that didn't work.

答:
One simple way is to use the length:

```<code>order by len(weekcol), weekcol
</code>```

For multiple years:

```<code>order by left(weekcol, 4), len(weekcol), weekcol
</code>```

Title: Sorting in SQL Server

Body:
One simple way is to use the length:

order by len(weekcol), weekcol

For multiple years:

order by left(weekcol, 4), len(weekcol), weekcol


问:
Call to a member function tasks() on null on laravel 5
Let me explain with a couple of word my problem.
On my controller i have this line:

```<code>$tasks = $student->group->tasks()->orderBy('created_at', 'desc')->withPivot('id')->get();
</code>```

This works for existing users, but when i try to create new ones i receive

Call to a member function tasks() on null

Can i with something like this or what do you suggest ?

```<code>if(!is_null($tasks))
    $tasks = $student->group->tasks()->orderBy('created_at', 'desc')->withPivot('id')->get();
}
</code>```

This i my show function on controller

```<code>public function show(){
    $user = Auth::user();

    if(!$user)
        return redirect('/')->withErrors(config('constants.NA'));

    $countries = Country::all()->lists('name', 'id')->toArray();
    $profile = $user->profile;
  $student = $profile->student;

  // Tasks showed on students profile
  if ($student->group) {
      $tasks = $student->group->tasks()
          ->orderBy('created_at', 'desc')
          ->withPivot('id')
          ->get();
  }
  // Classmates
  if ($student->group) {
      $classmates = $student->group->students()
      ->where('id', '!=', $student->id)
      ->get();

  }

  // Activated books
  $books = Auth::user()->books()->orderBy('grade_id', 'asc')->get();

  if(!is_null($student->group))
    $iTasks = $student->group->tasks->count();
  else {
    $iTasks = 0;
  }

  $iTodos = $user->todos->count();

    return view('student.profile.show',compact('user','profile', 'countries', 'iTasks', 'iTodos', 'tasks', 'classmates', 'books'));
}
</code>```

This is my show view, for the tasks

```<code><div class="tab-pane <?php if(isset($tab) && $tab == 'timeline'): ?> active <?php endif; ?>" id="timeline">
                        @if($tasks->count())
                          <div class="timeline">
                            @foreach($tasks as $task)
                              <!-- TIMELINE ITEM -->
                              <div class="timeline-item">
                                <div class="timeline-badge">
                                  <div class="timeline-icon">
                                    <i class="mdi mdi-clipboard-text font-red-intense"></i>
                                  </div>
                                </div>
                                <div class="timeline-body">
                                  <div class="timeline-body-arrow"> </div>
                                  <div class="timeline-body-head">
                                    <div class="timeline-body-head-caption">
                                      <span class="timeline-body-title font-blue-madison">
                                        {{ $task->professor->profile->user->name }}
                                      </span>
                                      <span class="timeline-body-time font-grey-cascade">ju ca caktuar një <a href="/student/tasks" class="font-red sbold">detyrë</a> të re.</span>
                                    </div>
                                  </div>
                                  <div class="timeline-body-content">
                                    <span class="font-grey-cascade">
                                      {{ $task->pivot->comment }}
                                    </span>
                                  </div>
                                  <hr>
                                  Lenda: <span class="timeline-body-time font-grey-cascade sbold">{{ $task->subject->name }}</span>
                                  <div class="pull-right">
                                    Krijuar më: <span class="timeline-body-time font-grey-cascade sbold">{{ $task->created_at->format(Config::get('klasaime.date_format')) }}</span>
                                  </div>
                                </div>
                              </div>
                              <!-- END TIMELINE ITEM -->
                            @endforeach
                          </div>
                        @else
                          <div class="alert">
                            Ju nuk keni asnje detyrë të caktuar!
                          </div>
                        @endif
                      </div>
</code>```

答:
Looks to me like you haven't added the student to a group yet, or that somehow hasn't been persisted. If you have added the student to a group after creating and saving the student, try this:

```<code>$student->load('group')
</code>```

Before running:

```<code>$tasks = $student->group->tasks()->orderBy('created_at', 'desc')->withPivot('id')->get();
</code>```

I'll need to see more of your code to give a more accurate answer. But the error you're getting is related to the ->group, of your student, not your student itself.

Body:
Let me explain with a couple of word my problem.
On my controller i have this line:

$tasks = $student->group->tasks()->orderBy('created_at', 'desc')->withPivot('id')->get();

This works for existing users, but when i try to create new ones i receive

Call to a member function tasks() on null

Can i with something like this or what do you suggest ?

if(!is_null($tasks))
    $tasks = $student->group->tasks()->orderBy('created_at', 'desc')->withPivot('id')->get();
}

This i my show function on controller

public function show(){
    $user = Auth::user();

    if(!$user)
        return redirect('/')->withErrors(config('constants.NA'));

    $countries = Country::all()->lists('name', 'id')->toArray();
    $profile = $user->profile;
  $student = $profile->student;

  // Tasks showed on students profile
  if ($student->group) {
      $tasks = $student->group->tasks()
          ->orderBy('created_at', 'desc')
          ->withPivot('id')
          ->get();
  }
  // Classmates
  if ($student->group) {
      $classmates = $student->group->students()
      ->where('id', '!=', $student->id)
      ->get();

  }

  // Activated books
  $books = Auth::user()->books()->orderBy('grade_id', 'asc')->get();

  if(!is_null($student->group))
    $iTasks = $student->group->tasks->count();
  else {
    $iTasks = 0;
  }

  $iTodos = $user->todos->count();

    return view('student.profile.show',compact('user','profile', 'countries', 'iTasks', 'iTodos', 'tasks', 'classmates', 'books'));
}

This is my show view, for the tasks

<div class="tab-pane <?php if(isset($tab) && $tab == 'timeline'): ?> active <?php endif; ?>" id="timeline">
                        @if($tasks->count())

                            @foreach($tasks as $task)

                                        {{ $task->professor->profile->user->name }}

                                      ju ca caktuar një detyrë të re.

                                      {{ $task->pivot->comment }}

                                  Lenda: {{ $task->subject->name }}

                                    Krijuar më: {{ $task->created_at->format(Config::get('klasaime.date_format')) }}

                            @endforeach

                        @else

                            Ju nuk keni asnje detyrë të caktuar!

                        @endif

Body:
Looks to me like you haven't added the student to a group yet, or that somehow hasn't been persisted. If you have added the student to a group after creating and saving the student, try this:

$student->load('group')

Before running:

$tasks = $student->group->tasks()->orderBy('created_at', 'desc')->withPivot('id')->get();

I'll need to see more of your code to give a more accurate answer. But the error you're getting is related to the ->group, of your student, not your student itself.