text:
Q: React Native - Change background color in tabnavigator dynamically i want to change my tab navigator background color dynamically in based on my API response so below is my code
_TabNavigator.js
const MyTabnav = TabNavigator({
ScreenOne: {
    screen: ({ navigation, screenProps }) => <ScreenOneNav screenProps={{ tabbarNavigation: navigation, ...screenProps }} onNavigationStateChange={null} />,
    navigationOptions: {
        tabBarLabel: 'ScreenOne',
        tabBarIcon: ({ tintColor }) => (
            <View style={[styles.tabViewBox]}>
                 <Text style={[styles.tabText, { color: tintColor }]}>ScreenOne</Text>
            </View>
        )
    }
},
ScreenTwo: {
    screen: ({ navigation, screenProps }) => <ScreenOneNav screenProps={{ tabbarNavigation: navigation, ...screenProps, }} onNavigationStateChange={null} />,
    navigationOptions: {
        tabBarLabel: 'ScreenOne',
        tabBarIcon: ({ tintColor }) => (
            <View style={[styles.tabViewBox]}>
                <Text style={[styles.tabText, { color: tintColor }]}>ScreenTwo</Text>
            </View>
        )
    }
},
ScreenThree: {
    screen: ({ navigation, screenProps }) => <StockNotificationNav screenProps={{ tabbarNavigation: navigation, ...screenProps }} onNavigationStateChange={null} />,
    navigationOptions: {
        tabBarLabel: 'Notifications',
        tabBarIcon: ({ tintColor }) => (
            <View style={[styles.tabViewBox]}>
                 <Text style={[styles.tabText, { color: tintColor }]}>ScreenThree</Text>
            </View>
        )
    }
},
},
 {

    tabBarOptions: {

        style: {
            backgroundColor: white,
            height: 55,
            borderTopColor: 'transparent',
            borderTopWidth: 1,
            paddingRight: 10,
            paddingLeft: 10,
            borderTopWidth: 1,
            borderTopColor: grayPlaceHolder
        },
        showLabel: false,
        showIcon : true,
    },
    tabBarComponent : TabBarBottom,

    initialRouteName: 'ScreenTwo',
    tabBarPosition: 'bottom',
    animationEnabled: false,
    swipeEnabled: false
}, []);

var styles = StyleSheet.create({
tabText: {
    fontSize: 10,
    fontWeight: "600",
    flex: 4,
},
tabViewBox: {
    flex: 1,
    alignItems: "center",
},
 tabIcon: {
    flex: 5,
    alignSelf: "center",
    marginTop: 10
  },
});
export default StocksTabNav;

I want to change my tabnavigtor background color in my ScreenTwo.js file which include API response code on it as per that it tabnavigator background color (backgroundColor) should change as black or white as per API response so how can i achieve this? your all suggestions are appreciable
After update code as per Rahul suggests give below warning message

A: what you can do is make one custom tabBar component and using javaScript immutability concept you can override style of tabBarOptions.
     const MyTabnav = TabNavigator({ScreenOne: {
        screen: ({ navigation, screenProps }) => <ScreenOneNav screenProps={{ tabbarNavigation: navigation, ...screenProps }} onNavigationStateChange={null} />,
        navigationOptions: {
            tabBarLabel: 'ScreenOne',
            tabBarIcon: ({ tintColor }) => (
                <View style={[styles.tabViewBox]}>
                     <Text style={[styles.tabText, { color: tintColor }]}>ScreenOne</Text>
                </View>
            )
        }
    },
    ScreenTwo: {
        screen: ({ navigation, screenProps }) => <ScreenOneNav screenProps={{ tabbarNavigation: navigation, ...screenProps, }} onNavigationStateChange={null} />,
        navigationOptions: {
            tabBarLabel: 'ScreenOne',
            tabBarIcon: ({ tintColor }) => (
                <View style={[styles.tabViewBox]}>
                    <Text style={[styles.tabText, { color: tintColor }]}>ScreenTwo</Text>
                </View>
            )
        }
    },
    ScreenThree: {
        screen: ({ navigation, screenProps }) => <StockNotificationNav screenProps={{ tabbarNavigation: navigation, ...screenProps }} onNavigationStateChange={null} />,
        navigationOptions: {
            tabBarLabel: 'Notifications',
            tabBarIcon: ({ tintColor }) => (
                <View style={[styles.tabViewBox]}>
                     <Text style={[styles.tabText, { color: tintColor }]}>ScreenThree</Text>
                </View>
            )
        }
    },
    },
     {

        tabBarOptions: {

            style: {
                backgroundColor: white,
                height: 55,
                borderTopColor: 'transparent',
                borderTopWidth: 1,
                paddingRight: 10,
                paddingLeft: 10,
                borderTopWidth: 1,
                borderTopColor: grayPlaceHolder
            },
            showLabel: false,

         showIcon : true,
        },

//Here Goes Your CustomTabBar Component
        tabBarComponent : CustomTabBarComponent,
        initialRouteName: 'ScreenTwo',
        tabBarPosition: 'bottom',
        animationEnabled: false,
        swipeEnabled: false
    }, []);

CustomTabBarComponent.js
     const TabBar = (props) => {
          const { navigationState } = props;
          let newProps = props;

            newProps = Object.assign(
              {},
              props,
              {
                style: {

         // get value from redux store and set it here
                  backgroundColor: 'rgba(0,0,0,0.1)',
                  position: 'absolute',
                  bottom: 0,
                  left: 0,
                  right: 0
                },
                activeTintColor: '#fff',
                inactiveTintColor: '#bbb',
              },
            );

          return <TabBarBottom {...newProps} />;
        };

Now You can connect this CustomTabBarComponent with Redux store and can change the value of whatever Property you want.

A: What you need to do is set your tab component as a function and send the color as a parameter to that function. Try this:
const MyTabnav = color => TabNavigator({
    ScreenOne: {
        screen: ({ navigation, screenProps }) => <ScreenOneNav screenProps={{ tabbarNavigation: navigation, ...screenProps }} onNavigationStateChange={null} />,
        navigationOptions: {
            tabBarLabel: 'ScreenOne',
            tabBarIcon: ({ tintColor }) => (
                <View style={[styles.tabViewBox]}>
                    <Text style={[styles.tabText, { color: tintColor }]}>ScreenOne</Text>
                </View>
             )
        }
    },
    ScreenTwo: {
        screen: ({ navigation, screenProps }) => <ScreenOneNav screenProps={{ tabbarNavigation: navigation, ...screenProps, }} onNavigationStateChange={null} />,
        navigationOptions: {
            tabBarLabel: 'ScreenOne',
            tabBarIcon: ({ tintColor }) => (
                <View style={[styles.tabViewBox]}>
                   <Text style={[styles.tabText, { color: tintColor }]}>ScreenTwo</Text>
                </View>
             )
        }
    },
    ScreenThree: {
        screen: ({ navigation, screenProps }) => <StockNotificationNav screenProps={{ tabbarNavigation: navigation, ...screenProps }} onNavigationStateChange={null} />,
        navigationOptions: {
            tabBarLabel: 'Notifications',
            tabBarIcon: ({ tintColor }) => (
                <View style={[styles.tabViewBox]}>
                     <Text style={[styles.tabText, { color: tintColor }]}>ScreenThree</Text>
                </View>
            )
        }
    },
},
{

    tabBarOptions: {
        //use the color you passed in the prop here:
        style: {
            backgroundColor: color,
            height: 55,
            borderTopColor: 'transparent',
            borderTopWidth: 1,
            paddingRight: 10,
            paddingLeft: 10,
            borderTopWidth: 1,
            borderTopColor: grayPlaceHolder
        },
        showLabel: false,
        showIcon : true,
    },
    tabBarComponent : TabBarBottom,

    initialRouteName: 'ScreenTwo',
    tabBarPosition: 'bottom',
    animationEnabled: false,
    swipeEnabled: false
    }, []);

var styles = StyleSheet.create({
    tabText: {
        fontSize: 10,
        fontWeight: "600",
        flex: 4,
    },
    tabViewBox: {
        flex: 1,
        alignItems: "center",
    },
    tabIcon: {
        flex: 5,
        alignSelf: "center",
        marginTop: 10
    },
});
export default MyTabNav;

