text:
Q: How to make an accurate search from two column in Mysql I am creating a search of First_name And Last_name from my database whereby the user inputs what he wants to find in a field and my php script will search the name that looks like those name.
So i did
$q=addslashes($_REQUEST['q']);

$q =mysqli_real_escape_string($connection, $q);

//In order to search word by word i explode the string
$notre_tableau=explode(',',$q);

//I count the string in order to search each word
$compter_tableau=count($notre_tableau);

$req_search = "SELECT   first_name, last_name

FROM  mytable

WHERE ";

//Now i read the array and search for each word
for ($i = 0; $i < $compter_tableau; $i++)
{
$notremotchercher=trim($notre_tableau["$i"]);

if($i==$compter_tableau) { $liaison="AND"; } else { $liaison=""; }

if($i!=0) { $debutliaison="AND"; } else { $debutliaison=""; }

//I search only if the string is not empty

if($notremotchercher!='')
{
$req_search .= "$debutliaison (first_name LIKE '%$notremotchercher%' OR last_name LIKE '%$notremotchercher%')  $liaison";
}

}

//Now i proceed with my search
$requete=mysqli_query($connection, "$req_search ORDER BY id  DESC LIMIT 20  ") or die(mysqli_error($connection));

So if someone's first Name are is Jennifer Jane and last name is DOE, for example, if i input in Jennifer (only Jennifer) it works,
and if i Input in Jennifer Jane  it works,
 and if i input in DOE, it also works.
The above code will display something like this for a search based on Jennifer
SELECT  first_name, last_name  FROM mytable WHERE    (first_name LIKE '%Jennifer%' OR last_name LIKE '%Jennifer%')

Therefore I get a result
Problem
If I input in Jane Jennifer, it does NOT work
Also if i Input in Jennifer DOE, it does not work. Please how to make it work for Both column knowing that i can not tell what the user will input in First ?
Thanks

A: You'll probably want to split up the words in the search. So if the search term was "Jane doe"...
<?php
     $search_phrase = "Jane Doe";
     $terms = explode(" ",$search_phrase);
     $query = "SELECT first_name, last_name  from myTable WHERE ";

     for($i=0;$i<count($terms);$i++){
         if($i!=0)
            $query.=" OR ";
         $query.=" (first_name LIKE '%".$terms[$i]."%' OR last_name LIKE '%".$terms[$i]."%')";
     }

     echo $query; //Should produce "SELECT first_name, last_name  from myTable WHERE (first_name LIKE '%Jane%' OR last_name LIKE '%Jane%') OR (first_name LIKE '%Doe%' OR last_name LIKE '%Doe%')"

?>

You can use something like above and taylor it to your needs, like only searching for the last name using the second part of the term, etc..

A: You explode your search string:
$searhStr     = 'Jane Jennifer';
$searchSplits = array(' ',',','.','-','?','!',"\n");
$searchArray  = explode($searchSplits,$searhStr);

and then you look for each word in the array:
forach ($searchArray as $searchWord)
{
  $queryParts[] = "first_name LIKE '%{$searchWord}%'";
  $queryParts[] = "prenom LIKE '%{$searchWord}%'";
}
$query = 'SELECT first_name,
                 last_name
          FROM mytable
          WHERE '.implode(' OR ',$queryParts);

It is never to late to learn new things. Have a look at how MySQL can help you doing searches:
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html


text:
Q: Import npm package to nuxt appliction For SEO Reasons i had to rebuild my vuejs app with Nuxt.
How can you import npm packages in nuxt app?
like in vue.js you simply add the code below to APP.vue
import InfiniteLoading from 'vue-infinite-loading'
vue.use(InfiniteLoading)

A: create new file in plugin folder infinite-loading.js
import vue from "vue"
import InfiniteLoading from 'vue-infinite-loading'
vue.use(InfiniteLoading)

in nuxt.config.js include your file name in plugin array
  plugins: [
    '@/plugins/infinite-loading',
  ],

then restart the serve

redpajama_set_name: RedPajamaStackExchange


text:
Q: pip freeze reports version number instead of git sha for certain package Typically, when I pip install -e from a git repo, and then do "pip freeze", it gives me git version info. For example:
$ pip install -e git://github.com/kennethreitz/requests.git@27b55a74d7b9bd2f8c60fd0ee342bcbbf40e0a66#egg=requests-dev
$ pip freeze | grep requests
-e git://github.com/kennethreitz/requests.git@27b55a74d7b9bd2f8c60fd0ee342bcbbf40e0a66#egg=requests-dev

Why is it that when I do this with the piplint package, "pip freeze" reports the version number instead of the git details?
$ pip install -e git://github.com/dcramer/piplint.git@cb2752e0c9692e4df2b2b03dec3087699e90f4da#egg=piplint
$ pip freeze | grep piplint
piplint==0.1.1

A: When "pip freeze" tries get vcs backend to piplint, It doesn't finds it, then it marks the package as not editable.
See:
https://github.com/pypa/pip/blob/develop/pip/init.py#L135
https://github.com/pypa/pip/blob/develop/pip/vcs/init.py#L60
Maybe it's a bug in pip or in piplint  setup.py.


text:
Q: How does changing Fourier coefficients affect a function's $L^1$ norm? I am hoping to prove a version of Lemma 1.12 about convex Fourier coefficients from Classical and Multilinear Harmonic Analysis by Muscalu and Schlag. The lemma is as follows:
Let $\{a_n\}_{n \in \mathbb{Z}}$ be an even sequence of nonnegative numbers that tend to zero, which is convex in the following sense:
$$a_{n+1} + a_{n−1} − 2a_n \geq\ 0 \forall\ n > 0.$$
Then, there exists $f \in L^1(\mathbb{T})$ with $f \geq 0$ and $\hat{f}(n) = a_n$.
Here $\mathbb{T} = \mathbb{R}/\mathbb{Z}$. The crux of the proof is in noticing that the Fourier coefficients of the Fejer kernels are exactly $\hat{K}_n(m) = (n-m)$. This allows them to construct the function
$$f = \sum_{n=1}^\infty n(a_{n+1} + a_{n-1} + 2a_n)K_n,$$
which has a bunch of nice properties which prove the lemma, and very important has bounded norm, $\Vert f \Vert_{L^1(\mathbb{T})} = \vert \hat{f}(0) \vert = a_0 < \infty$.
The lemma can be modified to work for odd convex sequences if one takes a family of kernels $F_n$ such that $\hat{F}_n(m) = \hat{K}_n(m)$ for $m \geq 0$ and $\hat{F}_n(m) = -\hat{K}_n(m)$ for $m < 0$. The issue I am having in proving this is that I don't know what the $L^1$ norm of these kernels are, in particular, whether they are bounded. If they are then that would be great and the proof is done by the exact same argument as in M&S. If not, then it may be because the claim is false... (This is in hopes of proving Problem 1.8 with a similar method as Exercise 1.7).

A: The result can not be true for both odd and even sequences.
Otherwise, I mean, if true for both, one could sum up the functions and get $H^1$ function
with Fourier coefficients $a_n$ for any convex, non negative, and tending to $0$ sequence $a_n$. However, as it is well known, (Hardy's inequality), for functions in $H^1$ one has
$$ \sum \frac{|a_n|}{n} < \infty$$
Also, for any convergent to $0$ sequence of numbers $b_n$ one can find convex, non negative, convergent to zero sequence $a_n$ such that $a_n >= |b_n|$


text:
Q: Yodlee FastLink Hide List of Added Accounts Is it possible to hide the list of added accounts (and also the "show all added accounts" link at the bottom) in Yodlee FastLink (see first image).
I'd also like to keep the help text on the next screen visible (see second image).  Looking at the HTML/CSS of the page I am not sure if this is possible.
Thank You!

A: Yes, this is possible.
Once you'll become Yodlee's customer and have your own staging environment, you can ask Yodlee support team to disable this for you.
Also, the Fastlink version you are looking is an older version. Yodlee has introduced the latest version Fastlink 2.0, this has additional features in comparison to Fastlink 1.0.


text:
Q: Finding max row after groupby in pandas dataframe I have a daframe as follows:
Month   Col1    Col2    Val
A       p       a1      31
A       q       a1      78
A       r       b2      13
B       x       a1      54
B       y       b2      56
B       z       b2      65

I want to get the following:
Month   a1  b2
A       q   r
B       x   z

Essentially for each pair of Month and Col2, I want to find the value in Col1 which is has the maximum value.
I am not sure how to approach this.

A: Your problem is:

*

*Find row with max Val within a group, which is sort and drop_duplicates, and

*transform the data, which is pivot:

(df.sort_values('Val')
   .drop_duplicates(['Month','Col2'], keep='last')
   .pivot(index='Month', columns='Col2', values='Col1')
)

Output:
Col2  a1 b2
Month
A      q  r
B      x  z


text:
Q: jQuery AJAX - Pass value to a PHP file I have a div which includes a data-id value. I want jQuery to detect when the div is clicked and then send or store the data-id value in a PHP file. My code is below, the click is detected and the data-id value is stored but I'm receiving an error for obtaining the data-id value in the php file, how do I solve this? I just want the value '189' to be stored in the 'player.php' file.
myteam.php file

Alisson

0

player.js file
$(document).ready(function(){

    $('.player').click(function() {

    var pid = $(this).data("id");

    $.ajax({
        method: "POST",
        url: "player.php?",
        data: pid,
        success: function( pid ){
            alert(pid);
          }
        });
    });

});

player.php file
if(session_id() == '' || !isset($_SESSION)) {
    // session isn't started
    session_name('FantasyKicks');
    session_start();
}

$pid = $_POST['pid'];

echo $pid;

A: Change your AJAX to identify the pid (and you don't need the ? on the URL):

    $('.player').click(function() {

    var pid = $(this).data("id");

    $.ajax({
        method: "POST",
        url: "player.php",
        data: { pid: pid } // the first `pid` is the identifier, the second is your value
        success: function( pid ){
            alert(pid);
          }
        });
    });

});


text:
Q: How to make vertical lines in the planes zx and z and gnuplot I need a little help.
I'm making a three surfaces together in gnuplot, but I need to place the vertical and horizontal grids for the Z axis on the back of the surfaces. I've only been able to make the horizontal lines, and I want to add the vertical lines, some suggestions to do this in my code
Thank you very much.
set key outside
set rmargin at screen 0.6
set lmargin at screen 0.18
set title 'Gnuplot surfaces'
set key
set pm3d depthorder hidden3d 1
set hidden3d offset 0
set xlabel "X"
set xrange [ -4.0000 : 4.0000 ] noreverse nowriteback
set mxtics 4
set ylabel 'Y'
set yrange [ -4.0000 : 4.0000 ] noreverse nowriteback
set mytics 4
set zlabel "Z"
set zrange [-1.000: 1.000] noreverse nowriteback
set mztics 4
set surface
set isosamples 25
unset colorbox
set ticslevel 0
set grid ztics xtics ytics lt 2 lc rgb "black"
set border 4095
set view 43, 32
a(x,y)= sin(sqrt(x**2+y**2)) / sqrt(x**2+y**2)
b(x,y)= x**3*y**2
c(x,y)= sin(x) * cos(y)
splot a(x,y) lc rgb 'gray' linewidth 2, b(x,y) lc rgb 'red' linewidth 0.5, c(x,y) lc rgb 'blue' linewidth 1

