问:
ReadAsync reads only once in async TcpClient
I wrote a simple async TcpClient. Here the relevant part of the code:

```<code>public class AsyncTcpClient : IDisposable
{
    private TcpClient tcpClient;
    private Stream stream;

    private int bufferSize = 8192;
    bool IsReceiving = false;

    public event EventHandler<string> OnDataReceived;
    public event EventHandler OnDisconnected;
    public event EventHandler OnConnected;
    public event EventHandler<Exception> OnError;

    public bool IsConnected
    {
        get
        {
            return tcpClient != null && tcpClient.Connected;
        }
    }

    public AsyncTcpClient() { }

    public async Task ConnectAsync(string host, int port, CancellationToken token = default(CancellationToken))
    {
        try
        {
            if (IsConnected) Close();
            tcpClient = new TcpClient();
            if (!tcpClient.ConnectAsync(host, port).Wait(250))
            {
                throw new TimeoutException();
            }
            stream = tcpClient.GetStream();
            OnConnected?.Invoke(this, EventArgs.Empty);
            await Receive();
        }
        catch (Exception)
        {
            OnDisconnected?.Invoke(this, EventArgs.Empty);
        }
    }

    public async Task Receive(CancellationToken token = default(CancellationToken))
    {
        try
        {
            if (!IsConnected || IsReceiving) throw new InvalidOperationException();
            IsReceiving = true;
            byte[] buffer = new byte[bufferSize];
            while (IsConnected)
            {
                token.ThrowIfCancellationRequested();

                // First time it reads the incoming data, then it hangs here forever
                int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, token);
                if (bytesRead > 0)
                {
                    byte[] data = new byte[bytesRead];
                    Array.Copy(buffer, data, bytesRead);
                    OnDataReceived?.Invoke(this, Encoding.ASCII.GetString(data));
                }
                buffer = new byte[bufferSize];
            }
        }
        catch (ObjectDisposedException) { }
        catch (IOException)
        {
            throw;
        }
        finally
        {
            IsReceiving = false;
        }
    }
}
</code>```

On another application I have a TcpListener that waits for connections.
After a successful connection, the server sends some data to the client. The data is received correcly from ReadAsync. Then if I try to send more data from the server, the client waits forever in the second call for ReadAsync.

I'm pretty sure the server is working because I receive the SendCallback with the correct bytes sent.

Am I using ReadAsync wrongly?

UPDATE

I add here the complete code of my server:

```<code>public class StateObject
{
    public Socket workSocket = null;
    public const int BufferSize = 4096;
    public byte[] buffer = new byte[BufferSize];
    public StringBuilder sb = new StringBuilder();
}

public class TcpServerAsync
{
    public readonly ConcurrentQueue<String> queue = new ConcurrentQueue<String>();
    public ManualResetEvent allDone = new ManualResetEvent(false);
    private Boolean _isRunning = true;

    public event EventHandler Connected;

    public TcpServerAsync(Int32 port)
    {
    }

    public void Start()
    {
        Thread t = new Thread(Run);
        t.Start();
    }

    public void Run()
    {
        IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");
        IPAddress ipAddress = ipHostInfo.AddressList[1];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 5000);
        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(1);

            while (_isRunning)
            {
                allDone.Reset();
                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
                allDone.WaitOne();
            }
        }
        catch (Exception e)
        {
            Debug.WriteLine(e.ToString());
        }
    }

    public void AcceptCallback(IAsyncResult ar)
    {
        allDone.Set();

        Connected.Invoke(this, new EventArgs());
        Socket listener = (Socket)ar.AsyncState;
        Socket handler = listener.EndAccept(ar);

        StateObject state = new StateObject
        {
            workSocket = handler
        };
        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);

        while (handler.Connected)
        {
            if (queue.TryDequeue(out String data))
            {
                try
                {
                    SendData(handler, data);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
            Thread.Sleep(0);
        }
    }

    public void ReadCallback(IAsyncResult ar)
    {
        String content = String.Empty;

        StateObject state = (StateObject)ar.AsyncState;
        Socket handler = state.workSocket;

        int bytesRead = handler.EndReceive(ar);

        if (bytesRead > 0)
        {
            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
            content = state.sb.ToString();
            Debug.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
        }
    }

    public void SendData(Socket handler, String data)
    {
        byte[] byteData = Encoding.ASCII.GetBytes(data);
        handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
    }

    private void SendCallback(IAsyncResult ar)
    {
        try
        {
            Socket handler = (Socket)ar.AsyncState;

            int bytesSent = handler.EndSend(ar);
            Debug.WriteLine("Sent {0} bytes to client.", bytesSent);
        }
        catch (Exception e)
        {
            Debug.WriteLine(e.ToString());
        }
    }
}
</code>```

答:
I reviewed your server code and I made some modifications. Firstly, there is a variable that named "queue". I didn't understand its purpose, because you aren't enqueuing it anywhere and you are trying to dequeue it within infinite while block in the BeginReceive method. That while statement blocks main thread and prevent to receive data from client, prevent accepting other clients and other operations that it should complete. If you enqueue it from somewhere and you want to send dequeued data to tcp client, you can do it after received completed and don't use infinite while loop for main thread. I provided modified methods like this;

```<code>    public void AcceptCallback(IAsyncResult ar)
    {
        allDone.Set();

        if (Connected != null)
        {
            Connected.Invoke(this, new EventArgs());
        }
        Socket listener = (Socket)ar.AsyncState;
        Socket handler = listener.EndAccept(ar);

        BeginReceive(handler);

        //while (handler.Connected)
        //{
        //    if (queue.TryDequeue(out String data))
        //    {
        //        try
        //        {
        //            SendData(handler, data);
        //        }
        //        catch (Exception ex)
        //        {
        //            throw;
        //        }
        //    }
        //    Thread.Sleep(0);
        //}
    }

    public void BeginReceive(Socket handler)
    {
        StateObject state = new StateObject
        {
            workSocket = handler
        };
        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
    }

    public void ReadCallback(IAsyncResult ar)
    {
        String content = String.Empty;

        StateObject state = (StateObject)ar.AsyncState;
        Socket handler = state.workSocket;

        int bytesRead = handler.EndReceive(ar);

        if (bytesRead > 0)
        {
            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
            content = state.sb.ToString();
            if (queue.TryDequeue(out String data))
            {
                try
                {
                    SendData(handler, data);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
            //SendData(handler, content);
            Debug.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
        }
        BeginReceive(handler);
    }
</code>```

Body:
I wrote a simple async TcpClient. Here the relevant part of the code:

public class AsyncTcpClient : IDisposable
{
    private TcpClient tcpClient;
    private Stream stream;

    private int bufferSize = 8192;
    bool IsReceiving = false;

    public event EventHandler<string> OnDataReceived;
    public event EventHandler OnDisconnected;
    public event EventHandler OnConnected;
    public event EventHandler<Exception> OnError;

    public bool IsConnected
    {
        get
        {
            return tcpClient != null && tcpClient.Connected;
        }
    }

    public AsyncTcpClient() { }

    public async Task ConnectAsync(string host, int port, CancellationToken token = default(CancellationToken))
    {
        try
        {
            if (IsConnected) Close();
            tcpClient = new TcpClient();
            if (!tcpClient.ConnectAsync(host, port).Wait(250))
            {
                throw new TimeoutException();
            }
            stream = tcpClient.GetStream();
            OnConnected?.Invoke(this, EventArgs.Empty);
            await Receive();
        }
        catch (Exception)
        {
            OnDisconnected?.Invoke(this, EventArgs.Empty);
        }
    }

    public async Task Receive(CancellationToken token = default(CancellationToken))
    {
        try
        {
            if (!IsConnected || IsReceiving) throw new InvalidOperationException();
            IsReceiving = true;
            byte[] buffer = new byte[bufferSize];
            while (IsConnected)
            {
                token.ThrowIfCancellationRequested();

                // First time it reads the incoming data, then it hangs here forever
                int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, token);
                if (bytesRead > 0)
                {
                    byte[] data = new byte[bytesRead];
                    Array.Copy(buffer, data, bytesRead);
                    OnDataReceived?.Invoke(this, Encoding.ASCII.GetString(data));
                }
                buffer = new byte[bufferSize];
            }
        }
        catch (ObjectDisposedException) { }
        catch (IOException)
        {
            throw;
        }
        finally
        {
            IsReceiving = false;
        }
    }
}

On another application I have a TcpListener that waits for connections.
After a successful connection, the server sends some data to the client. The data is received correcly from ReadAsync. Then if I try to send more data from the server, the client waits forever in the second call for ReadAsync.

I'm pretty sure the server is working because I receive the SendCallback with the correct bytes sent.

Am I using ReadAsync wrongly?

UPDATE

I add here the complete code of my server:

public class StateObject
{
    public Socket workSocket = null;
    public const int BufferSize = 4096;
    public byte[] buffer = new byte[BufferSize];
    public StringBuilder sb = new StringBuilder();
}

public class TcpServerAsync
{
    public readonly ConcurrentQueue<String> queue = new ConcurrentQueue<String>();
    public ManualResetEvent allDone = new ManualResetEvent(false);
    private Boolean _isRunning = true;

    public event EventHandler Connected;

    public TcpServerAsync(Int32 port)
    {
    }

    public void Start()
    {
        Thread t = new Thread(Run);
        t.Start();
    }

    public void Run()
    {
        IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");
        IPAddress ipAddress = ipHostInfo.AddressList[1];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 5000);
        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(1);

