text:
Q: ¿Cómo puedo enviar un ArrayList con MQTT usando Kotlin? Estoy trabajando con el protocolo de comunicación MQTT y para publicar un mensaje, sigo la siguiente estructura:
client.publish(topic : String, data : String, qos : Int)
Mi pregunta es si es posible mandar `data´ como un ArrayList en vez de un String. Y si es así, ¿cómo se podría hacer?
Adjunto mi parte de código donde declaro la función `publish´:
private fun publish(topic: String, data : String, qos: Int = 1) {
    try {
        val message = MqttMessage()
        message.payload = data.toByteArray(charset("UTF-8"))
        message.qos = qos
        val publishToken = client.publish(topic, message)
        publishToken.actionCallback = object : IMqttActionListener {
            override fun onSuccess(asyncActionToken: IMqttToken) {
                Log.d(TAG, "$data se ha publicado en $topic.")
            }

            override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable) {
                Log.d(TAG, "Fallo al publicar $data en $topic.")
            }
        }
    } catch (e: UnsupportedEncodingException) {
        e.printStackTrace()
    } catch (e: MqttException) {
        e.printStackTrace()
    }
}


text:
Q: C: "Invalid free(): Address 0x7feffee08 is on thread 1's stack" This is not my exact code, but it is like this in essence. I'm trying to create a stack variable in main()

int **x;

that I want to pass to a function foo(int **x, arg1, arg2, ...). On some condition, I'm supposed to dynamically allocate space for x in foo()

x = (int **) malloc(sizeof(int *) * num_elems);

I am also not allocating new space for each int * element, but assigning to it &y, where int y was created in foo().
I got this error when I tried freeing x in main(). I don't understand what it means, but I suspect it might be because I used &y?
EDIT: Also relevant: I got garbage values when I tried accessing the double-dereferenced elements of x.

A: You are not correctly declared in main function and not correctly defined in foo() function. You have to declare as
In main function
int *x ;
foo(&x);

In foo(int **x,....)
*x =  malloc(sizeof(int) * num_elems);

A: Consider this,
void foo()
{
    int y;
    int *x = NULL;
    x = &y;
}

In this case, y is stored in the stack. When foo returns, y will be unavailable (implementation dependant). If you absolutely need to do this, malloc y instead. If you do that, y will be stored on the heap instead.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which is the best option, SimpleXml or XML Parser in PHP? I have gone through the Stack Overflow post "Best XML Parser for PHP".
For the same question. It is mentioned that, if I need to manipulate XML files then go for DOM XML. My requirements are:

*

*I have saved navigation in database. It is an HTML string.

*I want to remove some pages or say li tags wrapping pages that user don't want to exist in his/her page. After removing the unwanted li's, I want to save the whole string back to the database.

*The same navigation will be used on another page. But, the HTML will be different. It will be similar, with the ul and li, but I need to add some more divs and spans to it.

*The navigation will be edited on this page and on each change (e.g. Changing page title, deleting a node/page, moving under another page as child.) a Ajax call will save the changes to another table in database.

*Using the new structure, again build the navigation, which will be updated in the first navigation table.
Which will be best option?

A: For your use case, using XMLParser does not make much sense since you want to save back the whole file after modifying it.
SimpleXML lets you do that much easier (saveXML() method) - with XMLReader you would have to generate the XML on your own during parsing.

A: I'd recommend SimpleXML.

A: My personal preference is XML Parser but I think that the library you choose probably will not affect the solution that much. The usages of any XML manipulation library is probably largely the same.

A: For larger files you will want to use XML Parser because Simple XML will load the entire XML into memory to parse it whereas XML parser is stream based.


text:
Q: Can you find the z component in this system? I will use uppercase letters to denote known variables and lowercase letters to denote unkown ones.
Assume I have a vector $<X', Y', z'>$, and an invertible matrix $T$, and a vector $<x,y,z>$ constrained to a known plane $P=(N,V)$ ($N$ being the normal and $V$ being a point in the plane).
We know that $<X', Y', z'> = T\times<x,y,z>$.
Is it possible to either find $z'$ or $<x,y,z>$ in this system?

A: From the fact that $r = (x,y,z)$ lies in the plane you get:
$$N^T(r-V)= 0$$
From the other equation you have:
$$q = Tr$$
Where $q = (X', Y', z')$. Note that $T$ is invertible so the equations are not linearly dependent. Then ultimately you get 4 equations for 4 unknowns.


text:
Q: Batch file with two lessc commands, only one executes I have a batch file with two lessc commands. The first one execute, the second does not.
lessc --clean-css app.less app.min.css
lessc app.less app.css

How can I make both to run.
Running the batch file on Windows 10 with node.js and less installed.

A: I just added & after each command to chain them and it worked.


text:
Q: How can I calculate the Average CPU usage of every process in C In need to calculate the total CPU occupy time of process and divide that by the current time minus the process start time.
So far I have the following code:
    #include <linux/time.h>

    cputime_t kernel_time = task_cputime->stime;  //total time running in kernel space
    cputime_t user_time =  task_cputime->utime;  //total time  running in user space
    cputime_t total_occupy = kernel_time + user_time;  //Total CPU occupy time

    //convert to ms
    unsigned long total_occupy_ms = mulhdu(total_occupy, __cputime_msec_factor);

How would I use do_gettimeofday to get current time and task_strcut->real_start_time in ms? It may be easy, but I am fairly new to kernel programming.

A: struct timeval tv;
unsigned long timeofday_in_ms = 0;
unsigned logn real_start_time_in_ms = 0;
do_gettimeofday(&tv);
timeofday = jiffies_to_ms(timeval_to_jiffies(&tv));
real_start_time = jiffies_to_ms(timespec_to_jiffies(&current->real_start_time));

All the function involving above are self-explanatory and can be used in kernel


text:
Q: Java pattern expression to exclude a special string All , Source content may like this :
String content1 = "url:(\"../../aaa/bbb/ccc\")";
String content2 = "url:('/bb/add/www')";
String content3 = "url:(ggg/eee/xxx)";
String content4 = "url:('../../aaa/bbb/ccc')";

Who can help me design a high performance Java pattern matcher regex as below:
regex = "^[.]*url\\:\\([\"\\'][(?:\\.\\.)?]([^\"\\)]+)[\"\\']\\)$";

public static String parsePath(String content,String regex) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(content);
    if (matcher.find()) {
        return  matcher.group(1);
    }
    return null;
}

I want input such as content1 to content 4 , call parsePath function will always return /aaa/bbb/ccc , /bb/add/www , ggg/eee/xxx, /aaa/bbb/ccc . That is I want to skip the prefix ("|'.. and postfix '|") and just want to snap the middle actual url path start with / .
So anyone who can help me to write a regex expression with high performance  ?

A: I'm not sure about a single regex solution, but you can achieve the same in a 2-fold approach :
public static String parsePath(String content, String regex) {
    content = content.replaceFirst("^url\\:\\([\"']?([.]{2})?(/[.]{2})*", "");
    // rest is same as previous
    // .......................
}

Then use the following in Matcher :
  regex = "(^([a-z]+)?(/?[a-z]+)*)(?=[\"']?\\)$)"

You may put the regex inside method itself, rather than passing it as a parameter. And  update the character class([a-z]) as per your need.
NOTE : The above solution won't match strings like "url:(\"../..../aaa/bbb/ccc\")" or "url:(\"..../../aaa/bbb/ccc\")"  or "url:(\"..///")" at all, which was not handled by the regex you show in the question and comment.

A: Finally , I try many times and get it worked by designing a pattern expression as below :
regex = "url\\([\"\\'][(?:\\.\\.)]*([^\"\\)]+)[\"\\']\\)";

Now it works.


text:
Q: Echo of array doesn't do paragraphs on the right places I know this isn't a very useful question for most people but I have dedicated a lot of time to solve a small problem and I didn't get the results that I wanted, so I need your help:
<?php
$lines = file('temphum.txt');
$result = array_reverse($lines);
for($i=0; $i<count($result);$i=$i+4){
 $cenas= $result[$i]."ºC";
 $contentsite= nl2br($cenas);
 echo $contentsite ;
}
?>

This code prints this:
25ºC24
ºC23
ºC22
ºC21
ºC

Instead of this:
25ºC
24ºC
23ºC
22ºC
21ºC

What is the problem?

A: You append the °C sign after the newline at the end of the string.
<?php
$lines = file('temphum.txt', FILE_IGNORE_NEW_LINES);
$result = array_reverse($lines);
for($i=0; $i<count($result);$i=$i+4){
    echo $result[$i]."ºC"."<br>";
}


text:
Q: By proposition 3.21 is ether acute, right or obtuse Let A, B, C be points on a line with A ∗ B ∗ C. Let D be a point not on that line such
that angle ABD is obtuse. Show that angle CBD is acute. Do NOT use the Measurement Theorem. (Hint: By Proposition 3.21, angle CBD is either acute, right, or obtuse. Consider the cases when it's right and obtuse separately, obtaining a contradiction with
the hypothesis that angle ABD is obtuse in each case.)
for axioms http://math.gcsu.edu/~ryan/4510/notes/congruence.pdf
proposition 3.21
a. Exactly one of the following conditions holds (trichotomy): ∠P < ∠Q, ∠P ∼= ∠Q, or ∠P > ∠Q.
b. If ∠P < ∠Q and ∠Q ∼= ∠R, then ∠P < ∠R.
c. If ∠P > ∠Q and ∠Q ∼= ∠R, then ∠P > ∠R.
d. If ∠P < ∠Q and ∠Q < ∠R, then ∠P < ∠R.
can someone help me put this in context

A: Hint: $∠ABC=180^o=∠ABD+∠CBD$
Since $∠ABD$ is obtuse, $∠ABD>90^o$
Case I: $∠CBD>90^o$
$∠ABC=∠ABD+∠CBD>90^o+90^o=180^o$
which is a contradictiona as $∠ABC$ is a straight line angle.
Case II: $∠CBD=90^o$
$∠ABC=∠ABD+∠CBD=∠ABD+90^o>90^o+90^o=180^o$
which is a contradictiona as $∠ABC$ is a straight line angle.
You could alse see that in the photo below


text:
Q: template argument '(type)0' does not match 'EnumValue' Given this C++11 code:
#include <type_traits>

enum Enum { EnumValue };

template <typename>
struct Pred { constexpr static bool const value = true; };

template <
        typename T,
        typename ::std::enable_if<
            Pred<T>::value,
            Enum
        >::type = EnumValue>
class Huh {};

template <typename T>
constexpr bool f(Huh<T> const &) noexcept { return true; }

static_assert(f(Huh<int>()), "");

I get the following error message from GCC 7.3.0:
test.cpp:19:27: error: no matching function for call to 'f(Huh<int>)'
 static_assert(f(Huh<int>()), "");
                           ^
test.cpp:17:16: note: candidate: template<class T> constexpr bool f(const Huh<T>&)
 constexpr bool f(Huh<T> const &) noexcept { return true; }
                ^
test.cpp:17:16: note:   template argument deduction/substitution failed:
test.cpp:19:27: note:   template argument '(type)0' does not match 'EnumValue'
 static_assert(f(Huh<int>()), "");
                           ^

If I use int and 0 instead of Enum and EnumValue, the error is gone. Why does this fail with an enum?

