text:
Q: Creating a heart rate monitor I have been trying to create a heart rate monitor with chart.js, but I'm at odds as how to represent the graph.
I want to build something along the lines of this demonstration:
link to demo.
The charts in chart.js are made like this:
var data = {
    labels: ["Heart Rate Monitor"],
    datasets: [
        {
            label: "heart rate",
            data: [65, 59, 80, 81, 56, 55, 40]
        }
    ]
};

var myLineChart = new Chart(ctx).Line(data, {});

And we can update the data like this:
myLineChart.datasets[0].points[0].value = 50;

Which would set the first value in the array: 65, to 50.
So I have made some attempts at creating an array with values that look like the demo, and move the first element to last, and every other element one down (-1) on the array and fill the chart with the values. This works, to a certain extent, but I am not able to change the speed of the values, which I need to do.
Suggestions?

A: You could use 2 series and just swap in the points. You might need to interpolate between points to smoothen out the animation.
I've used linear interpolation, but for a smoother curve you could probably use something else, but I believe if you have actual data, linear interpolation would work fine.
function getActualData() {
    var actualData = []
    for (var m = 0; m < 20; m++)
        actualData.push(45 + parseInt(Math.random() * 35))
    return actualData;
}

var ANIMATIONSTEPS = 200;

var myLineChart;
var labels;
var animationStep;
setInterval(function () {
    if (myLineChart === undefined) {
        var actualData = getActualData();

        // if we have only a few data points interpolate to fill out enough points to make the animation smooth
        var interpolationSteps = Math.ceil(ANIMATIONSTEPS / actualData.length);
        labels = []
        var data = []
        var blankData = []
        for (var i = 0; i < (actualData.length - 1); i++) {
            labels.push('')
            data.push(actualData[i])
            blankData.push(null)

            // push interpolation
            var difference = actualData[i + 1] - actualData[i];
            var interpolationStep = 1 / interpolationSteps;
            for (var j = 1; j < interpolationSteps; j++) {
                labels.push('')
                data.push(actualData[i] + difference * Chart.helpers.easingEffects["linear"](j * interpolationStep));
                blankData.push(null)
            }
        }
        labels.push('')
        data.push(actualData[i])
        blankData.push(null)

        var data = {
            labels: labels,
            datasets: [
                {
                    strokeColor: "rgba(243, 118, 27, 1)",
                    data: blankData
                },
                {
                    strokeColor: "transparent",
                    data: data
                }
            ]
        };

        var ctx = document.getElementById("myChart").getContext("2d");
        myLineChart = new Chart(ctx).Line(data, {
            animation: false,
            datasetFill: false,
            pointDot: false,
            datasetStrokeWidth: 5,
            showTooltips: false,
            scaleOverride: true,
            scaleSteps: 12,
            scaleStepWidth: 5,
            scaleStartValue: 30,
            scaleShowVerticalLines: false,
            scaleShowLabels: false,
        });

        animationStep = 0;
    }

    // the actual animation
    myLineChart.datasets[0].points[animationStep].value = myLineChart.datasets[1].points[animationStep].value
    myLineChart.update();
    animationStep++;

    // start new cycle
    if (animationStep >= labels.length) {
        myLineChart.destroy();
        myLineChart = undefined;
    }
}, 10)

Fiddle - http://jsfiddle.net/t795k4j3/

A: An EKG is a graph of the electrical activity in the heart over a period of time. It is not your heart rate (however an EKG can show your heart rate because it shows an increase in electrical activity at certain points over time giving a average heart rate).
So I don't believe it is even possible for you to use the heart rate in order to generate a graph similar to an EKG.


text:
Q: Passing options to rackup via a Sinatra application I'm new to ruby, learning Sinatra. While creating a Sinatra site by requiring 'sinatra' and setting up the routes directly under is pretty easy and rather well documented, creating an application by requiring 'sinatra/base' and writing a class that inherits from 'Sinatra::Base', while still relatively easy, is very poorly documented (maybe because it's a pretty recent feature of Sinatra).
And that's exactly what I am doing. I am not having too much trouble on the Sinatra part, however I am having a bit of trouble on the rackup/thin/server part. Apparently there are two ways to deploy the application: using Sinatra itself (using the run! method) and using a rackup file (typically config.ru).
Using Sinatra's run! method is extremely intuitive and works like a charm, but apparently it doesn't work if I want to deploy my app on heroku. As a matter of fact, almost all the Sinatra apps that I have encountered on GitHub use a config.ru file.
Using a rackup file might be equally intuitive, but I can't manage to understand how to pass options from the Sinatra app to the server (ir: the port). I tried to merge options to rackup's default options array:
MyApp::App.default_options.merge!(
  :run  => false,
  :env  => :production,
  :port => 4567
)

run MyApp::App

by adding options directly to the app:
MyApp::App.set :port, 4567
MyApp::App.set :run, false
MyApp::App.set :env, :production

run MyApp::App

by setting options from within the application class:
module MyApp
  class App < Sinatra::Base
    set :port, 4567
    set :run, false
    set :env, :production

    # ...

  # config.ru
  require 'app'

  run MyApp::App

All the methods above failed, either by showing error messages or by just not taking any of the options into consideration. So is there any way to pass options to rackup/thin/the sever via a Sinatra app when using a rackup file? Or the options in questions should be passed directly to rackup/thin/the sever via command-line options?
As a reference to the problem, here is the little Sinatra application I am building: https://github.com/AzizLight/Wiki/

A: I know I'm resurrecting an ancient question here, but I came across another useful solution not yet mentioned. As stated in this rack wiki tutorial:

the first line starting with #\ is treated as if it was options, allowing rackup arguments to be specified in the config file.

So if you wanted to set your host to 0.0.0.0 and port to 5656, you would add the following line to the beginning of your config.ru file:
#\ -o 0.0.0.0 -p 5656

A: You're actully going to pass options to thin on the command line directly or via a configuration file. See all options:
$ thin -h

For production, use a configuration file:
$ thin -C thin-production.yml -R config.ru start

Here is an example thin-production.yml file:
---
address: localhost
port: 3020
servers: 4
max_conns: 1024
max_persistent_conns: 512
timeout: 30
environment: production
pid: tmp/pids/thin-production.pid
log: log/thin-production.log
daemonize: true

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accessing a list from a different fragment So I have my MainActivity.java, I also have a FragmentA.java and a FragmentB.java.
In my MainActivity I have a BottomNavigation which allows me to switch between the two fragments.
MainActivity.java
private BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        Fragment selectedFragment = null;
        switch (menuItem.getItemId()) {
            case R.id.nav_a:
                selectedFragment = new FragmentA();
                break;
            case R.id.nav_b:
                selectedFragment = new FragmentB();
                break;
        }

        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();

        return true;
    }
};

Inside FragmentA I have a RecyclerView with an adapter of course and on each CardView there is a button, when i click that button i want to pass the corresponding object to the RecyclerView in FragmentB.
FragmentA.java
adapter.setOnItemClickListener(new RewardItemAdapter.OnItemClickListener() {
    @Override
    public void onItemClick(int position) {
        //When I click the item, pass theItem to FragmentB
        CustomObject theItem = items.get(position);
    }
});

FragmentB.java
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.fragment_b, container, false);
            itemsList = new ArrayList<>();
            itemsList.add(new CustomObject(R.drawable.picture, "Text", "More text.", 200));

//I'm guessing I want to add the CustomObject that I clicked to the list here so that I can display it in the RecyclerView

            recyclerView = v.findViewById(R.id.fragmentBRecyclerView);
            recyclerView.setHasFixedSize(true);
            layoutManager = new LinearLayoutManager(getContext());
            adapter = new FragmentBItemAdapter(itemsList);
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setAdapter(adapter);

            return v;
        }

The only issue is I have no idea how to, I tried using Interfaces but I couldn't implement it properly, I'm not sure if it's because I am instantiating a new instance of the fragments.

A: You could achieve this by two ways:
1) Through Interface Contract between the Fragment and Activity
class FragmentA: Fragment() {
    interface SomeInterfaceName {
        fun setSelectedItem(item: SomeItem)
    }
}

class FragmentA: Fragment() {
    interface AnotherInterfaceName {
        fun getSelectedItem(): SomeItem
    }
}

class ContainerActivity: Activity(), AnotherInterfaceName, SomeInterfaceName {
   var someItem: SomeItem? = null

    fun setSelectedItem(item: SomeItem) {
        someItem = item
        // inflate your FragmentB
    }

    fun getSelectedItem(): SomeItem {
        return someItem;
    }
}

But the best solution in my opinion is to use a shared ViewModel for this case.
You can read about this he here under "Share data between fragments" section.

A: Doing the job by interface is correct, But you have to bind it to the Fragment in the onAttached lifeCycle method.
Define an Interface. OnFragmentInteractionListener.java
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(String args);
}

Then Implement your activity with the interface.
    public class MainActivity extends ActionBarActivity implements OnFragmentInteractionListener{

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

        @Override
        onFragmentInteraction(String args){
            **// Made the Change Here**
            // Send Local Broadcast Receiver
            Intent intent = new Intent("UPDATE_LIST");
            intent.putExtra("TYPE", 0);
            // Change the args to get position or the relevant param
            intent.putExtra("POSITION", selectedPosition);
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        }
   }

In the FragmentA.java,
public class FragmentA extends Fragment {
    OnFragmentInteractionListener mCallback;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnFragmentInteractionListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    ...

    adapter.setOnItemClickListener(new RewardItemAdapter.OnItemClickListener()
    {
       @Override
       public void onItemClick(int position) {
       //When I click the item, pass theItem to FragmentB
            CustomObject theItem = items.get(position);
            // Send the selected Item Name to Main Activity through args
            mCallback.onFragmentInteraction(theItem.getName);
       }
    });

}

On your FragmentB.java class add Local Broadcast Receiver
public class FragmentBt extends Fragment{
    public static Fragment newInstance(){
       ...
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.layout, container, false);
        return v;
    }

    ...

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        // Register Local Broadcast Receiver
        LocalBroadcastManager.getInstance(getContext()).registerReceiver(mMessageReceiver, new IntentFilter("UPDATE_LIST"));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Destroy the  Local Broadcast Receiver
        LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mMessageReceiver);
    }

    // Create Broadcast Receiver instance
    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.hasExtra("POSITION")){
                mAdapter.notifyItemChanged(intent.getIntExtra("POSITION", 0));
                // Update Adapter as the requirement
            }
        }
    };

}

Hope this will help.
Cheers!!


text:
Q: Campo do tipo type="email" despreza o ValidationMessageFor asp.net mvc? Quando se usa este tipo de campo ele despreza ValidationMessageFor?
Na classe
[Required(ErrorMessage = "Informe o seu login.")]
[DataType(DataType.EmailAddress, ErrorMessage = "Por favor insira ...")]
[StringLength(50, ErrorMessage = "O número de caracteres permitidos é 50.")]
public string login { get; set; }

No formulário
@Html.TextBoxFor(x => x.login, new { placeholder =
     @Projeto.WEB.Celular.Resources.HomeText.txtRecuperaSenha,
     @class = "form-control input-lg", type = "email", })
@Html.ValidationMessageFor(x => x.login)


