text:
Q: how do i setup nginx websites as in Xampp I am trying to migrate from XAMPP to Nginx webserver. I used to have multiple websites running  with Xampp with each web folder residing under xampp/htdocs folder. so for example, I will access sites(yii web sites) as [code]http://myserver/site1[code] and [code]http://myserver/site2[code] and they would be accessed from the site1 and site2 folders under htdocs. But I am having trouble setting this up in nginx. I have setup the default configuration with the root folder as /etc/share/nginx/www  (and site1 and site2 folders are under www) and when i access the same way with nginx, the webpage gives an error saying "No Input file specified". I understand that  multiple sites are setup in nginx with different domain names and different root folders, but is it possible to have the xampp like configuration? Because i am testing this on my local network and i do not want to setup multiple domain names for this.

A: Config for latest nginx versions is pretty simple. First you should edit nginx/conf/nginx.conf and make sure you have something like include vhosts/*.conf; inside http { section. That will make nginx look for extra configs under vhosts.
Also it's a good idea to declare the following in http { as well not to repeat it for each individual config:
gzip  on;
charset utf-8;
index index.php index.htm index.html;

Then in nginx/conf/vhosts/mydomain.com.conf:
server {
    listen       80;
    server_name  mydomain.com;
    root    /var/www/mydomain.com/www;

    location / {
        try_files   $uri $uri/ /index.php?$args; # Redirect everything that isn't real file to index.php including arguments.
    }

    location ~ \.php$ {
        include fastcgi.conf; # that's if you have one of latest versions of nginx. If not, see below
        fastcgi_pass   127.0.0.1:9000; # or pass through socket if it's how you've configured php-fpm
    }

    location ~ /\.(ht|svn) {
        deny all;
    }
}

In case you don't have fastcgi.conf here it is:
fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

Now the only thing left is to add mydomain.com to your hosts file so it's recognized locally.

A: That's simple.
Drop your databases, compress them, import them again OR use mysql -u root -p BASENAME < /the/path/BASEDROP.sql
Then simply move your default dir like /var/www/html and set permissions to 0777 or less by using chmod 0777 -R /the/path and also use chown www-data:www-data -R /the/path AND THEN reboot your system.

A: Well, after struggling through I finally found the ideal configuration. I understand this is not a recommended setup, but this is the give problem for me (nginx with multiple sites as subdirectories) and had to find a solution for it.
location /Site1/ {
            root /usr/share/nginx/www/Site1;
           try_files $uri $uri/ /index.php?$query_string;
    }

    # the images need a seperate entry as we dont want to concatenate that with index.php
    location ~ /Site1/.+\.(jpg|jpeg|gif|css|png|js|ico|xml)$ {
            root /usr/share/nginx/www/Site1;
    }
    # pass the PHP scripts to FastCGI server
    location ~ /Site1/.+\.php$ {
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            allow 127.0.0.1;
    #       # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
    #       # With php5-fpm:
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_index index.php;
    }
location /Site3/ {
            root    /usr/share/nginx/www/Site3;
    }

    # pass the PHP scripts to FastCGI server
    location ~ /Site3/.+\.php$ {
            allow 127.0.0.1;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            include fastcgi_params;
            #we are directly using the $request_filename as its a single php script
            fastcgi_param SCRIPT_FILENAME $request_filename;
    }

More details on this blog, http://programmersjunk.blogspot.com/2013/11/nginx-multiple-sites-in-subdirectories.html


text:
Q: React form's defaultValue updates on page reload when a unique key is assigned to it but it doesn't when key is not there I am currently working on edit functionality using react form and want the data in the form fields to be pre-populated with the props value and for that I have assigned it to defaultValue in the form fields.
But the problem I came across while doing this is my defaultValues flush out on page reload. I tried finding a solution for it and came across few hacks to make the dom in sync with defaultValue. One of which was assigning a key to the wrapper component of the input field.
What is the reason for this behaviour of defaultValue?
Could anyone please help me figure out why the form field behaves like that? Here's the related snippet:
 var title = this.props.post.title;
 return (
    <form
      onSubmit={
        postId ? this.handleUpdate.bind(this) :
        this.handleSubmit.bind(this)
      }
    >
      <h3>
        {postId ? "Edit post" : "Create a New Post"}
      </h3>
      <FormGroup key={title} controlId="formControlsText">
        <ControlLabel>Title</ControlLabel>
        <FormControl
          type="text"
          inputRef={ref => {
            this.title = ref;
          }}
          placeholder="Enter title"
          defaultValue={title}
        />
      </FormGroup>
     </form>
    )

redpajama_set_name: RedPajamaStackExchange


text:
Q: Evaluating a Lie Derivative of a Meromorphic Complex Form over a Holomorphic Vector Field. Given a meromorphic form $\omega : \Omega^{1, 0}$, we can get the form $\; \mathrm{d}\omega = \partial \omega + \bar \partial \omega \;$ through the use of Dolbeault operators.
I'm trying to find the lie derivative $\mathcal{L}_v \; \omega$, where $v$ is a holomorphic vector field. How can I find this for non-holomorphic forms?
For example, suppose we allow the following definitions: $$ \omega = \frac{z+4}{z-3i} \; \mathrm{d}z, \quad v = 2z-1.$$
What is the Lie derivative $\mathcal{L}_v \;\omega$?

A: Ironically enough, I feel able enough to finally respond  with an answer.
Given complex 1-form $$\omega = \alpha(z) \mathrm \; {d}z, \qquad \alpha \in \mathcal{M}(\mathbb{C}), \qquad \frac{\partial \alpha}{\partial \bar z} = 0 \; $$ and given vector field $v = \beta(z) \; \partial_z, $ where $\beta$ is holomorphic to $\mathbb{C}$, define the Lie derivative like such:
$$\mathcal{L}_v \; \omega = i_v \circ d\omega + d \circ i_v\omega.$$
$$\mathcal{L}_v \; \omega = \; \Big(\frac{\partial \alpha}{\partial z} + \frac{\partial \alpha}{\partial \bar{z}}\Big)\beta \;\mathrm{d}\bar z + \frac{\partial(\alpha \beta)}{\partial z} \, \mathrm{d}z + \frac{\partial(\alpha \beta)}{\partial \bar z} \, \mathrm{d}\bar z.$$
Using the fact that $\frac{\partial \alpha}{\partial \bar z} = \frac{\partial \beta}{\partial \bar z} = 0$, the final result can be determined:
$$\mathcal{L}_v \; \omega = (\alpha \beta)'_z \; \mathrm{d}z + \alpha'_z \beta \; \mathrm{d}\bar{z}.$$
This is a surprisingly beautiful and simple result.


text:
Q: How do I pass JSON data from a Node.js res.render method to react.js on the client I'm using node.js to accept a request, grab data from dynamodb, format/merge it into an existing JSON template object and return it.
This worked great when using node as a webservice and just returning json, but i'm testing writing new client side code in react.js.  I know I could do two roundtrips - first to load the page without the JSON, then AJAX in react.js to load the JSON, but I'd like to do it in one.
In node I'm filling "filledTemplate" and I'd like to return the JSON object filledTemplate (via the Jade template "forms") to be accessible on the client side.  I can pass the object to jade, but I'm not sure the next step after that.
            lib.pact.mergeDataIntoTemplate(formTemplateJSON,backgroundDatasetJSON, function(err, filledTemplate){
                if(err) {
                    console.log(err);
                }
                else{
                    res.render('forms', { title: 'Filled Forms', data: filledTemplate });
                }
        });

Long story short, I'm not sure how to pass/access the object in react.js (or vanilla js for that matter) on the client side.
Any tips or pointers would be much appreciated.
(also, apparently there's no tag for react.js, and I can't add it... if someone else wants to)


text:
Q: M2.2.4 - Category page listing all products (when products per page set to 24) I am experiencing an odd and troubling problem.
On our production environment, all product pages are listing all products on the single page, in which some pages will have north of 2-300 products, which obviously causes incredible load times for the page and the like (even with lazy loading on the images and such).
The peculiar part is with the exact same settings and environment placed on our staging server, it works as expected, and has the paging with only 24 products per page. That is where I am lost as to why/how this is happening.
I have tried all the common methods of having this corrected:
Configuration > Catalog > Catalog > Storefront
---> Setting `Products per Page on Grid Default Value`
     to the desired value (which is a value given in
     `Products per Page on Grid Allowed Values`

---> Allow All Products per Page set to `No`

I also have tried using XML updates within the categories design themselves, using:
<referenceContainer name="content">
   <referenceBlock name="product_list_toolbar">
      <action method="setDefaultGridPerPage">
             <argument name="limit" xsi:type="string">24</argument>
      </action>
</referenceBlock>

Again, all these changes and testing them with other numbers work on the staging environment but alas on the production, it continues to always stay displaying all products on a single page.
I assume somehow, somewhere be it with messing with different extensions or what, something got hardcoded somewhere or something, but I am at a loss.
Any ideas??

A: This was solved by finding out an extension that was affecting it for whatever reason (Tatvic_EnhancedEcommerce was the one for me) -- I had an outdated version, once I updated it was working as intended.


text:
Q: How does my activity run smoothly with lots of High Quality Images in Android? Scenario: Two activites are there in my Android App: Activity X and Activity Y
On Activity X, one button is there, on Clicking of button, I'm opening Activity Y.
Inside OnCreate of Activity Y, I'm calling Firestore Database, and fetching around 10 image link. That image link is dynamic, and also that link is Firebase Storage link, where actual High Quality images are uploaded.
After fetching that images link, I'm setting on ImageView using Glide library.
Problem:
Obviously, To show 10 big Image, I added Scrollview in Activity Y XML, so that user can scroll and view the Images. But scrolling behaviour is not smooth. Also this is not just first time problem. After loading all Images into Imageview, after that also If I try to scroll then also scrolling is not smooth.
Code:
String str = entry.getValue().toString();

switch (entry.getKey()) {
            case "link1":
                setImage(binding.image1, str);
                break;

            case "link2":
                setImage(binding.image2, str);
                break;

            case "link3":
                setImage(binding.image3, str);
                break;

            case "link4":
                setImage(binding.image4, str);
                break;

            case "link5":
                setImage(binding.image5, str);
                break;
        }
    }

     private void setImage(ImageView image1, String str) {
            image1.setVisibility(View.VISIBLE);
            Glide.with(context).load(str).
                    diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(image1);
        }

UPDATE:
Tried with Recycyclerview instead of Scrollview, but is it even possible that recycler can be more smooth. I tried with below code.
RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(context) {
                    @Override
                    protected int getVerticalSnapPreference() {
                        return LinearSmoothScroller.SNAP_TO_ANY;
                    }
                };
                smoothScroller.setTargetPosition(0);
                mLayoutManager.startSmoothScroll(smoothScroller);

XML:
<androidx.recyclerview.widget.RecyclerView xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/app_bar"
        android:clipToPadding="false"
        android:fadingEdge="none"
        android:fastScrollEnabled="true"
        android:focusable="true"
        android:overScrollMode="never"
        tools:listitem="@layout/row_preview_view" />

Also, is there any caching mechanism or something possible? I'm using Glide library to load the image. Can I do something with Glide?

A: Maybe try to replace Scroll View with the Recycler View. In android docs, we can read "If your app needs to display a scrolling list of elements based on large data sets (or data that frequently changes), you should use RecyclerView" Docs. I am not sure but I think with Recycler View it will be more smooth.


text:
Q: Want to run python script and Flask api from single Dockerfile I am trying to create container with following docker file. Since it is going to execute last CMD, it ignores CMD ["sh", "-c", "python3 run_scheduler.py --config=${config}"].
Is there a way to run both from single docker file. Also, is it possible to pass ${config} argument to flask api in CMD ["gunicorn",  "--bind", "0.0.0.0:5000",  "run_api:application", "&"]
FROM python:3.8

LABEL version="0.1"

WORKDIR /app
COPY . /app

ARG config=dev
RUN  pip install -r requirements.txt
EXPOSE 5000
CMD ["sh", "-c", "python3 run_scheduler.py --config=${config}"]
CMD ["gunicorn",  "--bind", "0.0.0.0:5000",  "run_api:application", "&"]

A: As mentioned in comments you can pass 2-line bash script in CMD. This can cause problems however. Docker is not really meant to run multiple processes in single container. I already see "&" argument in your second CMD. I guess you had problems with second process wasn't running so you tried to push it to the background.
The solution recommended by Docker is to run supervisord inside the container: https://docs.docker.com/config/containers/multi-service_container/
From naming concepts I guess you can solve your problem with Flask-APScheduler https://github.com/viniciuschiele/flask-apscheduler
This way you can get rid of second sidecar script.
And lastly you asked:

Also, is it possible to pass ${config} argument to flask api

and answer is yes. Declare ENV in your Dockerfile like so:
FROM python:3.8
...
...
ENV config foo
...
CMD ["whatever_command", "--option", "${config}"]

This way "${config}" will be replaced with value foo.


text:
Q: Read an intex hex file line by line and manipulate the data I am reading data from Intel hex format file after opening it in binary mode and then creating a data (unsigned char)buffer and storing all the data in that (unsigned char)buffer in hex format.
I'm facing issue when the length of the data line is even (not including ':') program is adding 1 extra 0 at the end of the data.
//Returns content of firmware file in line by line fashion
unsigned char * readline(FILE *fp, unsigned char *buffer)
{
    unsigned int ch, iterator_i = 0;
    size_t buff_len = 0;

    buffer = malloc(buff_len + 1);
    if (!buffer) return NULL;  // Out of memory

    while ((ch = fgetc(fp)) != '\n' && ch != EOF)
    {
        buff_len++;
        void *tmp = realloc(buffer, buff_len + 1);
        if (tmp == NULL)
        {
            free(buffer);
            return NULL; // Out of memory
        }
    buffer = tmp;

    buffer[iterator_i] = (char) ch;
    iterator_i++;
    }
    buffer[iterator_i] = '\0';

    // Detect end
    if (ch == EOF && (iterator_i == 0 || ferror(fp)))
    {
        free(buffer);
        return NULL;
    }
    return buffer;
}

int main(){
    unsigned int i, len, temp;
    unsigned char * str = NULL, buf[3] = {'\0'}, data[22] = {'\0'}, *ptr = NULL, fn[30] = {'\0'}, ch;
    FILE *fp = NULL;

    printf("Enter FileName: ");
    scanf("%s", fn);

    fp = fopen(fn, "rb");
    while ((str = readline(fp, 0)) != NULL)
    {
        printf("string: %s\n", str);
        if(str[0] == ':' || strlen(str) <= 44){
            len = strlen(str) - 1;
            temp = 0;
            for(i = 1 ; i < len-1 ; i += 2){
            strncpy(buf, &str[i], 2);
                buf[2]='\0';
                data[temp] = (unsigned char) strtoul(buf,(char ** __restrict__) &ptr, 16);
                temp++;
            }
            if(len % 2 == 1){
                buf[0] = '0';
                strncpy(&buf[1], &str[i],1);
            }
            else{
                strncpy(buf, &str[i],2);
            }
            buf[2]='\0';
            data[temp] = (unsigned char) strtoul (buf,(char ** __restrict__) &ptr, 16);
            temp += 1;
            data[temp] = '\0';
            for(i = 0 ; i < temp ; i++ ){
                printf("%X", data[i]);
            }
            printf("\n");
        }
        else{
            printf("Error in hex record; file is corrupt.");
            exit(1);
        }

    }
    return 0;
}

So, when the value of str is ":DEAD" my output should be "DEAD" but I'm getting "DEAD0" as output.
I've tried checking my logic several times but was not able to find the fault..
Please help me.
Thanks in advance.


text:
Q: Why the variable height value is rest to 0? using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[RequireComponent(typeof(UnityEngine.LineRenderer))]
public class DrawCircle : MonoBehaviour
{
    public enum CircleHeight
    {
        Center, Bottom, Top
    };

    public CircleHeight circleheight;
    [Range(0, 50)]
    public int segments = 50;
    [Range(1, 50)]
    public float xradius = 1.5f;
    [Range(1, 50)]
    public float yradius = 1.5f;
    [Range(-10, 10)]
    public float height = 0;
    public bool changeBothRadius = false;
    [Range(0.1f, 2)]
    public float lineThickness = 0.1f;
    public bool minimumRadius = false;
    public bool draw = false;
    public bool animateCircle = false;
    public float animationSpeed = 0.5f;

    private LineRenderer line;
    private Renderer renderer;
    private float Bottom;
    private float Top;
    private float Center = 0;
    private float t = 0f;

    void Start()
    {
        circleheight = CircleHeight.Center;

        line = gameObject.GetComponent<UnityEngine.LineRenderer>();
        line.positionCount = segments + 1;
        line.useWorldSpace = false;
        renderer = gameObject.GetComponent<Renderer>();

        Bottom = transform.InverseTransformPoint(renderer.bounds.min).y + 0.1f;
        Top = transform.InverseTransformPoint(renderer.bounds.max).y + 0.1f;
    }

    void Update()
    {
        line.startWidth = lineThickness;
        line.endWidth = lineThickness;

        if (draw)
        {
            line.enabled = true;
            CreatePoints();
        }
        else
        {
            line.enabled = false;
        }
    }

    bool animStart = true;
    void CreatePoints()
    {
        float x;
        float z;

        float angle = 20;

        if (animateCircle == false)
        {
            switch (circleheight)
            {
                case CircleHeight.Center:
                    height = Center;
                    break;
                case CircleHeight.Bottom:
                    height = Bottom;
                    break;
                case CircleHeight.Top:
                    height = Top;
                    break;
            }
        }
        else
        {
            AnimateCircle(Top, Bottom);
        }

        for (int i = 0; i < (segments + 1); i++)
        {
            x = Mathf.Sin(Mathf.Deg2Rad * angle) * xradius;
            z = Mathf.Cos(Mathf.Deg2Rad * angle) * yradius;

            line.SetPosition(i, new Vector3(x, height, z));

            angle += (360f / segments + 1);
        }
    }

    private void AnimateCircle(float From, float To)
    {
        if (animStart)
        {
            if (height == Center)
            {
                height = Mathf.Lerp(Center, From, t);
                t += animationSpeed * Time.deltaTime;
                if (height == From)
                {
                    animStart = false;
                }
            }
        }
    }
}

I'm using the animateCircle flag to prevent from the enum to reset the height to Center all the time:
if (animateCircle == false)

Then I added a breakpoint and it's not passing in again it's doing all the time the else part:
else
            {
                AnimateCircle(Top, Bottom);
            }

And I see that height value is 0.6 after doing the process inside AnimateCircle method.
But then I added a breakpoint also on the line:
line.SetPosition(i, new Vector3(x, height, z));

First loop height is 0.6 but then after the loop end when i = 50 and the loop start over again I see that height is 0. But I'm not reseting height any where else.
This is the AnimateCircle method unused code just to show what I tried and means to do:
private void AnimateCircle(float From, float To)
    {
        // From = Top To = Bottom
        // height = Center

        if (animStart)
        {
            if (height != From)
            {
                height = Mathf.Lerp(height, From, t);
            }
            else
            {
                height = Mathf.Lerp(From, To, t);
            }
            t += animationSpeed * Time.deltaTime;
            if (height == From || height == To)
                animStart = false;
        }
        else
        {
            height = Mathf.Lerp(From, To, t);
            t += animationSpeed * Time.deltaTime;

            if (t > 1.0f)
            {
                if (To == Top)
                {
                    float temp = To;
                    To = From;
                    From = temp;
                    t = 0.0f;
                }
                if(To == Bottom)
                {
                    float temp = From;
                    From = To;
                    To = temp;
                    t = 0.0f;
                }
            }

            if (To == Top)
            {
                height = Mathf.Lerp(Bottom, Top, t);
                t += animationSpeed * Time.deltaTime;

                if (t > 1.0f)
                {
                    float temp = Top;
                    Top = Bottom;
                    Bottom = temp;
                    t = 0.0f;
                }
            }

            if(To == Bottom)
            {
                height = Mathf.Lerp(Top, Bottom, t);
                t += animationSpeed * Time.deltaTime;

                if (t > 1.0f)
                {
                    float temp = Bottom;
                    Bottom = Top;
                    Top = temp;
                    t = 0.0f;
                }
            }
        }
    }*/

