text:
Q: How to create functions in the global scope based on name, calling a method by same name I'm trying to generate a bunch of functions based on the respective methods of a  logging.Logger instance from inside a function scope. The functions/methods I am interested in are:
['debug', 'info', 'warning', 'error', 'critical', 'exception']

which all share the same prototype.
Now I can obviously state:
global debug, info, warning, error critical, exception

and then go ahead and def each of them. I checked it and that works fine. Problem is that I have to repeat myself.
So I have an instance of a logging.Logger named mylog which is already a global. The following does what I want, but by hardcoding the name of the function/method respectively:
global debug
def debug(msg, *args, **kwargs):
    if mylog: mylog.debug(msg, *args, **kwargs)

For the sake of brevity I'm going to write my examples all with only debug in mind, skipping the rest. Unfortunately the real code is somewhat more complex so that the requirements for using a lambda don't seem to be fulfilled (single statement, right?).
So my obvious thinking was to use getattr with the name of "debug" on mylog and simply call whatever I get back inside the defined function and add that by name to the globals() dict. Example:
for fct in ['debug']:
    def x(msg, *args, **kwargs):
        if mylog: getattr(mylog, fct)(msg, *args, **kwargs)
    globals()[fct] = x

But I think this is not actually legal as I am calling what's supposed to be a class method as if it were a static method. Nevertheless this "works", but each output line is followed by another line saying: None.
So I thought to myself that I could possibly pass the instance as the first parameter. After all that's what the self is all about:
for fct in ['debug']:
    def x(msg, *args, **kwargs):
        if mylog: getattr(mylog, fct)(mylog, msg, *args, **kwargs)
    globals()[fct] = x

which gives me:
TypeError: not all arguments converted during string formatting

which is the identical effect that I get from this:
for fct in ['debug']:
    import types
    def x(msg, *args, **kwargs):
        if mylog: types.MethodType(getattr(mylog, fct), mylog)(msg, *args, **kwargs)
    globals()[fct] = x

which I based on the accepted answer of this question: Dynamically bind method to class instance in python
Applying the answer from Alex Martelli here gives the same error.
What am I doing wrong? How can I achieve the desired behavior without having to repeat myself?

Full traceback:
Traceback (most recent call last):
  File "/usr/lib64/python2.6/logging/__init__.py", line 776, in emit
    msg = self.format(record)
  File "/usr/lib64/python2.6/logging/__init__.py", line 654, in format
    return fmt.format(record)
  File "/usr/lib64/python2.6/logging/__init__.py", line 436, in format
    record.message = record.getMessage()
  File "/usr/lib64/python2.6/logging/__init__.py", line 306, in getMessage
    msg = msg % self.args
TypeError: not all arguments converted during string formatting

Complete script, based on the very first example code above:
#!/usr/bin/env python
import sys, logging

def setup_logging():
    global mylog
    mylog = logging.getLogger('foobar')
    mylog.addHandler(logging.StreamHandler())
    for fct in ['debug']:
        def x(msg, *args, **kwargs):
            if mylog: getattr(mylog, fct)(mylog, msg, *args, **kwargs)
        globals()[fct] = x

def main():
    setup_logging()
    debug('TEST LOG MESSAGE')

if __name__ == '__main__':
    sys.exit(main())

A: It seems to me that this ought to work:
debug = mylog.debug

or:
debug, info, warning, error, critical, exception = (
    mylog.debug, mylog.info, mylog.warning,
    mylog.error, mylog.critical, mylog.exception)

To set it dynamically:
for fct in ('debug', 'info', 'warning'):
    globals()[fct] = getattr(mylog, fct)

Your for loops for fct in ('debug'): are iterating over the string 'debug', you would have needed a comma for fct in ('debug',): to make it a tuple.
Also note that a construct such as:
for fct in ['debug']:
    def x(msg, *args, **kwargs):
        if mylog: getattr(mylog, fct)(msg, *args, **kwargs)
    globals()[fct] = x