Then where you use MyTabnav pass the color as a param to it.  for example
export default class App extends Component<{}> {
    constructor(props) {
        super(props);
        this.state = {
            color: 'black'
        };
    }
    getRandomColor = () => {
        var letters = '0123456789ABCDEF';
        var color = '#';
        for (var i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    };
    onPress = () => {
        this.setState({
            color: this.getRandomColor()
        });
    };
    render() {
        const Tabs = MyTabnav(this.state.color);
        return (
            <View style={{ flex: 1 }}>
                <Button onPress={this.onPress} title="Click me" />
                <Tabs />
            </View>
        );
    }
}

A: try using
const tabBarOptions = {
// setting height 'null', and top 0 will change the color of pressed tab
   indicatorStyle: {
     height: null,
     top: 0,
     backgroundColor: "red",
     borderBottomColor: "black",
     borderBottomWidth: 3,
   },
   activeTintColor: "black",
   pressColor: "white",
   style: {
     backgroundColor: "#ddc8be",
   },
   labelStyle: { fontSize: 13 },
};


text:
Q: Is it possible to give conditions in plotly heatmap color scheme? I have generated a heatmap using px.imshow

returns = returns.pivot('year', 'month', 'tradegain').fillna(0)
returns = returns\[\['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'\]\]
returns\['Total returns'\] = dayret.groupby(dayret.index.year).tradegain.sum().values
returns = round(returns,2)
fig = px.imshow(returns,text_auto=True,aspect='auto',title=title,color_continuous_scale= px.colors.sequential.BuGn_r)

I want negative returns to be displayed in red and everything else in green.
Is there any way possible to do that?
I have also tried making my own color scheme
fig = px.imshow(returns,text_auto=True,aspect='auto',title=title,color_continuous_scale=['red','yellow','green','green',                                                                                'green','green','green','green','green','green','green','green','green','green','green'])

also with
fig = px.imshow(returns,text_auto=True,aspect='auto',title=title,color_continuous_scale=[[0.0,'Red'],[0.5,'Free ']])

no good result
I want the result to be visually appealing.

A: You should create your own colorscale. Because there is no data for return in the question. I give you an example below:
import plotly.express as px
import numpy as np

z = np.array([[.1, .3, .5, .7, -.9],
     [1, .8, 60, -10, -.2],
     [.2, 0, -.5, .7, .9],
     [.9, .8, -.4, .2, 0],
     [.3, .4, -.5, .7, 1]])

maxz = np.max(z)+0.1
minz = np.min(z)

colorscale = ["green" if i>=0 else 'red' for i in np.arange(minz,maxz,0.01)]

fig = px.imshow(z, text_auto=True, aspect="auto", color_continuous_scale=colorscale)
fig.show()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loading Images on-demand (or; disable loading of hidden images) I have a slider-like widget which is basically, a div of sub-divs containing some page content (together with images).
Initially, all sub-divs are hidden except the main one.
My problem is that all web browser seem to load (request) all images in the content, whether they're hidden or not.
In my case specifically, it will end up loading some 350 images at one go. This is a lot, especially when considering images are at the very least 200kb. In fact, the network log specifies that the total website size is in the range of 6mb to 7mb.
All these images hinder page load, especially because they are expected to load before other page elements (eg; buttons etc).
What is the solution to my problem? Things I tried already:

*

*loading each sub-div as ajax. This is not possible, the page content must be there at all time.

*hiding the images themselves (in the hope that the web browser does not load them). This failed, the browser still loaded images with CSS display:none;.

*Possible solution: intentionally break the markup (server-side) so that the browser does not load the images, eg; writing <img alt="abc.jpg" src="about:blank"/>, then when tab switches, I would fix the markup correctly with jQuery. I haven't tried this yet, is it advisable?

A: Well, as I hinted in the question, a possible solution can be achieved by the following trick:
<?php
    // server-side content
    echo str_replace(' src=', ' data-dly="" src="blank.gif" data-src="', $html);
?>

// client-side script
function showPage(id){
    hidePages();

    var page = jQuery('#page'+id);

    page.find('img[data-dly="1"]').each(function(){
        jQuery(this).attr('src',jQuery(this).attr('data-src'));
    }).removeAttr('data-dly').removeAttr('data-src');

    page.fadeIn();
}

NB: Thanks to @jeffreydev for the help as well.


text:
Q: Optimizing for loop in python I have a dataframe (df) with distance traveled and I have assigned a label based on certain conditions.
distance=[0,0.0001,0.20,1.23,4.0]
df = pd.DataFrame(distance,columns=["distance"])
df['label']=0
for i in range(0, len(df['distance'])):
      if (df['distance'].values[i])<=0.10:
          df['label'][i]=1
      elif (df['distance'].values[i])<=0.50:
          df['label'][i]=2
      elif (df['distance'].values[i])>0.50:
          df['label'][i]=3

This is working fine. However, I have more than 1 million records with distance and this for loop is taking longer time than expected. Can we optimize this code to reduce the execution time?

A: In general, you shouldn't loop over DataFrames unless it's absolutely necessary. You'll usually get much better performance using a built-in Pandas function that's already been optimized, or by using a vectorized approach.
In this case, you can use loc and Boolean indexing to do the assignments:
# Initialize as 1 (eliminate need to check the first condition).
df['label'] = 1

# Case 1: Between 0.1 and 0.5
df.loc[(df['distance'] > 0.1) & (df['distance'] <= 0.5), 'label'] = 2

# Case 2: Greater than 0.5
df.loc[df['distance'] > 0.5, 'label'] = 3

Another option is to use pd.cut.  This is a method is a little more specialized to the example problem in the question.  Boolean indexing is a more general method.
# Get the low and high bins.
low, high = df['distance'].min()-1, df['distance'].max()+1

# Perform the cut.  Add one since the labels start at zero by default.
df['label'] = pd.cut(df['distance'], bins=[low, 0.1, 0.5, high], labels=False) + 1

You could also use labels=[1,2,3] in the code above, and not add 1 to the result.  This would give df['labels'] categorical dtype instead of integer dtype though.  Depending on your use case this may or may not be important.
The resulting output for either method:
   distance  label
0    0.0000      1
1    0.0001      1
2    0.2000      2
3    1.2300      3
4    4.0000      3

A: Use cut by assigning labels to the bins:
pd.cut(df.distance, [-np.inf, 0.1, 0.5, np.inf], labels=[1,2,3])

0    1
1    1
2    2
3    3
4    3

A: Comes with a warning about setting a value on a copy of a slice, but maybe someone can suggest a cleaner alternative?
Just based on fancy indexing to get the sub-array based on distance and then writing the values you want to it.
df.loc[:, "label"][df.loc[:, "distance"] <= 0.1] = 1
df.loc[:, "label"][(0.1 < df.loc[:, "distance"]) & (df.loc[:, "distance"] <= 0.5)] = 2
df.loc[:, "label"][df.loc[:, "distance"] > 0.5] = 3

EDIT: New and improved, without chained indexing.


text:
Q: Creating Ellipse in WGS84 with metric parameters I have points in WGS84 (x,y), radiuses in meters (rx, ry), rotation angle in degrees. I would like to create a new WGS84 geometry.
I've tried this but the major/minor distances seem to be off by a few hundred meters in some cases.
Ellipse (x,y,rx,ry,rotation,#of segments in 1/4 of ellipse)
SELECT
transform(
 translate(
  rotate(
   scale(
    buffer(
     transform(setsrid(makepoint(0,0),4326),3395),
     1,
   $6),
  $3,$4),
 $5),
x(transform(setsrid(makepoint($1,$2),4326),3395)),
y(transform(setsrid(makepoint($1,$2),4326),3395))),4326)


text:
Q: Session user data get error This is my Controller:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class admin extends ci_controller{

function __construct(){

    parent::__construct();

    $this->load->library('session');
    $this->load->helper(array('form', 'url', 'security', 'html'));
    $this->load->library('form_validation');
    $this->load->model($this->config->item('admin_model'), 'admin_db_connection', TRUE);
    //$this->load->model('admin_model' ,TRUE);
    //$this->load->helper('security');
    $this->load->helper('date');
    //$this->load->library('Ajax');
    $this->load->library("pagination");
    $this->load->database();
    $this->load->helper('url'); //You should autoload this one ;)
}

public function index(){
    $this->load->view('admin/login');
}

public function check_admin(){ //echo'admin';

    $this->load->helper('form');
    $this->form_validation->set_rules('admin_name','admin name','trim|required|xss_clean');
    $this->form_validation->set_rules('email','Email','trim|required|xss_clean');

    $this->form_validation->set_rules('password','password','trim|required|xss_clean');

    if($this->form_validation->run()== FALSE)
    { //echo 'invalid login ';
        $this->index();
    }
    else
    {
        $data=array();
        $data['admin_name']=$this->input->post('admin_name',true);
        $data['email']=$this->input->post('email',true);
        $data['password']=$this->input->post('password',true);
        //echo "<pre>";

        if ($query = $this->admin_db_connection->check_admin_validation($data))
        {
            // print_r($po);exit;
            $newdata=array
            (
             'id' => $query[0]['id'],
             'admin_name' => $query[0]['admin_name'],
             'email'=>$query[0]['email'],
             'status' => $query[0]['status'],
             'sign_in'=>TRUE
             );
            // echo "<pre>";
            //print_r($newdata);exit;

            $this->session->set_userdata('auth', $newdata);
            //$return= true;
            //print_r($auth);exit;
            redirect('dashboard');
            return TRUE;
        }
        else
        {
            echo 'invalid login';

            $this->index();
            //redirect('admin/index', 'refresh');
            return FALSE;
        }
    }
}

  function logout()
  {

    $this->session->sess_destroy();
    redirect('admin');
  }
}
?>

This is my model:
 <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class admin_model extends ci_model{

function check_admin_validation($data){
    $this->session->userdata('auth');
    $this->db->select('*');
    $this->db->from('admin_user');
    $this->db->where('admin_name' , $data['admin_name']);
    $this->db->where('email', $data['email']);
    $this->db->where('password', $data['password']);
    $query=$this->db->get();
    if($query->num_rows()>0)
    {
        $resulet=$query->result_array();
        $query->free_result();
        return $resulet;
    }
    else
    {
        return false;
    }
  }
}
?>

When I use this code $this->session->set_userdata($newdata); instead of $this->session->set_userdata('auth', $newdata); then it works, but above code doesn't. Can someone tell me, where the problem is?

A: If I am not mistaken, the second parameter for the set_userdata function is a string, whereas you're passing an array.
This may be why your code isn't working.

A: The way to set session value at codeigniter is
$this->session->set_userdata('some_name', 'some_value');
//some_value should not be array
//But your are setting array as value which is wrong.

$this->session->set_userdata($newdata);
//This will set each array key to your session.
//That's why it is working

If you really want to set array into one sesson key you can do it following way
   $this->session->set_userdata("auth",json_encode($newdata);

Now you can retrive data as
$auth=json_decode($this->session->userdata("auth"));

please look at codeigniter documentation

A: thank you now i solved my problem.thank you all and stackoverflow because if i not post here i cant find my answer.here is the problem my dashboard i passed wrong value 'sing_in' right value 'auth'.
 if (!$this->session->userdata('sing_in'))
          {
              redirect('admin');
          }`enter code here`


text:
Q: Can't convert array buffer to pdf in react I am using react and nestjs to convert a html template to pdf format. So far I can convert html to pdf in the backend using puppeteer and send an array buffer to frontend. When I try to convert the array buffer into pdf in the frontend for some reason the pdf opens but it shows a table that says 'Failed to load PDF document'.
Backend code

async downloadPlan() {
        const page = await this.browserContext.newPage();
        const content = await page.goto('https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Keyed_collections', {
            waitUntil: 'networkidle2'
        });
        console.log('content', content);
        const pdf = await page.pdf({ format: 'A4', path: 'lcs.pdf', printBackground: true, scale: 0.5 });
        this.browserContext.close();
        return pdf;
}

Frontend Code

function getPDF(): any {
    return axios.get(`http://localhost:4000/test/pdf`, {
      responseType: 'arraybuffer',
      headers: {
        'Accept': 'application/pdf'
      }
    })
  }

async function savePdf() {
    return getPDF()
     .then((response: any) => {
      console.log(response);
       const blob = new Blob([response.data], {type: 'application/pdf'})
       const link = document.createElement('a')
       link.href = window.URL.createObjectURL(blob)
       link.download = `your-file-name.pdf`
       link.click()
     })
  }


text:
Q: How to make a discord bot be able to play youtube audio more than once (discord.py) I'm trying to make my bot play music more than once (after a track finishes), but right now it can only play through one time then stops.
@bot.command(pass_context=True)
async def play(ctx, url):
    author = ctx.message.author
    voice_channel = author.voice_channel
    vc = await bot.join_voice_channel(voice_channel)
    player = await vc.create_ytdl_player(url)
    player.start()


text:
Q: WPF binding with Datacontext I'm new to WPF programming and I have this question going through my mind.
Why does binding only work when using properties instead of fields?
Here's the example that gave me this question:
xaml:
<ListBox ItemsSource="{Binding requiredPermissions}" DisplayMemberPath="MyText" Grid.Row="1" ></ListBox>

code behind(works):
public ObservableCollection<MyNotifyableText> requiredPermissions { get; set; }

code behind (doesn't work):
public ObservableCollection<MyNotifyableText> requiredPermissions;

Thanks in advance.

A:
Why does binding work when using properties instead of fields?

Because Microsoft use reflection behind the scenes to resolve the binding paths at runtime, and they only search for public properties of the DataContext using the Type.GetProperty method.
So you can only bind to public properties - not fields.

A: It seems that you aren't binding to the property correctly. The Binding isn't smart enough to know where is your property defined. You should set the DataContext of the View first with DataContext=...
Try this:
Put a name to your view and set itself to be the data context:
<Window x:Name="MyWindow" DataContext="{Binding ElementName=MyWindow}" ... />

Then, your ListBox Binding should work.


text:
Q: In simple words what are are the purposes of abstract classes and/or interfaces? I have to explain to some students the use of abstract classes and interfaces, as I have a very tecnical background, I would like to know if you would help me to define an easy explanation for junior.
Simple definition:
What are the purposes of abstract classes, interfaces, and what is the difference between the two ?
When is it appropriate to use one instead of the other?
Thanks.

A: I'll see if I can do this with generic terminology without too much hand-waving.
An interface is like a contract. It says that a class which implements the interface agrees to implement all of the functions declared (as signatures only; no function definition) by that interface. The class may do so in any way it chooses, and provide any other functionality, as long as it implements each one of the declared functions. An interface is useful when you want to be able to use some common functionality of otherwise unrelated classes- they share no implementation details, only the function signatures. In C#, function declarations within an interface are implicitly pure virtual.
An abstract class is a partially defined class that cannot be instantiated. It (usually) includes some implementation, but leaves some functions as pure virtual- declared only by their signature. Pure virtual functions are not defined in the class that declares them, so they must be implemented by a subclass (unless it too is an abstract class). Only a subclass which defines all of the pure virtual functions can be instantiated. The purpose of an abstract class is to define some common behavior that can be inherited by multiple subclasses, without implementing the entire class. In C#, the abstract keyword designates both an abstract class and a pure virtual method.
In practical terms, the difference between the two is that an interface defines only pure virtual functions, while an abstract class may also include concrete functions, members, or any other aspect of a class.

A: I will try to be simple.
An abstract class is a class. It is special in that you cannot create object of abstract class. A non-abstract class in called concrete class.
An abstract class, being a class, can have usual elements in it like fields, properties, methods events, indexers etc. Note that, as it is guaranteed that abstract class will not be instantiated to create object, some of those elements cab be without implementations (e.g. methods without body).
An interface is description of members that some other class will have for sure. C# interface can describe methods, properties, indexers and events only.
If a class implements interface, then it must implement all members described by interface.
This means if a class, implementing an interface, does not implement all members described by that interface then such class must be abstract class!
An abstract class can be 'half-cooked' class meaning it has provided few methods with body but few methods are without body etc. An interface can never implement any member it describes.
Abstract class takes part in hierarchy of classes based on inheritance. Note that in C#, a class can have at most one parent class which may or may not be abstract.
A class can implement many interfaces at the same time.
There many use cases for both of them.
Following statements should give you more clarity:

*

*Class must be either abstract or concrete.

*Interface, by definition, is abstract.

*Neither interface nor abstract class can be instantiated.

*Class may inherit from zero or one (abstract or concrete) class.

*Class may implement zero or more interfaces.

*Interface may inherit from zero or more interfaces.

*Interface cannot inherit a class.

*Abstract class may have members with implementation.

*Interface cannot have any member with implementation.

*To be concrete, class must implement all members in interface.
I hope this helps.

A: An interface says to the user that this class will support these functions.
For example:
public interface IWorker
{
    void DoWork();
}
public class MyInformation : IWorker
{
    public void DoWork()
    {
        //Do your class-specific Work
    }
}

var info = new MyInformation();
info.DoWork();

You might ask here - why not just add the method in MyInformation, instead of implementing an interface?
Here's a situation where it would be useful:
List<IWorker> workers = GetWorkers();
foreach(var worker in workers)
    worker.DoWork();

Here we don't know what kind of objects we're recieving. All we know is that they will implement any of the methods defined in IWorker. We don't care how they do it - all we care about is that they support your call.
As for an abstract class:
public abstract class Serializer
{
    protected void GetAttributes()
    {
        //Some default implementation
    }
    public abstract void SaveObject(String outputPath);
}

We have a serializer class, which has some basic default implementations - but by itself it does nothing. It does not know how to write the output - only how to get the attribute information.
Now you can have a concrete implementation such as :
public class XmlSerializer : Serializer
{
    public override void SaveObject(String outputPath)
    {
        //Do your xml serializing
    }
}

Which will serialize it to XML.
Again, you don't care how they serialize, only that they do it;
List<Serializer> serializers = GetWorkers();
foreach(var serializer in serializers)
    serializer.SaveObject(@"C:\out.tmp");

A: Interfaces are like skeletons. If you want to build a human, you should use that skeleton.
Interfaces simply create a kind of structure for your classes to denote that your class should have a defined and agree-upon structure. For example, all animals pee, eat and make sounds. Thus you can have an interface, called IAnimal which only mentions that classes should Pee, Eat, and MakeSound.
Interfaces are just like simple checklists, which should either be implemented totally, or none. When you want to use IAnimal interface, it's just like your boss telling you "Hey, don't create a Cat class unless you write some methods for it to eat, pee, and make sound".
Abstract classes are like skeletons, but with some meat on them as well. It's just there to make your work easier.
You can consider an abstract class to be an interface, which already has some implementation.
That was the plain English answer. But after getting that, please study more, to get the real concept.


text:
Q: Splitting op amp output into 2 different IC input I tried the circuit shown below on breadboard and found that when I connect both the IC's input pin to the node 1, the op amp output is giving a different value. I believe this is due to the imbalanced input resistance on the IC (U3 & U6) pin. The AD736 has a very high input impedance. Is there a way to isolate the loads of the op amp from each other so that the correct voltage will be seen at each input pin of IC.
Edited circuit

Original circuit

A: U3 is improperly connected for a non inverting buffer. It's output is shorted to U2 out and seems pointless.
You can disconnect these outputs from U2out to U3-in, but what you do with U3out is unknown.


text:
Q: How can I avoid problems with Google Maps JavaScript API? I am using the Google Maps JavaScript API in combination with an api key. This works great for some hours or days, but after a specific intervall I get the following 403 error and the map is gone:

I don't know where the problem is because I didn't have reached the 25.000 requests per day yet. If I reset the api key and reload the page the map is loading correctly again, but I don't wanna reset the api key again and again.
As you can see I am using a custom map, but I don't think that the code is the problem, but here is the code:
(function(window, google){

    var infoWindow = null;

    function init() {
        var map;
        var mapOptions = {
            zoom: 12,
            scrollwheel: false,
            center: new google.maps.LatLng(
                51.050409,
                13.737262
            ),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(
            document.getElementById('map'),
            mapOptions
        );
        setMarkers(map, locations);
        infoWindow = new google.maps.InfoWindow({
            content: "holding..."
        });
    }

    function setMarkers(map, locations) {
        var i, icon, marker, contentString;
        for (i = 0; i < locations.length; i++) {
            icon = '../Images/icn-marker.png';
            contentString = '
' + locations[i][0] + '
' + locations[i][1] + '
' + locations[i][4] + '
';
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[i][2], locations[i][3]),
                map: map,
                title: locations[i][0],
                icon: icon,
                html: contentString
            });
            google.maps.event.addListener(marker, 'click', function() {
                infoWindow.setContent(this.html);
                infoWindow.open(map, this);
            });
        }
    }

    google.maps.event.addDomListener(window, 'load', init);

})(window, google);

Any my script include looks like the following:

Hope you can help, because I dont' know where the problem is.

A: The 403 error response indicate that your API key is not valid or was not included in the request. Please enxure that you have included the entire key and that you have enabled the API for this key.
Also, check your usage limit, if you exceed the usage limits or otherwise abuse the service, the web service will return a specific error message. If you continue to exceed limits, your access to the web service may be blocked. It is also possible to receive 403 Forbidden responses.
The problem can be address by combining two approaches:

*

*Lowering usage, by optimizing applications to use the web services more efficiently.

*Increasing usage limits, when possible, by purchasing additional allowance for your Google Maps API for Work license.

Note:
When requests fail, you should ensure that you retry requests with exponential backoff. For example, if a request fails once, retry after a second, if it fails again, retry after two seconds, then four seconds, and so on. This ensures that broken requests or wide scale failures do not flood Google's servers, as many clients try to retry requests very quickly.
Here's a related SO ticket encountered 403 error response: Google static map API getting 403 forbidden when loading from img tag


text:
Q: VSCode messes up indentation in Java I am using VSCode (+ some java plugins) to do some core java work and the experience is very good so far. My team members, most of whom use Eclipse, complain that I mess up the spacing/indentation on every commit; sometimes even for lines that I don't change.
How do I prevent VSCode from doing that?
Michael

A: these settings might can give you some helps:

*

*"editor.insertSpaces": true,

*"editor.detectIndentation": false,

*"editor.tabSize": 4,

comes from:https://code.visualstudio.com/docs/getstarted/settings.
and these commands(click the 'Spaces:x' on the bottom right of vscode):
"Convert Indentation to Spaces",
"Convert Indentation to Tabs",
and so on...


text:
Q: How i get img from rss by php i want to get  from rss feeds by php or get this item
<enclosure url="http://www.youm7.com//images/newspics/large/S1220131618953.jpg " length="5000" type="image/jpge"/>

i use this code to get other item
<?

require_once 'rss_fetch.inc';
$url = 'http://egyptian-planet.com/rss.php';
$rss = fetch_rss($url);

echo "Site: ", $rss->channel['title'], "
";

foreach ($rss->items as $item ) {
    $title = $item[title];
    $url   = $item[link];
    $pub   = $item[pubdate];
    $desc  = $item[description];

    echo "$title

";
    echo "$pub
";
    echo "
$desc

";
    echo "
";
}
?>

Any help?


text:
Q: Use FFT to find all possible fixed-size subset sums I need to solve the following problem: given an integer sequence x of size N, and a subset size k, find all the possible subset sums. A subset sum is the sum of elements in the subset.
If elements in x are allowed to appear many times (up to k of course) in a subset (sub-multiset), this problem has a pseudo polynomial time solution via FFT. Here is an example:
x = [0, 1, 2, 3, 6]
k = 4
xFrequency = [1, 1, 1, 1, 0, 0, 1] # On the support of [0, 1, 2, 3, 4, 5, 6]
sumFrequency = selfConvolve(xFrequency, times = 4) # A fast approach is to simply raise the power of the Fourier series.
sumFrequency > 0 # Gives a boolean vector indicating all possible size-k subset sums.

But what can be done if an element cannot show up multiple times in a subset?
I came up with the following method but am unsure of its correctness. The idea is to first find the frequencies of sums that are produced by adding at least 2 identical elements:
y = [0, 2, 4, 6, 12] # = [0, 1, 2, 3, 6] + [0, 1, 2, 3, 6]
yFrequency = [0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1]
sumFrequencyWithRedundancy = convolve(yFrequency, x, x)

My reasoning is that since y represents all possible sums of 2 identical elements, then every sum in y + x + x is guaranteed to have been produced by adding at least 2 identical elements. Finally
sumFrequencyNoRedundancy = sumFrequency - sumFrequencyWithRedundancy
sumFrequencyNoRedundancy > 0

Any mistake or any other established method for solving the problem?
Thanks!
Edits:
After some tests, it does not work. There turns out to be much more combinations that should be excluded from sumFrequency besides sumFrequencyWithRedundancy, and the combinatoric analyses seem to escalate rapidly with k, eventually making it less efficient than brute-force summation.
My motivation was to find all possible sample sums given sampling without replacement and the sample size. Then I came across the idea of solving the standard subset sum problem via FFT --- free subset size and the qualified subsets themselves unneeded. The reference materials can be easily found online, basically a divide and conquer approach:

*

*Divide the superset into 2 sets, left and right.

*Compute all possible subset sums in the left and right sets. The sums are represented by 2 boolean vectors.

*Convolve the 2 boolean vectors.

*Find if the target sum is indicated in the final boolean vector.
You can see why the algorithm works for the standard subset sum problem.
If anyone can let me know some work on how to find all possible size-k subset sums, I would really appreciate it!

A: Given k and the n-element array x, it suffices to evaluate the degree-k coefficient in z of the polynomial
   n          x[i]
product (1 + y     z).
  i=1

This coefficient is a polynomial in y where the exponents with nonzero coefficients indicate the sums that can be formed using exactly k distinct terms.
One strategy is to split x with reasonably balanced sums, evaluate each half mod z^(k+1), and then multiply using the school algorithm for the outer multiplications and FFT (or whatever) for the inner. This should end up costing roughly O(k^2 S log^2 S).
The idea for evaluating elementary symmetric polynomials efficiently is due to Ben-Or.


text:
Q: COPY GRANTS not allowed in CREATE TASK command in Snowflake This is a small but annoying issue.
I cannot seem to use the COPY GRANTS command clause of the CREATE OR REPLACE TASK command in Snowflake.
I have tried moving the COPY GRANTS clause to different parts of the creation statement (Before the AS keyword) to see if that helps, but I just get a syntax error: SQL compilation error: syntax error line 4 at position 5 unexpected 'grants'. (Syntax error line number changes depending on where I put the COPY GRANTS command).
Snowflake SQL code:
create or replace task "DATABASE"."SCHEMA"."POPULATE"
WAREHOUSE = 'BILLING'
SCHEDULE = 'USING CRON 0 */3 * * * '
COPY GRANTS
AS
create or replace table tblname
copy grants
as
select *
from old_tbl;
According to the documentation, I should be able to do this:
https://docs.snowflake.com/en/sql-reference/sql/create-task.html

A: Unfortunately, even though the 'copy grants' parameter is listed as an option for the create or replace task and create task ... clone, it is not actually supported at this time.  There is a note about this at the end of the documentation section that describes the 'copy grants' parameter for the create task command.
Note in Snowflake Documentation


text:
Q: ModelMapper: how to keep converters registered at mapper level when using a TypeMap with custom mapping I use ModelMapper to convert Models to DTOs. I have a bunch of default converters for null values that have been registered at the mapper level like this:
        modelMapper.addConverter(new Converter<String, String>() {
            @Override
            public String convert(MappingContext<String, String> context) {
                if (context.getSource() == null) {
                    return "global null converter was here";
                }
                return context.getSource();
            }
        });

This works fine with simple mapping when the properties name are the same on both side of the conversion.
The converter is used to handle null values as expected.
Now if I need to do a more complex conversions with different properties name by using .map(getter, setter) on the type map, the global converters are not called anymore.
I don't want the global converters to be discarded when configuring the typemap.
How can I fix that ?
Here is a sample code (with lombok for code brevity) that use ModelMapper 2.3.8, the today's latest version:
@Data @AllArgsConstructor @NoArgsConstructor class A { String a; String b;}

@Data @AllArgsConstructor @NoArgsConstructor class B { String a; String b; }

@Data @AllArgsConstructor @NoArgsConstructor class C { String x; String y;}

public class MapperTestCase {

    public static void main(String[] args) throws IOException {

        A a = new A("aaa", "bbb");

        ModelMapper modelMapper = new ModelMapper();
        final TypeMap<A, B> AtoBTypeMap = modelMapper.createTypeMap(A.class, B.class);
        B b = AtoBTypeMap.map(a);
        System.out.println("conversion with no converter A -> B: " + a + " -> " + b);

        a = new A(null, null);
        b = AtoBTypeMap.map(a);
        System.out.println("conversion with no converter A -> B: " + a + " -> " + b);

        // Add a global/fallback converter that should convert all null String values.
        modelMapper.addConverter(new Converter<String, String>() {
            @Override
            public String convert(MappingContext<String, String> context) {
                if (context.getSource() == null) {
                    return "global null converter was here";
                }
                return context.getSource();
            }
        });

        final TypeMap<B, A> BtoATypeMap = modelMapper.typeMap(B.class, A.class);
        a = BtoATypeMap.map(b);
        System.out.println("conversion with global converter B -> A: " + b + " -> " + a);

        // add a local converter for the B to C type mape only
        BtoATypeMap.addMappings(mapper -> mapper.using(ctx -> {
            if (ctx.getSource() == null) {
                return "local converter was here";
            } else return ctx.getSource();
        }).map(B::getA, (w, x) -> w.setA(String.valueOf(x))));

        // in this conversion both converter (global and local) should be used
        a = BtoATypeMap.map(b);
        System.out.println("conversion with global and local converter B -> A: " + b + " -> " + a);

        // a new typeMap that will transform a B into a C, mapping B::a to C::x and B::b to C::y
        final TypeMap<B, C> BtoCTypeMap = modelMapper.typeMap(B.class, C.class);

        // a local converter for this type map
        BtoCTypeMap.addMappings(mapper -> mapper.using(ctx -> {
            if (ctx.getSource() == null) {
                return "local converter was here";
            } else return ctx.getSource();
        }).map(B::getA, (w, x) -> w.setX(String.valueOf(x))));

        BtoCTypeMap.addMapping(B::getB, C::setY);
        // first a conversion with a B instance without null values, works as expected
        b = new B("some", "data");
        C c = BtoCTypeMap.map(b);
        System.out.println("conversion with global and local converter B -> C: " + b + " -> " + c);

        // now a conversion with a B instance wirth null values, the local converer will be used, but not the global one defined at the mapper level. Why ?
        b = new B();
        c = BtoCTypeMap.map(b);
        System.out.println("conversion with global and local converter B -> C: " + b + " -> " + c);
    }
}

The output is:
conversion with no converter A -> B: A(a=aaa, b=bbb) -> B(a=aaa, b=bbb)
conversion with no converter A -> B: A(a=null, b=null) -> B(a=null, b=null)
conversion with global converter B -> A: B(a=null, b=null) -> A(a=global null converter was here, b=global null converter was here)
conversion with global and local converter B -> A: B(a=null, b=null) -> A(a=local converter was here, b=global null converter was here)
conversion with global and local converter B -> C: B(a=some, b=data) -> C(x=some, y=data)
conversion with global and local converter B -> C: B(a=null, b=null) -> C(x=local converter was here, y=null)

The expected output for the last line is C(x=local converter was here, y=global null converter was here)

A: If You wanna create general propertyConverter you can try someshing like this
        Converter<String, String> stringPropertyConverter = new Converter<String, String>() {
        @Override
        public String convert(MappingContext<String, String> context) {
            if (context.getSource() == null) {
                return "global null converter was here";
            }
            return context.getSource();
        }
    };

    ModelMapper modelMapper = new ModelMapper() {
        @Override
        public <S, D> TypeMap<S, D> typeMap(Class<S> sourceType, Class<D> destinationType) {
            TypeMap<S, D> typeMap = super.typeMap(sourceType, destinationType);
            typeMap.setPropertyConverter(stringPropertyConverter);
            return typeMap;
        }

    };

Generally problem in order convertors which using in mapping process.
At first modelMapper define convertor for your class, on the next step it search suitable convertor for field of class.
In the firs case your converters placed in order
"TypeMap[String -> String]"
"TypeMap[B -> A]"
"TypeMap[A -> B]"

in the second case
"TypeMap[B -> C]"
"TypeMap[String -> String]"
"TypeMap[B -> A]"
"TypeMap[A -> B]"

and convertor B to C is suitable convertor for any of your fields in your class.

A: I think i found the solution :
it's because your class C have different attribute names than your class A and B. If you rename x to a and y to b, the output will be good.
Your question now is "why is this working like that", simply because modelMapper apply the converter only if the name between the 2 objects are the same. I don't think modelMapper provide a solution for a real "global" converter by ignoring attributes name as you wish.
About your code, i think you should use Java 8 functionality :
modelMapper.addConverter(new Converter<String, String>() {
    @Override
    public String convert(MappingContext<String, String> context) {
        if (context.getSource() == null) {
             return "global null converter was here";
        }
        return context.getSource();
    }
});

can be rewrite :
modelMapper.addConverter(context -> context.getSource() == null ? "global null converter was here" : context.getSource());

// or much better because you extract your mapping logic :

modelMapper.addConverter(mySuperConverter());

private static Converter<String, String> mySuperConverter() {
    return context -> context.getSource() == null ? "global null converter was here" : context.getSource();
}

A: I must recognize that I normally use MapStruct or Dozer but, from time to time, I have used ModelMapper.
That been said, I will try to explain the mental model I follow when working with this library: I hope it helps you in understand your problem.
When you define a map between a source and a destination class in ModelMapper, you are actually defining the correspondence, the mappings, between their properties.
There is an implicit mapping that takes place if you do not define an explicit one between one property in the source class and another in the destination class.
This implicit mapping is based on several matching policies but we can safely say for our problem that it is based on property name matching.
If you define a Converter at the ModelMapper level, it will be applied to a property mapping only if one explicit property mapping is not provided, for the following reason: if you define an explicit property mapping between any properties in a TypeMap, by using the methods addMapping or addMappings, the configuration provided for that explicit mapping (source getter and destination setter, converters, pre-converters, post-converters) will be the only that will take place in the mapping process, no matter what you define at a higher mapping level.
You can easily test this fact by debugging your program and see, line by line, how the underlying property mappings are defined by the library.
For that reason I think it is not possible to implement such a global behavior: what you can do is repeat it by possibly implementing a factory method as suggested in other answer or better, by creating specific Converter classes that you can instantiate and set as converters (or, maybe, post-converters, in your use case) of every TypeMap and property mapping in which it is required.
There is an excelent post here in stackoverflow that will provide you a great and better explanation about what is happening under the hood when you use ModelMapper.


text:
Q: Magento 2 I am trying to upload CSV file for the configurable products. getting error like attribute code does not exists I am trying to upload this CSV file for the configurable products.
Unfortunately, the error I'm facing is

*

*Column configurable_variations: Attribute with code "rom" does not exist or is missing from product attribute set

I've assigned to attribute code to attribute set.
However, when I checked my additional_attributes and configurable_variations attributes, it seems like I got all of the definition of the attribute there already.
Please have a look into the file and helps me with the answer. Much appreciate it.
https://docs.google.com/spreadsheets/d/16TmSdzGJD-BCQGTbI3i2GVkjAtAq6wKEXmk5JnncTy8/edit?usp=sharing


text:
Q: Thingsboard emails not sending on alarm I'm trying to get an email to be sent whenever an alarm is created for a device. I have followed the tutorial at this link: https://thingsboard.io/docs/user-guide/rule-engine-2-0/tutorials/send-email/. The alarm is being created successfully but no email is being sent, not even to my spam folders.
I am using a local copy of thingsboard and when I configured my system SMTP settings, the test email sent successfully. I am using the system SMTP settings for the Send Email node, and I filled in my email for the To field in the To Email node.
Does anyone have any suggestions for getting the email to send?

A: I ran into the same issue while fooling around with TB. In my case the email was  received by SendGrid but it was being blocked by the gmail server which can be viewed in the SendGrid activity tab. Hence it never made it to the recipient. The reason it was getting blocked is I was using info@testemail.org in FROM field for email. I changed it to a valid email and it started working just fine.

A: enable the debug mode in the email node in rule engine and go to events tab to see the input/output of the node to see what is the response from the email server or if the email server is responding at all.
I've tried the guide and it is working like a charm, the debug mode helped me solving all the problems I faced.


text:
Q: How to mock a PaginatedScanList in DynamoDB? I know it's a bad thing to mock a list, instead of mock the item in list. But PaginatedScanList is too hard to new the instance. It's construct is too many params, and I try to new this list, then I find it's unmodifiable list, so that we can't add item to it.
How can I create a simple List to return in UT?

A: Now, I use the mock(PaginatedScanList.class) and mock the method:
when(scanList.toArray()).thenReturn(new Array[....])


text:
Q: How do I prevent javascript from converting my dates to GMT? I have a timestamp given by
timestamp = 2015-02-22T10:00:00.000Z

Why is it converted to GMT when I do this
var dt = new Date(timestamp);
console.log('dt = ' + dt); // prints Sun Feb 22 2015 05:00:00 GMT-0500 (EST)

I don't want it to convert my date to GMT. How do I prevent javascript from converting my dates?

A: When you try to execute dt = ' + dt, Javascript tries to convert the dt object to a string so it can be added to another string.  It does that by calling the dt.toString() method and the format you are seeing is the default string conversion for a date object.
FYI, this default format that looks like this:
Fri Mar 06 2015 19:24:42 GMT-0800 (Pacific Standard Time)

is NOT GMT time.  The time value shown is local time.  It is showing you that local time shown is -0800 hours from GMT, but the time itself is expressed in local time.
It's not uncommon to want to just truncate off the last part of this and display:
Fri Mar 06 2015 19:24:42

That can be done like this:
console.log('dt = ' + dt.toString().replace(/\sGMT.*$/, ""));

Working demo: http://jsfiddle.net/jfriend00/hg5m0r1r/

If you want something different to show, then you should construct the string representation you want yourself rather than letting the system automatically call .toString().  You can look at the Date object methods available and decide what you want to display.  A Date object internally is a number of ms since the epoch time so any string representation is a conversion of some kind.  You have to tell it what conversion you want.
You can see a list of the many date methods here.


text:
Q: Getting git-latexdiff and texcount to work together nicely What is the best way to get git-latexdiff to work nicely with texcount to view changed and deleted word counts between two commits?

A: It took me a long time to get this working, so just in case someone else comes looking for this in the future!
The first thing I did was use this answer so that texcount will use the formatting of latexdiff to be able to count added and deleted words.
There are several problems using this with git-latexdiff, however. The first is that gitlatex-diff uses latexpand to flatten any files that are included with \input or \include into one large .tex file. By default, this also removes any comments, including those %TC: comments for texcount formatting. So you will want to pass --latexpand --keep-comments to git-latexdiff.
The second issue is that git-latexdiff will make a temporary directory to store the diff files. You can tell git-latexdiff where to put these directories using the --tmpdirprefix, however the individual directories that are created each time you run git-latexdiff are named based upon the PID of the process. Therefore they are not easy to identify in order to run texcount on the generated diff files.
So based upon this answer I decided to put the word count in the document itself on the first page. This way when git-latexdiff runs, it will call texcount automatically and put the word counts in the document. Then you can tell git-latexdiff to output that file somewhere (or just view it in the viewer) and see the word counts. This answer gives some good insight on making a template for texcount. I used this to make it output in a format that I could include in a .tex file so that it would look good in the pdf (adding new line characters, etc).
But that answer requires that output to be saved in a file and then input using the \input command. The problem is that the first time that git-latex runs, it will compile the document once, which will create the word count file, and then it will flatten the doc before sending it to latexdiff. When it flattens the document, it will put the contents of the word count file directly in the flattened document. This will have the total number of words correct, but it will not show any added or deleted words since the diff file has not been made by latexdiff yet. And it will not input the contents of the word count file after this, because latexpand has already flattened the document. Note that if you give git-latexdiff the --no-flatten option, it will indeed leave the individual files; however, it will not send all the files to latexdiff (See this issue). It will only diff the top level file. For a large document, this is useless since all the content is likely in separate .tex files.
I could not find a way to get latexpand to ignore this input. I also tried putting the texcount command directly in the document using this answer, but latexpand still expands this and puts it in the document (I am using XeLaTeX). I could not find a way to get latexpand to ignore this command. (According to the code, it also expands \input commands that are in verbatim environments).
To solve this, I used the import package, which provides a command \import that \latexpand does not expand. This way the word count file can be generated each time the document is compiled (importantly: on the final diff document from latexdiff.)
The last thing I did was to only do this when the document is in draft mode. If the document is being edited and changed and you want to see this changes, it makes sense that it only happens in draft mode. See this answer for a list of things that draft mode changes. I added the command from this answer so that I could do stuff only in draft mode. I always want my pdf to have a TOC (since it is quite large), so I added this answer as well so that hyperref will always generate a TOC.
So in the end I added this to my preamble:
\makeatletter
\def\ifdraft{\ifdim\overfullrule>\z@
  \expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi}
\makeatother

\hypersetup{final}
\ifdraft{\usepackage{import}}{}

And then at the beginning of my document I added:
%TC:newcounter add Added
%TC:newcounter del Deleted
%TC:macro \DIFadd [add]
%TC:macro \DIFdel [del]
%TC:ignore
\immediate\write18{texcount -relaxed -sum -total -utf8 -opt=tc_template.cfg -merge \jobname.tex > 'WC.txt'}
\ifdraft{
{\LARGE \import{}{WC.txt}}
\clearpage}{}

For completeness, here is the content ot tc_template.cfg:
-template=
\Total Words: \textcolor{blue}{{sum}}\n\n
\Words in Text: {text}\n\n
\Words in Footnotes: {otherword}\n\n
\Words Added: \textcolor{green}{{add}}\n\n
\Words Deleted: \textcolor{red}{{del}}\n\n
\\rule{2.5in}{0.75pt}\n\n
\Words in Headers: {headerword}\n\n
\Num Headers: {header};  Floats: {float}\n\n
\Num Inline Math: {inline};  Display Math: {displaymath}\n\n

(I know that otherword in texcount can be things other than footnotes; but for my doc, it is nearly all footnotes. I also know that I could have put the %TC: macros in the config file. But I have lots of other %TC: comments in my document so that texcount ignores my preamble instead of parsing it, etc. So I just left them.)
The function that I call is:
git latexdiff --biber --xelatex --latexopt -shell-escape --main $1 --latexpand --keep-comments HEAD^1

I give it the name of the main .tex file. Since this solution uses \write18, remember that you will need to send the -shell-escape command to xelatex.
And that seems to work well. It puts the final word count and the added and deleted words in the final doc, which you can then peruse to see the differences in the last commit.
I might one day put this in CI in gitlab so that it generates this document automatically so that people can easily see what was changed, etc. That is for another day.


text:
Q: save() prohibited to prevent data loss due to unsaved related object 'user' with Foreign Keys I am trying to POST a new User in User table and assign attribute to this user in the next related table UserAttribute. UserAttribute table contains 'user' field, which is foreign key to the User table.

User.id = UserAttribute.user

My POST method creates a new record in User table, hovewer I can not create relation in UserAttribute table. I am getting:
save() prohibited to prevent data loss due to unsaved related object 'user'.
It is strange because the User is successfully created in User table.
I tried to save record in two ways. You can find the code on belove.
What is more, I tried transactions too.
models.py
class User(models.Model):
    id = models.IntegerField(primary_key = True)
    email = models.CharField(unique=True, max_length=180)
    roles = models.JSONField(default=dict)
    password = models.CharField(max_length=255, blank=True, null=True)
    name = models.CharField(max_length=255, blank=True, null=True)
    firebase_id = models.CharField(max_length=255, blank=True, null=True)
    created_at = models.DateTimeField(default=now)
    progress_sub_step = models.IntegerField(blank=True, null=True)
    step_available_date = models.DateTimeField(blank=True, null=True)
    progress_step = models.IntegerField(blank=True, null=True)
    active = models.IntegerField(default=1)
    last_login_at = models.DateTimeField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'user'

class Attribute(models.Model):
    name = models.CharField(max_length=255)
    value = models.CharField(max_length=255)

    class Meta:
        managed = False
        db_table = 'attribute'

class UserAttribute(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = 'attribute')
    attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE)