For example the game start when the enum default state is Center in the Start.
And if I call AnimateStart(Top, Bottom); or AnimateStart(Bottom, Top);
Then inside AnimateCircle I want to move the circle from the Center to the Top or Bottom depending on how I'm calling it. So From can be Top or Bottom.
After the circle moved from the Center once to the Top or Bottom then start a ping pong nonstop between Top and Bottom (Or bottom top).
And if the game start with the enum default state as Bottom or Top then just start a ping pong between the top and Bottom without the Center.
EDIT:
This is the code for the AnimateCircle I'm using now:
private void AnimateCircle(float From, float To)
    {
        if (animStart)
        {
            // prevent t from exceeding tGoal
            if (t > tGoal)
            {
                t = tGoal;
            }

            // end animation when t reaches goal
            if (t == tGoal)
            {
                animStart = false;
            }

            // advance height according to t
            height = Mathf.Lerp(Bottom, Top, Mathf.PingPong(t, 1f));

            // advance height according to time & speed
            t += animationSpeed * Time.deltaTime;
        }
    }

The CreatePoints didn't change:
    bool animStart = true;
    void CreatePoints()
    {
        float x;
        float z;

        float angle = 20;

        if (animateCircle == false)
        {
            switch (circleheight)
            {
                case CircleHeight.Center:
                    // t=0.5f, tGoal=1f to go to top first then stop at top
                    // t=0.5f, tGoal=2f to go to top first then stop at bottom
                    // t=1.5f, tGoal=2f to go to bottom first then stop at bottom
                    // t=1.5f, tGoal=3f to go to bottom first then stop at top

                    t = 0.5f;
                    tGoal = 2f;
                    height = Center;
                    break;
                case CircleHeight.Bottom:
                    t = 0f;
                    tGoal = 1f;
                    height = Bottom;
                    break;
                case CircleHeight.Top:
                    t = 1f;
                    tGoal = 2f;
                    height = Top;
                    break;
            }
        }
        else
        {
            AnimateCircle(Bottom, Top);
        }

        for (int i = 0; i < (segments + 1); i++)
        {
            x = Mathf.Sin(Mathf.Deg2Rad * angle) * xradius;
            z = Mathf.Cos(Mathf.Deg2Rad * angle) * yradius;

            line.SetPosition(i, new Vector3(x, height, z));

            angle += (360f / segments + 1);
        }
    }