A: First, add a data block (gnuplot 5.0 or greater) for all the grid lines as vectors:
$data << EOD
-4 -3 -1 0 0 2
-4 -2 -1 0 0 2
-4 -1 -1 0 0 2
-4  0 -1 0 0 2
-4  1 -1 0 0 2
-4  2 -1 0 0 2
-4  3 -1 0 0 2
-3  4 -1 0 0 2
-2  4 -1 0 0 2
-1  4 -1 0 0 2
 0  4 -1 0 0 2
 1  4 -1 0 0 2
 2  4 -1 0 0 2
 3  4 -1 0 0 2
EOD

Now, just create an arrow style as black with no heads and add this 'file' to the plot with vectors and no title.
set style arrow 1 nohead lc 'black'
replot "$data" with vectors arrowstyle 1 title ""

If you do not have gnuplot 5.0 or greater, put the data block in a file and just plot the file.


text:
Q: Running a continuous running worker process on Heroku What is the best way for running a continuous worker process on Heroku? My application needs this process running 24/7, so delayed_job or other queues seem like overkill. I can trigger the process manually through the Heroku console, and I could detach it would run by itself.
Preferably, I'd like to assign just this single method call to a dyno, such that when my app boots, it launches the extra worker-dyno and then calls my single method and starts humming away. But not sure how to assign that method call?
I could use delayed job and it would solve everything, but it seems my need is for a singularly activity that is immediate (when called) and not scheduled. But perhaps this is the only way.

A: In your Procfile you could add a seperate process for your extra worker job
# Procfile
web: ...
worker: ...
collector: bundle exec ruby stats_collector.rb -p $PORT # or any other command

You could then scale this process with $ heroku ps:scale collector=1. It would run seperately and be stopped and restarted at every deploy. I'd say that what your app does thus has to be safe to be interrupted any time to use such a long running process.
If interruptions might lead to problem (e.g. stuff you want only done once is done twice if restarted) the a 'traditional' background worker using e.g. Sidekiq that queues messages might be a safer solution.
Update
If you want to execute long-running code non-interactively in the context of your Rails app, you can use the rails runner command.
# Procfile
web: ...
worker: ...
collector: bundle exec rails runner 'MyModel.my_long_running_job'


text:
Q: Github Actions Workflow that runs when branch is main AND a matching tag is present I'm having trouble figuring out how to make the events that trigger a workflow respond in an "AND" manner, as they seem to default to "OR" - the below YAML results in the workflow running twice (I presume once in response to the branch being correct and the other being due to the tag being matched):
on:
  push:
    branches:
      - main
    tags:
      - v*

What I'm looking for is the workflow to run when the commit is to the main branch and tagged with a v* tag. What actually happens is that the workflow will run when either of these conditions are true (or twice if they both are).
Is there a way to restrict the workflow to only running when all on events are matched?


text:
Q: groupy and aggregation in Dask My dataframe look like the below:
    # initialize list of lists
    data = [['tom', 10], ['nick', 15], ['juli', 14],['tom', 10], ['juli', 15] ]

    # Create the pandas DataFrame
    df = pd.DataFrame(data, columns = ['Name', 'Age'])

            Name    Age
        0   tom     10
        1   nick    15
        2   juli    14
        3   tom     10
        4   juli    15

I want to group by the 'Name', count the 'Age' and unique count of 'Age'.
Using pandas I got the result:
           Age
           count    nunique
    Name
    juli    2      2
    nick    1      1
    tom     2      1

Pandas code :
    types = ['count', 'nunique']
    df.groupby('Name').agg({'Age': types})

How can i achieve this in Dask?
In dask, I can do either count or nunique...
    ddf = daskdf.from_pandas(df, npartitions=4)
    ddf.groupby('Name').Age.count().to_frame().compute()

               Age
        Name
        nick    1
        tom     2
        juli    2

A: The advantage of lazy computations is that you can specify them one at a time, but the actual computation will be done with some optimization to avoid redundant calculations.
Specifically, you can create lazy computation for nunique and count separately, then combine the computed results:
# calculation with dask
dask_series = ddf.groupby("Name")["Age"]

# these are lazy results that will need to be computed
lazy_results = [
    dask_series.nunique().to_frame(name="age_nunique"),
    dask_series.count().to_frame(name="age_count"),
]

# note that concatenation happens on computed results
print(pd.concat(*dd.compute(lazy_results), axis=1))

Here's the full snippet:
import dask.dataframe as dd
import pandas as pd

# initialize list of lists
data = [["tom", 10], ["nick", 15], ["juli", 14], ["tom", 10], ["juli", 15]]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns=["Name", "Age"])

# calculation with pandas
types = ["count", "nunique"]
print(df.groupby("Name").agg({"Age": types}))
#        Age
#      count nunique
# Name
# juli     2       2
# nick     1       1
# tom      2       1

# calculation with dask
dask_series = ddf.groupby("Name")["Age"]

# these are lazy results that will need to be computed
lazy_results = [
    dask_series.nunique().to_frame(name="age_nunique"),
    dask_series.count().to_frame(name="age_count"),
]

# note that concatenation happens on computed results
print(pd.concat(*dd.compute(lazy_results), axis=1))
#       age_nunique  age_count
# Name
# nick            1          1
# tom             1          2
# juli            2          2


text:
Q: How can I compile CIL code that is Large Address Aware I have compiled a c# application and dll for "Any CPU" and decompiled both afterwards with ildasm.exe. In the next step I assembled the data (.il and .res) file back into an application/dll file with ilasm.exe which worked fine, except for the Large Address Aware flag.
When looking into the .il file, the COFF Header Characteristics 0x2122  indicate that the Large Address Aware flag was detected, but the re-assembled file is lacking this flag 0x2102.
Disassembler command:
ildasm.exe "test.dll" /out="test.il" /text /all /bytes /linenum /nobar /source /tokens
Assembler commands:
ilasm.exe "test.il" /out="test.il.dll" /res:"test.res" /dll /optimize /flags=0x2122
Does anybody have an idea why this is not working or what I am doing wrong?


text:
Q: Vue.js, Url and Routing I'm writing a Vue.js application. I don't know why it keeps appending '#' to every Url I type into the browser. Has anyone had a similar issue with Vue? For example, when I type 'localhost:8080/register' the browser changes it into 'localhost:8080/register#/'. The routing isn't working properly either. Does anyone know what may be causing the problem?

A: In your route configuration, set the mode to history.
mode: "history"

like:

const router = new VueRouter({
  mode: "history",
  routes: [
    // ...
  ]
})


text:
Q: How to reverse a string without using reverse() function, wanting the reverse to be word by word not from last index to the first index in swift let word = "String to be reverse"

var reversed = ""
for char in word.characters {
    reversed.insert(char, at: reversed.startIndex)
}
print(reversed)

This returns : "esrever eb ot gnirtS"
What i'm trying to do is like this "ngirtS ot eb esrever"

A: You can use enumerateSubstrings in range using options .byWords, get all substrings range and replace them with the substring of the same range reversed:
let string = "String to be reverse"

var ranges: [Range<String.Index>] = []
string.enumerateSubstrings(in: string.startIndex..., options: .byWords) { _, range, _, _ in
    ranges.append(range)
}
var result = string
for range in ranges {
    var newWord = string[range]
    var reversed = ""
    while !newWord.isEmpty {
        reversed.append(newWord.removeLast())
    }
    result.replaceSubrange(range, with: reversed)
}
print(result) // "gnirtS ot eb esrever"


text:
Q: How to use model form instances of a formset in Django template I'm trying to access the instance of the forms in a formset, but it is not working.  I CAN access them using the variable notation, as in {{ form }}, but not in code, as in {% url 'section' form.instance.pk %}.  I need to iterate through the forms in the formset along with the corresponding model instance.
My view:
# views.py