defines a function uses the current value of `fct`` when it is called. You need an extra level of indirection to handle more than one logging method. e.g.
def make_log(fct):
    def x(msg, *args, **kwargs):
        if mylog: getattr(mylog, fct)(msg, *args, **kwargs)
    return x

for fct in ['debug','info']:
    globals()[fct] = make_log(fct)


text:
Q: Regex to match possibly-escaped quotes I'm trying to write a regex to match single quotes, which may be escaped. A matched quote should have an even number of backslashes before it (an odd number means that the quote is escaped). For example, in these five strings:
'quotes should be matched'
\'quotes should NOT be matched\'
\\'quotes should be matched\\'
\\\'quotes should NOT be matched\\\'
\\\\'quotes should be matched\\\\'

Here is the regex that I have:
(?<=[^\\](?:\\\\)*)'

However, this does not match anything in the above example. I find this strange because removing the * from the regex matches the quotes with two backslashes, as it should:
(?<=[^\\](?:\\\\))' matches \\'

A: As far as I can see, it's not possible to match just the '. This is because you can't have dynamic length lookbehinds as Wiseguy pointed out.
The following regex would match the correct ' AND any \s leading up to it however. Not sure if this will be of any use..
(?<!\\)(?:\\\\)*'

Matches an arbitrary number of double \s not preceded by a \ and followed by a '.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Uncaught SyntaxError: Unexpected token : i have an unexpected token :
but i dont know why this is.
the code where it is happening.
<script type="text/javascript">
$('.delete-btn').click(function() {
 $.ajax(function() {
    type: 'POST',
    url: 'ajax.php',
    data: { filename: filename },
    success: function(return) {
        if(return == 'SUCCESS') {
            $this = $(this).closest('tr');
            $this.remove();
        }
    }
});
});
</script>

I hope someone can find why i get the unexpeded token : at the url: 'ajax.php', rule.

A: The syntax error is in your success callback. You've named the argument return, which is a reserved word. Call it something else.

Niet here, merging my answer into this one to complete the picture:
Change:
$.ajax(function() {

To:
$.ajax({

Pay closer attention to what you're writing :p

A: return is a reserved word in JavaScript. Use any other name other than return. I have used data instead of return. Also there is type is an error in ajax function you have written. updated the same. Use the below code
<script type="text/javascript">
$('.delete-btn').click(function() {
 $.ajax({
    type: 'POST',
    url: 'ajax.php',
    data: { filename: filename },
    success: function(data) {
        if(data == 'SUCCESS') {
            $this = $(this).closest('tr');
            $this.remove();
        }
    }
});
});
</script>

A: return is a keyword at javascript dont use it as a variable name
 <script type="text/javascript">
    $('.delete-btn').click(function() {
     $.ajax(function() {
        type: 'POST',
        url: 'ajax.php',
        data: { filename: filename },
        success: function(data) {
            if(data== 'SUCCESS') {
                $this = $(this).closest('tr');
                $this.remove();
            }
        }
    });
    });
    </script>


text:
Q: WCF Serialization and Deserialization i am new to WCF Service. I am creating WCF Service which take record from Dynamics CRM. After deployed to IIS, i tested the service. And the service run well when and returning data with xml format. Here's is my code
Service.svc
public List<Presid> GetPresalesIdList(string userlogin)
    {
        List<Presid> idsales = new List<Presid>();
        Presid presales = new Presid();
        string cmb = userdomain + userlogin;
        InitializeCRMService(userName, passWord, domain);

        try
        {
            if (!string.IsNullOrEmpty(userlogin))
            {
                QueryExpression qe = new QueryExpression("systemuser");
                string[] cols = { "businessunitid", "domainname", "systemuserid" };
                qe.Criteria = new FilterExpression();
                qe.Criteria.AddCondition("domainname", ConditionOperator.Equal, cmb);
                qe.ColumnSet = new ColumnSet(cols);

                var guid = _service.RetrieveMultiple(qe);

                userid = ((EntityReference)guid[0].Attributes["businessunitid"]).Id;
                systemid = (Guid)guid[0].Attributes["systemuserid"];

                QueryExpression query = new QueryExpression("opportunity");
                string[] cols2 = { "new_presalesid","createdon", "ownerid", "name", "parentaccountid", "statecode", "estimatedclosedate" };
                query.Criteria = new FilterExpression();
                query.Criteria.AddCondition("ownerid", ConditionOperator.Equal, systemid);
                query.ColumnSet = new ColumnSet(cols2);
                EntityCollection preid = _service.RetrieveMultiple(query);

                string prsId = string.Empty;
                string optNm = string.Empty;
                string cusNm = string.Empty;
                string stscde = string.Empty;
                DateTime closedate;
                DateTime open;

                foreach (Entity enty in preid.Entities)
                {

                    presales = new Presid();
                    if (enty.Attributes.Contains("new_presalesid"))
                    {
                        prsId = enty.GetAttributeValue<string>("new_presalesid");
                        if (!string.IsNullOrEmpty(prsId))
                        {
                            presales.PresalesID = prsId;
                        }
                        else
                        {
                            presales.PresalesID = null;
                        }
                    }

                    if (enty.Attributes.Contains("name"))
                    {
                        optNm = enty.GetAttributeValue<string>("name");
                        if (!string.IsNullOrEmpty(optNm))
                        {
                            presales.OptiName = optNm;

                        }
                        else
                        {
                            presales.OptiName = null;
                        }
                    }

                    //cusNm = enty.GetAttributeValue<EntityReference>("parentaccountid").Name;

                    if (enty.Attributes.Contains("parentaccountid"))
                    {
                        cusNm = ((EntityReference)enty["parentaccountid"]).Name;

                        if (!string.IsNullOrEmpty(cusNm))
                        {
                            presales.CustomerName = cusNm;
                        }
                        else
                        {
                            presales.CustomerName = null;
                        }
                    }

                    if (enty.Attributes.Contains("statecode"))
                    {
                        stscde = enty.FormattedValues["statecode"];
                        if (!string.IsNullOrEmpty(stscde))
                        {
                            presales.Status = stscde;
                        }
                        else
                        {
                            presales.Status = null;
                        }
                    }

                    if (enty.Attributes.Contains("estimatedclosedate"))
                    {
                        closedate = enty.GetAttributeValue<DateTime>("estimatedclosedate");
                        if (closedate != null)
                        {
                            presales.ClosedDate = closedate;
                        }

                    }

                    if (enty.Attributes.Contains("createdon"))
                    {
                        open = enty.GetAttributeValue<DateTime>("createdon");
                        if (open != null)
                        {
                            presales.CreateOn = open;
                        }
                    }

                    idsales.Add(presales);
                }
                return idsales;

            }
        }
        catch (Exception ex)
        {

        }
        return idsales;
    }

Presid Class:
namespace WCF_CRM_Multipolar
{
[Serializable]
[DataContract(Namespace = "http://mlpt-web.com/CRM/services")]
public class Presid
{
    [DataMember]
    public string PresalesID
    {
        get;
        set;
    }

    [DataMember]
    public string OptiName
    {
        get;
        set;
    }

    [DataMember]
    public string CustomerName
    {
        get;
        set;
    }

    [DataMember]
    public string Status
    {
        get;
        set;
    }

    [DataMember]
    public Nullable<DateTime> ClosedDate
    {
        get;
        set;
    }

    [DataMember]
    public DateTime CreateOn
    {
        get;
        set;
    }

}

}
IService
[OperationContract]
    [WebInvoke(Method = "GET",
      ResponseFormat = WebMessageFormat.Xml,
      RequestFormat = WebMessageFormat.Xml,
      BodyStyle = WebMessageBodyStyle.Wrapped,
      UriTemplate = "/GetPresalesIdList/{userlogin}")]
    List<Presid> GetPresalesIdList(string userlogin);

Those code run well when i tested from my pc by calling from this URL:
http://localhost:8076/Service1.svc/Getpresalesidlist/user

But, when other division want to call this service by Deserialize it, they say that they can't do it. So they ask me to search what causes the problems. I think that my code is yet serialize, so they are unable to deserialize. Based on that story, i've got questions:

*

*Is that true that my code is serialize yet ? If that's true, how to make it serializeable ?
I have looking for the example of serializable on the internet. Using something called MemoryStream. But i'am unable to implement that within my code. So please show me the way to make my code serializable.

A: Based on your configuration and your formal declaration, your List<Presid> will be in xml format in the response. Perhaps the response is empty {} or an error occurs in which case plain html may be returned to the caller, the error description, depending on server configuration.
One thing to try is to remove the [Serializable] attribute as the [DataContract(Namespace = "http://mlpt-web.com/CRM/services")] will handle serialization more specific to your configuration. You don't need both.


text:
Q: could not get the path on live server symfony 2 I have write a php code that upload the image to web/uploads/slider which i get through
$dir = $this->container->getParameter('assetic.write_to') . '\uploads\slider';

In my local server(windows apache) it works fine and upload as expected but the problem comes when i used it in live server it creates a folder name 'web\uploads\slider' in a project folder and upload a file in it

A: You need to use forward slashes:
$dir = $this->container->getParameter('assetic.write_to') . '/uploads/slider';

Backslashes only work on Windows OS but forward slashes work on any OS (including Windows).


text:
Q: What is horizontal inheritance? Not once I heard about the so called horizontal inheritance, I tried googling it but didn't find anything that would clarify it for me. What is the fundamental difference between the two types of inheritance?

A: Based on the link and comments above, there is no such thing as "horizontal inheritance".
What there is ... is "horizontal inheritance mapping".  And that actually means is horizontal mapping of inheritance to tables.  As distinct from flat or vertical mapping of inheritance to tables.  In other words the "horizontal" versus "vertical" versus "flat" is about the scheme for mapping ... not the nature of inheritance itself.

A: I think this term is used in php, it is supposed to resolve somehow the problem of multiple inheritance through the use of "trait <-> use" keywords
take a look :
"Traits use a form of inheritance that is known as horizontal inheritance in which the code from the trait is included in the classes in which it is used. It is pretty much like using 'require'or 'include' in the classes to include code from the outside, albeit not hackish."
From : "The essentials of Object Oriented PHP: Learn, practice, and apply" by Joseph Harosh


text:
Q: Cannot resolve symbol AppCompatActivity в Android Studio Всем, привет!
Установил Android Studio на машину где нет интернета (обновить код через SDK Manager нет возможности)
Создал новый проект и ...  красным подсветились все классы. Сообщения об ошибках выглядят таким образом:
cannot resolve symbol "AppCompatActivity"

File->InvalidateCahces и Build->Clean Project не помогают.
в dependencies стоит:
compile "com.android.support:appcompat-v7:23.1.1"

как решить проблему?
Спаcибо.

A: "Установил Android Studio на машину где нет интернета" Очевидно, что нужно подключить интернет, ибо строка compile "com.android.support:appcompat-v7:23.1.1" гикорит Gradle, чтобы тот скачал эту библиотеку и скомпилировал, а как вы это собираетесь сделать, если интернета нету. Можно решить и иначе, вы скачиваете где-нибудь AppCompact либу и добавляете её в свой проект в качестве библиотеки, т.е. имортите не через gradle, а как файл, чтобы он был у вас виден как проект, далее в gradle добавить строку на подобие этой compile project(":Имя вашего проекта-библиотеки")


text:
Q: Laravel - Multi Auth Email Confirmation I'm using Laravel Hesto Multi Auth package to create multiple auth. I have not used the default auth, but created user, admin, support, professionals guards with laravel hesto
Now im trying to implement Laravel email confirmation using this package
This send me a activation link to my email. However when that routes to http://localhost:8000/confirmation/2/jOVjV2xkfRZqAM4nwjAKdwTwn2 it shows an error
Method App\Http\Controllers\Auth\RegisterController::confirm does not exist.

It should check in App\Http\Controllers\UserAuth\RegisterController::confirm
How to change this? Also would like to know how to implement the same for other guards

A: If you check https://github.com/bestmomo/laravel-email-confirmation/blob/master/routes/web.php you will note they have defined routes for this. You can override this by doing the following:
1) Disable auto-discover for the package on the dont-discover portion of your compopser.json file.
2) Register the package's service provider before App\Providers\RouteServiceProvider::class so you can override the registered routes on your application.
3) Go ahead and register the routes you want, which will probably be like this:
Route::get('confirmation/resend', 'UserAuth\RegisterController@resend');
Route::get('confirmation/{id}/{token}', 'UserAuth\RegisterController@confirm');

That should do it or at least get you in the right track.
Also ensure you use the package Traits on your UserAuth controllers.


text:
Q: Filter based on ranking I have 2 Table Sign up and Like.I want filter based on top like. If user has more like then other it should be on top.
Two Table
1 First Signup :
`signup`(`id`, `first_name`, `last_name`, `mobile`, `password`,
`confirm_password`, `email`, `username`, `country_id`, `state_id`,
`city_id`, `gender`, `occupation_id`, `personal_address`,
`personal_description`, `personal_status`, `business_name`,
`business_categories_id`, `business_phone`, `business_email`,
`business_address`, `business_website`, `services`, `business_status`,
`personal_profile_photo`, `business_profile_photo`, `created_on`, `otp`,
`status`)

2 Like Table : b_like(id, userid, profile_id, type, timestamp)
i want filter based on top likes

A: Guessing that 'id' and 'profile_id' have the same value, you should do something like this:
SELECT table_signup.id, COUNT(table_b_like.profile_id) count
FROM signup table_signup
LEFT JOIN b_like table_b_like ON table_signup.id = table_b_like.profile_id
GROUP BY table_signup.id
order by count desc

You get the id (and count) of users from signup table that have the most likes in b_like table


text:
Q: Rotating geometry and shifting angles in clockwise direction in PostGIS? I have point (cp) and line layer (one row each) in my PostgreSQL database. The point (cp) is on line layer and the direction of line is 112 degrees.

For cp, following code generates a buffer of 50 meters and divides the buffer (circle) into 12 sections (pie-like wedges):
WITH circle AS
    (
    SELECT gid, ST_Buffer(geom, 50,25) as geom FROM cp
    ),
dump AS (
    SELECT gid, (ST_DumpPoints(ST_Buffer(geom,60,3))).geom as geom
    FROM cp
    UNION ALL
    SELECT gid, geom FROM cp
    ),
triangles AS    (
    SELECT gid, (ST_Dump(ST_DelaunayTriangles(ST_Collect(geom),0, 0))).geom geom
    FROM dump
    GROUP BY gid
    )
 SELECT a.gid as pt_id, ST_Intersection(a.geom, b.geom) geom
 FROM circle as a, triangles as b

The output of above code (with line and point layer) is:

I need to rotate circle segments geometry i.e., I need to align 1st segment with line direction (112 degrees) such that starting from this direction, all other segments follow a step of 30 degrees till last segment. For example, 112, 142, 172 and so on. The desired output scenario could be like:

I am aware that ST_Rotate() function rotates the geometry but it does in counterclock wise according to this link while I need to rotate circle segments according to line direction (clockwise).
Can anyone suggest me how to use ST_Rotate() for clockwise rotation?


text:
Q: 'Upload a file'-button in rich text editor does not insert link to document if the document is uploaded to a document library with extra columns This was tested on a non-branded, out of the box enterprise wiki page. The behavior is consistent.
Case 1 (as expected): I have an unmodified document library 'Documents' and a pages library 'Pages' with wiki-pages. When I edit a wiki page and in the ribbon choose 'Upload a document', I get the dialog for uploading and choose to upload to the Documents-library. I'm then back on the wiki-page where an document type icon and a link to the uploaded document have been inserted in the text.
Case 2: Same as case 1, but I now have added a site column, e.g. 'URL', to the document library. When I choose to upload a file to the document library I then get another form asking me to fill out the value of the 'URL'-column. After saving the form, I'm returned to the wiki-page, but no link to the uploaded document have been added to the text.
With the browser console open, I see that I get a javascript-error in the file sp.ui.rte.js "Uncaught TypeError: Cannot read property 'newFileUrl' of undefined" after clicking save. As this file is minimized it's a bit hard to specify exactly where it is, but it is in the function $FG_0.
var b=document.createElement("A");
b.href=a.newFileUrl;

Workaround for now is to remove the extra columns of the document library, but that is unfortunate. Any ideas if it's possible to fix?

A: After a long research, I was able to figure out a solution and it worked for me.
What I tried was,
Went to advanced settings of the document library and selected Yes for 'Allow management of content types?'
After doing all my adding and removing content type changes finally I set this to 'No'. It worked.


text:
Q: Matplotlib axis labels How do I reduce the number of ticks on the axes with matplotlib (without using pyplot)?
    self.figure = Figure((2.0, 2.0))
    self.canvas = FigureCanvas(self.figure)
    self.canvas.setParent(self)
    self.axes = self.figure.add_subplot(111)
    self.figure.subplots_adjust(left=0.18)
    self.axes.fill(x, y, 'b')

now....?

A: In pyplot it was xticks(...), but I couldn't find that in matplotlib.
It turns out, you have to use set_xticks


text:
Q: DNS: MX listing points to google apps and A listing to my own server. Can I send emails from my own server without being classified as spam? Linux DNS networking question:
If an MX record points to IP address 111.111.111.111 and A record of a domain points to 222.222.222.222, can I still send emails from 222.222.222.222 on the behalf of a domain, without being classified as spam? The reason being this: I'd like to use javax.mail to send newsletters from the application, but to receive personal emails on Google Apps to avoid possible Linux sendmail/qrunner exploits.

A: MX is to specify where incoming mail for that domain should be sent to.  You can send mail on behalf of that domain from a completely separate host.
The problem with mail from 222.222.222.222 being classified as spam doesn't have much to do with the MX record, but to other factors:

*

*whether 222.222.222.222 has a PTR (reverse DNS) record associated with it

*whether that IP is in some black listed block

*whether there is an SPF record for the domain saying that it is a legitimate sender of mail for the domain

*whether you are signing the outgoing mail with DKIM

There are probably other things I haven't thought of off-hand.  These are factors other than how spammy the contents of the email are, by the way.
One thing to keep in mind is that there are third party mass mailing services (e.g., Sendgrid) that have put some resources to solving these problems on your behalf.

A: Classified as spam by what (or who)?  Sounds like it's going to be a question of how your recipients do their spam classification, and whether they use a reverse MX lookup.
If you want to be safe, you could always add an MX record for your domain's mailserver at a high priority value (lower numeric values are preferred).  Your mail sever wouldn't even have to do anything, short of sending the HELO reply you want, to validate your domain against this kind of anti-spam check.
I'm afraid I don't know how commonly used reverse MX-lookups are as a spam-fighting technique, because that's all up to the mail admin(s) at the recipient's domain.  Might be a good idea to check with the mail providers of your newsletter recipients (or at least the most common mail providers on your list) to see if you're going to run afoul of their anti-spam checks or not.


text:
Q: Value of a child in firebase database showing null i usually work with firebase database like a constant 'Name' and a variable 'Value' but now according to my new project im trying to make both of it as variables which means that both aren't decided by me but the user... like this - https://ibb.co/cGh3qJ
My error - https://ibb.co/hiJ4xy
Code
Fetching Data
Results results;
String Name, Score;
private void fetchResults() {
    mDatabaseReference.child("Users").child(id).child("Quiz").child("Results").child(id).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
                Name = childDataSnapshot.getKey().toString();
                Score = String.valueOf(childDataSnapshot.child(Name).getValue(Results.class));
                results = new Results(Name, Score);
                resultsList.add(results);
                mAdapter.notifyDataSetChanged();
            }
            mAdapter.notifyDataSetChanged();

                    }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException();
        }
    });
}

Class
public class Results {
private String Name;
private String Score;

public Results() {
}

public Results(String Name, String Score) {
    this.Name = Name;
    this.Score = Score;
}

public String getName() {
    return Name;
}

public void setName(String name) {
    Name = name;
}

public String getScore() {
    return Score;
}

public void setScore(String score) {
    Score = score;
}

}
Can anyone point out where i have gone wrong please... before i used to not get the name also and somehow i managed to get it and now struggling with the score
Error
Process: com.appmaster.akash.messageplus, PID: 8881
                                             java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
                                                 at com.appmaster.akash.messageplus.TakingQuizDone$1.onDataChange(TakingQuizDone.java:68)
                                                 at com.google.android.gms.internal.zzduz.zza(Unknown Source)
                                                 at com.google.android.gms.internal.zzdwu.zzbvb(Unknown Source)
                                                 at com.google.android.gms.internal.zzdxa.run(Unknown Source)
                                                 at android.os.Handler.handleCallback(Handler.java:742)
                                                 at android.os.Handler.dispatchMessage(Handler.java:95)
                                                 at android.os.Looper.loop(Looper.java:157)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5571)
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)

A: Change this:
 Score = String.valueOf(childDataSnapshot.child(Name).getValue(Results.class));

into this:
  Score =childDataSnapshot.child(Name).getValue().toString();

Your datasnapshot is at the userid, then you iterated inside of it and used getKey() to be able to retrieve the name, then to retrieve the value just get the value of the child Name.

A: You need to change
Score = String.valueOf(childDataSnapshot.child(Name).getValue(Results.class));

into this:
Score = (String) childDataSnapshot.getValue();

The problem with your implementation was that you were already iterating over the children of dataSnapshot. So you didn't need to give the key and get the value, the childDataSnapshot has the value.


text:
Q: How to insert data in symfony table? I have made a symfony form and I used:
$conn->insert('Invoiceshasitems', array('Invoiceitemsid' => '$items'));

for data insertion but it not works ho i do insert data from symfony controller.
here is my code:
$itemscounter = $request->request->get('itemscounter');
if(isset($_SESSION['invoiceid'])) {
    $invoiceid=$_SESSION['invoiceid'];
    //echo $invoiceid;
    //exit;
}
//$entity= new Invoiceshasitems();
if($request->isXmlHttpRequest()) {

    if($itemscounter > 1){

        for($i=1; $i<=$itemscounter; $i++){

            if($i==1){
                $items = $_POST['items'];
            }else {
                $items.$i = $_POST['items'.$i];
            }
        }
    }else{

        $items = $_POST['items'];
        $conn->insert('Invoiceshasitems', array('Invoiceitemsid' => '$items'));
    }
}

A: You can use native query in Doctrine, there is some docs here: http://docs.doctrine-project.org/en/latest/reference/native-sql.html
For your example the code is something like that:
$rsm = new ResultSetMapping();
$query = $this->_em->createNativeQuery('INSERT INTO Invoiceshasitems SET Invoiceitemsid = ?', $rsm);
$query->setParameter(1, $items);

$result = $query->getResult();


text:
Q: Java desktop notifications Ubuntu Ubuntu has desktop notifications at the bottom of the screen. My question is how to use it with Java. I couldn't find a solution for this. I use Gnome-shell, but does it work on the same way with Unity? And has Debian also the same notification system? And if you know the answer, I hope you will give an example so I'll understand it better.

A: The SystemTray and TrayIcon should do what you need. If not, maybe Twinkle will:

Twinkle lets you create desktop notifications from your Java Swing
  application with ease!

A: Read the section from the Swing tutorial on How to Use The System Tray for a working example.


text:
Q: Copy Constructor for MyString causes HEAP error. Only Gives Error in Debug Mode So, I've never experienced this before.  Normally when I get an error, it always triggers a breakpoint.  However, this time when I build the solution and run it without debugging (ctrl+F5), it gives me no error and runs correctly.  But when I try debugging it (F5), it gives me this error:
HEAP[MyString.exe]: HEAP: Free Heap block 294bd8 modified at 294c00 after it was freed
Windows has triggered a breakpoint in MyString.exe.

This may be due to a corruption of the heap, which indicates a bug in MyString.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while MyString.exe has focus.

The output window may have more diagnostic information.

This assignment is due tonight, so I'd appreciate any quick help.
My code is here:
https://gist.github.com/anonymous/8d84b21be6d1f4bc18bf
I've narrowed the problem down in the main to line 18 in main.cpp ( c = a + b; )  The concatenation succeeds, but then when it is to be copied into c, the error message occurs at line 56 in MyString.cpp ( pData = new char[length + 1]; ).
The kicker is I haven't had a problem with this line of code until I tried overloading the operator>>.  I've since scrapped that code for the sake of trying to debug this.
Again, any help would be appreciated!

A: Let's go through line 18:

1. In line 17 you create string c with dynamically allocated memory inside.
2. You make assignment: c = a + b:
  2.1. Operator+ creates LOCAL object 'cat'.
  2.2. cat's memory is allocated dynamically.
  2.3. cat becomes concatenation of two given strings.
  2.4. Operator+ exits. cat is LOCAL object and it's being destroyed.
    2.4.1. cat is being destroyed. cat's destructor runs.
    2.4.2. destructor deletes pData;
    2.4.3. After delete you make *pData = NULL. //ERROR - should be pData = NULL (1)
  2.5. c is initialized with result of operator+.
  2.6. operator= calls copy().
  2.7. copy() allocates new memory without checking the current one. //ERROR - memory leak (2)

(1)
pData is char*. In destructor we have: delete[] pData (deletes memory) and then *pData = NULL.
Because pData is a pointer, *pData is same as pData[0]. So you write to already freed memory. This is the cause of your error.
(2)
Additional problem. Copy() overwrites current memory without checking. Should be:
copy()
{
    if(this->pData)
    {
        delete this->pData;
    }
    //now allocate new buffer and copy
}

Also, when dealing with raw bytes (chars), you don't want to use new() and delete(), but malloc() and free() instead. In this case, in functions like copy(), instead of calling delete() and then new(), you would simply use realloc().
EDIT:
One more thing: errors caused by heap damage usually occur during debugging. In release binary, this will simply overwrite some freed (and maybe already used by someone else) memory. That's why debugging is so important when playing with memory in C++.


text:
Q: Rank of quaternionic matrix Is there a method of founding of rank of quaternionic matrix by Dieudonne's determinants ?

A: I think that the method is exactly the same as in the commutative case. The rank of a quaternionic matrix (or more generally, over any not necessarily commutative field) is equal to the maximal size of a minor with non-zero Dieudonne determinant. The proof of this fact is essentially the same as in the commutative case. The key point is: given a square quaternionic matrix, its rows (equivalently, columns) are linearly independent if and only if the Dieudonne determinant does not vanish.
Unfortunaly I do not have a reference for the answer to your question. But non-commutative linear algebra and Dieudonne determinants are discussed in the book "Geometric algebra" by
E. Artin.


text:
Q: Images not showing in pug template I have put the images folder inside the views folder and added the relative path to the images but the images are not loading on the html page. I have tried multiple options like putting the folder outside views, giving absolute path but nothing worked. Can anyone please take a look and help me figure out what the error is?
Screenshot of my directory structure
I have tried many options but nothing worked.
Screenshot of webpage

A: Static files are processed differently from other types of routes in an Express application. A Http path for static files such as abc.com/img/bg.jpg does not map to a file bg.jpg in the views folder. Where it maps to is specified by the express.static function. So, something like:
const express = require("express");
const app = express();
const path = require("path");
app.use(express.static(path.join(__dirname, "public"));

will map the Http path / for static files to the folder public in your application's launch folder.
See __dirname for more information on this parameter.


text:
Q: pandas dataframe in a loop I have a big .csv file that I'm reading into a pandas dataframe.  Then I loop through the file and once I find the values I'm looking for I use the dataR = df.append(data).  There are 2 columns in the .csv file that I read one of the (column A ) where the values go from 1 to 3 and then it repeats again from 1 to 3 and again like this: Notice that column B does not repeat.
+-----+---+---+--+--+
|     | A | B |  |  |
+-----+---+---+--+--+
| 288 | 1 | 4 |  |  |
+-----+---+---+--+--+
| 245 | 2 | 3 |  |  |
+-----+---+---+--+--+
| 543 | 3 | 6 |  |  |
+-----+---+---+--+--+
| 867 | 1 | 9 |  |  |
+-----+---+---+--+--+
| 345 | 2 | 7 |  |  |
+-----+---+---+--+--+
| 122 | 3 | 8 |  |  |
+-----+---+---+--+--+
| 233 | 1 | 1 |  |  |
+-----+---+---+--+--+
| 346 | 2 | 6 |  |  |
+-----+---+---+--+--+
| 765 | 3 | 3 |  |  |
+-----+---+---+--+--+

What I want to do is instead of appending the values as rows I would like to append them as columns like this:
+-----+---+---+-----+
|     | A | B | C   |
+-----+---+---+-----+
| 288 | 1 | 4 | 9   |
+-----+---+---+-----+
| 245 | 2 | 3 | 7   |
+-----+---+---+-----+
| 543 | 3 | 6 | 8   |
+-----+---+---+-----+
| 867 |NaN| 9 | 1   |
+-----+---+---+-----+
| 345 |NaN| 7 | 6   |
+-----+---+---+-----+
| 122 |NAN| 8 | 3   |
+-----+---+---+-----+
| 233 |NaN| 1 | NaN |
+-----+---+---+-----+
| 346 |NaN| 6 | NaN |
+-----+---+---+-----+
| 765 |NaN| 3 | NaN |
+-----+---+---+-----+

Is there a flag to set for this?  dataR = df.append(data, flag=?)
Thanks

A: Use concat with axis=1 instead of append.
See examples here.


text:
Q: Moving the .git directory wihout moving the files I am using to track changes to some linux system files (/etc/*), I had the .git in /etc
but now I decided to move it to / as I want to track files that are outside /etc (both /etc and / are in the same filesystems...), I did that and tried to re-add the same files with:
git add $(git status | awk '/deleted/ { print "etc/"$3 } ')

But it does not appear to be working as I hoped as now the are two lists one with a list of "new files" and one with a list of "deleted files", if commit now I will lose all the history
for the files....
What would have been the correct steps?
Thanks!
Antonio

A: Use git subtree (installation instructions if not already installed).
Create a new repository at / and merge it with the existing one in /etc:
$ cd /
$ git init
$ git subtree --prefix etc /etc master

A: Ther are similar questions on SO:
My Git repository is in the wrong root directory. Can I move it? (../ intead of ./)
Moving a git repository
And there is no way of chaning directory without losing history of files.


text:
Q: JAWS reads "link" between every line of text in a table cell I am facing issue while reading multiple lines in a single table cell. I am using Insert+Shift followed by key T to move to the table layer. After this, I am using down arrow key to read the table contents. Once it comes to the cell which has multiple  tags, it reads in this manner:
content of line1, "link", "content of line2".
In the following example it reads "Alfreds Futterkiste, link, Nice to test".
How can I get rid of the text "link" in between and make the text "Nice to test" to be read immediately when user presses down arrow key after reading "Alfreds Futterkiste"?
Please find the code below:
<!DOCTYPE html>

<button>Click</button>

    Company
    Contact
    Country

    Alfreds Futterkiste
Nice to test

    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

A: You should remove tabindex attribute from the table tag.


text:
Q: Translating a MySQL query to DQL This question is a follow-up to what I asked (and received a working answer to) here.
How can I translate this into DQL?  The docs on JOINs is a bit confusing to me.

EDIT:
I'm using Doctrine with Symfony2, and have the following entities:
Question:
/**
 * @ORM\Entity
 * @ORM\Table(name="Question", indexes={@ORM\Index(name="id_idx", columns={"id"})})
 */

class Question
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string question
     *
     * @ORM\Column(name="question", type="string", length=255)
     */
    private $question;

    /**
     * @var array scores
     *
     * @ORM\OneToMany(targetEntity="Score", mappedBy="question")
     */
    private $scores;

    // getters and setters
}

Score:
/**
 * @ORM\Entity
 * @ORM\Table(name="Score", indexes={@ORM\Index(name="id_idx", columns={"id"})})
 */

class Score
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var integer $question
     *
     * @ORM\ManyToOne(targetEntity="Question", inversedBy="scores")
     * @ORM\JoinColumn(name="question_id", referencedColumnName="id")
     */
    private $question;

    /**
     * @var float score
     *
     * @ORM\Column(name="score", type="float")
     */
    private $score;

    // getters and setters
}

I've used the following query:
$query = $em->createQuery('SELECT q AS question, AVG(s.score) AS average FROM CMSBundle:Question q JOIN q.scores s GROUP BY q.id ORDER BY q.id ASC');

$questions = $query->getResult();

However, with that query, $questions contains 0 elements.  I'm not getting any errors, either (at least, none that PhpStorm can find in its debugger).
With a lack of feedback on why I'm getting literally nothing from my query, I'm at a bit of a loss.  Any help would be appreciated.

A: I remember coming across this exactly problem just last week. I spent a long time figuring out how do this and I managed to come up with the following DQL. Add a new method to your Question's repository class.
I've had to tweak my own code to match the question so no guarantee it work work but give it a try.
<?php

namespace Acme\CMSBundle\Entity;

use Doctrine\ORM\EntityRepository;

class QuestionRepository extends EntityRepository
{
    /**
     * @return array
     */
    public function findAverageScoresPerQuestion()
    {
        $dql = <<<SQL
SELECT
    q question,
    AVG(s.score) average
FROM
    Acme\CMSBundle\Entity\Question q,
    Acme\CMSBundle\Entity\Score s
WHERE
    s.question = q.id
GROUP BY q.id
ORDER BY q.id ASC
SQL;

        $q = $this->_em->createQuery($dql);

        return $q->getResult();
    }
}

When rendering the result with Twig from the controller, the question properties are nested one level deeper
public function averageScoresAction()
{
    $em = $this->getDoctrine()->getManager();
    $questions = $em->getRepository('AcmeCMSBundle:Question')->findAverageScoresPerQuestion();

    return $this->render('AcmeCMSBundle:Question:questions.html.twig', array(
        'questions' => $questions
    ));
}

In questions.html.twig

        Question
        Average Score

    {% for q in questions %}

        {{ q.question.question }}
        {{ q.average }}

    {% else %}

        No results found

    {% endfor %}


text:
Q: Apply Interaction using Box2d in iPhone App I am currently using box2D and UIKit to create an app. Gravity is working great with the objects that I have added. However, I would like the objects to have user interaction through touches. Most of the articles and guides online refer to box2d and cocos2d (cocos2d I am not using).
Can anyone provide some help in getting TouchesBegan, TouchesMoved, and TouchesEnded to recognize and react to the Box2d objects.
Thanks for any help!

A: Think about it like for a mouse : you have three events that could be called onMouseDown, onMouseDrag and onMouseUp... But you have... multiple mouses...
Then, what you want to do with a mouse is :

*

*check if a body is under your "mouse" when it clicks ;

*create a mouse joint if there's a body under the mouse, and attach it to this body and to your "mouse" (anchors of your b2MouseJoint) ;

*destroy the mouse joint when the "mouse" is up.

You can create multiple mouse joints in box2d.


text:
Q: Storing Params in a Session with Nested Resource I am using Rails 4.
I have subarticles nested into articles. I am storing all of the form data from subarticles in a session when a user needs to create an account before submission.
Here is what I am using (subarticles_controller):
def create
  if current_user.nil?

  session[:subarticle] = params

  redirect_to new_user_session_path
end

Then after the user signs up, it creates the subarticle with the stored params using
if session[:subarticle].present?
  @subarticle = current_user.subarticles.create(session[:subarticle]["subarticle"])

  session[:subarticle] = nil

  flash[:notice] = "Awesome, you are logged in and your answer is undergoing review."

  edit_user_registration_path
end

I am having trouble, however, saving the article_id in which the subarticle is created under. Can someone point me in the right direction to doing this?

A: A better approach could be to save the (sub)articles created by guest users in the database.
class SubArticlesController < ApplicationController

  before_action :set_article, only: [:show, :edit, :update, :destroy]

  # ...

  def create
    @subarticle = Article.new(article_params) do |a|
      if current_user
        a.user = current_user
      else
        a.token = SecureRandom.hex
      end
    end
    if @subarticle.save
      if @subarticle.user
        redirect_to @subarticle
      else
        session[:after_sign_in_path] = edit_article_path(@subarticle, token: @subarticle.token)
        redirect_to new_user_session_path, notice: 'Please sign in to finalize your article.'
      end
    else
      render :new
    end
  end

  def edit
    if @subarticle.user.nil? && @subarticle.token != params[:token]
      redirect_to root_path, alert: 'You are not authorized.'
    end

    flash[:notice] = 'Please press save again to publish your post.' unless @subarticle.user
    render :edit
  end

  def update
    # The @subarticle.token should be included in the edit form
    unless @subarticle.user && @subarticle.token == params[:sub_article][:token]
      # let the current user claim the article
      @subarticle.user = current_user
    end

    if @subarticle.update(article_params)
      redirect_to @subarticle
    else
      render :edit
    end
  end

  private

  def set_article
    @subarticle = Article.find(params[:id])
  end

  def sub_article_params
    params.require(:sub_article).permit(...)
  end
end

So here we we instead give the user a link to the edit page for the article where he/she can "finish" the article after logging in.
Since a malicious user could potentially "steal" unclaimed articles by guessing the id and entering the edit url we add a random token which we store in the database with the article and add to the url. Not 100% foolproof but at least better.
To make this work you will also need to add a token field to your form:
<%= form_for(@subarticle) do |f| %>
  ...
  <%= f.hidden_field :token %>
  ...
<% end %>

The reason you might want to consider this is because session storage is often memory based and if you have a large amount of traffic storing the entire params hash in the session will exhaust the server memory. Also you should reset the session before logging a user in or out to avoid session fixation.
We do have a few issues though - first we don't want to accumulate a bunch of "unclaimed" articles if the user (or a bot) never logs in. The easiest way to do this is to setup a cron job to delete articles over a certain age without an associated user.
You would also want to filter any articles without a user from you show/index action.


text:
Q: How can I use my .conll file from nlp parser for feature selection I have an outputted .conll format file from Malt Parser, which is using the engmalt.linear-1.7.mco training model. My original input was a large text file of sentences. How can I use this file for feature selection?
I am using python with Scikit-learn (currently using tfidf bag of words to select features). However, I want to utilize nlp, by for example, only searching for adjectives. How can I do this with a conll file?

A: The output of a parser in the CoNLL-X format provides a separate column for the part-of-speech tags. For example, if you parse the sentence

"I want to select adjectives only, and disregard other tags."

the output might be as follows:
1   I           _   PRP PRP _   2   nsubj   _   _
2   want        _   VB  VBP _   0   null    _   _
3   to          _   TO  TO  _   4   aux _   _
4   select      _   VB  VB  _   2   xcomp   _   _
5   adjectives  _   NN  NNS _   4   dobj    _   _
6   only        _   RB  RB  _   4   advmod  _   _
7   ,           _   ,   ,   _   2   punct   _   _
8   and         _   CC  CC  _   2   cc  _   _
9   disregard   _   VB  VB  _   2   conj    _   _
10  other       _   JJ  JJ  _   11  amod    _   _
11  tags        _   NN  NNS _   9   dobj    _   _
12  .           _   .   .   _   2   punct   _   _

Columns 4 and 5 show the coarse- and fine-grained part-of-speech tags, respectively. If you only want to select adjectives, you need to just pick words that have JJ as their coarse-tag in column 4.
Once you have selected the specific words according to whatever your selection criteria is, you can proceed to construct the vectors in the usual way.
P.S. I assumed your query was mostly to do with the CoNLL format, and not about how to extract the adjectives (which, of course, can be done by tab-splitting rows or regex matching -- there are several questions and answers on SO pertaining to the pythonic ways of doing those).


text:
Q: How to remove Ubuntu partition and boot menu? how do I completely remove the Ubuntu partition and the boot menu so I can just keep the Windows 7 partition and boot directly into it? I want to remove it all and so I can go and reside the partition also.

A: First hit from Google:
http://www.makeuseof.com/tag/how-to-safely-uninstall-ubuntu-in-windows-dual-boot-environment/
Please look for answers before posting a question, many have already been answered.


text:
Q: sqldf missing value where TRUE/FALSE needed In sqldf_0.4-7.1 I get:
 Error in if (.allows_extensions(db)) { :
  missing value where TRUE/FALSE needed

Where is the package that fixes the bug? My error is the same as the one generated by:
sqldf("select * from warpbreaks limit 6")

I downloaded sqldf v0.4-7.1 from CRAN but with newer source does not help some 8 hours later.

A: Problem is with that sqldf version.  Fixed version should be already on the cran so you will need to update your sqldf package.
Download file sqldf_0.4-9.tar.gz and in console run:
R CMD INSTALL sqldf_0.4-9.tar.gz


text:
Q: How to train DeepLearning4J model Using a Java Object... Cant find assistance anywhere on this question I am working on a Phrase Input and Response System (Similar to SIRI) want to train a Model on how to detect a phrase category, i.e. command, misc., special, using a Phrase[] Java object from Apache OpenNLP. How do I do that? my only experience with deeplearning4j with using .csv files to train models. How do I use a set of java objects to train models? in DL4J?
The examples i am looking at
The only experience with ML is apache Open NLP. And as for the examples, most of them are Outdated (the outdated ones are some of the first websites like baeldung.com or medium.com to pop up via google search)!
The other ones use Java dependencies that don't exist in my maven repositories (https://github.com/eclipse/deeplearning4j-examples) another reason, these don't work, is that, the examples are for eclipse and i use Netbeans IDE, so i can't just import the code and have it run, without some sort of problem.
I am using DeepLearning4J 1.0.0 Beta 7 and am using NetBeans IDE 12.0. The programming language i use for DL4J and Apache Open NLP is Java
Apache OpenNLP experience
I am familiar and use everything (all the way up to Parsing (#10 in the table of contents)) shown in the apache OpenNLP manual: (https://opennlp.apache.org/docs/1.9.3/manual/opennlp.html)


text:
Q: Is there a way to have my checkboxes alinged horizontally with a fixed number using bootstrap? I don't want my checkboxes under each other but alinged next to each other. But only in columns of 5 for example.
At the moment I have something like this:
Checkboxes vertical
But i want this:
[x] label [x] label [x] label [x] label [x] label
[x] label [x] label [x] label [x] label [x] label

This is my code:

              Klassen

              @Html.EditorFor(x => x.CheckBoxKlassen)

Already tried with formcheck inline etc, but not giving result.
 EDIT:
Rendered code:
<input id="CheckBoxKlassen_0__ID" name="CheckBoxKlassen[0].ID" type="hidden" value="61" />
<input id="CheckBoxKlassen_0__Display" name="CheckBoxKlassen[0].Display" type="hidden" value="BIO 1Aa" />
<input data-val="true" data-val-required="The WasChecked field is required." id="CheckBoxKlassen_0__WasChecked" name="CheckBoxKlassen[0].WasChecked" type="hidden" value="False" />
<input data-val="true" data-val-required="The IsChecked field is required." id="CheckBoxKlassen_0__IsChecked" name="CheckBoxKlassen[0].IsChecked" type="checkbox" value="true" />
BIO 1Aa

<input id="CheckBoxKlassen_1__ID" name="CheckBoxKlassen[1].ID" type="hidden" value="64" />
<input id="CheckBoxKlassen_1__Display" name="CheckBoxKlassen[1].Display" type="hidden" value="BIO 1Ab" />
<input data-val="true" data-val-required="The WasChecked field is required." id="CheckBoxKlassen_1__WasChecked" name="CheckBoxKlassen[1].WasChecked" type="hidden" value="False" />
<input data-val="true" data-val-required="The IsChecked field is required." id="CheckBoxKlassen_1__IsChecked" name="CheckBoxKlassen[1].IsChecked" type="checkbox" value="true" />
BIO 1Ab

<input id="CheckBoxKlassen_2__ID" name="CheckBoxKlassen[2].ID" type="hidden" value="58" />
<input id="CheckBoxKlassen_2__Display" name="CheckBoxKlassen[2].Display" type="hidden" value="BIO 1Ac" />
<input data-val="true" data-val-required="The WasChecked field is required." id="CheckBoxKlassen_2__WasChecked" name="CheckBoxKlassen[2].WasChecked" type="hidden" value="False" />
<input data-val="true" data-val-required="The IsChecked field is required." id="CheckBoxKlassen_2__IsChecked" name="CheckBoxKlassen[2].IsChecked" type="checkbox" value="true" />
BIO 1Ac

<input id="CheckBoxKlassen_3__ID" name="CheckBoxKlassen[3].ID" type="hidden" value="71" />
<input id="CheckBoxKlassen_3__Display" name="CheckBoxKlassen[3].Display" type="hidden" value="BIO 1Ad" />
<input data-val="true" data-val-required="The WasChecked field is required." id="CheckBoxKlassen_3__WasChecked" name="CheckBoxKlassen[3].WasChecked" type="hidden" value="False" />
<input data-val="true" data-val-required="The IsChecked field is required." id="CheckBoxKlassen_3__IsChecked" name="CheckBoxKlassen[3].IsChecked" type="checkbox" value="true" />
BIO 1Ad

<input id="CheckBoxKlassen_4__ID" name="CheckBoxKlassen[4].ID" type="hidden" value="59" />

A: Here is the working example , you could refer to and make the modification according to your need.
Model
 public class CheckBoxKlassen
{
    public int Id { get; set; }
    public string Display { get; set; }

    public bool IsChecked { get; set; }
}

public class CheckBoxViewModel
{
    public IList<CheckBoxKlassen> CheckBoxKlassen { get; set; }
}

CheckBoxList.cshtml , use the CSS to align checkboxes horizontally and change the width percent of
 to adjust the number of checkboxes per line.
@model WebApplication1.Models.CheckBoxViewModel

            Klassen

            @for (var i = 0; i < Model.CheckBoxKlassen.Count(); i++)
            {

                <input type="checkbox" asp-for="CheckBoxKlassen[i].IsChecked" value="@Model.CheckBoxKlassen[i].Id" />
                @Model.CheckBoxKlassen[i].Display

            }

Controller , get the data of checkboxlist
public IActionResult CheckBoxList()
    {
        CheckBoxViewModel model = new CheckBoxViewModel()
        {
            CheckBoxKlassen = _context.CheckBoxKlassen.ToList()
        };
        return View(model);
    }

A: I personally prefer using flexbox for cases like this. You can check a super easy, fast explaining guide here. This in combination with the CSS calc function. I find one of the best ways to do styling.
This CSS code should work:
div.form-check { display: flex; flex-wrap: wrap; width: 100%; }

div.form-check div { flex-basis: 20%; }


text:
Q: Best approach for an independent scrolling cells in a grid-like view? I've been racking my brain on this for a few days and I'm unsure the best method to use to acheive this
I basically want an Android View that has a grid-like view, but I can independently scroll the cells of this grid both vertically and horizontally. I am going to need the ability to click the "cells" (which need to be views of some description). I have a potato-quality drawing to try and better explain what I mean :)
I've implemented this so far and it's sort of working using a ViewGroup, and essentially adding all the views and calculating where they should be, and then using the onTouch event to handle moving the views (based on the dX and dY of the view, but it doesn't feel stable at all, and the events are randomly picked up (because i'm trying to decide if the ViewGroup should handle the onTouch event of the "cell" (view) should handle it in the onInterceptTouch, which isn't really a good way of doing this I know. I'm at the stage where I need to completely re-write it I think, but that got me thinking is this the way it should be being done do you think? I thought about using a RecyclerView and some sort of custom LayoutManager to handle the movement of the cells, which in my mind sounds like a better way of doing it, but I don't really know how I would start using that and how it would meet all the requirements of this view. Even so, is this the better way of doing it?
Thanks


text:
Q: telebot (python). Не выполняется вызов атрибута callback_data из за атрибута url в telebot.types.InlineKeyBoardButton import telebot
from telebot import types
insertSubInline = types.InlineKeyBoardMarkup()
join = types.InlineKeyBoardButton(text="Пройти на канал", callback_data = "joinSub", url="https://t.me/namechannel")
insertSubInline.add(join)

@bot.callback_query_handler(func = lambda call: True)
def answer(call):
    pass

При использовании InlineKeyBoardButton, атрибут callback_data не срабатывает, как я понял из за того, что я указываю адрес (url) для пересылки на другой канал в атрибутах InlineKeyBoardButton.
Какого причина его не правильной работы?
Мне нужно во время переадресации на другой канал вызывать определенную функцию для проверки/сбора данных
или
отдельная от InlineKeyBoardButton(без атрибута url) функция или т.п., которая будет пересылать на другой канал.

A: как вариант:
def inline_keyboard(where_call):
    insert_subinline = types.InlineKeyboardMarkup()
    if where_call == 'start':
        join = types.InlineKeyboardButton(text="Показать ссылку на канал", callback_data="joinSub")
        insert_subinline.add(join)
        return insert_subinline
    elif where_call == 'joinSub':
        join = types.InlineKeyboardButton(text="Join", url="https://t.me/namechannel")
        insert_subinline.add(join)
        return insert_subinline

@bot.message_handler(commands=['start'])
def start(message):
    bot.send_message(message.chat.id, 'Тут кое-что интересное ', reply_markup=inline_keyboard('start'))

@bot.callback_query_handler(func = lambda call: True)
def answer(call):
    if call.data == 'joinSub':
        bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id,
                              text='namechannel', reply_markup=inline_keyboard('joinSub'))

        some_function_collect_and_check_data()

сначала отправляем inline кнопку, по нажатию изменяем содержимое + вызываем функцию для сбора\проверки данных.


text:
Q: Can you create a custom property list type that Property List Editor will recognize? Is there a way to create a custom property list type, such that Property List Editor would recognize it the way it does an Info.plist property list?
I noticed the DTD in Apple's Info.plist format, but I don't know much about XML schemas. Is there more to it?

A: The list of formats for property lists is not extensible.
The list is defined in the NSPropertyListFormat type/enumeration found in the NSPropertyList.h from the Foundation framework (equivalently, CFPropertyListFormat found in CFPropertyList.h from Core Foundation).

If you are looking for a plain text format that is easier to edit (easier than the XML format), then you may be interested in the older NeXTSTEP/OpenStep property list format. Unfortunately, it can not represent all the types that are supported by the new XML and binary formats (it lacks direct representations for booleans, numbers, and dates). Because of this forward incompatibility, the standard library and tools (NSPropertyListSerialization, defaults, plutil, PlistBuddy, etc.) will read this older format, but they will not write it (although the output of default read looks suspiciously like the NeXTSTEP format).
This format is often found in the .strings files that are used to localize applications (probably because this use case is limited to string keys and values in a dictionary (all supported types) and because it is easy to edit in virtually any text editor).


text:
Q: Let $V$ be vector space of dimension $m\geq 2$. Let $T:V\to V$ be a linear transformation such that $T^{n+1}=0 $ and $T^n\neq 0$ for some $n\geq 1$. Let $V$ be vector space of dimension $m\geq 2$. Let $T:V\to V$ be a linear transformation such that $T^{n+1}=0 $ and $T^n\neq 0$ for some $n\geq 1$. Then which of the following is necessarily TRUE?
(a). $Rank (T^n)\leq Nullity(T^{n+1})$
(b). $Trace(T)\neq 0$
(c). T is diagonalizable
(d). $n=m$

A: (a) is true since $\ker T^{n+1}= V$.
(b) is false, since the  minimal polynomial of $T$ is $x^{n+1}$,  and the trace is the sum of the eigenvalues of $T$.
(c) is false, because $T$ is diagonalisable if and only if its minimal polynomial splits into a product of distinct linear factors.
(d) is false in general. Counter-example: $\;T=\begin{bmatrix}0&0&1\\0&0&0\\0&0&0\end{bmatrix}$ satisfies $\;n=1$. What is true is $\;n<m$.


text:
Q: Makefile compile many programs with main function with one makefile error Im trying with one Makefile to compile many .c files. I have written all the rules and I want to add a rule that says: execute all the rules who depend on .c files.
In reference of : Compile all C files in a directory into separate programs
PROGRAMS := copy.c sec_soft.c
PROGRAMS_NO_EX := $(basename $(PROGRAMS))
PROGRAMS_TO_CREATE := $(PROGRAMS_NO_EX).elf $(PROGRAMS_NO_EX).dump $(PROGRAMS_NO_EX).bin $(PROGRAMS_NO_EX).hex $(PROGRAMS_NO_EX).mem  $(PROGRAMS_NO_EX).coe

RISCV_OPTIONS = -march=rv32if -mabi=ilp32 -o
RISCV_LINK = $(RISCV_GCC) $(CFLAGS) $< -o $@                            #produces .elf file!
RISCV_OBJDUMP = $(RISCV_PREFIX)objdump -D   $(DFLAGS)                       #produces a dump file to see the assembly code!
RISCV_OBJCOPY = $(RISCV_PREFIX)objcopy -O binary                        #produces a bin file!

ALL_RES = $(PROGRAMS:%.c=%.elf)

%.elf: %.c
    $(info Generating .elf file from files: $(PROGRAMS_NO_EX))
    $(RISCV_LINK)
    $(info Success!)
    $(info ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~)
%.dump: %.elf
    $(info Copying assembly to dump file $(PROGRAMS_NO_EX).dump)
    @$(RISCV_OBJDUMP) $< > $@
    $(info Success!)
    $(info ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~)
%.bin: %.elf
    $(info Generating bin file)
    @$(RISCV_OBJCOPY) $< $@
    $(info Success!)
    $(info ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~)
%.hex: %.bin
    $(info Generating hex file)
    echo cd $(SCRIPTDIR)
    $(info Running binary to hex >>>)
    python $(SCRIPTDIR)/bin2hex.py -a $(START_ADDRESS) -o $@ $<
    $(info Hex Generation Successful!)
    $(info ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~)
%.mem: %.bin
    $(info Instantiating memory addresses...)
    head -c $$(( $(START_ADDRESS))) /dev/zero | cat - $< | xxd -g1 -c4 | awk '{print $$5$$4$$3$$2}' > $@
    $(info Memory instantiation Successful!)
    $(info ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~)
%.coe: %.bin
    $(info Instantiating memory vector...)
    python $(SCRIPTDIR)/bin2coe.py $< -o $@
    $(info Memory vector instantiation Successful )
    $(info ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~)

all: $(ALL_RES);

But this line ALL_RES = $(PROGRAMS:%.c=%.elf) does not execute all the rules. I was hoping that after generating .elf files then all of the rules below would execute but not.
Im newbie on Makefiles, so please forgive any mistakes.
Thank you in advance

A: make will not create targets that you did not ask for. Your all target only asks to create files with .elf extension, nothing more. If you wish to build all others, you should tell make to do so.
The definition of targets to build should be updated, as it does not create file names properly. Written as it is, it only concatenates extension to the end of the variable. See for yourself:
$ make -rp 2>&1 | grep PROGRAMS_TO_CREATE
PROGRAMS_TO_CREATE := copy sec_soft.elf copy sec_soft.dump copy sec_soft.bin copy sec_soft.hex copy sec_soft.mem  copy sec_soft.coe

This should be updated to a proper string manipulation, e.g.:
PROGRAMS_TO_CREATE := $(foreach program,$(PROGRAMS_NO_EX),$(addprefix $(program),.elf .dump .bin .hex .mem .coe))

This will generate a proper list of targets:
$ make -rp 2>&1 | grep PROGRAMS_TO_CREATE
PROGRAMS_TO_CREATE := copy.elf copy.dump copy.bin copy.hex copy.mem copy.coe sec_soft.elf sec_soft.dump sec_soft.bin sec_soft.hex sec_soft.mem sec_soft.coe

which after setting as dependency to target all:
all: $(PROGRAMS_TO_CREATE)

will result in proper build.


text:
Q: RequestMethod.DELETE not working I am trying to send a DELETE request using FireFox RestClient
Details below:
Method : DELETE
URL :
http://hostname:port/my-web/test/batch

Headers : Content-Type: application/json
BODY:
{
    "users": [
    "string1",
    "string2"
    ]
}

MY JAVA CONTROLLER is
@RequestMapping(method = {RequestMethod.DELETE}, value = "/batch")
public MYHTTPEntity<RestResponse> bulkDelete(@RequestBody String[] users,    WebRequest request){
..
}

I am getting 400 Bad Request. Description :The request sent by the client was syntactically incorrect. Please help check what is wrong. All my other requests are working fine with similar setup.

A: Assuming that MYHTTPEntity<RestResponse> is something you have setup that is valid to be returned by the controller, based on the JSON you are sending you need to do the following:
Add a class that will map the request, for example DeleteContent
public class DeleteContent {
    private List<String> users;

    public List<String> getUsers() {
        return users;
    }

    public void setUsers(List<String> users) {
        this.users = users;
    }
}

Then the controller would be:
@RequestMapping(method = {RequestMethod.DELETE}, value = "/batch")
public MYHTTPEntity<RestResponse> bulkDelete(@RequestBody DeleteContent deleteContent, WebRequest request){
..
}

If MYHTTPEntity<RestResponse> is not valid, you could return some custom object using
@RequestMapping(method = {RequestMethod.DELETE}, value = "/batch")
public @ResponseBody YourCustomResponse bulkDelete(@RequestBody DeleteContent deleteContent, WebRequest request){
..
}


text:
Q: How to protect an Excel worksheet/workbook from a macro of another workbook I am using Excel 2010 and I have a workbook with sheets that must be protected, but I still want to make changes to locked cells from a VBA macro. I found out that this is easily possible by running
myWorksheet.Protect UserInterfaceOnly:=True

However if a user opens another workbook in the same Excel Application, they might accidentaly run another macro which might mess up my worksheet.
Is there an option like UserInterfaceOnly to protect from macros of other workbooks as well?
Otherwise is it safe to only temporarly use UserInterfaceOnly and fully protect at the end of any of my macros again, or would this be dangerous due to concurrency?

A: The safest thing to do is protect the worksheets at the end of your code setting UI-only back to false.


text:
Q: What is the HTML5 canvas? I'm a little confused to what HTML5 canvas is.  I've been told it is JavaScript, but it seems to be a much bigger deal?

*

*What makes it different than javascript?

*Why is it so amazing?

*Does it do other things than JavaScript?

A: The canvas is basically an img element that you can draw on using javascript.

A: I suggest you read this article HTML5 Canvas - the basics
But in short. It does not replace javascript.

HTML 5 canvas gives you an easy and
  powerful way to draw graphics using
  JavaScript. For each canvas element
  you can use a "context" (think about a
  page in a drawing pad), into which you
  can issue JavaScript commands to draw
  anything you want. Browsers can
  implement multiple canvas contexts and
  the different APIs provide the drawing
  functionality.

A: The Canvas element is essentially a drawing canvas that can be painted on programmatically; a sort of scriptable bitmap drawing tool for the web.
I suppose the "amazing" thing about it, apart from the fact that we can now all create web-based MS Paint clones with ease, is that you have a much richer, completely free-form area for creating complex graphics client-side and on-the-fly. You can draw pretty graphs, or do things with photos. Allegedly, you can also do animation!
Mozilla's Developer Center has a reasonable tutorial if you want to try it out.

A: First of all, Canvas is NOT JavaScript! These 2 are totally different things.
Canvas is a HTML5 element that can be used for rendering graphics, animation, graphs, photo compositions or any other visual objects on the fly by using JavaScript. More often, canvas has used for building web game and online presentation.

A: *

*Canvas - A rectangle area like white paper

*Context - Returns the object by using what we can call many functions on which is used to draw the graphics and animations on a canvas (like how pencils are used on paper)

See the following example which draws a line on the canvas:

<html>
      <body>
       <canvas id="c" width="200" height="200" style="border:1px solid"></canvas>
        <script>
          var canvas = document.getElementById("c");//get the canvas in javascript
          var context = canvas.getContext("2d");//getcontext on canvas
          context.beginPath();//start the path.we are going to draw the line
          context.moveTo(20,20);//starting point of Line
          context.lineTo(40,20);//ending point of Line
          context.stroke(); //ink used for drawing Line (Default: Black)
        </script>
      </body>
    </html>


text:
Q: Tokenization of sentence final punctuations when they are not followed by whitespace We are trying to select a tokenizer to utilize in our annotation pipeline. Currently, I am testing the PTBTokenizer with some twitter texts.
In our data we have some texts in which there is no whitespace after the sentence final dot:"This is a test.And some more."
The PTBTokenizer does not recognize "test",".","And" as separate tokens, instead it takes the "test.And"as a single token. Is there any option or setting in the tokenizer which makes it to recognize the sentence final punctuations as single tokens even though it is not followed by a white space?
Thank you.

A: Not all dots are final punctuations. Such as "e.g., U.S., Corp."   etc. So, this is a real NLP problem which requires some effort to solve. That's why I didn't insert space around dots.
Thanks.


text:
Q: What does CPython actually do when "=" is performed on primitive type variables? For instance:
a = some_process_that_generates_integer_result()
b = a

Someone told me that b and a will point to same chunk of integer object, thus b would modify the reference count of that object. The code is executed in function PyObject* ast2obj_expr(void* _o) in Python-ast.c:
static PyObject* ast2obj_object(void *o)
{
    if (!o)
        o = Py_None;
    Py_INCREF((PyObject*)o);
    return (PyObject*)o;
}

......

case Num_kind:
    result = PyType_GenericNew(Num_type, NULL, NULL);
    if (!result) goto failed;
    value = ast2obj_object(o->v.Num.n);
    if (!value) goto failed;
    if (PyObject_SetAttrString(result, "n", value) == -1)
            goto failed;
    Py_DECREF(value);
    break;

However, I think modifying reference count without ownership change is really futile. What I expect is that each variable holding primitive values (floats, integers, etc.) always have their own value, instead of referring to a same object.
And in the execution of my simple test code, I found the break point in the above Num_kind branch is never reached:
def some_function(x, y):
    return (x+y)*(x-y)

a = some_function(666666,66666)
print a

b = a
print a
print b

b = a + 999999
print a
print b

b = a
print a
print b

I'm using the python2.7-dbg program provided by Debian. I'm sure the program and the source code matches, because many other break points works properly.
So, what does CPython actually do on primitive type objects?

A: First of all, there are no "primitive objects" in Python. Everything is an object, of the same kind, and they are all handled in the same way on the language level. As such, the following assignments work the same way regardless of the values which are assigned:
a = some_process_that_generates_integer_result()
b = a

In Python, assignments are always reference copies. So whatever the function returns, its reference is copied into the variable a. And then in the second line, the reference is again copied into the variable b. As such, both variables will refer to the exact same object.
You can easily verify this by using the id() function which will tell you the identity of an object:
print id(a)
print id(b)

This will print the same identifying number twice. Note though, that wil doing just this, you copied the reference two more times: It's not variables that are passed to functions but copies of references.
This is different from other languages where you often differentiate between "call by value" and "call by reference". The former means that you create a copy of the value and pass it to a function, which means that new memory is allocated for that value; the latter means that the actual reference is passed and changes to that reference affect the original variable as well.
What Python does is often called "call by assignment": every function call where you pass arguments is essentially an assignment into new variables (which are then available to the function). And an assignment copies the reference.
When everything is an object, this is actually a very simple strategy. And as I said above, what happens with integers is then no different to what happens to other objects. The only "special" thing about integers is that they are immutable, so you cannot change their values. This means that an integer object always refers to the exact same value. This makes it easy to share the object (in memory) with multiple values. Every operation that yields a new result gives you a different object, so when you do a series of arithmetic operations, you are actually changing what object a variable is pointing to all the time.
The same happens with other immutable objects too, for example strings. Every operation that yields a changed string gives you a different string object.
Assignments with mutable objects however are the same too. It's just that changing the value of those objects is possible, so they appear different. Consider this example:
a = [1] # creates a new list object
b = a # copies the reference to that same list object
c = [2] # creates a new list object
b = a + c # concats the two lists and creates a new list object
d = b
# at this point, we have *three* list objects
d.append(3) # mutates the list object
print(d)
print(b) # same result since b and d reference the same list object

Now coming back to your question and the C code you cite there, you are actually looking at the wrong part of CPython to get an explanation there. AST is the abstract syntax tree that the parser creates when parsing a file. It reflects the syntax structure of a program but says nothing about the actual run-time behavior yet.
The code you showed for the Num_kind is actually responsible for creating Num AST objects. You can get an idea of this when using the ast module:
>>> import ast
>>> doc = ast.parse('foo = 5')

# the document contains an assignment
>>> doc.body[0]
<_ast.Assign object at 0x0000000002322278>

# the target of that assignment has the id `foo`
>>> doc.body[0].targets[0].id
'foo'

# and the value of that assignment is the `Num` object that was
# created in that C code, with that `n` property containing the value
>>> doc.body[0].value
<_ast.Num object at 0x00000000023224E0>
>>> doc.body[0].value.n
5

If you want to get an idea of the actual evaluation of Python code, you should first look at the byte code. The byte code is what is being executed at run-time by the virtual machine. You can use the dis module to see byte code for Python code:
>>> def test():
        foo = 5

>>> import dis
>>> dis.dis(test)
  2           0 LOAD_CONST               1 (5)
              3 STORE_FAST               0 (foo)
              6 LOAD_CONST               0 (None)
              9 RETURN_VALUE

As you can see, there are two major byte code instructions here: LOAD_CONST and STORE_FAST. LOAD_CONST will just load a constant value onto the evaluation stack. In this example, we just load a constant number, but we could also load the value from a function call instead (try playing with the dis module to figure out how it works).
The assignment itself is made using STORE_FAST. The byte code interpreter does the following for that instruction:
TARGET(STORE_FAST)
{
    v = POP();
    SETLOCAL(oparg, v);
    FAST_DISPATCH();
}

So it essentially gets the value (the reference to the integer object) from the stack, and then calls SETLOCAL which essentially will just assign the value to local variable.
Note though, that this does not increase the reference count of that value. That's what happens with LOAD_CONST, or any other byte code instruction that gets a value from somewhere:
TARGET(LOAD_CONST)
{
    x = GETITEM(consts, oparg);
    Py_INCREF(x);
    PUSH(x);
    FAST_DISPATCH();
}

So tl;dr: Assignments in Python are always reference copies. References are also copied whenever a value is used (but in many other situations that copied reference only exists for a short time). The AST is responsible for creating an object representation of parsed programs (only the syntax), while the byte code interpreter runs the previously compiled byte code to do actual stuff at run-time and deal with real objects.


text:
Q: segmentation fault while importing nltk in python I am getting a segmentation fault while trying to import nltk on a debian machine.
Here's the python verbose output :-
>>> import nltk
....
....

import scipy.linalg.blas # precompiled from /usr/local/lib/python2.7/dist-packages/scipy/linalg/blas.pyc
# trying /usr/local/lib/python2.7/dist-packages/scipy/linalg/_fblas.so
dlopen("/usr/local/lib/python2.7/dist-packages/scipy/linalg/_fblas.so", 2);
Segmentation fault

Any suggestions ? I have tried uninstalling and reinstalling scipy followed by nltk.
thanks,
Amit

A: I had the same problem. I uninstalled scipy and nltk, then reinstalled nltk only.
pip uninstall scipy
pip uninstall nltk
pip install --no-cache-dir nltk

python
import nltk
nltk.download()

works.
However, the problem came back when I reinstalled scipy...
The solution for me was to uninstall both packages using pip and conda (conda uninstall nltk), then reinstall scipy using conda and nltk using pip. This combination worked for me, I'm not exactly sure why buit the reason was probably a faulty prior installation of nltk in anaconda.


text:
Q: Regex function to check the presence of any letter on the string or only number or symbols I'm a little confused about the usage of regular expression in all the entry string.
I need to understand if a given string contain any number or symbols, or viceversa don't contain any letters:

good
no good

!

- 1 -

=>

foo

foo bar

{

I have 3 bananas

123 456

So I need something like that /[^A-Za-z]/ but in the strign I have 3 bananas the preg_math_full is fired, how can I use the regex pattern in all the string??

A: If you want to exclude letters, you can simply search for [a-z] and reverse the result, such as :
$testArray = [
    "!",
    "- 1 -",
    "=>",
    "foo",
    "foo bar",
    "{",
    "I have 3 bananas",
    "123 456"
];

foreach ($testArray as $element)
{
    echo "$element is ";
    //  v--- check this
    if (!preg_match("#[a-z]#i", $element))
    {
        echo "good" . PHP_EOL;
    }
    else
    {
        echo "not good" . PHP_EOL;
    }
}

This will output :
! is good
- 1 - is good
=> is good
foo is not good
foo bar is not good
{ is good
I have 3 bananas is not good
123 456 is good

Fiddle


text:
Q: Azure Network Security Group - Internet vs Any
In the Image we can see AllowInternetOutboundRule is open to Internet. But does Internet here convey 0.0.0.0/0 IP?
If not, then what is difference between 'Internet' and 'Any'.
Also, does AllowInternetOutboundRule imply port 443 open to 0.0.0.0/0 or we will have to open 443 port to any?


text:
Q: Fill below certain threshold How can I insert Fill in the plot below, such that only the area below 0.5 and below the line is filled?
Plot[-x + 1, {x, 0, 1}]

EDIT: I was hoping the solution to this simpler question would also work for my real problem, which involves the following data, but this is not the case:
How can I implement you solution on this data?
Using Michael's solution combined with comments by void life
Plot[{data  , Min[1/2, #] & data }, {x, 0, 1}, PlotStyle -> {Automatic,None}, Filling -> {1 -> 0, 2 -> {{1}, White}}]

I get:

{0.744318, 0.60038, 0.539471, 0.5542, 0.592916, 0.613237, 0.673014, 0.687572, 0.658548, 0.69416, 0.65248, 0.653574, 0.596889, 0.577856, 0.592349, 0.505633, 0.51403, 0.520655, 0.492696, 0.459513, 0.463524, 0.463181, 0.415386, 0.422303, 0.422072, 0.406222, 0.40379, 0.389445, 0.375038, 0.349756, 0.332508, 0.323173, 0.308245, 0.290745, 0.285053, 0.275322, 0.268835, 0.25514, 0.25281, 0.254935, 0.250978, 0.251613, 0.25431, 0.251915, 0.252345, 0.253374, 0.253928, 0.248666, 0.25169, 0.253212, 0.257687, 0.257374, 0.256379, 0.262966, 0.263945, 0.268633, 0.270197, 0.273909, 0.274298, 0.275465, 0.274321, 0.273316}

A: Possibly also this:
Plot[{-x + 1, Min[1/2, -x + 1]}, {x, 0, 1},
 PlotStyle -> {Automatic, None},
 Filling -> {1 -> 0, 2 -> {{1}, White}}]

A: data = {0.744318, 0.60038, 0.539471, 0.5542, 0.592916, 0.613237,
   0.673014, 0.687572, 0.658548, 0.69416, 0.65248, 0.653574, 0.596889,
    0.577856, 0.592349, 0.505633, 0.51403, 0.520655, 0.492696,
   0.459513, 0.463524, 0.463181, 0.415386, 0.422303, 0.422072,
   0.406222, 0.40379, 0.389445, 0.375038, 0.349756, 0.332508,
   0.323173, 0.308245, 0.290745, 0.285053, 0.275322, 0.268835,
   0.25514, 0.25281, 0.254935, 0.250978, 0.251613, 0.25431, 0.251915,
   0.252345, 0.253374, 0.253928, 0.248666, 0.25169, 0.253212,
   0.257687, 0.257374, 0.256379, 0.262966, 0.263945, 0.268633,
   0.270197, 0.273909, 0.274298, 0.275465, 0.274321, 0.273316};

threshold = 0.5;

Show[Plot[data, {x, 0, 1}, PlotStyle -> {Automatic, None}],
 Plot[threshold, {x, 0, 1}, Filling -> Min@data]]

Or
Show[Plot[data, {x, 0, 1}, PlotStyle -> {Automatic, None},
  PlotRange -> {0.2, 0.8}],
 Plot[threshold, {x, 0, 1}, Filling -> 0.2]]


text:
Q: Is it currently possible to swap pulsar in for Kafka in spring-cloud-streams I've been trying to do some searching (Google, Slack, Stack) and have yet to find an answer. We have some applications that are written using Spring Cloud Streams and were interested in swapping the back end from Kafka to Pulsar. Spring currently doesn't have any native support for Kafka, however it appears that pulsar provides the ability to use the Kafka API to communicate with pulsar directly (https://pulsar.apache.org/docs/en/adaptors-kafka).
I'm wondering if anybody has gone down the route of trying to use this replacement for the Kafka-clients library in the context of Spring cloud messaging.
An alternative valid approach, of course, is to just re-write the code - but I wanted to turn to the community to see if anybody has gone down this road as of yet.
Thanks

A: While not exactly what you're asking for, I've tried to integrate Pulsar with Spring-Kafka using the shaded library org.apache.pulsar:pulsar-client-kafka:2.5.0 and it blows-up with this stack trace:
Caused by: java.lang.UnsupportedOperationException: null
at org.apache.kafka.clients.consumer.KafkaConsumer.partitionsFor(KafkaConsumer.java:650) ~[pulsar-client-kafka-2.5.0.jar:2.5.0]
at org.springframework.kafka.listener.AbstractMessageListenerContainer.checkTopics(AbstractMessageListenerContainer.java:312) ~[spring-kafka-2.2.10.RELEASE.jar:2.2.10.RELEASE]
at org.springframework.kafka.listener.ConcurrentMessageListenerContainer.doStart(ConcurrentMessageListenerContainer.java:136) ~[spring-kafka-2.2.10.RELEASE.jar:2.2.10.RELEASE]
at org.springframework.kafka.listener.AbstractMessageListenerContainer.start(AbstractMessageListenerContainer.java:292) ~[spring-kafka-2.2.10.RELEASE.jar:2.2.10.RELEASE]
at org.springframework.kafka.config.KafkaListenerEndpointRegistry.startIfNecessary(KafkaListenerEndpointRegistry.java:311) ~[spring-kafka-2.2.10.RELEASE.jar:2.2.10.RELEASE]
at org.springframework.kafka.config.KafkaListenerEndpointRegistry.start(KafkaListenerEndpointRegistry.java:255) ~[spring-kafka-2.2.10.RELEASE.jar:2.2.10.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:182) ~[spring-context-5.1.10.RELEASE.jar:5.1.10.RELEASE]

This specific error can be bypassed (for these specific library versions) using a custom implementation of AbstractMessageListenerContainer.checkTopics but you'll likely run into more issues.


text:
Q: SQL*Loader: Use a field not in the table Got an odd question, I'm trying to load some data into Oracle using SQL*loader.
The trick is, there is a field provided which I need to use as input to a user function to calculate another field. The original field I don't want to load.
I tried this: however, a FILLER field cannot be referenced as a BIND variable:
  LOAD DATA
     APPEND
     INTO TABLE my_table
     (
     XREF_NUM        FILLER   POSITION(8:26),
     ID_NUM                   POSITION(1:1) "my_func(:XREF_NUM)",
     ... other columns ...
     )

Table defintion is just:
  ID_NUM
  COL1
  COl2

but XREF_NUM does not exist in the table.
How do I set this up ?

A: Define it as BOUNDFILLER, which means treat it as a "remembered" FILLER.  You can use it in expressions.
LOAD DATA
     APPEND
     INTO TABLE my_table
     (
     XREF_NUM   BOUNDFILLER  POSITION(8:26),
     ID_NUM                  POSITION(1:1) "my_func(:XREF_NUM)",
     ... other columns ...
     )


text:
Q: How to subtract every element from one array to another? I have got two arrays of equal size.
double[] array1;
double[] array2; //array1 size == array2 size

I have also got a constant number double constant  = 5. Say 5 for example
I want to create a new array double[] array3; where we take every element in array1 and subtract the element at the same index in array2 from array1.
So that:
array3[i] = array1[i] - array2[i]
I then want to subtract the constant to all elements in array3 thereafter.
I can do this all with a for loop however my arrays are massive so it takes a very long time to compute. Is there a way to do the subtraction specifically without using for loops?
example data:
if:
array1 = {1, 2, 3, 4, 5, 6};
array2 = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6};

then
array3 = {0.9, 1.8, 2.7, 3.6, 4.5, 5.4}

now subtract constant
array3 = {-4.1, -3.2, -2.3, - 1.4, -0.5, 0.4}

A: There's really no avoiding having to loop over the arrays at least once, but there is the built-in LINQ Zip method which does most of the hard work for you.
The thing to NOT do is loop more than necessary so dont subtract the constant value after doing the initial subraction - do it at the same time
var array1 = new[]{1, 2, 3, 4, 5, 6};
var array2 = new[]{0.1, 0.2, 0.3, 0.4, 0.5, 0.6};
var constant = 5;
var array3 = array1.Zip(array2, (x,y) => x-y-constant).ToArray();

Live example: https://dotnetfiddle.net/An8IuE
This will ultimately be a little slower than a simple for loop
var array1 = new[]{1, 2, 3, 4, 5, 6};
var array2 = new[]{0.1, 0.2, 0.3, 0.4, 0.5, 0.6};
var constant = 5;
var array3 = new double[array1.Length];
for(int i=0,j=array1.Length; i<j;i++)
    array3[i] = array1[i] - array2[i] - constant;

Live example: https://dotnetfiddle.net/r5JQKN

A: If the order doesn't actually matter, then you can use AsParallel to parallelize your Zip using PLINQ:
var array1 = new[]{1, 2, 3, 4, 5, 6};
var array2 = new[]{0.1, 0.2, 0.3, 0.4, 0.5, 0.6};
var constant = 5;
var array3 = array1.AsParallel().Zip(array2.AsParallel(), (x,y) => x-y-constant);

Because it happens in parallel, the results will be out of order (but will still be correct).
Demo
Edit:
Whether the parallel one will be faster than the sequential one depends on your hardware and input size. For me, a lot of the online compilers (rextester, C# fiddle) showed the sequential execution to be faster (most likely because their resources are limited and input size couldn't be too large), On my local machine, I was able to see the parallel execution become faster as the input size approached ~10 million elements per array. The takeaway for you is "Benchmark, benchmark, benchmark"

A: Enumerable.Range(0, array1.Length).Select(x => array1[x] - array2[x] + constant);

A: Use the overload of Enumerable.Zip that has a parameter resultSelector
double[] array1 = ...;
double[] array2 = ...;
const double value = 5.0;

var result = array1.Zip(array2, (x, y) => x - y - value);


text:
Q: Prevent image to fly outside of the window I have an image in my code that moves 750px every 5 seconds but it fly out of the page so you cant see it anymore. How do I prevent it to fly out of the page?
this is the code:

so far I tried to set the max width/height of the page but that doesnt work, I think you can solve it with tracking the image or something like that but I have no idea how to work that out.

A: Use window.innerHeight and window.innerWidth if it's smaller than 750
function moveduck() {
  var top = Math.floor(Math.random() * Math.min(750, window.innerHeight));
  var left = Math.floor(Math.random() * Math.min(750, window.innerWidth));
  duck.style.top = top + 'px';
  duck.style.left = left + 'px';
  score++
};

Also, I don't think you need things other than top and left


text:
Q: How do I substitute one word in a string variable in Python? I know people have asked about how to substitute words in strings, but I'd like to replace a specific word in a variable string, and leave the rest untouched.
For example: if the user enters "My family does not like chicken", I'd like the computer to output back to them "Your family does not like chicken". The word being replaced is "My", and the word replacing it is "Your". I'm using Python 2.7.13.

A: Use the replace() string method:
>>> "My family does not like chicken".replace("My", "Your")
Your family does not like chicken

A: The other answers do not deal with storing user input, you can do so by using raw_input in python 2:
#Store users input into a variable
user_input = raw_input("Please enter a sentence: ")

#Use str.replace to replace ALL occurrences of the word "My" with "Your" and output using print
print user_input.replace("My", "Your")

Example Usage:
Please enter a sentence:  My family does not like chicken
Your family does not like chicken

Try it here!
Link to python documentation for: str.replace

A: Use the replace() function
oldstr = 'my family does not like chicken'
newstr = oldstr.replace('my', 'your')
print(newstr)

Output
    your family does not like chicken


text:
Q: IPTABLES CODE ISSUE I am using iptables to block all the ports. However to allow ping www.google.com I am using the following code
filter -A INPUT -p tcp --dport 53 -j ACCEPT
filter -A OUTPUT -p tcp --sport 53  -j ACCEPT
filter -A INPUT -p udp --dport 53 -j ACCEPT
filter -A OUTPUT -p udp --sport 53 -j ACCEPT

This works fine though saving it gives me error because using the filter in start is not the right way. However when I use the code without word filter the ping to www.google.com doesn't work. PS I am directly saving to iptables files under /etc/sysconfig
Edit: Ok it seems the filter broke the whole code and iptables was deleting the whole rules. The problem is that I can't ping www.google.com despite opening my DNS port.

A: The ping utility uses ICMP (Internet Message Control Protocol), not UDP (User Datagram Protocol) or TCP (Transmission Control Protocol). To allow outgoing ping requests through your fire-wall you could add a rule such as the following:
iptables -A OUTPUT -p icmp --icmp-type echo-request -j ALLOW

You probably also want to add a rule such as the following to allow the returning traffic:
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

A: The ordering of iptables rules is important: the first matching rule with either -j ACCEPT, -j DROP or -j REJECT will decide the fate of the packet. Adding new rules after a "drop everything" rule will have no effect, as the matching packets would never reach that rule.

A: Ok the correct rules were these . Got it from a forum issue resolved.
-A INPUT -p udp --sport 53 -j ACCEPT
-A INPUT -p udp --dport 53 -j ACCEPT
-A OUTPUT -p udp --sport 53 -j ACCEPT
-A OUTPUT -p udp --dport 53 -j ACCEPT


text:
Q: How to set custom name for android language directory? I would like to have different directories for multiple languages. For example I have Kurdish language with 2 dialects - Badini and Sorani. But there are no specific regions for them in Android.

Can I name them customly for each region?
Correct dir naming for Kurdish but one dir for all regions - not desired

Inorrect naming but desired one
While building throws Error: Invalid resource directory name

Is it even possible ?

A: In one word NO,
According to google documentation To add support for more locales, create additional directories inside res/. Each directory's name should adhere to the following format:
<resource type>-b+<language code>[+<country code>]

After you've decided on the locales to support, create the resource subdirectories and files.
For example, values-b+es/ contains string resources for locales with the language code es. Similarly, mipmap-b+es+ES/ contains icons for locales with the es language code and the ES country code. Android loads the appropriate resources according to the locale settings of the device at runtime.
MyProject/
    res/
       values/
           strings.xml
       values-b+es/
           strings.xml
       mipmap/
           country_flag.png
       mipmap-b+es+ES/
           country_flag.png

for more details follow the document language