For the move first to the Top I'm calling the AnimateCircle like this:
AnimateCircle(Top, Bottom);

And inside the AnimateCircle also Top, Bottom like this:
height = Mathf.Lerp(Top, Bottom, Mathf.PingPong(t, 1f));

In the switch case part t = 0.5f and tGoal = 2f
But instead moving first to the Top it's moving to the Bottom fast then from Bottom to Top.
But if I change t = 1.5f and tGoal = 3f; Then it will move first to the Top then from top to Bottom and that is fine. But 0.5 and 2 not moving it first up.
And if t = 1.5f and tGoal = 2f; it will move up to the Top and stop there.
But I can't find how to make the Bottom part so it will move to the Bottom first and stop or move first to the Bottom and move to Top.

A: Add a float field called tGoal:
private float tGoal;

Set t depending on where you want it to start and tGoal on where you want it to stop animating. If you want it to start at Center, you have to determine the appropriate lerp value to start with:
        switch (circleheight)
        {
            case CircleHeight.Center:
                float centerT = Mathf.InverseLerp(Bottom, Top, Center);

                // t=0f+centerT, tGoal=1f to go to top first then stop at top
                // t=0f+centerT, tGoal=2f to go to top first then stop at bottom
                // t=2f-centerT, tGoal=2f to go to bottom first then stop at bottom
                // t=2f-centerT, tGoal=3f to go to bottom first then stop at top

                t = 2f - centerT;
                tGoal = 3f;
                height = Center;
                break;
            case CircleHeight.Bottom:
                t= 0f;
                tGoal = 1f;
                height = Bottom;
                break;
            case CircleHeight.Top:
                t = 1f;
                tGoal = 2f;
                height = Top;
                break;
        }

Then use Mathf.PingPong to turn t into a lerp value that ping pongs. Stop when t equals tGoal, making sure tGoal never can exceed it:
private void AnimateCircle()
{
    if (animStart)
    {
        // prevent t from exceeding tGoal
        if (t > tGoal) {
            t = tGoal;
        }

        // end animation when t reaches goal
        if (t == tGoal) {
            animStart = false;
        }

        // advance height according to t
        height = Mathf.Lerp(Bottom, Top, Mathf.PingPong(t,1f));

        // advance height according to time & speed
        t += animationSpeed * Time.deltaTime;

    }
}


text:
Q: How to Convert .doc/.docx to pdf in java using POI..?
how to convert ms-document to PDF,  is there any example pls share
  with me.. thanks.

A: If you are requiered to use POI i guess you should take a look at org.apache.poi.hwpf.converter
I never tried this, but i guess it´s worth a try atleast.
It seems like you can use WordToFoConverterto convert your XWPFDocument to a FO-file (example here).
From there you can use apaches FOP to transform the FO-file to a PDF like this:
// Step 1: Construct a FopFactory
// (reuse if you plan to render multiple documents!)
FopFactory fopFactory = FopFactory.newInstance();

// Step 2: Set up output stream.
// Note: Using BufferedOutputStream for performance reasons (helpful with FileOutputStreams).
OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("C:/Temp/myfile.pdf")));

try {
  // Step 3: Construct fop with desired output format
  Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);

  // Step 4: Setup JAXP using identity transformer
  TransformerFactory factory = TransformerFactory.newInstance();
  Transformer transformer = factory.newTransformer(); // identity transformer

  // Step 5: Setup input and output for XSLT transformation
  // Setup input stream
  Source src = new StreamSource(new File("C:/Temp/myfile.fo"));

  // Resulting SAX events (the generated FO) must be piped through to FOP
  Result res = new SAXResult(fop.getDefaultHandler());

  // Step 6: Start XSLT transformation and FOP processing
  transformer.transform(src, res);

} finally {
  //Clean-up
  out.close();
}

This Code was taken from https://xmlgraphics.apache.org/fop/0.95/embedding.html incase you want to read more on this topic.


text:
Q: Roman number for lines in algorithm Similar to this question, I have this minimal working code:
\documentclass{article}
\usepackage{algorithm}
\usepackage{algorithmic}
\begin{document}
    \begin{algorithm}
        \caption{Some alg}
        \begin{algorithmic}[1]
            \REQUIRE a,b, c
            \STATE d = a + b + c
            \STATE d = d/2
            \STATE d = d/3
            \RETURN d
        \end{algorithmic}
    \end{algorithm}
\end{document}

What I want is to number the steps as Roman (instead of Arabic).
What I tried:

*

*        \begin{algorithmic}[\Roman{1}] (line 7)

*\setcounter{ALG@line}{\Roman{0}} (after line 7, following this)

*        \begin{algorithmic}[label=\Roman*] (line 7)

*\renewcommand\theALG@line{\Roman{ALG@line}} (from this)

A: The line number in an algorithmic environment uses counter ALC@line. Unfortunately, that counter is not documented, and its format used in printing is hard-coded to \arabic.
In the following example,

*

*\theALC@line replaces \arabic{ALC@line}

*\setAlgoLinenoFormat{<an one-arg macro>} is provided, so \setAlgoLinenoFormat{\roman} will set the line number to roman.

\documentclass{article}
\usepackage{algorithm}
\usepackage{algorithmic}
\usepackage{xpatch}

\makeatletter
% patch env "algorithmic" to use \the<lineno counter>
\xpatchcmd\algorithmic
  {\ALC@linenosize \arabic{ALC@line}\ALC@linenodelimiter}
  {\ALC@linenosize \theALC@line\ALC@linenodelimiter}
  {}{\fail}