text:
Q: Select two or more consecutive rows based on a criteria using python I have a data set like this:
user        time              city    cookie    index
A        2019-01-01 11.00     NYC     123456      1
A        2019-01-01 11.12     CA      234567      2
A        2019-01-01 11.18     TX      234567      3
B        2019-01-02 12.19     WA      456789      4
B        2019-01-02 12.21     FL      456789      5
B        2019-01-02 12.31     VT      987654      6
B        2019-01-02 12.50     DC      157890      7
A        2019-01-03 09:12     CA      123456      8
A        2019-01-03 09:27     NYC     345678      9
A        2019-01-03 09:34     TX      123456      10
A        2019-01-04 09:40     CA      234567      11

In this data set I want to compare and select two or more consecutive which fit the following criteria:

*

*User should be same

*Time difference should be less than 15 mins

*Cookie should be different

So if I apply the filter I should get the following data:
user        time              city    cookie    index
A        2019-01-01 11.00     NYC     123456      1
A        2019-01-01 11.12     CA      234567      2
B        2019-01-02 12.21     FL      456789      5
B        2019-01-02 12.31     VT      987654      6
A        2019-01-03 09:12     CA      123456      8
A        2019-01-03 09:27     NYC     345678      9
A        2019-01-03 09:34     TX      123456      10

So, in the above, comparing first two rows(index 1 and 2) satisfy all the conditions above. The next two (index 2 and 3) has same cookie, index 3 and 4 has different user, 5 and 6 is selected and displayed, 6 and 7 has time difference more than 15 mins. 8,9 and 10 fit the criteria but 11 doesnt as the date is 24 hours apart.
How can I solve this using python dataframe? All help is appreciated.

What I have tried:
I tried creating flags using

shift()

cookiediff=pd.DataFrame(df.Cookie==df.Cookie.shift())
cookiediff.columns=['Cookiediffs']
timediff=pd.DataFrame(pd.to_datetime(df.time) - pd.to_datetime(df.time.shift()))
timediff.columns=['timediff']
mask = df.user != df.user.shift(1)

timediff.timediff[mask] = np.nan
cookiediff['Cookiediffs'][mask] = np.nan

A: This will do the trick:
import numpy as np

#you have inconsistent time delim-just to correct it per your sample data
df["time"]=df["time"].str.replace(":", ".")
df["time"]=pd.to_datetime(df["time"], format="%Y-%m-%d %H.%M")

cond_=np.logical_or(
    df["time"].sub(df["time"].shift()).astype('timedelta64[m]').lt(15) &\
    df["user"].eq(df["user"].shift()) &\
    df["cookie"].ne(df["cookie"].shift()),
    df["time"].sub(df["time"].shift(-1)).astype('timedelta64[m]').lt(15) &\
    df["user"].eq(df["user"].shift(-1)) &\
    df["cookie"].ne(df["cookie"].shift(-1)),
)

res=df.loc[cond_]

Few points- you need to ensure your time column is datetime in order to make the 15 minutes condition verifiable.
Then - the final filter (cond_) you obtain by comparing each row to the previous one, checking all 3 conditions OR by doing the same, but checking against the next one (otherwise you would just get all the consecutive matching rows, except the first one).
Outputs:
  user                time city  cookie  index
0    A 2019-01-01 11:00:00  NYC  123456      1
1    A 2019-01-01 11:12:00   CA  234567      2
4    B 2019-01-02 12:21:00   FL  456789      5
5    B 2019-01-02 12:31:00   VT  987654      6
7    A 2019-01-03 09:12:00   CA  123456      8
8    A 2019-01-03 09:27:00  NYC  345678      9
9    A 2019-01-03 09:34:00   TX  123456     10

A: You could use regular expressions to isolate the fields and use named groups and the groupdict() function to store the value of each field into a dictionary and compare the values from the last dictionary to the current one. So iterate through each line of the dataset with two dictionaries, the current dictionary and the last dictionary, and perform a re.search() on each line with the regex pattern string to separate each line into named fields, then compare the value of the two dictionaries.
So, something like:
import re
c_dict=re.search('(?P<user>\w) +(?P<time>\d{4}-\d{2}-\d{2} \d{2}\.\d{2}) +(?P<city>\w+) +(?P<cookie>\d{6}) +(?P<index>\d+)',s).groupdict()

for each line of your dataset. For the first line of your dataset, this would create the dictionary {'user': 'A', 'time': '2019-01-01 11.00', 'city': 'NYC', 'cookie': '123456', 'index': '1'}. With the fields isolated, you could easily compare the values of the fields to previous lines if you stored those in another dictionary.


text:
Q: Type of a passed parameter in a CL CALL statement On my iSeries running i/OS 6.1, I have a CL program that I'm cleaning up a bit.  In this program there is a bunch of Cut-and-paste code of the form:
IF COND(&ENV='PRD') THEN(DO)
    CALL JCHKSTS PARM(&RS '127.0.0.1' '6500')
    /* more junk here */
ENDDO
IF COND(&ENV='TST') THEN(DO)
    CALL JCHKSTS PARM(&RS '127.0.0.1' '16500')
    /* more junk here, same as in the first block */
ENDDO
/* repeat for several more &ENV values */

Naturally when I saw this, my first thought is, let's move that port number into a variable and eliminate all the duplicate blocks of code, so I ended up with:
DCL &ENVPORT *CHAR(6)
IF COND(&ENV='PRD') THEN(CHGVAR VAR(&ENVPORT) VALUE('6500'))
IF COND(&ENV='TST') THEN(CHGVAR VAR(&ENVPORT) VALUE('16500'))
CALL JCHKSTS PARM(&RS '127.0.0.1' &ENVPORT)
/* more junk here, but only one copy of it now. */

When I run this code, it fails, because as it turns out the JCHKSTS program expects a string as its third parameter (which it converts to an integer internally), and the &ENVPORT variable, despite being declared as a string and initialized with a string value, is apparently not being passed as a string.  (checking the parameters from within JCHKSTS shows a value of MAXINT for the port value.)
I worked around this by the cheap expedient of changing the value from '6500' to '6500 ', but I don't understand why it didn't work right in the first place; the IBM documentation says:

A program variable can be passed if the call is made from a CL program or ILE CL procedure, in which case the receiving program must declare the field to match the variable defined in the calling CL program or ILE CL procedure.

And that sure reads to me like, the receiving program expects a string, I declared the variable as a 6-character string, it should work.
So, did I miss something?  How should I declare the variable in order for the receiving program to see it as a string representation of a number, instead of as an actual number?

A: Something is not right with your sample.
First DCL &ENVPORT *CHAR(6) is not valid.
It should be DCL &ENVPORT *CHAR 6 or fully DCL VAR(&ENVPORT) TYPE(*CHAR) LEN(6).
Second JCHKSTS is called once with a constant value of '6500', again with '16500', and your workaround is '6500 ' none of which are a length of 6.
If you set the correct string length it should work as you expect.

A: The default length for a character variable passed as a literal is 32.  My guess is that JCHKSTS is expecting a 32 byte variable.  Try DCL &ENVPORT *CHAR 32

A: I have not seen this type of declaration before
DCL &ENVPORT *CHAR(6)

I'm used to seeing it this way:
DCL VAR(&ENVPORT) TYPE(*CHAR) LEN(6)

or perhaps this way:
DCL &ENVPORT *CHAR LEN(6)

IBM reference


text:
Q: split up a radForm into multiple files I have tried multiple ways to do this.
I have a Telerik Radform, it has a tabbed interface.
Due to that the code is getting largeish, around 3,000 lines.
I would like to have a separate file for each of the tabs - there are currently 5 different tabs.
I have tried using a partial class inheriting from my main form by:

*

*step 1 - created a blank code file.

*step 2 - put my namespace and create a partial class from my main form.

*step 3 - move a button click event from my main form file to my new file