    class Meta:
        managed = False
        db_table = 'user_attribute'

serializers.py
class UserAttributeSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserAttribute
        fields = ('attribute',)

class UserSerializer(serializers.ModelSerializer):
    attribute = UserAttributeSerializer(many = True)
    class Meta:
        model = User
        fields = ('email', 'name', 'firebase_id', 'attribute')

    @transaction.atomic()
    def create(self, validated_data):
        attributes = validated_data["attribute"]
        del validated_data["attribute"]

        firebase_id_v = validated_data.get('firebase_id')
        user_save = User.objects.create(**validated_data)
        # Second method
        # user_save = User(**validated_data)
        # user_save.save()
        for attribute in attributes:
            a = UserAttribute.objects.create(user = user_save, **attribute)
        return user

views.py
class UserAttViewSet(viewsets.ModelViewSet):
    queryset = UserAttribute.objects.all()
    serializer_class = UserAttributeSerializer

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer


text:
Q: How to display all association collection in rails console? I'd like to display in rails console all the collections of the parent entity "Article", which would be a relationship between itself, example:
# article.rb

class Article < ActiveRecord::Base
 belongs_to :parent, :class_name => 'Article', optional: true
 has_many :sub_articles, :class_name => 'Article', :foreign_key => 'parent_id'
end

Now what I have is:
irb(main):095:0> Article.find(1)
Article Load (0.9ms)  SELECT "articles".* FROM "articles" ORDER BY
"articles"."id" ASC LIMIT $1  [["LIMIT", 1]]
=>
#<Articles:0x0000264231faa292

id: 1,
name: "king article"
created_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
updated_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
parent_id: nil

What I'd like to display on the rails console:
id: 1,
name: "king article"
created_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
updated_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
parent_id: nil
sub_articles:

[ Article:0x0000641428defb71
id: 2,
  name: "pencils article"
  created_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
  updated_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
  parent_id: 1
  sub_articles:
    [ Article:0x0000621438defb71
    id: 3,
    name: "pencil child 1"
    created_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
    updated_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
    parent_id: 2
    sub_articles: [],

    id: 4,
    name: "pencil child 2"
    created_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
    updated_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
    parent_id: 2
    sub_articles: []
  ]

]

Ultimately what I am looking for is if a parent is consulted to show their children (and the children of the children if possible)

A: It's probably best achieved by calling to_json on the top-level article, and configuring the as_json method of Article to include sub_articles
class Article < ActiveRecord::Base
  def as_json(options={})
    super(methods: [:subarticles])
  end
end

in the rails console:
$> Article.find(3).to_json # => should give you the hierarchy you're looking for


text:
Q: Visual studio not hitting the breakpoint for xamarin.forms Im facing this issue from the time I have updated my VS , I have created the test project and its working fine in other projects but its not working in my current project.
I tried deleting .bin and .obj files its the same again . I even tried this "project property window and go to "Build->Advanced" to check if "Debugging inforamtion" is "Portable"" and even this is portable in my project.
Please share me if u have any solutions for this.

A: Check the configuration of your project if Use Fast Deployment is enabled, if not enable it and try again .

Refer to
https://developercommunity.visualstudio.com/t/breakpoint-not-hit-debugging-xamarin-android-proje/1561025


text:
Q: Adding textbox to Android Keyboard I would like to add Textbox next to the soft keyboard sample code in order to have some space to write comments without the need to open additional application for that.
How can I change the layout of the keyboard so it will have text area in the right or in the left of it ?
Thanks


text:
Q: using request and beautiful soup module in python My code is very short code but it is giving unexpected error
import bs4

url = "https://www."+input("Enter The Name of the website: ")+".com"
req = re.get(url)
html_text = req.text
htmls = bs4.BeautifulSoup(html_text, "html.parser").prettify()
with open("facebook.html", "w+") as file:
    file.write(htmls)

Traceback (most recent call last):
  File "C:\Users\Tanay Mishra\PycharmProjects\First_Project\Web Scraping\web.py", line 9, in <module>
    file.write(htmls)
  File "C:\Users\Tanay Mishra\AppData\Local\Programs\Python\Python38-32\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u200b' in position 756: character maps to <undefined>```

A: \u200b means ZERO WIDTH SPACE in Unicode. Try to specify encoding="utf-8" in open() function. Also good practice is to use .content property of Response object and let BeautifulSoup to guess the encoding:
import bs4
import requests

url = "https://www."+input("Enter The Name of the website: ")+".com"
req = requests.get(url)
htmls = bs4.BeautifulSoup(req.content, "html.parser").prettify()
with open("facebook.html", "w+", encoding="utf-8") as file:
    file.write(htmls)


text:
Q: incremental form fields in flutter I'm implementing a form. And in this form the user can add more fields and dropdown. The hard part is controlling the value of the dropdowns. For the text fields I have a dynamic TextEditingControler() but for the dropdowns I store the selected value in a string. So the issue is it returns null value. The code is below.
First I created a class to group them together
class _GroupControllers {
  TextEditingController phone = TextEditingController();
  TextEditingController email = TextEditingController();
  String? selectedCatagory;
  void dispose() {
    phone.dispose();
    email.dispose();
    selectedCatagory;
  }
}

then initialize them
  List<TextFormField> _phoneFields = [];
  List<TextFormField> _emailFields = [];
  List<_GroupControllers> _groupControllers = [];
  List<DropdownButtonFormField2> _categoryDropDown = [];

and I created a widget for adding them
Widget _addTile(int index) {
    return Container(
      height: 50,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text("Add Phone"),
          IconButton(
              onPressed: () {
                final group = _GroupControllers();

                final phoneField = _generateTextField(group.phone,
                    "phone number", RegExp(r'(^(?:[+0]9)?[0-9]{10,12}$)'));

                final emailField = _generateTextField(
                    group.email,
                    "email",
                    RegExp(
                        r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+"));
                final categoryDropdown =
                    _generatedDropDown(category, group.selectedCatagory);

                index == 0
                    ? setState(() {
                        _groupControllers.add(group);
                        _phoneFields.add(phoneField);
                        _emailFields.add(emailField);
                        _categoryDropDown.add(categoryDropdown);
                      })
                    : setState(() {
                        _groupControllers.removeAt(index);
                        _phoneFields.removeAt(index);
                        _emailFields.removeAt(index);
                        _categoryDropDown.removeAt(index);
                      });
              },
              icon: index == 0
                  ? const Icon(
                      Icons.add,
                      color: Colors.green,
                    )
                  : const Icon(
                      CupertinoIcons.minus,
                      color: Colors.red,
                    ))
        ],
      ),
    );
  }

then created their fields
DropdownButtonFormField2 _generatedDropDown(
      List<String> category, String? selected) {
    final group = _GroupControllers();
    return DropdownButtonFormField2(
      decoration: InputDecoration(
        isDense: true,
        contentPadding: EdgeInsets.zero,
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(5),
        ),
      ),
      isExpanded: true,
      hint: const Text(
        'Select Category',
        style: TextStyle(fontSize: 14),
      ),
      icon: const Icon(
        Icons.arrow_drop_down,
        color: Colors.black45,
      ),
      iconSize: 30,
      buttonHeight: 60,
      buttonPadding: const EdgeInsets.only(left: 20, right: 10),
      items: category
          .map((item) => DropdownMenuItem<String>(
                value: item,
                child: Text(
                  item,
                  style: const TextStyle(
                    fontSize: 14,
                  ),
                ),
              ))
          .toList(),
      validator: (value) {
        if (value == null) {
          return 'Please select Catagory.';
        }
      },
      onChanged: (value) {
        //Do something when changing the item if you want.
        setState(() {
          selected = value.toString();
          group.selectedCatagory = value.toString();
        });
      },
      onSaved: (value) {
        selected = value.toString();
        group.selectedCatagory = value.toString();
      },
    );
  }

  TextFormField _generateTextField(
      TextEditingController controller, String hint, RegExp pattern) {
    return TextFormField(
      controller: controller,
      validator: (value) {
        if (value == null || value.isEmpty) {
          return 'Please enter ${hint}';
        } else if (!pattern.hasMatch(value)) {
          return 'Enter a valid ${hint}';
        }
        return null;
      },
      decoration: InputDecoration(border: OutlineInputBorder(), hintText: hint),
    );
  }