            while (_isRunning)
            {
                allDone.Reset();
                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
                allDone.WaitOne();
            }
        }
        catch (Exception e)
        {
            Debug.WriteLine(e.ToString());
        }
    }

    public void AcceptCallback(IAsyncResult ar)
    {
        allDone.Set();

        Connected.Invoke(this, new EventArgs());
        Socket listener = (Socket)ar.AsyncState;
        Socket handler = listener.EndAccept(ar);

        StateObject state = new StateObject
        {
            workSocket = handler
        };
        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);

        while (handler.Connected)
        {
            if (queue.TryDequeue(out String data))
            {
                try
                {
                    SendData(handler, data);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
            Thread.Sleep(0);
        }
    }

    public void ReadCallback(IAsyncResult ar)
    {
        String content = String.Empty;

        StateObject state = (StateObject)ar.AsyncState;
        Socket handler = state.workSocket;

        int bytesRead = handler.EndReceive(ar);

        if (bytesRead > 0)
        {
            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
            content = state.sb.ToString();
            Debug.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
        }
    }

    public void SendData(Socket handler, String data)
    {
        byte[] byteData = Encoding.ASCII.GetBytes(data);
        handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
    }

    private void SendCallback(IAsyncResult ar)
    {
        try
        {
            Socket handler = (Socket)ar.AsyncState;

            int bytesSent = handler.EndSend(ar);
            Debug.WriteLine("Sent {0} bytes to client.", bytesSent);
        }
        catch (Exception e)
        {
            Debug.WriteLine(e.ToString());
        }
    }
}