% use roman line numbers
\newcommand\setAlgoLinenoFormat[1]{%
  \renewcommand*{\theALC@line}{#1{ALC@line}}}
\makeatother

\begin{document}
    \begin{algorithm}
        \caption{Some alg}
        \begin{algorithmic}[1]
            \setAlgoLinenoFormat{\roman}
            \REQUIRE a,b, c
            \STATE d = a + b + c
            \STATE d = d/2
            \STATE d = d/3
            \RETURN d
        \end{algorithmic}
    \end{algorithm}

    \begin{algorithm}
        \caption{Some alg}
        \begin{algorithmic}[1]
            \setAlgoLinenoFormat{\Roman}
            \REQUIRE a,b, c
            \STATE d = a + b + c
            \STATE d = d/2
            \STATE d = d/3
            \RETURN d
        \end{algorithmic}
    \end{algorithm}
\end{document}


text:
Q: Android Listview Next-Prev Buttons for show items I m starting android development and I m learning. I m making some kind of list application.
My application connects my server every 10 seconds and get 10 items, and append retrieved item onto to the listview.
I want to show just one item at a time, I have previous and next button.
I want to make listview almost like this :

How can I do like this listview (I don't want to show small pictures left or right like this pic, I just want to move or reload new items When I click the prev or next Button)?
Does anyone know any way or any tutorial on this subject?
Note : I do'nt want to refresh my activity, I know making this way but its not for my application.

A: I wouldn't use a ListView for this, I'd have a look at using a ViewPager.
ViewPager
To set the width of each page, override getPageWidth() in your PagerAdapter
getPageWidth()
You can then use a PageTransformer to modify each page's View relative to its position in the ViewPager.
PageTransformer
Examples


text:
Q: EF Core Power Tools - Missing EF Core 5 Version I am using .NET core 5 and entity framework core 5 version in my project and to generate dB Context I am using EF Core Power Tools but the problem is this tool is not showing me EF Core 5 version in the selection. please refer to the below screenshot

A: EF Core 5 is no longer supported. If you really need support and are not able to update to EF Core 6 please contact me via the Github repository and I can provide an unsupported version of the tool that works with EF core 5.


text:
Q: CustomProvider on Symfony2 I have a custom UserProvider which works well but I cannot override function refreshUser.
When I refresh page I'm redirected to the UserProvider __construct function (default) then to the CustomProvider __construct function and after that to the refreshUser function of the default provider and not in my customProvider.
Why?


text:
Q: How can I get the limit of $(-1)^{2n} $ when $n$ goes to infinity How can I get the limit of $(-1)^{2n}$ when $n$ goes to infinity? I checked it with wolframalpha but the result is $e^{2i}$, $0$ to $\pi$, why $i$???

A: Note that $(-1)^{2n}=((-1)^2)^n=(1)^n$
As $n$ tends toward infinity, what happens now?


text:
Q: How to force specific order of the variables on the X axis? My question has to do with order of plot bars when using ggplot.
EffectNames = c("Pull Back(A)","Hook(B)","Peg(C)","AB","BC","AC","ABC")
Half_Effect = c(10.4, 6.5, 5.6, 1.6, 0.98, .77, .65)
paretoData = cbind(EffectNames, Half_Effect)
paretoData = as.data.frame(paretoData)

ggplot(paretoData, aes(x = EffectNames, y = Half_Effect)) +
    geom_bar(stat = "identity") +
    geom_text(aes(label = Half_Effect), vjust = 1.5, colour = "white")

Result:
Bar heights are in following order
1.6 0.65 0.77 0.98    6.5    5.6        10.4
 AB  ABC   AC   BC Hook(B) Peg(C) PullBack(A)

Bar heights are not in order seen in Half_Effect. How to force ordering of EffectNames to match descending order of Half_Effect? Can this be done in ggplot2?  Yes it can! See solution below.
EffectNames=c( "Pull Back(A)","Hook(B)", "Peg(C)","AB", "BC", "AC", "ABC")
Half_Effect=c( 10.4,6.5,5.6,1.6,0.98,.77,.65 )
paretoData=data.frame(EffectNames, Half_Effect)
paretoData
paretoData$EffectNames = factor(paretoData$EffectNames,
    levels=c("Pull Back(A)","Hook(B)", "Peg(C)","AB", "BC", "AC", "ABC"))
p=ggplot(paretoData, aes(x=EffectNames, y=Half_Effect)) +
geom_bar(stat="identity") +
geom_text(aes(label=Half_Effect), vjust=1.5, colour="white")
p

A: Elaborating eipi10's comment, the reordering of levels can by accomplished conveniently using Hadley's forcats package. In addition, the reordering can be done within the call to aes() instead of manipulating the underlying data. This offers additional flexibilty in finding a suitable graphical display.
Initial plot
paretoData <-  data.frame(
  EffectNames = c("Pull Back(A)", "Hook(B)", "Peg(C)", "AB", "BC", "AC", "ABC"),
  Half_Effect = c(10.4, 6.5, 5.6, 1.6, 0.98, .77, .65))

library(ggplot2)
p <- ggplot(paretoData, aes(x = EffectNames, y = Half_Effect)) +
  geom_bar(stat = "identity") +
  geom_text(aes(label = Half_Effect), vjust = 1.5, colour = "white")
p

Here, the order is alphabetical by default.
Reorder the levels in order of first appearance
library(forcats)
p + aes(x = fct_inorder(EffectNames))

*

*The factors are ordered by their first appearance in the vector (which probably was choosen intentionally by the OP with respect to the value of Half_Effect, so no real surprise here.)

*In this example, fct_inorder() saves us from typing the same stuff twice which would be required when explicitely specifying the levels in a call to factor.

*The plot p was modified by only changing the x aesthetics. The underlying data needn't to be touched.

Reorder the levels according to another variable
p + aes(x = fct_reorder(EffectNames, Half_Effect))

Here, the levels are ordered by increasing value of Half_Effect. We could have achieved the same effect by using reorder() from base R instead of fct_reorder().
To show the levels in decreasing order as requested by the OP we can do
p + aes(x = fct_reorder(EffectNames, Half_Effect, .desc = TRUE))

Note that reorder() has no explicit parameter to reverse the order so we would need to modify the controlling variable reorder(EffectNames, -Half_Effect).


text:
Q: Airflow None Schedule is not working. Tasks are still running automatically I have an airflow dag which i don't want to schedule. I'm using schedule_interval:None in my dag file but the dag is still running automatically once it is deployed.
Airflow version used: 2.1.0
Airflow Screenshot Attached.

I'm using the following python code in my dag file.
import os
import sys
import logging
import croniter
import datetime
from datetime import timedelta
from airflow import DAG
from airflow.operators.python_operator import PythonOperator

default_args = {
'owner': 'test-owner',
'depends_on_past': True,
'start_date': '2021-11-14',
'email': ['test.owner@gmail.com'],
'email_on_failure': True,
'email_on_retry': True,
'retries': 1,
'retry_delay': timedelta(minutes=5),
'schedule_interval':None,
 }

 dag = DAG(
'test-dag',
default_args=default_args,
description='test description'
)

def test_task(ds, **kwargs):
    print(kwargs)
    print(ds)

task = PythonOperator(
    task_id="test_task",
    provide_context=True,
    python_callable=test_task,
    op_kwargs={"image": "value"},
    dag=dag,
)

Also I have setup airflow env variables to the following:

*

*AIRFLOW__CORE__LOAD_EXAMPLES: "False"

*AIRFLOW__SCHEDULER__DAG_DIR_LIST_INTERVAL: 30

*AIRFLOW__CORE__DAGS_ARE_PAUSED_AT_CREATION: "False"

A: You've set schedule_interval in the default_args, which propagates the given dict as arguments to all operators in the DAG. However, schedule_interval is an argument on DAG, so you must set it there:
 dag = DAG(
'test-dag',
default_args=default_args,
description='test description',
schedule_interval=None,
)


text:
Q: MySql group by on second record I have this query...
SELECT gallery.* FROM gallery INNER JOIN company_details ON gallery.com_id = company_details.com_id GROUP BY gallery.com_id ORDER BY company_details.adv_src_pos

when i run this in phpmyadmin it will show group by with first record of group but i want group by with second record of group. i search for it in stackowerflow there are example also but i don't know how to do it with particular query? and above query shows in phpmyadmin is

A: I guess you'd just replace
GROUP BY gallery.com_id

with
GROUP BY company_details.com_id

But, isn't the resulting view the same? Please clarify what you mean by "second record."


text:
Q: Toolbar Search Suggestions Theming I'm trying to change search suggestions to "light theme".
I'm using appcompat-v7:22.2.0 library and read about new feature for customizing search view widget  (android.support.v7.widget.SearchView).
FIRST TRY SECTION
Toolbar
<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:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

Main Theme
<style name="Main.Theme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/red</item>
    <item name="colorPrimaryDark">@color/red_dark</item>
    <item name="searchViewStyle">@style/Main.Theme.SearchView</item>
</style>

SearchView Theme
<style name="Main.Theme.SearchView" parent="Widget.AppCompat.Light.SearchView">
    <item name="voiceIcon">@mipmap/test_icon</item>
</style>

This way I'm not able to affect the search view. To test it I'm changing the voice icon in the search view, and it doesn't change from default.
SECOND TRY SECTION
The second try was to override the overlay theme in toolbar:
Overlay Theme
<style name="Main.Theme.Overlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="searchViewStyle">@style/Main.Theme.SearchView</item>
</style>

This way I've some feedback, but I lose "material design", in particular I've the "old" hint icon and it's underlined.
My final aim is to change the search suggestion row background:
Suggestion row layout
<item name="suggestionRowLayout">@layout/my_custom_layout</item>

I think that I'm far away to accomplish this...can you help me?

A: This is how I am using my own search suggestions...
This is my CountriesFragment file that just show all country name in suggestions.
The trick here is that I am providing custom View to Suggestion list to show.
public class CountriesFragment extends Fragment {

    private boolean mSearchCheck;
    private SimpleCursorAdapter mAdapter;
    public static final String TEXT_FRAGMENT = "TEXT_FRAGMENT";
    public static final String CITY_NAME = "cityName";
    private LayoutInflater mInflater;
    private ViewGroup mainContainer;

    private static final String[] COUNTRIES = {
            "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica",
            "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados",
            "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegowina", "Botswana", "Bouvet Island", "Brazil",
            "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde",
            "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros",
            "Congo", "Congo, the Democratic Republic of the", "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia (Hrvatska)", "Cuba", "Cyprus",
            "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea",
            "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "France Metropolitan", "French Guiana",
            "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada",
            "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard and Mc Donald Islands", "Holy See (Vatican City State)",
            "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran (Islamic Republic of)", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",
            "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Kyrgyzstan",
            "Lao, People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg",
            "Macau", "Macedonia, The Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique",
            "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco",
            "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria",
            "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines",
            "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia",
            "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Seychelles", "Sierra Leone", "Singapore",
            "Slovakia (Slovak Republic)", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "Spain", "Sri Lanka",
            "St. Helena", "St. Pierre and Miquelon", "Sudan", "Suriname", "Svalbard and Jan Mayen Islands", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic",
            "Taiwan, Province of China", "Tajikistan", "Tanzania, United Republic of", "Thailand", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia",
            "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States",
            "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Virgin Islands (British)", "Virgin Islands (U.S.)",
            "Wallis and Futuna Islands", "Western Sahara", "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
    };

    public static CountriesFragment newInstance(String text) {
        CountriesFragment mFragment = new CountriesFragment();
        Bundle mBundle = new Bundle();
        mBundle.putString(TEXT_FRAGMENT, text);
        mFragment.setArguments(mBundle);
        return mFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loadHints();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_countries, container, false);
        mInflater = inflater;
        mainContainer = (ViewGroup) rootView.findViewById(R.id.container);
        //rootView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu, menu);

        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.menu_search));
        searchView.setQueryHint(this.getString(R.string.search));

        ((EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text))
                .setHintTextColor(getResources().getColor(R.color.nliveo_white));

        searchView.setSuggestionsAdapter(mAdapter);
        searchView.setOnQueryTextListener(onQuerySearchView);
        searchView.setOnSuggestionListener(onQuerySuggestion);

        menu.findItem(R.id.menu_add).setVisible(true);
        menu.findItem(R.id.menu_search).setVisible(true);

        mSearchCheck = false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case R.id.menu_add:
                addCountry();
                break;

            case R.id.menu_search:
                mSearchCheck = true;
                break;
        }
        return true;
    }

    private void addCountry() {
        final ViewGroup newView = (ViewGroup) mInflater.inflate(R.layout.country_row, mainContainer, false);
        final TextView countryName = (TextView) newView.findViewById(android.R.id.text1);
        countryName.setText(COUNTRIES[(int) (Math.random() * COUNTRIES.length)]);

        final Animation fadeIn = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_in);
        final Animation fadeOut = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_out);
        fadeIn.setFillAfter(false);
        fadeOut.setFillAfter(false);

        final ImageButton closeButton = (ImageButton) newView.findViewById(R.id.delete_button);
        closeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                newView.startAnimation(fadeOut);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mainContainer.removeView(newView);
                    }
                }, fadeOut.getDuration());
            }
        });

        mainContainer.addView(newView, 0);
        newView.startAnimation(fadeIn);
    }

    private SearchView.OnQueryTextListener onQuerySearchView = new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            mSearchCheck = false;
            return false;
        }

        @Override
        public boolean onQueryTextChange(String query) {
            if (mSearchCheck) {
                // implement your search here
                giveSuggestions(query);
            }
            return false;
        }
    };

    private void giveSuggestions(String query) {
        final MatrixCursor cursor = new MatrixCursor(new String[]{BaseColumns._ID, CITY_NAME});
        for (int i = 0; i < COUNTRIES.length; i++) {
            if (COUNTRIES[i].toLowerCase().contains(query.toLowerCase()))
                cursor.addRow(new Object[]{i, COUNTRIES[i]});
        }
        mAdapter.changeCursor(cursor);
    }

    private SearchView.OnSuggestionListener onQuerySuggestion = new SearchView.OnSuggestionListener() {
        @Override
        public boolean onSuggestionSelect(int position) {
            return false;
        }

        @Override
        public boolean onSuggestionClick(int position) {
            return false;
        }
    };

    private void loadHints() {
        final String[] from = new String[]{CITY_NAME};
        final int[] to = new int[]{android.R.id.text1};
        mAdapter = new SimpleCursorAdapter(getActivity(),
                R.layout.hint_row,
                null,
                from,
                to,
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
    }
}