the in my ListView.builder()
                Column(
                  children: [
                    _addTile(index),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          "Phone Number:",
                          style: TextStyle(
                              fontSize: width * 0.04,
                              fontWeight: FontWeight.bold,
                              letterSpacing: width * 0.002),
                        ),
                        SizedBox(
                          height: height * 0.005,
                        ),
                        _phoneFields[index],
                      ],
                    ),
                    SizedBox(
                      height: height * 0.005,
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          "Email:",
                          style: TextStyle(
                              fontSize: width * 0.04,
                              fontWeight: FontWeight.bold,
                              letterSpacing: width * 0.002),
                        ),
                        SizedBox(
                          height: height * 0.005,
                        ),
                        _emailFields[index],
                      ],
                    ),
                    SizedBox(
                      height: height * 0.005,
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          "Category:",
                          style: TextStyle(
                              fontSize: width * 0.04,
                              fontWeight: FontWeight.bold,
                              letterSpacing: width * 0.002),
                        ),
                        SizedBox(
                          height: height * 0.005,
                        ),
                        _categoryDropDown[index]
                      ],
                    ),
                    SizedBox(
                      height: height * 0.005,
                    ),
                  ],
                ),

but the dropdown returns null. Why is that?


text:
Q: Proof that $\frac{2\theta}{\pi} < \sin \theta < \theta$ The following inequality hold: if $\theta $ is in radians and $ 0 < \theta  <\pi/2$, then
$\frac{2\theta}{\pi} < \sin \theta < \theta$
How can be proved this inequality?