Body:
I reviewed your server code and I made some modifications. Firstly, there is a variable that named "queue". I didn't understand its purpose, because you aren't enqueuing it anywhere and you are trying to dequeue it within infinite while block in the BeginReceive method. That while statement blocks main thread and prevent to receive data from client, prevent accepting other clients and other operations that it should complete. If you enqueue it from somewhere and you want to send dequeued data to tcp client, you can do it after received completed and don't use infinite while loop for main thread. I provided modified methods like this;

    public void AcceptCallback(IAsyncResult ar)
    {
        allDone.Set();

        if (Connected != null)
        {
            Connected.Invoke(this, new EventArgs());
        }
        Socket listener = (Socket)ar.AsyncState;
        Socket handler = listener.EndAccept(ar);

        BeginReceive(handler);

        //while (handler.Connected)
        //{
        //    if (queue.TryDequeue(out String data))
        //    {
        //        try
        //        {
        //            SendData(handler, data);
        //        }
        //        catch (Exception ex)
        //        {
        //            throw;
        //        }
        //    }
        //    Thread.Sleep(0);
        //}
    }

    public void BeginReceive(Socket handler)
    {
        StateObject state = new StateObject
        {
            workSocket = handler
        };
        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
    }

    public void ReadCallback(IAsyncResult ar)
    {
        String content = String.Empty;

        StateObject state = (StateObject)ar.AsyncState;
        Socket handler = state.workSocket;

        int bytesRead = handler.EndReceive(ar);

        if (bytesRead > 0)
        {
            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
            content = state.sb.ToString();
            if (queue.TryDequeue(out String data))
            {
                try
                {
                    SendData(handler, data);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
            //SendData(handler, content);
            Debug.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
        }
        BeginReceive(handler);
    }


来源: stackexchange

问:
jCarousel Next Button Doesn't Work Unless Inspected by Developer Tool
I did a clean jCarousel setup, meaning I didn't use the provided stylesheet or any of the skins and styled it from scratch. But the Next button isn't working. The weird thing is that it does work after I inspect it with FireBug or the built-in element inspector on Chrome. I assume it has something to do with the element being in focus, but I don't know how to fix the problem. I tried modifying the z-indexes of the elements but to no avail. Any ideas as to what's going on here? Thanks!

答:
Perhaps you left some

```<code>console.log(...)
</code>```

in your code. Try removing those

ContentLicense: CC BY-SA 2.5

Body:
Perhaps you left some

console.log(...)

in your code. Try removing those


问:
JSON do not add the last comma
I have the script:

```<code><script type="application/ld+json">
            {
              "@context": "http://schema.org",
              "@type": "Product",
              "aggregateRating": {
                "@type": "AggregateRating",

                "ratingValue": "<?php echo $rating;?>",

              "reviewCount": "<?php echo $review_total; ?>"
              },

              "description": "<?php echo $description; ?>",

              "name": "<?php echo $heading_title; ?>",

              "image": "<?php echo $thumb; ?>",
              "review": [
                <?php foreach($reviewss as $review) {  ?>
                {
                  "@type": "Review",
                  "author": "<?php echo $review['author'];?>",
                  "datePublished": "<?php echo $review['date_added'];?>",
                  "description": "<?php echo $review['text'];?>",
                  "name": "<?php echo $review['author'];?>",
                  "reviewRating": {
                    "@type": "Rating",
                    "bestRating": "5",
                    "ratingValue": "<?php echo $review['rating'];?>",
                    "worstRating": "1"
                    }

                    }
                <?php } ?>
                ]

            }
        </script>
</code>```

It working fine if I have only one review.
If I have several reviews I need add the commas after each piece of this:

```<code>{
                  "@type": "Review",
                  "author": "<?php echo $review['author'];?>",
                  "datePublished": "<?php echo $review['date_added'];?>",
                  "description": "<?php echo $review['text'];?>",
                  "name": "<?php echo $review['author'];?>",
                  "reviewRating": {
                    "@type": "Rating",
                    "bestRating": "5",
                    "ratingValue": "<?php echo $review['rating'];?>",
                    "worstRating": "1"
                    }

                    },
</code>```

But after the last value, comma should be removed.
Can anybody help? How to remove the last comma?

答:
Instead of generating json yourself you should use json_encode()

Sorry it took so long, had to dissect your json.

```<code><?php
// your arbitrary vars
$rating = 1;
$review_total = 100;
$description = 'How do I not break json';
$heading_title = 'As above...';
$thumb = 'http://.../thumb.jpg';

$json = [
    '@context' => 'http://schema.org',
    '@type' => 'Product',
    'aggregateRating' => [
        [
            '@type' => 'AggregateRating',
            'ratingValue' => $rating,
            'reviewCount' => $review_total,
        ]
    ],
    'description' => $description,
    'name' => $heading_title,
    'image' => $thumb,
    'review' => [],
];

// query reviews from db
$reviews = [
    [
        'author' => 'Lawrence Cherone',
        'date_added' => '11/11/17 00:00:00',
        'text' => 'You should instead use json_encode',
        'rating' => 1
    ],
];

foreach ($reviews as $review) {
    $json['review'][] = [
        '@type' => 'Review',
        'author' => $review['author'],
        'datePublished' => $review['date_added'],
        'description' => '',
        'name' => $review['author'],
        'reviewRating' => [
            '@type' => 'Rating',
            'bestRating' => 5,
            'ratingValue' => $review['rating'],
            'worstRating' => 1
        ]
    ];
}
?>

<script type="application/ld+json">
<?= json_encode($json, JSON_PRETTY_PRINT) ?>
</script>
</code>```

Result will be perfect valid json.

```<code><script type="application/ld+json">
{
    "@context": "http:\/\/schema.org",
    "@type": "Product",
    "aggregateRating": [
        {
            "@type": "AggregateRating",
            "ratingValue": 1,
            "reviewCount": 100
        }
    ],
    "description": "How do I not break json",
    "name": "As above...",
    "image": "http:\/\/...\/thumb.jpg",
    "review": [
        {
            "@type": "Review",
            "author": "Lawrence Cherone",
            "datePublished": "11\/11\/17 00:00:00",
            "description": "",
            "name": "Lawrence Cherone",
            "reviewRating": {
                "@type": "Rating",
                "bestRating": "5",
                "ratingValue": 1,
                "worstRating": "1"
            }
        }
    ]
}</script>
</code>```

https://3v4l.org/u0Fd3

ContentLicense: CC BY-SA 3.0

Title: JSON do not add the last comma

Body:
I have the script:

It working fine if I have only one review.
If I have several reviews I need add the commas after each piece of this:

{
                  "@type": "Review",
                  "author": "<?php echo $review['author'];?>",
                  "datePublished": "<?php echo $review['date_added'];?>",
                  "description": "<?php echo $review['text'];?>",
                  "name": "<?php echo $review['author'];?>",
                  "reviewRating": {
                    "@type": "Rating",
                    "bestRating": "5",
                    "ratingValue": "<?php echo $review['rating'];?>",
                    "worstRating": "1"
                    }

                    },

But after the last value, comma should be removed.
Can anybody help? How to remove the last comma?

Body:
Instead of generating json yourself you should use json_encode()

Sorry it took so long, had to dissect your json.

<?php
// your arbitrary vars
$rating = 1;
$review_total = 100;
$description = 'How do I not break json';
$heading_title = 'As above...';
$thumb = 'http://.../thumb.jpg';

$json = [
    '@context' => 'http://schema.org',
    '@type' => 'Product',
    'aggregateRating' => [
        [
            '@type' => 'AggregateRating',
            'ratingValue' => $rating,
            'reviewCount' => $review_total,
        ]
    ],
    'description' => $description,
    'name' => $heading_title,
    'image' => $thumb,
    'review' => [],
];

// query reviews from db
$reviews = [
    [
        'author' => 'Lawrence Cherone',
        'date_added' => '11/11/17 00:00:00',
        'text' => 'You should instead use json_encode',
        'rating' => 1
    ],
];

foreach ($reviews as $review) {
    $json['review'][] = [
        '@type' => 'Review',
        'author' => $review['author'],
        'datePublished' => $review['date_added'],
        'description' => '',
        'name' => $review['author'],
        'reviewRating' => [
            '@type' => 'Rating',
            'bestRating' => 5,
            'ratingValue' => $review['rating'],
            'worstRating' => 1
        ]
    ];
}
?>

<script type="application/ld+json">
<?= json_encode($json, JSON_PRETTY_PRINT) ?>
</script>

Result will be perfect valid json.

<script type="application/ld+json">
{
    "@context": "http:\/\/schema.org",
    "@type": "Product",
    "aggregateRating": [
        {
            "@type": "AggregateRating",
            "ratingValue": 1,
            "reviewCount": 100
        }
    ],
    "description": "How do I not break json",
    "name": "As above...",
    "image": "http:\/\/...\/thumb.jpg",
    "review": [
        {
            "@type": "Review",
            "author": "Lawrence Cherone",
            "datePublished": "11\/11\/17 00:00:00",
            "description": "",
            "name": "Lawrence Cherone",
            "reviewRating": {
                "@type": "Rating",
                "bestRating": "5",
                "ratingValue": 1,
                "worstRating": "1"
            }
        }
    ]
}</script>

https://3v4l.org/u0Fd3


问:
React-Navigation: Route should declare a screen... error
I am new to react-navigation and I followed the steps on the site, however I get an error saying Route 'Chat' should declare a screen... Below is my code for reference.

```<code>import React from 'react';
import {
  AppRegistry,
  Text,
  View,
  Button,
} from 'react-native';
import { StackNavigator } from 'react-navigation';

class HomeScreen extends React.Component {
  static navigationOptions = {
    title: 'Welcome',
  };
  render() {
    const { navigate } = this.props.navigation;
    return (
      <View>
        <Text>Hello, Chat App!</Text>
        <Button
          onPress={() => navigate('Chat')}
          title="Chat with Lucy"
        />
      </View>
    );
  }
}

AppRegistry.registerComponent('navigationApp', () => navigationApp);
</code>```

This is where I believe the error is occurring

```<code>const navigationApp = StackNavigator({
  Home: { screen: HomeScreen },
  Chat: { screen: ChatScreen },
});

class ChatScreen extends React.Component {
  static navigationOptions = {
    title: 'Chat with Lucy',
  };
  render() {
    return (
      <View>
        <Text>Chat with Lucy</Text>
      </View>
    );
  }
}
</code>```

答:
If you have an index.js for your component or directory, don't forget to add the export there too! (Not that I've ever done that....)

A good article about organizing a project is and the use of index.js: Organizing a React Native Project on Medium

Body:
I am new to react-navigation and I followed the steps on the site, however I get an error saying Route 'Chat' should declare a screen... Below is my code for reference.

import React from 'react';
import {
  AppRegistry,
  Text,
  View,
  Button,
} from 'react-native';
import { StackNavigator } from 'react-navigation';

class HomeScreen extends React.Component {
  static navigationOptions = {
    title: 'Welcome',
  };
  render() {
    const { navigate } = this.props.navigation;
    return (
      <View>
        <Text>Hello, Chat App!</Text>
        <Button
          onPress={() => navigate('Chat')}
          title="Chat with Lucy"
        />
      </View>
    );
  }
}

AppRegistry.registerComponent('navigationApp', () => navigationApp);

This is where I believe the error is occurring

const navigationApp = StackNavigator({
  Home: { screen: HomeScreen },
  Chat: { screen: ChatScreen },
});

class ChatScreen extends React.Component {
  static navigationOptions = {
    title: 'Chat with Lucy',
  };
  render() {
    return (
      <View>
        <Text>Chat with Lucy</Text>
      </View>
    );
  }
}


问:
PDO_ODBC accessing IBM DB2 tables with special characters in the table names
I'm working on a DB2 table on as/400. I'm trying to run a basic query against it but the table name contains a . in it. For example: my.table is the table name.

The problem is that PDO believes that I'm specifying a database name my with my table name table. Hence the prepared statement is failing and saying no such table table exists in database my. Changing the table name is not an option.

What is the best way to handle a period in the table name? I've tried escaping the period but haven't had any success.

Here's some example code of my problem:

```<code>$sql= "select * from '[THE.TABLE]'";
        try {
            $statement = $this->db->query($sql);
            $results = $statement->execute();
            foreach ($results as $result) {
                print_r($result);
            }
            exit;
        }
        catch (\Exception $e)
        {
            //log issue and other stuff
        }
</code>```

The application is running in Zend Framework 2.

答: I stand corrected. As aynber mentioned in a comment, the solution was to use double quotes escaped correctly. The answer could be found in the question directed towards MySQL.</p>

Body:
I'm working on a DB2 table on as/400. I'm trying to run a basic query against it but the table name contains a . in it. For example: my.table is the table name.

The problem is that PDO believes that I'm specifying a database name my with my table name table. Hence the prepared statement is failing and saying no such table table exists in database my. Changing the table name is not an option.

What is the best way to handle a period in the table name? I've tried escaping the period but haven't had any success.

Here's some example code of my problem:

$sql= "select * from '[THE.TABLE]'";
        try {
            $statement = $this->db->query($sql);
            $results = $statement->execute();
            foreach ($results as $result) {
                print_r($result);
            }
            exit;
        }
        catch (\Exception $e)
        {
            //log issue and other stuff
        }

The application is running in Zend Framework 2.


问:
Does Azure WebJob look at the app.config once deployed
I have a Web site running on Azure App Services. It has a WebJob that deploys with it, and thus gets put in it's App_data folder once deployed.

If I FTP to the wwwroot/app_data folder of my site once deployed, the app.config file has none of the configured settings that I set up in the "Application Settings Blade" in the Azure portal. The settings are changed in my web.config for the Website though.

The most curious thing is that when I run the WebJob, the log output indicates that the correct settings are being used!!

So as per my title, does the WebJob use the App.Settings file once deployed or does it use some kind of in-memory copy of the app-settings from the azure portal, or does it use what is in the web.config of the website?

Just to pre-emt a possible question, I know that the app.settings gets renamed to myappname.exe.config

答:
David Ebbo answer is perfectly right.

Just wanted to state that you can also run web jobs in place by a using a parameter in settings.job:

```<code>{
    "is_in_place": true
}
</code>```

Details can be found in Kudu docs:

https://github.com/projectkudu/kudu/wiki/WebJobs#webjob-working-directory

Body:
David Ebbo answer is perfectly right.

Just wanted to state that you can also run web jobs in place by a using a parameter in settings.job:

{
    "is_in_place": true
}

Details can be found in Kudu docs:

https://github.com/projectkudu/kudu/wiki/WebJobs#webjob-working-directory


问:
.htaccess rewriting URLs that don't exist
Currently, I'm working with some guys that love short URLs for marketing purposes when posting to social media.

They have https://www.example.com/folder/subfolder

For their marketing, they would like https://www.example.com/mysuperbuzzword which would point to the first URL but in the browser, you would still see the shorter URL.

My first thought was "I'll just add a rewrite rule in the .htaccess"

Something like Redirect 301 /mysuperbuzzword /folder/subfolder/ which would work but then the URL changes.

I did some reading and discovered the [P] flag. Then I tried this:

RewriteCond %{REQUEST_URI} ^/vanityurl
 RewriteRule ^(.*)$ /folder/subfolder [P]

The issue I have now is that because /vanityurl doesn't exist, instead of rewriting, I just get a 404 error.

I've been testing my rule using a .htaccess rule checking tool and the URL it spits out looks correct, but again, I just get a 404.

Also, if you use the flag [PT] the resource is found but the URL is changed in the address bar.

答:
You tested with a permanent redirect. Never do that. It is cached by the browser, and the browser will no longer do requests to the server. This is possible, because such a redirect is supposed to be... well... permanent. If you must test redirects, test them with a temporary redirect (302) and change them later if everything turns out to be fine.

With mod_rewrite you can do three things:

Do an internal rewrite. If you internally rewrite url a to url b, then the user sees url a, but url b is being executed on the server.

Do an external redirect. If you externally redirect url a to url b you send back a response: "Please request url b instead.". The browser then sends another request to the server with url b and changes the url in the address bar accordingly.

Do a proxy request. If you proxy url a to url b, the user requests url a. The server then opens a http connection and requests url b. It then waits for the response and channels that back to the client. It is very expensive to do such a thing via mod_rewrite.

What you simply want to do is:

```<code>RewriteRule ^vanityurl$ /folder/subfolder [L]
</code>```

It as a simple internal rewrite.

Body:
You tested with a permanent redirect. Never do that. It is cached by the browser, and the browser will no longer do requests to the server. This is possible, because such a redirect is supposed to be... well... permanent. If you must test redirects, test them with a temporary redirect (302) and change them later if everything turns out to be fine.

With mod_rewrite you can do three things:

Do an internal rewrite. If you internally rewrite url a to url b, then the user sees url a, but url b is being executed on the server.

Do an external redirect. If you externally redirect url a to url b you send back a response: "Please request url b instead.". The browser then sends another request to the server with url b and changes the url in the address bar accordingly.

Do a proxy request. If you proxy url a to url b, the user requests url a. The server then opens a http connection and requests url b. It then waits for the response and channels that back to the client. It is very expensive to do such a thing via mod_rewrite.

What you simply want to do is:

RewriteRule ^vanityurl$ /folder/subfolder [L]

It as a simple internal rewrite.


问:
Failed to read file attributes for Images.xcassets in Xcode 9
I have old project that is running in Xcode 8 fine but when i am trying to run the project in Xcode 9 beta version I am getting the error

Failed to read file attributes for Images.xcassets

答:
It fixes for me by update to latest Cocoapods:</p>

```<code>sudo gem install cocoapods --pre
</code>```

Body:
It fixes for me by update to latest Cocoapods:

sudo gem install cocoapods --pre


问:
How can I set up a reverse DNS for a private subnet using route 53?
I have websites running in a private subnet that communicates to the outside world using NAT.

Our mails are going straight to spam folder, even though AWS has unlocked our full account.

How do you create a reverse dns for our website using route 53?  Do we have to use the nat ip address?

Thanks!

Edit: What goes into "Name", "Type", "Alias", "TTLS", and "Value"?

答:
Yes, you would use the EIP of the NAT Gateway.

However, that is probably not going to be enough. There are a number of reasons that email servers decide that email is SPAM.

This AWS document will help you understand the processes and solutions. This document is for Amazon SES but the principles are the same.

Amazon SES and Deliverability


问:
Compress Block Blob that is already uploaded
I'm working on a project that requires my Block Blob to be copied to another directory inside the same container (directory File to Arquive).

I'm using the method MoveBlobInSameStorageAccount, suggested here https://social.msdn.microsoft.com/Forums/sqlserver/en-US/310a7a6e-efb8-4aef-ba26-7c543fccd443/ssis-script-task-could-not-load-file-or-assembly-microsoftwindowsazurestorage-version5000?forum=sqlintegrationservices.

Is it possible to compress the file to a gZip compressed file without having to download it?

I really appreciate any help!

答:
Azure blobs are not compatible with normal file I/O: You'd need to download the blob locally (stream, file, etc), process it (gzip, in your case), and upload it again. You don't need to download to a local machine; you can download to a VM or any other Azure service where you're running your processing (and if within the same region, you won't have any bandwidth costs).