A:
Does anyone have any idea about how to work around this on broken versions of GCC while keeping the enum?

You can grit your teeth and tell the compiler what it fails to deduce:
static_assert(f<int>(Huh<int>()), "");

Success
If the unsightliness would be widespread maybe you can localize it in some conditionally compiled wrapping.


text:
Q: Removing trailing zero after decimal point in python import math
math.floor(85.21)

returns 85.0
I want to save the number as a file name and I don't want to see the zero! I would like the output to be 85

A: Then you should consider casting to int which does the same thing but without the trailing .0 instead of math.floor:
>>> int(85.21)
85

I want to save the number as a file name

Since OP will not be working with negative numbers, they could keep this, or use int(math.floor(...)) that works also for negative numbers.

A: import math
result=int(math.floor(85.21))
print(result)


text:
Q: Plotting a datetime serie, counting the values for another serie I am stuck on a plotting issue. I've done some research before asking for help.
I've a dataframe that looks like this:
date            text
2020-08-18      hey what's up?
2020-08-18      all good here
2020-08-17      happy Monday
2020-08-17      no news good news
2020-08-17      it's been a while
2020-08-16      see you tomorrow

Long story short, I'm trying to plot a vertical bar chart, or a line plot, with ['date'] as my x and the COUNT of ['text'] as my y. There are 2 entries for 2020-08-18, 3 entries for 2020-08-17, and 1 for 2020-08-16.
Using SQL I'd simply have to do something like:
SELECT date, COUNT(date) AS count_date FROM my_table GROUP BY date

With Python I've been over complicating things, doing this:
df['date_count'] = df.groupby(['date'])['date'].transform('size')
df_temporary = df.loc[ : , ['date', 'date_count'] ].drop_duplicates()

And I can then plot the whole thing doing either:
sns.plotline(data=df_temporary, x='date', y='date_count')

or its Matplotlib equivalent:
plt.line(df_temporary.date, df_temporary.date_count)

It works, but I mean, it can't be that complicated, right?
What's the obvious thing that I'm not seeing? How do I get the COUNT for each unique date?

A: The simplest is:
ax = df.groupby('date').size().plot(kind='bar')

Which gives you a very plain looking chart which you can customize to your liking:

A: Yes, you are right. All these things can be done in one line.
plt.plot(df.groupby("date").apply(len))

A: You can create a temporary dataframe, to count uniuqe date per date.
temp['date_count'] = df.groupby(['date'])['date'].nunique().reset_index()

Then use it to plot your charts
sns.plotline(data=temp, x='date', y='date_count')

A: you are close indeed, the syntax is actually very similair to SQL
the key would be df.groupby(key to group by)[target column for agg function].count()
import matplotlib.pyplot as plt
from io import StringIO

d = """date            text
2020-08-18      hey what's up?
2020-08-18      all good here
2020-08-17      happy Monday
2020-08-17      no news good news
2020-08-17      it's been a while
2020-08-16      see you tomorrow"""

df = pd.read_csv(StringIO(d),sep='\s\s+',parse_dates=['date'])

df.groupby('date')['date'].count().plot(kind='line',title='Count of Text by Date'
                                   )


text:
Q: How to Move All tables from one Database into Different Database? I am using Oracle SQL Developer and I have ten tables. Now I want to move all 10 tables from Oracle into a SQL Server 2008 R2 database. Is there any easy solution for this task?

A: There are a lot of ways to do this one that go beyond what I listed, but here's a start.
1) You could try the SQL Server Migration Assistant for Oracle.  It's free and usually works well for me for smaller or medium sized datasets.
http://www.microsoft.com/en-us/download/details.aspx?id=28766
2) Create a SSIS package.
3) You could create a linked server in SQL and then select * from Oracle into SQL table (messy and probably not a good idea).
http://support.microsoft.com/kb/280106
4) Export to flat files and import into SQL.  Again, a ton of caveats with this one.

A: You can use Data Pump for SQL Server which allows transfering tables from any ADO-compatible data source including Oracle to MS SQL Database. It is not free but can be setup quickly.


text:
Q: Swift: Today Widget with animation I'd like to write a Today Widget Extension with an UIImageView which display an animation.
Here are my code.
    override func viewDidLoad() {
        super.viewDidLoad()
        layoutComponents()
        imageView.startAnimating()
   }

func layoutComponents() {
    self.extensionContext?.widgetLargestAvailableDisplayMode = NCWidgetDisplayMode.expanded

    self.view.backgroundColor = UIColor.blue

    let images = [UIImage(named:"1.png"), UIImage(named:"2.png"), UIImage(named:"3.png")]

    imageView.frame = CGRect(x: 0, y: 0, width: self.extensionContext!.widgetMaximumSize(for: .expanded).width, height: self.extensionContext!.widgetMaximumSize(for: .expanded).height)
    imageView.animationImages = images
    imageView.image = images[0]
    imageView.animationDuration = 1.0
    imageView.animationRepeatCount = 0
    self.view.addSubview(imageView)

    debugPrint("Done LayoutComponents")
  }

The code compiled successfully. However, the widget cannot be loaded, it display "Unable to Load" on the widget when run on the iPhone. And in the debug print, after printing "Done LayoutComponents". It has a line "Program ended with exit code: 0".
Any clues what i have done wrong? thanks.
Note that whenever i put the code imageView.startAnimating() in either viewWillAppear() viewDidAppear or widgetPerformUpdate() it will exit and with the problem that "Unable to load".
My question is actually is Today Extension support animating an UIImageView?