def sec(request, companyurl):
    company = get_if_exists(Company, author=request.user)

    SectionFormSet = modelformset_factory(Section, form=SectionForm, can_delete=True)
    sections = Section.objects.filter(company=company).order_by('order')
    formset = SectionFormSet(request.POST or None,
                             initial=[{'company': company}],
                             queryset=sections

    context = {
        'sections': sections,
        'formset': formset,
    }
    return render(request, 'questions/sections.html', context)

My model:
# models.py

class Section(models.Model):

    section = models.CharField(max_length=100)
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    order = models.PositiveIntegerField(default=1000000)
    show = models.BooleanField(default=True)

    def __str__(self):
        return self.section

My Form (I'm using django-crispy forms):
# forms.py
class SectionForm(forms.ModelForm):
    class Meta:
        model = Section
        fields = ['company', 'section', 'show', 'order']
        labels = {
            'section': '',
            'show': 'Show'
        }
    def __init__(self, *args, **kwargs):
        super(SectionForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Div(
                Div(HTML("##"), css_class = 'my-handle col-auto'),
                Div('section', css_class='col-3'),
                Div('show', css_class = 'col-auto'),
                Div('DELETE', css_class = 'col-auto'),
                Field('company', type='hidden'),
                Field('order', type='hidden'),
                css_class='row',
            ),
        )

My template (this is where the problem is seen):
<form action="#" method="post">
  {% csrf_token %}

  {{ formset.management_form }}

  {% for fo in formset %}

      {% crispy fo %}

      {{ fo.instance }} + {{ fo.instance.pk }} + {{ fo.instance.section }}

        {{ fo.instance }}

      <input type="hidden" name="order" value="{{ section.pk }}">

      {% for hid in fo.hidden_fields %}
        {{ hid }}
      {% endfor %}

  {% endfor %}

  <button type="submit" class="btn btn-outline-primary">Save changes</button>

</form>

When I add the  link line I get
Reverse for 'section' with arguments '(None, '')' not found. 1 pattern(s) tried: ['section/(?P<pk>[0-9]+)/(?P
[^/]+)\\Z']
The error is clear.  fo.instance.pk is None and fo.instance.section is an empty string.  Yet when I remove the anchor tag, the line above appears and shows the correct values for both of these.  I think I know the difference in how the {{  }} and the {%  %}, and I thought I knew how model form instances were tied to the model, but I am missing something.
Thanks for any help.

A: Formsets create blank forms
The answer was staring me in the face, when I printed the results.  The last form, a blank, of course was giving me None and an empty string, since it had no data to fill it with.  Thus the simple solution is to check for this before trying to form the url with the information.  Therefore, this has nothing to do with the differences between {{ }} and {%  %} nor form instances.
{% for fo in formset %}

      {% crispy fo %}

      {{ fo.instance }} + {{ fo.instance.pk }} + {{ fo.instance.section }}

      {% if fo.instance.pk %}

           {{ fo.instance }}

      {%  endif %}

      <input type="hidden" name="order" value="{{ section.pk }}">

      {% for hid in fo.hidden_fields %}
        {{ hid }}
      {% endfor %}

  {% endfor %}

  <button type="submit" class="btn btn-outline-primary">Save changes</button>

</form>


text:
Q: How to receive input as JSON in RESTEasy api? I have a users table having details of multiple users. I am supposed to receive an input from the front end which sends user details in JSON format which is to be inserted or updated in the table accordingly.
How can I receive the input in RESTEasy and parse it to populate the variables corresponding to the table?

A: It is very easy, all you need is to do is define a json provider for RESTeasy (such as resteasy-jackson-provider), annotate the relevant resource method with consumes("application/json") and supply it with your domain object as an input parameter.
The provider will do the hard work for you.
As an example, you can refer:
@POST
@Consumes("application/json")
    public Response createUserFromJSON(User user) {
      // insert the user
    ...
}


text:
Q: How to make an editable/typeable widget (like the Google Now search box)? My first guess was to try EditText but it's not available for an AppWidget.
I did some research and found out that it's only possible on some selected HTC devices and that is not the solution I seek.
However I can see just the behaviour I want in the Google Now search widget - I tap on it and a keyboard appears. I can't seem to do it though.
Is there a way to do that? Or is it just reserved for Google-stuff and a couple devices which have such a mechanism implemented?


text:
Q: How to tell if my iPad and iOS Simulator are using the same iCloud account? I am trying to sync my iPad with the iOS simulator (8.1.1) for debugging under XCode 6.1.  How can I tell if they are both using the same iCloud account?  I have looked in Google and SO, but found nothing that would answer my question.
Thanks...

A: Open up the Settings app, and scroll down to iCloud.  It lists your account below "iCloud"


text:
Q: Is any way I can define where to look for images when rendering img tag? Like any other mvc project, I have used img tag and src="~/Images/test.png" all over my project to display different images in different pages. Is there any ideas to control where to look for images (assume I have hosted these images in different place) instead of looking into images folder before rendering?

A: pass the location in as part of the model.
<img src='@string.Format("~/{0}/test.png", url)'>


text:
Q: Making an HTML page communicate with a socket in C I am working on a project for my studies, which consists in programming a small "Twitter-like" thing, which goal is to work with sockets and network in C. The idea is that you boot up a server executable, then you can use a client executable to connect to the server.
Once connected (in the terminal), you can use a selection of commands to follow a new user, display all tweets from people you follow, and so on.
Now, one bonus goal of this project is to create a web interface for this. Instead of using the terminal, as the client, you use a web browser. I managed to make the server display "Welcome on blahblah, enter your login" on the webpage, but then, I don't know how the client can interact with the page, to send info to the server.
I imagine I'd have to create a HTML page with some forms, to send data. Now, the issue is, how can I send these data to my server's socket ? Ideally, I would like to simply send something like "ALL" to the server, just like a client in the terminal would do, and for the server to send back to the client (in this case the web browser) the response.
So my goal is to simulate the kind of message the terminal would send, so that I don't have to fully write a second set of commands, and can use the ones already implemented.
I've searched the lot, and I'm mainly disappointed. The only way I found to do that would be using Websockets in js. The problem is that they use special kind of secured communications, that are absolutely not compatible with my current socket, which is very "barebone". What could you advise ? How could I, from my HTML page, establish a connexion with the socket, and then send data to the socket ? As well as receive them ? Of course, no libraries or frameworks are allowed.

A: I would suggest you to look for mongoose server. Its very light weight server that can fit into your server application. The integration part is quite simple. Look at their examples on how they integrate and communicate with HTML client to the server.


text:
Q: Mutate a data frame based on regex and regex value Is a feature has a match for a regex, I would like to use the value of the match to populate a new feature, else NA.
I found this post and tried to use the answer for my problem.
library(dplyr)
library(stringr)

dat.p <- dat.p %>%
  mutate(
    cad = ifelse(str_locate(text_field, "\\[[^]]*\\]"),
                 str_extract(text_field, "\\[[^]]*\\]"),
                 NA)
    )

Where if there's a match for regex \\[[^]]*\\] within text_field use that value in new column cad, else make the value of cad NA.
When I run it I get error:
Error: wrong result size (1000000), expected 500000 or 1

How do I do this?
Some example data:
df <- data.frame(
  id = 1:2,
  sometext = c("[cad] apples", "bannanas")
)

df.desired <- data.frame(
  id = 1:2,
  sometext = c("[cad] apples", "bannanas"),
  cad = c("[cad]", NA)
)

A: I don't know why you bother with mutate and an ifelse when its a one liner using the fact that str_extract will give you an NA if it extracts nothing:
> df$cad = str_extract(df$sometext,"\\[[^]]*\\]")
> df
  id     sometext   cad
1  1 [cad] apples [cad]
2  2     bannanas  <NA>

You can debug R by trying expressions individually and seeing what happens. For example, the first element to your ifelse is this:
> str_locate(df$sometext,"\\[[^]]*\\]")
     start end
[1,]     1   5
[2,]    NA  NA

which is clearly not going to work as the first argument of an ifelse. So why did you think it did?

A: > df$cad <- regmatches(df$sometext, gregexpr("\\[[^]]*\\]", df$sometext))
> df
  id     sometext   cad
1  1 [cad] apples [cad]
2  2     bannanas


text:
Q: How to join 2 tables with one of them containing multiple values in a single column I have two tables users and interests which i'm trying to join. Inside users table i have columns as id, name, interest, etc. The interest column contain multiple values as "1,2,3". My second table interests have 2 columns id and name as:
id | name
-------------
1  | business
2  | farming
3  | fishing

What i want to do is join interests table with users table so i get the following output:
users table:
id | name     | interest | interest_name
----------------------------------------------
1  | username | "1,2"    | "business, farming"
2  | username | "2,3"    | " farming, fishing"

I wrote the following query to achieve this:
select users.*, interests.name as interest_name
  from users
  left join interests on users.interest = interests.id;

Results i got:
id | name     | interest | interest_name
----------------------------------------
1  | username | "1,2"    | "business"
2  | username | "2,3"    | " farming"

Problem:
I'm only getting the name of first values from interest column whereas i want all the values from interest column i have already tried using group_concat and find_in_set but getting the same results.

A: Pull the interest column out of the users table and create a user_interests table that contains the user ids and interest ids:
user_id | interest_id
--------+------------
1       | 1
1       | 2
2       | 2
2       | 3

Then join the users table to the user_interests table, and the user_interests table to the interests table:
SELECT users.username, interests.interest
  FROM users
  LEFT JOIN user_interests ON users.id = user_interests.user_id
  LEFT JOIN interests ON user_interests.interest_id = interests.id
  WHERE interest_id IS NOT NULL;

Outputs:
username | interest
---------+---------
Clark    | business
Clark    | farming
Dave     | farming
Dave     | fishing

Then use your server programming language to compile the query results.
Try it here: https://onecompiler.com/mysql/3yfe5pp7x
-- create
CREATE TABLE users (
  id INTEGER PRIMARY KEY,
  username TEXT NOT NULL
);

CREATE TABLE user_interests (
  user_id INTEGER,
  interest_id INTEGER,
  UNIQUE KEY user_interests_constraint (user_id,interest_id)
);

CREATE TABLE interests (
  id INTEGER PRIMARY KEY,
  interest TEXT NOT NULL
);

-- insert
INSERT INTO users VALUES (1, 'Clark'), (2, 'Dave'), (3, 'Ava');
INSERT INTO interests VALUES (1, 'business'), (2, 'farming'), (3, 'fishing');
INSERT INTO user_interests VALUES (1, 1), (1, 2), (2, 2), (2, 3);

-- fetch
SELECT users.username, interests.interest
  FROM users
  LEFT JOIN user_interests ON users.id = user_interests.user_id
  LEFT JOIN interests ON user_interests.interest_id = interests.id
  WHERE interest_id IS NOT NULL;

A: In the case you cannot create an additional database table in order to normalize the data...
Here's a solution that creates an ad hoc, temporary user_interests table within the query.
SELECT users.id user_id, username, interests, interests.interest
FROM users
LEFT JOIN (
  SELECT
    users.id user_id,
    (SUBSTRING_INDEX(SUBSTRING_INDEX(users.interests, ',', ui.ui_id), ',', -1) + 0) ui_id
  FROM users
    LEFT JOIN (SELECT id AS ui_id FROM interests) ui
      ON CHAR_LENGTH(users.interests) - CHAR_LENGTH(REPLACE(users.interests, ',', '')) >= (ui.ui_id - 1)
) user_interests ON users.id = user_interests.user_id
LEFT JOIN interests ON user_interests.ui_id = interests.id
ORDER BY user_id, ui_id;

Outputs:
user_id | username | interest_ids | interest
--------+----------+--------------+---------
1       | fred     | 3,4,8,6,10   | fishing
1       | fred     | 3,4,8,6,10   | sports
1       | fred     | 3,4,8,6,10   | religion
1       | fred     | 3,4,8,6,10   | science
1       | fred     | 3,4,8,6,10   | philanthropy
2       | joe      | 7,11,8,9     | art
2       | joe      | 7,11,8,9     | science
2       | joe      | 7,11,8,9     | politics
2       | joe      | 7,11,8,9     | cooking

As you can see...
SELECT
  users.id user_id,
  (SUBSTRING_INDEX(SUBSTRING_INDEX(users.interests, ',', ui.ui_id), ',', -1) + 0) ui_id
FROM users
  LEFT JOIN (SELECT id AS ui_id FROM interests) ui
    ON CHAR_LENGTH(users.interests) - CHAR_LENGTH(REPLACE(users.interests, ',', '')) >= (ui.ui_id - 1)

...builds and populates the temporary table user_interests with the users.interests field data normalized:
user_id | ui_id
--------+------
1       | 3
1       | 4
1       | 6
1       | 8
1       | 10
2       | 7
2       | 8
2       | 9
2       | 11

...which is then LEFT JOIN'ed between the users and interests tables.

Try it here: https://onecompiler.com/mysql/3yfhmgq3y
-- create
CREATE TABLE users (
  id INT PRIMARY KEY,
  username VARCHAR(20),
  interests VARCHAR(20)
);

CREATE TABLE interests (
  id INT PRIMARY KEY,
  interest VARCHAR(20)
);

-- insert
INSERT INTO users VALUES (1, 'fred', '3,4,8,6,10'), (2, 'joe', '7,11,8,9');
INSERT INTO interests VALUES (1, 'business'), (2, 'farming'), (3, 'fishing'), (4, 'sports'), (5, 'technology'), (6, 'religion'), (7, 'art'), (8, 'science'), (9, 'politics'), (10, 'philanthropy'), (11, 'cooking');

-- select
SELECT users.id user_id, username, interests, interests.interest
FROM users
LEFT JOIN (
  SELECT
    users.id user_id,
    (SUBSTRING_INDEX(SUBSTRING_INDEX(users.interests, ',', ui.ui_id), ',', -1) + 0) ui_id
  FROM users
    LEFT JOIN (SELECT id AS ui_id FROM interests) ui
      ON CHAR_LENGTH(users.interests) - CHAR_LENGTH(REPLACE(users.interests, ',', '')) >= (ui.ui_id - 1)
) user_interests ON users.id = user_interests.user_id
LEFT JOIN interests ON user_interests.ui_id = interests.id
ORDER BY user_id, ui_id;

Inspired by Leon Straathof's and fthiella's answers to this SO question.


text:
Q: Grails gsp won't render correctly This is the main login page of my application:

Once you're logged in, you see this page:

Now on this page if you press the 'Choose/Upload' button (circled in blue), you get a template rendered in the middle part of the page and then it looks like this:

If you wait a while such that your session becomes null, then I want the 'Choose/Upload' button to redirect back to the login page, which it does but things look like this:

This is the controller function associated with the 'Choose/Upload' button:
def chooseupload = {
        if (session.user == null) {
            redirect(action: customerLogin)
        }
        else {
            def batchList = (Batch.findAllWhere(userId: session.user.id.toLong(), [sort: "lastUpdate", order: "desc"]))
            render(template: 'chooseupload', model:  [batchList: batchList, batchCount: batchList.size()])
        }

    }

and this is the code of the login action:
def customerLogin = {
    } //just renders the view customerLogin.gsp

Any advice greatly appreciated. I am happy to provide more relevant code if needed.

A: you seem to be calling chooseupload in an AJAX request. If you call redirect in the controller, the browser gets the fully decorated (with header & footer) page back. In order to be able to differentiate between AJAX/noAJAX calls, I'm using the following code:
request.xhr ? render( template:'customerLogin' ) : redirect( action:'customerLogin' )


text:
Q: can not find videogular2 in angular 10 I want to use the video player videogular2 and I install this player with this commands:
npm install videogular2
npm install @types/core-js
VgCoreModule,
VgControlsModule,
VgOverlayPlayModule,
VgBufferingModule,

and I want to import module:
import { VgCoreModule } from 'videogular2/core';
import { VgControlsModule } from 'videogular2/controls';
import { VgOverlayPlayModule } from 'videogular2/overlay-play';
import { VgBufferingModule } from 'videogular2/buffering';

but it can not find this imports of this modules .

Cannot find module 'videogular2/core' or its corresponding type declarations.
Cannot find module 'videogular2/controls' or its corresponding type declarations.
Cannot find module 'videogular2/overlay-play' or its corresponding type declarations.
Cannot find module 'videogular2/buffering' or its corresponding type declarations.

how can I solve this problem ????

A: seems like videogular2 does not support Angular 9+
https://github.com/videogular/videogular2/issues/904
The recommendation is to migrate to ngx-videogular


text:
Q: how to make a flash swf object occupy browser completely? i have a swf file of width 1000 and height 700. i want to show the swf file in full screen of the browser it self (not like videos plying full screen).
i tried like the following
1) get user screen width and height using java script using the functions available (screen.availHeight and screen.availWidth) the screen size is  available  by using the functions but not applying to the flash object
2) tried giving 100% for both height and width in object code that also not working
can any one help me on this please.
Thanks in advance.

