text:
Q: MySQL 8.0 "show columns from ..." query returns 0 rows I am running MySQL 8.0.22 on Mac OS 11.7. Before I upgraded MySQL from 5.6, the following query worked fine.
show columns from Viewing where field="type";
But now, after upgrading to MySQL 8.0.22, I get the expected 1 row returned when I'm logged into MySQL as root:
mysql> show columns from Viewing where field="type";
+-------+------------------------------------------------+------+-----+---------+-------+
| Field | Type                                           | Null | Key | Default | Extra |
+-------+------------------------------------------------+------+-----+---------+-------+
| type  | enum('edits','other','page','preview','whole') | YES  |     | NULL    |       |
+-------+------------------------------------------------+------+-----+---------+-------+
1 row in set (0.01 sec)

But when I log in as the user I've created for the webpage that issues this query, 0 rows are returned. This user is view_pjn@localhost, and its grants are:
mysql> show grants for "view_pjn"@"localhost";
+--------------------------------------------------------------------+
| Grants for view_pjn@localhost                                      |
+--------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `view_pjn`@`localhost`                       |
| GRANT SELECT, INSERT ON `blog`.`viewing` TO `view_pjn`@`localhost` |
+--------------------------------------------------------------------+
2 rows in set (0.00 sec)

But when I log into MySQL 8.0.22 as view_pjn, I get the following when I issue this query:
mysql> show columns from Viewing where field="type";
Empty set (0.00 sec)

I have searched MySQL 8.0 Manual and it would seem that as view_pjn@localhost has SELECT, INSERT privileges on blog.viewing, it ought to be able to issue a show columns from Blog.Viewing query.
If anyone can tell me why view_pjn is getting 0 rows returned, I'd really appreciate it.


text:
Q: Label's text not showing 'á' (hungarian) letter I want to display hungarian languge letters in a kivy app, but whenever i use é , á, ö or some other ones it is displayed like this (é -> é)(á -> á) (ö -> ö)
example:
ButtonF:
    id: beallit
    pos_hint: {'x': .375, 'y': .27}
    text: "Beállitások"

now this Button's text is displayed as: Beállitások
I have tried changing the font to a font which supports the hungrian alphabet, even though the font of the text changed the letters still didnt show.
example:
ButtonF:
    id: beallit
    pos_hint: {'x':.375, 'y': .27}
    text: "Beállitások"
    font_name: 'OpenSans'
    on_release: app.root.ids.sm.current  = 'screen5'

Here the Button's text is in OpenSans font but it still doesnt diplay hungarian letters: Beállitások
But when i write the Button's text from the python code not from the kivy rule, the text containing hungarian alphabet is shown correctly.
in py:
beallit_text = StringProperty()
beallit_text = 'Beállitások'

in kv:
ButtonF:
    id: beallit
    pos_hint: {'x':.375, 'y': .27}
    text: root.beallit_text
    font_name: 'OpenSans'
    on_release: app.root.ids.sm.current  = 'screen5'

Now i could just change all the Label's/Button's text from the py code but there are too many of them.
Is there an easier way?

A: Apparently this is a common encoding issue in Kivy where non-UTF-8 encoding (such as chcp 1252) is being used. One way is to just find the encoded version of the text. For example, what you can do instead of this
ButtonF:
    text: 'Título'

is to use the UTF-8 encoded version of it in literal.
ButtonF:
    text: str(b'T\xc3\xadtulo'.decode())

For your case, á -> \xc3\xa1 (in UTF-8 literal). You can check out the whole list here.
Or, you can simply identify the encoding used. Make sure your .kv file is saved in UTF-8
from kivy.lang import Builder
with open('MyApp.renamed.kv', encoding='utf8') as f:
    Builder.load_string(f.read())

this pointed me to the answer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Output category based on multiple inputs I have 8 combinations o triplets, each with a name attached to them. For example:
Category a = 1,2,3
Category b = 3,1,2
etc...
Each value in the triplet is either 1, 2 or 3.
I need to be able to input 3 values (also 1,2 or 3) into 3 cells, and I need the corresponding category to be displayed next to them (based on the 8 hard coded variants).
For example: if I were to enter 3 1 2 into the three cells, "Category b" would show up in the 4th cell.
Here is a screenshot of what I need:

The yellow cells are hard coded.
I have a long list of green cells.
I need to calculate the category in the blue cells based on the green cells.

A: use this in E2:
 =INDEX(G:G,AGGREGATE(15,6,ROW($G$2:$G$9)/(($H$2:$H$9=B2)*($I$2:$I$9=C2)*($J$2:$J$9=D2)),1))

Then copy down


text:
Q: A mean related to a continuous random variable
We are filling some liquid in multiple containers. The volume poured is uniformly distributed between 5.1 and 5.7 deciliters. Every centiliter costs 0.01 dollar.
Knowing that any centiliter added beyond 5.5 deciliters represents an extra cost for the producer, what is the mean of this extra cost?

I am not sure about how to approach this.
Since the volume is uniformly distributed, the mean volume is $(5.7+5.1)/2=5.4$, which is less than $5.5$. From this, I could say that, on average, the producer won't spend any extra dollars.
But then I thought that maybe I should interpret this as the average if we only consider the cases where the volume is more than $5.5$, so that my random variable is now $5.5\leq X\leq 5.7$.
If so, my new mean is $5.6$, which is just one centiliter above the lower-bound volume for there being an extra cost, resulting in a mean of $0.01$$.
Or maybe $\int_{5.5}^{5.7}\left[0.1(x-5.5)\right]f(x)dx$, where $f(x)$ is the pdf?

A: Hint:  Your "new mean" is better described as a conditional mean and can be written $E(X | X > 5.5)$.  To proceed in this way you then need to consider the probability that the condition is satisfied, that is, $P(X > 5.5)$.

A: When a container is filled in such a way that the volume poured does not exceed $5.5$ deciliters, there is no extra cost incurred.  When the volume poured does exceed $5.5$ deciliters, there is an extra cost, which is proportional to the amount of volume above $5.5$.
Your misunderstanding is that somehow, containers whose volume poured is below $5.5$ can compensate for the extra cost incurred from those containers where the volume poured is above $5.5$.  For instance, if only two containers are filled and one is filled to $5.1$ deciliters and the second is filled to $5.7$, the savings of the first container does not cancel out the extra cost of the second, which is still incurred even though the overall cost may still be acceptable.
Another way to think about it is that the producer would have filled the first container to $5.1$ anyway.  The extra cost is conceptualized as answering the question of, "if every container could have been filled so as to guarantee none has more than $5.5$ deciliters, how much money could have been saved?"
With this in mind, we see that the unconditional mean fill volume is not an indicator of the extra cost.  If $X$ is the random fill volume, then we are given $$X \sim \operatorname{Uniform}(5.1, 5.7).$$  The extra cost random variable is $$Y = 0.1 \min(X - 5.5, 0) = \begin{cases} 0, & 5.1 \le X \le 5.5 \\ (0.1)(X - 5.5), & 5.5 < X \le 5.7. \end{cases}$$  You want to compute $$\operatorname{E}[Y \mid X > 5.5] = 0.1 \operatorname{E}[X - 5.5 \mid X > 5.5] = 0.1 ( \operatorname{E}[X \mid X > 5.5] - 5.5 ).$$  Note that the extra cost of $0.01$ dollar per centiliter equals $0.1$ dollar per deciliter, which explains the factor of $0.1$.


text:
Q: JMeter versus The Grinder? I'm looking at stress testing our website and having trouble picking the right tool.
It looks to me like two of the most popular are JMeter and The Grinder.  Can anyone help with reasons in favor of either?
Thanks!

A: As of Jmeter:

*

*It's free.

*it's easy to Start with lot of documentation on its Website and on internet

*it has a proxy feature to easily create test plan from browser navigation

*It is easy to start up processes on other machines. It remote testing, can be done from GUI or console.

*The scripts can be written in beanshell, java, or any jsr223 language ( groovy, Javascript, scala, jexl ...)

*it has a lot of built- in samplers and thanks to its plugin architecture it's very Easy to add new ones or use any scripting engine to do what's missing

*it has great user mailing list

*it has very reactive support

*it's now a top Level Apache project

*...

A: Use gatling.
http://gatling-tool.org/
Its lovely, great DSL, and you can just edit the .scala files and rerun and it will compile for you on demand. Also emits very nice graphs
http://gatling-tool.org/sample/index.html

A: If you're not familiar with Jython (like I wasn't) then there is also a great little tool that comes with Grinder (the TCP Proxy or some such name) that allows you to click around in a webapp and save your actions as a ready-made Jython script for Grinder, which you can then analyse/edit/adopt as necessary.

A: There is an excellent blog post that describes
Load Test Tools:

*

*Grinder 3.11

*Gatling 2.0.0.M3a

*Tsung 1.51

*JMeter 2.11

*

*The Grinder
The Grinder consists of two main parts:

*

*The Grinder Console - This is GUI application which controls various Grinder agents and monitors results in real time. The console can be used as a basic IDE for editing or developing test suites.

*Grinder Agents - These are headless load generators; each can have a number of workers to create the load

Key Features of the Grinder:

*

*TCP proxy - records network activity into the Grinder test script

*Distributed testing - can scale with the increasing number of agent instances

*Power of Python or Closure combined with any Java API for test script creation or modification

*Flexible parameterization which includes creating test data on-the-fly and the capability to use external data sources like files, databases, etc.

*Post processing and assertion - full access to test results for correlation and content verification

*Support of multiple protocols

*Apache JMeter
Key Features of the JMeter:

*

*Cross-platform. JMeter can be run on any operating system with Java

*Scalable. When you need to create a higher load than a single machine can create, JMeter can be executed in a distributed mode - meaning one master JMeter machine will control a number of remote hosts.

*Multi-protocol support. The following protocols are all supported 'out-of-the-box': HTTP, SMTP, POP3, LDAP, JDBC, FTP, JMS, SOAP, TCP

*Multiple implementations of pre and post processors around sampler. This provides advanced setup, teardown parametrization and correlation capabilities

*Various assertions to define criteria

*Multiple built-in and external listeners to visualize and analyze performance test results

*Integration with major build and continuous integration systems - making JMeter performance tests part of the full software development life cycle

A: I just went through the process of trying at both and I would totally agree with Rob here. Grinder also seemed faster, and I really like how simple and lightweight it is compared to Jmeter. The grinder.properties file is totally easy to use, especially if you're more of a console guys then a UI guy.

A: I have worked a bunch with The Grinder and there are three main reasons I like it.

*

*It's free.  I assume from your question, you are only looking at free solutions.  There are some excellent commercial products as well, but most of the time, I cannot justify the cost

*It is easy to start up processes on other machines.  When really trying to crank up load on a cluster, I need to easily distribute the load out to remote machines.  Grinder is great for that.

*The scripts are all Jython.  That allows me to easily customize my scripts to programatically tweak my scripts (e.g. randomize certain paths).