If you're using Azure Files, then you can use normal File I/O, but an Azure File store cannot be used with regular block blobs.


问:
Generate random tint colors
at the moment I have this code to generate a random color:

```<code>let color = Math.floor(Math.random() * 16777216).toString(16);
color = '#000000'.slice(0, -color.length) + color;
department.color = color;
</code>```

but what I want is to genertae a random "tint" color , what should I add/change to make it work...?

答:
If you can just use hsl() for your colors, that will be the easiest. You can just set your hue to a random value and set your saturation and lightness constant (or a small range).

If you need rgb strings, you can use the standard HSL->RGB conversion found here and elsewhere to make the rgb string.

let [sat, lightness] = [.6, .8]
let container = document.getElementById("colors")
for (let i = 0; i < 12; i++) {
  let hue = Math.random()
  let block = document.createElement('div');
  block.className = 'colorbrick';
  block.style.backgroundColor = hslToRgb(hue, sat,lightness);
  container.appendChild(block)
}

function hslToRgb(h, s, l) {
  let r, g, b;
  if (s == 0) {
    r = g = b = l;
  } else {
    function hue2rgb(p, q, t) {
      if (t < 0) t += 1;
      if (t > 1) t -= 1;
      if (t < 1 / 6) return p + (q - p) * 6 * t;
      if (t < 1 / 2) return q;
      if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
      return p;
    }
    var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
    var p = 2 * l - q;
    r = hue2rgb(p, q, h + 1 / 3);
    g = hue2rgb(p, q, h);
    b = hue2rgb(p, q, h - 1 / 3);
  }
  return "#" + [r * 255, g * 255, b * 255].map(c => Math.floor(c).toString(16)).join('');
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.colorbrick {
  display: inline-block;
  width: 80px;
  height: 80px;
  margin: 6px;
}</code>```

```

Title: Generate random tint colors

Body:
at the moment I have this code to generate a random color:

let color = Math.floor(Math.random() * 16777216).toString(16);
color = '#000000'.slice(0, -color.length) + color;
department.color = color;

but what I want is to genertae a random "tint" color , what should I add/change to make it work...?

Body:
If you can just use hsl() for your colors, that will be the easiest. You can just set your hue to a random value and set your saturation and lightness constant (or a small range).

If you need rgb strings, you can use the standard HSL->RGB conversion found here and elsewhere to make the rgb string.

let [sat, lightness] = [.6, .8]
let container = document.getElementById("colors")
for (let i = 0; i < 12; i++) {
  let hue = Math.random()
  let block = document.createElement('div');
  block.className = 'colorbrick';
  block.style.backgroundColor = hslToRgb(hue, sat,lightness);
  container.appendChild(block)
}

function hslToRgb(h, s, l) {
  let r, g, b;
  if (s == 0) {
    r = g = b = l;
  } else {
    function hue2rgb(p, q, t) {
      if (t < 0) t += 1;
      if (t > 1) t -= 1;
      if (t < 1 / 6) return p + (q - p) * 6 * t;
      if (t < 1 / 2) return q;
      if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
      return p;
    }
    var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
    var p = 2 * l - q;
    r = hue2rgb(p, q, h + 1 / 3);
    g = hue2rgb(p, q, h);
    b = hue2rgb(p, q, h - 1 / 3);
  }
  return "#" + [r * 255, g * 255, b * 255].map(c => Math.floor(c).toString(16)).join('');
};

.colorbrick {
  display: inline-block;
  width: 80px;
  height: 80px;
  margin: 6px;
}

<div id="colors">
</div>


问:
tips on creating a component library for angular/react components
I'm trying to head up a potential project at work that would require our company to use components for our projects so that our products will have universal look/functionality to our brand. The main caveat is how do I manage this in such a way that updates/changes to components in the library automatically apply to all projects using them? Any basic tips on this would be very appreciated.</p>

答: Automatically is a strong word. The best way to go about creating a shared component library is to use NPM or even setup a private NPM repository at your company. Then any consumer of your library can just npm install like any other dependency and update whenever they want


问:
Slow T-SQL trigger
I have 2 tables "Vector" and "VectorElement". A vector has many elements so there is a foreign key relation between Vector and VectorElement with a cascaded delete.

Vector has a field VectorSize that contains the number the number of related records in VectorElement.

Obviously this field is redundant but it optimizes performance and keeps our queries simple as we are oftyen interested in the number of elements in a vector.

There is a trigger on VectorElement that updates the VectorSize field in Vector. This trigger works but gets very slow when many Vector records are deleted or inserted in one transaction.

When the Vectors get deleted, the cascaded delete deletes the VectorElements after which the trigger fires. Now the trigger does update the to-be-deleted Vector record which could cause some trouble but this also happens with inserts.

Here is the trigger:

```<code>CREATE TRIGGER [TFact].[AfterDeleteInsertVectorElement]
   ON  [TFact].[VectorElement]
   AFTER DELETE, INSERT
AS
BEGIN
    SET NOCOUNT ON;

  WITH cteChangedVectors AS
  (
      SELECT DISTINCT i.VectorId
      FROM inserted i
      UNION
      SELECT DISTINCT i.VectorId
      FROM deleted i
  )

    UPDATE
        TFact.Vector
    SET
        VectorSize = x.size
    FROM
        Vector v
    JOIN
        (SELECT VectorId, COUNT(*) as size FROM TFact.VectorElement GROUP BY VectorId) x
        ON v.Id = x.VectorId
    JOIN cteChangedVectors chg ON chg.VectorId = v.Id

END
</code>```

答:
Try tracking the total number of VectorElements using an indexed view.

See http://technet.microsoft.com/en-us/library/cc917715.aspx#XSLTsection124121120120

SQL Server knows how to track aggregates efficiently - that's cheaper than starting a piece of general purpose procedural code with every trigger call.

If you are on the SQL Server Enterprise, just create the view and your queries will be dynamically rewritten to use them.

Something like...

```<code>CREATE VIEW VectorSize AS
SELECT VectorId, COUNT(*)
FROM Vector NATURAL JOIN VectorElement
GROUP BY VectorId
GO
CREATE UNIQUE CLUSTERED INDEX VectorSizeInd ON VectorSize( VectorId )
</code>```

SQL Server will then keep an automatically updated "hard-copy" of the vector sizes in the database.

Title: Slow T-SQL trigger

Body:
I have 2 tables "Vector" and "VectorElement". A vector has many elements so there is a foreign key relation between Vector and VectorElement with a cascaded delete.

Vector has a field VectorSize that contains the number the number of related records in VectorElement.

Obviously this field is redundant but it optimizes performance and keeps our queries simple as we are oftyen interested in the number of elements in a vector.

There is a trigger on VectorElement that updates the VectorSize field in Vector. This trigger works but gets very slow when many Vector records are deleted or inserted in one transaction.

When the Vectors get deleted, the cascaded delete deletes the VectorElements after which the trigger fires. Now the trigger does update the to-be-deleted Vector record which could cause some trouble but this also happens with inserts.

Here is the trigger:

CREATE TRIGGER [TFact].[AfterDeleteInsertVectorElement]
   ON  [TFact].[VectorElement]
   AFTER DELETE, INSERT
AS
BEGIN
    SET NOCOUNT ON;

  WITH cteChangedVectors AS
  (
      SELECT DISTINCT i.VectorId
      FROM inserted i
      UNION
      SELECT DISTINCT i.VectorId
      FROM deleted i
  )

    UPDATE
        TFact.Vector
    SET
        VectorSize = x.size
    FROM
        Vector v
    JOIN
        (SELECT VectorId, COUNT(*) as size FROM TFact.VectorElement GROUP BY VectorId) x
        ON v.Id = x.VectorId
    JOIN cteChangedVectors chg ON chg.VectorId = v.Id

END

Body:
Try tracking the total number of VectorElements using an indexed view.

See http://technet.microsoft.com/en-us/library/cc917715.aspx#XSLTsection124121120120

SQL Server knows how to track aggregates efficiently - that's cheaper than starting a piece of general purpose procedural code with every trigger call.

If you are on the SQL Server Enterprise, just create the view and your queries will be dynamically rewritten to use them.

Something like...

CREATE VIEW VectorSize AS
SELECT VectorId, COUNT(*)
FROM Vector NATURAL JOIN VectorElement
GROUP BY VectorId
GO
CREATE UNIQUE CLUSTERED INDEX VectorSizeInd ON VectorSize( VectorId )

SQL Server will then keep an automatically updated "hard-copy" of the vector sizes in the database.


问:
Disable warning for "unused property" only for specific functions/variables?
Original Question:

I have some JavaScript functions that are only referenced from outside of my project. Is there any way to tell WebStorm not to warn on those but still warn on others? Perhaps with JSDoc or similar syntax?

Example:

```<code>function externallyCalled() {
    //this should not show a warning if not used
}

function internalFunction() {
   //this should show a warning if it's not used
}
</code>```

Is this possible?

edit:

Based on Vipin's answer, // noinspection JSUnusedGlobalSymbols works outside of a closure but not inside:

I have opened https://youtrack.jetbrains.com/issue/WI-39066 and accepted @Vipin's answer.

答:
You can add // noinspection JSUnusedGlobalSymbols where you want to suppress the warning like below

```<code>// noinspection JSUnusedGlobalSymbols
function externallyCalled() {
    //this should not show a warning if not used
}

// noinspection JSUnusedGlobalSymbols
function internalFunction() {
    //this should show a warning if it's not used
}
</code>```

Quick Fix Menu

Edited:

For closure, one way is to add // noinspection JSUnusedGlobalSymbols on top of return like below

```<code>var app = (function () {
    // noinspection JSUnusedGlobalSymbols
    return {
        externallyCalled: function () {
            //this should not show a warning if not used
        },
        internalFunction: function () {
            //this should show a warning if it's not used
        }
    }
})();
</code>```

This will disable the warnings on all the public properties/methods of returned object.

Body:
Original Question:

I have some JavaScript functions that are only referenced from outside of my project. Is there any way to tell WebStorm not to warn on those but still warn on others? Perhaps with JSDoc or similar syntax?

Example:

function externallyCalled() {
    //this should not show a warning if not used
}

function internalFunction() {
   //this should show a warning if it's not used
}

Is this possible?

edit:

Based on Vipin's answer, // noinspection JSUnusedGlobalSymbols works outside of a closure but not inside:

I have opened https://youtrack.jetbrains.com/issue/WI-39066 and accepted @Vipin's answer.

Body:
You can add // noinspection JSUnusedGlobalSymbols where you want to suppress the warning like below

// noinspection JSUnusedGlobalSymbols
function externallyCalled() {
    //this should not show a warning if not used
}

// noinspection JSUnusedGlobalSymbols
function internalFunction() {
    //this should show a warning if it's not used
}

Quick Fix Menu

Edited:

For closure, one way is to add // noinspection JSUnusedGlobalSymbols on top of return like below

var app = (function () {
    // noinspection JSUnusedGlobalSymbols
    return {
        externallyCalled: function () {
            //this should not show a warning if not used
        },
        internalFunction: function () {
            //this should show a warning if it's not used
        }
    }
})();

This will disable the warnings on all the public properties/methods of returned object.


问:
getSupportActionBar() on a null object reference?
The following are a part of my project. The error is on the line getSupportActionBar().setDisplayHomeAsUpEnabled(true);. I checked for any theme mismatch but there were no theme mismatch to my knowledge, the activity extends 'appcompatActivity' and i used the 'getSupportActionBar()' but still getting the nullpointer exception (Error posted Below)..

Home_Activity.java

```<code>import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;

public class Home_Activity extends AppCompatActivity {

DrawerLayout drawerLayout;
ActionBarDrawerToggle mToggle;
android.support.v4.app.FragmentTransaction fragmentTransaction;
Toolbar mToolbar;
NavigationView navigationView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.nav_page);

    mToolbar = findViewById(R.id.toolbar_cust);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); //ERROR
}
</code>```

nav_page.xml

```<code><android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<RelativeLayout
    android:id="@+id/relative_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <include
        android:id="@+id/inc"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        layout="@layout/toolbar_layout"
        />
    <FrameLayout
        android:id="@+id/maincontainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/inc">
    </FrameLayout>

</RelativeLayout>
<!-- The navigation drawer -->
<android.support.design.widget.NavigationView
    android:id="@+id/navigation"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:menu="@menu/menu_list_items"
    app:headerLayout="@layout/navigation_header"
    android:background="#ffffff">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
</code>```

Gradle dependencies

```<code>dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support:design:26.1.0'
}
</code>```

styles.xml

```<code><resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

</resources>
</code>```

ERROR

```<code>FATAL EXCEPTION: main
                                                                 Process: com.app.ce.cybereye, PID: 30688
                                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.ce.cybereye/com.app.ce.cybereye.Home_Activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2696)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2757)
                                                                     at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                     at android.os.Looper.loop(Looper.java:163)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:6237)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
                                                                     at com.app.ce.cybereye.Home_Activity.onCreate(Home_Activity.java:30)
                                                                     at android.app.Activity.performCreate(Activity.java:6847)
                                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2649)
</code>```

Hope i am clear enough!

EDIT

toolbar_layout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/toolbar_cust"
android:background="?attr/colorPrimaryDark"
android:minHeight="?attr/actionBarSize"
android:fitsSystemWindows="true"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
>

</android.support.v7.widget.Toolbar>
</code>```

EDIT 2

I even removed the id provided to the include tag and tried again but still not working.

答:
That's because your layout does not contain a View with id = "toolbar_cust".

So the findViewById(R.id.toolbar_cust) returns null, so you're setSupportActionBar(null) and getSupportActionBar() will then also return null.

Body:
The following are a part of my project. The error is on the line getSupportActionBar().setDisplayHomeAsUpEnabled(true);. I checked for any theme mismatch but there were no theme mismatch to my knowledge, the activity extends 'appcompatActivity' and i used the 'getSupportActionBar()' but still getting the nullpointer exception (Error posted Below)..

Home_Activity.java

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;

public class Home_Activity extends AppCompatActivity {

DrawerLayout drawerLayout;
ActionBarDrawerToggle mToggle;
android.support.v4.app.FragmentTransaction fragmentTransaction;
Toolbar mToolbar;
NavigationView navigationView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.nav_page);

    mToolbar = findViewById(R.id.toolbar_cust);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); //ERROR
}

nav_page.xml

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<RelativeLayout
    android:id="@+id/relative_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <include
        android:id="@+id/inc"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        layout="@layout/toolbar_layout"
        />
    <FrameLayout
        android:id="@+id/maincontainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/inc">
    </FrameLayout>

</RelativeLayout>

<android.support.design.widget.NavigationView
    android:id="@+id/navigation"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:menu="@menu/menu_list_items"
    app:headerLayout="@layout/navigation_header"
    android:background="#ffffff">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>

Gradle dependencies

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support:design:26.1.0'
}

styles.xml

<resources>

</resources>

ERROR

FATAL EXCEPTION: main
                                                                 Process: com.app.ce.cybereye, PID: 30688
                                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.ce.cybereye/com.app.ce.cybereye.Home_Activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2696)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2757)
                                                                     at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                     at android.os.Looper.loop(Looper.java:163)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:6237)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
                                                                     at com.app.ce.cybereye.Home_Activity.onCreate(Home_Activity.java:30)
                                                                     at android.app.Activity.performCreate(Activity.java:6847)
                                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2649)

Hope i am clear enough!

EDIT

toolbar_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/toolbar_cust"
android:background="?attr/colorPrimaryDark"
android:minHeight="?attr/actionBarSize"
android:fitsSystemWindows="true"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
>

</android.support.v7.widget.Toolbar>

EDIT 2

I even removed the id provided to the include tag and tried again but still not working.


问:
SQL string before and after certain characters
```<code>SELECT NAME
FROM SERVERS
</code>```

returns:

```<code>SDACR.hello.com
SDACR
SDACR\AIR
SDACR.hello.com\WATER
</code>```

I need the SELECT query for below result:

```<code>SDACR
SDACR
SDACR\AIR
SDACR\WATER
</code>```

Kindly help ! I tried using LEFT and RIGHT functions as below, but not able to get combined output correctly:

```<code> SELECT
     LEFT(Name, CHARINDEX('.', Name) - 1)
 FROM
     SERVERS

SELECT
    RIGHT(Name, LEN(Name) - CHARINDEX('\', Name))
FROM
    SERVERS
</code>```

答:
You can use LEFT for this to select everything up to the first period (dot) and add on everything after the last \

```<code>declare @servers table ([NAME] varchar(64))
insert into @servers
values
('SDACR.hello.com '),
('SDACR'),
('SDACR\AIR'),
('SDACR.hello.com\WATER')

select
    left([NAME],case when charindex('.',[NAME]) = 0 then len([NAME]) else charindex('.',[NAME]) -1 end) +
    case when charindex('\',left([NAME],case when charindex('.',[NAME]) = 0 then len([NAME]) else charindex('.',[NAME]) -1 end)) = 0 then right([NAME],charindex('\',reverse([NAME]))) else '' end
from @servers
</code>```

Body:
SELECT NAME
FROM SERVERS

returns:

SDACR.hello.com
SDACR
SDACR\AIR
SDACR.hello.com\WATER

I need the SELECT query for below result:

SDACR
SDACR
SDACR\AIR
SDACR\WATER

Kindly help ! I tried using LEFT and RIGHT functions as below, but not able to get combined output correctly:

 SELECT
     LEFT(Name, CHARINDEX('.', Name) - 1)
 FROM
     SERVERS

SELECT
    RIGHT(Name, LEN(Name) - CHARINDEX('\', Name))
FROM
    SERVERS

Body:
You can use LEFT for this to select everything up to the first period (dot) and add on everything after the last \

declare @servers table ([NAME] varchar(64))
insert into @servers
values
('SDACR.hello.com '),
('SDACR'),
('SDACR\AIR'),
('SDACR.hello.com\WATER')

select
    left([NAME],case when charindex('.',[NAME]) = 0 then len([NAME]) else charindex('.',[NAME]) -1 end) +
    case when charindex('\',left([NAME],case when charindex('.',[NAME]) = 0 then len([NAME]) else charindex('.',[NAME]) -1 end)) = 0 then right([NAME],charindex('\',reverse([NAME]))) else '' end
from @servers


问:
Can we use Paint Component without extending JPanel Class?
I'm making a gui in which draw a line using paint component method i know i can do that with extends JPanel. But i really want to know how to do this without extending anything.Like in this program

```<code>public class Main {

    static JPanel panel;

    public static void main(String[] args) {
        JFrame frame = new JFrame("Our Frame");
        panel = new JPanel();
        frame.setSize(600,480);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.add(panel);
    }
}
</code>```

And on this Way

```<code>public class Main {

    public static void main(String[] args) {
        Frame obj = new Frame();
    }
        }
</code>```

The frame

```<code> public class Frame extends JFrame{

    private JPanel panel;

    public Frame(){
        panel = new JPanel();
        setSize(600,480);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
        add(panel);
    }
}
</code>```

答:
You can do something like this: </p>

```<code>JPanel panel = new JPanel(true) {
            @Override
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                // do painting
            }
}
</code>```

Body:
I'm making a gui in which draw a line using paint component method i know i can do that with extends JPanel. But i really want to know how to do this without extending anything.Like in this program

public class Main {

    static JPanel panel;

    public static void main(String[] args) {
        JFrame frame = new JFrame("Our Frame");
        panel = new JPanel();
        frame.setSize(600,480);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.add(panel);
    }
}

And on this Way

public class Main {

    public static void main(String[] args) {
        Frame obj = new Frame();
    }
        }

The frame

 public class Frame extends JFrame{

    private JPanel panel;

    public Frame(){
        panel = new JPanel();
        setSize(600,480);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
        add(panel);
    }
}

Body:
You can do something like this:

JPanel panel = new JPanel(true) {
            @Override
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                // do painting
            }
}


问:
Automating a input slider over time
I have a range input on my website like this:

```<code><input type="range"  min="1036000000000" max="1510462800000" value="0" class="slider" id ="slider"/>
</code>```

I have some D3 code that loads a visualization onto the page. It's online here:

https://bl.ocks.org/KingOfCramers/raw/5c166e770c4a865d861452dd184b54f4/

Over the period of 10 seconds, I want to automate the value of the slider from it's min value to it's max value. The thumb slider should move accordingly.

I need this function (probably setTimeout?) to fire after the visualization has finished loading my D3 code (which is currently wrapped in a d3.queue function), and allow for the user to move the slider after it's reached the max value.

How would I do this in Javascript?

答:
Here is a DEMO. I believe this will help you with your automation.

JS

```<code>  $(document).ready(function(){
  var val;
  var inte = setInterval(function(){
    val = $('#slider').val();
    val= parseInt(val) + 10000000000;
    $('#slider').val(val);
    $('#value').val(val);
    if(val > $('#slider').attr('max')){
      clearInterval(inte);
    }
  },10000);
});
</code>```

Title: Automating a input slider over time

Body:
I have a range input on my website like this:

<input type="range"  min="1036000000000" max="1510462800000" value="0" class="slider" id ="slider"/>

I have some D3 code that loads a visualization onto the page. It's online here:

https://bl.ocks.org/KingOfCramers/raw/5c166e770c4a865d861452dd184b54f4/

Over the period of 10 seconds, I want to automate the value of the slider from it's min value to it's max value. The thumb slider should move accordingly.

I need this function (probably setTimeout?) to fire after the visualization has finished loading my D3 code (which is currently wrapped in a d3.queue function), and allow for the user to move the slider after it's reached the max value.

How would I do this in Javascript?

Body:
Here is a DEMO. I believe this will help you with your automation.

JS

  $(document).ready(function(){
  var val;
  var inte = setInterval(function(){
    val = $('#slider').val();
    val= parseInt(val) + 10000000000;
    $('#slider').val(val);
    $('#value').val(val);
    if(val > $('#slider').attr('max')){
      clearInterval(inte);
    }
  },10000);
});


问:
How to start session with node-session
I have a node.js server with socket.io like this:

```<code>var port = process.env.PORT || 1337;
var server = require('http').createServer().listen( port );
var io = require('socket.io').listen( server );
var user = require('./p/a/t/h/user');
io.sockets.on('connection', function( socket ){
socket.on('login', function( data ){
      user.login( data, function ( err, res ) {

      });
   });
});
</code>```

And id like to have some kind of session system which recognize logged in users (i choose this one).
So my user module look something like this:

```<code>var session = require('node-session');
session = new session({secret: 'secret-string','driver': 'file','files': process.cwd() + '/sessions','lifetime': 3600000,'expireOnClose': false});
module.exports = {
    login: function ( data, callback ) {
        session.sessionStart(  ); // ??
    }
};
</code>```

How to start a session here and/or get the related session data from the session storage?

答:
Found a working solution.

```<code>var port = process.env.PORT || 1337;
var server = require('http').createServer().listen( port );
var io = require('socket.io').listen( server );
var user = require('./p/a/t/h/user');
io.sockets.on('connection', function( socket ){
    socket.on('login', function( data ){
          user.login( socket, data, function ( err, res ) {

          });
    });
});
</code>```

and in user.js:

```<code>var session = require('node-session');
session = new session({secret: 'secret-string'});
module.exports = {
login: function ( socket, data, callback ) {
    session.startSession( socket.request, socket.request.res, function() {
       user.session = socket.request.session;

    });
}
</code>```

};

Hope it's helpful for someone.

Title: How to start session with node-session

Body:
I have a node.js server with socket.io like this:

var port = process.env.PORT || 1337;
var server = require('http').createServer().listen( port );
var io = require('socket.io').listen( server );
var user = require('./p/a/t/h/user');
io.sockets.on('connection', function( socket ){
socket.on('login', function( data ){
      user.login( data, function ( err, res ) {

      });
   });
});

And id like to have some kind of session system which recognize logged in users (i choose this one).
So my user module look something like this:

var session = require('node-session');
session = new session({secret: 'secret-string','driver': 'file','files': process.cwd() + '/sessions','lifetime': 3600000,'expireOnClose': false});
module.exports = {
    login: function ( data, callback ) {
        session.sessionStart(  ); // ??
    }
};

How to start a session here and/or get the related session data from the session storage?

Body:
Found a working solution.

var port = process.env.PORT || 1337;
var server = require('http').createServer().listen( port );
var io = require('socket.io').listen( server );
var user = require('./p/a/t/h/user');
io.sockets.on('connection', function( socket ){
    socket.on('login', function( data ){
          user.login( socket, data, function ( err, res ) {

          });
    });
});

and in user.js:

var session = require('node-session');
session = new session({secret: 'secret-string'});
module.exports = {
login: function ( socket, data, callback ) {
    session.startSession( socket.request, socket.request.res, function() {
       user.session = socket.request.session;

    });
}

};

Hope it's helpful for someone.


问:
Custom Glide ModelLoader for base64 images
I have images from some SOAP API that are encoded in base64. To load them directly with Glide I decided to wrote custom ModelLoader.

Glide Version: 4.3.1

Glide load line:

```<code>GlideApp.with(activity)
        .load(Data().apply { code = licensePlateData.licensePlateImgId })
        .into(view.imageLicense)
</code>```

GlideModule:

```<code>@GlideModule
class MyAppGlideModule : AppGlideModule() {

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        super.registerComponents(context, glide, registry)
        val app = context.applicationContext as MyApplication
        registry.append(Data::class.java, ByteArray::class.java, MyImageLoaderFactory(app.api))
    }
}
</code>```

Loader:

```<code>class MyImageLoaderFactory(private val api: Api) : ModelLoaderFactory<Data, ByteArray> {

    override fun teardown() {

    }

    override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<Data, ByteArray> {
        return MyImageLoader(api)
    }
}

class MyImageLoader(private val api: Api) : ModelLoader<Data, ByteArray> {

    override fun buildLoadData(model: Data, width: Int, height: Int, options: Options): ModelLoader.LoadData<ByteArray> {
        val key = "code:${model.code};width:$width;height:$height"
        return ModelLoader.LoadData<ByteArray>(ObjectKey(key), MyImageDataFetcher(api, GetImageRequest().apply { data = model }))
    }

    override fun handles(model: Data): Boolean {
        return true
    }
}

class MyImageDataFetcher(private val api: Api, private val request: GetImageRequest) : DataFetcher<ByteArray> {

    private val disposables = CompositeDisposable()

    override fun cleanup() {
        disposables.clear()
    }

    override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in ByteArray>) {
        api.getImage(request) //soap request
                .map { it.image.decodeBase64() } //translate String to ByteArray
                .subscribe({ callback.onDataReady(it) }, {
                    if (it is Exception) {
                        callback.onLoadFailed(it)
                    } else {
                        callback.onLoadFailed(MyException(it))
                    }
                })
                .addTo(disposables)
    }

    override fun cancel() {
        disposables.clear()
    }

    override fun getDataClass(): Class<ByteArray> {
        return ByteArray::class.java
    }

    override fun getDataSource(): DataSource {
        return DataSource.REMOTE
    }

}
</code>```

Stack trace / LogCat:

```<code>com.bumptech.glide.Registry$NoSourceEncoderAvailableException: Failed to find source encoder for data class: class [B
    at com.bumptech.glide.Registry.getSourceEncoder(Registry.java:534)
    at com.bumptech.glide.load.engine.DecodeHelper.getSourceEncoder(DecodeHelper.java:232)
    at com.bumptech.glide.load.engine.SourceGenerator.cacheData(SourceGenerator.java:74)
    at com.bumptech.glide.load.engine.SourceGenerator.startNext(SourceGenerator.java:45)
    at com.bumptech.glide.load.engine.DecodeJob.runGenerators(DecodeJob.java:298)
    at com.bumptech.glide.load.engine.DecodeJob.runWrapped(DecodeJob.java:268)
    at com.bumptech.glide.load.engine.DecodeJob.run(DecodeJob.java:229)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
    at java.lang.Thread.run(Thread.java:764)
    at com.bumptech.glide.load.engine.executor.GlideExecutor$DefaultThreadFactory$1.run(GlideExecutor.java:413)
</code>```

I think that I'm missing something to make it work.

答:
Thanks to comment from https://github.com/bumptech/glide/issues/2677 I found the solution.</p>
```<code>@GlideModule
class MyAppGlideModule : AppGlideModule() {

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        super.registerComponents(context, glide, registry)
        val app = context.applicationContext as MyApplication
        registry.append(Data::class.java, ByteBuffer::class.java, MyImageLoaderFactory(app.api))
    }
}

class MyImageLoaderFactory(private val api: Api) : ModelLoaderFactory<Data, ByteBuffer> {

    override fun teardown() {

    }

    override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<Data, ByteBuffer> {
        return MyImageLoader(api)
    }
}

class MyImageLoader(private val api: Api) : ModelLoader<Data, ByteBuffer> {

    override fun buildLoadData(model: Data, width: Int, height: Int, options: Options): ModelLoader.LoadData<ByteBuffer> {
        val key = "code:${model.code};width:$width;height:$height"
        return ModelLoader.LoadData<ByteBuffer>(ObjectKey(key), MyImageDataFetcher(api, GetImageRequest().apply { data = model }))
    }

    override fun handles(model: Data): Boolean {
        return true
    }
}

class MyImageDataFetcher(private val api: Api, private val request: GetImageRequest) : DataFetcher<ByteBuffer> {

    private val disposables = CompositeDisposable()

    override fun cleanup() {
        disposables.clear()
    }

    override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in ByteBuffer>) {
        api.getImage(request)
                .map { it.image.decodeBase64() }
                .subscribe({ callback.onDataReady(ByteBuffer.wrap(it)) }, {
                    if (it is Exception) {
                        callback.onLoadFailed(it)
                    } else {
                        callback.onLoadFailed(MyException(it))
                    }
                })
                .addTo(disposables)
    }

    override fun cancel() {
        disposables.clear()
    }

    override fun getDataClass(): Class<ByteBuffer> {
        return ByteBuffer::class.java
    }

    override fun getDataSource(): DataSource {
        return DataSource.REMOTE
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have images from some SOAP API that are encoded in base64. To load them directly with Glide I decided to wrote custom ModelLoader.

Glide Version: 4.3.1

Glide load line:

GlideApp.with(activity)
        .load(Data().apply { code = licensePlateData.licensePlateImgId })
        .into(view.imageLicense)

GlideModule:

@GlideModule
class MyAppGlideModule : AppGlideModule() {

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        super.registerComponents(context, glide, registry)
        val app = context.applicationContext as MyApplication
        registry.append(Data::class.java, ByteArray::class.java, MyImageLoaderFactory(app.api))
    }
}

Loader:

class MyImageLoaderFactory(private val api: Api) : ModelLoaderFactory<Data, ByteArray> {

    override fun teardown() {

    }

    override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<Data, ByteArray> {
        return MyImageLoader(api)
    }
}

class MyImageLoader(private val api: Api) : ModelLoader<Data, ByteArray> {

    override fun buildLoadData(model: Data, width: Int, height: Int, options: Options): ModelLoader.LoadData<ByteArray> {
        val key = "code:${model.code};width:$width;height:$height"
        return ModelLoader.LoadData<ByteArray>(ObjectKey(key), MyImageDataFetcher(api, GetImageRequest().apply { data = model }))
    }

    override fun handles(model: Data): Boolean {
        return true
    }
}

class MyImageDataFetcher(private val api: Api, private val request: GetImageRequest) : DataFetcher<ByteArray> {

    private val disposables = CompositeDisposable()

    override fun cleanup() {
        disposables.clear()
    }

    override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in ByteArray>) {
        api.getImage(request) //soap request
                .map { it.image.decodeBase64() } //translate String to ByteArray
                .subscribe({ callback.onDataReady(it) }, {
                    if (it is Exception) {
                        callback.onLoadFailed(it)
                    } else {
                        callback.onLoadFailed(MyException(it))
                    }
                })
                .addTo(disposables)
    }

    override fun cancel() {
        disposables.clear()
    }

    override fun getDataClass(): Class<ByteArray> {
        return ByteArray::class.java
    }

    override fun getDataSource(): DataSource {
        return DataSource.REMOTE
    }

}

Stack trace / LogCat:

com.bumptech.glide.Registry$NoSourceEncoderAvailableException: Failed to find source encoder for data class: class [B
    at com.bumptech.glide.Registry.getSourceEncoder(Registry.java:534)
    at com.bumptech.glide.load.engine.DecodeHelper.getSourceEncoder(DecodeHelper.java:232)
    at com.bumptech.glide.load.engine.SourceGenerator.cacheData(SourceGenerator.java:74)
    at com.bumptech.glide.load.engine.SourceGenerator.startNext(SourceGenerator.java:45)
    at com.bumptech.glide.load.engine.DecodeJob.runGenerators(DecodeJob.java:298)
    at com.bumptech.glide.load.engine.DecodeJob.runWrapped(DecodeJob.java:268)
    at com.bumptech.glide.load.engine.DecodeJob.run(DecodeJob.java:229)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
    at java.lang.Thread.run(Thread.java:764)
    at com.bumptech.glide.load.engine.executor.GlideExecutor$DefaultThreadFactory$1.run(GlideExecutor.java:413)

I think that I'm missing something to make it work.

Body:
Thanks to comment from https://github.com/bumptech/glide/issues/2677 I found the solution.

@GlideModule
class MyAppGlideModule : AppGlideModule() {

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        super.registerComponents(context, glide, registry)
        val app = context.applicationContext as MyApplication
        registry.append(Data::class.java, ByteBuffer::class.java, MyImageLoaderFactory(app.api))
    }
}

class MyImageLoaderFactory(private val api: Api) : ModelLoaderFactory<Data, ByteBuffer> {

    override fun teardown() {

    }

    override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<Data, ByteBuffer> {
        return MyImageLoader(api)
    }
}

class MyImageLoader(private val api: Api) : ModelLoader<Data, ByteBuffer> {

    override fun buildLoadData(model: Data, width: Int, height: Int, options: Options): ModelLoader.LoadData<ByteBuffer> {
        val key = "code:${model.code};width:$width;height:$height"
        return ModelLoader.LoadData<ByteBuffer>(ObjectKey(key), MyImageDataFetcher(api, GetImageRequest().apply { data = model }))
    }

    override fun handles(model: Data): Boolean {
        return true
    }
}

class MyImageDataFetcher(private val api: Api, private val request: GetImageRequest) : DataFetcher<ByteBuffer> {

    private val disposables = CompositeDisposable()

    override fun cleanup() {
        disposables.clear()
    }

    override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in ByteBuffer>) {
        api.getImage(request)
                .map { it.image.decodeBase64() }
                .subscribe({ callback.onDataReady(ByteBuffer.wrap(it)) }, {
                    if (it is Exception) {
                        callback.onLoadFailed(it)
                    } else {
                        callback.onLoadFailed(MyException(it))
                    }
                })
                .addTo(disposables)
    }

    override fun cancel() {
        disposables.clear()
    }

    override fun getDataClass(): Class<ByteBuffer> {
        return ByteBuffer::class.java
    }

    override fun getDataSource(): DataSource {
        return DataSource.REMOTE
    }

}