A: Use swfobject to embed your flash and configure so that it fills 100%.
Check first question on the faq here SWFobject faq

A: Changing the dimensions on the embed/object HTML should do the trick.
Otherwise, here's some resources:
http://www.kirupa.com/developer/mx2004/fullscreen.htm
http://www.adobe.com/devnet/flashplayer/articles/full_screen_mode.html
http://www.bezzmedia.com/swfspot/tutorials/flash8/True_Fullscreen_Flash_Mode

A: Use this for your html file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head>
        <script type="text/javascript" src="swfobject.js"></script>
        <script type="text/javascript">
        swfobject.embedSWF("MySwf.swf", "swf_container", "100%", "100%", "10.0.0");
        </script>
    </head>

    <body>
        <div id="swf_container">
        </div>
    </body>
</html>

And add that swfobject.js file to bin or bin-debug or wherever it needs to go.
All that's really required is that swfobject.embed javascript call, specifying percent sizes and the flash player version.
Hope that helps,
Lance


text:
Q: Binary search error I am trying to do a binary search in a method on an array of numbers randomly filled with 0 to 100 for each number.  I am searching for the number in the array but I keep getting multiple errors when I run the program.
public static void binarySearch(int[] array){
  Arrays.sort(array);
  int searchComparisons = 0;
  int lower = array[0];
  int upper = array[array.length - 1];

  for (int i = 0; i<array.length; i++){
    System.out.println("Element "+i+" is " +array[i]);
  }

  int testSubject = (array[0]+array[array.length-1])/2;

  while((array[testSubject] != 99) && (lower <= upper)){
  searchComparisons++;
    if (array[testSubject] > 99){
              upper = testSubject - 1;
         }
              else{
          lower = testSubject + 1;
    }
       testSubject = (lower + upper) / 2;
     }

     if (lower <= upper){
           System.out.println("Binary search - number of comparisons "   +searchComparisons);
           System.out.println("This index = "+testSubject);
     }
     else{
          System.out.println("Linear search - number of commparisons: " +searchComparisons);
          System.out.println("Number not found");
  }

}

The errors are:
java.lang.ArrayIndexOutOfBoundsException: 50
    at SearchArray.binarySearch(SearchArray.java:49)
    at SearchArray.main(SearchArray.java:82)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)


text:
Q: Arduino servo library conflict In my code I use only LiquidCrystal library and Servo library. When I try to compile the code following error appears
Servo/Servo.cpp.o: In function `Servo::attached()':
/usr/share/arduino/libraries/Servo/Servo.cpp:336: multiple definition of `__vector_42'
robot_v2.cpp.o:/usr/share/arduino/robot_v2.ino:662: first defined here
/usr/lib/gcc/avr/5.4.0/../../../avr/bin/ld: Disabling relaxation: it will not work with multiple definitions
Servo/Servo.cpp.o: In function `Servo::attached()':
/usr/share/arduino/libraries/Servo/Servo.cpp:336: multiple definition of `__vector_47'
robot_v2.cpp.o:/usr/share/arduino/robot_v2.ino:662: first defined here
collect2: error: ld returned 1 exit status

Apart from above mentioned libraries, I use a 16 bit timer as follows.
DDRC |= B01010101;
......
cli();

TCCR4A = 0;
TCCR4B = 0;
TCCR5A = 0;
TCCR5B = 0;

OCR4A = l_target;
OCR5A = l_target;

TCCR4B = _BV(WGM42) | _BV(CS41);
TCCR5B = _BV(WGM52) | _BV(CS51);

TIMSK4 |= (1 << OCIE4A);
TIMSK5 |= (1 << OCIE5A);

sei();

Let me know what I'm doing wrong and how to fix this issue? Are there any other libraries than the standard Servo library for arduino? I'm using Arduino Mega board.
Here are the ISRs.
ISR(TIMER4_COMPA_vect)
{
   if (OCR4A != l_target) {
       OCR4A = l_target;
   }
   PORTC ^= B00000001;
}

ISR(TIMER5_COMPA_vect)
{
    if (OCR5A != r_target) {
        OCR5A = r_target;
    }
    PORTC ^= B00010000;
}

A: The servo library allocates timers only as needed.  Each timer supports up to 12 servos so on the Mega, 1 to 12 servos use timer5, 13 to 24 will also use timer1 and so on. The allocation order is defined in the file ServoTimers.h as follows:  timer5, timer1, timer3, timer4
Assuming you are not using more than 24 servos, timers 3 and 4 are available. If you change all references to timer 5 (TCCR5x, OCR5x, TIMSK5) to timer 3 TCCR3x, OCR3x, TIMSK3)  you should not have the conflict.

A: I found the related code from Servo library. According to that it uses 1,3,4 and 5 timers. So, I cannot use them for any other purpose. I will have to use Timer 2 or any other solution. I'm answering my own question as a reference for any one else who faces similar situation.
// Say which 16 bit timers can be used and in what order
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define _useTimer5
#define _useTimer1
#define _useTimer3
#define _useTimer4


text:
Q: Procesar un fichero .csv en java Estoy intentando leer un archivo excell para crear un archivo sin formato de texto con sus datos. Me da un error tipo errorjava.util.InputMismatchException, pero no muestra ningun tipo de ruta de locaclizacion del fallo. Creo que es por el modo de cómo trato de invocar los metodos que ofrece Scanner, pero estoy atascado.
El código Java es el siguiente
private static void procesaFichero(String filename) throws IOException{
        Scanner is = new Scanner(new FileInputStream(filename));
        VectorDinamicoRegistro vPM10 = new VectorDinamicoRegistro();
        VectorDinamicoRegistro vPM25 = new VectorDinamicoRegistro();
        VectorDinamicoRegistro vNO2 = new VectorDinamicoRegistro();
        Formatter dos = new Formatter("RegistroContaminantes.txt");
        Registro r = null;

        is.useDelimiter("; , |\r\n");
        // Primero lee la cabecera
        String c1 = is.next();
        String c2 = is.next();
        String c3 = is.next();
        String c4 = is.next();
        String c5 = is.next();

        // Y la escribe en RegistroCampus.txt
        dos.format("%2s%2s%3s%3s%3s\n", c1, c2, c3, c4, c5);
        while (is.hasNext()) {
            // Lee cada linea de texto en un Registro
            r = new Registro(); // cada vez un registro distinto!!
            r.setFechayHora(is.next());
            r.setZona(is.next());
            r.setPM10(is.nextInt());
            r.setPM25(is.nextInt());
            r.setNO2(is.nextInt());
            // Y añade el registro al vector
            vPM10.add(r);
            vPM25.add(r);
            vNO2.add(r);
            // Escribe la linea en RegistroCampus.txt
            dos.format("%24s%20s%22d%17.2f\n", r.getFechayHora(), r.getZona(), r.getPM10(), r.getPM25(), r.getNO2());
        }
        is.close();
        dos.close();
}

Y en cuanto al archivo .csv

Tiene un formato parecido al siguiente:
Fecha;Zona;PM10,PM25,NO2
2018-11-01 01:00h;CONSTITUCION;9,6,19
2018-11-02 01:00h;CONSTITUCION;17,7,35

A: Sin demasiada información, pero lo he ejecutado en mi entorno, y el problema parece estar en tu regex. No sé exáctamente cuáles son tus posibles separadores, pero tu regex toma como separador todos esos caracteres juntos. Para que matchee uno de los caracteres, tienes que ponerlo entre corchetes:
is.useDelimiter("[;,\\n]");
Este me funcionó a mi con tu ejemplo de archivo, usa punto y coma, coma, y salto de línea como separadores, y obtuve esto:
C1:Fecha, C2:Zona, C3:PM10, C4:PM25, C5:NO2
C1:2018-11-01 01:00h, C2:CONSTITUCION, C3:9, C4:6, C5:19
C1:2018-11-02 01:00h, C2:CONSTITUCION, C3:17, C4:7, C5:35


text:
Q: Google Drive Url System Design I noticed this behavior on Google Drive.
When a link is created for a file on Google Drive, the link is valid until the file is deleted.
Moving the file to another folder(s) does not affect the behavior of url.
I will like to understand how they achieved this at scale.

A: This is an expected behavior when moving files to another folder within your google drive. This is because a google file URL is usually composed of the following:

*

*product domain

*product

*document Id

Therefore, moving the file to another folder within the google drive will not affect the file URL because file path is not included in the URL format.
References:

*

*Google Sheets API Overview

*Docs API


text:
Q: How to sendKeys wherever the cursor is in selenium nodejs I have created a script to comment in facebook posts, I did clicked on comment box, and cursor do appears but unable to perform .sendKeys()
here's my code:
var commentBox = driver.findElement(By.xpath('//*[@id="addComment_'+this.postIdSlice+'"]/div/div[2]/div/div/div/div[1]/div'));
actions.mouseMove(commentBox).click().perform();
driver.sleep(2000);
actions.sendKeys("Hello").perform();

but when I execute it doesnt sends 'Hello' to comment box.
PS: that postIdSlice is id of the post, no issues there just want to push/send string in that commentbox.

A: Use the Xpath to click on the comment box, then you can use the ActionSequence to sequnce input and ENTER key.
let action = new webdriver.ActionSequence(driver);
    action.sendKeys("comment");
    action.sendKeys(Keys.ENTER);

action.perform()


text:
Q: Bootstrap custom button border appearing only on hovering I am currently designing a webpage using bootstrap. I needed a custom button color, so I designed my own button classes, which you can see there:
 .btn.btn-radio {
    background: #f3bb70;
    border-color: transparent;
    border-right-color: #684235;
}

.btn.btn-plus {
  background: #684235;
  border-color: transparent;
}