A: Sometimes a picture is worth a hundred words.

$\sin\theta$ is the vertical line.  It is the shortest distance to the x-axis.
$\theta$ is the arclength, which is clearly bigger than $\sin\theta$
And the diagonal line $(0,1)$ to $(1,0)$ are points that are $\frac {2\theta}{\pi}$ above the x-axis for $0<\theta<\frac{\pi}2.$

A: There is a formal way to show it.
The fact we will use is

if $f(x_0) = g(x_0)$ and $f'(x) \ge g'(x)$ when $x \in [x_0, x_1]$ then $f(x) \ge g(x)$ when $x\in [x_0, x_1]$.

First let's prove that $\sin\vartheta \leq \vartheta$ when $\vartheta \in \left[0,\frac{\pi}{2}\right]$. Indeed, $\sin 0 = 0$ and $\sin'\vartheta = \cos\vartheta \leq 1 = \vartheta '$.
Then let's prove that $\sin\vartheta \geq \frac{2\vartheta}{\pi}$. Let $f(\vartheta) = \sin\vartheta $ and $g(\vartheta) = \frac{2\vartheta}{\pi}$. Note that $f(0) = g(0)$ and $f\left(\frac{\pi}{2}\right) = g\left(\frac{\pi}{2}\right)$. Suppose that there is one more point $\varphi \in \left[0,\frac{\pi}{2}\right]$ such that $f(\varphi) = g(\varphi)$. Then we get using Rolle's theorem that function $f(\vartheta) - g(\vartheta)$ has at least two stationary points on $\left[0,\frac{\pi}{2}\right]$. But equation
$$
f'(\vartheta) - g'(\vartheta) = \cos\vartheta - \frac{2}{\pi} = 0
$$
leads to $\vartheta = \pm\arccos\left(\frac{2}{\pi}\right) + 2\pi n$, $n \in \mathbb{Z}$ and it has exactly one solution in the interval $\left[0,\frac{\pi}{2}\right]$. Thus there is no solutions of equation $\frac{2\vartheta}{\pi} = \sin \vartheta$ on the interval $\left[0,\frac{\pi}{2}\right]$ (except $0$ and $\frac{\pi}{2}$) and as, for example,
$$
\sin\frac{\pi}{4} = \frac{\sqrt{2}}{2} > \frac{1}{2} = \frac{2}{\pi}\cdot\frac{\pi}{4}
$$
this inequality holds on the whole interval. QED.