here is the hint_row.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:background="@color/nliveo_green_colorPrimaryDark"
    android:textColor="@color/nliveo_white"
    android:paddingLeft="15dp"
    android:paddingRight="15dp"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"
    android:elevation="3dp"
    android:alpha="0.7" />

Simple menu file having SearchView. menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/menu_search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        android:icon="@mipmap/ic_search_white_24dp"
        app:showAsAction="ifRoom|collapseActionView"
        android:title="@string/search"/>
    <item
        android:id="@+id/menu_add"
        android:icon="@mipmap/ic_add_white_24dp"
        app:showAsAction="ifRoom"
        android:title="@string/add"/>

</menu>

I am getting this beautiful suggestions...

A: Suggestions is a dynamic list created by system and is not an activity. So you cannot apply light theme to it.
Instead you can customize suggestions to give it feel like a light theme by using style.
use this hint_row.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    style="@style/suggestionsTheme"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:gravity="center_vertical"
    android:text="demo"
    android:paddingLeft="15dp"
    android:paddingRight="15dp" />

And apply this style
<style name="suggestionsTheme" parent="TextAppearance.AppCompat.Light.SearchResult.Subtitle" >
        <item name="android:background">@android:color/white</item>
        <item name="android:textColor">@android:color/black</item>

Now I am getting this

You can give more style according to your need

A: I know I'm late, but I think it will be helpful for those, who are still searching for this issue. Suggested solution works if use the Toolbar. First you need to override theme of Toolbar in your styles like belov:
<style name="AppTheme.Toolbar" parent="Base.ThemeOverlay.AppCompat.Dark.ActionBar">
        <item name="searchViewStyle">@style/CustomSearchStyle</item>
    </style>

    <style name="CustomSearchStyle" parent="Base.Widget.AppCompat.SearchView.ActionBar">
        <item name="suggestionRowLayout">@layout/custom_search_layout</item>
    </style>

I used Dark theme, but I thinkg with Light this solution also will work. As you can see, I had overridden searchViewStyle of Toolbar's theme and suggestionRowLayout of SearchView, where I put my own layout:
<?xml version="1.0" encoding="utf-8"?>
<!--
/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
-->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="58dip"
    android:background="@color/white"
    style="@style/RtlOverlay.Widget.AppCompat.Search.DropDown">

    <!-- Icons come first in the layout, since their placement doesn't depend on
         the placement of the text views. -->
    <ImageView
        android:id="@android:id/icon1"
        android:layout_width="48dip"
        android:layout_height="48dip"
        android:scaleType="centerInside"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:tint="@color/black"
        android:visibility="invisible"
        style="@style/RtlOverlay.Widget.AppCompat.Search.DropDown.Icon1" />

    <ImageView
        android:id="@+id/edit_query"
        android:layout_width="48dip"
        android:layout_height="48dip"
        android:scaleType="centerInside"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:background="?attr/selectableItemBackground"
        android:visibility="gone"
        style="@style/RtlOverlay.Widget.AppCompat.Search.DropDown.Query" />

    <ImageView
        android:id="@android:id/icon2"
        android:layout_width="48dip"
        android:layout_height="48dip"
        android:scaleType="centerInside"
        android:layout_alignWithParentIfMissing="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:visibility="gone"
        style="@style/RtlOverlay.Widget.AppCompat.Search.DropDown.Icon2" />

    <!-- The subtitle comes before the title, since the height of the title depends on whether the
         subtitle is visible or gone. -->
    <TextView android:id="@android:id/text2"
        style="?android:attr/dropDownItemStyle"
        android:singleLine="true"
        android:layout_width="match_parent"
        android:textColor="@color/black"
        android:textSize="16sp"
        tools:text="id/text2"
        android:layout_height="29dip"
        android:paddingBottom="4dip"
        android:gravity="top"
        android:layout_alignWithParentIfMissing="true"
        android:layout_alignParentBottom="true"
        android:visibility="gone"
        />

    <!-- The title is placed above the subtitle, if there is one. If there is no
         subtitle, it fills the parent. -->
    <TextView android:id="@android:id/text1"
        style="?android:attr/dropDownItemStyle"
        android:singleLine="true"
        android:textColor="@color/black"
        tools:text="id/text1"
        android:textStyle="bold"
        android:textSize="18sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_above="@android:id/text2" />

</RelativeLayout>

This layout I took from original theme and added some changes to it to get what I need.
NOTE:
Unfortunately I didn't find the way how to change the standard recent icon, so I left it, because it was not critical for me.
So, to change the background color of the suggestion item, just add it to root RelativeLayout - in my case I changed it to white. You can put you own color.
I checked that for suggestions use only ImageView with id @android:id/icon1 and TextView with id @android:id/text1 so I added changes to these two. Because of in Dark theme default recent icon is white, I added android:tint="@color/black". TextView you can configure, like you want.
And the latest thing we need is to apply theme to our Toolbar:
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/AppTheme.Toolbar"
    app:titleTextColor="@color/white"
    app:navigationIcon="?attr/homeAsUpIndicator"
    app:theme="@style/AppTheme.Toolbar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    tools:elevation="4dp">

Here is a result of what I got:


text:
Q: Deploying a python package to AWS Lambda via Cloudformation, CodeBuild and CodePipeline I want to setup a CI/CD pipeline for my AWS infrastructure and a AWS Lambda function. The idea is to have everything in code, version-controlled and automated. I just want to git push to a repository and have CodePipeline take over from there, updating my infrastructure, running tests and, if successful, updating my Lambda function with the latest code.
I'm basing my CloudFormation template on this excellent example. It looks like this:
AWSTemplateFormatVersion: 2010-09-09
Description: playground pipeline 1
Parameters:
  SourceRepositoryName:
    Type: String
    Default: lambda-playground
  SourceBranchName:
    Type: String
    Default: master