Since the button group is of the same color I wanted to put a border only on the right side, to show the separation. But the border appears only when the mouse is over the button (see https://jsfiddle.net/DTcHh/20757/ ). Why is it so ? How do I make it be there all the time ?

A: This problem has to do with the z-index of the buttons so to fix the problem without mixing up with the margin you need to  put borders to all the buttons then remove the first-child left border
.btn.btn-radio {
    background: #f3bb70;
    border-color: transparent;
    border-right-color: #684235;
    border-left-color: #684235;
}
.btn.btn-radio:first-child{
    border-left-color: transparent;
}

.btn.btn-plus {
    background: #684235;
    border-color: transparent;

}

A: Bootstrap has this line in css. This creates problem.
.btn-group .btn+.btn, .btn-group .btn+.btn-group, .btn-group .btn-group+.btn, .btn-group .btn-group+.btn-group {
      margin-left: -1px;
 }

You can use this, but i dant know if it will not make some other problems:
 .btn.btn-radio {
    background: #f3bb70;
    border-color: transparent;
    border-right-color: #684235;
    margin-left: 0!important;
 }

A: you will have to override the .btn in bootstrap.css file
it currently has
border:1px solid transparent; and hence your border is not showing normally


text:
Q: UL li horizontal menu not rendering properly in compatibility mode IE or IE 8 Hello all I am creating a horizontal menu for a site that needs to be supported in IE 8 or IE 9 -Compatability mode. In IE 9 this renders fine, however in IE8 /9-compatibility the horizontal layout is lost and as a result the items are listed vertically. The hover effect (background image) still works, as well as the other styles. Can anyone take a look at the css and tell me what I am missing to get this to render properly in earlier browser versions?
html

Home

Reporting

Dashboard

My Profile

Management Console

CSS
   .topmenubar ul a
{
    line-height: 28px;
    list-style-type:none;
    text-decoration: none;
    color: #ffffff;
    display: inline-block;
    padding: 0px 10px 0px 10px;
}

.topmenubar li  a:hover
{
    height: 28px;
    list-style-type:none;
    display: inline-block;
    text-decoration: none;
    line-height:28px;
    background-image: url('../images/topgradientBarHl.png');
    background-repeat: repeat-x;
}

.topmenubar ul
{
    display:inline-block;
    list-style-type: none;
    padding: 0;
    margin: auto 0;
}

.topmenubar li
{
    display: inline-block;
    list-style-type: none;
    padding: 0;
    margin: auto 0;
}

.topmenubar
{
    display: block;
    width: 100%;
    height: 27px;
    min-width: 920px;
    border-bottom: 1px solid #47547d;
    background-image: url('../images/topgradientBar.png');
    background-repeat: repeat-x;
}

Thanks in advance

A: Sorry all, In looking at the CSS I realized I had inline-block which was causing the return on the element. Changing the property for each of the ul and li elements to
display:inline;

Resolved the issue.
Hope this can help others at least.
Thanks


text:
Q: CSS positions and if statements in Jquery I'm using a script to move certain background elements on a page. It works by moving the "right" position of an element called #tright. This is similar to a parallax effect. All this works great, except I want the #right element to stop moving when it has a right value greater than 0. I tried to put everything in an if statement. So if the value is greater than 0 do nothing. If it's less than zero keep going. I'm obviously not a programer so I'm not even sure if this is the best way to go about this. Can anyone tell me what I'm doing wrong
$(window).bind('scroll',function(e){
    moveTriangles();
});

function moveTriangles(){
    var scrolled = $(window).scrollTop();
    var rightTriPosition = $( 'canvas#tRight.bTri' ).css( "right" );

if (rightTriPosition < 0){
    $('#tRight').css('right',(-70+(scrolled*.10))+'%');
}
else{
}

}

A: css() returns the value with an unit. Now you're comparing something like this ('-100px' < 0). You need to get rid of the unit before comparing the value with a number. For example like this:
var rightTriPosition = parseFloat($( 'canvas#tRight.bTri' ).css( "right" ));

If you don't want to execute anything when the comparison is not passed, you can simply omit the else.


text:
Q: Custom transition between two UIViews I have two views "A" and "B". A floats in the middle of the window (it's not full screen). B, the view which will replace A, is full screen. I'd like to write a custom transition that flips A to reveal B on the back side, but simultaneously scales the flipping rectangle so that when the flip is finished, B is full screen.
I've tried using the flip transitions available with transitionFromView:toView:duration:options:completion, but I can only get it to flip the entire screen instead of starting the flip with A's frame and ending with B's frame.
I know I can do 3D-like transforms to the view's layers, but I'm not sure which set of animation APIs I should use to accomplish this. One thing I tried is to modify the view's layer properties in the animations block of transitionWithView:duration:options:animations:completion: but that didn't work as it only seems to honor view property modifications.
Can someone point me in the right direction? I'd much appreciate it.
UPDATE: Here is my code thus far for this effect. You can see a video of what it does here: http://www.youtube.com/watch?v=-xNMD2fGRwg

CGRect frame = [[UIApplication easybookDelegate] rootViewController].view.bounds ;
float statusHeight = [UIApplication sharedApplication].statusBarFrame.size.height ;
frame.origin.y = statusHeight ;
frame.size.height -= statusHeight ;
self.view.frame = frame ; // self.view is view "B"

// Put the snapshot as thet topmost view of our view
UIImageView *imageView = [[UIImageView alloc] initWithImage:image] ; // image is a snapshot of view "A"
imageView.frame = self.view.bounds ;
[self.view addSubview:imageView] ;
[self.view bringSubviewToFront:imageView] ;

// Pre-transform our view (s=target/current, d=target-current)
CGAffineTransform transform = CGAffineTransformIdentity ;

// Translate our view
CGPoint center  = CGPointMake(screenOrigin.x + (image.size.width/2.0), screenOrigin.y + (image.size.height/2.0)) ;
float dX = center.x - self.view.center.x ;
float dY = center.y - self.view.center.y ;
NSLog( @"dx: %f, dy: %f" , dX, dY ) ;

transform = CGAffineTransformTranslate(transform, dX, dY) ;

// Scale our view
float scaleWFactor = image.size.width / self.view.frame.size.width ;
float scaleHFactor = image.size.height / self.view.frame.size.height ;
transform = CGAffineTransformScale(transform,scaleWFactor, scaleHFactor) ;

self.view.transform = transform ;

[[[UIApplication easybookDelegate] rootViewController].view addSubview:self.view] ;

// Perform the animation later since implicit animations don't seem to work due to
// view "B" just being added above and hasn't had a chance to become visible. Right now
// this is just on a timer for debugging purposes. It'll probably be moved elsewhere, probably
// to view "B"'s -didMoveToSuperview
double delayInSeconds = 0.3;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    [UIView transitionWithView:self.view duration:3 options:UIViewAnimationOptionTransitionFlipFromRight| UIViewAnimationOptionCurveEaseOut animations:^(void)
        {
        [imageView removeFromSuperview] ;
        self.view.transform = CGAffineTransformIdentity ;
        }
        completion:^(BOOL finished){
                [self.view removeFromSuperview] ;
                [navController presentModalViewController:self animated:NO] ;
        }] ;
});

[imageView release];

A: I've done this before. Here's the gist of how I did it:

*

*View A is on screen

*Create View B, give it a frame that makes it fullscreen, but don't add it to the screen yet

*View B has a UIImageView as it's topmost view

*Capture a UIImage of View A, and set it as the image of View B's image view
UIGraphicsBeginImageContext(view.bounds.size);
[viewA.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
viewB.imageView.image = image;

*Set View B's transform (scale and translation) so that it is shrunk to the size of View A and is positioned where View A is on the screen

*Add View B to the screen

*At this point, the user hasn't noticed anything change, because View B looks exactly like View A

*Now start an animation block, in which you

*

*Set [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView:ViewB

*set View B's transform to CGAffineTransformIdentity

*remove View B's imageview from View B

The result is an animation that looks like View A is flipping over and zooming to fill the screen with View B as the opposite side.

A: Checkout this svn repository:
http://boondoggle.atomicwang.org/lemurflip/

This does flip two views.

A: This is an easy example that i made for you :-) Start with it... Try to understand it... Read Documentation and then you will be able to do what you want ;-)
- (void)moveTable:(UITableView *)table toPoint:(CGPoint)point excursion:(CGFloat)excursion {

[UIView beginAnimations:nil context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.5];
[table setCenter:point];

// scaling
CABasicAnimation *scalingAnimation = (CABasicAnimation *)[table.layer animationForKey:@"scaling"];
if (!scalingAnimation)
{
    scalingAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
    scalingAnimation.duration=0.5/2.0f;
    scalingAnimation.autoreverses=YES;
    scalingAnimation.removedOnCompletion = YES;
    scalingAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    scalingAnimation.fromValue=[NSValue valueWithCATransform3D:CATransform3DMakeTranslation(0.0, 0.0, 0.0)];
    scalingAnimation.toValue=[NSValue valueWithCATransform3D:CATransform3DMakeTranslation(excursion, 0.0, 0.0)];
}
[table.layer addAnimation:scalingAnimation forKey:@"scaling"];
[UIView commitAnimations];

}

A: Try something like this.  As long as A's frame isn't fullscreen to start with then the animation should just flip A.  When you add a subview to a view in a flip transition then it is added to the back of that view, so view A's frame is the one you want to modify.
[UIView beginAnimations:@"flipopen" context:nil];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self cache:TRUE];
[a addSubview:b];
a.frame = b.frame;
[UIView commitAnimations];

A: I'm assuming you just want to change the image view's image while you flip and scale it.
Following code flips the image view using default animation, scales it to the other view's frame and sets the image:
[UIView beginAnimations:nil context:nil];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.imageViewA cache:NO];
[UIView setAnimationDuration:2];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationFinished:)];
self.imageViewA.frame = self.imageViewB.frame;
self.imageViewA.image = self.imageViewB.image;
[UIView commitAnimations];

if you wish to show the A view as your tiny floating view again with some other image you can just set it's frame and image without the animation block in AnimationDidStopSelector method which you can set
-(void)animationFinished:(id)context
{
    self.imageViewA.frame = tinyRect;
    self.imageViewA.image = [UIImage imageNamed:@"a.jpg"];
}

where tinyRect is the floating A view's original frame.

A: It's a little rough around the edges, but here's what I did using block animations. The following flips the view, centers it and goes fullscreen:
// the view on the other side of the card
UIView* redView = [[UIView alloc]initWithFrame:CGRectMake(0.0, 0.0, viewToFlip.frame.size.width, viewToFlip.frame.size.height)];
redView.backgroundColor = [UIColor redColor];

// add a green square to the red view so we have something else to look at
UIView* greenSquare = [[UIView alloc]initWithFrame:CGRectMake(10.0, 10.0, 20.0, 20.0)];
greenSquare.backgroundColor = [UIColor greenColor];
[redView addSubview:greenSquare];

// the flip animation
[UIView animateWithDuration:0.25
                      delay:0.0
                    options:UIViewAnimationCurveLinear
                 animations:^{

                     // rotate 90 degrees
                     [viewToFlip.layer setTransform: CATransform3DRotate(viewToFlip.layer.transform, -M_PI/2, 0.0, 1.0, 0.0)];

                 }
                 completion:^(BOOL finished){

                     // now that we're 90 degrees, swap one view for the other
                     // but if we add it now, the view will be backwards, so flip the original view back
                     [viewToFlip.layer setTransform: CATransform3DRotate(viewToFlip.layer.transform, M_PI, 0.0, 1.0, 0.0)];
                     [viewToFlip addSubview:redView];

                     // now let's continue our rotation
                     [UIView animateWithDuration:0.25
                                           delay:0.0
                                         options:UIViewAnimationCurveLinear
                                      animations:^{

                                          // rotate the last 90 degrees
                                          [viewToFlip.layer setTransform: CATransform3DRotate(viewToFlip.layer.transform, -M_PI/2, 0.0, 1.0, 0.0)];

                                      }
                                      completion:^(BOOL finished){

                                          [UIView animateWithDuration:0.25
                                                                delay:0.0
                                                              options:UIViewAnimationCurveLinear
                                                           animations:^{

                                                               // animate the views to the center of the screen and adjust their bounds to fill up the screen
                                                               [viewToFlip setCenter:CGPointMake(self.view.center.x, self.view.center.y)];
                                                               [viewToFlip setBounds:CGRectMake(0.0, 0.0, self.view.frame.size.width, self.view.frame.size.height)];
                                                               [redView setCenter:CGPointMake(self.view.center.x, self.view.center.y)];
                                                               [redView setBounds:CGRectMake(0.0, 0.0, self.view.frame.size.width, self.view.frame.size.height)];
                                                           }
                                                           completion:nil];

                                      }];

                 }];