A: Consider an unit circle centered at the origin $O$. Draw an arc $AB$ of angle $\theta$ beggining at $(1,0)$ and going counter clockwise. Now draw a paralell to $X$ axis through $B$, that intersects the $Y$ axis at $C$.
Now draw a $90$ degree arc with radius $OC$.
Compare the longitudes of the arc $AB$, trhe segment $OC$, and the lastly drawn arc.

A: Assuming you meant $0 < \theta <\frac{\pi}{2}$, try
$$
1) f_1 = \theta - \sin \theta \\
2) f_2 = \pi \sin \theta - 2 \theta
$$
The second equation is a bit more challenging, but if you take the second derivative, you notice that $f'_2$ is monotone decreasing, so by intermediate value theorem it has only one root, hence $f_2$ first increases and then decreases, and in $\frac{\pi}{2}$ is equal to $0$, so by Rolle's theorem it has roots only at $0$ and $\frac{\pi}{2}$.


text:
Q: Navigation bar is not responsive after scrolling I am new to web development.I met a problem when designing a scrolling navigation bar.
I used a bootstrap grid and jquery for this. If I don't scroll down and just resize the window, then everything is fine. The navigation bar is resized and in the center of the window. But after I scroll down, the size of navigation bar will be fixed. Its size won't change when I make window larger(it will be smaller if I make window smaller, but not centered). This may caused by setting width: nav.width() in js file, but I don't know how to fix it.
This is a new account so I don't have enough reputation to upload images. I will try to describe it using words. For example, at beginning, the parent of navigation bar is 1140px, the width of navigation bar is 100%, so its size is 1140px. If I resize the window, let us say the width of its parent is 720px, then the navigation bar width is also 720px. Then if I scroll down, the callback function in js will run, it will set the width to 720px, which is a fixed value, thus it won't be responsible any more. Now, if I resize window to make its parent back to 1140px, the width of navigation bar is 720px rather than 1140. So how to fix this?

                                Home

                                 About

                                 Portfolio

                                 Skills

                                 Contact