Resources:
  ArtifactsBucket:
    Type: AWS::S3::Bucket
    DependsOn: CloudFormationRole
    DeletionPolicy: Delete
    Properties:
      BucketName: lambda-playground-artifacts

  CodeBuildRole:
    Type: AWS::IAM::Role
    DependsOn: CloudFormationRole
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - sts:AssumeRole
            Principal:
              Service:
                - codebuild.amazonaws.com
      Policies:
        - PolicyName: ServiceRole
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Sid: CloudWatchWriteLogsPolicy
                Effect: Allow
                Action:
                  - logs:CreateLogGroup
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Resource: '*'
              - Sid: CodeCommitPullPolicy
                Effect: Allow
                Action:
                  - codecommit:GitPull
                Resource: '*'
              - Sid: S3GetObjectPolicy
                Effect: Allow
                Action:
                  - s3:GetObject
                  - s3:GetObjectVersion
                Resource: '*'
              - Sid: S3PutObjectPolicy
                Effect: Allow
                Action:
                  - s3:PutObject
                Resource: '*'

  CodePipelineRole:
    Type: AWS::IAM::Role
    DependsOn: CloudFormationRole
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - sts:AssumeRole
            Principal:
              Service:
                - codepipeline.amazonaws.com
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AdministratorAccess

  CloudFormationRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - sts:AssumeRole
            Principal:
              Service:
                - cloudformation.amazonaws.com
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AdministratorAccess

  CodeCommitRepository:
    Type: AWS::CodeCommit::Repository
    Properties:
      RepositoryName: !Ref SourceRepositoryName

  CodeBuildProject:
    Type: AWS::CodeBuild::Project
    DependsOn: CloudFormationRole
    Properties:
      Description: A playground of Lambda
      Artifacts:
        Type: CODEPIPELINE
      Environment:
        ComputeType: BUILD_GENERAL1_SMALL
        Image: aws/codebuild/python:2.7.12
        Type: LINUX_CONTAINER
      Name: lambda-playground
      ServiceRole: !GetAtt CodeBuildRole.Arn
      Source:
        Type: CODEPIPELINE
      TimeoutInMinutes: 5

  CodePipeline:
    Type: AWS::CodePipeline::Pipeline
    Properties:
      ArtifactStore:
        Type: S3
        Location: !Ref ArtifactsBucket
      Name: !Ref AWS::StackName
      RestartExecutionOnUpdate: true
      RoleArn: !GetAtt CodePipelineRole.Arn
      Stages:
        - Name: Source
          Actions:
            - Name: Source
              ActionTypeId:
                Category: Source
                Owner: AWS
                Provider: CodeCommit
                Version: 1
              Configuration:
                RepositoryName: !Ref SourceRepositoryName
                BranchName: !Ref SourceBranchName
              OutputArtifacts:
                - Name: SourceOutput
        - Name: PipelineDeploy
          Actions:
            - Name: UpdatePipeline
              ActionTypeId:
                Category: Deploy
                Owner: AWS
                Provider: CloudFormation
                Version: 1
              Configuration:
                ActionMode: CREATE_UPDATE
                Capabilities: CAPABILITY_IAM
                RoleArn: !GetAtt CloudFormationRole.Arn
                StackName: !Ref AWS::StackName
                TemplatePath: SourceOutput::infra.yml
              InputArtifacts:
                - Name: SourceOutput
        - Name: Build
          Actions:
            - Name: BuildAndTest
              ActionTypeId:
                Category: Build
                Owner: AWS
                Provider: CodeBuild
                Version: 1
              Configuration:
                ProjectName: !Ref CodeBuildProject
              InputArtifacts:
                - Name: SourceOutput
              OutputArtifacts:
                - Name: BuildOutput

  LambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        S3Bucket: !Ref ArtifactsBucket
        S3Key: !Ref BuildOutput # DOES NOT WORK
      FunctionName: playground-fc
      Handler: src.main.handler
      # TODO: Role: foo
      Runtime: python2.7

Outputs:
  ArtifactsBucketURL:
    Description: Artifacts bucket URL
    Value: !GetAtt ArtifactsBucket.WebsiteURL
  RepositoryURL:
    Description: SSH URL of the repository
    Value: !GetAtt CodeCommitRepository.CloneUrlSsh

So I have a CodePipeline with 3 stages - Source, which grabs code from a CodeCommit repo, PipelineDeploy, which updates my CloudFormation stack if necessary and Build, which runs the configured CodeBuild project.
My buildspec.yml is here:
version: 0.1

phases:
  install:
    commands:
      - pip install -r requirements.txt -t lib
  pre_build:
    commands:
      - python lib/pytest.py src
artifacts:
  type: zip
  files:
    - src/**/*
    - lib/**/*

It just installs the necessary libraries, runs the tests via pytest and creates a deployment zip. This zip file is then the OutputArtifact of the Build stage and gets stored in the ArtifactsBucket. However, each time, it gets a unique name (e.g. dfVV6Uh), which makes sense, but I don't know how to reference it in the LambdaFunction -> Properties -> Code -> S3Key field.
So my question is, how can I create a stack/pipeline, that after doing all the steps, will deploy the latest version to my AWS Lambda function? Is there a way to maybe use CodeDeploy to do this? What is the best practice here?

A: You can use a Parameter Override with Fn::GetArtifactAtt and the ObjectKey attribute to dynamically provide the the name of the artifact .zip generated by AWS CodePipeline to your CloudFormation deploy action.
Using your example, the configuration for your UpdatePipeline CloudFormation deploy action would look something like this:
Configuration:
  ActionMode: CREATE_UPDATE
  Capabilities: CAPABILITY_IAM
  RoleArn: !GetAtt CloudFormationRole.Arn
  StackName: !Ref AWS::StackName
  TemplatePath: SourceOutput::infra.yml
  ParameterOverrides:
    {
      "LambdaKey" : { "Fn::GetArtifactAtt" : ["LambdaFunctionSource", "ObjectKey"]}
    }
InputArtifacts:
- Name: SourceOutput
- Name: BuildOutput

Then, declare and then reference the LambdaKey Parameter within your CloudFormation stack template:
Parameters:
  LambdaKey:
    Type: String
  # ...
Resources:
  LambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        S3Bucket: !Ref ArtifactsBucket
        S3Key: !Ref LambdaKey
      # ...

A: There is an example of how to do achieve something similar (deploying lambda functions via CodePipeline/CodeBuild).
http://docs.aws.amazon.com/lambda/latest/dg/automating-deployment.html
This example is for lambda functions written in NodeJS, but the basic idea is the same. You use CloudFormation to deploy/update your lambda functions after you've build your artifact via CodeBuild and let CodePipeline manage artifact propagation within stages.
Let me know if this helps.


text:
Q: Why is arr = [] faster than arr = new Array? I ran this code and got the below result. I curious to know why [] is faster?
console.time('using[]')
for(var i=0; i<200000; i++){var arr = []};
console.timeEnd('using[]')

console.time('using new')
for(var i=0; i<200000; i++){var arr = new Array};
console.timeEnd('using new')

*

*using []: 299ms

*using new: 363ms
Thanks to Raynos here is a benchmark of this code and some more possible way to define a variable.

A: One possible reason is that new Array requires a name lookup on Array (you can have a variable with that name in scope), whereas [] does not.

A: Good question.
The first example is called an array literal. It is the prefered way to create arrays among many developers. It could be that the performance difference is caused by checking the arguments of the new Array() call and then creating the object, while the literal creates an array directly.
The relatively small difference in performance supports this point I think. You could do the same test with the Object and object literal {} by the way.

A: Also, interesting, if the length of the array is known in advance (elements will be added just after creation), the use of an array constructor with a specified length is much faster on recent Google Chrome 70+.

*

*"new Array( %ARR_LENGTH% )" – 100% (faster)!

*"[]" – 160-170% (slower)

The test can be found here - https://jsperf.com/small-arr-init-with-known-length-brackets-vs-new-array/2
Note: this result tested on Google Chrome v.70+; in the Firefox v.70 and IE both variants almost equal.

A: Further expanding on previous answers...
From a general compilers perspective and disregarding VM-specific optimizations:
First, we go through the lexical analysis phase where we tokenize the code.
By way of example, the following tokens may be produced:
[]: ARRAY_INIT
[1]: ARRAY_INIT (NUMBER)
[1, foo]: ARRAY_INIT (NUMBER, IDENTIFIER)
new Array: NEW, IDENTIFIER
new Array(): NEW, IDENTIFIER, CALL
new Array(5): NEW, IDENTIFIER, CALL (NUMBER)
new Array(5,4): NEW, IDENTIFIER, CALL (NUMBER, NUMBER)
new Array(5, foo): NEW, IDENTIFIER, CALL (NUMBER, IDENTIFIER)

Hopefully this should provide you a sufficient visualization so you can understand how much more (or less) processing is required.

*

*Based on the above tokens, we know as a fact ARRAY_INIT will always produce an array.  We therefore simply create an array and populate it.  As far as ambiguity, the lexical analysis stage has already distinguished ARRAY_INIT from an object property accessor (e.g. obj[foo]) or brackets inside strings/regex literals (e.g. "foo[]bar" or /[]/)

*This is miniscule, but we also have more tokens with new Array.  Furthermore, it's not entirely clear yet that we simply want to create an array.  We see the "new" token, but "new" what?  We then see the IDENTIFIER token which signifies we want a new "Array," but JavaScript VM's generally do not distinguish an IDENTIFIER token and tokens for "native global objects."  Therefore...

*We have to look up the scope chain each time we encounter an IDENTIFIER token.  Javascript VMs contain an "Activation object" for each execution context which may contain the "arguments" object, locally defined variables, etc.  If we cannot find it in the Activation object, we begin looking up the scope chain until we reach the global scope.  If nothing is found, we throw a ReferenceError.

*Once we've located the variable declaration, we invoke the constructor.  new Array is an implicit function call, and the rule of thumb is that function calls are slower during execution (hence why static C/C++ compilers allow "function inlining" - which JS JIT engines such as SpiderMonkey have to do on-the-fly)

*The Array constructor is overloaded.  The Array constructor is implemented as native code so it provides some performance enhancements, but it still needs to check for arguments length and act accordingly.  Moreover, in the event only one argument is supplied, we need to further check the type of the argument.  new Array("foo") produces ["foo"] where as new Array(1) produces [undefined]
So to simplify it all: with array literals, the VM knows we want an array; with new Array, the VM needs to use extra CPU cycles to figure out what new Array actually does.

A: This would make some sense

Objects literals enable us to write code that supports lots of
  features yet still make it a relatively straightforward for the
  implementers of our code. No need to invoke constructors directly or
  maintain the correct order of arguments passed to functions, etc.

http://www.dyn-web.com/tutorials/obj_lit.php


text:
Q: How to get everything before a character and x amount after? It has been trial and error and can't seem to get what I want.
I am accessing an API to get some info. Unfortunately it's the only API to get that info and to do it, it downloads a binary content of a file and names it:
folder\filename.whatever
i.e. test\purpleMonkeyTest.docx
There is a bunch more info that comes in from the call but there is this line:
Saved the binary content to: /home/user/python/test\purpleMonkeyTest.docx

Some of the files have " or other special characters so I can't just get the file name and delete it as part of the script, since I won't know what to escape.
So my goal here is to strip the line and get:
/home/user/python/test\purpleMonkeyTest.docx

then get only:
/home/user/python/test\pu

then:
os.remove "/home/user/python/test\pu"*

I'm thinking that a wildcard should work for all, unless there is a better way to do it. All files saved have the character \ in them so I've got to the point where I'm getting everything prior to the \ but I want one or two characters after that as well.
Here's what I've tried:
def fileName(itemID):
    import fnmatch
    details = itemDetails(itemID, True) # get item id and file details
    filepath = matchPattern((details), 'Saved the binary content to: *')
    filepath = (filepath).split('\\')[0]
    print(filepath)
    #os.remove(re.escape(filepath))
    return (matchPattern((details), 'Binary component: *'))