问:
Smart cast to kotlin.String
I was trying Kotlin and got message from compiler:

```<code>Smart cast to kotlin.String
</code>```

Code:

```<code>/*"mTripStatus" is a nullable String*/
var html :String = HTML
html = if (mTripStatus!=null) html.replace("TRIP_STATUS_VALUE", mTripStatus) else html
</code>```

What does this mean?

答:
The compiler knows that mTripStatus cannot be null if the if condition is satisfied, so it performs a smart cast from String? to String.  That's what allows html.replace("TRIP_STATUS_VALUE", mTripStatus) to compile.

But note that this shouldn't be interpreted as a compiler warning.  This is idiomatic Kotlin code.

Title: Smart cast to kotlin.String

Body:
I was trying Kotlin and got message from compiler:

Smart cast to kotlin.String

Code:

/*"mTripStatus" is a nullable String*/
var html :String = HTML
html = if (mTripStatus!=null) html.replace("TRIP_STATUS_VALUE", mTripStatus) else html

What does this mean?


问:
iPhone orientation - two boxes
My iPhone app has two boxes with content. When user switch the orientation of a phone boxes change the position like this:

Portrait

```<code>|---------|
| BUTTON1 |
| BUTTON2 |
|---------|
|         |
| BUTTON3 |
| BUTTON4 |
|         |
|---------|
</code>```