The code runs, but if I double click the button in the designer it takes me back to the spot where the code used to be - the RadForm1.cs file not the StopCreation_code.cs file.
Here is my namespace and class from my main file:
namespace Flex_EDI_Console
{
    public partial class RadForm1 : Telerik.WinControls.UI.RadForm
    {

and here is my new file and the button click event I moved:
namespace Flex_EDI_Console

{
    public partial class RadForm1
    {
        private void radButton31_Click(object sender, EventArgs e)
        {
            //Flex_EDI_Console.stop_details newStop = new Flex_EDI_Console.stop_details();

            DateTime shipDateToSearch = Convert.ToDateTime("1/1/2017");

            //this.radDataEntry1.DataSource = newStop;
            var consingeeList = (from c in dbContext.stop_details where c.ship_date > shipDateToSearch select c.con_name).ToArray().Distinct();

            this.consignee_name_DD.DataSource = consingeeList;
            this.consignee_name_DD.AutoCompleteMode = AutoCompleteMode.Suggest;
            this.consignee_name_DD.DropDownListElement.AutoCompleteSuggest.SuggestMode = Telerik.WinControls.UI.SuggestMode.Contains;

            consignee_lb.Text = "Consignee - found " + consingeeList.Count();

        }
    }
 }

Also, the CodeCreation_code.cs opens up a form designer.
Thank you for any advice....I used to use regions for this but I am trying to stay away from that.

A: Unfortunately, I don't think the Form Designer supports this kind of the scenario. Take a look at the following statement from MSDN forum.

The Windows Forms Designer does not support dividing a designable
  type's definition into more than two partial implementations. This
  restriction includes creating a new class file that contains a third
  partial definition of the type, as well as adding a third partial
  class definition of the type in either the main file or the designer
  file. Members defined this way will not be visible in the Windows
  Forms Designer. See
  http://msdn.microsoft.com/en-us/library/ms171843.aspx
This is by design and I don't think you the Windows Forms Designer
  will work with your secondary partial class.

And we know that the RadForm control is an extension of the standard Windows Form. So its Form Designer would not support that either.
However, you should be able to use the navigation options or relevant keyboard shortcuts in VS to locate your partial class files.
Please refer to this link for more details.


text:
Q: Joomla Virtuemart - Identify new DB records - PHP I am trying to write some code which i will execute from a cron job daily, which will email me the product_sku field from #__virtuemart_products where the date is today. I have started by just trying to access the data through the following code:
    <?php

// Get a db connection.
$db = JFactory::getDbo();

// Create a new query object.
$query = $db->getQuery(true);

// Select all records from the user profile table where key begins with "custom.".
// Order it by the ordering field.
$query->select($db->quoteName(array('product_sku')));
$query->from($db->quoteName('#__virtuemart_products'));
//$query->where($db->quoteName('profile_key') . ' LIKE '. $db->quote('\'custom.%\''));
$query->where($db->quoteName (DATE_FORMAT('created_on', '%Y-%m-%d')) = CURDATE();
$query->order('ordering ASC');

// Reset the query using our newly populated query object.
$db->setQuery($query);

// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();

$db->setQuery($query);
$row = $db->loadRow();
print_r($row);
?>

I have been working with joomla for quite some time, but this is the first time that i have tried to write something from scratch. When i run this i get a 500 error, and i'm not sure where to start to try and fix it? Any help would be most appreciated.
Best Regards
Donna


text:
Q: Tree with $k$ edges is a subgraph of any graph with all vertices of degree $\geq k$.
Let $T$ be a tree with $k$ edges. Let $G$ be a graph where every vertex has a degree of at least $k$. Show that $T$ is a subgraph $G$.

I know this implies that in a graph where every vertex is at least $k$, you can find a copy of every tree with $k$ edges, but I'm stuck here.

A: Hint: Induction on $k$ (deleting a leaf to apply the induction hypothesis).

A: Here's a rough idea; I'll leave you to fill in the details.
We proceed algorithmically.
Pick a vertex $u$ in $T$ and map it to a vertex $\varphi(u)$ in $G$.  Mark $u$ as "mapped" and $\varphi(u)$ as "used".
While there are unmapped vertices in $T$, pick a vertex $x$ in $T$ that is a neighbor of a mapped vertex $w$.  Map it to a vertex $\varphi(x)$ in $G$ that is an unused neighbor of $\varphi(w)$.  Mark $x$ as "mapped" and $\varphi(x)$ as "used".
What remains is to check (a) $\varphi(x)$ always exists, and (b) if $ab$ is an edge in $T$ then $\varphi(a)\varphi(b)$ is an edge in $G$.


text:
Q: Hibernate - INSERT QUERY doesn't work I'm tring to insert data from textfield into database, but my code doesn't work (although there is no errors in console), what am I doing wrong? here is a code:
        Query query = entityManager.createNativeQuery("INSERT INTO Employee(idemployee, name, lastname,"
                + "gender, position, salary, phonenumber, adress) VALUES (:idemployee, :name, :lastname, :gender,"
                + ":position, :salary, :phonenumber, :adress )");

        Employee em = new Employee();

        em.setEID(emplID.getText());
        em.setName(emplName.getText());
        em.setLastName(empllastName.getText());
        em.setGender(emplGender.getText());
        em.setPosition(emplPosition.getText());
        em.setSalary(emplSalary.getText());
        em.setPhonenumber(emplphoneNumber.getText());
        em.setAddress(emplAdress.getText());

        query.setParameter("idemployee", em.getEID());
        query.setParameter("name", em.getEID());
        query.setParameter("lastname", em.getEID());
        query.setParameter("gender", em.getEID());
        query.setParameter("position", em.getEID());
        query.setParameter("salary", em.getEID());
        query.setParameter("phonenumber", em.getEID());
        query.setParameter("adress", em.getEID());

        entityManager.getTransaction().commit();

A: The use of named parameters is not defined for native queries. From the JPA specification (section 3.6.3 Named Parameters):
Named parameters follow the rules for identifiers defined in Section 4.4.1. The use of named parameters applies to the Java Persistence query language, and is not defined for native queries. Only positional parameter binding may be portably used for native queries.
So try the following instead:
Query query = entityManager.createNativeQuery("INSERT INTO Employee(idemployee, name, lastname,"
            + "gender, position, salary, phonenumber, adress) VALUES (?1, ?2, ?3, ?4,"
            + "?5, ?6, ?7, ?8 )");

    Employee em = new Employee();

    em.setEID(emplID.getText());
    em.setName(emplName.getText());
    em.setLastName(empllastName.getText());
    em.setGender(emplGender.getText());
    em.setPosition(emplPosition.getText());
    em.setSalary(emplSalary.getText());
    em.setPhonenumber(emplphoneNumber.getText());
    em.setAddress(emplAdress.getText());

    query.setParameter(1, em.getEID());
    query.setParameter(2, em.getEID());
    query.setParameter(3, em.getEID());
    query.setParameter(4, em.getEID());
    query.setParameter(5, em.getEID());
    query.setParameter(6, em.getEID());
    query.setParameter(7, em.getEID());
    query.setParameter(8, em.getEID());

    query.setString("status", "purged");
    int rowsCopied=query.executeUpdate();

    entityManager.getTransaction().commit();

Note that in JPA >= 2.0 you can use named parameters in native queries.
For more information, please follow the
JPA/Hibernate Native Queries do not recognize Parameters


text:
Q: Action Hook: item.create not passing data I have three action hooks on my 'subscribers' collection in my application:
'item.update.subscribers' => function (array $data) {}
'item.delete.subscribers' => function (array $data) {}
'item.create.subscribers' => function (array $data) {}

and the following filter hook:
'item.create.subscribers:before' => function (\Directus\Hook\Payload $payload) {}

All hooks except for action item.create.subscribers hook work as expected. This is the error I'm getting in the browser console:

if I change the function arg to function ($data), $data is null.

A: @JRedford - It seems like; there is an issue for storing the data and it's not an issue of hooks.
Can you please confirm once that the data stored successfully in DB?
If yes - then check the logs as @RANGER suggested.


text:
Q: HTML form Radio button positioning My question is pretty basic. its about the placement of my radio button
The buttons are slightly below its adjacent text. how to position it exactly in front of its text
Click at the link of sign up form as it provides the image of my problem
   sign up form

A: see this form the radio buttons are exactly before the text

<!DOCTYPE html>

        <title></title>

    <form >

    Name

    <input type="text">

    Email

    <input type="email" name="">

    Date

    <input type="date" name="">

    Password

    <input type="password" name="">

    Color

    <input type="color" name="">

    Select Any One
    <input type="checkbox" name="">Travel
    <input type="checkbox" name="">Food

    <input type="checkbox" name="">Hotel

    Select Gender
    <input type="radio" name="gender">Male
    <input type="radio" name="gender">FeMale

    <select>
        <option>Select Box</option>
    </select>

    <textarea rows="4" cols="50"></textarea>

    </form>

A: Removing width:100% from the following code solved the problem in your jsfiddle
*{
margin:0px auto;

}

Its because that style was applicable for all the elements the text and radio button was misplaced


text: Q: Плагин на отображение контента в папках Здравствуйте! Есть ли на wordpress плагин который допустим отображал контент в папках? Например я удалил файл из папки, заменил на новый и новый файл отобразился на сайте. Или возможно такое реализовать без плагинов?


text:
Q: how to post image with ajax without form-data? I tried var $pic1 = document.getElementById("pic").value; give the image path: C:fakepath/pictures/pic.jpg
Solutions always include sending in form-data. However, I could not do it.
my images folder: /img
I want image upload to 'img' folder after INSERT process.
view : https://i.stack.imgur.com/t7Gxx.png

<input type="text" class="form-control" id="input1" name="name" placeholder="Name">

            <input type="file" class="custom-file-input" id="pic" aria-describedby="inputGroupFileAddon01" accept=".jpg,.gif,.png">
            Choose Image

        <input type="hidden" name="projeid" value="<?php echo $_POST['proje_id']; ?>">
        <button type="submit" name="add"  id="add" class="btn btn-primary btn-md btn-block">Add</button>

$('#add').click(function(){
    var name = document.getElementById('input1').value;
    var action = 'insert';
    $.ajax({
        url:"data/action.php",
        method:"POST",
        data: {
            name: name,
            action: action
        },
        success:function(data) {
            load_data(projid);
        }
    });
});

--data/action.php--
if($_POST["action"] == "insert") {
    $query = "INSERT INTO grundriss (name) VALUES ('".$_POST["name"]."')";
    $statement = $db->prepare($query);
    $statement->execute();

    echo '
Data Inserted...
';
}

A: Try to convert image to base64 and then post it with ajax.


text:
Q: Disable SSH Public Key Login for a user when her Active Directory account is disabled I have many users in my environment who deploy their public keys on the linux servers for password-less and secure login via SSH.
All these users have accounts on our Active Directory, however, when a user leaves the company and we disable her corresponding AD account, her keys are still there and she can still login to all servers that have her public keys deployed.
Is there any way I can prevent the user from logging in to a server via her public key when her AD account is disabled, locked, expired or deleted?
Note: We use PBIS-Open for AD authentication

A: You can set the user shell to /sbin/nologin, it might be also a different path depending on the distribution and version.
usermod --shell /sbin/nologin <user-name>

Additionally you can set the expire date as well.
usermod --shell /sbin/nologin --expiredate 1 <user-name>

Depending on your configuration, these information might also be configured in LDAP, NIS or directly in AD. In those cases you might have to execute some different commands to alter the login shell and the expiration date.


text:
Q: Fail to run MySQL in Mac OSX 10.5.8 my mac is a powerPC.  and I have tried both 64 bit and 32 bit version.
Both return me "bad CPU type in executable"   when I try to do this /usr/local/mysql/bin/mysql
I followed all the steps as specified in the mysql official website.

A: All the versions on http://dev.mysql.com/downloads/mysql/ for Mac OSX are for x86 that is Intel computers.


text:
Q: React useEffect: "Can't perform a React state update on an unmounted component" with Redux I am building an e-commerce website and I have a reducer to calculate the total price, but when I submit the order in the end I get this error

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

The reducer
export const totalReducer = (total = 0, action) => {
  switch (action.type) {
    case CALCULATE_TOTAL:
      for (let i = 0; i < action.data.length; i++) {
        total += parseFloat(action.data[i].price) * action.data[i].count;
      }
      return total;
    default:
      return 0;
  }
};

The action
export const calculateTotal = (data) => {
  return {
    type: CALCULATE_TOTAL,
    data,
  };
};

I am using a useEffect to change the total price
 useEffect(() => {
    dispatch(calculateTotal(foods));
  }, [foods]);

This doesn't trigger any warnings, but when I move to the checkout page and submit the form below I get the error after getting redirected to /submitted, and the website starts lagging.
 const total = useSelector((state) => state.totalReducer);

  const submitHandler = (e) => {
    e.preventDefault();
    history.push("/submitted");
  };

  return (

Total Price = {total}

 <form className="information-form" onSubmit={submitHandler} action="">
//////////////
</form>

How can I clean useDispatch in Redux and what's causing the error this late in the process?


text:
Q: "Simple Dynamic" Dropdown menu in django form First, I am quite new with django...
I am trying to add a dropdown menu of available distinct Users (by name and coming from my db "dynamically") in a form.
I am using django 2.2.6.
# MyCustomForm
class DetailedReportForm(forms.Form):
    AVAILABLE_USERS = MyUserModel.objects.order_by().values_list('name').distinct()
    selected_date = forms.DateTimeField(input_formats=['%d/%m/%Y'], required=True, widget=DateInput())
    selected_user = forms.CharField(label="Select a user", widget=forms.Select(choices=AVAILABLE_USERS))

# MyModel
class MyUserModel(models.Model):
    id = models.AutoField(db_column='Id', primary_key=True)
    name = models.CharField(db_column='Name', unique=True, max_length=90)
    ...
    def __str__(self):
        return str(self.name)

The issue I am facing is my queryset is not working (not sure why) as it is giving me the following: not enough values to unpack (expected 2, got 1)
I tried to google it but still not very clear to me what this error message means.
Can someone please explain what this django error means so I can fix it and include the dropdown list in my form?

A: The problem is choices argument expecting list of tuples like this: [(1, "one"), (2, "two")]. First element in tuple actual value to store in DB, second is human readable representation.
But actually in your case you can just use ModelChoiceField instead:
class DetailedReportForm(forms.Form):
    AVAILABLE_USERS = MyUserModel.objects.order_by().values_list('name').distinct()
    selected_date = forms.DateTimeField(input_formats=['%d/%m/%Y'], required=True, widget=DateInput())
    selected_user = forms.ModelChoiceField(label="Select a user", queryset=MyUserModel.objects.order_by().distinct("name"))

Otherwise list of available options wiil not updated dynamically, since code inside form class running only once on django starting.


text:
Q: How to use jCarousel with multiple versions of jQuery I am using jCarousel (https://sorgalla.com/jcarousel/) for a gallery. If I use only one version of jQuery, only version 1.12.4 in my case, everything is working correctly for me. With this code, everything is perfect:

The problem is that in my application, I have some legacy code that requires jQuery 1.3.1. I need to include both jQuery 1.12.4 and jQuery 1.3.1. But when I use this, the jCarousel gallery does not work anymore:

I understand that the problem is that I am including both jQuery 1.3.1 and 1.12.4. I am trying to use the jQuery.noConflict() solution explained at https://api.jquery.com/jquery.noconflict/ in order to load and use two versions of jQuery without problems. This is how I am trying to implement jQuery.noConflict():

I guess now I need to find "$" and replace it with "$jq1" in both of my jCarousel files, jquery_jcarousel_min.js and jcarousel_connected_carousels.js. You can see the content of those files at https://sorgalla.com/jcarousel/dist/jquery.jcarousel.min.js and https://sorgalla.com/jcarousel/examples/connected-carousels/jcarousel.connected-carousels.js. I already tried this that I am mentioning in this paragraph, but the jCarousel gallery stopped working. This is the content of my https://sorgalla.com/jcarousel/dist/jquery.jcarousel.min.js and https://sorgalla.com/jcarousel/examples/connected-carousels/jcarousel.connected-carousels.js files after I replaced "$" with "$jq1":
jquery.jcarousel.min.js
/*! jCarousel - v0.3.4 - 2015-09-23
* http://sorgalla.com/jcarousel/
* Copyright (c) 2006-2015 Jan Sorgalla; Licensed MIT */
!function(a){"use strict";var b=a.jCarousel={};b.version="0.3.4";var c=/^([+\-]=)?(.+)$jq1/;b.parseTarget=function(a){var b=!1,d="object"!=typeof a?c.exec(a):null;return d?(a=parseInt(d[2],10)||0,d[1]&&(b=!0,"-="===d[1]&&(a*=-1))):"object"!=typeof a&&(a=parseInt(a,10)||0),{target:a,relative:b}},b.detectCarousel=function(a){for(var b;a.length>0;){if(b=a.filter("[data-jcarousel]"),b.length>0)return b;if(b=a.find("[data-jcarousel]"),b.length>0)return b;a=a.parent()}return null},b.base=function(c){return{version:b.version,_options:{},_element:null,_carousel:null,_init:a.noop,_create:a.noop,_destroy:a.noop,_reload:a.noop,create:function(){return this._element.attr("data-"+c.toLowerCase(),!0).data(c,this),!1===this._trigger("create")?this:(this._create(),this._trigger("createend"),this)},destroy:function(){return!1===this._trigger("destroy")?this:(this._destroy(),this._trigger("destroyend"),this._element.removeData(c).removeAttr("data-"+c.toLowerCase()),this)},reload:function(a){return!1===this._trigger("reload")?this:(a&&this.options(a),this._reload(),this._trigger("reloadend"),this)},element:function(){return this._element},options:function(b,c){if(0===arguments.length)return a.extend({},this._options);if("string"==typeof b){if("undefined"==typeof c)return"undefined"==typeof this._options[b]?null:this._options[b];this._options[b]=c}else this._options=a.extend({},this._options,b);return this},carousel:function(){return this._carousel||(this._carousel=b.detectCarousel(this.options("carousel")||this._element),this._carousel||a.error('Could not detect carousel for plugin "'+c+'"')),this._carousel},_trigger:function(b,d,e){var f,g=!1;return e=[this].concat(e||[]),(d||this._element).each(function(){f=a.Event((c+":"+b).toLowerCase()),a(this).trigger(f,e),f.isDefaultPrevented()&&(g=!0)}),!g}}},b.plugin=function(c,d){var e=a[c]=function(b,c){this._element=a(b),this.options(c),this._init(),this.create()};return e.fn=e.prototype=a.extend({},b.base(c),d),a.fn[c]=function(b){var d=Array.prototype.slice.call(arguments,1),f=this;return this.each("string"==typeof b?function(){var e=a(this).data(c);if(!e)return a.error("Cannot call methods on "+c+' prior to initialization; attempted to call method "'+b+'"');if(!a.isFunction(e[b])||"_"===b.charAt(0))return a.error('No such method "'+b+'" for '+c+" instance");var g=e[b].apply(e,d);return g!==e&&"undefined"!=typeof g?(f=g,!1):void 0}:function(){var d=a(this).data(c);d instanceof e?d.reload(b):new e(this,b)}),f},e}}(jQuery),function(a,b){"use strict";var c=function(a){return parseFloat(a)||0};a.jCarousel.plugin("jcarousel",{animating:!1,tail:0,inTail:!1,resizeTimer:null,lt:null,vertical:!1,rtl:!1,circular:!1,underflow:!1,relative:!1,_options:{list:function(){return this.element().children().eq(0)},items:function(){return this.list().children()},animation:400,transitions:!1,wrap:null,vertical:null,rtl:null,center:!1},_list:null,_items:null,_target:a(),_first:a(),_last:a(),_visible:a(),_fullyvisible:a(),_init:function(){var a=this;return this.onWindowResize=function(){a.resizeTimer&&clearTimeout(a.resizeTimer),a.resizeTimer=setTimeout(function(){a.reload()},100)},this},_create:function(){this._reload(),a(b).on("resize.jcarousel",this.onWindowResize)},_destroy:function(){a(b).off("resize.jcarousel",this.onWindowResize)},_reload:function(){this.vertical=this.options("vertical"),null==this.vertical&&(this.vertical=this.list().height()>this.list().width()),this.rtl=this.options("rtl"),null==this.rtl&&(this.rtl=function(b){if("rtl"===(""+b.attr("dir")).toLowerCase())return!0;var c=!1;return b.parents("[dir]").each(function(){return/rtl/i.test(a(this).attr("dir"))?(c=!0,!1):void 0}),c}(this._element)),this.lt=this.vertical?"top":"left",this.relative="relative"===this.list().css("position"),this._list=null,this._items=null;var b=this.index(this._target)>=0?this._target:this.closest();this.circular="circular"===this.options("wrap"),this.underflow=!1;var c={left:0,top:0};return b.length>0&&(this._prepare(b),this.list().find("[data-jcarousel-clone]").remove(),this._items=null,this.underflow=this._fullyvisible.length>=this.items().length,this.circular=this.circular&&!this.underflow,c[this.lt]=this._position(b)+"px"),this.move(c),this},list:function(){if(null===this._list){var b=this.options("list");this._list=a.isFunction(b)?b.call(this):this._element.find(b)}return this._list},items:function(){if(null===this._items){var b=this.options("items");this._items=(a.isFunction(b)?b.call(this):this.list().find(b)).not("[data-jcarousel-clone]")}return this._items},index:function(a){return this.items().index(a)},closest:function(){var b,d=this,e=this.list().position()[this.lt],f=a(),g=!1,h=this.vertical?"bottom":this.rtl&&!this.relative?"left":"right";return this.rtl&&this.relative&&!this.vertical&&(e+=this.list().width()-this.clipping()),this.items().each(function(){if(f=a(this),g)return!1;var i=d.dimension(f);if(e+=i,e>=0){if(b=i-c(f.css("margin-"+h)),!(Math.abs(e)-i+b/2<=0))return!1;g=!0}}),f},target:function(){return this._target},first:function(){return this._first},last:function(){return this._last},visible:function(){return this._visible},fullyvisible:function(){return this._fullyvisible},hasNext:function(){if(!1===this._trigger("hasnext"))return!0;var a=this.options("wrap"),b=this.items().length-1,c=this.options("center")?this._target:this._last;return b>=0&&!this.underflow&&(a&&"first"!==a||this.index(c)0&&!this.underflow&&(a&&"last"!==a||this.index(this._first)>0||this.tail&&this.inTail)?!0:!1},clipping:function(){return this._element["inner"+(this.vertical?"Height":"Width")]()},dimension:function(a){return a["outer"+(this.vertical?"Height":"Width")](!0)},scroll:function(b,c,d){if(this.animating)return this;if(!1===this._trigger("scroll",null,[b,c]))return this;a.isFunction(c)&&(d=c,c=!0);var e=a.jCarousel.parseTarget(b);if(e.relative){var f,g,h,i,j,k,l,m,n=this.items().length-1,o=Math.abs(e.target),p=this.options("wrap");if(e.target>0){var q=this.index(this._last);if(q>=n&&this.tail)this.inTail?"both"===p||"last"===p?this._scroll(0,c,d):a.isFunction(d)&&d.call(this,!1):this._scrollTail(c,d);else if(f=this.index(this._target),this.underflow&&f===n&&("circular"===p||"both"===p||"last"===p)||!this.underflow&&q===n&&("both"===p||"last"===p))this._scroll(0,c,d);else if(h=f+o,this.circular&&h>n){for(m=n,j=this.items().get(-1);m++<h;)j=this.items().eq(0),k=this._visible.index(j)>=0,k&&j.after(j.clone(!0).attr("data-jcarousel-clone",!0)),this.list().append(j),k||(l={},l[this.lt]=this.dimension(j),this.moveBy(l)),this._items=null;this._scroll(j,c,d)}else this._scroll(Math.min(h,n),c,d)}else if(this.inTail)this._scroll(Math.max(this.index(this._first)-o+1,0),c,d);else if(g=this.index(this._first),f=this.index(this._target),i=this.underflow?f:g,h=i-o,0>=i&&(this.underflow&&"circular"===p||"both"===p||"first"===p))this._scroll(n,c,d);else if(this.circular&&0>h){for(m=h,j=this.items().get(0);m++<0;){j=this.items().eq(-1),k=this._visible.index(j)>=0,k&&j.after(j.clone(!0).attr("data-jcarousel-clone",!0)),this.list().prepend(j),this._items=null;var r=this.dimension(j);l={},l[this.lt]=-r,this.moveBy(l)}this._scroll(j,c,d)}else this._scroll(Math.max(h,0),c,d)}else this._scroll(e.target,c,d);return this._trigger("scrollend"),this},moveBy:function(a,b){var d=this.list().position(),e=1,f=0;return this.rtl&&!this.vertical&&(e=-1,this.relative&&(f=this.list().width()-this.clipping())),a.left&&(a.left=d.left+f+c(a.left)*e+"px"),a.top&&(a.top=d.top+f+c(a.top)*e+"px"),this.move(a,b)},move:function(b,c){c=c||{};var d=this.options("transitions"),e=!!d,f=!!d.transforms,g=!!d.transforms3d,h=c.duration||0,i=this.list();if(!e&&h>0)return void i.animate(b,c);var j=c.complete||a.noop,k={};if(e){var l={transitionDuration:i.css("transitionDuration"),transitionTimingFunction:i.css("transitionTimingFunction"),transitionProperty:i.css("transitionProperty")},m=j;j=function(){a(this).css(l),m.call(this)},k={transitionDuration:(h>0?h/1e3:0)+"s",transitionTimingFunction:d.easing||c.easing,transitionProperty:h>0?function(){return f||g?"all":b.left?"left":"top"}():"none",transform:"none"}}g?k.transform="translate3d("+(b.left||0)+","+(b.top||0)+",0)":f?k.transform="translate("+(b.left||0)+","+(b.top||0)+")":a.extend(k,b),e&&h>0&&i.one("transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd",j),i.css(k),0>=h&&i.each(function(){j.call(this)})},_scroll:function(b,c,d){if(this.animating)return a.isFunction(d)&&d.call(this,!1),this;if("object"!=typeof b?b=this.items().eq(b):"undefined"==typeof b.jquery&&(b=a(b)),0===b.length)return a.isFunction(d)&&d.call(this,!1),this;this.inTail=!1,this._prepare(b);var e=this._position(b),f=this.list().position()[this.lt];if(e===f)return a.isFunction(d)&&d.call(this,!1),this;var g={};return g[this.lt]=e+"px",this._animate(g,c,d),this},_scrollTail:function(b,c){if(this.animating||!this.tail)return a.isFunction(c)&&c.call(this,!1),this;var d=this.list().position()[this.lt];this.rtl&&this.relative&&!this.vertical&&(d+=this.list().width()-this.clipping()),this.rtl&&!this.vertical?d+=this.tail:d-=this.tail,this.inTail=!0;var e={};return e[this.lt]=d+"px",this._update({target:this._target.next(),fullyvisible:this._fullyvisible.slice(1).add(this._visible.last())}),this._animate(e,b,c),this},_animate:function(b,c,d){if(d=d||a.noop,!1===this._trigger("animate"))return d.call(this,!1),this;this.animating=!0;var e=this.options("animation"),f=a.proxy(function(){this.animating=!1;var a=this.list().find("[data-jcarousel-clone]");a.length>0&&(a.remove(),this._reload()),this._trigger("animateend"),d.call(this,!0)},this),g="object"==typeof e?a.extend({},e):{duration:e},h=g.complete||a.noop;return c===!1?g.duration=0:"undefined"!=typeof a.fx.speeds[g.duration]&&(g.duration=a.fx.speeds[g.duration]),g.complete=function(){f(),h.call(this)},this.move(b,g),this},_prepare:function(b){var d,e,f,g,h=this.index(b),i=h,j=this.dimension(b),k=this.clipping(),l=this.vertical?"bottom":this.rtl?"left":"right",m=this.options("center"),n={target:b,first:b,last:b,visible:b,fullyvisible:k>=j?b:a()};if(m&&(j/=2,k/=2),k>j)for(;;){if(d=this.items().eq(++i),0===d.length){if(!this.circular)break;if(d=this.items().eq(0),b.get(0)===d.get(0))break;if(e=this._visible.index(d)>=0,e&&d.after(d.clone(!0).attr("data-jcarousel-clone",!0)),this.list().append(d),!e){var o={};o[this.lt]=this.dimension(d),this.moveBy(o)}this._items=null}if(g=this.dimension(d),0===g)break;if(j+=g,n.last=d,n.visible=n.visible.add(d),f=c(d.css("margin-"+l)),k>=j-f&&(n.fullyvisible=n.fullyvisible.add(d)),j>=k)break}if(!this.circular&&!m&&k>j)for(i=h;;){if(--i<0)break;if(d=this.items().eq(i),0===d.length)break;if(g=this.dimension(d),0===g)break;if(j+=g,n.first=d,n.visible=n.visible.add(d),f=c(d.css("margin-"+l)),k>=j-f&&(n.fullyvisible=n.fullyvisible.add(d)),j>=k)break}return this._update(n),this.tail=0,m||"circular"===this.options("wrap")||"custom"===this.options("wrap")||this.index(n.last)!==this.items().length-1||(j-=c(n.last.css("margin-"+l)),j>k&&(this.tail=j-k)),this},_position:function(a){var b=this._first,c=b.position()[this.lt],d=this.options("center"),e=d?this.clipping()/2-this.dimension(b)/2:0;return this.rtl&&!this.vertical?(c-=this.relative?this.list().width()-this.dimension(b):this.clipping()-this.dimension(b),c+=e):c-=e,!d&&(this.index(a)>this.index(b)||this.inTail)&&this.tail?(c=this.rtl&&!this.vertical?c-this.tail:c+this.tail,this.inTail=!0):this.inTail=!1,-c},_update:function(b){var c,d=this,e={target:this._target,first:this._first,last:this._last,visible:this._visible,fullyvisible:this._fullyvisible},f=this.index(b.first||e.first)<this.index(e.first),g=function(c){var g=[],h=[];b[c].each(function(){e[c].index(this)<0&&g.push(this)}),e[c].each(function(){b[c].index(this)<0&&h.push(this)}),f?g=g.reverse():h=h.reverse(),d._trigger(c+"in",a(g)),d._trigger(c+"out",a(h)),d["_"+c]=b[c]};for(c in b)g(c);return this}})}(jQuery,window),function(a){"use strict";a.jcarousel.fn.scrollIntoView=function(b,c,d){var e,f=a.jCarousel.parseTarget(b),g=this.index(this._fullyvisible.first()),h=this.index(this._fullyvisible.last());if(e=f.relative?f.target<0?Math.max(0,g+f.target):h+f.target:"object"!=typeof f.target?f.target:this.index(f.target),g>e)return this.scroll(e,c,d);if(e>=g&&h>=e)return a.isFunction(d)&&d.call(this,!1),this;for(var i,j=this.items(),k=this.clipping(),l=this.vertical?"bottom":this.rtl?"left":"right",m=0;;){if(i=j.eq(e),0===i.length)break;if(m+=this.dimension(i),m>=k){var n=parseFloat(i.css("margin-"+l))||0;m-n!==k&&e++;break}if(0>=e)break;e--}return this.scroll(e,c,d)}}(jQuery),function(a){"use strict";a.jCarousel.plugin("jcarouselControl",{_options:{target:"+=1",event:"click",method:"scroll"},_active:null,_init:function(){this.onDestroy=a.proxy(function(){this._destroy(),this.carousel().one("jcarousel:createend",a.proxy(this._create,this))},this),this.onReload=a.proxy(this._reload,this),this.onEvent=a.proxy(function(b){b.preventDefault();var c=this.options("method");a.isFunction(c)?c.call(this):this.carousel().jcarousel(this.options("method"),this.options("target"))},this)},_create:function(){this.carousel().one("jcarousel:destroy",this.onDestroy).on("jcarousel:reloadend jcarousel:scrollend",this.onReload),this._element.on(this.options("event")+".jcarouselcontrol",this.onEvent),this._reload()},_destroy:function(){this._element.off(".jcarouselcontrol",this.onEvent),this.carousel().off("jcarousel:destroy",this.onDestroy).off("jcarousel:reloadend jcarousel:scrollend",this.onReload)},_reload:function(){var b,c=a.jCarousel.parseTarget(this.options("target")),d=this.carousel();if(c.relative)b=d.jcarousel(c.target>0?"hasNext":"hasPrev");else{var e="object"!=typeof c.target?d.jcarousel("items").eq(c.target):c.target;b=d.jcarousel("target").index(e)>=0}return this._active!==b&&(this._trigger(b?"active":"inactive"),this._active=b),this}})}(jQuery),function(a){"use strict";a.jCarousel.plugin("jcarouselPagination",{_options:{perPage:null,item:function(a){return''+a+""},event:"click",method:"scroll"},_carouselItems:null,_pages:{},_items:{},_currentPage:null,_init:function(){this.onDestroy=a.proxy(function(){this._destroy(),this.carousel().one("jcarousel:createend",a.proxy(this._create,this))},this),this.onReload=a.proxy(this._reload,this),this.onScroll=a.proxy(this._update,this)},_create:function(){this.carousel().one("jcarousel:destroy",this.onDestroy).on("jcarousel:reloadend",this.onReload).on("jcarousel:scrollend",this.onScroll),this._reload()},_destroy:function(){this._clear(),this.carousel().off("jcarousel:destroy",this.onDestroy).off("jcarousel:reloadend",this.onReload).off("jcarousel:scrollend",this.onScroll),this._carouselItems=null},_reload:function(){var b=this.options("perPage");if(this._pages={},this._items={},a.isFunction(b)&&(b=b.call(this)),null==b)this._pages=this._calculatePages();else for(var c,d=parseInt(b,10)||0,e=this._getCarouselItems(),f=1,g=0;;){if(c=e.eq(g++),0===c.length)break;this._pages[f]=this._pages[f]?this._pages[f].add(c):c,g%d===0&&f++}this._clear();var h=this,i=this.carousel().data("jcarousel"),j=this._element,k=this.options("item"),l=this._getCarouselItems().length;a.each(this._pages,function(b,c){var d=h._items[b]=a(k.call(h,b,c));d.on(h.options("event")+".jcarouselpagination",a.proxy(function(){var a=c.eq(0);if(i.circular){var d=i.index(i.target()),e=i.index(a);parseFloat(b)>parseFloat(h._currentPage)?d>e&&(a="+="+(l-d+e)):e>d&&(a="-="+(d+(l-e)))}i[this.options("method")](a)},h)),j.append(d)}),this._update()},_update:function(){var b,c=this.carousel().jcarousel("target");a.each(this._pages,function(a,d){return d.each(function(){return c.is(this)?(b=a,!1):void 0}),b?!1:void 0}),this._currentPage!==b&&(this._trigger("inactive",this._items[this._currentPage]),this._trigger("active",this._items[b])),this._currentPage=b},items:function(){return this._items},reloadCarouselItems:function(){return this._carouselItems=null,this},_clear:function(){this._element.empty(),this._currentPage=null},_calculatePages:function(){for(var a,b,c=this.carousel().data("jcarousel"),d=this._getCarouselItems(),e=c.clipping(),f=0,g=0,h=1,i={};;){if(a=d.eq(g++),0===a.length)break;b=c.dimension(a),f+b>e&&(h++,f=0),f+=b,i[h]=i[h]?i[h].add(a):a}return i},_getCarouselItems:function(){return this._carouselItems||(this._carouselItems=this.carousel().jcarousel("items")),this._carouselItems}})}(jQuery),function(a,b){"use strict";var c,d,e={hidden:"visibilitychange",mozHidden:"mozvisibilitychange",msHidden:"msvisibilitychange",webkitHidden:"webkitvisibilitychange"};a.each(e,function(a,e){return"undefined"!=typeof b[a]?(c=a,d=e,!1):void 0}),a.jCarousel.plugin("jcarouselAutoscroll",{_options:{target:"+=1",interval:3e3,autostart:!0},_timer:null,_started:!1,_init:function(){this.onDestroy=a.proxy(function(){this._destroy(),this.carousel().one("jcarousel:createend",a.proxy(this._create,this))},this),this.onAnimateEnd=a.proxy(this._start,this),this.onVisibilityChange=a.proxy(function(){b[c]?this._stop():this._start()},this)},_create:function(){this.carousel().one("jcarousel:destroy",this.onDestroy),a(b).on(d,this.onVisibilityChange),this.options("autostart")&&this.start()},_destroy:function(){this._stop(),this.carousel().off("jcarousel:destroy",this.onDestroy),a(b).off(d,this.onVisibilityChange)},_start:function(){return this._stop(),this._started?(this.carousel().one("jcarousel:animateend",this.onAnimateEnd),this._timer=setTimeout(a.proxy(function(){this.carousel().jcarousel("scroll",this.options("target"))},this),this.options("interval")),this):void 0},_stop:function(){return this._timer&&(this._timer=clearTimeout(this._timer)),this.carousel().off("jcarousel:animateend",this.onAnimateEnd),this},start:function(){return this._started=!0,this._start(),this},stop:function(){return this._started=!1,this._stop(),this}})}(jQuery,document);

jcarousel.connected-carousels.js
(function($jq1) {
    // This is the connector function.
    // It connects one item from the navigation carousel to one item from the
    // stage carousel.
    // The default behaviour is, to connect items with the same index from both
    // carousels. This might _not_ work with circular carousels!
    var connector = function(itemNavigation, carouselStage) {
        return carouselStage.jcarousel('items').eq(itemNavigation.index());
    };

    $jq1(function() {
        // Setup the carousels. Adjust the options for both carousels here.
        var carouselStage      = $jq1('.carousel-stage').jcarousel();
        var carouselNavigation = $jq1('.carousel-navigation').jcarousel();

        // We loop through the items of the navigation carousel and set it up
        // as a control for an item from the stage carousel.
        carouselNavigation.jcarousel('items').each(function() {
            var item = $jq1(this);

            // This is where we actually connect to items.
            var target = connector(item, carouselStage);

            item
                .on('jcarouselcontrol:active', function() {
                    carouselNavigation.jcarousel('scrollIntoView', this);
                    item.addClass('active');
                })
                .on('jcarouselcontrol:inactive', function() {
                    item.removeClass('active');
                })
                .jcarouselControl({
                    target: target,
                    carousel: carouselStage
                });
        });

        // Setup controls for the stage carousel
        $jq1('.prev-stage')
            .on('jcarouselcontrol:inactive', function() {
                $jq1(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $jq1(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '-=1'
            });

        $jq1('.next-stage')
            .on('jcarouselcontrol:inactive', function() {
                $jq1(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $jq1(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '+=1'
            });

        // Setup controls for the navigation carousel
        $jq1('.prev-navigation')
            .on('jcarouselcontrol:inactive', function() {
                $jq1(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $jq1(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '-=1'
            });

        $jq1('.next-navigation')
            .on('jcarouselcontrol:inactive', function() {
                $jq1(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $jq1(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '+=1'
            });
    });
})(jQuery);

How should I apply jQuery.noConflict to in order to make jCarousel (https://sorgalla.com/jcarousel/) work while I am invoking both jQuery 1.12.4 and 1.3.1 in my code? Thank you.

A: The solution was adding "jQuery.noConflict();" at the very beginning of jcarousel.connected-carousels.js, without having to replace "$" with "$jq1" at all.


text:
Q: right join where key is null in python pandas with MultiIndexes I have two dataframes with MultiIndexes, and I need to right join them and then get the items on the right side which didn't have a key match.
The preferred answer for how to do right join where key is null in python pandas suggests to do something like this:
In [1]: dfa = pd.DataFrame({'A': range(5)}, index=range(5))

In [2]: dfb = pd.DataFrame({'A': range(10, 15)}, index=range(3,8))

In [3]: dfa
Out[3]:
   A
0  0
1  1
2  2
3  3
4  4

In [4]: dfb
Out[4]:
    A
3  10
4  11
5  12
6  13
7  14

In [5]: dfb.loc[dfb.index - dfa.index]
Out[5]:
    A
5  12
6  13
7  14

but when I try that with my code, I get an error:
TypeError: cannot perform __sub__ with this index type: <class 'pandas.core.indexes.multi.MultiIndex'>

What options do I have given that MultiIndexes can't be subtracted from one another?

A: You do not need a join to get the items that did not match. A simpler way would be using the below:
df = dfb[dfb.index.isin(dfa.index) == False]

Alternate way, that uses join, would be:
a = dfa.join(dfb, lsuffix='a', how='right')
a[a.Aa.isnull()][['A']]

I do not know your exact requirement, but to get the result, 1st is probably a neater way of achieving the goal. Regards


text:
Q: Return complex object from an AJAX call Environment used: ASP.NET, jQuery
I have the following AJAX call:
var tempVar = JSON.stringify({plotID:currentId});

$.ajax({
       type: "POST",
       url: "testPage.aspx/getPlotConfig",
       data: tempVar,
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function(msg) {
       $('#xDimLbl').text(msg.xDim);
       $('#bDimLbl').text(msg.bDim);
       }
});

The code behind has the method getPlotConfig(string plotID) defined as
public static string getPlotConfig(string plotID)
{
      string x = "T1";
      string b = "T2";
      return Json(new { xDim= x, bDim= b });
}

Questions:

*

*When I do a build, I get the error: The name 'Json' does not exist in the current context Which namespace is amiss?

*Along with the two strings x and b, I would like to return a hash table whose key is a string and value is a list of comma separated strings. How do I do that and how to access each key value pair at the client side?

cheers

A: This could be referring to the Json method used in ASP.NET MVC controller. As your getPlotConfig function is static you cannot use this method. You may take a look at PageMethods. Here's an example:
[WebMethod]
[ScriptMethod]
public static object getPlotConfig(string plotID)
{
    var hash = new Dictionary<string, string>()
    {
        { "key1", "valueA,valueB" },
        { "key2", "valueC,valueD" },
    };
    var x = "T1";
    var b = "T2";
    return new { xDim = x, bDim = b, hash = hash };
}

And in javascript:
success: function(msg) {
   $('#xDimLbl').text(msg.d.xDim);
   $('#bDimLbl').text(msg.d.bDim);
   for(var key in msg.d.hash) {
       var value = msg.d.hash[key];
       // Do something with key and value...
    }
}


text:
Q: display textboxes centered inside a skewed rectangle How do I put centered textboxes inside each of the colored boxes in the image below?
Update: As requested, I'm adding my embarrassing attempt. I know it's bad, but I don't do design so I am kind of lost.
p.s. thanks for the down votes!
http://jsfiddle.net/Zrhe3/
table{width: 585px; height: 585px; background-image: url('http://i.stack.imgur.com/uknk9.png');}
input{background-color: transparent; width: 100%; border-style:none; font-size: 32px;}

        <input type="number" id="number" value="1" />

        <input type="number" id="number"  value="2" />

        <input type="number" id="number" value="3" />

        <input type="number" id="number" value="4" />

A: You can find a solution over here http://jsfiddle.net/ZC2bd/46/ but I'm sure you haven't looked for enough ;) google is your friend
HTML:

  <input id="top" type="text" />
  <input id="left" type="text" />
  <input id="right" type="text" />
  <input id="bottom" type="text" />

CSS:
div#background{
    display: block;
    width: 597px;
    height: 597px;
    background-image: url('http://i.stack.imgur.com/uknk9.png');
}
#top{
    width: 150px;
    height: 25px;
    position: absolute;
    margin: 135px 0 0 224px;
}
#left{
    width: 150px;
    height: 25px;
    position: absolute;
    margin: 290px 0 0 70px;
}
#right{
    width: 150px;
    height: 25px;
    position: absolute;
    margin: 290px 0 0 380px;
}
#bottom{
    width: 150px;
    height: 25px;
    position: absolute;
    margin: 435px 0 0 230px;
}

Concerning the HTML part it's pretty explicit, there is one container which contains four inputs.
In the CSS file, I've set your image in background of my container with fixed width and height.
Then I've created four id's for the inputs all with the property position set to absolute.
The absolute attribute allows you to set the position of an element taking as reference the parent element, here the
.
So since you know its size you can position your elements with the margin prooperty.
Hope it helps.


text:
Q: Binance ccxt fetch ohlcv exceeding 1000 limit Trying to create a loop that will get  all 5m interval ohlcv data for coins in pair_list between start and date (3 months)
Based on some discussions and snippets I've come up with the following, however, it doesn't work
import ccxt
import config
import pandas as pd
pd.set_option('display.max_rows', 1000)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

import warnings
warnings.filterwarnings('ignore')

import numpy as np
#np.printoptions(precision=2, suppress=True)

from datetime import datetime, timedelta, date, time

import datetime as dt

import datedelta
import calendar
import dateutil.relativedelta
from dateutil.relativedelta import relativedelta

start = str(int(dt.datetime(2021, 5, 1).replace(hour=1).timestamp() * 1000))
end = str(int(dt.datetime(2021, 2, 1).replace(hour=1).timestamp() * 1000))

for i in pair_list:

    startDate = end
    while startDate>start:

        bars[i] = 'exchange.fetch_ohlcv(binancePair[i], timeframe=timeframe, '
        if startDate is not None:
            bars[i] += 'since='+ str(startDate) +', limit=1000'
            d2[i] = pd.DataFrame(bars[i][:-1], columns =['timestamp', 'open', 'high', 'low', 'close',
            'volume' ])
            d[i] = pd.concat([d2[i], d[i]], axis=0, ignore_index=True, keys=None)
            startDate[i] = d[i].timestamp[0]

            d[i].reset_index(drop=True, inplace=True)
            d[i]['timestamp'] = pd.to_datetime(d[i]['timestamp'], unit='ms')

A: This isn't exactly the answer you are looking for, but it will definitely solve your problem (ccxt):
    limit=None

Code would look something like this(ccxt):
    start_date = int(datetime.datetime(2018, 1, 1, 10, 20).timestamp() * 1000)
    candles = exchange.fetch_ohlcv('BTC/USDT', timeframe='1d', since=start_date, 2012', limit=None)

That should get candles to present time, then you could easily amend pandas df.
I know the Binance exchange documents state 1000 limit, though when using their api they still allow large amounts of data, for instance this code works on Binance (binance api):
    candles = client.get_historical_klines("BTCUSDT", Client.KLINE_INTERVAL_1DAY, "1 Jan, 2018", "22 May, 2021")

I know what you want to do specifically, as some exchanges do need the limit.  Though the Binance exchange those code snippets will work.
I'll make time in a few days to answer the original question, until then i hope this helps.


text:
Q: Breeze validation messages are not production ready Breeze's default validation messages use the database field name as part of the displayed error message; such as, "EmpTeleNo is required".  Obviously, this probably shouldn't end up in the production version of our software.
But as we approach delivery of our software, it was hoped that this might be fixed, perhaps by inspecting the "Display" attribute from the model or something like that.  As far as I can tell, this issue still remains.
Has this problem been resolved or has anyone figured out a work-around?
Thanks.

A: This is not YET well documented but you can simply set the 'displayName' property on any dataProperty and this will override the autogenerated display name and will be used for all validation messages for this property. So
var custType = myEntityManager.metadataStore.getEntityType("Customer");
var dp = custType.getProperty("companyName");
dp.displayName = "My custom display name";

Also, see the "Customize the message templates" topic at the bottom of this page: http://www.breezejs.com/documentation/validation.
There is also an item on the Breeze User Voice that requests something very similar to what you are asking for. Please vote for it.
https://breezejs.uservoice.com/forums/173093-breeze-feature-suggestions


text:
Q: CSS only scrollable table body I want to use CSS to scroll only the table body. I found a few examples but they don't work well if the table rows length is different.
I started with this example:
https://codepen.io/pdg/pen/MayBJK
HTML code:

CSS only scrollable table body

by PDG

    Head 1
    Head 2
    Head 3
    Head 4

      1
      First row
      3 dsad sad sad sad sad sadsadsad sadasd asdsa
      4 dasd sad asdsad sad sadsa dasdsad

      1 dasd asd sadsadsad sadsad
      2dsadsadsa dsad sadasd sad sad sa
      A very long cell content comes here, just to test it all!!!
      4

      1
      2 dsad asd asd sad sad sad asdsadsad
      3

      1
      2
      3
      There is an empty cell above!

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
       Last row

Notes

The table uses flex properties to arrange the cell sizes, however, this tends to make them the same as "fixed width". To fix that, you need to create additional classes that target the td:nth-child() and th:nth-child() with a specific flex-basis property.

The height of the body also must be fixed and cannot be percentages (in the example above I use "vh")

CSS code:
.container{
  padding: 1rem;
  margin: 1rem;
}
.table-scroll{
  /*width:100%; */
  display: block;
  empty-cells: show;

  /* Decoration */
  border-spacing: 0;
  border: 1px solid;
}

.table-scroll thead{
  background-color: #f1f1f1;
  position:relative;
  display: block;
  width:100%;
  overflow-y: scroll;
}

.table-scroll tbody{
  /* Position */
  display: block; position:relative;
  width:100%; overflow-y:scroll;
  /* Decoration */
  border-top: 1px solid rgba(0,0,0,0.2);
}

.table-scroll tr{
  width: 100%;
  display:flex;
}

.table-scroll td,.table-scroll th{
  flex-basis:100%;
  flex-grow:2;
  display: block;
  padding: 1rem;
  text-align:left;
}

/* Other options */

.table-scroll.small-first-col td:first-child,
.table-scroll.small-first-col th:first-child{
  flex-basis:20%;
  flex-grow:1;
}

.table-scroll tbody tr:nth-child(2n){
  background-color: rgba(130,130,170,0.1);
}

.body-half-screen{
  max-height: 50vh;
}

.small-col{flex-basis:10%;}

It seemed to be a good idea and in their demo everything looks fine, but on a more complex example you can see that the columns are not vertical aligned very well. See my example below:
https://jsfiddle.net/pnfu321g/
I also tried a different example: http://jsfiddle.net/hashem/CrSpu/555/
But this also doesn't work well in my case, on complex tables with rows that have different widths.
Please suggest a css solution (no javascript) that will make a table with rows of any size to look good.
UPDATE
The reason why other solutions didn't worked for me was because I was using an older version of Mozilla Firefox - 57. And that's why almost evrything that I tested didn't worked. I marked the questions as duplicate.

A: You can use position:sticky on the th elements within the table head.
Basic example (CSS):
table.sticky-headers { width:100%; }
table.sticky-headers thead tr th { text-align:left; position:sticky; top:0; background:#fff; }

Basic markup (Add more rows to get scrollbars):

            Head 1
            Head 2
            Head 3
            Head 4
            Head 5

            Content 1
            Content 2
            Content 3
            Content 4
            Content 5

Working example here: http://jsfiddle.net/yp1xb7dj/

A: If you want fixed cell width and the text in cells with more content to break and fall on two-three lines, you can try specifying the cell width and the height will be fixed automatically:
table.sticky-headers thead tr th {
    width: 20%;
    text-align:left;
    position:sticky;
    top:0;
    background:#fff;
}

The result:


text:
Q: Datepicker function (count days between 2 dates)not working after call ajax I have 2 datepickers to count days between them:
$(function() {
    $("#datepicker2").datepicker();
    $("#datepicker3").datepicker({
        onSelect: showDays
    });
});

function showDays() {
    var start = $('#datepicker2').datepicker('getDate');
    var end = $('#datepicker3').datepicker('getDate');

    if (!start || !end)
        return;

    var days = (end - start) / 1000 / 60 / 60 / 24;
    $('#totaldays').val(days);
}

This works. Now the problem is with the next AJAX request the function showDays() stops working. I tried this inside success as others answers here suggest, but it still does not work.
$("#datepicker3").datepicker({
    onSelect: showDays
});

The AJAX call:
$(document).ready(function() {
    ///PARA SELECCIONAR NUMERO DE HABITACION
    $('#id_residencial').on('change', function() {
        var id_residencial = $(this).val();
        if (id_residencial) {
            $.ajax({
                type: 'POST',
                url: 'get_id_habitacion.php',
                data: 'id_residencial='+id_residencial,
                success: function(html) {
                    $('#id_habitacion').html(html);
                }
            });
        }
    });
});

SOLUTION:
I put $('.datepicker3').not('.hasDatePicker').datepicker();
$(document).ready(function() {
        ///PARA SELECCIONAR NUMERO DE HABITACION
        $('#id_residencial').on('change', function() {
            var id_residencial = $(this).val();
            if (id_residencial) {
                $.ajax({
                    type: 'POST',
                    url: 'get_id_habitacion.php',
                    data: 'id_residencial='+id_residencial,
                    success: function(html) {
                        $('#id_habitacion').html(html);
                        $('.datepicker3').not('.hasDatePicker').datepicker();
                    }
                });
            }
        });
    });

And it´s working :)


text:
Q: C++11 types for variables defined with auto I am reading Bjarne Stroustrup's book The C++ Programming Language, and in section 3.2.4, he demonstrates a class hierarchy, starting with an abstract class. His code looks something like this:
class Shape
{
public:
    virtual Point center()const = 0; //Point is a class defined elsewhere and is unimportant for this question
    virtual void move(Point to) = 0;

    virtual void draw()const = 0;
    virtual void rotate(int angle) = 0;
}

class Circle: public Shape
{
    //overrides functions
}

void rotate_all(vector<Shape*>& v, int angle)
{
    for(auto p:v)
        p->rotate(angle);
}

My question is this: what type is the p variable when the function rotate_all is called with a vector of Circle objects? If it was a Shape, then wouldn't the objects be sliced into generic Shape objects? If it was a Circle, then wouldn't the function work only for vectors of Circle objects, and not other subclasses of the Shape class?

A: rotate_all() is never called with "a vector of Circle objects". Its first argument is always a reference to std::vector<Shape*>.
The tricky part is, that type of this vector must not necessarily reflect what is stored inside - because you can put into it pointer to any class, that inherits from Shape (technically/ideologically speaking, this probably should be converted into "publicly inherits from Shape, but leave that).
Moreover, this vector will never store any instance of Shape, because it's an abstract class, so its instantiation is forbidden.
So, to illustrate:
class Circle: public Shape
{
    //cut
    virtual void draw() const override { printf("Circle!\n"); }
}

//add another class
class Square: public Shape
{
    //cut
    virtual void draw() const override { printf("Square!\n"); }
}

void draw_all(vector<Shape*>& v, int angle)
{
    for(auto p : v)
        p->draw(); //p is an iterator pointing internally to Shape*
}

Shape* c = new Circle();
Shape* s = new Square();

std::vector<Shape*> v;

v.push_back(c);
v.push_back(s);

draw_all(v);

Output:
Circle!
Square!

Simply speaking: Shape* is used here to easily introduce polymorphic behaviour for collection of objects.

A: A ranged based for loop will expand from:
for ( range_declaration : range_expression ) loop_statement

To
{
    auto && __range = range_expression ;
    for (auto __begin = begin_expr, __end = end_expr;  __begin != __end; ++__begin) {
        range_declaration = *__begin;
        loop_statement
    }
}

So here the auto variable declared in the for loop is set to the value of the beginning iterator which in your case is a Shape*.  Since it is a pointer no slicing will occur otherwise polymorphism would not be possible.

A: It is the value_type of the container in most cases (or slightly more accurate, the result of dereferencing begin) , which for your vector is Shape* and so as a pointer, no risk of slicing.
You can also use auto &p when you want to iterate something that contains values, but don't want to copy them (because you want to mutate them, performance, no copy-constructor, etc.).
http://en.cppreference.com/w/cpp/language/range-for has more details on exactly what the ranged for loop expands to, and how it determines the range for arrays, classes with a begin member and using ADL begin otherwise. The actual value type is the result of dereferencing the "iterator", and C++ auto just takes that right hand side type.
As an aside, in Visual Studio 2015 at least (cant remember for others), if you hover over a variable declared auto, it will try to show you the actual type, and some more detail if you hover over "auto" (e.g. it shows me the std::vector typedef).


text:
Q: Euclidean Domains Let F be a field, let k be a non-negative integer, and define a function $d$ from the set F* of non-zero elements of F to the set of non-negative integers by $d(a)=k \quad \forall a\in F^*$. Prove that $d$ is a Euclidean function on F and that F is a Euclidean domain.
I know that the definition of a Euclidean function is
Let R be an integral domain. A Euclidean function on R means a function $d:R^*\mapsto \mathbb{N}\cup {0}$,
   $R^*={\{r\in R| r \neq0}\}$ such that
i.) $d(ab)\ge d(a) \quad \forall a,b\in R^*$;
ii.) If $a,b\in R$ with $b \neq0$ then there exists $q,r\in R$ such that $a=bq+r$ and either $r=0$ or $d(r) \lt d(b)$.
and a Euclidean domain is an integral domain for which there exists a Euclidean function.
But I am unsure as how to apply this definition.

A: You can divide the problem in two parts. First prove that a field is an integral domain, and then prove that the function $d$ is an Euclidean function.
For the first part, recall the definition of a field and the definition of an integral domain. Mainly that a field is commutative, and that all non-zero elements are invertible.
For the second part, you can check that the first condition is trivially satisfied. For the second condition, try $q=b^{-1}a$ (why can we do this?)


text:
Q: VMware Workstation - Use a Dedicated NIC on a desktop with two NICs and two separate Routers thanks for any help in advance.

*

*Problem: I have a desktop with VMware Workstation Pro installed. I have two NICs installed. I also have two routers/networks in my home office since my ISP provides me with static IPs. I want to have my primary NIC on my desktop go to one network and keep all the traffic there. I want the secondary NIC to be plugged into a separate router and have all the VMware Workstation traffic go there.

*How do I configure this in VMware Workstation to work as described above? Do I need any static route statements to make this work correctly? If so, can you give me an example with two different private subnets?

*Can I achieve this without having to purchase a router that does VLANs and Inter-VLAN Routing?

*My goal is for all the network traffic for my virtual machines to go 100% to one router, while any other traffic and work I do on my Desktop goes to a primary router.
Thanks again. The more details the better. I know the products very well, but Networking isn't my strong suit.
I didn't realize this until I posted it, should I have posted this on StackExchange instead of superuser? I thought that is what I was doing until I realized it wasn't. :/

A: I assume your host OS is Windows. With bridged networking, this is relatively easy to achieve.

*

*Make Windows not use the secondary NIC unless required

*

*You could disable all protocols (IPv4, IPv6) in the connection properties

*You could make sure it doesn't have a default gateway set

*You could make it have a higher metric so its default gateway won't be used

*In VMware Virtual Network Editor, select an unused virtual network

*Set this network to be bridged specifically to your secondary NIC

*Make your VMs' virtual network adapters use this virtual network

If you want to do this with NAT, I'm not sure that's even possible.


text:
Q: How can I split one string into two variables in TypeScript? I have a string SVchnsSoQQjr5kafygOh,,,Skyrim and I'm trying to put the first 'string' into a variable, the 'Skyrim' into another variable and remove the ',,,'
I've tried .substr()
Expected output:
str = 'SVchnsSoQQjr5kafygOh,,,Skyrim'

strOne = 'SVchnsSoQQjr5kafygOh'
strTwo = 'Skyrim'

A: split is your friend

console.log('SVchnsSoQQjr5kafygOh,,,Skyrim'.split(',,,'));

To have two string variables assigned:

const foo = 'SVchnsSoQQjr5kafygOh,,,Skyrim'.split(',,,');

const [str1, str2] = foo;
console.log(str1, str2);


text:
Q: Fix image size in grid.arrange I am using grid.arrange to plot two ggplots side by side (in a single row) in a Jupyter notebook. When I do this the image plotted is too large and the plot height is larger than the screen which looks pretty bad. I want to fix the height (say 2 or 3 inches) of the image. Is there a way to do this?

EDIT
The code used
library(ggplot2)
library(gridExtra)

df <- data.frame(group = as.factor(c("Base", "Online", "TV",  "Print")),value = c(60, 12, 7, 6))
df_0 <- data.frame( group = as.factor(c("Base")), value = c(100))

plot_left <- ggplot(transform(transform(df, value=value/sum(value)), labPos=cumsum(value)-value/2),
                    aes(x="", y = value, fill = group)) + geom_bar(width = 1, stat = "identity") + coord_polar(theta = "y") +
  theme_void() + labs(title = "Decompose Sales") + geom_text(aes(y=labPos, label=paste0(round(100*value, 0), "%")), size = 3)

plot_right <- ggplot(transform(transform(df_0, value=value/sum(value)), labPos=cumsum(value)-value/2), aes(x="", y = value)) +
  geom_bar(width = 1, stat = "identity") + coord_polar(theta = "y") + theme_void() +
  labs(title = "Total Sales") + geom_text(aes(y=labPos, label=paste0(round(100*value, 0), "%")), col = "orange", size = 3)

grid.arrange(plot_right+ guides(fill = "none") ,plot_left+ guides(fill = "none"), ncol=2, widths=c(3/10, 3/10))


text:
Q: using mcrypt with enigma algorithm i have the following example Code for using mcrypt with php:
/* Open the cipher */
$td = mcrypt_module_open('tripledes', '', 'ofb', '');

/* Create the IV and determine the keysize length, use MCRYPT_RAND
 * on Windows instead */
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
$ks = mcrypt_enc_get_key_size($td);

/* Create key */
$key = substr(md5('this is a very good key'), 0, $ks);

/* Intialize encryption */
mcrypt_generic_init($td, $key, $iv);

/* Encrypt data */
$encrypted = mcrypt_generic($td, 'This is very important data');

/* Terminate encryption handler */
mcrypt_generic_deinit($td);

/* Initialize encryption module for decryption */
mcrypt_generic_init($td, $key, $iv);

/* Decrypt encrypted string */
$decrypted = mdecrypt_generic($td, $encrypted);

/* Terminate decryption handle and close module */
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

/* Show string */
echo trim($decrypted) . "\n
";

This code is working fine, but I have to use "enigma" instead of tripledes.
If I'm changing the first line to:
mcrypt_module_open('enigma', '', 'ofb', '');

I get the following errors:
Warning: mcrypt_module_open(): Could not open encryption module in /Applications/MAMP/htdocs/test/mcrypt.php on line 13
Warning: mcrypt_enc_get_iv_size() expects parameter 1 to be resource, boolean given in /Applications/MAMP/htdocs/test/mcrypt.php on line 17
Warning: mcrypt_create_iv(): Cannot create an IV with a size of less than 1 or greater than 2147483647 in /Applications/MAMP/htdocs/test/mcrypt.php on line 17
Warning: mcrypt_enc_get_key_size() expects parameter 1 to be resource, boolean given in /Applications/MAMP/htdocs/test/mcrypt.php on line 18
Warning: mcrypt_generic_init() expects parameter 1 to be resource, boolean given in /Applications/MAMP/htdocs/test/mcrypt.php on line 24
Warning: mcrypt_generic() expects parameter 1 to be resource, boolean given in /Applications/MAMP/htdocs/test/mcrypt.php on line 27
Warning: mcrypt_generic_deinit() expects parameter 1 to be resource, boolean given in /Applications/MAMP/htdocs/test/mcrypt.php on line 30
Warning: mcrypt_generic_init() expects parameter 1 to be resource, boolean given in /Applications/MAMP/htdocs/test/mcrypt.php on line 33
Warning: mdecrypt_generic() expects parameter 1 to be resource, boolean given in /Applications/MAMP/htdocs/test/mcrypt.php on line 36
Warning: mcrypt_generic_deinit() expects parameter 1 to be resource, boolean given in /Applications/MAMP/htdocs/test/mcrypt.php on line 39
Warning: mcrypt_module_close() expects parameter 1 to be resource, boolean given in /Applications/MAMP/htdocs/test/mcrypt.php on line 40

I don't know why this happens and how to fix it. If I'm checking the available modes with:
$modes = mcrypt_list_modes();

foreach ($modes as $mode) {
    echo "$mode
\n";
}

I get the following:
cbc
cfb
ctr
ecb
ncfb
nofb
ofb
stream

By checking the available algorithms:
$algorithms = mcrypt_list_algorithms("/usr/local/lib/libmcrypt");

foreach ($algorithms as $cipher) {
    echo "$cipher
\n";
}

I receive this output:
cast-128
gost
rijndael-128
twofish
arcfour
cast-256
loki97
rijndael-192
saferplus
wake
blowfish-compat
des
rijndael-256
serpent
xtea
blowfish
enigma
rc2
tripledes

I hope someone knows what's the problem and how to fix this. Thanks!


text:
Q: Problem with android ConstraintLayout chained layout I've been staring at and checking this for hours.  Its a constant Layout with 4 headings and a RecyclerView.  The headings are 'Task Name', 'Description', 'Date', and 'Duration'.  It's using a Chain Layout (long story but I need to use Chain Layout rather than weight).  In the Degigner and app I only get the first 3 columns displayed.  The last one 'Duration' is not displayed.

The code for the layout is
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <TextView
        android:id="@+id/td_name_heading"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="4dp"
        android:layout_marginTop="4dp"
        android:background="?attr/colorButtonNormal"
        android:padding="4dp"
        android:text="@string/td_text_name"
        android:textAlignment="viewStart"
        android:textStyle="bold"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintHorizontal_weight="1"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/td_description_heading" />

    <TextView
        android:id="@+id/td_description_heading"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="4dp"
        android:layout_marginEnd="4dp"
        android:background="?attr/colorButtonNormal"
        android:padding="4dp"
        android:text="@string/td_text_description"
        android:textAlignment="viewStart"
        android:textStyle="bold"
        app:layout_constraintBaseline_toBaselineOf="@+id/td_name_heading"
        app:layout_constraintHorizontal_weight="1"
        app:layout_constraintStart_toEndOf="@+id/td_name_heading"
        app:layout_constraintEnd_toStartOf="@+id/td_start_heading" />

    <TextView
        android:id="@+id/td_start_heading"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="4dp"
        android:layout_marginEnd="4dp"
        android:background="?attr/colorButtonNormal"
        android:padding="4dp"
        android:text="@string/td_text_date"
        android:textAlignment="viewStart"
        android:textStyle="bold"
        app:layout_constraintBaseline_toBaselineOf="@+id/td_name_heading"
        app:layout_constraintHorizontal_weight="1"
        app:layout_constraintStart_toEndOf="@+id/td_description_heading"
        app:layout_constraintEnd_toStartOf="@+id/td_duration_heading" />

    <TextView
        android:id="@+id/td_duration_heading"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="4dp"
        android:layout_marginEnd="4dp"
        android:background="?attr/colorButtonNormal"
        android:padding="4dp"
        android:text="@string/td_text_duration"
        android:textAlignment="viewStart"
        android:textStyle="bold"
        app:layout_constraintBaseline_toBaselineOf="@+id/td_name_heading"
        app:layout_constraintHorizontal_weight="1"
        app:layout_constraintEnd_toStartOf="@+id/td_start_heading"
        app:layout_constraintStart_toEndOf="parent"/>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/td_list"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/td_name_heading"
        tools:listitem="@layout/task_duration_items" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: You are setting the start to the end of the parent - essentially saying put the TextView offscreen.
<TextView
    android:id="@+id/td_duration_heading"
    ...
    app:layout_constraintStart_toEndOf="parent"/>


text:
Q: C# making a tab, adding controls to the tab, and then having multiple tabs of that type TabPage newpage = new TabPage();
Tabs.TabPages.Add(newpage);
newpage.Controls.Add(this.tableLayoutPanel41);
newpage.Location = new System.Drawing.Point(4, 26);
newpage.Name = "AddMaintAgreement" + offset;
newpage.Size = new System.Drawing.Size(736, 523);
newpage.TabIndex = 10;
newpage.Text = "Add Maintenance Agreement";
newpage.UseVisualStyleBackColor = true;
offset++;

Basically thats what i have at the moment, I added the offset in there because i thought it might affect my problem.
Basically, this code here works okay for adding one "addmaintagreement" tab. After that only the latest tab has any controls on it!
Basically I'm stumped. Any help would be appreciated. Thanks.

A: I think short example should stay here:
        TextBox tmpLog = new TextBox(); // create new control of textbox type
        tmpLog.Text = "some text here";

        TabPage tb = new TabPage("my brand new tab"); //create tab
        tabControl.TabPages.Add(tb); // add tab to existed TabControl
        tb.Controls.Add(tmpLog); // add textBox to new tab

        tabControl.SelectedTab = tb;     // activate tab

A: Derive from TabPage and add the controls you want in that derived class. Then use your derived class instead of TabPage.

A: Controls can only be parented to one control, but it looks like you are trying to parent your tableLayoutPanel41 in every TabPage instance. You need to create new copies of the controls for each instance of the tab. There are various ways to fix this.

*

*Programmatically create your tab page and its contents multiple times.

*Have the contents of your TabPage implemented as a user control that you dock fill on a tab page. Then recreate one of those for each page duplicate your require.

*Create a class derived from TabPage that implements your tab page and create new instances of that for each use.


text:
Q: Navigation bar. Text inline with and on top a horizontal rule? I have been trying to get a navigation bar with text inline with a horizontal rule & text on top of the horizontal rule.

I'm pretty new to to css and bootstrap and was wondering if it is possible to have it centered and span 8-10 columns
Something kind of like this

TEXT

horizontal rule with text on top

A: You're getting close.
I would use the offset classes instead of empty columns. Other than that you just need to place your navigation in your .col-md-8 DIV.
My example below has some CSS for the navigation so it will display inline. By default
 elements are set to display: block; and will take up the whole width of their parent element. Basically, they'll end up stacking.
The only major thing of note is the text in the first column and attempting to vertically align it with the border/horizontal rule. There's a couple ways to this. In my example I've chosen to double the default line-height that Bootstrap uses.

      TEXT

One

Two

Three

Four

ul, li {
  margin: 0;
  padding: 0;
}
.callout {
  line-height: 2.85714286; /* twice Bootstrap's line-height */
  text-align: center;
}
.primary-nav {
  border-bottom: 1px solid #333;
}
.primary-nav li {
  display: inline-block;
  margin: 0 10px;
}

The JSFiddle.


text:
Q: PHP: Clear form entries upon successful submission I have simple one page contact form with the following logic

*

*If the user hits the send button and an error occurs, show the error and retain form values

*If the user hits the send button and everything is good, show success msg and clear form values

Here's the complete code. I am using $_POST = array(); to try and clear the values, but doesn't seem to be working.
<form id="contact_form" method="POST">
    Name
<input type="text" name="name"  value="<?php echo isset($_POST["name"]) ? $_POST["name"] : ''; ?>" required>

    Email
<input type="text" name="email" value="<?php echo isset($_POST["email"]) ? $_POST["email"] : ''; ?>" required>

    ...
    <input type="submit" value="Send"><input type="reset" value="Clear">
</form>

<?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $name = $_POST['name'];
        $email = $_POST['email'];
        ...

        if (mail($recipient, $subject, $message, $headers) == TRUE) {
            $_POST = array();
            echo "Your msg has been sent.";
        }
        else {
            echo "An error occurred while trying to send your message.";
        }
    }
?>

Any help would be highly appreciated.

A: Actually you are using post data before checking that it is correct or not, so it will display the data every time. You can put your php code before form and set a flag if it is success then don't print anything in input value attribute.
<?php
$success = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    $email = $_POST['email'];
    ...

    if (mail($recipient, $subject, $message, $headers) == TRUE) {
        $success = true;
        echo "Your msg has been sent.";
    }
    else {
        echo "An error occurred while trying to send your message.";
    }
}
?>
<form id="contact_form" method="POST">
    Name
<input type="text" name="name" value="<?php echo (!$success) ? $_POST["name"] : ""; ?>" required>

    Email
<input type="text" name="email" value="<?php echo isset($_POST["email"]) && (!$success) ? $_POST["email"] : ''; ?>" required>

    ...
    <input type="submit" value="Send"><input type="reset" value="Clear">
</form>