text:
Q: How to display dropdown list below option in twitter bootstrap I wanted to show the dropdown list below the dropdown title. For example. The list will display just below of the title.
Currently the list is left justified/ always displaying from left. Here is the code snippet.

                        Engineering

Glyphicons

Available glyphs

How to use

Examples

Button groups

Basic example

Button toolbar

Sizing


text:
Q: Cambiar un campo de la clase padre en los modelos de Django Tengo una clase padre donde tengo un atributo que deseo modificar según la clase hijo:
class Service(models.Model):
   # otros atributos
   SERVICE_TYPE = {
       'None': 'Unknown service type',
       'visa': 'Visa',
   }
   service_type = None

   def get_service_type(self):
       if self.service_type:
           return self.service_type
       else:
           return self.SERVICE_TYPE['None']

Y tengo varias clases que heredan de esta, una de ellas es la siguiente:
class Visa(Service):
    # atributos de esta clase

El problema es que cuando creo un objeto de tipo Visa el atributo service_type de la clase padre Service nunca se modifica (siempre es None). He tratado de modificar el método save de Model y tambien modificarlo directamente en la vista para crear y no funciona.
modificando el método save:
class Visa(Service):
    # atributes
    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
    self.service_type = 'visa'
    return super(Visa, self).save(force_insert, force_update, using, update_fields)

modificando el atributo en la vista:
class ServiceCreateView(generic.CreateView):
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.service_type = 'visa'
        return super(ServiceCreateView, self).form_valid(form)

A: Leyendo la documentación de Django sobre Herencia de modelos encontré una forma de poder acceder al valor de la clase padre. Así es como quedarían los modelos:
models.py
class Service(models.Model):
    # otros atributos
    SERVICE_TYPE = {
        'None': 'Tipo de servicio desconocido',
        'visa': 'Visado',
        'passport': 'Pasaporte',
    }
    service_type = None

    def get_service_type(self):
        if self.service_type:
            return self.SERVICE_TYPE[self.service_type]
        else:
            return self.SERVICE_TYPE['None']

class Visa(Service):
    # atributos de la clase Visa
    service_type = 'visa'

class Passport(Service):
    # atributos de la clase Passport
    service_type = 'passport'

Entonces en la plantilla quedaría así:
templates/index.html
{% if service.visa %}
    {{ service.visa.get_service_type }}
{% elif service.passport %}
    {{ service.passport.get_service_type }}
{% else %}
    {{ service.get_service_type }}
{% endif %}

Mostrando Visado si el objeto es de la clase Visa o muestra Pasaporte si es una instancia de la clase Passport. Si no pertenece a ninguna de estas clases, entonces muestra Tipo de servicio desconocido.


text:
Q: Iterating through a gzipped object in Python with strings, not bytes Depending on the extension of files, I use a different opener with context manager like so:
if args.vcf_in.endswith(".gz"):
    dopenf = gzip.open
    mode = "rb"
else:
    openf = open
    mode = "rt"

Unfortunately, when I try to iterate through the object in one case it is bytes and in another string, and the code fails:
with openf(args.vcf_in, mode) as fin:
    for line in fin:
        count += 1
        print(line)
        if line.startswith("#"):

Is there way to iterate through a gzipped file so that the outputted lines are strings? I know I can check if they are bytes and decode them but I am curious is there a better way using the opener, or io package.
Thanks!

A: Perhaps I've misunderstood something here but if your gzipped file is a text file, you should be able to simply call gzip.open() with mode='r' (not 'rb') in place of the standard open(). There is no need for all the io classes.


text:
Q: Expected BEGIN_ARRAY but was BEGIN_OBJECT after retrofit call I know this was asked a lot before but i cannot find a solution in my case.
I am requesting for a json response about a list of POJO (Movie)
While this is my first time using retrofit i have the problem in the title. The url i am building is right and below is a sample of the response:
{
   "page":1,
   "total_results":19850,
   "total_pages":993,
   "results":[
      {
         "vote_count":855,
         "id":420817,
         "video":false,
         "vote_average":7.2,
         "title":"Aladdin",
         "popularity":445.349,
         "poster_path":"\/3iYQTLGoy7QnjcUYRJy4YrAgGvp.jpg",
         "original_language":"en",
         "original_title":"Aladdin",
         "genre_ids":[
            12,
            14,
            10749,
            35,
            10751
         ],
         "backdrop_path":"\/v4yVTbbl8dE1UP2dWu5CLyaXOku.jpg",
         "adult":false,
         "overview":"A kindhearted street urchin named Aladdin embarks on a magical adventure after finding a lamp that releases a wisecracking genie while a power-hungry Grand Vizier vies for the same lamp that has the power to make their deepest wishes come true.",
         "release_date":"2019-05-22"
      },
      {
         "vote_count":5224,
         "id":299537,
         "video":false,
         "vote_average":7.1,
         "title":"Captain Marvel",
         "popularity":399.859,
         "poster_path":"\/AtsgWhDnHTq68L0lLsUrCnM7TjG.jpg",
         "original_language":"en",
         "original_title":"Captain Marvel",
         "genre_ids":[
            28,
            12,
            878
         ],
         "backdrop_path":"\/w2PMyoyLU22YvrGK3smVM9fW1jj.jpg",
         "adult":false,
         "overview":"The story follows Carol Danvers as she becomes one of the universe's most powerful heroes when Earth is caught in the middle of a galactic war between two alien races. Set in the 1990s, Captain Marvel is an all-new adventure from a previously unseen period in the history of the Marvel Cinematic Universe.",
         "release_date":"2019-03-06"
      },

This is my model
public class Movie implements Parcelable {

@PrimaryKey(autoGenerate = true)
private int id;
private String title;
private String releaseDate;
private String moviePoster;
private String avgVote;
private String plot;
private String movieId;
private String movieGenre;

@Ignore
public Movie(String title, String releaseDate, String moviePoster, String avgVote, String plot, String movieId, String movieGenre) {

    this.title = title;
    this.releaseDate = releaseDate;
    this.moviePoster = moviePoster;
    this.avgVote = avgVote;
    this.plot = plot;
    this.movieId = movieId;
    this.movieGenre = movieGenre;
}

public Movie(int id, String title, String releaseDate, String moviePoster, String avgVote, String plot, String movieId, String movieGenre) {

    this.id = id;
    this.title = title;
    this.releaseDate = releaseDate;
    this.moviePoster = moviePoster;
    this.avgVote = avgVote;
    this.plot = plot;
    this.movieId = movieId;
    this.movieGenre = movieGenre;

}

public String getMovieGenre() {
    return movieGenre;
}

public void setMovieGenre(String movieGenre) {
    this.movieGenre = movieGenre;
}

public int getId() {
    return id;
}

public void setId(int mID) {
    this.id = mID;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getReleaseDate() {
    return releaseDate;
}

public void setReleaseDate(String releaseDate) {
    this.releaseDate = releaseDate;
}

public String getMoviePoster() {
    return moviePoster;
}

public void setMoviePoster(String moviePoster) {
    this.moviePoster = moviePoster;
}

public String getAvgVote() {
    return avgVote;
}

public void setAvgVote(String avgVote) {
    this.avgVote = avgVote;
}

public String getPlot() {
    return plot;
}

public void setPlot(String plot) {
    this.plot = plot;
}

public String getMovieId() {
    return movieId;
}

public void setMovieId(String movieId) {
    this.movieId = movieId;
}

protected Movie(Parcel in) {
    title = in.readString();
    releaseDate = in.readString();
    moviePoster = in.readString();
    avgVote = in.readString();
    plot = in.readString();
    movieId = in.readString();
    movieGenre = in.readString();
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(title);
    dest.writeString(releaseDate);
    dest.writeString(moviePoster);
    dest.writeString(avgVote);
    dest.writeString(plot);
    dest.writeString(movieId);
    dest.writeString(movieGenre);
}

@SuppressWarnings("unused")
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
    @Override
    public Movie createFromParcel(Parcel in) {
        return new Movie(in);
    }

    @Override
    public Movie[] newArray(int size) {
        return new Movie[size];
    }
};

}
My @GET
public interface JsonPlaceHolderApi {

    @GET("popular")
    Call<List<Movie>> getMovies(@Query("api_key") String api_key);
}

my data request class
private static final String LOG_TAG = DataRequest.class.getSimpleName();

    ArrayList<Movie> mMovies = null;
    String jsonResponse = "";

    private DataInterface mListener;

    public DataRequest() {
        super();
    }

    public void  getData(String url)  {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.BASE_MOVIE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
        Call<List<Movie>> call = jsonPlaceHolderApi.getMovies(Constants.API_KEY);

        call.enqueue(new Callback<List<Movie>>() {
            @Override
            public void onResponse(Call<List<Movie>> call, Response<List<Movie>> response) {

               if(response!=null && response.body()!=null && mListener!=null){

                   mListener.responseData(response.body());
               }
            }
            @Override
            public void onFailure(Call<List<Movie>> call, Throwable t) {
                Log.d(LOG_TAG, "response code throwable " + t);
            }
        });
    }

    public void setOnDataListener(DataInterface listener) {
        mListener = listener;
    }

    public interface DataInterface {
        void responseData( List<Movie> myResponse );
    }
}

And finally what im trying to do in my mainactivity
prefSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                userOption = prefSpinner.getSelectedItem().toString();
                Log.d(LOG_TAG, "user option is "+ userOption);
                if (userOption.contentEquals("Most Popular") || userOption.contentEquals("Highest Rated")) {

                    DataRequest dataRequest = new DataRequest();
                    dataRequest.setOnDataListener(new DataRequest.DataInterface() {
                        @Override
                        public void responseData(List<Movie> myResponse) {
                            mMoviesList = myResponse;
                        }
                    });
                            dataRequest.getData(userOption);
                    movieRecycleViewAdapter.swapData(mMoviesList);

                } else if(userOption.contentEquals("Favorites")) {
                    setUpViewModel();
                    movieRecycleViewAdapter.notifyDataSetChanged();
                }
            }

A:
I am requesting for a json response about a list of POJO (Movie)

No, you are not. If you look at your JSON output, it is a JSON object, not a JSON array. It contains a JSON array in its results property.
You need to:

*

*Create a Java class that matches the JSON object structure (which will include a List<Movie> results field)

*Change Retrofit to return Call<...> where ... is whatever you call the Java class that you created in the preceding bullet


text:
Q: How can I call a function in a class that has the setState function from another stateful widget? I have a Stateful widget that uses the setState method in one of its class methods. I want to convert that widget into an ordinary class so I can use it in Object Oriented Programming. I want to instantiate an instance of that class in another stateful widget and access the methods that have the setState method in them. But I am currently getting this error "The method 'setState' isn't defined for the type 'MyClass'. Try correcting the name to the name of an existing method, or defining a method named 'setState'."
How can I do this?