A: imageView.startAnimating() belongs in viewDidAppear instead of viewDidLoad as there is nothing to animate before the view appears.
Also verify that "User Preferred Explicit Size" is disabled in the storyboard (Today's extension iOS10 Show More/Less)


text:
Q: Permutation and Combination Question How many $3$ digits numbers are there, whose written form contains exactly two consecutive digits $3$?

A: Hint:
There are two kinds of these numbers, written as $\;\color{red}{33x}$, where $\;x\in \{\dots\}$, or $\;\color{red}{x33}$, where  $\;x\in \{\dots\}$.


text:
Q: Django Rest Framework - If condition Ignored I created a end-point that returns a PDF.
I have an condition to check if the asset exists, but that condition is always ignored. If the condition doesn't exist the end-point returns 500 not 404 as I want
urls:
 url(r'^report/asset/(?P<pk>[0-9]+)$', api.DemoPDFView.as_view()),

views.py
from easy_pdf.views import PDFTemplateResponseMixin, PDFTemplateView

class DemoPDFView(PDFTemplateView):
    template_name = 'reports/asset.html'
    pdf_filename = 'asset.pdf'

    def get_context_data(self, **kwargs):
        pk = kwargs['pk']
        if not Asset.objects.filter(id=pk).exists():
               Response(status=status.HTTP_404_NOT_FOUND)
        else:
               asset = Asset.objects.get(id=pk)
               project = asset.project.name
               id = asset.id
               name = asset.title

               return super(DemoPDFView, self).get_context_data(
                   pagesize='A4',
                   title='Asset',
                   project=project,
                   name=name,
                   id=id,
                   **kwargs
                   )

the plugin is Available:
http://django-easy-pdf.readthedocs.io/en/v0.2.0-dev1/

A: Since your code is not in the view itself, but in the get_context_data() method, I guess as @schwobaseggl mentions in the comments the right way to go is to raise the Http404 exception.

from django.http import Http404
...
if not Asset.objects.filter(id=pk).exists():
    raise Http404
else:
    ...

A: Much better version:
from django.shortcuts import get_object_or_404
asset = get_object_or_404(Asset, pk=pk)

It will raise 404 error automatically if Asset doesn't exist.

A: while I recommend using @Eugene Morozov answer, the issue with your current code is that you don't return the response in if
if not Asset.objects.filter(id=pk).exists():
    return Response(status=status.HTTP_404_NOT_FOUND)


text:
Q: Invalid result returned from the software lookup service I tried to submit an iOS app via XCode organizer, but it failed right after authentication and organizer said "Invalid result returned from the software lookup service".
How can I solve this problem?

A: Check that your app status is "Waiting for Upload" in iTunes Connect.
You can change the status to press "Ready to Upload Binary" blue button.

A: Check that your app is "Ready to upload" in iTunes Connect (I had this error when I rejected a binary and forgot to reset it to "Ready to Upload")


text:
Q: Android notification in status bar: use text instead of small icon? With the Notification.Builder, there is the setSmallIcon() function to set icon to use in the status bar.
For my purpose, I don't want an icon, but rather I want text (numbers to be more precise), just like the battery level percentage indication that is put there by the system.
I can't see a way of doing this, and I have a sinking feeling that I will need to have a different icon for each and every possible number, including both positive and negative.  Please tell me that I'm wrong!


text:
Q: Mongoose Query Returning Undefined I've got a Mongoose query that definitely should be working as far as I can tell, but is returning undefined and I can't figure out why.
Here's the query:
...
var perPage = config.perpage;
var page = req.query.page > 0 ? req.query.page : 0;

db.Mail.find().select('-body -scraped').limit(perPage).skip(perPage * page).sort('-createdAt').exec(function (err, mail) {
...

Here's the schema just in case:
var mongoose    = require("mongoose");
var timestamps  = require("mongoose-simpletimestamps").SimpleTimestamps;
var Schema      = mongoose.Schema;
var ObjectId    = Schema.ObjectId;

var oneday = 24 * 60 * 60;

var mailSchema = new Schema({
  subject: { type: String, required: true },
  body: { type: Schema.Types.Mixed, required: true },
  status: { type: String, required: true },
  processed: {
    area: {type: ObjectId, ref: 'Area'},
    url: String
  },
  scraped: { type: Schema.Types.Mixed },
  properties: [{ type: ObjectId, ref: 'Property' }],
  notifications: [{ type: ObjectId, ref: 'Notification' }],
  datestamp: {
    type: Number,
    default: function () { return Math.floor(Date.now() / oneday ); }
  }
});
mailSchema.plugin(timestamps);

module.exports = mongoose.model("Mail", mailSchema);

Any help would be greatly appreciated, thanks!


text:
Q: Not understanding the output of this forEach() method Consider this example:
var a = {
    "Check" : function doThis(value, index, ar) {
        if(value >= 10) {
            document.write(value + ", ");
        }
        else {
            document.write("The array element is less than 10, ");
        }
    }
}

var arr = [12, 20, 2, 3, 15];
document.write(arr.forEach(a.Check));

Which results in:
12, 20, The array element is less than 10,
The array element is less than 10, 15, undefined

I don't understand why there is an extra element in the array which is undefined. Does it have something to do with defining the callback function in an object?

A: replace:
document.write(arr.forEach(a.Check));

with:
arr.forEach(a.Check);

With document.write(arr.forEach(a.Check)); you are printing what the arr.forEach() call returns (undefined)


text:
Q: How to rectify the error Operator '&&' cannot be applied to operands of type 'bool?' and 'bool' This is my c# code.I'm getting error in this particular line as Operator '&&' cannot be applied to operands of type 'bool?' and 'bool'
if (openFileDialog.ShowDialog() && viewModel.OpenFileCommand.CanExecute(openFileDialog.FileName))
                {
                    viewModel.OpenFileCommand.Execute(openFileDialog.FileName);
                }

Please help me to rectify this error.

A: Window.ShowDialog Method

Returns Nullable<Boolean> A Nullable value of type Boolean that
specifies whether the activity was accepted (true) or canceled
(false). The return value is the value of the DialogResult property
before a window closes.

The problem is the result from ShowDialog is nullable.
However, you can rectify this by just using the more verbose == true, the compiler then  understands you want to explicitly know it's true, and not null or false. Don't ask me why it doesn't like the shorthand version (I'd have to dig through the specs).
Either way, here is your solution:
if (openFileDialog.ShowDialog() == true && viewModel....)

A: if (openFileDialog.ShowDialog() ?? false && viewModel.OpenFileCommand.CanExecute(openFileDialog.FileName))


text:
Q: How is C++ destructor executed? For the following code, why is "A is closed: 3" printed twice?
#include <stdio.h>

class A
{
 public:
  int a;

  A(int n)
  {
    a = n;
    printf("This is A: %d.\n", a);
  }

  A()
  {
    a = 0;
    printf("This is A: %d.\n", a);
  }

  ~A()
  {
    printf("A is closed: %d.\n", a);
  }
};

class B
{
 public:
  A a;

  B()
  {
    a = A(3);
  }
};

void f()
{
  B b;
}

int main()
{
  f();
  return 0;
}

output:
This is A: 0.
This is A: 3.
A is closed: 3.
A is closed: 3.

A: If you're expecting it to print exactly once, allow me to introduce you to initializer lists:
class B {
    public:
        A a;

        B() : a(3) {
        }
};

Currently, in your code, it prints twice because when B is created, all its members are constructed, then the constructor of B is called. It is printing once to construct A a, then it's printing again when you set a to A(3). Initializer lists allow you to specify how each member should be constructed before the constructor runs.
Additional tip: The order of initialization of the members is only affected by the order of their appearance in the struct/class and is unrelated to their order in the initializer list.

A: because before b assigned a new value to a , it already had a value (an instance exists).
you are using the default assignment operator which just makes a copy of the temp A(3) instance into a ,the member of B, and that copy must now be destroyed.
When f returns the B instance it created gets destroyed and in turn destroys its member a.


text:
Q: Group by a second parameter SELECT c.user1, c.user2, a.username AS author_name, SUBSTRING(m.content,1,20) as content, m.viewed, m.sent_date, m.author, c1.username AS username1, c2.username AS username2
FROM conversation c
INNER JOIN message m ON m.conversationid = c.conversationid
INNER JOIN user c1 ON c1.userid = c.user1
INNER JOIN user c2 oN c2.userid = c.user2
INNER JOIN user a ON a.userid = m.author
WHERE (c.user1 = 33 OR c.user2 = 34)
GROUP BY c.conversationid ORDER BY m.sent_date DESC

This groups by the conversationid. When it groups by and keeps one row, I need it to be the row with the most recent sent_date.
Is this possible with this structure?
Thanks.

A: The safe way to do this is to add a subquery to calculate the most recent sent date for each conversation:
SELECT c.user1, c.user2, a.username AS author_name, SUBSTRING(m.content,1,20) as content, m.viewed, m.sent_date, m.author, c1.username AS username1, c2.username AS username2
FROM conversation c
INNER JOIN message m ON m.conversationid = c.conversationid
inner join (select conversationid, max(sent_date) as maxsentdate from message group by conversationid) mc on m.conversationid = mc.conversationid and m.sent_date = mc.maxsentdate
INNER JOIN user c1 ON c1.userid = c.user1
INNER JOIN user c2 oN c2.userid = c.user2
INNER JOIN user a ON a.userid = m.author
WHERE (c.user1 = 33 OR c.user2 = 34)
GROUP BY c.conversationid ORDER BY m.sent_date DESC

What this is doing is calculating the maximum sent date for each message.  It then joins this to the message table, which gets you the last message.  You could, in theory, get duplicates, if two messages were sent at exactly the same time.  I think that is unlikely.

A: The problem is that you are grouping by only one column in the SELECT list. MySQL uses an extension to the GROUP BY clause that allows columns in the SELECT list to be excluded from being named in a group by or aggregate function. This can lead to unexpected results. (see MySQL Extensions to GROUP BY)
From the MySQL Docs:

MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. ... You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause. Sorting of the result set occurs after values have been chosen, and ORDER BY does not affect which values the server chooses.

Ideally you will use a subquery to get the result. This subquery will get the max sent_Date for each conversation and then you will join that back to your messages table to return the remaining columns needed:
SELECT c.user1,
  c.user2,
  a.username AS author_name,
  SUBSTRING(m.content,1,20) as content,
  m.viewed,
  m.sent_date,
  m.author,
  c1.username AS username1,
  c2.username AS username2
FROM conversation c
INNER JOIN message m
  ON m.conversationid = c.conversationid
INNER JOIN
(
  select max(sent_date) sent_date, conversationid
  from message
  group by conversationid
) m1
  ON m1.conversationid = c.conversationid
  AND m.sent_date = m1.sent_date
INNER JOIN user c1
  ON c1.userid = c.user1
INNER JOIN user c2
  ON c2.userid = c.user2
INNER JOIN user a
  ON a.userid = m.author
WHERE (c.user1 = 33 OR c.user2 = 34)
ORDER BY m.sent_date DESC


text:
Q: PHP ECHO to JSON result = JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data I have echo from php = echo "{success: true, redirect: '/home', auth_key:'$auth_key'}";
and tried to parse it but encountering error =

JSON.parse: expected property name or '}' at line 1 column 2 of the
  JSON data

I tried jquery parse and normal json.parse method
$.ajax({

    type: "POST",
    url: "/login/process",
    data: user,
    success: function (response) {
            var resp = $.parseJSON(response);
    }
});

I would like to get the value of auth from the echo

A: Your JSON is invalid. Try it on jsonlint. If you scroll down the page you will see Common errors and a rule:

Enclosing your collection keys in quotes. Proper format for a collection is { "key": "value" }

It should be:
echo '{"success": true, "redirect": "/home", "auth_key":"$auth_key"}';

Javascript test:

let invalidJson = "{success: true, redirect: '/home', auth_key:'$auth_key'}",
    validJson = '{"success": true, "redirect": "/home", "auth_key":"$auth_key"}';

try {
  console.log("invalid json", JSON.parse(invalidJson));
}
catch (e)
{
  console.error(e);
}

try {
  console.log("valid json", JSON.parse(validJson));
}
catch (e)
{
  console.error(e);
}

If you are creating a hard code json, I would advise to create an Array and echo it with json_encode(). The function will produce a valid json with your data and you won't need to worry about formatting it.

A: Instead you create array and save it as json and check,
$a =  ["success" =>  true, "redirect" =>  '/home', "auth_key" => $auth_key];
echo json_encode($a, JSON_UNESCAPED_SLASHES);die; //

JSON_UNESCAPED_SLASHES - Don't escape /.
Output
{"success":true,"redirect":"/home","auth_key":"123213123123"}

This will give sure short json output.


text:
Q: Recurrence Relation and closed form representation Consider the following recurrence relation describing a function $F$ whose domain is the set of all nonnegative integers:
$$F(0) = 2$$
$$F(N) = 3F(N-1) + 5; \quad N > 0$$
Question:  How to give a closed-form representation for $F$?

A: Hint: Try to expand:
$$F(n) = 3(3F(n-2) + 5) + 5 = 3^2 F(n-2) + 3\times 5  + 5 = 3^2(3F(n-3) + 5) + 3\times 5 + 5 = 3^3 F(n-3) + 3^2\times 5 + 3\times 5 + 5 = \cdots = 3^{n}F(0) + (\sum_{i=0}^{n-1} 3^i) \times 5 = 2\times 3^n + 5 \times \frac{3^n - 1}{2} = (2 + \frac{5}{2})\times 3^n - \frac{5}{2} = \frac{9}{2}\times 3^n-\frac{5}{2} = \frac{9\times 3^n - 5}{2} = \frac{3^{n+2} - 5}{2}$$

A: HINT:
$$f_1=3f_0+5$$
$$f_2=3^2f_0+3\cdot 5+5$$
$$f_3=3^3f_0+3^2\cdot 5+3\cdot 5+5$$
$$f_4=3^4f_0+3^3\cdot 5+3^2\cdot 5+3\cdot 5+5$$
$$...$$
$$f_n=3^n f_0+3^{n-1}\cdot 5+3^{n-2}\cdot 5+...+3\cdot 5+5$$

A: Hint: divide $\,f_n = 3f_{n-1} +5\,$ by $\,3^n\,$, then telescope:
$$\dfrac{f_n}{3^n} = \dfrac{f_{n-1}}{3^{n-1}} + 5 \cdot \dfrac{1}{3^n}=\dfrac{f_{n-2}}{3^{n-2}} +5 \cdot \left(\dfrac{1}{3^{n-1}} +\dfrac{1}{3^n}\right)=\ldots=\dfrac{f_0}{3^0}+ 5 \cdot \left(\dfrac{1}{3}+ \ldots\dfrac{1}{3^{n-1}} +\dfrac{1}{3^n}\right)$$


text:
Q: Evaluation of an integral of a particular form How to evaluate an integral of this form:
 $$ \iint_{[0,1]\times [0,1]}  \max\{x,y\}\,dx dy $$?
Please give  the approach to  help me out.

A: Fix $x$. Then tthe domain of integration of $y$ is naturally separated in two
parts. This leads to:
$$
\int_{[0,1]×[0,1]}\max\{x,y\}dxdy = \int_{x=0}^1 \left( \int_{y=0}^x x dy + \int_{y=x}^1 y dy
\right) dx
$$


text:
Q: libusb bulk transfer I am trying to implement user space usb driver using libusb1.0.9. I have lpc2148 blueboard(ARM7) with me..This board is loaded with opensource USB stack/firmware by Mr. Bertrik Sikken. Now my user space driver is trying read write with board. I am getting garbage data.
I want to know about the flow of bulk tranfer.
For any transfer/transaction is there kernel device driver involved??
and do we need usb gadget device driver also??
I am not able to understand that where the data gets copied.
Important thing is that when I read/write interrupt gets generated and I can see correct data on LCD. Do I need to read/write USBRxData/USBTxData?
Please do the needfull.
I tried the below code for bulk transfer read and write..
int usb_read(struct libusb_device *dev,struct libusb_device_handle *hDevice)
{
    char *data,*data1;
    struct  libusb_endpoint_descriptor *ep;
    struct  libusb_interface_descriptor *id;
    int len=64,r,ret_alt,ret_clm,ret_rst,i;
    struct libusb_device **list;

    data = (char *)malloc(512); //allocation  of buffers
    data1 = (char *)malloc(512);
    memset(data,'\0',512);
    memset(data1,'\0',512);

    if(hDevice==NULL)
    {
        printf("\nNO device found\n");
        return 0;
    }
    int ret_open = libusb_open(dev,&hDevice);
    if(ret_open!=0)
    {
        printf("Error in libusb_open\n");
        libusb_free_device_list(list,1);
        return -1;
    }
    char str_tx[512]="G";    //data to send to device
    char str_rx[512];        //receive string
    data = str_tx;

    printf("data::%s\t,str::%s\n",data,str_tx);
    //printf("%c\n",data);
    ep = active_config(dev,hDevice);
    printf("after ep\n");
    //printf("alt_interface = %d\n",alt_interface);
    ret_rst = libusb_reset_device(hDevice);
    if(ret_rst < 0)
    {
        printf("Error in reset :: %d",ret_rst);
        return -1;
    }
    printf("original data1 : %s\n",data1);
    r = libusb_bulk_transfer(hDevice,0x08,str_tx,512,&len,0);
    //write to device buffer from data

    printf("Error number :: %d\n",r);
    int le = ep->bEndpointAddress;
    int ty = ep->bDescriptorType;
    int y = ep->bmAttributes;

    printf("y::%d\tatt:: %d\n",y,ep->bmAttributes);
    if(r==-1)
        printf("Error in io\n");
    if(r==0)
    {
        printf("data returned :: %s\n",data);
        printf("len= %d\n",len);
        printf("Device Button Pressed!!!!\n");
    }
    else
    {
        printf("Error in bulk transfer\n");
        return -1;
    }

    r = libusb_bulk_transfer(hDevice,0x82,data1,512,&len,0);
    //read from device buffer to data1
    //str_rx = data1;
    //printf("End point address::%d\n",le);
    //printf("End point desc.type::%d\n",ty);
    if(r==-1)
        printf("Error in io\n");
    if(r==0)
    {
        printf("data1 returned::%s\n",data1);   //received string in data1
        printf("len= %d\n",len);
        printf("Device Button Pressed!!!!\n");
    }
    else
    {
        printf("Error in bulk transfer\n");
        return -1;
    }

    return 0;
}

A: Try the code given below and it should work on lpc2148.
I have tested this with a lpc2148 configured to receive an interrupt from USB after a write happens (from user-space) and RTC starts running.
Answering to your question whether it involves kernel driver in read/write or not, as far as I have studied, You have to detach the kernel driver and claim the interface using libusb APIs. Though I am not sure whether it can be done without detaching it or not.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include </usr/local/include/libusb-1.0/libusb.h>

#define BULK_EP_OUT     0x82
#define BULK_EP_IN      0x08

int interface_ref = 0;
int alt_interface,interface_number;

int print_configuration(struct libusb_device_handle *hDevice,struct libusb_config_descriptor *config)
{
    char *data;
    int index;

    data = (char *)malloc(512);
    memset(data,0,512);

    index = config->iConfiguration;

    libusb_get_string_descriptor_ascii(hDevice,index,data,512);

    printf("\nInterface Descriptors: ");
    printf("\n\tNumber of Interfaces : %d",config->bNumInterfaces);
    printf("\n\tLength : %d",config->bLength);
    printf("\n\tDesc_Type : %d",config->bDescriptorType);
    printf("\n\tConfig_index : %d",config->iConfiguration);
    printf("\n\tTotal length : %lu",config->wTotalLength);
    printf("\n\tConfiguration Value  : %d",config->bConfigurationValue);
    printf("\n\tConfiguration Attributes : %d",config->bmAttributes);
    printf("\n\tMaxPower(mA) : %d\n",config->MaxPower);

    free(data);
    data = NULL;
    return 0;
}

struct libusb_endpoint_descriptor* active_config(struct libusb_device *dev,struct libusb_device_handle *handle)
{
    struct libusb_device_handle *hDevice_req;
    struct libusb_config_descriptor *config;
    struct libusb_endpoint_descriptor *endpoint;
    int altsetting_index,interface_index=0,ret_active;
    int i,ret_print;

    hDevice_req = handle;

    ret_active = libusb_get_active_config_descriptor(dev,&config);
    ret_print = print_configuration(hDevice_req,config);

    for(interface_index=0;interface_index<config->bNumInterfaces;interface_index++)
    {
        const struct libusb_interface *iface = &config->interface[interface_index];
        for(altsetting_index=0;altsetting_index<iface->num_altsetting;altsetting_index++)
        {
            const struct libusb_interface_descriptor *altsetting = &iface->altsetting[altsetting_index];

            int endpoint_index;
            for(endpoint_index=0;endpoint_index<altsetting->bNumEndpoints;endpoint_index++)
            {
                const struct libusb_endpoint_desriptor *ep = &altsetting->endpoint[endpoint_index];
                endpoint = ep;
                alt_interface = altsetting->bAlternateSetting;
                interface_number = altsetting->bInterfaceNumber;
            }

            printf("\nEndPoint Descriptors: ");
            printf("\n\tSize of EndPoint Descriptor : %d",endpoint->bLength);
            printf("\n\tType of Descriptor : %d",endpoint->bDescriptorType);
            printf("\n\tEndpoint Address : 0x0%x",endpoint->bEndpointAddress);
            printf("\n\tMaximum Packet Size: %x",endpoint->wMaxPacketSize);
            printf("\n\tAttributes applied to Endpoint: %d",endpoint->bmAttributes);
            printf("\n\tInterval for Polling for data Tranfer : %d\n",endpoint->bInterval);
        }
    }
    libusb_free_config_descriptor(NULL);
    return endpoint;
}

int main(void)
{
    int r = 1;
    struct libusb_device **devs;
    struct libusb_device_handle *handle = NULL, *hDevice_expected = NULL;
    struct libusb_device *dev,*dev_expected;

    struct libusb_device_descriptor desc;
    struct libusb_endpoint_descriptor *epdesc;
    struct libusb_interface_descriptor *intdesc;

    ssize_t cnt;
    int e = 0,config2;
    int i = 0,index;
    char str1[64], str2[64];
    char found = 0;

// Init libusb
    r = libusb_init(NULL);
    if(r < 0)
    {
        printf("\nfailed to initialise libusb\n");
        return 1;
    }
    else
        printf("\nInit Successful!\n");

// Get a list os USB devices
    cnt = libusb_get_device_list(NULL, &devs);
    if (cnt < 0)
    {
        printf("\nThere are no USB devices on bus\n");
        return -1;
    }
    printf("\nDevice Count : %d\n-------------------------------\n",cnt);

    while ((dev = devs[i++]) != NULL)
    {
        r = libusb_get_device_descriptor(dev, &desc);
        if (r < 0)
            {
            printf("failed to get device descriptor\n");
            libusb_free_device_list(devs,1);
            libusb_close(handle);
            break;
        }

        e = libusb_open(dev,&handle);
        if (e < 0)
        {
            printf("error opening device\n");
            libusb_free_device_list(devs,1);
            libusb_close(handle);
            break;
        }

        printf("\nDevice Descriptors: ");
        printf("\n\tVendor ID : %x",desc.idVendor);
        printf("\n\tProduct ID : %x",desc.idProduct);
        printf("\n\tSerial Number : %x",desc.iSerialNumber);
        printf("\n\tSize of Device Descriptor : %d",desc.bLength);
        printf("\n\tType of Descriptor : %d",desc.bDescriptorType);
        printf("\n\tUSB Specification Release Number : %d",desc.bcdUSB);
        printf("\n\tDevice Release Number : %d",desc.bcdDevice);
        printf("\n\tDevice Class : %d",desc.bDeviceClass);
        printf("\n\tDevice Sub-Class : %d",desc.bDeviceSubClass);
        printf("\n\tDevice Protocol : %d",desc.bDeviceProtocol);
        printf("\n\tMax. Packet Size : %d",desc.bMaxPacketSize0);
        printf("\n\tNo. of Configuraions : %d\n",desc.bNumConfigurations);

        e = libusb_get_string_descriptor_ascii(handle, desc.iManufacturer, (unsigned char*) str1, sizeof(str1));
        if (e < 0)
        {
        libusb_free_device_list(devs,1);
            libusb_close(handle);
            break;
        }
        printf("\nManufactured : %s",str1);

        e = libusb_get_string_descriptor_ascii(handle, desc.iProduct, (unsigned char*) str2, sizeof(str2));
        if(e < 0)
        {
        libusb_free_device_list(devs,1);
            libusb_close(handle);
            break;
        }
        printf("\nProduct : %s",str2);
        printf("\n----------------------------------------");

        if(desc.idVendor == 0xffff && desc.idProduct == 0x4)
        {
        found = 1;
        break;
        }
    }//end of while
    if(found == 0)
    {
        printf("\nDevice NOT found\n");
        libusb_free_device_list(devs,1);
        libusb_close(handle);
        return 1;
    }
    else
    {
        printf("\nDevice found");
        dev_expected = dev;
        hDevice_expected = handle;
    }

    e = libusb_get_configuration(handle,&config2);
    if(e!=0)
    {
        printf("\n***Error in libusb_get_configuration\n");
        libusb_free_device_list(devs,1);
        libusb_close(handle);
        return -1;
    }
    printf("\nConfigured value : %d",config2);

    if(config2 != 1)
    {
        libusb_set_configuration(handle, 1);
        if(e!=0)
        {
            printf("Error in libusb_set_configuration\n");
            libusb_free_device_list(devs,1);
            libusb_close(handle);
            return -1;
        }
        else
            printf("\nDevice is in configured state!");
    }

    libusb_free_device_list(devs, 1);

    if(libusb_kernel_driver_active(handle, 0) == 1)
    {
        printf("\nKernel Driver Active");
        if(libusb_detach_kernel_driver(handle, 0) == 0)
            printf("\nKernel Driver Detached!");
        else
        {
            printf("\nCouldn't detach kernel driver!\n");
            libusb_free_device_list(devs,1);
            libusb_close(handle);
            return -1;
        }
    }

    e = libusb_claim_interface(handle, 0);
    if(e < 0)
    {
        printf("\nCannot Claim Interface");
        libusb_free_device_list(devs,1);
        libusb_close(handle);
        return -1;
    }
    else
        printf("\nClaimed Interface\n");

    active_config(dev_expected,hDevice_expected);

    //   Communicate

    char *my_string, *my_string1;
    int transferred = 0;
    int received = 0;
    int length = 0;

    my_string = (char *)malloc(nbytes + 1);
    my_string1 = (char *)malloc(nbytes + 1);

    memset(my_string,'\0',64);
    memset(my_string1,'\0',64);

    strcpy(my_string,"prasad divesd");
    length = strlen(my_string);

    printf("\nTo be sent : %s",my_string);

    e = libusb_bulk_transfer(handle,BULK_EP_IN,my_string,length,&transferred,0);
    if(e == 0 && transferred == length)
    {
        printf("\nWrite successful!");
        printf("\nSent %d bytes with string: %s\n", transferred, my_string);
    }
    else
        printf("\nError in write! e = %d and transferred = %d\n",e,transferred);

    sleep(3);
    i = 0;

    for(i = 0; i < length; i++)
    {
        e = libusb_bulk_transfer(handle,BULK_EP_OUT,my_string1,64,&received,0);  //64 : Max Packet Lenght
        if(e == 0)
        {
            printf("\nReceived: ");
            printf("%c",my_string1[i]);    //will read a string from lcp2148
            sleep(1);
        }
        else
        {
            printf("\nError in read! e = %d and received = %d\n",e,received);
            return -1;
        }
    }

    e = libusb_release_interface(handle, 0);

    libusb_close(handle);
    libusb_exit(NULL);

    printf("\n");
    return 0;
}

A: To handle kernal detaching.
if(libusb_kernel_driver_active(dev_handle, 0) == 1)         //find out if kernel driver is attached
{
    cout << "Kernel Driver Active" << endl;

    if(libusb_detach_kernel_driver(dev_handle, 0) == 0)     //detach it
    {
        cout << "Kernel Driver Detached!" << endl;
    }
}


text:
Q: React - How to add multiple values for a the state I am trying to add multiple values from an array to the state, but for some reasons, only the last one is added into the state
here is the code:
this.state = { languageList: {} };

const languages = ['English', 'Spanish', 'Russian']

languages.map(language =>
   this.setState({
     languageList: {
         ...this.state.languageList,
         [language]: true,
      },
   }),
);

Can anyone help?
Expected output:
languageList: { Engish: true, Spanish: true, Russian: true }

A: You can call setState only once rather than calling it into a loop.
If you do it into a loop, only the last setState will be applied because the previous ones haven't been executed yet.
this.setState({
  languageList: {
    ...this.state.languageList,
    ...Object.fromEntries(languages.map(language => [language, true]))
  }
}),

If you really want to call setState into a loop (I don't recommend it because it cause a lot of state updates), you must use the updater function to do the update from the previous state
languages.map(language =>
  this.setState(prevState => ({
    languageList: {
      ...prevState.languageList,
      [language]: true,
    },
  })),
);

A: Since you're updating state based on previous values, you need to use the updater form:
this.setState(prevState => ({
  languageList: {
    ...prevState.languageList,
    [language]: true,
  },
})),

This is because setState is async, and your loop will run to completion before the state is actually updated. Meaning this.state.languageList will be the same empty object for each iteration.


text:
Q: react-table selectbox filtering table plugin https://github.com/tannerlinsley/react-table
how i can filter my column with select box ? eg:
i have column and there is just two name
Name 1
Name 2
I want to put selectbox to column for select and filtering my NAME 1 or NAME 2 entries.
{Header: 'Owner',accessor: 'name', headerClassName: 'wordwrap', Filter: ({ filter, onChange }) =>
        <select
          onChange={event => onChange(event.target.value)}
          style={{ width: "100%" }}
          value={filter ? filter.value : "all"}
        >
          <option value="all">Show All</option>
          <option value="true">Name 1</option>
          <option value="false">Name 2</option>
        </select>
        },

I found in example something and implemented to my code. But I don't know how put options from my accessor


text:
Q: Write contents of each php array on a new line in a text file I have used a while loop to fetch rows from a database and collect them in an array.
Now what I want to achieve is that on each iteration of this loop, the elements of the array should be written on a new line in a text file
I've tried implode but it's not working. I am probably using it in a completely wrong way.
Here is my code:
$query = "SELECT hist FROM loch ;";
$result = mysql_query($query) or die(mysql_error());

$file = "/opt/lampp/htdocs/rrugd/ip.txt";
fopen($file,'a');

$output=array();
while($row=mysql_fetch_row($result))
{

        $instr1 = implode("\n", $row);
        file_put_contents($file, $instr1, FILE_APPEND | LOCK_EX);
}

I want the output to look like this -
1 2 10 5
1 2 10

But what I am getting is this -
1 2 10 51 2 10

Where am I going wrong?

A: Use PHP_EOL to add a new line like so:
file_put_contents($file, $instr1 . PHP_EOL, FILE_APPEND | LOCK_EX);


text:
Q: How can I underline an ListBoxItem in WPF? How can I underline an ListBoxItem in WPF? I'm using the following but the underline does not appear.
<DataTemplate x:Key="Phrase_List">
    <ListBoxItem IsSelected="{Binding IsDefault}">
        <TextBlock Text="{Binding Path=Phrase}" Tag="{Binding Path=ID}" TextDecorations="Underline"  />
    </ListBoxItem>
</DataTemplate>

A: I don't know what code you are trying to use. Please try to complete your question. I've used the following code to underline the 'World' item in my little ListBox.
    <ListBox>
        <ListBoxItem>Hello</ListBoxItem>
        <ListBoxItem>
            <Underline>World</Underline>
        </ListBoxItem>
    </ListBox>

A: You can use a textblock, and set the textdecorations property to underline. Remember the contents of a ListBoxItem can be things other than text, hence why it's not a simple case of setting some property on the ListBoxItem.

A: You will need to create an item template that displays your text in a TextBlock control.  On the TextBlock, set the TextDecorations property (which is a collection) to contain 'Underline'.

A: In XAML:
<ListBox Name="lst">
      <ListBoxItem Content="item1" />
      <ListBoxItem Content="item2" FontStyle="Italic" FontWeight="Normal" />
</ListBox>

In C#:
lst.Items.Clear();
lst.Items.Add(new ListBoxItem { Content = "item 1" });
lst.Items.Add(new ListBoxItem { Content = "item 2" });
lst.Items.Add(new ListBoxItem { Content = "item 3" });

ListBoxItem l = (ListBoxItem)lstItems.Items[2];
li.SetValue(TextElement.FontStyleProperty, FontStyles.Italic);


text:
Q: Vscode Folding Area Normal editor folding staying left side of html editor. But it did happen I don't know, it folding area moved to up of editor. So How I can fixed it ?

Thank you for helping...
Edit 1
I thought my problem was caused by this but my problem is like that,
there is folding in left side of editor. it's hiding in few second only vue template. It's working normal html files. How can I do like as below ?

A: This is not related to folding. The thing is called "breadcrumbs", and can be disabled using:
"breadcrumbs.enabled": false

A: I found solution,
I was using vetur extention. and Vetur published new version which is 0.27.1 and it's not working very well. I installed previous version it's fixed.


text:
Q: props.actions `undefined` when using redux and react.js I'm following a tutorial from this link: http://www.thegreatcodeadventure.com/react-redux-tutorial-part-ii-react-router-and-container-components/
But when the handleSubmit() function is fired i get an error:

TypeError: Cannot read property 'logInUser' of undefined

Indeed when i try to log this.props.actions it's undefined but i don't understand why. Is there something missing?
I'm using Antd as UI framework.
Component
import React, { Component } from 'react';
import { Form, Icon, Input, Button, Checkbox } from 'antd';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as sessionActions from './actions/sessionActions';

const FormItem = Form.Item;

class Login extends Component {
  constructor(props){
    super(props);
    this.state = {credentials: {username: '', password: ''}};
    this.handleSubmit = this.handleSubmit.bind(this);
    this.onChange = this.onChange.bind(this);
  }

  onChange(event) {
    const field = event.target.name;
    const credentials = this.state.credentials;
    credentials[field] = event.target.value;;
    return this.setState({credentials: credentials});
  }

  handleSubmit = (event) => {
    event.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        //console.log(this.props.actions);
        this.props.actions.logInUser(this.state.credentials);
      }
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
        <Form onSubmit={this.handleSubmit} className="login-form">
        <FormItem>
          {getFieldDecorator('userName', {
            rules: [{ required: true, message: 'username missing!' }],
          })(
          <Input
              name="username"
              value={this.state.credentials.username}
              prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="Username o email"
              onChange={this.onChange}/>
          )}
        </FormItem>
        <FormItem>
          {getFieldDecorator('password', {
            rules: [{ required: true, message: 'Password missing!' }],
          })(
          <Input
            name="password"
            value={this.state.credentials.password}
            prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
            type="password"
            placeholder="Password"
            onChange={this.onChange}/>
          )}
        </FormItem>
        <FormItem>
          {getFieldDecorator('remember', {
              valuePropName: 'checked',
              initialValue: false,
            })(
              <Checkbox>Ricordami</Checkbox>
            )}
          <Button type="primary" htmlType="submit" className="login-form-button">
          Log in
          </Button>
        </FormItem>
        </Form>
    );
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    actions: bindActionCreators(sessionActions, dispatch)
  };
}

export default Form.create()(Login);connect(null, mapDispatchToProps)(Login);

sessionReducer.js
import * as types from '../actions/actionTypes';
import initialState from './initialState';

export default function sessionReducer(state = initialState.session, action) {
  switch(action.type) {
    case types.LOG_IN_SUCCESS:
      this.context.history.push('/')
      return !!sessionStorage.jwt
    default:
      return state;
  }
}

sessionActions.js
import * as types from './actionTypes';
import sessionApi from '../api/sessionApi';

export function loginSuccess() {
  return {type: types.LOG_IN_SUCCESS}
}

export function logInUser(credentials) {
  return function(dispatch) {
    return sessionApi.login(credentials).then(response => {
      sessionStorage.setItem('jwt', response.jwt);
      dispatch(loginSuccess());
    }).catch(error => {
      throw(error);
    });
  };
}

UPDATE
I fixed the problem with the help of @Chaim Friedman but now i got another error:

Error: Actions must be plain objects. Use custom middleware for async actions.

But i'm using redux-thunk as middleware. Here's login function if it can helps:
sessionApi.js
import React from 'react'

var axios = require('axios');
var qs = require('qs');

class SessionApi {

  static login(credentials){
    axios.post('http://localhost:5000/login', qs.stringify({auth: credentials}))
      .then(response => {
        console.log(response);
        return response.json();
      }),
      error => {
        console.log(error);
        return error;
      };
  }
}

A: I believe your trouble is with this line here.
export default Form.create()(Login);connect(null, mapDispatchToProps)(Login);

You are only exporting what Form.create() returns, so therefor your component is not actually connected to redux.
To fix this issue you would need to do something like this.
export default Form.create(connect(null, matchDispatchToProps)(Login));

The exact syntax made be different, it would depend on the usage of Form.create(), but this would be the basic idea.


text:
Q: Creating a Symbolic Matrix Probably very simple, but I don't know where to start with this. How do I go about creating a symbolic matrix, such as the one below?

I want to be able to use this so that any list of lists that are entered to signify a matrix can be read as having indices {i,1,m},{j,1,n}, and then I can use another rule using the terms in the matrix, ai,j.
I found an answer that mentioned SymbolicMatrix, but this no longer seems to work on the most up-to-date versions of Mathematica.
EDIT: This seems to be trickier than I first thought. Essentially, whenever I enter a list of lists, such as mat[{{1,2,3},{4,5,6},{7,8,9}], I want to be able to automatically recognise that the first list corresponds to a1,1,a1,2,a1,3, the second list to a2,1,a2,2,a2,3, and the third list (in this example) to a3,1,a3,2,a3,3.
I then aim to write a rule that, when values of I and j are selected, gives back a list of {ai,j+1, ai,j-1, ai-1,j, ai+1,j}.

A: myMatrix[n_Integer, m_Integer] :=
 Table[Subscript[a, i, j], {i, n}, {j, m}] // MatrixForm

myMatrix[3, 4]

A: As mentioned in the comments, it is probably easier to stay away from using subscripts, which are primarily a formatting command. Your task is readily accomplished using Array, and defining a function to extract the elements you want:
mat = Array[a, {4, 5}]
fun[m_, i_, j_] := {a[i, j + 1], a[i, j - 1], a[i - 1, j], a[i + 1, j]};

mat defines the matrix and fun extracts the specified elements. For example:
fun[mat, 3, 4]
{a[3, 5], a[3, 3], a[2, 4], a[4, 4]}


text:
Q: How can I check if a value is inside of a d3 scale range I use d3's scaleLinear. I want to filter values that are outside of the scale's domain.
var arr = [0, 1, 15, 60, 700];

var scaleX = d3.scaleLinear()
    .domain([10, 100])
    .range([0, 200]);

// I need something like this:
scaleX.filter(arr)  // I want to get: [1, 15, 60]

My best solution is foreach all the values and check that the domain's min/max is less/greater than the given value. Like this.
Is there any more compact solution?

A: var filteredArr = arr.filter(function(d) {
    return d >= scaleX.domain()[0] && d <= scaleX.domain()[1]
})

A: Apply the filter method to the arr variable:
const filteredArray = arr.filter(function (value) { return ((value >= 10) && (value <= 100)) });

The filteredArray will contain only the values between 10 and 100 (inclusive).
You can read more about the .filter method here.


text:
Q: Inserting php if statement within php code? I have a php script that is basically querying my database and providing details about each store, and including an image. The code pulls in the image fine, but currently if no image exists in the database, I have spacer image being inserted instead. Instead of using a spacer image though, is there a way for me to use a PHP 'if' statement inside of the php code to not render an image if the database has no image listed? Here is the basic query code:
<?php
   if(strlen($query) >= $min_length){$query = htmlspecialchars($query);
   $query = mysql_real_escape_string($query);
   $raw_results = mysql_query("SELECT * FROM stores WHERE `TRAVEL` = '1' AND `STATE` = '$query'") or die(mysql_error());
   if(mysql_num_rows($raw_results) > 0){
   while($results = mysql_fetch_array($raw_results)){

   echo "

   ".$results['NAME']."

";
   }
   }    else{ echo "No results were found";

   }
   }    else{ echo " ".$min_length; }
?>

For the php if statement, I was thinking something along these lines:
<?php if ($results['IMAGE'] != '') {  ?>

<?php }?>

A: You're pretty close. Just use one more <?php ... ?> block in the img
<?php if ($results['IMAGE'] != '') {  ?>
  <img src='images/icons/<?php echo $results['IMAGE'] ?>' height="100" width="auto">
<?php }?>

You can use the alternative control flow syntax too. It reads a little nicer than spanning the { and } across multiple <?php tags
<?php if ($results['IMAGE'] != ''):  ?>
  <img src='images/icons/<?php echo $results['IMAGE'] ?>' height="100" width="auto">
<?php endif ?>

Shameless plug:
Generating HTML with PHP gets really ugly. At least in my opinion. To make the job a little nicer/easier, I made htmlgen, mirrored on packagist.

A: Simply like this :
if(isset($results['IMAGE'])){

  echo "

  ".$results['NAME']."

 	";

}


text:
Q: index+1 to with_index without going off index This is my very round-about way to prevent +1 to the last index in the array. What's the best practice to achieve this in ruby? Thanks in advance.
  array.each.with_index do |x, index|
    unless index+1 == array.length
      if x + array[index+1] == n
        ...

A: Try this:
array[0..-2].each.with_index do |x, index|
      if x + array[index+1] == n
        ...

A: You can use a range to do what you want. Something like:
array = [0, 1, 2, 3, 4]
array[0...-1].each do |x|
    print x
end
# => 0123

-1 refers to the last element, and using 3 dots ... means you're taking all the elements from the first to the last *exclusively*. 2 dots would also include the last one.
Bonus tip: in ruby, you'll be able to get away most of the times by using each instead of each_with_index, by culling/modifying the array beforehand.


text:
Q: Datetime format for series - Highcharts I need to implement this https://www.highcharts.com/demo/line-time-series, but that needs data like these https://cdn.jsdelivr.net/gh/highcharts/highcharts@v7.0.0/samples/data/usdeur.json, 1167868800000 is a datetime date format but I do not know how to pass my datatime to this format
I need to convert this date 2019-04-02 21:35:04 -0600 to this 1167868800000
How could I solve this? I'm working on ruby on rails

A: You can use momentjs to convert your date to epoch time.
Here is a sample.

var ADBE = [
    ['2019-04-02 21:35:04',23.17],
    ['2019-04-02 22:35:04',23.78],
    ['2019-04-02 23:35:04',24.10],
    ['2019-04-03 20:35:04',23.86],
    ['2019-04-03 21:35:04',24.54]
 ];

 ADBE = ADBE.map(function(data) { return [moment(data[0], "YYYY-MM-DD HH:mm:ss").valueOf(), data[1]]});
Highcharts.stockChart('container', {

    rangeSelector: {
        selected: 1
    },

    legend: {
        enabled: true,
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'top',
        y: 100
    },

    series: [{
        name: 'ADBE',
        data: ADBE
    }]
});


text:
Q: How to make a view not to scroll with soft input keyboard? I have 2 layouts

*

*Options layout: should scroll up with keyboard

*Layout(linear2) shouldn't scroll up with keyboard. (Keyboard should hide the particular layout , while scrolling it should be reachable)
'Options' layout working as expected. But the problem is with the layout(linear2) which also scrolls up with keyboard. How to fix it?
Attached the xml file below:
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/options"
        android:clipChildren="true"
        android:fillViewport="true"
        >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#ffffff" >

            <LinearLayout
                android:id="@+id/linear1
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                  android:orientation="vertical"
                >

                <EditText
                    android:id="@+id/edittext1
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                  />
            <EditText
                    android:id="@+id/edittext2
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                  />

            </LinearLayout>
<!-- shouldnot scroll up with keyboard -->
            <LinearLayout
                android:id="@+id/linear2
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:orientation="vertical"
                >
                <TextView
                    android:id="@+id/txtview1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_above="@+id/linear3"
                    android:paddingBottom="10dp"
                    android:visibility="gone" />

                <LinearLayout
                    android:id="@+id/linear3"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:visibility="gone" />
            </LinearLayout>
        </RelativeLayout>
    </ScrollView>

<!-- scrolls up with soft input keyboard -->
    <RelativeLayout
        android:id="@+id/options"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="#f8f8f8"
         >

        <Button
            android:id="@+id/save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            />

        <Button
            android:id="@+id/cancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
           android:layout_alignParentRight="true"
            />

    </RelativeLayout>
</RelativeLayout>


text:
Q: Python: `and` operator does not return a boolean value In Python, an empty list is considered a Falsey value
Therefore this is how things should work:
>>> [] and False
False

But in reality, python returns an empty list.
>>> [] and False
[]

Is this intended or a bug?

A: It's intended. Both and and or are defined to return the last thing evaluated (based on short-circuiting), not actually True or False. For and, this means it returns the first falsy value, if any, and the last value (regardless of truthiness) if all the others are truthy.
It was especially useful back before the conditional expression was added, as it let you do some almost-equivalent hacks, e.g. before the conditional expression:
b if a else c

could be written as:
a and b or c

and, assuming b itself was some truthy thing, it would behave equivalently (the conditional expression lacked that limitation and was more clear about intent, which is why it was added). Even today this feature is occasionally useful for replacing all falsy values with some more specifically-typed default, e.g. when lst might be passed as None or a list, you can ensure it's a list with:
lst = lst or []

to cheaply replace None (and any other falsy thing) with a new empty list.

A: This is how it is supposed to work. and will only return the right hand operand if the left hand operand is truthy. Since [] is falsy, and returns the left hand operand.

A: That's a totally expected behaviour. To understand it, you need to know how the Boolean operators (and, or, not) work. From the Boolean Operations documentation:

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

Now let's consider your example: [] and False. Here, since [] is falsey, it's value is returned back by the statement which is [].
Above linked Python documentation explicitly mentions:

Note: Neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument.

However, in case you need the return value as boolean, you can explicitly type-cast the value to True or False using the bool() function.
For example, in your case it will return as False:
>>> bool([] and False)
False


text:
Q: Get Remote site url by SOQL APEX in salesforce I want to get value of remote site url in salesforce
(Ex: I want to get http://abc.com like image below).
How can I use query SOQL in APEX to get it?

A: You can use ToolingAPI to access the RemoteSiteSettings. In developer you can try to query like below.
select id, SiteName, EndpointUrl from RemoteProxy

In the above query EndpointUrl is field which you are looking for.
You need to check the "Use Tooling API" check box to true else you will not get result.


text:
Q: Having Error in Android Manifest while building Execution failed for task ':app:processDebugResources'.

A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
Android resource linking failed
C:\Users\kcs\AndroidStudioProjects\OURVEDIC\app\build\intermediates\packaged_manifests\debug\AndroidManifest.xml:11: AAPT: error: resource xml/backup_descriptor (aka com.binni.ourvedic:xml/backup_descriptor) not found.

This is the error I am having
my code :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.binni.ourvedic">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.OURVEDIC"
        android:fullBackupContent="@xml/backup_descriptor">
        <activity android:name=".SplashScreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity">

        </activity>

        <meta-data
            android:name="preloaded_fonts"
            android:resource="@array/preloaded_fonts" />
    </application>

</manifest>

A: Remove the line android:fullBackupContent="@xml/backup_descriptor" in your application tag in manifest file, or add the needed xml file to your project.
<application
    android:fullBackupContent="@xml/backup_descriptor">
    ...
</application>

A: looks like if you have clone the project that uses shared preferences, this error wont go away by simply deleting
 android:fullBackupContent="@xml/backup_descriptor

In order to solve this problem, create a  new resource directory of type xml in res folder.
Inside this folder create a a file named : "backup_descriptor"
and copy this tag into it :
<full-backup-content>
</full-backup-content>

A: in Android Studio , try This
File > Invalidate Caches/Restart

A: Only remove
<meta-data
 android:name="preloaded_fonts"
 android:resource="@array/preloaded_fonts" />


text:
Q: Python Basemap fails I am using Anaconda 2.1.0 and Basemap installation is successful
conda install basemap

However, I keep getting the following error when I try to project lat,lon to a planar:
Assertion failed: (0), function query, file AbstractSTRtree.cpp, line 286.

My code looks like this:
import shapely.geometry as sg
from pymongo import MongoClient
from mpl_toolkits.basemap import Basemap

p = Basemap(projection='sinu',lon_0=0,resolution='c') #fails here

projected_xy = p([24.4,45.1])

The code fails even before attempting to project.

A: For some reason, Basemap has to be imported before shapely.
from mpl_toolkits.basemap import Basemap
import shapely.geometry as sg

Doing the import the other way around will cause the error.


text:
Q: which one is executed first I have a web application in php, I don't know which one will be ever called an processed first,
In my php file, I also have a javascript code

In my php code, I will send an array object into that javascript. So I wonder why the php code is executed first instead of the javascript ? Does it mean that all server code will always be executed before the client script runs during the browser view is shown.

A: The server side code is executed first and the output generated by server side is sent back to client where client side code is executed.

A: Yes, normally, the whole server processing finished before the page is delivered to the browser. At this moment, JavaScript execution starts.
You can add late execution of PHP code using AJAX.

A: Of course, the server code (be it PHP,ASP,JSP,etc) runs first in the server, it generates an html page which contains your javascript code, your computer receives this page, renders it in the browser and runs the javascript in it.

A: if you have html,php,js in a single file you should know these two things   only:
1)your file extension must be .php (because php execution required .php extension)
2)you will see the output exactly in the same order as you typed in your file.

<?php
 echo "i m php upper"."
";
?>

i am html upper

<?php
 echo "i m php bottem"."
";
?>

i am html bottem

...output looks like this...
i m php upper
i am html upper
i am javascript upper
i m php bottem
i am javascript bottom
i am html bottem


text:
Q: Fitltering in findall I have rule:
best_fit(Team, Enemies, Result, List) :-
    findall((H, E), score(H, Enemies, Team, E), List),

where score definition is:
score(Hero, Enemies, Team, Result) :-
   hero(Hero),
...

I would like to find only that (H,E) where H is not in Enemies or Team. I tried to later exclude but the results are tuples and it is kind of complicated to make it work. Is there a way to filter it out in findall method? How can I approach this?

A: You can enforce that in the goal:
best_fit(Team, Enemies, Result, List) :-
    findall((H, E), (
        score(H, Enemies, Team, E),
        \+ member(H, Enemies),
        \+ member(H, Team),
    ), List).
So here we modified the goal such that it is satisfied if score(H, Enemies, Team, E) and H is not a member of Enemies, and H is not a member of Team.


text:
Q: SQL Nested Query based on value of Dependent Column In the below table structure, TB_Vehicles is the Master table and TB_Cars, TB_Bikes, TB_Cars are Satellite tables which hold more info about respective vehicles.
**TB_Scooters**
V_NAME  V_ID    V_YEAR  V_TYPE  V_MILEAGE
Activa  10  2003    Scooter 45
Access  20  2004    Scooter 50

**TB_Bikes**
V_NAME  V_ID    V_YEAR  V_TYPE  V_ENGINE
Karizma 30  2001    Bike    180
Pulsar  40  2008    Bike    150

**TB_Cars**
V_NAME  V_ID    V_YEAR  V_TYPE  V_CAR_TYPE
Linea   50  2011    Car Sedan
i20 60  2012    Car Sedan

**TB_Vehicles**
V_NAME  V_ID    V_YEAR  V_TYPE  V_COLOR V_AVAILABLE
Activa  10  2003    Scooter Black   Yes
Access  20  2004    Scooter Black   No
Karizma 30  2001    Bike    Red Yes
Pulsar  40  2008    Bike    Black   Yes
Linea   50  2011    Car White   No
i20 60  2012    Car Red Yes

I want users to search using the Name. So, when users enter Name as 'Access', my query should give all information about that vehicle, including that from Satellite Tables (using both TB_Vehicles and TB_Scooters).
SELECT * FROM TB_Vehicles
WHERE V_NAME = 'Access';

Similarly, if user enters 'Linea', it should give info from TB_Vehicles and TB_Cars tables.
So, with V_NAME as input, I'll find V_TYPE from TB_Vehicles table, and using that, I need to identify which satellite table, I need to join to retrieve more info.
How do I do this? Can you please help me with the query? Do I need to use CASE or DECODE to achieve this?
EDIT:
The requirement here is to display only those columns which are applicable for that particular vehicle type. So, when user gives 'Access' as input, it should display all columns from TB_Vehicles table, and V_MILEAGE from TB_Scooters table.
I was thinking whether this can be done using CASE or DECODE, where I first identify the type (V_TYPE) of the vehicle from TB_Vehicles table using the input name (V_NAME), and then based on this V_TYPE, I'll search the relevant table and display only relevant columns.
When Input Name is 'Access', then result should be:
V_NAME     V_ID   V_YEAR   V_TYPE    V_COLOR   V_AVAILABLE   V_MILEAGE
Access   20     2004     Scooter   Black     No            50

When Input Name is 'i20', then result should be:
V_NAME     V_ID   V_YEAR   V_TYPE   V_COLOR   V_AVAILABLE   V_CAR_TYPE
i20      60     2012     Car      Red       Yes           Sedan

A: You shouldn't be storing the name in both the vehicles tables and the subtables.  If this is common information, then just store it in the vehicles table.  This is true of all the common columns.
Next, when you access data, do it by bringing together all the tables:
select v.*,
       s.v_mileage, b.v_engine, c.v_car_type
from TB_vehicles v left join
     TB_Scooters s
     on s.v_id = v.v_id and v.type = 'scooter' left join
     TB_Bikes b
     on b.v_id = v.v_id and v.type = 'bike' left join
     TB_Cars c
     on c.v_id = v.vid and v.type = 'car';

From this query, you can then choose the row and the fields that you want.
However, you need to work on normalizing your data structure so fields like v_year are only in one table.

A: Thanks Gordon! Appreciate your help over this...
For others with similar query, please look into the above response from Gordon as well as the below link:
http://www.orafaq.com/forum/t/189451/180198/


text:
Q: Tkinter Button with icon: `_tkinter.TclError: image doesn't exist` In a script, that I am writing I need a button with a little trash bin as an icon on it. I use the code shown below:
# Python 3.7.1
import tkinter as tk

master = tk.Tk()

photo = tk.PhotoImage(file="bin.png")

icon_button = tk.Button(master, image=photo)
icon_button.pack()

The following error occurs:
_tkinter.TclError: image "pyimage1. doesn't exist
Since I specified bin.png as the image file, I cannot really understand how pyimage1 is specified in the error.
After some debugging, I realized, that the PhotoImage returns the string pyimage1, and therefore gives "pyimage1" as a parameter to the Button, but I still don't know how to fix my issue.

A: The problem is that Relative path won't be accepted, i.e. if you have your bin.png in C:\ then you should do as-
tk.PhotoImage(file='C:\\bin.png')

Now, if you still want to use relative paths then the following will do-
import tkinter as tk
import os

Win = tk.Tk()
Img = tk.PhotoImage(file=os.path.abspath('bin.png')

tk.Button(Win, image=Img).pack()
Win.mainloop()

Or use this-
import sys, os

def get_path(file):
    if not hasattr(sys, ''):
        file = os.path.join(os.path.dirname(__file__), file)
        return file
    else:
        file = os.path.join(sys.prefix, file)
        return file

It simply just gets the full path of a file.
Now, use the function-
...file=get_path('bin.png'))


text:
Q: how to configure sonarqube in multi maven project running from jenkins assuming you have a maven module with the following structure:

*

*root module

*

*integration test module

*sources module A

*sources module B

*additional modules...

and you have a pipeline in jenkins which use multiple jobs as part of the build process: preliminary job that compile all modules, and then, additional job that runs the integrations test by executing a maven command on the integration tests module.
now, in sonarqube server, you would like to see all of the sources from all modules, and for each of them, the coverage data.
from what I understand, there are two ways to accomplish this, and the first way is preferable -

*

*Using sonar's "BaseProjectDir" property.
https://docs.sonarqube.org/display/SONAR/Analysis+Parameters#AnalysisParameters-projectBaseDir

*run an aggregation job to collect the data after integration test over.

we tried to configure the base directory property (sonar.projectBaseDir) as a maven parameter, pom property and in sonar-project.properties file.
(also tried an absolute and relative paths)
no matter what we tried, it seems that the base folder is not affecting sonar.
as you can see in the picture below (base dir), and by reviewing results in sonar server, the only files that we get are files that located inside integration-tests module (inner module).
while we would like that the analysis will be done regarding all the files inside the parent module.

Additional data:
list of sonar parameters (passed by maven)-
sonar.host.url=$SONAR_HOST_URL
sonar.login=$SONAR_AUTH_TOKEN
sonar.sources=src/main
sonar.projectBaseDir=../
sonar.jacoco.reportPaths=**/target/jacoco-it.exec

I am using the following versions:

*

*Sonarqube server: 7.3

*sonar-maven-plugin: 3.5.0.1254.

Am I missing something?
does sonar support this kind of configuration?
I would appreciate any help..


text:
Q: MySQL 'Order By' - sorting alphanumeric correctly I want to sort the following data items in the order they are presented below (numbers 1-12):

1
2
3
4
5
6
7
8
9
10
11
12
However, my query - using order by xxxxx asc sorts by the first digit above all else:

1
10
11
12
2
3
4
5
6
7
8
9
Any tricks to make it sort more properly?
Further, in the interest of full disclosure, this could be a mix of letters and numbers (although right now it is not), e.g.:

A1
534G
G46A
100B
100A
100JE

etc....
Thanks!
update: people asking for query
select * from table order by name asc

A: I had some good results with
SELECT alphanumeric, integer FROM sorting_test ORDER BY CAST(alphanumeric AS UNSIGNED), alphanumeric ASC

A: This type of question has been asked previously.
The type of sorting you are talking about is called "Natural Sorting".
The data on which you want to do sort is alphanumeric.
It would be better to create a new column for sorting.
For further help check
natural-sort-in-mysql

A: If you need to sort an alpha-numeric column that does not have any standard format whatsoever
SELECT * FROM table ORDER BY (name = '0') DESC, (name+0 > 0) DESC, name+0 ASC, name ASC

You can adapt this solution to include support for non-alphanumeric characters if desired using additional logic.

A: This should sort alphanumeric field like:
1/ Number only, order by 1,2,3,4,5,6,7,8,9,10,11 etc...
2/ Then field with text like: 1foo, 2bar, aaa11aa, aaa22aa, b5452 etc...
SELECT  MyField
FROM MyTable
order by
    IF( MyField REGEXP '^-?[0-9]+$' = 0,
    9999999999 ,
    CAST(MyField AS DECIMAL)
    ), MyField

The query check if the data is a number, if not put it to 9999999999 , then order first on this column, then order on data with text
Good luck!

A: Instead of trying to write some function and slow down the SELECT query, I thought of another way of doing this...
Create an extra field in your database that holds the result from the following Class and when you insert a new row, run the field value that will be naturally sorted through this class and save its result in the extra field.  Then instead of sorting by your original field, sort by the extra field.
String nsFieldVal = new NaturalSortString(getFieldValue(),  4).toString()
The above means:
- Create a NaturalSortString for the String returned from getFieldValue()
- Allow up to 4 bytes to store each character or number (4 bytes = ffff = 65535)

| field(32)  |  nsfield(161)                            |
  a1            300610001

String sortString = new NaturalSortString(getString(), 4).toString()
import StringUtils;

/**
 * Creates a string that allows natural sorting in a SQL database
 * eg, 0 1 1a 2 3 3a 10 100 a a1 a1a1 b
 */
public class NaturalSortString {

    private String inStr;
    private int byteSize;
    private StringBuilder out = new StringBuilder();

    /**
     * A byte stores the hex value (0 to f) of a letter or number.
     * Since a letter is two bytes, the minimum byteSize is 2.
     *
     * 2 bytes = 00 - ff  (max number is 255)
     * 3 bytes = 000 - fff (max number is 4095)
     * 4 bytes = 0000 - ffff (max number is 65535)
     *
     * For example:
     * dog123 = 64,6F,67,7B and thus byteSize >= 2.
     * dog280 = 64,6F,67,118 and thus byteSize >= 3.
     *
     * For example:
     * The String, "There are 1000000 spots on a dalmatian" would require a byteSize that can
     * store the number '1000000' which in hex is 'f4240' and thus the byteSize must be at least 5
     *
     * The dbColumn size to store the NaturalSortString is calculated as:
     * > originalStringColumnSize x byteSize + 1
     * The extra '1' is a marker for String type - Letter, Number, Symbol
     * Thus, if the originalStringColumn is varchar(32) and the byteSize is 5:
     * > NaturalSortStringColumnSize = 32 x 5 + 1 = varchar(161)
     *
     * The byteSize must be the same for all NaturalSortStrings created in the same table.
     * If you need to change the byteSize (for instance, to accommodate larger numbers), you will
     * need to recalculate the NaturalSortString for each existing row using the new byteSize.
     *
     * @param str        String to create a natural sort string from
     * @param byteSize   Per character storage byte size (minimum 2)
     * @throws Exception See the error description thrown
     */
    public NaturalSortString(String str, int byteSize) throws Exception {
        if (str == null || str.isEmpty()) return;
        this.inStr = str;
        this.byteSize = Math.max(2, byteSize);  // minimum of 2 bytes to hold a character
        setStringType();
        iterateString();
    }

    private void setStringType() {
        char firstchar = inStr.toLowerCase().subSequence(0, 1).charAt(0);
        if (Character.isLetter(firstchar))     // letters third
            out.append(3);
        else if (Character.isDigit(firstchar)) // numbers second
            out.append(2);
        else                                   // non-alphanumeric first
            out.append(1);
    }

    private void iterateString() throws Exception {
        StringBuilder n = new StringBuilder();
        for (char c : inStr.toLowerCase().toCharArray()) { // lowercase for CASE INSENSITIVE sorting
            if (Character.isDigit(c)) {
                // group numbers
                n.append(c);
                continue;
            }
            if (n.length() > 0) {
                addInteger(n.toString());
                n = new StringBuilder();
            }
            addCharacter(c);
        }
        if (n.length() > 0) {
            addInteger(n.toString());
        }
    }

    private void addInteger(String s) throws Exception {
        int i = Integer.parseInt(s);
        if (i >= (Math.pow(16, byteSize)))
            throw new Exception("naturalsort_bytesize_exceeded");
        out.append(StringUtils.padLeft(Integer.toHexString(i), byteSize));
    }

    private void addCharacter(char c) {
        //TODO: Add rest of accented characters
        if (c >= 224 && c <= 229) // set accented a to a
            c = 'a';
        else if (c >= 232 && c <= 235) // set accented e to e
            c = 'e';
        else if (c >= 236 && c <= 239) // set accented i to i
            c = 'i';
        else if (c >= 242 && c <= 246) // set accented o to o
            c = 'o';
        else if (c >= 249 && c <= 252) // set accented u to u
            c = 'u';
        else if (c >= 253 && c <= 255) // set accented y to y
            c = 'y';

        out.append(StringUtils.padLeft(Integer.toHexString(c), byteSize));
    }

    @Override
    public String toString() {
        return out.toString();
    }
}

For completeness, below is the StringUtils.padLeft method:
public static String padLeft(String s, int n) {
    if (n - s.length() == 0) return s;
    return String.format("%0" + (n - s.length()) + "d%s", 0, s);
}

The result should come out like the following
-1
-a
0
1
1.0
1.01
1.1.1
1a
1b
9
10
10a
10ab
11
12
12abcd
100
a
a1a1
a1a2
a-1
a-2
áviacion
b
c1
c2
c12
c100
d
d1.1.1
e

A: MySQL ORDER BY Sorting alphanumeric on correct order
example:
SELECT `alphanumericCol` FROM `tableName` ORDER BY
  SUBSTR(`alphanumericCol` FROM 1 FOR 1),
  LPAD(lower(`alphanumericCol`), 10,0) ASC

output:
1
2
11
21
100
101
102
104
S-104A
S-105
S-107
S-111

A: I hate this, but this will work
order by lpad(name, 10, 0)  <-- assuming maximum string length is 10
                            <-- you can adjust to a bigger length if you want to

A: Just do this:
SELECT * FROM table ORDER BY column `name`+0 ASC

Appending the +0 will mean that:
0,
10,
11,
2,
3,
4
becomes :
0,
2,
3,
4,
10,
11

A: I know this post is closed but I think my way could help some people. So there it is :
My dataset is very similar but is a bit more complex. It has numbers, alphanumeric data :
1
2
Chair
3
0
4
5
-
Table
10
13
19
Windows
99
102
Dog

I would like to have the '-' symbol at first, then the numbers, then the text.
So I go like this :
SELECT name, (name = '-') boolDash, (name = '0') boolZero, (name+0 > 0) boolNum
FROM table
ORDER BY boolDash DESC, boolZero DESC, boolNum DESC, (name+0), name

The result should be something :
-
0
1
2
3
4
5
10
13
99
102
Chair
Dog
Table
Windows

The whole idea is doing some simple check into the SELECT and sorting with the result.

A: People use different tricks to do this. I Googled and find out some results each follow different tricks. Have a look at them:

*

*Alpha Numeric Sorting in MySQL

*Natural Sorting in MySQL

*Sorting of numeric values mixed with alphanumeric values

*mySQL natural sort

*Natural Sort in MySQL
Edit:
I have just added the code of each link for future visitors.
Alpha Numeric Sorting in MySQL
Given input
1A 1a 10A 9B 21C 1C 1D
Expected output
1A 1C 1D 1a 9B 10A 21C
Query
Bin Way
===================================
SELECT
tbl_column,
BIN(tbl_column) AS binray_not_needed_column
FROM db_table
ORDER BY binray_not_needed_column ASC , tbl_column ASC

-----------------------

Cast Way
===================================
SELECT
tbl_column,
CAST(tbl_column as SIGNED) AS casted_column
FROM db_table
ORDER BY casted_column ASC , tbl_column ASC

Natural Sorting in MySQL
Given input
Table: sorting_test
 -------------------------- -------------
| alphanumeric VARCHAR(75) | integer INT |
 -------------------------- -------------
| test1                    | 1           |
| test12                   | 2           |
| test13                   | 3           |
| test2                    | 4           |
| test3                    | 5           |
 -------------------------- -------------

Expected Output
 -------------------------- -------------
| alphanumeric VARCHAR(75) | integer INT |
 -------------------------- -------------
| test1                    | 1           |
| test2                    | 4           |
| test3                    | 5           |
| test12                   | 2           |
| test13                   | 3           |
 -------------------------- -------------

Query
SELECT alphanumeric, integer
       FROM sorting_test
       ORDER BY LENGTH(alphanumeric), alphanumeric

Sorting of numeric values mixed with alphanumeric values
Given input
2a, 12, 5b, 5a, 10, 11, 1, 4b

Expected Output
1, 2a, 4b, 5a, 5b, 10, 11, 12

Query
SELECT version
FROM version_sorting
ORDER BY CAST(version AS UNSIGNED), version;

A: This works for type of data:
   Data1,
Data2, Data3 ......,Data21. Means "Data" String is common in all rows.
For ORDER BY ASC it will sort perfectly, For ORDER BY DESC not suitable.
SELECT * FROM table_name ORDER BY LENGTH(column_name), column_name ASC;

A: This is from tutorials point
SELECT * FROM yourTableName ORDER BY
SUBSTR(yourColumnName FROM 1 FOR 2),
CAST(SUBSTR(yourColumnName FROM 2) AS UNSIGNED);

it is slightly different from another answer of this thread
For reference, this is the original link
https://www.tutorialspoint.com/mysql-order-by-string-with-numbers
Another point regarding UNSIGNED is written here
https://electrictoolbox.com/mysql-order-string-as-int/
While this has REGEX too
https://www.sitepoint.com/community/t/how-to-sort-text-with-numbers-with-sql/346088/9

A: SELECT length(actual_project_name),actual_project_name,
SUBSTRING_INDEX(actual_project_name,'-',1) as aaaaaa,
SUBSTRING_INDEX(actual_project_name, '-', -1) as actual_project_number,
concat(SUBSTRING_INDEX(actual_project_name,'-',1),SUBSTRING_INDEX(actual_project_name, '-', -1)) as a
FROM ctts.test22
order by
SUBSTRING_INDEX(actual_project_name,'-',1) asc,cast(SUBSTRING_INDEX(actual_project_name, '-', -1) as unsigned) asc

A: This is a simple example.
SELECT HEX(some_col) h
FROM some_table
ORDER BY h

A: order by len(xxxxx),xxxxx
Eg:
SELECT * from customer order by len(xxxxx),xxxxx

A: SELECT
s.id, s.name,  LENGTH(s.name) len, ASCII(s.name) ASCCCI
FROM table_name s
ORDER BY ASCCCI,len,NAME ASC;

A: Try this For ORDER BY DESC
SELECT * FROM testdata ORDER BY LENGHT(name) DESC, name DESC

A: Assuming varchar field containing number, decimal, alphanumeric and string, for example :
Let's suppose Column Name is "RandomValues" and Table name is "SortingTest"

A1
120
2.23
3
0
2
Apple
Zebra
Banana
23
86.Akjf9
Abtuo332
66.9
22
ABC

SELECT * FROM SortingTest order by IF( RandomValues REGEXP '^-?[0-9,.]+$' = 0,
9999999999 ,
CAST(RandomValues AS DECIMAL)
), RandomValues

Above query will do sorting on number & decimal values first and after that all alphanumeric values got sorted.

A: This will always put the values starting with a number first:
ORDER BY my_column REGEXP '^[0-9]' DESC, length(my_column  + 0), my_column ";

Works as follows:

*

*Step1 - Is first char a digit? 1 if true, 0 if false, so order by this DESC

*Step2 - How many digits is the number? Order by this ASC

*Step3 - Order by the field itself

Input:
  ('100'),
  ('1'),
  ('10'),
  ('0'),
  ('2'),
  ('2a'),
  ('12sdfa'),
  ('12 sdfa'),
  ('Bar nah');

Output:
0
1
2
2a
10
12 sdfa
12sdfa
100
Bar nah

A: Really problematic for my scenario...
select * from table order by lpad(column, 20, 0)
My column is a varchar, but has numeric input (1, 2, 3...) , mixed numeric (1A, 1B, 1C) and too string data (INT, SHIP)


text:
Q: Interrupter on induction heater Im currently trying to control the power of my induction heater, i want to use an interrupter to control it. but if i now interrupt the driver at random points, the mosfets wont turn off at zero voltage points, how would i go with building a comperator circuit that only interrupts at a zero crossing?

A: You could use a current limited buck converter in front of your induction heater circuit .I have done this on a scientific experiment for heating a needle .This approach meant that ZVS was not disturbed .I think that it improves reliability so it is worth the cost and complexaty

A: I went for a pulse density modulation approach after all, this meant that i had to use IGBTs because of the high impulse current.


text:
Q: Character-wise string diff in PHP In short I am looking for something like google-diff-match-patch in PHP.
I have had a look at some similar questions at SO, and also at the algorithm provided here, but all of them fail:
diff("draßen", "da draußen")

should not give
draßen da draußen

(which is kind of stupid for my purpose, because I want to compare file names), but (try here)
da draußen

Is there a code snippet in PHP that does this? Unfortunately, I cannot use (i.e. install) external packages.

A: https://github.com/gorhill/PHP-FineDiff supports character-wise diff and can render the differences in HTML

A: The PEAR Package Text_Diff provides Inline-Diffs.

A: There is a php version of google-diff-match-patch available here: https://github.com/nuxodin/diff_match_patch-php

A: There is a port of fresh version google-diff-match-patch library.
It is much faster than previous and have no problems wth utf8.