CSS
 #nav-wrap {
    font: 22px 'opensans-bold', sans-serif;
    width: 100%;
    margin: 0 auto;
    left: 0;
    top: 0;

}

    ul#nav {
    text-align: center;
    padding: 0;
    width: 100%;
    background: rgba(0, 0, 0, 0.3);
    z-index: 2;
}

    ul#nav li {
    height: 48px;
    display: inline-block;
}

    ul#nav li a {
    color:white;
    padding: 8px 13px;
    display: inline-block;
    text-align: center;
}

    $(function() {
    var nav = $('#nav');
    var navHomeY = nav.offset().top;
    var isFixed = false;
    var navWrap = $('#nav-wrap');
    var $w = $(window);
    $w.scroll(function () {
        var scrollTop = $w.scrollTop();
        var shouldBeFixed = scrollTop > navHomeY;
        if(shouldBeFixed && !isFixed) {
            nav.css({
                position: 'fixed',
                width: nav.width()
            });
            isFixed = true;
        }else if (!shouldBeFixed && isFixed) {
            nav.css({
                position: 'static'
            });
            isFixed = false;
        }
    });
});

A: Your problem most likely comes from this part.
 var shouldBeFixed = scrollTop > navHomeY;
        if(shouldBeFixed && !isFixed) {
            nav.css({
                position: 'fixed',
                width: nav.width()
            });
            isFixed = true;

Try inversing or removing that part all together. It is saying if the navbar is not at the top, add a position of fixed to it as well as nav.width(), whatever you set that to equal - and this is precisely the opposite of what you want because it's what your problem is according to the question.


text:
Q: How can I insert text into another file [file_put_contents] I've been trying to use php's file management systems, but I can't figure out how to do one thing. I have a file that I am going to use as a template file. Basically I would copy the contents of the template file and save them as another file.
I tried to use file_put_contents to insert a string into the copied file, but rather than simply inserting the string somewhere in the copied file, it completely replaces the entire code with the string.
How could I put a string into a php file without erasing the already existing code?

A: Looks like you are not specifying the FILE_APPEND flag when calling file_put_contents.
Example:
file_put_contents($file, $person, FILE_APPEND);

You can find the documentation here:
https://www.php.net/manual/en/function.file-put-contents.php


text:
Q: Mean number of times a player can play roulette
In the game of Russian roulette (not recommended by the author), one inserts a single cartridge into the drum of a revolver, leaving the other five chambers of the drum empty. One then spins the drum, aims at one's head, and pulls the trigger.
(a) What is the probability of being still alive after playing the game N times?
(b) What is the probability of surviving (N-1) turns in this game and then being shot the Nth time one pulls the trigger?
(c) What is the mean number of times a player gets the opportunity of pulling the trigger in this macabre game?

A: The player has a $\dfrac56$ chance of survival per game.
a) To survive $N$ games is $\left(\dfrac56\right)^N$
b) $\left(\dfrac56\right)^{N-1}\dfrac16$
c) The answer to (b) is a geometric distribution, with $p$ being the chance of success, (in this case failure!), so the mean is $\dfrac{1}{\frac16}=6$.

A: (1) $({5\over6})^N$ you need to not get shoot for $N$ consecutive turns.
(2) $({5\over6})^{N-1}{1\over6}$
(3) The expected number is $6$ as the probability is $1\over6$.
As for a rigorous proof using the definition, the expected number is
$1({1\over6})+2({5\over6})({1\over6})+3({5\over6})^2({1\over6})+...$
$=(({1\over6})+({5\over6})({1\over6})+({5\over6})^2({1\over6})+...)+(({5\over6})({1\over6})+({5\over6})^2({1\over6})+...)+(({5\over6})^2({1\over6})+...)+...$
$={1\over6}({1\over1-{5\over6}})+{1\over6}({5\over6})({1\over1-{5\over6}})+{1\over6}({5\over6})^2({1\over1-{5\over6}})+...$
$={1\over6}({1\over1-{5\over6}})({1\over1-{5\over6}})$
$=6$

A: Another way to understand what needs to be done at letter (c):
On (b) we found out the chance of surviving $N$ turns is:
$p(N) = (\frac{5}{6})^{N-1}(\frac{1}{6})$
By definition, the expected value of a variable is:
$<N> = \sum_{N=1}^\infty p(N) * N$
Here we go from one (died on first shot) to infinity, because the game can go on forever.
So,
$<N> = \sum_{N=1}^\infty (\frac{5}{6})^{N-1}(\frac{1}{6}) N = \frac{1}{6} \cdot \sum_{N=1}^\infty (\frac{5}{6})^{N-1} N$
That's the series you needd to calculate; then just use any method (like this or any other suggested) and find that:
$<N> = \frac{1}{6} \cdot 36 = 6$
(Wolfram confirms it)


text:
Q: How to cancel request in retrofix2.0 (rxandroid) when I request same url I want to call request when user click button. But when first request not response , user want to change parameter and call new request with same url.
Problem
How to cancel first request and call new request with same url.
 ServiceFactory
            .createService()
            .getSomething(page)
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DefaultObserver<SomthingResponse>() {
                @Override
                public void onNext(@NonNull SomthingResponse response) {
                    showSomthing()
                    hideProgressDialog();

                }

                @Override
                public void onError(@NonNull Throwable e) {
                    hideProgressDialog();
                    showErrorMessage(e.getMessage());
                }

                @Override
                public void onComplete() {

                }
            });