A: The setState method is linked to the state of a stateful Widget. If you want to convert your widget to a Class you can't use setState in it. But you can give the Class a Function as parameter. Anytime you instantiate this Class in a stateful Widget just give the setState from this stateful Widget to the class.

A: I think you need to add a better state management solution to your code than stateful widget ,maybe riverpod,
Using riverpod you can access the same notifier from other widgets and thus the setState functionality plus it has the added benefit of splitting the logic and ui into an mvvm like pattern

A: setState only exists for the StatefulWidget. You cannot call setState in the class without extending a StatefulWidget. So if you want to do that you can use a state management plugin in the Flutter like Provider, Bloc or Getx.


text:
Q: Convert categorical variable into binary columns in R I made the stupid mistake of enabling people to select multiple categories in a survey question.
Now the data column for this question looks something along the lines of this.

respondent
answer_openq

1
a

2
a,c

3
b

4
a,d

using the following line in r,
datanum <- data %>% mutate(dummy=1) %>%
spread(key=answer_openq,value=dummy, fill=0)

I get the following:

However, I want the dataset to transform into this:

respondent
a
b
c
d

1
1
0
0
0

2
1
0
1
0

3
0
1
0
0

4
1
0
0
1

Any help is appreciated (my thesis depends on it). Thanks :)

A: Try this:
library(dplyr)
library(tidyr)
df %>%
  separate_rows(answer_openq, sep = ',') %>%
  pivot_wider(names_from = answer_openq, values_from = answer_openq,
              values_fn = function(x) 1, values_fill = 0)
# A tibble: 4 × 5
  respondent     a     c     b     d
       <int> <dbl> <dbl> <dbl> <dbl>
1          1     1     0     0     0
2          2     1     1     0     0
3          3     0     0     1     0
4          4     1     0     0     1


text:
Q: How to get xml element values to a string using Xdocument I am storing a xml in a string and using Xdocument i am parsing the string to xml from that i need to get xml element values and using that values i need to insert it in db. Any help would be appreciated.
XML:
<ListInventorySupplyResponse xmlns="http://mws.amazonaws.com/FulfillmentInventory/2010-10-01/">
- <ListInventorySupplyResult>
- <InventorySupplyList>
- <member>
  <SellerSKU>043859634910</SellerSKU>
  <FNSKU>X000IA4045</FNSKU>
  <ASIN>B005YV4DJO</ASIN>
  <Condition>NewItem</Condition>
  <TotalSupplyQuantity>10</TotalSupplyQuantity>
  <InStockSupplyQuantity>10</InStockSupplyQuantity>
- <EarliestAvailability>
  <TimepointType>Immediately</TimepointType>
  </EarliestAvailability>
  <SupplyDetail />
  </member>
  </InventorySupplyList>
  </ListInventorySupplyResult>
- <ResponseMetadata>
  <RequestId>d50af29d-f203-4efc-a864-1725a59ded97</RequestId>
  </ResponseMetadata>
  </ListInventorySupplyResponse>

Code:
XDocument xd = XDocument.Parse(a);
string Sku = xd.Element();
var ASIN = xd.Descendants("ASIN");
var Condition = xd.Descendants("Condition");
var TotalSupplyQuantity = xd.Descendants("TotalSupplyQuantity");

A: You should use the xml namespace http://mws.amazonaws.com/FulfillmentInventory/2010-10-01/
var xDoc = XDocument.Parse(xml);
XNamespace ns = "http://mws.amazonaws.com/FulfillmentInventory/2010-10-01/";

var condition = (string)xDoc.Descendants(ns + "Condition").First();

OR
you can search for Tag Condition in any xml namespace
var condition2 = (string)xDoc.Descendants()
                             .First(d => d.Name.LocalName == "Condition");

OR
you can use XPath to get Condition in any xml namespace
var condition3 = (string)xDoc.XPathSelectElement("//*[local-name()='Condition']");

A: Use this:
string value = xd.Root.Element("SellerSKU").Value;


text:
Q: Is the solution of the initial value problem global? If we have an initial value problem where the right hand side is continuous and bounded, is the solution of it global? if yes, does it have to be unique?
I am a beginner in ODE and I really cannot answer this question so some help would be much appreciated. I know about local solutions but I am not good with answering questions regarding global ones.


text:
Q: How would I prevent duplicates in array of objects? And if there is a object with same property, it should sume its value So basically what I am trying to achieve is.. I have an array with objects, in my case array of items in stock. And when I add item to cart array, it should check if an object with the same property (name) already exists. And if it exists, it should just sum the count of them. So that I don't have duplicates... But it sums the count.
const stock = [
  {
    id: 0,
    name: 'Leaf Blower',
    price: 250,
    stock: 24,
    count: 0,
    logoURL: process.env.PUBLIC_URL + '/images/1.png',
  },
  {
    id: 1,
    name: 'Generator',
    price: 1299,
    stock: 12,
    count: 0,
    logoURL: process.env.PUBLIC_URL + '/images/2.png',
  },
  {
    id: 2,
    name: 'Log Splitter',
    price: 2133,
    stock: 5,
    count: 0,
    logoURL: process.env.PUBLIC_URL + '/images/3.png',
  },
  {
    id: 3,
    name: 'Lawn Mower',
    price: 250,
    stock: 24,
    count: 0,
    logoURL: process.env.PUBLIC_URL + '/images/4.png',
  },
  {
    id: 4,
    name: 'Chainsaw',
    price: 344,
    stock: 16,
    count: 0,
    logoURL: process.env.PUBLIC_URL + '/images/5.png',
  },
];

This:
const shoppingCart = [
  {
    id: 0,
    name: 'Leaf Blower',
    price: 250,
    stock: 24,
    count: 5,
    logoURL: process.env.PUBLIC_URL + '/images/1.png',
  },
    id: 0,
    name: 'Leaf Blower',
    price: 250,
    stock: 24,
    count: 3,
    logoURL: process.env.PUBLIC_URL + '/images/1.png',
}
]

Should be:
const shoppingCart = [
  {
    id: 0,
    name: 'Leaf Blower',
    price: 250,
    stock: 24,
    count: 8,
    logoURL: process.env.PUBLIC_URL + '/images/1.png',
  }

]

A: You can check if the objectToBeAdded is already there in the shoppingCart. And then update shoppingCart accordingly.
const indexOfObject = shoppingCart.findIndex(item => item.name === objectToBeAdded.name);
if(indexOfObject > -1) {
   shoppingCart[indexOfObject].count += objectToBeAdded.count;
} else {
   shoppingCart = [...shoppingCart, objectToBeAdded];
}

A: You can do this by using array reduce method. Just traverse the array and sum the count property.

const shoppingCart = [
  {
    id: 0,
    name: 'Leaf Blower',
    price: 250,
    stock: 24,
    count: 5,
    logoURL: `process.env.PUBLIC_URL + '/images/1.png`,
  },
  {
    id: 0,
    name: 'Leaf Blower',
    price: 250,
    stock: 24,
    count: 3,
    logoURL: `process.env.PUBLIC_URL + '/images/1.png`,
  },
];

let ret = shoppingCart.reduce((prev, c) => {
  const p = prev;
  if (!p[c.id]) p[c.id] = { ...c };
  else p[c.id] = { ...c, count: c.count + p[c.id].count };
  return p;
}, {});
ret = Object.values(ret);
console.log(ret);

A: Something like this should work:
    if (!shoppingCart.find(element => element.name == objectToBeAdded.name)) {shoppingCart.push(objectToBeAdded)}

Here, you use Array.find() to check if there is an object with a matching name in the array. If not, you add the object to array.


text:
Q: Calculate $\sum_{k=0}^n k \binom{n}{k} p^k (1-p)^{n-k}$ For $p \in [0,1]$ calculate
$$S =\sum_{k=0}^n k \binom{n}{k} p^k (1-p)^{n-k}.$$

Since
$$ (1-p)^{n-k} = \sum_{j=0}^{n-k} \binom{n-k}{j} (-p)^j, $$
then
$$ S =\sum_{k=0}^n \sum_{j=0}^{n-k} k \dfrac{n!}{k!j!(n-k-j)!} p^k (-p)^j. $$
If it weren't for that $k$, I would have
$$ S = (1+p-p)^n = 1\ldots $$

A: We have the binomial expansion
$$
(p+q)^n=\sum_{k=0}^n\binom{n}{k}p^kq^{n-k}.
$$
Differentiating with respect to $p$ we get
$$
n(p+q)^{n-1}=\sum_{k=0}^nk\binom{n}{k}p^{k-1}q^{n-k}
$$
and hence
$$
np(p+q)^{n-1}=\sum_{k=0}^nk\binom{n}{k}p^{k}q^{n-k}.
$$
Setting $q=1-p$ above we finally obtain
$$
np=\sum_{k=0}^nk\binom{n}{k}p^{k}(1-p)^{n-k}.
$$

A: Use the identity $k\binom{n}{k}=n\binom{n-1}{k-1}$ and the binomial identity to get
$$
\begin{align}
\sum_{k=0}^nk\binom{n}{k}p^k(1-p)^{n-k}
&=\sum_{k=1}^nn\binom{n-1}{k-1}p\,p^{k-1}(1-p)^{n-k}\\
&=np\sum_{k=1}^n\binom{n-1}{k-1}p^{k-1}(1-p)^{n-k}\\
&=np\,(p+(1-p))^{n-1}\\[12pt]
&=np
\end{align}
$$

A: An answer from the point of view of probability theory rather than logic is as follows.
Let $X_1,\ldots,X_n$ be independent random variables, each equal to $1$ with probability $p$ and to $0$ with probability $1-p$.
The probability that exactly $k$ of them are equal to $1$ is $\dbinom n k p^k (1-p)^{n-k}$.  The expected number of them that are equal to $1$ is therefore $\displaystyle\sum_{k=0}^n k\binom n k p^k (1-p)^{n-k}$.
But the expected value is
$$
\mathbb E(X_1+\cdots+X_n) = \mathbb E(X_1)+\cdots+\mathbb E(X_n) = p + \cdots + p = np.
$$


text:
Q: Check if part of json value of a certain key is the same as given input (javascript) I have a very big Json file (dataset is bigger then 30 000) . I need to check if a part of the value of a certain key is the same as a given string and then increment an int.
This is part of the Json:
[
    {
        "geo": null,
        "coordinates": null,
        "in_reply_to_status_id_str": null,
        "contributors": null,
        "in_reply_to_user_id": null,
        "in_reply_to_status_id": null,
        "truncated": false,
        "created_at": "Tue Nov 13 20:17:17 +0000 2012"

I want to check if the key "created_at" has a certain day(value). Like for example 'Tue'
and then increment : var tuesday = 0;
only thing i could come up with is this function:
function getValues(obj, key) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getValues(obj[i], key));
        } else if (i == key) {
            objects.push(obj[i]);
        }
    }
    return objects;
}

But it only checks the key and puts the value in an array. That is not what i want.

A: It is not immediately clear from your question what the structure of the data is, but it looks to be an array of objects where the created_at property will be populated with a Date. If you need it to be recursive (which the code you provided suggests) the following code would need modification. But going off the description:

I want to check if the key "created_at" has a certain day(value). Like
  for example 'Tue' and then increment : var tuesday = 0;