Landscape

```<code>|---------|---------------|
| BUTTON1 |    BUTTON3    |
| BUTTON2 |    BUTTON4    |
|---------|---------------|
</code>```

What is the right way to go? Two XIBs, other tricks? Should I resize elements manually in code?

答:
Use something like this:

```<code>-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
if(toInterfaceOrientation == UIInterfaceOrientationPortrait){
    button.frame = CGRectMake(20,20,125,125);
    }else{
    button.frame = CGRectMake(20,20,125,125);
    }
}
</code>```

Of course you'll have to use your own dimensions in the CGRectMake box, but other than that, I hope this helps.

Title: iPhone orientation - two boxes

Body:
My iPhone app has two boxes with content. When user switch the orientation of a phone boxes change the position like this:

Portrait

|---------|
| BUTTON1 |
| BUTTON2 |
|---------|
|         |
| BUTTON3 |
| BUTTON4 |
|         |
|---------|

Landscape

|---------|---------------|
| BUTTON1 |    BUTTON3    |
| BUTTON2 |    BUTTON4    |
|---------|---------------|

What is the right way to go? Two XIBs, other tricks? Should I resize elements manually in code?

Body:
Use something like this:

-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
if(toInterfaceOrientation == UIInterfaceOrientationPortrait){
    button.frame = CGRectMake(20,20,125,125);
    }else{
    button.frame = CGRectMake(20,20,125,125);
    }
}