def matchPattern(details, pattern):
    import fnmatch
    return (fnmatch.filter((details), pattern)[0].split(": " ,1)[1])

Output:
/home/user/python/test
purpleMonkeyTest.docx

I do want the file name for later: that's actually the main goal. The API downloads the damn file automatically though.
EDIT:
Answer below works for getting the chars I want. Os remove is not removing the file though.
OSError: [Errno 2] No such file or directory: '/home/user/python/test\\Re*'

Managed to get it to work using glob, I guess os.remove doesn't support Wilds.
    files = glob.glob((filepath)+"*")
    for file in files:
     os.remove(file)

Thanks for the help!!

A: As far as I understand your question you would like to retrieve 2 parts - everything between first / and \ with 2 chars afterwards and then everything after \:
str = "Saved the binary content to: /home/user/python/test\purpleMonkeyTest.docx"

print (str[str.index("/"):str.rindex("\\") + 3])
print (str[str.rindex("\\") + 1:])

Output

/home/user/python/test\pu
purpleMonkeyTest.docx


text:
Q: How to change UIImageView image using SwipeGestureRecognizer? Hello everyone I have a UIViewController and UIImageView and i have a SwipeGestureRecognizer in it. So if the user swipe left or right it will change the UIImageView image.So far its working. I cannot use  a UIScrollView the size of one of the images, with paging enabled.I want to achieve the effect of drag and see part the the next UIImageView as in the UIScrollView of images would do.

A: Simple answer :
Add two gesture for the image view and place one count variable, toggle the count variable based on the swipe and no. of the images. Finally change the image based on the count.
Use this code its working fine and simple too.
- (void)addAnimationPresentToView:(UIView *)viewTobeAnimated
{
    CATransition *transition = [CATransition animation];
    transition.duration = 0.30;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    [transition setValue:@"IntroSwipeIn" forKey:@"IntroAnimation"];
    transition.fillMode=kCAFillModeForwards;
    transition.type = kCATransitionPush;
    transition.subtype =kCATransitionFromRight;
    [viewTobeAnimated.layer addAnimation:transition forKey:nil];

}

- (void)addAnimationPresentToViewOut:(UIView *)viewTobeAnimated
{
    CATransition *transition = [CATransition animation];
    transition.duration = 0.30;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    [transition setValue:@"IntroSwipeIn" forKey:@"IntroAnimation"];
    transition.fillMode=kCAFillModeForwards;
    transition.type = kCATransitionPush;
    transition.subtype =kCATransitionFromLeft;
    [viewTobeAnimated.layer addAnimation:transition forKey:nil];

}
                - (void)viewDidLoad
                {
                    [super viewDidLoad];
                    count = 0;
                    // Do any additional setup after loading the view from its nib.
                    [self.imageViewSwipe setUserInteractionEnabled:YES];
                    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
                    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeRight:)];

                    // Setting the swipe direction.
                    [swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
                    [swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];

                    // Adding the swipe gesture on image view
                    [self.imageViewSwipe addGestureRecognizer:swipeLeft];
                    [self.imageViewSwipe addGestureRecognizer:swipeRight];

                }
                -(void)changeImage
                {
                    switch (count) {
                        case 1:
                            self.imageViewSwipe.image = [UIImage imageNamed:@"Screen Shot 2013-09-17 at 10.57.51 AM.png"];
                            break;
                        case 2:
                            self.imageViewSwipe.image = [UIImage imageNamed:@"Screen Shot 2013-09-17 at 10.58.04 AM.png"];
                            break;
                        case 3:
                            self.imageViewSwipe.image = [UIImage imageNamed:@"Screen Shot 2013-09-17 at 10.58.00 AM.png"];
                            break;

                        default:
                            break;
                    }
                }
                -(void)handleSwipe:(id)sender
                {
                 if(count < 4)
                 {
                     count++;
                     UIImageView *moveIMageView = self.imageViewSwipe;
                     [self addAnimationPresentToView:moveIMageView];
                     [self changeImage];
                 }

                }
                -(void)handleSwipeRight:(id)sender
                {
                    if(count>0)
                    {
                        count--;
                  UIImageView *moveIMageView = self.imageViewSwipe;
                 [self addAnimationPresentToViewOut:moveIMageView];
                        [self changeImage];
                    }

                }
                    -(void)handleSwipe:(id)sender
                    {
                     if(count < 4)
                     {
                         count++;
                         [self changeImage];
                     }

                    }
                    -(void)handleSwipeRight:(id)sender
                    {
                        if(count>0)
                        {
                            count--;
                            [self changeImage];
                        }

                    }

A: Add scroollview to mainview(set frame appropriately)
[mainview addSubview:scr];

write a method like:
- (void)setupScrollView:(UIScrollView*)scrMain {
}

Then in viewDidLoad pass scrollview to method,
 [self setupScrollView:scr];

- (void)setupScrollView:(UIScrollView*)scrMain {
    // we have 10 images here.
    // we will add all images into a scrollView & set the appropriate size.

    for (int i=1; i<=5; i++) {
        // create image
//        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"sti%02i.png",i]];
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"sti%02i.png",i]];
        // create imageView
//        NSLog(@"===============>%d",i);
        UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake((i-1)*scrMain.frame.size.width, 0, scrMain.frame.size.width, scrMain.frame.size.height)];
        // set scale to fill
        imgV.contentMode=UIViewContentModeScaleToFill;
        // set image
        [imgV setImage:image];
        // apply tag to access in future
        imgV.tag=i+1;
        // add to scrollView
        [scrMain addSubview:imgV];
    }
    // set the content size to 10 image width
    [scrMain setContentSize:CGSizeMake(scrMain.frame.size.width*5, scrMain.frame.size.height)];
    // enable timer after each 2 seconds for scrolling.
    // [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:nil userInfo:nil repeats:YES];
}

It let you move in both the directions manually.

A: *You can try with something imageView.layer to give some animation effect.
*

A: I think the best is use UIPanGestureRecognizer:
UIPanGestureRecognizer * pan1 = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(moveObject:)];
pan1.minimumNumberOfTouches = 1;
[image1 addGestureRecognizer:pan1];

-(void)moveObject:(UIPanGestureRecognizer *)pan;
{
 image1.center = [pan locationInView:image1.superview];
}

when you start dragging check the somehow the direction. if the direction is left to right, add the "before" image to the screen with -image.width , and in the move method, move this imageBefore.center = [pan locationInView:image1.superview]; too. If the direction is right to left, add the "next" image to the scree with +screensize+image.width, and int he move method, move this imageNext.center = [pan locationInView:image1.superview]; too.
I haven't tried this, but i think it should work. I hope it helps
EDIT:
I found for you how to detect the direction:
-(void)moveObject:(UIPanGestureRecognizer *)pan;
{

    CGPoint vel = [pan velocityInView:self.view];
    if (vel.x > 0)
    {
        // user dragged towards the right
        counter++;
    }
    else
    {
        // user dragged towards the left
        counter--;
    }
}

A: -(void)panTableView:(UISwipeGestureRecognizer *)pan{
    if (pan.state==UIGestureRecognizerStateEnded) {
        int curr=currentPage;

        if (pan==self.panGestureLeft)
        {
            // user dragged towards the right

                CATransition *transition = [CATransition animation];
                transition.duration = 0.35;
                transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
                transition.type = kCATransitionPush;
                transition.subtype =kCATransitionFromRight;
                transition.delegate = self;
                [scrollview.layer addAnimation:transition forKey:nil];

        }
        else if (pan==self.panGestureRight)
        {
            // user dragged towards the left

                CATransition *transition = [CATransition animation];
                transition.duration = 0.35;
                transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
                transition.type = kCATransitionPush;
                transition.subtype =kCATransitionFromLeft;
                transition.delegate = self;
                [scrollview.layer addAnimation:transition forKey:nil];

        }

}

}

A: Implement Horizontal Table Scrolling
Create a TableView and transform the table
self.horizontalTableView.transform = CGAffineTransformMakeRotation(-M_PI * 0.5);

Then, you apply the transform in reverse on the content inside the cell.
CGAffineTransformMakeRotation(M_PI * 0.5)

If you want, you can then put it into another TableView inside a custom UITableViewCell, and have a vertical table of horizontal tables.
You get all the benefits of Native Scrolling
See this Tutorial:
http://www.raywenderlich.com/4723/how-to-make-an-interface-with-horizontal-tables-like-the-pulse-news-app-part-2


text:
Q: COBOL (.cob) file cannot open due to unknown encoding So I was helping my dad's small business in Taiwan migrate old COBOL application from a very old XP computer to a Windows 11 computer.
I copied all the COBOL files and installed OpenCobolIDE on the new computer.
However, the IDE cannot open the file as the encoding is not correct.
Is there a simple fix? I spent the whole day playing with different IDEs but in vain. As I have zero knowledge of COBOL, if it is too difficult to migrate, I will probably write a complete new system for my dad. The one who wrote it has already retired and no one took over his job. Thank you!
................
Here are the details. The main file is TNMENU.COB. On the old computer, it was run by RM/COBOL, and the interface looks like
this (it basically a menu of options)
On the new computer, the IDE
cannot read the file.
The hex values are given
here.
I tried different IDEs, but all showed bad characters.

A: As you found out: There are a lot of hex values in your ".COB", so (as jimcastro) pointed out, those are not COBOL source files but compiled sources in a format that is loaded/executed from the old environment's runtime RM/COBOL.
To move these to the new environment: as long as the RM/COBOL runtime is 32bit: just copy it along and use it on the new computer.
If the runtime is 16bit it won't work on newer environments directly, you could try with an emulator or virtual machine (DOSBOX or FreeDOS running in VirtualBox for example).
As an alternative: if the COBOL source code is available then you could recompile it with GnuCOBOL using -std=rm-strict, allowing you to run in in 64 (or 32) bit on nearly every operating system.