Then the following will take the array as data and result in the variable value containing an object with a map of days and the number of items where the created_at property begins with each of the 7 day of week strings.
var valMap = {
  Sun: 'sunday',
  Mon: 'monday',
  Tue: 'tuesday',
  Wed: 'wednesday',
  Thu: 'thursday',
  Fri: 'friday',
  Sat: 'saturday'
}

var value = data.reduce(function(m, i, x){
  for (d in valMap){
    if (i.created_at.indexOf(d) === 0){
      m[valMap[d]]++;
      return m;
    }
  }
  return m;
}, {
  sunday: 0,
  monday: 0,
  tuesday: 0,
  wednesday: 0,
  thursday: 0,
  friday: 0,
  saturday: 0
});

result would resemble:
{
  sunday: 0,
  monday: 1,
  tuesday: 3,
  wednesday: 0,
  thursday: 1,
  friday: 0,
  saturday: 6
}

A: If you are wanting to see if the key is present in the object's field name, use indexOf
 function getValues(obj, key) {
        var objects = [];
        for (var i in obj) {
            if (!obj.hasOwnProperty(i)) continue;
            if (typeof obj[i] == 'object') {
                objects = objects.concat(getValues(obj[i], key));
            } else if (s.indexOf(key) !== -1) {
                objects.push(obj[i]);
            }
        }
        return objects;
    }


text:
Q: NodeJs Server: Run two different exported app.js within one http.createServer() How can I run two app.js within hhtps.createServer() on given condition?
Or you can say two completely different node website within one http.createServer().
Below code is running only html files with on some modification.
Such as folder name with correspond to website folder. For https you can create your certificate, otherwise use http.createServer instead https.createServer.
enter code hereconst path = require("path");
const fs = require('fs');
const http = require('http');
const https = require('https');
const { Server } = require("socket.io");
const static = require('node-static');

const app1 = require('./folder1/app');
const app2 = require('./folder2/app');

let folder1 = new (static.Server)('./folder1');
let folder2 = new (static.Server)('./folder2');

//Some certificate
const options = {
  key: fs.readFileSync(path.join(__dirname, './Cert') + '/folder1.com.key', 'utf8'),
  cert: fs.readFileSync(path.join(__dirname, './Cert') + '/folder_com.crt', 'utf8')
};

let server = https.createServer(options,(req, res) => {
  req.addListener('end', () => {
    try {
      let hostName = req.headers.host.split(':')[0];
      console.log(hostName);
      switch(hostName){
        case 'folder1.com':
          folder1.serve(req, res);
          break;
        case 'folder2.com':
          folder2.serve(req, res)
          break;
        default:
          folder2.serve(req, res)
      }
    }
    catch{
      console.log(e);
    }
  }).resume();
})

const io = new Server(server, {log: false});
let port = process.env.PORT || 443;
server.listen(port);
console.log('Server is listening on port: '+ port);

A: Are you trying to expose both an http and an https endpoint?
If so, my suggestion would be to only expose https and handle incoming http requests in your webserver such as nginx and have them redirect to https automatically.


text:
Q: Can't make the datatable show up. Laravel 5.5 Using yajra/laravel-datatables and I'm having trouble, it's a bit confusing. I can't make the datatable work. I always get this error:

DataTables warning: table id=datatable - Ajax error. For more information about this error, please see http://datatables.net/tn/7

Here's my code:
pr-items.blade.php
@extends('layouts.app')
@section('content')

Add Items

                    <form class="form-inline" action="#">

                        PR Form Number:
                        <input type="text" class="form-control" value="{{$pr_details->pr_form_no}}" readonly required>

                                    ITEM NO.
                                    QTY
                                    UNIT
                                    DESCRIPTION
                                    COST PER UNIT
                                    COST PER ITEM
                                    ACTION

                                    <input class='form-control input-sm'style='width:100%;' type="text" name="" value="1" readonly required>
                                    <input class='form-control input-sm' style='width:100%;' type="text" name="">
                                    <input class='form-control input-sm' style='width:100%;' type="text" name="">
                                    <input class='form-control input-sm' style='width:100%;' type="text" name="">
                                    <input class='form-control input-sm' style='width:100%;' type="text" name="">
                                    <input class='form-control input-sm' style='width:100%;' type="text" name="">
                                    <button class="btn btn-info btn-sm"></button>

                                    GRAND TOTAL:

                                            <input type='text' class='form-control input-sm' id='grand_total' name='grand_total' value='0' readonly required>

                    </form>

@endsection

@section('script')

@endsection

PurchaseRequestItemController.php
public function index($id)
    {
        //
        $pr_details = PurchaseRequestModel::find($id);
        return view('pr-items',compact('pr_details'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    public function getItems()
    {
        $pr_details = PurchaseRequestModel::all()->pr_form_no;
        $item_query = PurchaseRequestItemModel::query()->where('pr_form_no','=',$pr_details);
        return \DataTables::of($item_query)
        ->addColumn('action', function ($pr) {
            return 'EditDelete';
        })->make(true);
    }

I was here trying to make a table which adds items upon pressing the add button. Sorry if my code is confusing. Thanks


text:
Q: $det(I+A(\epsilon))$ where $A$ is an infinite matrix and not trace class! Assume that $A$ is an infinite matrix and it's a function of the parameter $\epsilon$. I would like to find $\epsilon$ so that the $det(I+A(\epsilon))=0$.
I know if $A$ was a trace class I could use the Fredholm identity, i.e.
\begin{equation}
det(I+A)=\prod_{n\geq 1} (1+\lambda_{n})
\end{equation}
where $\lambda_{n}$'s are eigenvalues of $A$.
In my case however, $A$ is not a trace class but it is symmetric and I know it's eigenvalues $\lambda_{n}(\epsilon)$. I was wondering if there is an identity similar to this that I can use. Also, how good of an approximation this would be if I truncate the product for a large $n$?


text:
Q: Selecting description based on 3 int columns I have a table with the fields ID,department_code,sub_department_code,class_code,desc_text
The desc_text has the name of the department when the sub_department_code and class_code fields are null, the sub_department name when the department_code and sub_department_code are not null but class_code is null, and the name of the class when the class_code is not null.
My issue is I have another table that has the id from the table above, but I would like to select the fields with department_code,desc_text(of the department),sub_department_code,desc_text(of the sub_department), etc.
I tried a few methods, but I am unsure even how to search for this issue.
I have the following two tables:
Hierarchy
id,department_code,subdept_code,class_code
1    1               null          null
2     1               1           null
3     1               1            1
4      2              1           null
Hierarchy_detail
id,hierarchy_id,short_text
1      1           car
2      2            truck
The hierarchy.id is linked to hierarchy_detail.hierarchy_id
With this, I have a table that has data I want, which the fk from hierarchy.id, which I cna link and get the department, sub-sept and class codes, but I am having trouble getting the text on there for each type.

A: You want to use a case statement to capture the logic.  If Im' reading correctly, it looks something like this:
select id, department_code, sub_department_code, class_code,
       (case when sub_department_code is null and class_code is null
             then desc_text
        end) as department_name,
       (case when department_code is not null and sub_department_code is not null and class_code is null
             then desc_text
        end) as sub_department_name,
       (case when class_code is not null then desc_text
        end) as class_name
from t

You can then use this query as a subquery to join to other tables.


text:
Q: How can I get scala's blocking to work with tailrec? I'm writing scala <-> java interop wrappers for Futures and I don't know the Right Way to implement scala.concurrent.Future.onComplete (http://www.scala-lang.org/api/current/index.html#scala.concurrent.Future).  This probably works:
def onComplete[U](func: Try[T] => U)(implicit executor: ExecutionContext): Unit = {
  executor.execute(new Runnable {
    @tailrec
    def run = value match {
      case Some(t) => func(t)
      case None => { Thread.sleep(100); run }
    }
  })
}

but Asynchronous IO in Scala with futures suggests that when I have to block I should pass the relevant part of the code to scala.concurrent.blocking to let the ExecutionContext know what's up. The problem is that when I surround the value match{...} with blocking {} it's no longer a tail call.
What's the proverbial right way to do this?
Edit: for completeness here is the entire wrapping class:
class JavaFutureWrapper[T](val jf: java.util.concurrent.Future[T]) extends scala.concurrent.Future[T] {
  def isCompleted = jf.isDone

  def result(atMost: Duration)(implicit permit: CanAwait): T =
    atMost match { case Duration(timeout, units) => jf.get(timeout, units) }

  def onComplete[U](func: Try[T] => U)(implicit executor: ExecutionContext): Unit = {
    executor.execute(new Runnable {
      @tailrec
      def run = value match {
        case Some(t) => func(t)
        case None => { Thread.sleep(100); run }
      }
    })
  }

  def ready(atMost: Duration)(implicit permit: CanAwait): this.type = atMost match {
    case Duration(timeout, units) => {
      jf.get(timeout, units)
      this
    }
  }

  def value: Option[Try[T]] = (jf.isCancelled, jf.isDone) match {
    case (true, _) => Some(Failure(new Exception("Execution was cancelled!")))
    case (_, true) => Some(Success(jf.get))
    case _ => None
  }
}

A: I would just wait for the Java future to complete:
import scala.util.{Try, Success, Failure}
import scala.concurrent._
import java.util.concurrent.TimeUnit

class JavaFutureWrapper[T](val jf: java.util.concurrent.Future[T])
  extends scala.concurrent.Future[T] {
  ...

  def onComplete[U](func: Try[T] => U)(implicit executor: ExecutionContext): Unit =
    executor.execute(new Runnable {
      def run: Unit = {
        val result = Try(blocking(jf.get(Long.MaxValue, TimeUnit.MILLISECONDS)))
        func(result)
      }
    })
  ...
}

A: Hmm, my edit to 0__ 's answer didn't get approved, so for the sake of future readers, here's the solution I'm going with (which is simplified from 0__'s)
def onComplete[U](func: Try[T] => U)(implicit executor: ExecutionContext): Unit = {
  executor.execute(new Runnable {
    def run = func(Try( blocking { jf.get } ))
  })
}


text:
Q: git p4 sync only labels I am migrating a repo from Perforce to Git. I have already migrated all branches of interest. Now I am looking for  migrating all perforce labels as git tags.
I am running below command

git-p4.py sync //depot/path/... --import-labels --verbose

This is not able to fetch all labels, saying it could not find git commit for changelist. If I run this with @all , its able to get the labels. Only concern is it will take more time.
Is there any option to import just labels, I am not keen for revisions. Thanks !


text:
Q: How to assign more than 1 partition to a kafka consumer I have created kafka consumer in c and created a topic with 10 partition, when i tried to read data using consumer it is only reading from 2 partitions and then says no more messages.
I tried using both the methods i.e subscribe and assign but none of them works.
How should i assign all 10 partition to a single consumer, Is this is the correct way of assigning partition to consumer?
I have build custom consumer using this repo https://github.com/edenhill/librdkafka/blob/master/examples/consumer.c
And modified line number 173 and 180 of above repo with below lines so that i can consume from all partition. But it is still not working.
for(int partition_number = 0 ; partition_number < 10 ; partition_number) {
    rd_kafka_topic_partition_list_add(sub_list,topic[i],partition_number);
}
rd_kafka_assign(consumer,sub_list);

A: Please try to run your example as it is without changing its logic, it using subscribe() with consumer group, your change to assign function instead of subscribe is breaking the logic... please update what happens after using the exact example, just change topic names.
With using subscribe() it ignore partitions and subscribe to the whole topic with consumer group and kafka control logic

Here is @edenhill assigner test, you might want to look in that code as well
https://github.com/edenhill/librdkafka/blob/master/tests/0051-assign_adds.c