Of course you'll have to use your own dimensions in the CGRectMake box, but other than that, I hope this helps.


问:
Generating new random number in python?
So i'm trying to create this really really simple game in python where the person types a number and if it matches the number that the computer generated the user is prompted with a message saying it got the right number and if its wrong a message saying its wrong, now I cant quite figure it out what I did wrong here because when I run this, I try different numbers multiple times and it always displays me the message that I didnt guess the right number, could anyone tell me what I am doing wrong here since I have no idea what the problem is?

```<code>import random

number = random.randint(0,10)
user_number = input()

while user_number != number:
  if user_number == number:
    print("GREAT! You guessed the right number! :)")
  else:
    print("AWW! You guessed the wrong number, try again! :)")
  input()
</code>```

EDIT I have a problem, how would I make my script generate a different number everytime the user inputs something, because what I have right now generates a number and that number never changes (btw thanks to Anton vBR for this updates version that I tweaked a bit):

```<code>import random

number = random.randint(0,10)
user_number = None
valid_num = [str(i) for i in range(0,10)]
random = 2

while random > 1:
while True:
    user_number = input("Enter a number between 1-10: ")
    if user_number in valid_num:
        user_number = int(user_number)
        break
    else:
        print("Not valid!")
if user_number == number:
    print("GREAT! You guessed the right number! :)")
else:
    print("AWW! You guessed the wrong number, try again! :)")
</code>```