I haven't used JMeter in a long time, so I cannot say authoritatively how it compares on points 2 & 3.


text:
Q: Django Vuejs -- Using Axios - Issue in redering Data I am trying to use VueJs inside my Django Framework ( Django as Backend) and Vuejs as Front-End. However, I am very new with axios, which I found more easier to use with VueJS Front-End. On integrating all togetherr, I didn't see anything coming up but I can see that my code is loop through the data using vueJS Developer Tools.
index.html
{% load static %}

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>The greatest news app ever</title>

        <template v-for="post in posts">

 Hello - {{ post.title }}

        </template>

app.js
new Vue({
  el: '#app',
  data: {

    posts: []
  },

  methods:{
    getPost: function(){
      var self = this;
      let url = "http://127.0.0.1:8000/api/allpost/";
      axios.get(url).then((response) => {
        this.posts = response.data
      }, (error) => {
          console.log(error);
      });
    }
  },
  mounted: function() {
    this.getPost();
  }

});

The Output of the code

A: {{ post.title }} has been the problem rendering the Data into Django Page, because Django also make use of this {{ }}. However, in a situation where someone is rendering the page with VueJS Server is doesn't apply. then, remember to add this:
delimiters: ['[[', ']]'],

      [[ post.title ]]

      [[ post.body ]]

new Vue({
  delimiters: ['[[', ']]'],

  el: '#app',
  data: {

    posts: []
  },

  methods:{
    getPost: function(){
      var self = this;
      let url = "http://127.0.0.1:8000/api/allpost/";
      axios.get(url).then((response) => {
        this.posts = response.data
      }, (error) => {
          console.log(error);
      });
    }
  },
  mounted: function() {
    this.getPost();
  }

});


text:
Q: Probability calculation when rolling a 6 sided dice this is a newbie question but I can't seem to get to the answer right.
The scenario is the following - it's said (in this book I'm reading) that the probability to roll a 6-sided dice 30 times and have the number 6 as an outcome 21 of those 30 times is 0.000297.
How do they calculate this result? My calculation is obviously off, since I thought the probability must be $\frac{1}{6}^{21} * \frac{5}{6}^9$ but it obviously isn't because I'm not getting the correct number.
Thanks in advance!

A: Your working assume that the first $21$ outcome is $6$ and the rest are not.
You need to multiply it by $\binom{30}{21}$.
$$\binom{30}{21}\left( \frac16\right)^{21} \left( \frac56\right)^9$$
Check out binomial distribution.


text:
Q: How do I connect my information to my toast message package edu.apsu.assignment4;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.widget.RadioGroup;
import android.widget.CheckBox;
import android.widget.TextView;

public class MainActivity extends Activity implements
android.view.View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    Button sendButton,aboutButton;
    EditText DrinkNum;
    Double subtotal;
    TextView order,aboutApp,Sroom,drinkType,Croom,go,flavor;

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

        RadioGroup drink = (RadioGroup) findViewById(R.id.drinks);
        drink.setOnClickListener(this);

        CheckBox Croom = (CheckBox) findViewById(R.id.cream);
        Croom.setOnCheckedChangeListener(this);

        DrinkNum=(EditText) findViewById(R.id.editText1);

        sendButton=(Button) findViewById(R.id.send);
        sendButton.setOnClickListener(this);

        aboutButton=(Button) findViewById(R.id.about);
        aboutButton.setOnClickListener(this);
    }

        @Override
        public void onClick(android.view.View v) {

            RadioGroup drinkGroup = (RadioGroup) findViewById(R.id.drinks);

            switch (drinkGroup.getCheckedRadioButtonId()) {
            case R.id.coffee:
                drinkType.setText("coffee");
                subtotal=2.50;
                break;
            case R.id.cappuccino:
                drinkType.setText("cappuccinno");
                subtotal=4.50;
                break;
            case R.id.espresso:
                drinkType.setText("espresso");
                subtotal=4.50;
            case R.id.latte:
                drinkType.setText("latte");
                subtotal=4.50;
                break;
            case R.id.iced_latte:
                drinkType.setText("iced_latte");
                subtotal=5.00;
                break;
            }

            order.setText("Subtotal: "+subtotal+ "Tax: "+subtotal*.09+"Total: "+subtotal+subtotal*.09);

        }

    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        Croom= (TextView) findViewById(R.id.cream);
        Sroom= (TextView) findViewById(R.id.sugar);
        go= (TextView) findViewById(R.id.go);
        flavor= (TextView) findViewById(R.id.flavoring);
        if (buttonView.getId() == R.id.cream) {
            if (isChecked) {
                Croom.setText("Room for cream");
            } else {
                Croom.setText("No room for cream");
            }
        }
            else if (buttonView.getId() == R.id.sugar) {
            if (isChecked) {
                Sroom.setText("Room for sugar");
            } else {
                Sroom.setText("No room for sugar");
            }

        }
            else if (buttonView.getId() == R.id.go) {
                if (isChecked) {
                    go.setText("To go");
                } else {
                    go.setText("Stay");
                }

            }
            else if (buttonView.getId() == R.id.chocolate) {
                if (isChecked) {
                    flavor.setText("Chocolate flavoring");
                }

            }

            else if (buttonView.getId() == R.id.cherry) {
                if (isChecked) {
                    flavor.setText("Cherry flavoring");
                }

            }

            else if (buttonView.getId() == R.id.vanilla) {
                if (isChecked) {
                    flavor.setText("Vanilla flavoring");
                }
            }

    aboutButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg7) {
        // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "*In boxer announcer voice*: "+"\n"+"Credit is given to me.", Toast.LENGTH_LONG).show();
        }

    });

    sendButton.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg8) {
            String message;
            message = "Number of cups: "+DrinkNum+"\n"+go+"\n"
            +Croom+"\n"+Sroom+"\n"+"Drink type: "+drinkType+"\n"+"Flavoring: "+flavor
            +"\n"+"Price details: "+order+"\n"+"Thanks for ordering";

            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
            }
        });
    }

}

My second toast message is not connecting my information from the earlier code. Also, I can not select just one radio button, if I click any other buttons they are also selected. How can I fix these two problems?

A: For your first question, you are trying to concatenate DrinkNum, which is of type EditText (or View), to a String. This is not possible and I would be surprised if it compiles.
To address your second question, you've attached an onClickListener to the entire RadioGroup. This means that if any of the RadioButton's inside the group are clicked, the onClickListener's onClick() method will execute.


text:
Q: Android: layout_wilih attribute error I'm on the Android tutorial and I keep getting this error message even though the  layout_width attribute is already supplied:
 "Binary XML file line #2: You must supply a layout_width attribute"

Please help! Thanks

A: You're supposed to declare android:layout_width, not layout_wilih


text:
Q: Won't delete or replace £ (pound) sign I'm trying to delete all the £ symbols in a text file (.csv) using sed, however it doesn't work and I've no clue as to why. Any suggestions?  Basically using:
sed -i 's/£//g' file.csv

Output of locale:
LANG=en_GB.UTF-8
LANGUAGE=
LC_CTYPE="en_GB.UTF-8"
LC_NUMERIC="en_GB.UTF-8"
LC_TIME="en_GB.UTF-8"
LC_COLLATE="en_GB.UTF-8"
LC_MONETARY="en_GB.UTF-8"
LC_MESSAGES="en_GB.UTF-8"
LC_PAPER="en_GB.UTF-8"
LC_NAME="en_GB.UTF-8"
LC_ADDRESS="en_GB.UTF-8"
LC_TELEPHONE="en_GB.UTF-8"
LC_MEASUREMENT="en_GB.UTF-8"
LC_IDENTIFICATION="en_GB.UTF-8"
LC_ALL=

Update:
So, I don't know why sed wasn't working, but
    tr -d '\243' < inputfile
Does work! Thanks to @devnull for that!

A: This might work for you (GNU sed):
sed 's/o\302\o243//g' file

N.B. if you are in doubt how sed sees a particular character use the l command and sed will display the character as it sees it (in this case in octal). e.g.
echo '£' | sed 'l'
\302\243$

The dollar following the octal codes represents the end of string.
For long strings use l0 this will prevent wrapping.

A: Use the hex code for the pound sign.
Seems like different versions in different platforms, sed act very differently. I just got the GNU version and works fine.
Before using sed, one should read the section "When should I NOT use sed"

A: Did you try:
sed "s/\xA3//" inputfile

Alternatively, you can use tr:
tr -d '\243' < inputfile


text:
Q: Pandas: Edit index values and re-groupby, according to new values I have my index set to 'ShiftId' which looks like this: 201912240 (the date followed by a 0 or 1 that indicates day or night shift). I have my df grouped by index values that return, as expected, something like this:
           col1 col2
201912240  NaN  23
201912241  44   75
201912250  12   NaN
201912251  46   91

I want to regroup this dataframe to take the mean of each day (ignoring NaN values), then it will look like this
           col1 col2
20191224   44   49
20191225   29   91

But I can't get the current index values to be grouped. I have tried
    days_frame.index = days_frame.index.map(lambda x: str(x)[:-1])
    days_frame.groupby(days_frame.index).mean()

But this doesn't even change anything in the df?
Please help

A: Your solution for me working, maybe you forget assign output to variable like df here:
days_frame.index = days_frame.index.map(lambda x: str(x)[:-1])
df = days_frame.groupby(days_frame.index).mean()
print (df)
          col1  col2
20191224  44.0  49.0
20191225  29.0  91.0

Another solution rename index first and then use mean per index values:
df = days_frame.rename(lambda x: str(x)[:-1]).mean(level=0)
print (df)
          col1  col2
20191224  44.0  49.0
20191225  29.0  91.0

Or convert index to strings, remove last value and pass to groupby with aggregate mean:
df = days_frame.groupby(days_frame.index.astype(str).str[:-1]).mean()
print (df)
          col1  col2
20191224  44.0  49.0
20191225  29.0  91.0

EDIT:
If want avoid truncating all columns without A column use this solution before write to file:
df = pd.DataFrame({'A':[.41,1.5,.2,2,.3],
                   'B':['a'] * 5,
                   'C':[3,4,5,4,5],
                   'D':[1.0,3,4,5,6]})

cols = df.columns.difference(['A'])

df[cols] = df[cols].applymap(lambda x: '%.0f' % x if isinstance(x, (float, int)) else x)
print (df)

      A  B  C  D
0  0.41  a  3  1
1  1.50  a  4  3
2  0.20  a  5  4
3  2.00  a  4  5
4  0.30  a  5  6


text:
Q: OpAmp: Better to actively attenuate, or drive full range into a divider? I want to get a +-15V differential signal (60Vp-p) into an ADC that has a single 3.3V supply.  When I asked a friend to proofread it, he was concerned about the noise performance of R5-R6 vs. using R1-R4 to make U2A output the desired level to start with:

simulate this circuit – Schematic created using CircuitLab
(input protection not shown for clarity)
My understanding is that an opamp's noise level does not depend on signal level, therefore a hotter signal is better.  So I only attenuated U2A enough to match the full input range and left the rest to R5-R6.
(Another benefit is that if something goes wrong and U2A becomes a comparator, then the ADC input is still within the limits.  Probably not likely, but possible.)
My friend thinks I would actually have less noise by putting all the attenuation in R1-R4, deleting R5-R6, and driving C1 directly.  Is this true?

A: Why in the world are you worried about Johnson noise?
Consider that the LM833 has a power bandwidth less than 1 MHz. Assuming your ADC has a 3 V input and 16 bit resolution, 1 lsb is ~46 µV. A 1 kΩ resistor with a 1 MHz bandwidth has a Johnson noise voltage of ~4 µV, and noise scales as the square root of the resistance. It would take a 529 kΩ resistor to give you 1 lsb of noise.
You don't say what your desired input impedance is. Let's say that it's 1 MΩ. You could use a 475kΩ/50kΩ/475kΩ divider network to get your input down to 3 Vp-p, followed by a simple unity-gain differential receiver, and still have ⅓ lsb of noise. And, of course, any lower value of input resistance will directly cause a lowering of resistor noise.
I really don't see the problem.

A: I assume that 6K is intended to represent the input impedance of the ADC, so it doesn't contribute noise.
The R5/R6 combination contributes 2.0nV/sqrt(Hz) at the ADC input. The output of the op-amp has noise of about 18nV/sqrt(Hz) (mostly due to Johnson noise in the resistors), so about 1.9nV/sqrt(Hz) at the divider output, or a total of 2.8nV/sqrt(Hz) at the ADC input. In other words the two contributions are similar (divider and amplifier).
I encourage you to do a full noise analysis and look at the various contributions individually. Since they add in quadrature, the magnitudes of the squared values are important. This Analog Devices paper gives you the information you need.

I may have made an error, but when I do the analysis with an attenuator made with 10K/546.5 ohm resistors rather than 10K/5K and no divider (gain is 0.0546 in both cases), I get a noise for your circuit of 51nV/sqrt(Hz) referred to the input of the diffamp vs. 119nV/sqrt(Hz) for the no-divider circuit, corresponding to 2.8nV/sqrt(Hz) vs. 6.49nV/sqrt(Hz) at the ADC input.
All this stuff refers to the region above the voltage and current noise corners, of course, which should be valid for most of the audio spectrum (but it never seems to be for the stuff I do).


text:
Q: Javascript keycodes for Alt, Ctrl, and Shift $("#text").bind('keypress', function(e) {
    var code = (e.KeyCode ? e.keyCode : e.which);
    alert(code);
}

It works fine for everything except Alt, Ctrl, or Shift.
But in all tutorials that i found it should echos 17, 18, 19
Why?

A: use .keydown() or .keyup()
see it in action

jQuery(function($){
  var output = $('.output');
  $("#text1").bind('keypress', function(e) {
    var code = (e.KeyCode ? e.keyCode : e.which);
    output.text(code);
  });
  $("#text2").bind('keydown', function(e) {
    var code = (e.KeyCode ? e.keyCode : e.which);
    output.text(code);
  });
  $("#text3").bind('keyup', function(e) {
    var code = (e.KeyCode ? e.keyCode : e.which);
    output.text(code);
  });

})

keypress <input type="text" id="text1">

keydown <input type="text" id="text2">

keyup <input type="text" id="text3">

Output:

A: Have you considered using the jquery.hotkeys extension that allows you to bind by specifying a string?
"C-A-q" would bind you to:

Control + Alt + q.

A: It would probably be better to use console.log to find them. You can also use just one textbox easily for this.
$("#textbox").keydown(function(e) {
    console.log("keydown: "+e.keyCode);
});

And do the same for keyup and keypress to see better how it all works.
Side note: JavaScript sure is hard to write on a phone ;)


text:
Q: What is the meaning of this sentence? "The right side of $a\equiv b \pmod c$ is less than or equal to the left side." Let us consider a congruence of the form
$$a\equiv b \pmod c$$
What is the meaning of the following sentence?
$$\text{The right side of the congruence is less than or equal to the left side.}$$

For context, the Jones, et.al, American Mathematical Monthly article "Diophantine Representation of the Set of Prime Numbers" (PDF link via umd.edu) has the following (Lemma 2.4, pg 452; emphasis added):

For any numbers $p$, $n$ and $a\geq 1$ we have the congruence
$$\chi_a(n) \equiv p^n+\psi_a(n)(a-p) \pmod{2ap-p^2-1}$$
Furthermore, when $0< p^n<a$, the right side of the congruence is less than or equal to the left side.

A: I am not an expert on the topic, but I think you can use the definition of congruence modulo which is that $\displaystyle a\equiv b\ (\bmod c) \ \Leftrightarrow a-b=ck$, so I would think you can replace the equality sign with a greater than or equal to. It would then be $\displaystyle a-b\geqslant ck$. I am not sure, however.


text:
Q: do I use Krb5LoginModule or LdapLoginModule Sorry if this is a silly question.
Do I use LdapLoginModule when I want to check if user exist or authorized?
Do I use Krb5LoginMoudle when I want to check if user has a ticket to do work?
Regards,
JemRug

A: I'm guessing they are both forms of logging in , but the underline protocols they are manipulating  is the key. One is talking Kerberos, the other LDAP.


text:
Q: set gridview scrolling disable android I have a Gridview of values in listview.
every  listview position contain a textview and gridview.
and every gridview contain a set of items.
But,to view all items i have to go through scroll.
I want to show the full list of items ,without scrolling.
<GridView
                android:id="@+id/grid_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:columnWidth="70dp"
                android:gravity="center"

                android:horizontalSpacing="10dp"
                android:numColumns="auto_fit"
                android:stretchMode="columnWidth"
                android:verticalSpacing="10dp"

                >
            </GridView>

A: You can't have two scrollable view as same derivatives.
Android doesn't recommend having a child scrollable view when you already have a scrollable view as parent .
Although, if you want to achieve this there are many other ways, I will suggest you better have a linear layout and inflate it dynamically whenever your listView items gets in.

A: You can switch off clicks on GridView by setting "clickable" attribute to false
That will toggle scrolling off too.


text:
Q: Maven cannot use scope compile I have a problem with my maven project. When I build my Jar, the dependency "BukkitLib" with <scope>compile</scope> will not be compiled in the Jar. In another project, this way (same structure of the pom.xml) works fine.
Here is the pom.xml from my project
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>de.flammenfuchs</groupId>
    <artifactId>Farming</artifactId>
    <version>1.0</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <!--Spigot API-->
        <dependency>
            <groupId>de.flammenfuchs</groupId>
            <artifactId>BukkitLib</artifactId>
            <version>1.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.spigotmc</groupId>
            <artifactId>spigot-api</artifactId>
            <version>1.16.5-R0.1-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>de.varox</groupId>
            <artifactId>VaroxMatrix</artifactId>
            <version>1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>

Some other information:
Intellij Version: 2021.1.1 (Ultimate-Edition)
OS: elementaryOS 5.1 (Hera) (based on Ubuntu)
Java-Version: 11
My English is very basic, please give me easy or translatable (e. g. deepl) instructions.


text:
Q: Azure ItemPaged iterator doesn't raise StopIteration I'm trying to list all the Linked Services in my ADF account using Azure ADF SDK. The below code prints the results for the first 50 items and then appears to get "stuck" until it is cancelled manually. How do I iterate over the ItemPaged iterator to print the complete result set?
from azure.identity import ClientSecretCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.datafactory import DataFactoryManagementClient
from azure.mgmt.datafactory.models import *
import time

subscription_id = ""
tenant_id       = ""
client_secret = ""
client_id = ""

credentials = ClientSecretCredential(client_id=client_id, client_secret=client_secret, tenant_id=tenant_id)
adf_client = DataFactoryManagementClient(credentials, subscription_id)

for _, row in enumerate(adf_client.linked_services.list_by_factory('my-resource-group', 'my-data-factory')):
  print(_, row.name)

Edit: I get an HttpResponseError: (InternalError) Internal error has occurred. error message if I wait long enough. This issue was reported on the azure-sdk-for-python repo on github.


text:
Q: Forward HTTP traffic to a server behind gateway I have a server behind gateway, which means it's only pingable internally. Now I want to forward traffic from a outside server to this internal server. I want to use socat like:
socat TCP4-LISTEN:8080, TCP:[internal server]:8080 # on external server

Which clearly won't work because the IP address of that server is not available.
So how can I achieve this? I am open to any solutions.


text:
Q: How do I Download efficiently with rsync? A couple of questions related to one theme: downloading efficiently with Rsync.
Currently, I move files from an 'upload' folder onto a local server using rsync. Files to be moved are often dumped there, and I regularly run rsync so the files don't build up. I use '--remove-source-files' to remove files that have been transferred.
1) the '--delete' options that remove destination files have various options that allow you to choose when to remove the files. This would be handly for '--remove-source-files' since is seems that, by default, rsync only removes the files after all files have been transferred, rather than after each file; Othere than writing a script to make rsync transfer files one-by-one, is there a better way to do this?
2) on the same problem, if a large (single) file is transferred, it can only be deleted after the whole thing has been sucessfully moved. It strikes me that I might be able to use 'split' to split the file up into smaller chunks, to allow each to be deleted as the file downloads; is there a better way to do this?
Thanks.


text:
Q: Searching for a pattern in dictionary keys I want to search python dictionary keys with some given pattern. This is more like a substring search, but with the char level. Below code is working fine, but I need some tuning, as it will have performace issues when we have thousands of keys. Hash Keys have sorted alphabets. By alphabetical sorting of keys, I mean every key (word) of the dictionary is sorted in itself, NOT the whole dictionary sorted on basis of keys. i.e. key can be aaklm, not the kamal.
Also, Is there any external library/API for this searching portion?
import re

def getKey(str, list):
    expr = re.compile(str)
    return [elem for elem in list if expr.match(elem)]

wordDict = {'AADFLORW':['value1'], 'AAAGRU': ['VAL1', 'SOME DIFFERENT VALUE']}
m = re.compile(u'[a-zA-Z]').findall('ADOLF')    # I'm searching ADOLF in the keys
pat = '.*' + '(.*)'.join(sorted(m)) + '.*'

for key in getKey(pat, wordDict.keys()):
    print(key)

A: As it is now, the main portion of the search will be in checking every key in wordDict against the pattern. One optimization I can think of is to reduce this search.
First I build "meta" dictionary, where keys are frozenset of characters of wordDict's keys and values are lists of wordDict keys.
In getKey(), with this meta dictionary I check only keys where there's possibility of match (so not all of keys).
import re
from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