text:
Q: How do I loop through criteria in Advanced Filter? I'm trying to filter a table based on a criteria and copy&paste the result to a different sheet.
Basically I have a huge amount of data stored in one sheet("Department ERP") and I need to filter column("GLO_MASS_LINE") based on a criteria, then copy&paste each of the results to a different sheet.
Since AutoFilter and subsequent copy&paste option is too slow, I decided to go for Advanced Filtering. I prepared a huge range of sheets (from sheets 11 to 38), where I want to put details for specific costs (for example, I want to filter the table stored in "Department ERP") for Employee education and copy&paste the result into sheet("EDUC") = sheet no. 11), then I want to filter "Events/Relationship marketing" and copy&paste the result to sheet("ERMA"), etc etc...)
Sub GetData2()
Dim wbData As Range

Dim wbCriteria As Range

Dim wbExtract As Range

Dim i As Integer

Dim GLO2 As Integer

GLO2 = 21

i = 11
Set wbData = Worksheets("Department ERP").Range("A:P")

For GLO2 = 21 To 48
Set wbCriteria = Worksheets("Inputs").Range(Cells(4, GLO2), Cells(5, GLO2))
Worksheets(i).Activate
         wbData.CurrentRegion.AdvancedFilter Action:=xlFilterCopy, _
        CriteriaRange:=wbCriteria, CopyToRange:=Worksheets(i).Range("A2"), Unique:=False

 i = i + 1

  Next GLO2

End Sub

The problem I am now facing is that the code loops through sheets and filters the data, but only for the first criteria (the criteria is still the first one "Employee education").
Would you help me find the problem here? Any help would be highly appreciated.

A: I think this is what you want.
Sub Copy_With_AutoFilter1()
'Note: This macro use the function LastRow
    Dim My_Range As Range
    Dim CalcMode As Long
    Dim ViewMode As Long
    Dim FilterCriteria As String
    Dim CCount As Long
    Dim WSNew As Worksheet
    Dim sheetName As String
    Dim rng As Range

    'Set filter range on ActiveSheet: A1 is the top left cell of your filter range
    'and the header of the first column, D is the last column in the filter range.
    'You can also add the sheet name to the code like this :
    'Worksheets("Sheet1").Range("A1:D" & LastRow(Worksheets("Sheet1")))
    'No need that the sheet is active then when you run the macro when you use this.
    Set My_Range = Range("A1:D" & LastRow(ActiveSheet))
    My_Range.Parent.Select

    If ActiveWorkbook.ProtectStructure = True Or _
       My_Range.Parent.ProtectContents = True Then
        MsgBox "Sorry, not working when the workbook or worksheet is protected", _
               vbOKOnly, "Copy to new worksheet"
        Exit Sub
    End If

    'Change ScreenUpdating, Calculation, EnableEvents, ....
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    ActiveSheet.DisplayPageBreaks = False

    'Firstly, remove the AutoFilter
    My_Range.Parent.AutoFilterMode = False

    'Filter and set the filter field and the filter criteria :
    'This example filter on the first column in the range (change the field if needed)
    'In this case the range starts in A so Field 1 is column A, 2 = column B, ......
    'Use "<>Netherlands" as criteria if you want the opposite
    My_Range.AutoFilter Field:=1, Criteria1:="=Netherlands"

    'If you want to filter on a cell value you can use this, use "<>" for the opposite
    'This example uses the activecell value
    'My_Range.AutoFilter Field:=1, Criteria1:="=" & ActiveCell.Value

    'This will use the cell value from A2 as criteria
    'My_Range.AutoFilter Field:=1, Criteria1:="=" & Range("A2").Value

    ''If you want to filter on a Inputbox value use this
    'FilterCriteria = InputBox("What text do you want to filter on?", _
     '                              "Enter the filter item.")
    'My_Range.AutoFilter Field:=1, Criteria1:="=" & FilterCriteria

    'Check if there are not more then 8192 areas(limit of areas that Excel can copy)
    CCount = 0
    On Error Resume Next
    CCount = My_Range.Columns(1).SpecialCells(xlCellTypeVisible).Areas(1).Cells.Count
    On Error GoTo 0
    If CCount = 0 Then
        MsgBox "There are more than 8192 areas:" _
             & vbNewLine & "It is not possible to copy the visible data." _
             & vbNewLine & "Tip: Sort your data before you use this macro.", _
               vbOKOnly, "Copy to worksheet"
    Else
        'Add a new Worksheet
        Set WSNew = Worksheets.Add(After:=Sheets(ActiveSheet.Index))

        'Ask for the Worksheet name
        sheetName = InputBox("What is the name of the new worksheet?", _
                             "Name the New Sheet")

        On Error Resume Next
        WSNew.Name = sheetName
        If Err.Number > 0 Then
            MsgBox "Change the name of sheet : " & WSNew.Name & _
                 " manually after the macro is ready. The sheet name" & _
                 " you fill in already exists or you use characters" & _
                 " that are not allowed in a sheet name."
            Err.Clear
        End If
        On Error GoTo 0

        'Copy/paste the visible data to the new worksheet
        My_Range.Parent.AutoFilter.Range.Copy
        With WSNew.Range("A1")
            ' Paste:=8 will copy the columnwidth in Excel 2000 and higher
            ' Remove this line if you use Excel 97
            .PasteSpecial Paste:=8
            .PasteSpecial xlPasteValues
            .PasteSpecial xlPasteFormats
            Application.CutCopyMode = False
            .Select
        End With

        ' If you want to delete the rows that you copy, also use this
        ' With My_Range.Parent.AutoFilter.Range
        '     On Error Resume Next
        '     Set rng = .Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count) _
        '               .SpecialCells(xlCellTypeVisible)
        '     On Error GoTo 0
        '     If Not rng Is Nothing Then rng.EntireRow.Delete
        ' End With

    End If

    'Close AutoFilter
    My_Range.Parent.AutoFilterMode = False

    'Restore ScreenUpdating, Calculation, EnableEvents, ....
    My_Range.Parent.Select
    ActiveWindow.View = ViewMode
    If Not WSNew Is Nothing Then WSNew.Select
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With

End Sub

Function LastRow(sh As Worksheet)
    On Error Resume Next
    LastRow = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlValues, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
    On Error GoTo 0
End Function

See the link below for additional ideas.
https://www.rondebruin.nl/win/s3/win006.htm


text:
Q: Use gdal installed with QGIS in Python Windows 7 On my Windows 7 PC, I installed QGIS 2.18 and gdal is part of this Installation.   How do I connect Python 3.6 to gdal?

A: I succeeded by following this:
https://pythongisandstuff.wordpress.com/2016/04/13/installing-gdal-ogr-for-python-on-windows/


text:
Q: SSRS How to keep drill-down from showing up in the Web Service URL I have what seems like a very simple problem.  We have built a project with 3 reports using SSRS (SQL Server Reporting Services) 2012.  One main report and 2 drill-down reports that are called from the main project.  Something like this:

*

*Main Report

*Details 1

*Details 2

When Details 1 or Details 2 are called with the necessary parameters from the Main Report, everything works correctly.  The problem is the when I go to the Web Service URL which is where the reports are published, the users see the 2 drill-down reports that are not relevant when run by themselves.  What I need to try to do is hide the Details 1 and Details 2 from the Web Service URL so that they don't show up.  I can't figure out how/where to do that.
Any suggestions would be appreciated.
George

A: The Web services URL is also known as the Reporting Services Interface and usually has an address similar to http://servername/reportserver/. This interface is not intended for user access. You can't hide reports in this interface.
The Report Manager, default URL of http://server/reports/, is intended for user access. In the properties for reports, data sources, and folders you will find a check box labelled "Hide in tile view." This is as close as you can get to what you are describing without building your own front end.


text:
Q: ReferenceError: window is not defined in React I installed "react-speech" package for my application to build text to speech functionality. But while importing the package I'm getting the following error. I did enough googling to resolve this issue but unable to do so. Any help is much appreciated.
Error:
ReferenceError: window is not defined

    at new SpeakTTS (/Users/moharja/Project/React-master/node_modules/speak-tts/lib/speak-tts.js:22:48)

    at Object.<anonymous> (/Users/moharja/Project/React-master/src/components/Judgement/Landing/RightBar/Top/top.component.jsx:24:16)

    at Module._compile (internal/modules/cjs/loader.js:1201:30)

    at Module._compile (/Users/moharja/Project/React-master/node_modules/pirates/lib/index.js:99:24)

    at Module._extensions..js (internal/modules/cjs/loader.js:1221:10)

    at Object.newLoader [as .jsx] (/Users/moharja/Project/React-master/node_modules/pirates/lib/index.js:104:7)

    at Module.load (internal/modules/cjs/loader.js:1050:32)

    at Function.Module._load (internal/modules/cjs/loader.js:938:14)

    at Module.require (internal/modules/cjs/loader.js:1090:19)

    at require (internal/modules/cjs/helpers.js:75:18)

npm ERR! code ELIFECYCLE

npm ERR! errno 1

npm ERR! lm-suite-react@0.1.0 start: `rimraf build && webpack --mode production --progress --profile --color && node index.js`

npm ERR! Exit status 1

npm ERR!

npm ERR! Failed at the lm-suite-react@0.1.0 start script.

npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:

npm ERR!     /Users/moharja/.npm/_logs/2020-10-19T17_30_09_085Z-debug.log `

Note: I tried to use different packages too instead of "react-speech". But the same error is occurring.

A: This library is not compatible with SSR (Server Side Rendering).
I guess you are trying to do that with, webpack.
if (typeof window === 'undefined') {
  global.window = {}
}

I guess this might not throw any error, remember you have to declared this before you import the library.

A: I don't know anything about the react-speech package. But I encountered something similar while trying to bundle one of my modules for browser using webpack (bundle process runs on node and window is undefined in that context).
This is what I used:
let win
try {
  win = window
} catch (error) {
  // suppress the Reference error and assign an empty object to win
  // this should not be reachable in actual browser as window
  // will be defined in that context.

  win = {}
}

We are doing this just so that webpack builds the module without throwing.
...
// replace window with win

// window.fetch(...)
win.fetch(...)

Since you are trying to use a library maintained by someone else, you could either try to build it on your own, or you could raise an issue for the package maintainers.