答:
you must devise the execution blocks (if you go within the time must carry an indentation)

besides that your loop becomes infinite because you do not ask the question inside, you must put the input inside and also devise the code to know where it starts and ends the execution blocks

Title: Generating new random number in python?

Body:
So i'm trying to create this really really simple game in python where the person types a number and if it matches the number that the computer generated the user is prompted with a message saying it got the right number and if its wrong a message saying its wrong, now I cant quite figure it out what I did wrong here because when I run this, I try different numbers multiple times and it always displays me the message that I didnt guess the right number, could anyone tell me what I am doing wrong here since I have no idea what the problem is?

import random

number = random.randint(0,10)
user_number = input()

while user_number != number:
  if user_number == number:
    print("GREAT! You guessed the right number! :)")
  else:
    print("AWW! You guessed the wrong number, try again! :)")
  input()

EDIT I have a problem, how would I make my script generate a different number everytime the user inputs something, because what I have right now generates a number and that number never changes (btw thanks to Anton vBR for this updates version that I tweaked a bit):

import random

number = random.randint(0,10)
user_number = None
valid_num = [str(i) for i in range(0,10)]
random = 2

while random > 1:
while True:
    user_number = input("Enter a number between 1-10: ")
    if user_number in valid_num:
        user_number = int(user_number)
        break
    else:
        print("Not valid!")
if user_number == number:
    print("GREAT! You guessed the right number! :)")
else:
    print("AWW! You guessed the wrong number, try again! :)")


问:
Different way to write this
I have a script that will sometimes catch a ChunckedEncodingError while using the requests package in python.

I've successfully fixed the issue by doing the following:

```<code>try:
    _, status, html_data, _ = lib.core.common.get_page(url, agent=agent, proxy=proxy)
except requests.exceptions.ChunkedEncodingError:
    lib.core.settings.logger.warning(lib.core.settings.set_color(
        "encoding seems to be messed up, trying the request again...", level=30
    ))
    try:
        _, status, html_data, _ = lib.core.common.get_page(url, agent=agent, proxy=proxy)
    except requests.exceptions.ChunkedEncodingError:
        lib.core.settings.logger.error(lib.core.settings.set_color(
            "encoding is unable to be fixed from a retry, skipping...", level=40
        ))
        return False, None
except requests.exceptions.InvalidURL:
    url = "http://{}".format(url)
    _, status, html_data, _ = lib.core.common.get_page(url, agent=agent, proxy=proxy)
</code>```

Now this works and all, but I don't really like the whole try inside an except block, is there another way I could write this to be more pythonic and readable?

From the provided answer, I was able to come up with this:

```<code>retry_flags = 3
auto_assign = "http://{}"
url_verification = re.compile(r"http(s)?", re.I)

if url_verification.search(url) is None:
    lib.core.settings.logger.warning(lib.core.settings.set_color(
        "protocol missing from URL, automatically assigning protocol...", level=30
    ))
    url = auto_assign.format(url)

while retry_flags > 0:
    try:
        _, status, html_data, _ = lib.core.common.get_page(url, agent=agent, proxy=proxy)
    except requests.exceptions.ChunkedEncodingError:
        lib.core.settings.logger.warning(lib.core.settings.set_color(
            "encoding seems to be messed up, retrying request...", level=30
        ))
        retry_flags -= 1
return False, None
</code>```

Thanks everyone!

答:
A while loop is clear and well structured by quite a few linguistic standards.</p>

```<code>def get_url_wrapper(url, agent, proxy):
    flag = 3

    while flag > 0:
        try:
           _, status, html_data, _ = lib.core.common.get_page(url, agent=agent, proxy=proxy)
           return status, html_data
        except requests.exceptions.InvalidURL:
            # This is a case of invalid structure. Don't modify flag
            url = "http://{}".format(url)
        except requests.exceptions.ChunkedEncodingError:
            lib.core.settings.logger.error(lib.core.settings.set_color(
                "encoding is unable to be fixed from a retry, skipping...", level=40
            ))
            # this is an actual error, decrement flag.
            flag -= 1

    return False, None
</code>```

Title: Different way to write this

Body:
I have a script that will sometimes catch a ChunckedEncodingError while using the requests package in python.

I've successfully fixed the issue by doing the following:

try:
    _, status, html_data, _ = lib.core.common.get_page(url, agent=agent, proxy=proxy)
except requests.exceptions.ChunkedEncodingError:
    lib.core.settings.logger.warning(lib.core.settings.set_color(
        "encoding seems to be messed up, trying the request again...", level=30
    ))
    try:
        _, status, html_data, _ = lib.core.common.get_page(url, agent=agent, proxy=proxy)
    except requests.exceptions.ChunkedEncodingError:
        lib.core.settings.logger.error(lib.core.settings.set_color(
            "encoding is unable to be fixed from a retry, skipping...", level=40
        ))
        return False, None
except requests.exceptions.InvalidURL:
    url = "http://{}".format(url)
    _, status, html_data, _ = lib.core.common.get_page(url, agent=agent, proxy=proxy)

Now this works and all, but I don't really like the whole try inside an except block, is there another way I could write this to be more pythonic and readable?

From the provided answer, I was able to come up with this:

retry_flags = 3
auto_assign = "http://{}"
url_verification = re.compile(r"http(s)?", re.I)

if url_verification.search(url) is None:
    lib.core.settings.logger.warning(lib.core.settings.set_color(
        "protocol missing from URL, automatically assigning protocol...", level=30
    ))
    url = auto_assign.format(url)

while retry_flags > 0:
    try:
        _, status, html_data, _ = lib.core.common.get_page(url, agent=agent, proxy=proxy)
    except requests.exceptions.ChunkedEncodingError:
        lib.core.settings.logger.warning(lib.core.settings.set_color(
            "encoding seems to be messed up, retrying request...", level=30
        ))
        retry_flags -= 1
return False, None

Thanks everyone!

Body:
A while loop is clear and well structured by quite a few linguistic standards.

def get_url_wrapper(url, agent, proxy):
    flag = 3

    while flag > 0:
        try:
           _, status, html_data, _ = lib.core.common.get_page(url, agent=agent, proxy=proxy)
           return status, html_data
        except requests.exceptions.InvalidURL:
            # This is a case of invalid structure. Don't modify flag
            url = "http://{}".format(url)
        except requests.exceptions.ChunkedEncodingError:
            lib.core.settings.logger.error(lib.core.settings.set_color(
                "encoding is unable to be fixed from a retry, skipping...", level=40
            ))
            # this is an actual error, decrement flag.
            flag -= 1

    return False, None