def getKey(string, pat, meta):
    k = ''.join(sorted(set(string)))
    expr = re.compile(pat)
    return [elem for elem in meta[frozenset(k)] if expr.match(elem)] # <--- here I search only valid keys (keys where there's possibility of match)

wordDict = {'AADFLORW':['value1'], 'AAAGRU': ['VAL1', 'SOME DIFFERENT VALUE']}

# build meta information about wordDict.keys()
# This could take a while!!!
meta = {}
for k in wordDict.keys():
    for p in powerset(set(k)):
        if p:
            meta.setdefault(frozenset(p), []).append(k)

# from pprint import pprint
# pprint(meta)

m = re.compile(r'[a-zA-Z]').findall('ADOLF')    # I'm searching ADOLF in the keys
pat = '.*' + '(.*)'.join(sorted(m)) + '.*'

for key in getKey('ADOLF', pat, meta):
    print(key)

Prints:
ADFLORW

For illustration, the "meta" dictionary now looks like this:
{frozenset({'A'}): ['AADFLORW', 'AAAGRU'],
 frozenset({'D'}): ['AADFLORW'],
 frozenset({'L'}): ['AADFLORW'],
 frozenset({'R'}): ['AADFLORW', 'AAAGRU'],
 frozenset({'W'}): ['AADFLORW'],
 frozenset({'O'}): ['AADFLORW'],
 frozenset({'F'}): ['AADFLORW'],
 frozenset({'A', 'D'}): ['AADFLORW'],
 frozenset({'A', 'L'}): ['AADFLORW'],
 frozenset({'A', 'R'}): ['AADFLORW', 'AAAGRU'],
 frozenset({'W', 'A'}): ['AADFLORW'],

...

It could be quite big, so now you are trading "space" for "speed".


text:
Q: ProxyPass(Apache2) with a DynDNS fails after getting a new IP-Address I'm getting a big headache with this issue and can't find a solution. I have the following setting.
An IP Camera connected to a Fritz.Box which is accessible via a dynamic DNS from selfhost.eu. And I have a Webserver with Apache2 with a ProxyPass to this xxx.selfhost.eu-URL. When someone access my webserver he will get a live update of the webcam because the ProxyPass works fine until the Fritz.Box gets a new IP-Address. Only when I restart the Apache2-Server it will work again, so my idea is that maybe Apache just caches the IP-Address and I've to stop that but I'm not sure.
Maybe someone has an idea. Thank you!
Here my ProxyPass-Setting
ProxyPass "/tmpfs" "http://xxx.selfhost.eu:59677/tmpfs"
And here some related Log-Error from apache
2017-05-07 16:04:43    Error (110)Connection timed out: AH00957: HTTP: attempt to connect to 79.210.185.5:59677 (xxx.selfhost.eu) failed Apache-Fehler
2017-05-07 16:04:43 Error AH00959: ap_proxy_connect_backend disabling worker for (xxx.selfhost.eu) for 0s Apache-Fehler
2017-05-07 16:04:43 Error 79.204.237.78 AH01114: HTTP: failed to make connection to backend: xxx.selfhost.eu, referer: https://xxx.yyy.de/ Apache-Fehler
2017-05-07 16:04:43 Error (110)Connection timed out: AH00957: HTTP: attempt to connect to 79.210.185.5:59677 (xxx.selfhost.eu) failed Apache-Fehler
2017-05-07 16:04:43 Error 80.143.179.219 AH01114: HTTP: failed to make connection to backend: xxx.selfhost.eu, referer: https://xxx.yyy.de/ Apache-Fehler

A: Does disablereuse=On help?
ProxyPass "/tmpfs" "http://xxx.selfhost.eu:59677/tmpfs" disablereuse=On


text:
Q: Zoom to Box examples on https://bl.ocks.org do not work properly with Internet Explorer Description of Bug: Instead of zooming to fit the constraints of the bounding box, it's zooming to the size of the entire browser.
Browser Not Working On: Internet Explorer
Versions of Browser Tested On: 11
Examples Not Working
Zoom to Bounding Box
https://bl.ocks.org/mbostock/4699541
The code on this link only works because the raw code is displayed in an Iframe, click "open" from the page to display without an IFrame or click the link below:
https://bl.ocks.org/mbostock/raw/4699541/
Zoom to Bounding Box II
https://bl.ocks.org/mbostock/9656675
The code on this link only works because the raw code is displayed in an Iframe, click "open" from the page to display without an IFrame or click the link below:
https://bl.ocks.org/mbostock/raw/9656675/
Click-to-Zoom via Transform
https://bl.ocks.org/mbostock/2206590
The code on this link only works because the raw code is displayed in an Iframe, click "open" from the page to display without an IFrame or click the link below:
https://bl.ocks.org/mbostock/raw/2206590/

A: Fixed it with the following line:

.attr("overflow", "hidden");

Below is where it needs to be placed:
var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .attr("overflow", "hidden");


text:
Q: Finding values starting with a specific piece of string I have a *.txt file and I keep some codes of some files in it. Format is the following:
code1, a/b/c/1.jpg
code2, a/b/c/2.jpg
code1, a/b/c/3.jpg
code2, a/b/d/4.jpg
code3, a/b/d/5.jpg

My purpose is finding the files in the same folder with the same codes (duplicates). All the file names are different. If the same code occurs in different folder like code2, a/b/c/ and code2, a/b/d/ I want to skip it. Right now I have the following code which searches a specific code in the whole *.txt document:
reader = csv.reader(csvfile)
dataDict = dict()
for row in reader:
    if any (row):
        if row[0] in dataDict.keys():
            dataDict[row[0]].append(row[1])
        else:
            dataDict[row[0]] = [row[1]]

But this gives me the duplicates in different folders. However, I want to find the duplicate files exactly in the same folder.
Edit:The title is not clear. I did not know how to describe this in the title.

A: reader = csv.reader(csvfile)
dataDict = dict()
for row in reader:
    if any (row):
        code, filename = row
        _, dir_path = filename.rsplit('/', 1)
        if dir_path not in dataDict.keys():
            dataDict[dir_path] = {}
        if code not in dataDict[dir_path]:
            dataDict[dir_path][code] = []
        dataDict[dir_path][code].append(filename)
duplicates = []
for k_dir, v in dataDict.items():
    for _, paths in dataDict[k_dir].items():
        if len(paths) > 1:
            duplicates.append(paths)
return duplicates

First part is sorting codes and files together
The second part is detecting duplicates and returning them


text:
Q: Namespace tags are not supported. ReactJSX is not XML I am getting the below react exception in the browser console, It seems that jsp tags are not supported in React, Could someone confirm ? In case they are supported, What would be the solution ?
Code :

render: function() {

  var defaultComp=this.state.defaultComp;
  var defaultUI=[];
  for(var compIndex=0;compIndex<defaultComp.length;compIndex++){
   //Push label first
   defaultUI.push(
    <form:label path={defaultComp[compIndex]['path']}>
     {defaultComp[compIndex]['label']}
    </form:label>
    );

   if(defaultComp[compIndex]['type']==='input'){
    defaultUI.push(
     <form:input path={defaultComp[compIndex]['path']} />
    );
   }else{

   }

   defaultUI.push(
);
  }
   return (

      <form:form action="display-makes.html"
       method="post" commandName="configuration">
       {defaultUI}
      </form:form>

    );
  }

browser.min.js:7 Uncaught SyntaxError: http://localhost:8080/Neo/resources/js/script.jsx: Line 48: Namespace tags are not supported. ReactJSX is not XML.
      46 |          //Push label first
      47 |          defaultUI.push(
    > 48 |              <form:label path={defaultComp[compIndex]['path']}>
         |      ^
      49 |                  {defaultComp[compIndex]['label']}
      50 |              </form:label>
      51 |              );


text:
Q: Problems with Angular deploy-url switch I want to deploy my spring-boot webapp with angular-frontend to a tomact-server. I build the angular app with angular-cli and the following commando
ng build --deploy-url /mywebapp/

The app works but following problems still exist:

*

*Each time I have to change manually the base href tag to <base href="/mywebapp/">. Why is this not done automatically in the build process?

*All paths to static ressources of the 'assets' directory must also changed manually to '/mywebapp/assets' (i.e. <img src="/mywebapp/assets/logo.png">)

*Browser refresh of router links URLs (subpaths) does not work anymore. (i.e. angular navigation to http://localhost:8080/mywebapp/feature1 works but if I want to refresh the same URL in the browser it does not work. I can only refresh the root URL http://localhost:8080/mywebapp/)

A: Whenever u build
build it with
ng build --base-href .

This will solve ur Problems #1 & #2
For Problem 3
This SO Post will work
angular html5mode in tomcat apache 8.5.4 gives 404 on page refresh

*

*add in /opt/tomcat/conf/context.xml

<!-- REWRITE VALVE -->
 <Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
 <!-- // -->

*add rewite.config file in specific project WEB-INF folder with below content
for eg. on /opt/tomcat/webapps/projectName/WEB-INF/rewrite.config

RewriteCond %{REQUEST_URI} !^.*\.(bmp|css|gif|htc|html?|ico|jpe?g|js|pdf|png|swf|txt|xml|svg|eot|woff|woff2|ttf|map)$
RewriteRule ^(.*)$ /index.html [L]

What this does is
for each of this route requests it redirects to index.html


text:
Q: ajax request not working? I am sending ajax request to a php page on a button click. Here is my request being sent
$("#enteruser").on('click',function(){
console.log("entered here");
var name=$("#ename").val();
var email=$("#eemail").val();
var role=$("#erole").val();

var data={name: name, email:email, role:role};
var url='addemployee.php';

 $.ajax({
     url : url,
     data: data,
     type: 'POST',
     success: function(response)
     {
         if(response=="success")
             {
             $("#rmsg").text("Hello World");
             }
         else
             {

             }

     }
 });

});

My this line is not working and URL after returning back contains the values I sent. So If I resend request the request is not sent again due to url. If I put the following line
window.location="anotherpage.html"; in the success block the page is redirected to the that page. Then why the rmsg paragraph is not being written?

I am adding the form dynamically using the following code
$("#create").on('click',function(){
var htmc='
\n\

Create Employee
\n\
      <form>\n\

\n\
      \n\
      <input type="text" name="eemail" id="eemail" placeholder="Email" required/>\n\
      \n\
      <input type="text" name="ename" id="ename" placeholder="Name" required/>\n\
      \n\
      <input type="text" name="erole" id="erole" placeholder="Role" required/>\n\
       <button id="enteruser" class="button">Enter</button>\n\
      </form>\n\

';
$("#view").html(htmc);
});

$(document).on("#enteruser",'click',function(e){
    e.preventDefault();
    console.log("entered here");
var name=$("#ename").val();
var email=$("#eemail").val();
var role=$("#erole").val();

var data={name: name, email:email, role:role};
var url='addemployee.php';

 $.ajax({
     url : url,
     data: data,
     type: 'POST',
     success: function(response)
     {
         if(response=="success")
             {

             alert(response);
             $("#rmsg").text("Hello World");
             }
         else
             {

             }

     }
 });

});

A: One thing i like to do when troubleshooting HTTP calls is to view the actual network event in a debugging tool.
In Google Chrome, use CTRL + SHIFT + I to open up the debugging tools. Then click on the Network tab. In here, you may view the POST and Response and verify that your response is correct.
In MS IE, you can hit F12 to view the developer tools there

A: You are not preventing default behaviour for a form. YOu should say to your app: "do nothing with the form and make it handled by js".
Also you are using a delegated function in the wrong way.
To do so change this:
$("#enteruser").on('click',function(){
console.log("entered here");

to this:
$("#enteruser").click(function(e){
e.preventDefault();
console.log("entered here");

all the other part of your code can remain as now if the form is in the dom from the beginning.
$(document).on('click',"#enteruser",function(e){
e.preventDefault();
console.log("entered here");

if the form is added to the page after it is loaded. YOu can also replace document with any element already in the page that is before the form in the dom structure

A: Try this

    <input type="text" id="ename" />
    <input type="text" id="eemail" />
    <input type="text" id="erole" />

    <button id="enteruser">Button</button>

PHP:
<?php session_start(); echo 'success'; ?>


text:
Q: Cant Sort ObservableCollection List by any Item [duplicate]
solution on here

i want sort my ObservableCollection list but i cant find how.
I saw this but idk how can use
I want sort;
ObservableCollection < CariHesaplarPickerItems > _pickerlistItemsSource = new ObservableCollection < CariHesaplarPickerItems > ();

by ID.
My main code:
public List < string > pickerListItems = new List < string > {...};

ObservableCollection < CariHesaplarPickerItems > _pickerlistItemsSource = new ObservableCollection < CariHesaplarPickerItems > ();

private async Task GetAllData()
{
  ...

  var resCariGrup = await client.ExecuteAsync(request, Method.Post);
  var dataCariGrup = JsonConvert.DeserializeObject < RootCariGrup > (resCariGrup.Content);

  _pickerlistItemsSource.Clear();
  pickerListItems.Clear();
  pickerListItems.Add("Hepsi");

  for (int i = 0; i < dataCariGrup.data.Count(); i++)
  {
    ...
  }
  pickerCariListe.ItemsSource = pickerListItems;

  ...
}

List items:
public class CariHesaplarPickerItems
{
    public int ID { get; set; }
    public string grupAd { get; set; }
    public string kullaniciAd { get; set; }
    public string subeAd { get; set; }
}

I want sort this items
{
  "data": [
    {
      "id": 10,
      "grup": "kasa alaçak",
      "kullaniciAdi": "demo",
      "subeAdi": "Merkez"
    },
    {
      "id": 4,
      "grup": "MÜŞTERİ",
      "kullaniciAdi": "demo",
      "subeAdi": "Merkez"
    },
    {
      "id": 5,
      "grup": "TOPTANCI",
      "kullaniciAdi": "mehmet@bilsoft.com",
      "subeAdi": "Merkez"
    },
    {
      "id": 7,
      "grup": "ALICI",
      "kullaniciAdi": "mehmet@bilsoft.com",
      "subeAdi": "Merkez"
    },
    {
      "id": 8,
      "grup": "SATICI",
      "kullaniciAdi": "mehmet@bilsoft.com",
      "subeAdi": "Merkez"
    },
    {
      "id": 9,
      "grup": "SATIŞ",
      "kullaniciAdi": "mehmet@bilsoft.com",
      "subeAdi": "Merkez"
    },
    {
      "id": 11,
      "grup": "asansör bakımları",
      "kullaniciAdi": "demo",
      "subeAdi": "Merkez"
    },
    {
      "id": 12,
      "grup": "genel giderler",
      "kullaniciAdi": "demo",
      "subeAdi": "Merkez"
    },
    {
      "id": 13,
      "grup": "TAŞERON",
      "kullaniciAdi": "demo",
      "subeAdi": "Merkez"
    }
  ],
  "totalCount": 9,
  "success": true,
  "message": null,
  "code": null
}

A: You can do something like below to order your collection based on ID
_pickerlistItemsSource.OrderBy(var=> var.ID)

This will return an ordered list of objects


text:
Q: Create and publish a static web project in Eclipse when I tried to create and publish a static web project in eclipse I got: "Error copying file index.html: No such file or directory"
My environment: SuSE 12.2, Eclipse Indigo Release 2, Apache2 2.2.22,
This is what I did to create the project:
1) Create new Server

*

*Basic, HTTP Server

*Publishing Directory: /srv/www/htdocs

*Enable publishing to this server: true

2) Create Project

*

*New -> Static Web Project

*Project Name: Simplepage

*Target Runtime: HTTP Server (from 1)

*Default Configuration

*Content root: Simplepage

*Web content folder name: WebContent

3) Create very simple page

*

*Create new HTML file

*Parent folder: Simplepage/WebContent

*Name: index.html

*Content:<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=${encoding}">
<title>Insert title here</title>
</head>
<body>
Test
</body>
</html>
4) Start Project

*

*Right Click on Project Name -> Run as -> Run on Server

Here I got the error message mentioned above.
At this point there is a new folder /srv/www/htdocs/Simplepage created but has no content.
Later I made a test with the following configuration:

*

*Change publishing directory to: "/srv/www/htdocs/XY"

Start Project gives error: "Access forbidden! You don't have permission to access the requested directory..."
At this time there is a new directory created: /srv/www/htdocs/XY/Simplepage containing the file index.html.
The window in eclipse is showing the path http://localhost/Simplepage/. When I change this manually to http://localhost/XY/Simplepage/ the newly created page is shown.
I don't understand this behaviour. Can someone explain this?

A: You have installed Apache2 server on your home computer, with the publishing directory /srv/www
Note that Apache2 runs on its own user (on my Ubuntu it is www-data). Apache's publishing directory /srv/www is normally owned by Apache's user.
You have also directed HTTP Server of Eclipse to the same directory.  Note that this server is different from Apache; it is run by Eclipse inside its belly, and usually on different ports from Apache, to avoid port conflict.  I think this server is run on the same user Eclipse runs, i.e., your regular user on your home comp.
I think that the error messages you get, are permission mismatch: Eclipse cannot publish in directories owned by Apache's user.
The solution is not to try to use Apache's directories but rather the default directories of Eclipse.
I have explained this in more detail here: Eclipse Web (http) servers: Debugging and publishing http files in Eclipse.
I do use both Eclipse' HTTP Preview server and Apache2:

*

*Eclipse' HTTP Preview server for files I work on in Eclipse, and

*Apache2 to run a localhost copy of my Wordpress site.

When files I work on in Eclipse, are mature, I transfer them manually to Wordpress as posts or pages.


text:
Q: Codeigniter, when I try to update, the single quote displays as ' I like set_value. Every time, when I try to update the post, the single quote displays as &#039 ;. Not only single quote, some characters display too. Please, help me
Im using Codeigniter 3, Php 7
View
$description = array(
        'name' => 'description',
        'type' => 'text',
        'placeholder' => 'description',
        'class' => 'form-control',
        'rows' => '3',
        'value' => set_value('description', $post->INTRO_DESCRIPTION),
    );

  Details

<?php echo form_textarea($description); ?>

<?php echo form_error('description', '
', '
'); ?>

A: Well I found the solution. And it's very simple. Just adding "false" at end of the set_value.
set_value('description', $post->INTRO_DESCRIPTION, FALSE)


text:
Q: Display canonical rewritten URLs and hide dynamic ones I have tried countless stuff but I can't find a way to display, in the browser URL bar, the rewritten URL instead of the one with the 3 get parameters.
My "ugly" URL :
http://example.com/archive.php?id=tt2131523&date=20131004&title=graceland
The "pretty" URL I need to display :
http://example.com/tt2131523-20131004-graceland.html
Here is my .htaccess file :
RewriteEngine on

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule .* http://%1%{REQUEST_URI} [R=301]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule .* https://%1%{REQUEST_URI} [R=301]

RewriteRule ^([^-]*)-([^-]*)-([^-]*)\.html$ /archive.php?id=$1&date=$2&title=$3 [NC,L]

My other PHP files serve the "ugly" links, the links work but the URLs remain "ugly". The "prettyfied" version is not displayed.
If I type the "pretty" URL in the browser, the rewriting works and I access the page.
I would like that, even if a user types the "ugly" version, he will be redirected to the "pretty" one.
Do I need to change my links structure (in other php files) and make them directly point to the rewritten version of the URLs or is there a way in .htaccess to display the rewritten version ?
And by the way, are the flags ok ?
Thanks.

A: You can use this :
RewriteEngine On
RewriteCond %{THE_REQUEST} /archive\.php\?id=([^&]+)&date=([^&]+)&title=([^\s]+) [NC]
RewriteRule ^ /%1-%2-%3.html? [NC,R,L]
RewriteRule ^([^-]+)-([^-]+)-([^.]+)\.html$ /archive.php?id=$1&date=$2&title=$3 [QSA,L,NC]


text:
Q: It is necessary to limit the ability to resend codes via SMS I need to check if the user re-requests sending SMS more than once every 30 seconds, I need to return an error that the action is performed too often and the remaining time until the next send.
The controller itself
@PostMapping("/resend/sms")
@PreAuthorize("hasAuthority('ROLE_ADMIN') or hasAuthority('SCOPE_trusted')")
public Mono<UserDTO> trustedResendRegistrationSms(
        @Validated @RequestBody RegistrationDTO registrationDTO,) {
    return accountService.resendRegistrationSms(registrationDTO.getLogin());
}

A: You could register user requests by some user fingerprint inside your controller bean, and break the request whenever it comes within 30 seconds or in some extra cases.
Here is my example,
package com.example.app.rest;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/request-limited/")
public class RequestLimitedController {

    // Store user request in set inside the bean
    private Set<UserRequest> requests = new HashSet<>();
    private static class UserRequest {
        public String userFingerprint; // we will use user ip as a fingerprint
        public LocalDateTime lastRequestTime = LocalDateTime.now();
        public Long count = 0L; // not used in this example, but you can limit the max number of request from the same ip

        public UserRequest(String userFingerprint) {
            this.userFingerprint = userFingerprint;
        }
    }

    @GetMapping("frequency-sensitive-request")
    public ResponseEntity<Object> processFrequencySensitiveRequest(HttpServletRequest httpRequest) {

        // First, remove expired requests from set
        requests = requests.stream()
                .filter( entry -> entry.lastRequestTime.isAfter(LocalDateTime.now().minusHours(1)) )
                .collect(Collectors.toSet());

        String userFingerprint = httpRequest.getRemoteAddr();

        // Find the last request for this user
        UserRequest userRequest = requests.stream().filter( r -> r.userFingerprint.equals(userFingerprint)).findFirst().orElse(null);
        if (userRequest!=null && userRequest.lastRequestTime.isAfter(LocalDateTime.now().minusSeconds(30))) {
            // if it was within 30 seconds, then throw 403
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        if (userRequest == null) {
            // If it doesn't exist then create and register it
            userRequest = new UserRequest(userFingerprint);
            requests.add(userRequest);
        }
        // Update count and time
        userRequest.count++;
        userRequest.lastRequestTime = LocalDateTime.now();

        // Process the request here

        return ResponseEntity.ok().build();
    }

}


text:
Q: Citation of the British National Corpus (BNC) I am new here but I have been reading along for couple of months now. My biggest problem at the moment is to cite internet sources especially internet webpages.
In my current paper I would like to quote the "British National Corpus". But because of my settings I always get "Corpus, B. N. (2001)" in my bibliography. Is there a way to change that only for that particular case? I would like to get "British National Corpus (2001): Url: . Accessed: 05.04.2015". Unfortunately, "lastchecked" does not appear in my bibliography.
Here my bib-file:
    @article{BNC,
    Author = {British National Corpus},
    Date-Added = {2015-05-04 14:58:49 +0000},
    Date-Modified = {2015-05-04 15:10:16 +0000},
    Lastchecked = {04.05.2015},
    Url = {http://www.natcorp.ox.ac.uk},
    Year = {2001},
    Bdsk-Url-1 = {http://www.natcorp.ox.ac.uk}}

Here my settings:
\usepackage[style=apa,
       apabackref=true,
       backend=biber,
       hyperref=true,
       maxnames=1,
       maxcitenames=6,
       maxbibnames=99,
       sorting=debug,
       natbib=true,
       language=ngerman,
       doi=true,
       url=true
       ]{biblatex}

\DeclareLanguageMapping{ngerman}{ngerman-apa}
\DefineBibliographyStrings{ngerman}{andothers={et\ al\adddot}}
\addbibresource{lit1.bib}

\NewBibliographyString{retrieved}
\DefineBibliographyStrings{ngerman}{retrieved={Letzter Zugriff am}}

\usepackage{url}
\setcounter{biburlnumpenalty}{100}
\setcounter{biburlucpenalty}{100}
\setcounter{biburllcpenalty}{100}

I have changed my bib-file and added the {{-brackets to the author.
article{BNC, Author = {{{British National Corpus}}},
Date-Added = {2015-05-04 14:58:49 +0000},
Date-Modified = {2015-05-04 16:37:05 +0000},
Url = {natcorp.ox.ac.uk},
Urldate = {2015-05-04},
Year = {2001},
Bdsk-Url-1 = {natcorp.ox.ac.uk}} –

Unfortunately, I got this:
Entity: line 1944: parser error : Extra content at the end of the document <bcf:field>title<

And then I cannot compile the file.
I have just seen that there were three {{{ before that is because my BibDesk add one { to each entry automatically. I have fixed that so I only got two {{ now. But I still got the same error.
When I compile the file it says:
bbl:95: Paragraph ended before \name was complete. <to be read again> \par l.95?

However, line 95 is empty in my file.


text:
Q: Passing optional arguments to a listing environment based on conditionals I am trying to make a presentation which can optionally compiled for handouts. This presentation also contains highlighted code snippets. For highlighting I use the code from this question. (Which works fine in my real presentation, however produces highlights too far to the right in the minimal examples.)
When I compile for handout mode, the last of the highlighted lines is still present in the listing. Therefore I am looking for some way to conditionally disable the highlighting.
What I have so far:
The conditional:
\newif\ifhandout
\handouttrue
\ifhandout
   \documentclass[handout]{beamer}
\else
  \documentclass{beamer}
\fi

The highlighting:
\begin{frame}[fragile]{ListingTest}
  \begin{lstlisting}[linebackgroundcolor={
    \btLstHL<1>{1-3}
    \btLstHL<2>{6,9}
    }]
    ... some code thats at least 9 lines long
  \end{lstlisting}
\end{frame}

The problem now is, that I don't know how I achieve optional compilation of the optional linebackground argument. An additional problem is that I have to escape commands inside the listing environmt. I have tried placing ifs at various locations like:
\ifhandout
\begin{lstlisting}
(*@\else
\begin{lstlisting}[linebackgroundcolor={
  \btLstHL<1>{1-3}
  \btLstHL<2>{6,9}
  }](*@\fi@*)
    ... code
\end{lstlisting}

But nothing worked as expected. (I even managed to place them in a way that collapsed all code in the listing in a single line.)
Does someone know, how I can exclude the argument in [] from compilation when handout ist true?
Here is the complete "minimal" example for testing. Thank you very much in advance.
\newif\ifhandout

\handouttrue

\ifhandout
    \documentclass[handout]{beamer}
\else
    \documentclass{beamer}
\fi

\usepackage{lmodern}
\usepackage{pgf, pgffor}
\usepackage{listings}
\usepackage{lstlinebgrd}

\lstset
{
    inputencoding=utf8,
    language=c++,
    basicstyle=\tiny\ttfamily,
    numberstyle=\tiny,
    numbers=left,
    stepnumber=1,
    numbersep=5pt,
    escapeinside={(*@}{@*)},
    showstringspaces=false,
    backgroundcolor=\color{white},
    frame=single,
    tabsize=4,
    morekeywords={decltype},
    literate={ö}{{\"o}}1
           {ä}{{\"a}}1
           {ü}{{\"u}}1
           {Ä}{{\"A}}1
           {Ö}{{\"O}}1
           {Ü}{{\"U}}1
           {ß}{{\ss}}1
           {~}{{\textasciitilde}}1
}

\lstloadlanguages{C++}

% Some Code copied from stackoverflow for highlighting

\makeatletter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% \btIfInRange{number}{range list}{TRUE}{FALSE}
%
% Test in int number <number> is element of a (comma separated) list of ranges
% (such as: {1,3-5,7,10-12,14}) and processes <TRUE> or <FALSE> respectively

\newcount\bt@rangea
\newcount\bt@rangeb

\newcommand\btIfInRange[2]{%
    \global\let\bt@inrange\@secondoftwo%
    \edef\bt@rangelist{#2}%
    \foreach \range in \bt@rangelist {%
        \afterassignment\bt@getrangeb%
        \bt@rangea=0\range\relax%
        \pgfmathtruncatemacro\result{ ( #1 >= \bt@rangea) && (#1 <= \bt@rangeb) }%
        \ifnum\result=1\relax%
            \breakforeach%
            \global\let\bt@inrange\@firstoftwo%
        \fi%
    }%
    \bt@inrange%
}
\newcommand\bt@getrangeb{%
    \@ifnextchar\relax%
        {\bt@rangeb=\bt@rangea}%
        {\@getrangeb}%
}
\def\@getrangeb-#1\relax{%
    \ifx\relax#1\relax%
        \bt@rangeb=100000%   \maxdimen is too large for pgfmath
    \else%
        \bt@rangeb=#1\relax%
    \fi%
}

\newcommand<>{\btLstHL}[1]{%
  \only#2{\btIfInRange{\value{lstnumber}}{#1}{\color{blue!30}\def\lst@linebgrdcmd{\color@block}}{\def\lst@linebgrdcmd####1####2####3{}}}%
}%
\makeatother

\begin{document}

\begin{frame}[fragile]{ListingTest}
  \begin{lstlisting}[linebackgroundcolor={
      \btLstHL<1>{1-3}
      \btLstHL<2>{6,9}
      \btLstHL<3>{7}
      \btLstHL<4>{8}
    }]
        /**
         * Prints Hello World.
         **/
        #include <stdio.h>

        int main(void) {
           printf("Hello World!");
           return 0;
        }
  \end{lstlisting}
\end{frame}
\end{document}


text:
Q: What is Difference Between Console.WriteLine($"welcome{name}") and Console.WriteLine("welcome {0}",name) I have taken
String name="Max";
when I going to print a name like this, what operation was done under this.
Console.WriteLine($"welcome{name}")

and
 Console.WriteLine("welcome {0}",name).

A: Both are same. This is called String Interpolation. For more information read this article
Before C# version 6 (Console.WriteLine works as String.Format)
Console.WriteLine("welcome " + name) //with + operator

string newstring = string.Format("welcome {0}", name) //with string.format

Console.WriteLine("welcome {0}", name) //same as string.format

$ is introduced with C# version 6 to simplify String Interpolation
Console.WriteLine($"welcome {name}")

A: Though both doing the same things but has few differences.
 Console.WriteLine("welcome {0}",name)

As first one you are passing your value as parameter which belongs to
  {0} place holder.

On  the other hand,
Console.WriteLine($"welcome{name}")`

Secondly, $ is introduced with C# version 6 where value directly passed
  on the container. $ String interpolation  working here as place
  holder

Hope this would help.


text:
Q: How do I create a pie chart in Matplotlib using a dataframe, and use the categorical variables in a column as labels? As the question stated, I want to create a pie chart of the variable total_product_line and use the categorical variables in df['product_line'] as labels. I know I could create a list of the labels, but wouldn't it be a lot more efficient to do it something like this?
total_product_line = df.groupby('product_line')[['total']].sum()
plt.pie(total_product_line, labels=df['product_line'])
plt.show()


text:
Q: How can I make Bash automatically pipe the output of every command to something like tee? I use some magic in $PROMPT_COMMAND to automatically save every command I run to a database:
PROMPT_COMMAND='save_command "$(history 1)"'

where save_command is a more complicated function.  It would be nice to save also the head/tail of the output of each command, but I can't think of a reasonable way to do this, other than manually prepending some sort of shell function to everything I type (and this becomes even more painful with complicated pipelines or boolean expressions).  Basically, I just want the first and last 10 lines of whatever went to /dev/tty to get saved to a variable (or even a file) - is there any way to do this?

A: script(1) will probably get you started. It won't let you just record the first and last 10 lines, but you can do some post-processing on its output.

A: bash | tee /dev/tty ./bashout

This saves all stdout gets saved to bashout.
bash | tee /dev/tty | tail > ./bashout

The tail of stdout of every command gets written to bashout.
bash | tee /dev/tty | sed -e :a -e '10p;$q;N;11,$D;ba' > ./bashout

The first and last 10 lines of stdout of every command gets written to bashout.
These don't save the command, but if you modify your save_command to print the command to stdout, it will get in there.


text:
Q: Salesforce REST API: Session expired or invalid: INVALID_SESSION_ID Background
I am trying to access the Salesforce Reporting REST API.
public with sharing class SalesforceReportApi {

    private final static String REPORTS_RESOURCE = '/services/data/v44.0/analytics/reports/';

    private static HttpResponse execute(String method, String restResource) {

        HttpRequest request = new HttpRequest();

        request.setMethod(method);
        request.setEndpoint(endpoint + restResource);
        request.setTimeout(120000); // 2 Minutes

        request.setHeader('Accept', 'application/json');
        request.setHeader('Content-Type',  'application/json');
        request.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionID());
        request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
        request.setCompressed(false);

        HttpResponse httpResponse = new Http().send(request);

        return httpResponse;
    }

    private static String endpoint {
        get {
            return URL.getOrgDomainUrl().toExternalForm();
        }
    }

    public static MatrixReport getMatrixReport(Id reportId) {

        HttpResponse response = execute(HttpMethod.GET, REPORTS_RESOURCE + reportId);

        return (MatrixReport) JSON.deserialize(response.getBody(), MatrixReport.class);
    }
}

The request produced is:

Method: GET
  URL: https://x--x.cs83.my.salesforce.com/services/data/v44.0/analytics/reports/XXXX

But I am getting this error:

{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}

I thought that since the recent release using URL.getOrgDomainUrl() meant to access the REST API meant I didn't need to authenticate.
Sandbox org is on Spring '19 Patch 19.4
Questions

*

*What am I doing wrong?

*How can I fix it?

NOTE: I fixed this using Named Credentials you can read more here

A: Based on the comments, it seems you are using a Guest User here to be able to get a Session Id and utilize that in your code using request.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionID());
The error INVALID_SESSION_ID you are receiving is expected in that case. Refer to Guest user session ID returned NULL in UserInfo.getSessionId() knowledge article. It discusses exactly this scenario which you are facing now.
You will need to adjust the approach here as there's no workaround to get past this.


text:
Q: How to make a relationship between tables in MySQL I want to have some relation between my tables in MySQL. I use GORM ORM and go. I have 3 table with this name: singertbl, covertbl, singerscovertbl.
my tables have id with autoincrement value.
in singertbl and covertbl, I have this fields: ID and {some another field}.
and in singerscovertbl I have this fields: ID, singer_id, cover_id.
there is a relation between {ID.singertbl -> singer_id.singerscovertbl} and
{ID.covertbl -> cover_id.singerscovertbl} when I want to apply this relation as a foreign key in MySQL workbench with this SQL query:
    ALTER TABLE `mskm`.`albumscovers`
ADD INDEX `ID_idx` (`album_id` ASC) VISIBLE,
ADD INDEX `ID_idx1` (`cover_id` ASC) VISIBLE;
;
ALTER TABLE `mskm`.`albumscovers`
ADD CONSTRAINT `ID`
  FOREIGN KEY (`album_id`)
  REFERENCES `mskm`.`albumstbls` (`ID`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;

I get this error:
 Operation failed: There was an error while applying the SQL script to the database.
Executing:
ALTER TABLE `mskm`.`albumscovers`
ADD INDEX `ID_idx` (`album_id` ASC) VISIBLE,
ADD INDEX `ID_idx1` (`cover_id` ASC) VISIBLE;
;
ALTER TABLE `mskm`.`albumscovers`
ADD CONSTRAINT `ID`
  FOREIGN KEY (`album_id`)
  REFERENCES `mskm`.`albumstbls` (`ID`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;

ERROR 1064: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '
ADD INDEX `ID_idx1` (`cover_id` ASC) VISIBLE' at line 2
SQL Statement:
ALTER TABLE `mskm`.`albumscovers`
ADD INDEX `ID_idx` (`album_id` ASC) VISIBLE,
ADD INDEX `ID_idx1` (`cover_id` ASC) VISIBLE

how I can make this relationship between this tables?!


text:
Q: Initialised property in class instance is "undefined" if set to zero or an empty string I have an instance of a class, in which several number and string properties are initialized to 0 or "" respectively. When accessing these properties they are "undefined". Initializing these properties to anything else, ie 0.1 or " " and it is considered defined.
Why? Are 0 and "" equivalent to undefined?
export class Car {
     id = 0
     name = ""
}

If I have an instance of Car and try to access a property it will be "undefined",
let myCar = new Car
if (myCar.id) {
    console.log('yay')
} else {
    console.log('boo')
}

It will show 'boo'.

A: In javascript, the value 0 is evaluated as a falsy statement. Same for an empty string "". If you want to test if the property is undefined you need to do so explicitely
let myCar = new Car
if (myCar.id !== undefined) {
    console.log('yay')
} else {
    console.log('boo')
}


text:
Q: Datameer partition filter expression to specify 2 Months I need dynamic data partition for my datameer workbook. I need two months of data from today. So if i go to Advance partition filtering and specify something like $partition > TODAY()-60d && $partition <= TODAY() , it isn't getting me full 60 days of data. Couldn't see any examples on how to use MONTH in datameer documentation. Any help is appreciated.
I use datameer version 4

A: "For this particular use case, I'd recommend the following Advanced Partition Filter:
$partition >= STARTOFMONTH(ADDTODATE(TODAY();"-2M"))
To break this down, the formula's core starts with the same TODAY() calculation and then uses the ADDTODATE function to go to the date 2 months ago ("-2M"). After this, the STARTOFMONTH function is used to ensure that the first of the month is referenced to align with the partition definition. "


text:
Q: Aspose.Pdf can't find its license file I have this code in a PDF generation method:
Dim license As license = New license
License.SetLicense(Path.Combine(Request.PhysicalApplicationPath, "bin", "Aspose.Pdf.lic"))

I also tried simply:
Dim license As license = New license
License.SetLicense("Aspose.Pdf.lic")

I verified that the license file exists at the above path, but I still get this error:

Cannot find license 'C:\Users\MyUsername\source\repos\MyApp\Src\MyProject\bin\Aspose.Pdf.lic'.

If the license file is there (and it does appear to be a legitimate XML file, not just a placeholder), why is it not being found?

A: I needed to give the IIS_IUSRS user group on my PC "full control" permission to the license file. I'm not sure why Aspose.Pdf needs to be able to write the license file, not just read it, but that seems to have worked.


text:
Q: Get html tags from string in PHP How gets html tags from string?
For example, I have string: $text="Text1ABCD Some Text3";
How can I get tags to array $arr :  , ,  , , ,

A: Try this:
preg_match_all('$</?\\w+((\\s+\\w+(\\s*=\\s*(?:".*?"|\\'.*?\\'|[^'">\\s]+))?)+\\s*|\\s*)/?>$', $text, $arr, PREG_PATTERN_ORDER);

The resulst is here $arr

A: Use those expressions:
<[^\/][^>]*> for opening (and self closing like
) tags: https://regex101.com/r/558dsy/2
<\/[^>]+> for closing tags: https://regex101.com/r/VBzbwh/3


text:
Q: bokehjs on click callback I have a bokeh chart that is displaying several glyphs with the hover tool working properly on them, giving very useful information on hover.
What I need is a way of making that information persistent, i.e. not to disappear on mouse out.
A click-to-pin would work for me, but so would do a linked table with the latest clicked glyph info.
In general, it would be great I could register a click javascript callback to be called with the DataSource info of the element that has been clicked.
Is there any way to do it?

A: If something like this is what you are after I did this with the bokeh data table, just making sure I used the same source.
To see what I mean make sure you click on the data points. Shift click is also possible.

A: I tried based on this example. It seems to work fine with Bokeh 0.11.
from bokeh.plotting import figure, output_notebook, show
from bokeh.io import output_file, show, vform
from bokeh.models import ColumnDataSource, HoverTool, CustomJS
from bokeh.models.widgets import DataTable, TableColumn
output_file("test.html")

# define some points and a little graph between them
x = [2, 3, 5, 6, 8, 7]
y = [6, 4, 3, 8, 7, 5]

p = figure(width=400, height=400, title='Hover over points')

cr = p.circle(x, y, color='olive', size=30, alpha=0.4, hover_color='olive', hover_alpha=1.0)

# Add a hover tool, that sets the link data for a hovered circle
code = """
var data = {'x0': [], 'y0': []};
var cdata = circle.get('data');
var indices = cb_data.index['1d'].indices;

for (i=0; i < indices.length; i++) {
    // pay attention to where x and y are defined, if you define them outside for loop,
    // it will be updated at the same time you mouse hover off the target.
    // If you want to keep the last hover on result, put x and y inside for loop.
    x = []
    y = []
    idx = indices[i]
    x.push(cdata.x[idx]);
    y.push(cdata.y[idx]);
}
data_table.set('data', {
    'x' : x,
    'y' : y
});
"""

source = ColumnDataSource({})

columns = [
        TableColumn(field="x", title="x"),
        TableColumn(field="y", title="y"),
    ]

data_table = DataTable(source=source, columns=columns, width=400, height=280)
callback = CustomJS(args={'circle': cr.data_source, 'data_table':data_table.source}, code=code)
p.add_tools(HoverTool(tooltips=None, callback=callback, renderers=[cr]))
layout = vform(p,data_table)
show(layout)


text:
Q: How to break date values in Jquery UI date picker? I have some things to do, but is bit complicated for me.I need some help from you guys.
 Here is the thing, I set Jquery UI date picker on first input field with id of day, but date values I get--> 03/02/2011 should be parsed on three  input fields in particular format? see code below:
<label>Enter Day of Arrival (in the format DD)
<input type="text" name="$DAY$" id="day" size="6" maxlength="6" />

<label>Enter Month of Arrival (in the format MM)
<input type="text" name="$MONTH$" id="month" size="6" maxlength="6" />

<label>Enter Year of Arrival (in the format YYYY)
<input type="text" name="$YEAR$" id="year" size="6" maxlength="6" />>

A: I've coded an example on fiddle. Code below
<input type='text' id='full' name='fulldate'>
<!-- Your other HTML fields listed above -->

$('#full').datepicker({
    onSelect: function(dateText, inst) {
        var pieces = dateText.split('/');
        $('#day').val(pieces[0]);
        $('#month').val(pieces[1]);
        $('#year').val(pieces[2]);
    }
})

Example : http://jsfiddle.net/jomanlk/7NgpQ/


text:
Q: How could I make react-native-onesignal work on all devices? I've been facing this scenario for months on my OneSignal and I still haven't figured out how to solve it:

My question is: How could I make it work on all devices? I imagine that I am getting lost in the settings of the dependencies in the gradle files.
android/build.gradle
buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 29
        googlePlayServicesAuthVersion = "16.0.1"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath('com.android.tools.build:gradle:4.0.1')
        classpath 'com.google.gms:google-services:4.1.0'
    }
}

allprojects {
    repositories {
        mavenLocal()
        maven {
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        jcenter()
        maven { url 'https://www.jitpack.io' }
    }
}

android/app/build.gradle
apply plugin: "com.android.application"

import com.android.build.OutputFile

project.ext.react = [
    enableHermes: false,
]

apply from: "../../node_modules/react-native/react.gradle"

def enableSeparateBuildPerCPUArchitecture = false

def enableProguardInReleaseBuilds = false

def jscFlavor = 'org.webkit:android-jsc:+'

def enableHermes = project.ext.react.get("enableHermes", false);

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.smartial"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 33
        versionName "3.6.1"
        multiDexEnabled true
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
        release {
            storeFile file('smartial-app.jks')
            storePassword KEYSTORE_PASSWORD
            keyAlias KEY_ALIAS
            keyPassword KEY_PASSWORD
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            signingConfig signingConfigs.release
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    packagingOptions {
        pickFirst "lib/armeabi-v7a/libc++_shared.so"
        pickFirst "lib/arm64-v8a/libc++_shared.so"
        pickFirst "lib/x86/libc++_shared.so"
        pickFirst "lib/x86_64/libc++_shared.so"
    }

    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }

        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'com.google.android.gms:play-services-auth:18.0.0'
    implementation "com.google.android.gms:play-services-base:16.0.1"
    implementation "com.google.firebase:firebase-core:16.0.6"
    implementation "com.google.firebase:firebase-messaging:17.3.4"
    implementation "com.facebook.react:react-native:+"

    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
    compile 'com.android.support:multidex:1.0.1'

    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
      exclude group:'com.facebook.fbjni'
    }

    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }

    implementation project(':react-native-config')

}

task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply plugin: 'com.google.gms.google-services'
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
apply plugin: 'com.google.gms.google-services'

Ps: I'm also using react-native-google-signin in this project.
Update
I opened an issue on react-native-onesignal

A: It looks like you are using an outdated version of the Android SDK Build Tools. Make sure you are downloading them at the correct place as well as updating them often from here: https://developer.android.com/studio/releases/build-tools
If this does not fix your OneSignal notifications issues, it might be a messed up setting under your OneSignal.com dashboard. Make sure that the server urls that is connecting to are correct.
Could you also explain which devices the notifications aren't currently working on?


text:
Q: How to format USB stick to exfat in Ubuntu 18.04 (now with kernel 5.3.0-42)? This is a dual boot laptop HP 8570p with Ubuntu 18.04 and Win 10. I've installed exfat-fuse and exfat-utils (both are of version 1.2.8-1 and they are now located in directory: /dev/sda5/usr/share/doc in form of changelog.Debian.gz), Ubuntu is in this /dev/sda5 device.
I tried to mount exfat using terminal two commands:
1.) at first 'mount exfat usr/share/doc', but the reply was: 'mount: only root can do that';
2.) and secondly 'sudo mount -t exfat /dev/sda5/usr/share/doc  /media/exfat, but the reply was:
'FUSE exfat 1.2.8
ERROR: failed to open '/dev/sda5/usr/share/doc': Not a directory.'
How can I proceed with mounting correctly ?
After this I tried to format USB stick to exFat with GParted, but my GParted (vers 0.30.3) does not support exFat. Can I do something to make my GParted to support also exFat ?

A: I use something like this when manullay mounting USB Devices.
Code:
sudo mount -t vfat /dev/{usbdevicename} /media/external -o uid=1000,gid=1000,utf8,dmask=027,fmask=137

The options following the "-o" give you ownership of the drive, and the masks allow for extra security for file system permissions. If you don't use those extra options you may not be able to read and write the drive with your regular username. Use the correct location/path instead of {usbdevicename}
If you need the correct path you can use:
sudo fdisk -l

It will be something like sdb1, sdc1. The 3rd letter depends on the amount of storage devices in the system.


text:
Q: Concurrent Programming, Stacks and Heaps in C/C++ Well, I am sorry if this feels like a repetition of old questions, I have gone through several questions on Stack Overflow, the Modern Operating Systems Book by tanenbaum, and have still to clear my doubts regarding this.
First off, I would appreciate any book/resource that I should go through in more detail to better understand this structure. I fail to understand if these are concepts generally explained in OS books, or Programming Languages or Architecture books.
Before I ask my questions, I will list out my findings based on readings about stacks/heaps
Heap

*

*Contains all Instance Variables, Dynamically Allocated (new/malloc), and Global Variables only

*Does not use the data structure heap anymore, uses more complex structures

*Access through memory locations, individual process responsible for memory allocated on it

*Defragmentation, and allocation of memory is done by the OS (If yes or no, please answer my question on who manages the heap, os or runtime environ)

*Shared among all threads within the process which have access to its reference

Stack

*

*Contains all local variables only. (Pushed on at function call)

*Uses an actual Stack Data Structure for operation

*Faster to access due to contiguous nature

Now, For a few of my questions regarding the same.

*

*Global Variables, where do they get allocated? (My belief is that they get allocated on the heap, If so, When do they get allocated, at runtime or compile time, and one further question, can this memory be cleared (as in using delete)? )

*What is the structure of the heap? How is the heap organized (is it managed by the os or the run time environment (as set up by the C/C++ compiler) ).

*Does the stack hold ONLY method, and their local variables?

*Each application (Process) is given a separate heap, but if you exceed heap allocations, then does it mean that the os was not able to allocate more memory? (I am assuming lack of memory causes the OS to reallocate to avoid fragmentation)

*The Heap is accessible from all threads within the process (I believe this to be true). If yes all threads can access Instance Variables, Dynamically allocated variables, global variables (If they have a reference to it)

*Different processes, cannot access each others heap (even if they are passed the address)

*A Stack overflow crashes

*

*only the current thread

*current process

*all processes

*In C/C++, does memory get allocated during run time on the stack for block variables within a function (For example, if a sub-block (eg. For loop) of code creates a new variable is that allocated during run-time on the stack (or the heap) or is it preallocated?) when are they removed (Block level scope, how is that maintained). My belief on this is, all additions to stack are made at runtime before the start of a block, whenever the end of that block is reached, all elements added till that point are pushed.

*The CPU's support for the stack register is limited to a stack pointer that can be incremented (pop) and decremented (push) via normal access to memory. (Is this true?)

*Last, are both stack, and heap structures generated by the OS/Runtime environment that exist on Main Memory (As an abstraction?)

I know this is a lot, and I appear to be very confused throughout, I would appreciate it if you could point me in the right direction to get these things cleared up!

A: *

*Global variables are allocated in a static section of memory that's laid out at compile time. The values are initialized during startup before main is entered. The initialization may, of course, allocate on the heap (i.e. a statically allocated std::string will have the structure itself sit in the statically laid out memory, but the string data it contains is allocated on the heap during startup). These things are deleted during normal program shutdown. You can't free them before then, if you wish to, you may want to wrap the value in a pointer, and initialize the pointer on program startup.

*The heap is managed by an allocator library. There's one that comes with the C runtime, but also custom ones like tcmalloc or jemalloc that you can use in place of the standard allocator. These allocator get large pages of memory from the OS using system calls, and then give you portions of these pages when you call malloc. The organization of the heap is somewhat complex and varies between allocators, you can look up how they work on their websites.

*Yes-ish. Though you can use library functions like alloca to make a chunk of space on the stack, and use that for whatever you want.

*Each process has a separate memory space, that is, it thinks it is all alone and no other process exists. Generally the OS will give you more memory if you ask for it, but it can also enforce limits (like ulimit on linux), at which time it can refuse to give you more memory. Fragmentation isn't an issue for the OS because it gives memory in pages. However fragmentation in your process may cause your allocator to ask for more pages, even if there's empty space.

*Yes.

*Yes, however there's generally OS specific ways to create shared-memory regions that multiple processes can access.

*stack overflows doesn't crash anything itself, it causes memory values to be written in places that may hold other values, thus corrupting it. Acting on corrupted memory causes crashes. When your process accesses unmapped memory (see note below) it crashes, not just a thread, but the whole process. It would not affect other processes since their memory spaces are isolated. (This is not true in old operating systems like Windows 95, where all processes shared the same memory space).

*In C++, stack-allocated objects are created when the block is entered, and destroyed when the block is exited. The actual space on the stack may be allocated less precisely though, but the construction and destruction will take place at those particular points.

*The stack pointer on x86 processes can be arbitrarily manipulated. It's common for compilers to generate code that simply add the amount of space to the stack pointer, and then set the memory for values on the stack, instead of doing a bunch of push operations.

*The stacks and heap of the process all live in the same memory space.
An overview of how memory is organized may be helpful:

*

*You have physical memory which the kernel sees.

*The kernel maps pages of physical memory to pages of virtual memory when a process asks for it.

*A process operates in its own virtual memory space, ignorant of other processes on the system.

*When a process starts, it puts sections of the executable (code, globals, etc) into some of these virtual memory pages.

*The allocator requests pages from the process in order to satisfy malloc calls, this memory constitutes the heap.

*when a thread starts (or the initial thread for the process), it asks the OS for a few pages that form the stack. (You can also ask your heap allocator, and use the space it gives you as a stack).

*When the program is running, it can freely access to all memory in its address space, heap, stack, whatever.

*When you attempt to access a region of your memory space that is not mapped, your program crashes. (more specifically, you get a signal from the OS, which you can choose to handle).

*Stack overflows tend to cause your programs to access such unmapped regions, which is why stack overflows tend to crash your program.

A: *

*Where global variables are allocated is actually system dependent. Some systems will place them statically in the binary, some will allocate them on the heap, some will allocate them on the stack. If a global variable is a pointer, you can delete the value it points to, but there is no way to clear that memory otherwise. Destructors for global variables will be called automatically when the application exits (well, maybe not with a SIGTERM)

*I'm not positive, but I imagine it's managed by the operating system, specifically the kernel.

*Yes, and only to a certain point. For instance, you can't do infinite recursion because values will (no pun intended) stack up. You'll wind up with a, wait for it, stack overflow (AHH, there it is, he said it!)

*Some operating systems may impose a heap size limit through a separate process, but generally if you fail to allocate memory it's because there's no memory left.

*All threads share a common heap, and so yes, they can all access global variables, dynamically allocated, etc..

*Generally correct, though on some really bare-bones architectures this may not be true. For the most part, the OS executes the process in the context of a virtual table, so the pointer values you're using actually point to a different memory address than what they would appear to.

*The current process, if by process you mean OS-level process.

*I'm assuming that is correct, but I don't know myself.

*This one's out of my wheelhouse.

*Yes, sort of. As I mentioned before, most OSes use vtables to map process pointers to main memory. Also, consider paging to disk (swapping)


text:
Q: Javascript Rotating Banner I am wanting to make a rotating banner using Javascript. This is intended to have advertisements on my website which have an image with a clickable link and changes every 5 seconds. I would like the banner to be 728x90. I would like to have the image and link files in the javascript file so if it needs to be modified, it can be easily without going through 100 html pages. Is there anyone that can help me out with this? I am very new to coding, so if someone can give me a basic walkthrough, that would be greatly appreciated.

A: To provide an image as link, you need to embedd it inside an anchor element.

To set the urls at runtime via JavaScript, you can simply do
document.getElementById("ad-link").setAttribute("href", "http://...");
document.getElementById("ad-img").setAttribute("src", "http://...");

To change the banner every 5 seconds, you need to define a timeout, after which a specific function is called.
setTimeout(function() {
    //update banner
}, 5000);

To rotate the banner, i recomend to use css. see How to do a webkit css endless rotation-animation.