when user click button user will send page parameter to query string but this request have not already finish. User will change to page parameter and send new request. I want to cancel first request.
Thankyou

A: Answer to your question is switchMap() operator:
public static class User {} // Dummy server response

public Observable<Object> getButtonClicks() {
    return RxView.clicks(findViewById(R.id.button)); // (1)
}

public Single<User> getUserFromApi() {
    return Single.just(new User()) // (2)
            .delay(5, TimeUnit.SECONDS);
}

public void fun() {
    getButtonClicks()
            .subscribeOn(AndroidSchedulers.mainThread())
            .observeOn(Schedulers.io())
            .switchMap(__ -> getUserFromApi().toObservable()) // (3)
            .observeOn(AndroidSchedulers.mainThread()) // (4)
            .subscribeWith(new DisposableObserver<User>() {
                @Override public void onNext(@NonNull User user) {
                    Log.d("fun", "onNext");
                }

                @Override public void onError(@NonNull Throwable e) {
                    Log.d("fun", "onError");
                }

                @Override public void onComplete() {
                    Log.d("fun", "onComplete");
                }
            });
}

What happens here:

*

*Use library RxBinding to get reactive listeners to UI events. This observable emits an Object everytime button is clicked.

*Dummy API Observable. Response is delayed to imitate real API.

*Switch and map from from click observable to API observable. In case new click object is emitted during execution of the API call, old call is cancelled and new one executed.

*You probably want to observe changes in MainThread.

A: You can use a Subject and debounce
http://reactivex.io/documentation/operators/debounce.html
https://github.com/kaskasi/TraktTVSample/blob/master/app/src/main/java/de/fluchtwege/movielist/viewmodel/MovieListViewModel.java
You can check out this sample, it solves a similar problem. When the user enters a query a request is started only when the user stops editing for 1 sec, this way only the result of the last request ist shown:
requestsAPI.queryMovies(query, pagesLoaded)

            .observeOn(schedulerMain)

            .debounce(1000, TimeUnit.MILLISECONDS)

            .subscribe(new Subscriber<List<MovieQuery>>() {

                @Override

                public void onCompleted() {

                }

                @Override

                public void onError(Throwable e) {

                }

                @Override

                public void onNext(List<MovieQuery> movieQueries) {

                    onMoviesLoaded(filterMoviesFromSearchResults(movieQueries));

                }

});


text:
Q: Hardware Reserved 4GB (DIMM Slot 1B) So recently my task manager started showing that only 12GB of my 16GB DDR3 RAM in Dual Channel was available stating "Hardware Reserved 4.0 GB"
These are the steps I've currently taken to attempt to rectify the issue.

*

*Flashed BIOS

*Wiped OS and installed to a new drive

*Set max page file size to recommended (2.5GB)

*Maximum memory isn't enabled in advanced boot options

*Replaced the odd stick of RAM (I had a Kingston HyperX Fury) with the same model (now all Corsair Vengeance) so now all sticks match

*Resetting CMOS fixed it for a few hours before returning.

I want to avoid the idea that the DIMM slot is faulty due to a CMOS reset fixing it (even if temporarily).
The RAM I'm using is: CMZ12GX3M3A1600C9 (3) and CMZ4GX3M1A1600C9 (1) Both the same model of RAM, but the 3 came in a kit for 12GB whilst the other came as a single kit of 4GB, hence the slight difference in the part numbers.
The motherboard I'm using is 990FXA-UD3 R5.
I'm asking as a seperate question due to the fact I've tried every other suggestion in the other questions and now feel that my situation is unique enough for it's own question.


text:
Q: Array Error: terminating with uncaught exception of type NSException I'm trying to recreate a basic app by looking through the source code of the orignal app and learning it and then trying to retype into a separate file (and also making sure various parts in the Interface Builder match the original). One issue I'm having though is that I'm getting the following error:

2014-05-27 14:02:10.701 Nav Ctrl Practice[3513:60b] adding stock price:  to company at index 1
2014-05-27 14:02:10.703 Nav Ctrl Practice[3513:60b] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000101a3d495 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010179c99e objc_exception_throw + 43
    2   CoreFoundation                      0x00000001019e3745 -[__NSArrayM objectAtIndex:] + 213
    3   Nav Ctrl Practice                   0x0000000100003ad2 -[ParentViewController connectionDidFinishLoading:] + 530
    4   Foundation                          0x000000010148d36b __65-[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:]_block_invoke + 48
    5   Foundation                          0x0000000101340bdb -[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:] + 210
    6   Foundation                          0x0000000101340aec -[NSURLConnectionInternal _withActiveConnectionAndDelegate:] + 69
    7   CFNetwork                           0x0000000106950637 ___ZN27URLConnectionClient_Classic26_delegate_didFinishLoadingEU13block_pointerFvvE_block_invoke + 107
    8   CFNetwork                           0x000000010694e802 ___ZN27URLConnectionClient_Classic18_withDelegateAsyncEPKcU13block_pointerFvP16_CFURLConnectionPK33CFURLConnectionClientCurrent_VMaxE_block_invoke_2 + 84
    9   CoreFoundation                      0x00000001019e3f74 CFArrayApplyFunction + 68
    10  CFNetwork                           0x00000001068c13e7 _ZN19RunloopBlockContext7performEv + 133
    11  CFNetwork                           0x00000001068c1217 _ZN17MultiplexerSource7performEv + 247
    12  CFNetwork                           0x00000001068c103a _ZN17MultiplexerSource8_performEPv + 72
    13  CoreFoundation                      0x00000001019ccd21 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    14  CoreFoundation                      0x00000001019cc5f2 __CFRunLoopDoSources0 + 242
    15  CoreFoundation                      0x00000001019e846f __CFRunLoopRun + 767
    16  CoreFoundation                      0x00000001019e7d83 CFRunLoopRunSpecific + 467
    17  GraphicsServices                    0x0000000103bb4f04 GSEventRunModal + 161
    18  UIKit                               0x0000000100349e33 UIApplicationMain + 1010
    19  Nav Ctrl Practice                   0x0000000100005eb3 main + 115
    20  libdyld.dylib                       0x0000000101fc25fd start + 1
    21  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

I found a couple links on this site relating to the error shown above ("terminating with uncaught exception of type NSException"), however none of the specific causes seemed to match mine. The code I'm using is completely copied from a working file. So I'm not sure what I'm missing here. I've included below the source for the section where it appears to have an issue with the array.
//
//  ParentViewController.m
//

#import "ParentViewController.h"
#import "ChildViewController.h"
#import "DataAccess.h"
#import "sqlite3.h"

@interface ParentViewController ()
{

    NSMutableArray *arrayOfProducts;
    NSMutableArray *arrayOfCompanies;
    sqlite3 *productDB;
    sqlite3 *companyDB;

}

@end

@implementation ParentViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    arrayOfProducts = [[NSMutableArray alloc] init];

    [[self myTableView]setDelegate:self];
    [[self myTableView]setDataSource:self];

    self.dataAccess = [[DataAccess alloc] init];
    [self.dataAccess setCompanyListFromDB];

    self.childVC = [[ChildViewController alloc] init];

     NSMutableString *urlQuotes = [NSMutableString stringWithString:@"http://download.finance.yahoo.com/d/quotes.csv?s="];

    for(int i =0; i<self.dataAccess.companyList.count; i++) {
        Company *company = self.dataAccess.companyList[i];
        [urlQuotes appendFormat:@"%@", company.stockSymbol];

        if(i<self.dataAccess.companyList.count-1)
    {       [urlQuotes appendString:@","];
    }
        [urlQuotes appendString:@"&f=l1,"];

        NSLog(@"Quote URL: %@", urlQuotes);

        _responseData =[[NSMutableData alloc] init];
        NSURLRequest *request = [NSURLRequest requestWithURL:
                                 [NSURL URLWithString:urlQuotes]] ; //we are creating the request here
        NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; //we are creating the url connection and firing the request here
        [conn start]; //start the connection

    }

}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    NSLog(@"numberOfSectionsInTableView");
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"numberOfRowsInSection");

    return [self.dataAccess.companyList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"Cell";

           UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"UITableViewCell"];
    }

    int row = indexPath.row;
    NSLog(@"Cell at index: %d", row);

    //Find the company for this row in the table
    Company * company = self.dataAccess.companyList[row];
    NSLog(@"Got company %@ at index: %d from companyList Array", company.name, row);

    // Configure the cell...

    //make the row's text be the company's name
    cell.textLabel.text = company.name;
    [[cell imageView] setImage: [UIImage imageNamed: company.logo]];
    cell.detailTextLabel.text = company.stockPrice;

    return cell;
}

#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    int row = indexPath.row;
    NSLog(@"Cell at index: %d", row);
    self.childVC.company = self.dataAccess.companyList[row];
    //  [self.dataAccess test];
    self.childVC.dataAccess2 = self.dataAccess;
    [self.navigationController pushViewController:self.childVC animated:YES];
}

#pragma mark NSURLConnection Delegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to the instance variable you declared
    [_responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
     NSString *str =  [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
    NSMutableArray *responseArray= [NSMutableArray arrayWithArray:   [str componentsSeparatedByString:@"\n"]  ];

    //includes extra blank character at the end; just leaving it there for now
    NSLog(@"Response Array: %@", responseArray);

    for(int i=0;i<[self.dataAccess.companyList count];i++){
        Company *company = self.dataAccess.companyList[i];
        NSMutableString *string = responseArray[i];
        NSLog(@"adding stock price: %@ to company at index %d", string, i);
        company.stockPrice = string;

    } //simple loop for referring to items in companyList

    [self.tableView reloadData];

    NSLog (@"connectionDidFinishLoading Done");

}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog (@"connection didFailWithError: %@", error.debugDescription);

}

@end

A: The problem appears to be in your implementation of connectionDidFinishLoading:.
for(int i=0;i<[self.dataAccess.companyList count];i++){
    Company *company = self.dataAccess.companyList[i];
    NSMutableString *string = responseArray[i];
    ...
}

Here, you use the same iterator variable (i) for both companyList and responseArray, even though they are different sizes. You should ensure that i is less than the length of both responseArray and companyList:
for(int i=0;i<[self.dataAccess.companyList count] && i<[responseArray count];i++){
    Company *company = self.dataAccess.companyList[i];
    NSMutableString *string = responseArray[i];
    ...
}