text:
Q: How to add a string from a buffer to another array and print this? So basically I want to write a word, and when I press enter I want to store this string from buffer to array. As I write the first word it might work but when I want to add a second word it is getting tricky.
e.g.1st input is:first\0
    2nd input is:two\0
    then:Ctrl+Z(to get out of the loop)
    Output I want:first two (actually printing the 'array' array.)

My Code is Here:
position=0;
printf("Enter a text: \n");
while(fgets(buffer, 100 , stdin) != NULL){
    for (i=position;i<(position+numberOfChars);i++){
        array[i]=buffer[i];
    }
    numberOfChars=strlen(buffer);
    position=position+numberOfChars+1;
}

A: See comments in the code:
position=0;
printf("Enter a text: \n");
while(fgets(buffer, 100 , stdin) != NULL){

    /* because you want to add space between 'first' and 'two' */
    if (position != 0) {
        array[position] = ' ';
        position++;
    }

    /* you need to get the buffer len for THIS iteration */
    numberOfChars=strlen(buffer);

    for (i=position;i<(position+numberOfChars);i++){
        /* i is a valid indice for array but not for buffer[0..numberOfChars-1] */
        /* array[i]=buffer[i]; */
        array[i] = buffer[i-position];
    }

    /* adding one will not add a space char */
    /* position=position+numberOfChars+1; */
    position = position+numberOfChars;
}

/* finaly add the null char at the end of the string (string is null terminated) */
array[position] = '\0';

You may also try this:
printf("Enter a text: \n");

/* set array as an empty string */
array[0] = 0;

/* read from stdin */
while(fgets(buffer, 100, stdin) != NULL) {

    /* append a space to array if it isn't empty */
    if (array[0] != 0)
        strcat(array, " ");

    /* append buffer to array */
    strcat(array, buffer)
}

/* print resulting array */
printf("%s\n");

A: Note that fgets() stores the newline read from the stdin into the buffer as well. So, you want to get rid of it. And you want to put an extra space between the two words. Also, you are initializing numberOfChars too late. It should happen before it is used in the copy loop.
Try this:
position = 0;
printf("Enter a text: \n");
while(fgets(buffer, 100 , stdin) != NULL) {
    numberOfChars = strlen(buffer);
    buffer[numberOfChars - 1] = ' '; //this replaces newline with space
    // note that i <= in the condition; to copy the '\0' over
    for (i = position; i <= (position + numberOfChars); i++) {
        array[i] = buffer[i];
    }
    position = position + numberOfChars;
}


text:
Q: How to attach Sitecore context for controller action mappled to route robots.txt? In Sitecore I'm trying to set up a way for our client to modify the robots.txt file from the content tree. I am attempting to set up a MVC controller action that is mappled to route "robots.txt" and will return the file contents. My controller looks like this:
public class SeoController : BaseController
{
  private readonly IContentService _contentService;
  private readonly IPageContext _pageContext;
  private readonly IRenderingContext _renderingContext;

  public SeoController(IContentService contentService, IPageContext pageContext, IRenderingContext renderingContext, ISitecoreContext glassContext)
     : base(glassContext)
  {
     _contentService = contentService;
     _pageContext = pageContext;
     _renderingContext = renderingContext;
  }

  public FileContentResult Robots()
  {
     string content = string.Empty;
     var contentResponse = _contentService.GetRobotsTxtContent();

     if (contentResponse.Success && contentResponse.ContentItem != null)
     {
        content = contentResponse.ContentItem.RobotsText;
     }

     return File(Encoding.UTF8.GetBytes(content), "text/plain");
  }
}

And the route config:
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        RouteTable.Routes.MapRoute("Robots.txt", "robots.txt", new { controller = "Seo", action = "Robots" });
    }
}

This all works great if I use a route without the ".txt" extension. However after adding the extension I get a null reference exception in the domain layer due to the context database being null. Here's where the error happens:
public Item GetItem(string contentGuid)
{
    return Sitecore.Context.Database.GetItem(contentGuid);
}

I'm assuming that there is a setting in sitecore that ignores the .txt extension. I've tried adding it as an allowed extension in the Sitecore.Pipelines.PreprocessRequest.FilterUrlExtensions setting of the config. Is there anything else I could be missing?

A: Ok, I found the issue. I was correct in assuming that txt needed to be added to the allowed extensions for the Sitecore.Pipelines.PreprocessRequest.FilterUrlExtensions setting. However robots.txt was listed under the IgnoreUrlPrefixes setting in the config file. That was causing sitecore to ignore that request. I removed it from that list and it's working great now.

A: This is a pure guess, but you might also have to add it to the allowed extensions of Sitecore.Pipelines.HttpRequest.FilterUrlExtensions in httpRequestBegin as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: kotlin + get all component / members from class (object) with its original order Im trying to get all memberProperties of a class. I'm using bellow code
for (props in SomeClass::class.memberProperties) {
    //do something with the props
}

I can get all the members, but the sequence that I get is ignoring the original member/property's order, instead it automatically ordering it by alphabet (a-z)
For example, If I declare my class as
class foo(b:String, a:String, c:String)

when I print all of its properties, I would get a,b,c rather than b,a,c
is there any way for me to iterate all members of a class and maintain it's original order / sequence?


text:
Q: How can I get 0 margin between two cells of a table? I'm trying to get two images adjacent to each other to look like a single image.  This is the HTML I have going:

The image in the right cell is actually a tall, narrow image that is repeated.
The problem is, I am not getting the two cells to look like one when run.  In this image, you can see what it looks like on the left, and what I need it to look like on the right.  There is this "gutter" between them, even when I specify border="0".

I've seen this done; I am just having trouble reproducing it!
edited to add: BTW, this is a straight HTML page on IE9.
Following up on the comments to the Accepted answer: Using CSS to try to achieve the desired result did not work.  Setting the style="border: 0px; border-spacing: 0px; padding: 0px;" gave a reduced size "gutter" between the two images, but that's all.  Perhaps there was more that has to be done?  Anyway, I got the job done using the Accepted answer.

A: There is only one way:

...


text:
Q: Does this have two meanings: 'how do you like your coffee'?
How do you like your coffee?

Can I use the above sentence either on an offering situation that I ask if they like it black or with sugar, or during having situation that I ask if the coffee tastes good?
When the latter is possible, can next both answers be possible?

*

*I like it a lot.

*It's good.

A: This phrase does have two meanings in US English, as agreed by other posters.
For the sake of completeness, I feel compelled to add that in British English, this is a phrase that would only be used when offering coffee. Using it as a question to affirm how much someone was enjoying their coffee would probably be understood, but would sound extremely odd. Instead, British people might say:

"Are you enjoying your coffee?"
"Is that coffee OK for you?"

Or something similar.
Divided by a common language and all that.

A: Beyond the answers given by other contributors, I would also add another parse:
If asked at a bar at night, when the other party is clearly not drinking coffee, the individual who asked may be implying that they will be making coffee for the other party the following morning; that is, it could also serve as an implicit pick-up line.

A: Context depends greatly on whether I ask:
before I give it to you, where it's equivalent to "Would you like milk/sugar/etc.?"
after I give it to you, where I'm asking "Do you like it?"/"Is that coffee ok?"

A: You may use this in both situations, and indeed in others; the context will make it clear which meaning is intended:

*

*If you ask before you start preparing the coffee, you are asking how your hearer prefers their coffee to be prepared—Do you like it strong or weak (or possibly boiled to a black sludge)?

*If you ask before or as you serve the coffee, you are asking how your hearer 'takes' their coffee—Do you want cream or sugar with your coffee?

*If you ask after your hearer has started drinking the coffee, you are asking about the taste of the coffee—Is the coffee OK?
As for your answers, both are possible, as are many more:

*

*It's terrific!

*It's horrible!

*It's coffee!

*It's Blue Mountain, apparently from St Thomas Parish; rather underroasted, to my mind, and a coarser grind should be used with that press.

A: As the other answers suggest, "How do you like your coffee?" can indeed have either meaning, depending on context.
If you're looking for unambiguous versions, you could instead ask:

How do you take your coffee?  Meaning: Milk? Sugar?

Or

How is your coffee? Meaning: Do you like the coffee you're drinking?

A: Be careful of emphasis
There are 2 ways of emphasizing the question:

*

*How do you like your coffee?

*How do you like your coffee?

The first is equivalent to 'how do you take your coffee?', so I would expect it in that context after someone has agreed to or requested some coffee.
The second is equivalent to 'how are you enjoying your coffee?', so I would expect it in the context of someone having tasted some coffee they have received. To this, any answer about the quality or my enjoyment of the coffee is fine, but it is not a yes/no question ('how' requires a full answer).

A: Good question -- in addition to the answers concerned with the various contexts in which this is asked:
The ambiguity is as much a question of contrastive focus:

*

*How do you like your coffee?

*How do you like your coffee?

*How do you like your coffee?

*How do you like your coffee?

*How do you like your coffee?

*How do you like your coffee?

Even context-free, emphasis on the words in bold (or any combination of words in this sentence) affects the meaning. See Wikipedia: Focus (linguistics) for a more technical description of contrastive focus.

A: The sentence looks ambiguous and hence, it can be used for both the situations. And thus...*
If I want to ask about the 'quality' of coffee, I'd use...

How was your coffee? ~ Ah, it was good!

OR

Did you like the coffee? ~ Yeah, I liked it!

If I am asking for a choice, I'd say it this way -

Which coffee would you like to have? Black or with sugar?

Note that I'd prefer using would and not do! I'm offering the guest and coffee hasn't come yet!

A: It's easier to see the meaning if you expand the two sentences to avoid the ambiguity:

How do you like your coffee [to be]?

And the second definition:

How do you like your coffee [in front of you]?

The latter is usually instead said without the "how" (in fact, I have a feeling including the "how" is grammatically incorrect), just as:

Do you like your coffee?

Or even more clear:

How is your coffee?

A: One other possible interpretation is if it's being said by someone who doesn't like coffee, in an incredulous manner:

How do you like your coffee?? I hate it!

(This is me. :))


text:
Q: Need help in ios 7 Keychain add and retrieve Public Key kSecReturnRef In iOS7, when I add a RSA Public Key in the Keychain, it is successfully added but if I want to retrieve "kSecReturnRef", I get nil as result, but if I retrieve "kSecReturnPersistentRef" or "kSecReturnData" it is working fine.
This problem only occurs if I add a RSA public key via "SecItemAdd()" method.
Everything is good if I generate a public key via "SecKeyGeneratePair()" and retrieve "kSecReturnRef".
Steps to Reproduce:

*

*Download the sample code "CryptoExercise"

*Call method "addPeerPublicKey:keyBits:"

*Pass a public key data and name

*Above method internally calls "getKeyRefWithPersistentKeyRef", and this method returns nil value for "SecKeyRef".

This problem is only in iOS 7 whereas the same code works just fine from iOS3 to  iOS6.
Expected Results:
< SecKeyRef algorithm id: 1, key type: RSAPublicKey, version: 2, block size: 512 bits, exponent: {hex: 10001, decimal: 65537}, modulus: AE098BC28358D88AE7602E8BB91007239018D40BB1A87F2245199A208CA21B8EFCFFE2373B470E6075D740AC1A25CD7914A6BA5680701DFB9428E2DD461965B7, addr: 0x9abe600 >

Actual Results:
< nil>

Sample Code: https://developer.apple.com/library/IOs/samplecode/CryptoExercise/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008019-Intro-DontLinkElementID_2

Any help would be appreciated.


text:
Q: Managing dependency inheritance in .NET Core Say I have four Projects. DataRepositories, DataRepositoryInterfaces, SetupInject, WebAPI. I want WebAPI to only have a direct reference to two of those projects. Essentially making WebAPI ignorant to the concrete implementations of my repository interfaces.
To do this I've made it so SetupInjections main purpose is to define the concrete types that will be injected. However, when I reference the InjectionSetup project  I get all it's dependencies in the WebAPI project as well.

Although I never referenced the project that defines the concrete classes directly, they are still available for me to use. The main objective is to restrict the developer from making an instance of the class in this project.

I recall being able to do something like this in previous versions of .NET. Is there any way to do this now?
1) Is what I'm trying to do suggested?
2) Can it be done with .Net Core?
3) Why could it be done in previous versions.

A: I believe you can do this using Friend Assemblies, https://msdn.microsoft.com/en-us/library/mt632254.aspx  I've often use this in Unit Test projects that need to access classes defined as internal.
In your SUT
using System.Runtime.CompilerServices;
    using System;
[assembly: InternalsVisibleTo("AssemblyB")]

// The class is internal by default.
class FriendClass
{
    public void Test()
    {
        Console.WriteLine("Sample Class");
    }
}

In your Unit/Int tests
// Public class that has an internal method.
public class ClassWithFriendMethod
{
    internal void Test()
    {
        Console.WriteLine((new FriendClass).Test);
    }

}

Here's more details, https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx  You may also add additional code signing to further restrict it.


text:
Q: Content Security Policy in IE support I am aware of Content Security Policy as a new feature build into IE10.
Wondering if there is any 3rd party vendors providing implementation thru add-on(BHO) for IE9 and older version?
Thanks,

A: IE 10 only runs on windows 8 and there is only a preview version available for windows 7. IE 9 on the other hand is the browser already used by the majority of IE users so having a solution that works on IE 9 allows the deployment of content security policy from a website without requiring their clients to upgrade to IE 10. Having a BHO would be very helpful in ie 9 for this reason.

A: Older than IE 10, use  X-Frame-Options.
IE 10 and newer, use X-Content-Security-Policy.
For me X-Content-Security-Policy worked in IE 9 as well.


text:
Q: How to use the SQL grant command to restrict access columns and rows in Access database I am beginner to this subject and self studying. I think this is basic but I could not find it in the ebook I am using. I do not know whether this is relevant to others because when I search this site all the questions are advance to me. So as a beginner, I thought to ask this again because last time my question was discarded as not relevant and not adequate research. I tried my best to find an answer browsing the net but came non.
This is the table INVENTORY (BOOK_CODE, BRANCH_NUM, ON_HAND)
grant update on INVENTORY to Mark and this is the only way it explained in the pdf.
This is the question I want to answer.
Users Chambers must be able to change the units on hand for books in branch number 2 but must be unable to access data in any other branch.
This is what I thought.
GRANT UPDATE ON(ON_HAND WHERE BRANCH_NUM = '2') ON BRANCH TO CHAMBERS

is this correct?
If you think this is not relevant to your community please discard.

A: I'd say the best way to do this (on any RDBMS) is to create a view of the columns you want to grant access to and then give read access to that view.

A: I am not aware of any database engine that allows access to be defined at that level. I suspect there is not one. That type of micrologic logic is normally handled by a front end application that has some security model that is more granular than what the database provides.

A: As mentioned by Hogan you would need to create a view first and then assign update permissions to the user against that view so...
create view branch2_inventory as select book_code, on_hand from inventory where branch_num = 2;

grant update on branch2_inventory to chambers;


text:
Q: Using Volley to Parse an array from PHP into Android I am unable to find any resources about parsing an array into my android application from PHP. I am using Volley to handle the connection.
At the moment I have an array in the PHP script on the web server containing connections to a database which puts the data from MySQL query into the array.
$latitude = array (
    //Code for array here
);

$longitude = array (
    //Code for array here
);

I am able to connect to the script okay but cannot get figure out how to get each element from the array in PHP to an array in my mainActivity.java file.
The Java code is throwing an exception saying 'No value for Latitude'
The way I understand this is because 'latitude' also tried '$latitude' is not the name of the array it is the variable name. In PHP I don't think there is such a name.
Is there another way to parse the contents of this array to Java.
The Java code I have tried is:
String url = "urlHere";
    JSONObject jObj = new JSONObject();
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, jObj,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try
                    {
                        JSONArray jsonArray = response.getJSONArray("$latitude");
                        //Loop through array
                        for (int i = 0; i<jsonArray.length(); i++)
                        {
                            JSONObject locationItem = jsonArray.getJSONObject(i);
                            String latitude = locationItem.getString("index1");
                        }
                    }
                    catch (Exception e)
                    {
                        //Error encountered.
                        //Log Error
                        Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            //Toast.makeText(getApplicationContext(), volleyError.toString(), Toast.LENGTH_LONG).show();
        }
    });

A: So the reason your getting an error is because
"latitude":
{
     "index1": "100",
     "index2": "200",
}

should be (in order to get your code to work):
"latitude": [
         { "index1": "100" },
         { "index2": "200" },
]

*

*In the original JSON, you've just got a JSON object with keys that are named index1 and index2.

*In the second JSON, you've got an array of JSON objects with index1 as a key in the first element and index2 in the second element.

UPDATE:
Even though the above will get your code to work. I recommend that you change the JSON to:
"latitude": [
    "100",
    "200",
]

and for your onResponse(...) method write:
@Override
public void onResponse(JSONObject response) {
    try
    {
        JSONArray jsonArray = response.getJSONArray("latitude");
        //Loop through array
        for (int i = 0; i<jsonArray.length(); i++)
        {
            String latitude = jsonArray.getString(i);
        }
    }
    // Rest of your code can stay the same
}

Seems more intuitive to me.


text:
Q: OCaml using parametrized module In OCaml, I am dealing with a module and a functor.
I set up the signature and struct for the input module and the functor.
Then I made a new module using modules above.
It turned out that my new module does not contain functions in the input module.
Am I supposed to be able to use functions with my new module?
Functions in the functor works fine, by the way.
Also, How can I make sure if it is a valid module?

A: Let's take a real example:
module type MONAD = sig
  type 'a t
  val return : 'a -> 'a t
  val (>>=) : 'a t -> ('a -> 'b t) -> 'b t
end

module MonadOps (M : MONAD) = struct
  open M (* values from M visible in scope *)
  let rec mapM f = function
    | [] -> return []
    | x::xs ->
        f x >>= fun y ->
        mapM f xs >>= fun ys ->
        return (y :: ys)
end

module Option = struct
  type 'a t = 'a option
  let return x = Some x
  let (>>=) m f = match m with
    | None -> None
    | Some x -> f x
end

module OptionOps = MonadOps(Option)

let test = OptionOps.mapM
(* val test : ('a -> 'b Option.t) -> 'a list -> 'b list Option.t = <fun> *)
let test = OptionOps.return x
(* Error: Unbound value OptionOps.return *)

The functor MonadOps provides some generic features built on top of any monad, but it does not by itself contain the base monad features. It provides extra stuff without including the existing stuff.
You can change that by using the include item to include the content of an existing module inside the module value being defined:
module MonadOps (M : MONAD) = struct
  include M (* values from m *included* in the module *)
  let rec mapM f = function
    [...]
end

However, I don't necessarily advise to do that. You are introding some redundancy that is convenient in some situations (eg. if you want to open just one module and have everything in scope), but can also make for some problems in other situations, eg. if you want to combine two module-extending functor you have to wonder in which order to apply them, and you may run into strange module-system hackery. ML module systems are complex beasts inside, and I recommend to keep your uses simple to avoid run into corners.
Note that by not including M into the functor, you leave the functor's users the choice to do it whenever they want to: they have more options that if you decide to include it directly in the functor. The way I would use such a functor would be something like
(* file 'option.ml' *)
type 'a option = None | Some of 'a

module Monad = struct
  ...
end

module Ops = MonadOps(Monad)

include (Monad : MONAD with type 'a t := 'a option)
include Ops

A: In a simpler setting, any value exported by the module M bound in functor F can be accessed by using the M. qualifier (like for any module):
(* out there M does not exist *)
module F (M : sig val v : int end) =
struct
    (* in there M is defined *)
    let m_v = M.v
end

or by using open M before any access to values of M.
module  F (M : sig val v : int end) =
struct
    open M
    let m_v = v
end

If you want to make the values of M available from the module generated by F, you must somehow export it, either:

*

*directly by aliasing certain values of M in the new module,
module F (...) = struct
    let v = M.v
end

*by including the module in its entirety
module F (...) = struct
    include M
end

It is not necessary always possible or easy to use inclusion, since you might want to define types name colliding with other types in M.

*by making the module a part of the new module
module F (....) = struct
    module M' = M
end

module G = F(struct let v = 5 end);;
print_int G.M.v;;

Include or not include? It depends on the client side of the functor, and the client side of the generated module. You might work on a programme which must only know about the generated module, or only know about the functor. If the module M content is necessary for operating the module G, which is delivered ready made, then you have to provide M somehow.


text:
Q: How to quickly get the reason for the most recent update of a package from the command-line? Is there a command-line command I can run to quickly determine the reason for a package update?  Ideally, a command that dumps a set of URLs to all of the relevant information.
For example (it's a long example - sorry), today all of my systems updated these 5 packages:
Reading package lists...
Building dependency tree...
Reading state information...
The following packages will be upgraded:
  login openssh-client openssh-server openssh-sftp-server passwd
5 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 1,977 kB of archives.
After this operation, 24.6 kB of additional disk space will be used.
Get:1 http://archive.ubuntu.com/ubuntu/ trusty-updates/main login amd64 1:4.1.5.1-1ubuntu9.2 [301 kB]
Get:2 http://archive.ubuntu.com/ubuntu/ trusty-updates/main passwd amd64 1:4.1.5.1-1ubuntu9.2 [759 kB]
Get:3 http://archive.ubuntu.com/ubuntu/ trusty-updates/main openssh-sftp-server amd64 1:6.6p1-2ubuntu2.6 [34.2 kB]
Get:4 http://archive.ubuntu.com/ubuntu/ trusty-updates/main openssh-server amd64 1:6.6p1-2ubuntu2.6 [321 kB]
Get:5 http://archive.ubuntu.com/ubuntu/ trusty-updates/main openssh-client amd64 1:6.6p1-2ubuntu2.6 [562 kB] Preconfiguring packages ...
Fetched 1,977 kB in 3s (506 kB/s)
(Reading database ... 88021 files and directories currently installed.) Preparing to unpack .../login_1%3a4.1.5.1-1ubuntu9.2_amd64.deb ...
Unpacking login (1:4.1.5.1-1ubuntu9.2) over (1:4.1.5.1-1ubuntu9.1) ...
Processing triggers for man-db (2.6.7.1-1ubuntu1) ...
Setting up login (1:4.1.5.1-1ubuntu9.2) ...
(Reading database ... 88021 files and directories currently installed.) Preparing to unpack .../passwd_1%3a4.1.5.1-1ubuntu9.2_amd64.deb ...
Unpacking passwd (1:4.1.5.1-1ubuntu9.2) over (1:4.1.5.1-1ubuntu9.1) ...
...

I'm not seeing anything obviously related on the Ubuntu Security Notices (USN) page, which is my usual go-to location.  Updates of this nature (login, passwd, and OpenSSH) tend to be security related, but that doesn't, on the surface, appear to be the case here.
apt-cache show login

Shows a source of 'http://pkg-shadow.alioth.debian.org/', which says the parent 'shadow' package hasn't been updated since May 9, 2014.  Okay.  Not sure why there isn't a link to Launchpad.net baked into apt-cache show, but whatev's.  Looking specifically at the 'shadow' package on Launchpad 'https://launchpad.net/ubuntu/+source/shadow' and looking for the package version '1:4.1.5.1-1ubuntu9.2', I see a changelog:
18 hours ago

Changelog

shadow (1:4.1.5.1-1ubuntu9.2) trusty; urgency=medium

  * debian/control, debian/rules: re-enable libaudit support. (LP: #1478087)

 -- Mathieu Trudel-Lapierre <email address hidden>  Fri, 22 Jan 2016 11:21:57 -0500

Which links to bug report #1478087.  Which, in turn, has a discussion on 'libaudit', which is used to track login attempts and why the package update happened.
In short, after spending about a half hour, I can finally figure out why the update happened.  It is security related as I originally suspected, but getting to that point of knowledge took too long.  Which brings me back around to the original question I started with, which is:  How to quickly get the reason for the update of a package from the command-line?

A: A simple way to check why a package has been updated is to check its changelog.
apt-get changelog pkgname

For example, here is the current changelog for openssh-client
$ apt-get changelog openssh-client

openssh (1:5.9p1-5ubuntu1.8) precise-security; urgency=medium

  * SECURITY UPDATE: information leak and overflow in roaming support
    - debian/patches/CVE-2016-077x.patch: completely disable roaming option
      in readconf.c.
    - CVE-2016-0777
    - CVE-2016-0778

 -- Marc Deslauriers <marc.deslauriers@ubuntu.com>  Wed, 13 Jan 2016 10:49:17 -0500

openssh (1:5.9p1-5ubuntu1.7) precise-security; urgency=medium

...


text:
Q: Simplifying a Summation : $\sum_{i=0}^\infty \frac{4^i}{(i!)^2}$ How can I simplify the following summation:
$$\sum_{i=0}^\infty \frac{4^i}{(i!)^2}$$
I cannot think of anyway to simplify this.

A: As said in comments, since the expansion of the modified Bessel function of the first kind write (see here)$$I_\nu(z)=\left(\frac z2 \right)^\nu \,\sum_{k=0}^\infty \frac{\left(\frac z2 \right)^{2k} }{k! \,\Gamma(\nu+k+1)}$$ then
$$I_o(z)=\sum_{k=0}^\infty \frac{\left(\frac z2 \right)^{2k} }{k! \,\Gamma(k+1)}=\sum_{k=0}^\infty \frac{\left(\frac z2 \right)^{2k} }{(k!)^2 }$$ and, as a result, $$\sum_{i=0}^\infty \frac{x^i}{(i!)^2}=I_0\left(2 \sqrt{x}\right)$$ which cannot reduce to elementary functions.
For your case, the numerical evaluation would converge very fast since $$u_n=\frac {4^n}{(n!)^2}\implies \frac{u_{n+1}}{u_n}=\frac{4}{(n+1)^2}$$ I give you below the numerical values for suucessive $n$
$$\left(
\begin{array}{ccc}
n & \text{exact} & \text{approx} \\
 0 & 1 & 1 \\
 1 & 5 & 5 \\
 2 & 9 & 9 \\
 3 & \frac{97}{9} & 10.7777777777778 \\
 4 & \frac{101}{9} & 11.2222222222222 \\
 5 & \frac{847}{75} & 11.2933333333333 \\
 6 & \frac{4577}{405} & 11.3012345679012 \\
 7 & \frac{1121429}{99225} & 11.3018795666415 \\
 8 & \frac{373811}{33075} & 11.3019198790627 \\
 9 & \frac{90836089}{8037225} & 11.3019218697996 \\
 10 & \frac{2270902241}{200930625} & 11.3019219494291 \\
 11 & \frac{1221240761}{108056025} & 11.3019219520614 \\
 12 & \frac{353287505863}{31259064375} & 11.3019219521346 \\
 13 & \frac{417939119435993}{36979473155625} & 11.3019219521363
\end{array}
\right)$$ As you can see, using seven terms, we already obtain six correct significant figures.


text:
Q: TSQL Not Equal <> behaving differently I have two tables in SQL Server 2008 R2
TABLE1 - Column DateCreated datetime null
TABLE2 - Column DateCreated datetime null

When I see the profiler
SELECT * from TABLE1
WHERE DateCreated <> '2011-06-10 00:00:00.000'

I have 3 records for this date
2011-06-10 00:00:00.000
2011-06-10 00:00:00.000
2011-06-10 09:45:00.000

None of the records are returned
On TABLE2
SELECT * from TABLE2
WHERE DateCreated <> '2011-06-10 00:00:00.000'

I have 3 records for this date
2011-06-10 18:02:05.000
2011-06-10 18:05:08.000
2011-06-10 18:07:09.000

All 3 records are returned. This is very weird. Why in the 1st case do I not get back any records when I should get 1 record back???

A: In your SQL, '2011-06-10 00:00:00.000' is not a date. It is a string that gets converted to a date. In the database '2011-06-10 00:00:00.000' might actually be '2011-06-10 00:00:00.00001'. Maybe try using DATEDIFF(mcs,DateCreated,'2011-06-10 00:00:00.000') to see what the actual difference is.


text:
Q: Laravel Query Builder select a column with multiple values I have four arrays and a one variable like below.
$jptypes = ["26","27"]
$jvalues = ["57","62"]
$jbranches = ["33","63"]
$jstream = ["2","2"]
$jmarks = 10
I want to collect employees with those matching arrays and value.
 $empsarr = DB::table('otc_employee_qualifications')
            ->whereIn('emp_qualifctn_type',$jptypes)
            ->whereIn('qualification_value',$jvalues)
            ->whereIn('emp_qualifctn_branch',$jbranches)
            ->whereIn('emp_qualifctn_stream',$jstream)
            ->where('qualification_mark','>=',$jmarks)
            ->distinct()
            ->lists('employee_id');

  return $empsarr;

But whereIn method will not checking  both values. its in OR case.
I want to check both the values in the array at once.
how can i solve this issue ?


text:
Q: Django Unique properties in admin I'm building a generic template that will be deployed for several sites, one of the customizing options we'd like to allow would be a custom font for the title text. I'd like to add this property to the admin interface.
Is there a better technique then creating a model for these properties and doing a Model.objects.get() to retrieve 1 instance.
Thanks in advance

A: I'd suggest using a context processor, and only hitting the database on first request, or if you forcefully trigger a reload of the settings. For instance:
from project.theme.models import Theme

THEME_SETTINGS = Theme.objects.values().get(id=1) # hits db first request

def theme(request):
    if 'reset_theme' in request.GET: # or some other mechanism
        THEME_SETTINGS = Theme.objects.values().get(id=1) # reset theme settings
    return THEME_SETTINGS

To use, just add the context processor to TEMPLATE_CONTEXT_PROCESSORS in your settings. Context processors are fairly simple, they take a RequestContext and return a dict used to populate the RequestContext.

A: I've currently implemented django-chunks from github
It allows the use of
{% load chunks %}
{% chunk "key" %}

where the chunk is a key,value set.
I've used this technique to insert "dynamic css", (my admin can provide the css required to upload a custom font)
Example:
subtitle_font_css
<style>
@font-face {
    font-family: "impact";
    src: url('/static/fonts/impact.ttf');
}
</style>

subtitle_font
font-family: impact;

Now for the html:
<head>
    {% load chunks %}
    {% chunk "subtitle_font_css" %}
</head>
<body>
    {% load chunks %}
    <span style="{% chunk "subtitle_font %}"> Title </span>
</body>


text:
Q: Google Map js showing a map in china rather than the actual location Basically, I'm just trying to set up my web page google map to show a location I've gotten the coordinates to, but it shows a location in China on my web page, no matter what coordinates I try it's always t he same place.

if($('#map-canvas').length != 0){
  var map;
  function initialize() {
   var mapOptions = {
    zoom: 16,
    scrollwheel: false,
     center: new google.maps.LatLng(25.932884, 83.569633),
     styles: [
       {"stylers": [{ hue: "#000000" },
       { saturation: -100 },
       { lightness: -5 }]},
         {
           "featureType": "road",
           "elementType": "labels",
           "stylers": [{"visibility": "off"}]
         },
         {
           "featureType": "road",
           "elementType": "geometry",
           "stylers": [{"lightness": 100},
                 {"visibility": "simplified"}]
         }
     ]
   };
   map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
   var image = 'include/images/map-marker.png';
   var myLatLng = new google.maps.LatLng(39.091617, -77.204273);
   var beachMarker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    icon: image
    });
  }

  google.maps.event.addDomListener(window, 'load', initialize);
 }
.map-container{height:400px; position:relative; margin:0; padding:0; }
#map-canvas{height:100%;}

I expected it to show these coordinates: 39.0916165, -77.2064619
Instead, I see a map of china, example can be seen here:
http://delcontedesigns.com/yaeger/contact
Any suggestions or help would be appreciated. I've done maps before but never ran into this issue.

A: Probably because you're centering your map on the wrong coordinates. Try the following instead:
center: new google.maps.LatLng(39.0916165, -77.2064619)

DEMO

A: Your code is centering the map at center: new google.maps.LatLng(25.932884, 83.569633).  Change that to center: new google.maps.LatLng(39.0916165, -77.2064619) or call map.setCenter(myLatLng); (once you have defined that).
code snippet:

if ($('#map-canvas').length != 0) {
  var map;

  function initialize() {
    var mapOptions = {
      zoom: 16,
      scrollwheel: false,
      center: new google.maps.LatLng(25.932884, 83.569633),
      styles: [{
          "stylers": [{
              hue: "#000000"
            },
            {
              saturation: -100
            },
            {
              lightness: -5
            }
          ]
        },
        {
          "featureType": "road",
          "elementType": "labels",
          "stylers": [{
            "visibility": "off"
          }]
        },
        {
          "featureType": "road",
          "elementType": "geometry",
          "stylers": [{
              "lightness": 100
            },
            {
              "visibility": "simplified"
            }
          ]
        }
      ]
    };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    var image = 'include/images/map-marker.png';
    var myLatLng = new google.maps.LatLng(39.091617, -77.204273);
    var beachMarker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      // icon: image
    });
    map.setCenter(myLatLng);
  }

  google.maps.event.addDomListener(window, 'load', initialize);
}
.map-container {
  height: 400px;
  position: relative;
  margin: 0;
  padding: 0;
}

#map-canvas {
  height: 100%;
}


text:
Q: java.lang.NoClassDefFoundError : org/apache/commons/lang3/ObjectUtils I'm trying to write a very simple servlet which must extract data from a csv file and display the result, here is the code:
      Reader reader = new FileReader(filePath);
      CSVReader csvReader = new CSVReader(reader);
      String[] data;
      PrintWriter out = response.getWriter();

      response.setContentType("text/html");
      while((data = csvReader.readNext()) != null){
        //do something
      }

but then I receive this log:

Type Exception Report
Message Servlet execution threw an exception
Description The server encountered an unexpected condition that
  prevented it from fulfilling the request.
Exception
javax.servlet.ServletException: Servlet execution threw an exception
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.lang.NoClassDefFoundError: org/apache/commons/lang3/ObjectUtils
    com.opencsv.CSVParser.(CSVParser.java:209)
    com.opencsv.CSVReader.(CSVReader.java:196)
    com.opencsv.CSVReader.(CSVReader.java:178)
    com.opencsv.CSVReader.(CSVReader.java:130)
    com.opencsv.CSVReader.(CSVReader.java:70)
    TheClass.doGet(TheClass.java:19)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note
The full stack trace of the root cause is available in the server
  logs.

I'set the tomcat-websocket CLASSPATH and copied the jar file in lib directory in WEB-INF but non of them affected.
The problem is raised when we make a CSVReader class. Is there anyone for some helps?

A: You are saying you have the jar file for opencsv but do you have the jar files for the dependencies?  Opencsv has dependencies on two to three apache commons libraries depending on which version of opencsv you are using.   The dependencies of the latest version can be found at http://opencsv.sourceforge.net/dependencies.html.
If you are building your project using maven or gradle you should have these dependencies already included in your war file.  How are you building/deploying your app?


text:
Q: Can you use a named JSON property to pass a complex object to a C# controller? I'm having trouble with some JSON data populating a C# object in the parameter of a POST method on my Web API controller when I try to assign a property name in my JSON object.
Here is my API controller:
[HttpPost]
public HttpResponseMessage MyResource(MyComplexClass myClass)
{
    var test = myClass.Name;

    return Request.CreateResponse(HttpStatusCode.Created);
}

Here is the MyComplexClass:
public class MyComplexClass
{
    public string Name { get; set; }
    public string Id { get; set; }
}

And here is my AJAX call:
<script>
    function test() {
        var innerData = {
            Name: 'Bob Loblaw',
            Id: "1"
        };

        var myData = {
            myClass: innerData
        };

        $.ajax({
            type: "POST",
            url: "api/Test/MyResource",
            data: JSON.stringify(myData),
            contentType: "application/json",
            dataType: "json",
            success: function (response) {
                // do success stuff
            },
            error: function (err) {
                // do error stuff
            }
        });
    }
</script>

The problem is: when I include the innerData object as a property in the myData object in my JS code, the properties of the myClass object are all null.
I know that if I pass the innerData into the AJAX call itself, the myClass object is populated properly, but I'm curious about why I can't use a named JSON property to pass a complex C# object to the controller.
Does anyone know how to pass the myClass object as a named JSON property, or can you give an explanation as to why I can't?
Rephrased question:
If this JSON object:
var data = {
    Name: 'Bob Loblaw',
    Id: "1"
};

matches up with this controller method:
public HttpResponseMessage MyResource(string Name, string Id)

Why doesn't this JSON object:
var data = {
    myClass: { Name: 'Bob Loblaw', Id: "1" }
};

match up with this controller method?
public HttpResponseMessage MyResource(MyComplexClass myClass)

Additional question:
Is it possible to have an API method declared as the following:
public HttpResponseMessage MyResource(MyComplexClass myClass, string anotherValue)

And if so, how would the JSON object be structured?

A: It's because you've nested the innerData object and C# doesn't know what it is. You could either not nest that object by just passing the innerData to ajax or have another layer to your C# object like so:
public class MyOuterClass
{
    public MyComplexClass innerData { get; set; }
}

A: Why doesn't this JSON object:
var data = {
    myClass: { Name: 'Bob Loblaw', Id: "1" }
};

match up with this controller method?
public HttpResponseMessage MyResource(MyComplexClass myClass)

Because of how model binding works in WEB API, when you send
var data = {
    Name: 'Bob Loblaw',
    Id: "1"
};

WEB API binds the properties of the json object you sent to the properties of the class you defined as a parameter.
So, in order to match
var data = {
    myClass: { Name: 'Bob Loblaw', Id: "1" }
};

MyComplexClass would need to be defined as
public class MyComplexClass
{
    public Object myClass{ get; set; }
}


text:
Q: specify position of some nodes in a graph Is there way to specify position of a certain subset of nodes of a connected graph, while some algorithm decide the position of other nodes?  I am hoping to find an algorithm which treats edges to be like spring so that it won't be away from other nodes too far, e.g. graphopt.  I looked at several other algorithms in igraph, e.g., lgl, drl, but none of them doesn't seem to allow specifying nodes' position, i have to let algorithm to have complete control of all nodes' locations.
I am asking this because i have network of data, and some of nodes i can find approximate geographic coordinates.  I am hoping to show the entire network on a map.  Viewing the network on a map then i can iteratively identify more nodes with some geographic identity, and at end i have georeferenced graph with decent accuracy at least visually.
I got started with igraph on R, but i am open to try other packages/language, or even GIS tool if there is something close to what i am looking for.
Thanks!
[EDIT]
After all, this question is not very good question, but since i started it, let me describe further what I am looking for.  Hopefully what I am seeking make sense and somebody have done that before.
G5W's suggestion is moving toward where i want go, but i am hoping to apply the principle of original algorithm after then got pinned to the desired direction.
FR method's paper says that:

We have only two principles for graph drawing:

*

*Vertices connected by an edge should be drawn near each other.

*Vertices should not be drawn too close to each other.

So i thought that the large loop including path 10-8-4-1-3 should shrink and get closer to the remaining nodes.  I imagined that i can find layout like below, if I fix the four points like G5M did.

I thought that algorithm may by chance create such graph, and tried like below, very crude, brute force method.  But the algorithm never generated what i was looking for...  I guess i need to specify some exemption to the algorithm to treat those edges between pinned nodes.
library(igraph)
set.seed(1)
g = erdos.renyi.game(10, 0.3)
LO = layout_with_fr(g)
plot(g, layout=LO)

n <- nrow(LO)
i <-  0
for (i in 1:100000) {
#  i <- i + 1
  LO <- layout_with_fr(g)
  chk <- c(all(LO[c(5,7),2] >= sort(LO[-c(5,7),2])[n-3]), # 5,7 should come close to top
           all(LO[c(2,9),2] <= sort(LO[-c(2,9),2])[2]),   # 2,9 near bottom
           all(LO[c(2,7),1] <= sort(LO[-c(2,7),1])[2]),   # 2,7 toward left
           all(LO[c(5,9),1] >= sort(LO[-c(5,9),1])[n-3])  # 5,9 toward right
  )
  if (all(chk)>1 ) break
}

[EDIT2]
Still looking for some way to do this.  I found a d3 page Stick Force Layout, which seems what I want.  The problem is that I am not sure I can export coordinates once I am  happy with the layout.  Also I probably want be able to save intermediates.  So that means i should be able to node coordiates along with attributes if they got stuck or not.  And this data in and out.  If this is trivial for people who know JS, please give me a pointer.  I try come up with json in/out interface if not.
A graph with no node position specified by user, determined by some kind of force layout algorithm

I pick position of some of nodes so that make the graph tree-like.  This is just one example but my point is that i want to be able to rough shape of layout without not have to determine position of every single nodes.

A: You do not give any example data for the graph or the specific layout that you are trying to achieve, so I will take a random graph and a simple configuration as the target. The idea is that you can let any algorithm lay out all of the points and then adjust the position of the ones that you want to specify.
## basic graph for illustration
library(igraph)
set.seed(1)
g = erdos.renyi.game(10, 0.3)
LO = layout_with_fr(g)
plot(g, layout=LO)

OK, now suppose that we want to take the nodes 2,5,7 and 9 and lay them out in a box without any edges crossing. What I want to do is take a basic box layout and shift it so that these four nodes and their edges are away from the rest of the graph. I will just shift these four nodes so that they are a little above all of the others.
UB = max(LO[,2])
DesiredLO = matrix(c(0,0,0,1,1,0,1,1), nrow=4, ncol=2, byrow=TRUE)
LO[c(2,7,9,5), ]  = DesiredLO + matrix(rep(LO[2,], 4), ncol=2, byrow=TRUE)
LO[c(2,7,9,5), 2] = LO[c(2,7,9,5), 2] + UB - LO[2,2] + 1
plot(g, layout=LO)

Maybe you can adapt this to what you want.  If not,  please use this example or something like it to specify more clearly what you do want.


text:
Q: Spring get time to next cron schedule I have implemented a class in spring boot with @scheduled as follows
@component
public class RunSchedule{
  @scheduled(cron="* * * 10 *")
     public void execute(){
        do something....
     }
}

I would like to be able to get the time to the next execution of the current method from within the code is this something that is possible?


text:
Q: How to fill column' value with another column and keep existing? I have this dataframe with two column['c1','c2'], and I want to fill c2 with its corresponding c1 if exist, also if c1 already have a value keep it don't change it with c2. Here is an example:
input
c1             c2
HP_0003470
HP_8362789    HP_0093723
              MP_0000231
              MP_0000231

output
c1             c2
HP_0003470
HP_8362789    HP_0093723
MP_0000231    MP_0000231
MP_0000231    MP_0000231

It's look easy, but I'm beginner in python :(
Any help please.

A: You can do so:
df['c1'] = df['c1'].replace('',np.NaN).fillna(df['c2'])
df['c2'] = df['c2'].replace('',np.NaN).fillna(df['c1'])

Output:
           c1          c2
0  HP_0003470  HP_0003470
1  HP_8362789  HP_0093723
2  MP_0000231  MP_0000231
3  MP_0000231  MP_0000231


text:
Q: What's the difference between a certificate and api key? I'm not sure which of these I need – a push certificate or an API key. They appear to do the same thing, but I'm not sure what the difference is, or even where to find them.

A: If you're developing an iOS app, you need to provide ExactTarget with a push certificate. ET signs your push message with this certificate so your app knows it's valid when received.
More info: https://code.exacttarget.com/mobilepush/integrating-mobilepush-sdk-your-ios-mobile-app#Provision
An Google Cloud Messaging (GCM) API Key is for Android apps.
More info: https://code.exacttarget.com/mobilepush/integrating-mobilepush-sdk-your-android-mobile-app#Provision
As a side note, make sure you use the SAME Code@ AppCenter app for both iOS and Android. You can always segment by Platform later when sending a push message. You can also do sends to both platforms at the same time this way.


text:
Q: controlling the time to load and play animated gifs I have a slide with many animated gifs. Every slide contains an animated gif.
The effect I am trying to achieve is having the animated gifs play according to the timeline I created in photoshop and from the first frame to last when in view.
My issue is the animated gifs will start from the middle of the timeline instead of from the first frame when it is active and in view. I reckon it could be due to the loading time? I have tried increasing the time for the first frame and last frame of each slide  but to no avail.
Is there a way to control the time to load and play the animated gifs when it is in view? is it something that needs to be done in javascript or jQuery?

A: From my point of view, CSS Sprites will give you better support that you wanted in your animation. Most important thing you need is to control over animation.
As you don't have any control over animated GIFs. You can't start them, you can't stop them, only thing they just do is to animate as soon as they load.
On the otherhand, with sprites, you can control the animation. Most importantly you can start, stop and react to browser events, pan through the animation.
As reference you can see Google Doodles which only activates when you only click on them.
For active reference, you can see the blog which might inspire you to use CSS Sprites.
https://itnext.io/creating-css-animations-using-sprite-sheet-47e2b7a3793c

Again, it's only opinion. Decisions is yours which one you will use for animation.


text:
Q: How to add dynamic header to generated PDF document Im using TuesPechkin to ceate Pdfs from dynamic Html.
The body is easy as it can take a Html string, the header & footer however only take Urls.
I have them stored locally atm as html, I can bring them in to the document, but without any dynamic content.
Is there a way to use Razor or similar to bring a value in like this -
var document = new HtmlToPdfDocument
{
    GlobalSettings = new GlobalSettings(),
    Objects =
    {
        new ObjectSettings
        {
            HtmlText = "
Some Html
",
            Footer = new FooterSetting { PageUrl = "file://C:/file.cshtml?Name=name" }
        }
    }
};

Html looking something like

Name: @Request["name"]

The project is just a class library so I believe it's missing some aspects needed to run razor?
Thanks in advance for any input.

A: You can try rendering the razor code to a string, then saving it as a file and finally export the file to PDF.
Sometime like this:
Razor to String
public string RenderRazorViewToString(string viewName, object model)
{
    ViewData.Model = model;
    using (var sw = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);
        viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
        return sw.GetStringBuilder().ToString();
    }
}

Export to PDF
public void MyPDFExport()
{
    string url = @"d:\Foo.html";
    string html = RenderRazorViewToString("File", "myName");
    System.IO.File.WriteAllBytes(url, System.Text.Encoding.ASCII.GetBytes(html));

    var document = new HtmlToPdfDocument
    {
        GlobalSettings = new GlobalSettings(),
        Objects =
        {
            new ObjectSettings
            {
                HtmlText = "
Some Html
",
                FooterSettings = new FooterSettings { HtmlUrl = url }
            }
        }
    };
    IConverter converter =
        new ThreadSafeConverter(
            new RemotingToolset<PdfToolset>(
                new Win32EmbeddedDeployment(
                    new TempFolderDeployment())));

    byte[] result = converter.Convert(document);
}

View File.cshtml
@model string

Name: @Model


text:
Q: Safari Desktop and Mobile: Image overlayed by canvas is very blurry I have an image that is overlayed by a canvas. Both image and canvas are wrapped in a div that is scaled. When drawing on the canvas the image gets very blurry. Do you have any ideas how to get rid of the blur?
Please see this fiddle:

            <canvas id="supercanvas" width="125" height="150" style="width:125px; height:125px"></canvas>


text:
Q: Can't use jsPDF-AutoTable is not a function since v3.5.13 (jsPDF v2.1.1) When I was using older versions of the libraries, I could create pdf just fine. But since these new versions I can't. Earlier I just downloaded jspdf.min.js file, but now I can see various of versions, like umd, es.. But I don't know, what to use (?), so I downloaded umd version.
I don't use angular or node.js, so I can't use require or import (with import I have an error: Uncaught SyntaxError: export declarations may only appear at top level of a module) instructions in my javascript code before creating pdf document. So I'm using  const { jsPDF } = window.jspdf; to to use jsPDF class (without it I get error "Uncaught ReferenceError: jsPDF is not defined", after line const doc = new jsPDF();).
But I want to use the plugin AutoTable also and in official page of the plugin https://github.com/simonbengtsson/jsPDF-AutoTable the author uses import or require, for me it doesn't work. When I try
const { jsPDF } = window.jspdf;
const doc= new jsPDF();
doc.autoTable({
  head: [['Name', 'Email', 'Country']],
  body: [
    ['David', 'david@example.com', 'Sweden'],
    ['Castille', 'castille@example.com', 'Spain'],
  ],
})

I get the error Uncaught TypeError: pdf.autoTable is not a function. How could I use the libraries right?
I guess jsPDF works for me with version umd and const { jsPDF } = window.jspdf; (I created just a simple document with a string and it worked), but AutoTable doesn't work

A: The only solution, that works for me now, is to save the code of jsPDF and AutoTable in the same file. It's not good idea, I know, I would like to have them in separate files, but I haven't founded another way. It anybody could tell a better way to avoid the errors, it would  be great

A: Export autoTable method, import autoTable from 'jspdf-autotable'
function createPdf() {
var doc = new jsPDF();
const head = [['ID', 'Country', 'Index', 'Capital']]
const data = [
[1, 'Finland', 7.632, 'Helsinki'],
[2, 'Norway', 7.594, 'Oslo'],
[3, 'Denmark', 7.555, 'Copenhagen'],
[4, 'Iceland', 7.495, 'Reykjavík'],
[5, 'Switzerland', 7.487, 'Bern'],
[9, 'Sweden', 7.314, 'Stockholm'],
[73, 'Belarus', 5.483, 'Minsk'],
]
autoTable(doc, {
head: head,
body: data,
didDrawCell: (data) => {
console.log(data.column.index)
},
})
doc.save('repro.pdf');
}

A: I successfully tried it for the newer versions of jspdf (version 2.5.1) and autotable (version 3.5.25).
Minimal example:
<!DOCTYPE html>

        <title>jspdf-autotable demo</title>

save pdf modal will pop up automatically


text:
Q: how to include filename in first column of existing csv file I have existing csv file.I want to modify the csv file and include filename in first column of the file.
Example
file.csv

1,love,anger

Modified csv
file.csv
file.csv,1,love,anger

Can we do it using  one liner in awk or unix
Thanks a lot in advance

A: another one
$ awk '{print FILENAME (NF?",":"") $0}' file

A: It's just as simple as: awk '{if($0) printf("%s,%s\n", FILENAME, $0); else print FILENAME;}' file.csv
where file.csv is input file name.
UPD.: I modified command adding condition to correctly deal with empty lines


text:
Q: I want to search for values greater than a specific number (e.g. 0) and list down adjacent cell values in MS Excel I have two columns of data with 'vehicle count' in first column and 'travel time' in second column. I want to search for rows with vehicle count greater than a specific number (e.g. 0) and list down adjacent cell values from the 'travel time' column.
Data Sample

A: You need FILTER() function like-
=FILTER(B:B,A:A>0)

Edit: For Excel-2019 use below formula.

=IFERROR(INDEX($B$1:$B$100,AGGREGATE(15,6,ROW($1:$100)/($A$1:$A$100>0),ROW($A1))),"")

Edit2: As per attached screenshot use below formula-

=IFERROR(INDEX($C$4:$C$27,AGGREGATE(15,6,(ROW(B$4:$B$27)-ROW($B$3))/($B$4:$B$27>0),ROW(1:1))),"")


text:
Q: How to load database from SQLite DB file? I want to create an SQLite file that will contain the database I will be using in my android app. I need to load it every time I start the app.
An advice on how to do so would be very much appreciated.
Thanks!


text:
Q: Angular 4 nested *ngFor for a number of times I have one Json object containing file hierarchy list like below:
{
    "path": "\\Users\\ad00440946\\Downloads\\Angular2-
                 GettingStarted-master",
    "name": "Angular2-GettingStarted-master",
    "type": "folder",
    "children": [
        {
           "path":
               "\\Users\\ad00440946\\Downloads\\Angular2-
                GettingStarted-master/Angular2-GettingStarted-master",
            "name": "Angular2-GettingStarted-master",
            "type": "folder",
           "children": []
        }
   ]
 }

And the list goes on till it reaches to end of a file where children array will be empty.
i have to print all this files in a tree view like this. The layout is working fine but problem is i don't know how many levels of children it will have and how many times do i need to iterate. Is there any work arround?
Here's my HTML code:

        {{allFilesData.name}}

             {{childl1.name}}

                    {{childl2.name}}

                            {{childl3.name}}

A: You should make a separate component which renders children, which you can use in your parent:

  <tree-item [data]="allFilesData"></tree-item>

And have a TreeItemComponent which you can repeat if the data has children:
@Component({
  selector: 'tree-item',
  template: `

      {{data.name}}

 0">

         <tree-item [data]="child"></tree-item>

  `
})
export class TreeItemComponent {
  @Input()
  public data: any = {};
}

beware that this is untested code, and merely a guideline for you. Basic concept is, use a component which renders children, and will render children of children if it's necessary


text:
Q: Switching to a fragment from a fragment onClick() I'm trying to create an application that has a similar framework to that of Snapchat, where I have three screens that can be swiped through. I have three screens (made with a fragment for each) and wish to slide to a screen on button press. Just to be clear, I have a table on one screen, from which a row is clickable and has a function that it calls onClick(). I wish to slide to the desired fragment using the mentioned function.
Fragment.Java:
public class ChatFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.chat_fragment_layout, container, false);
        rootView.findViewById(R.id.row0).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                openfrag("1");
            }
        });
        rootView.findViewById(R.id.row1).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                openfrag("2");
            }
        });
        rootView.findViewById(R.id.row2).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                openfrag("3");
            }
        });

        return rootView;
    }
    private void openfrag(String number){
    }

I'm swiping through the fragments by using a PagerAdapter that extends FragmentPagerAdapter:
public class PagerAdapter extends FragmentPagerAdapter {

    public PagerAdapter(FragmentManager fm) {
        super(fm);

    }

    @Override
    public Fragment getItem(int arg0) {
        switch (arg0) {
            case 0:

                return new MessageFragment();
            case 1:
                return new ChatFragment();
            case 2:
                return new CameraFragment();
            default:
                break;
        }
        return null;
    }

    @Override
    public int getCount() {
        return 3;
    }

I have tried the replace method with fragmentmanager, but that is not what I want, I want it to act as if I swiped to that fragment.
Thanks for the help.

A: You can use simply this given code
        String tag = "android:switcher:" + R.id.pager + ":" + 0;
        AddStudentFragment f = (AddStudentFragment) getActivity().getSupportFragmentManager().findFragmentByTag(tag);
        String tag1 = "android:switcher:" + R.id.pager + ":" + 1;
        AssignSubjectFragment a = (AssignSubjectFragment) getActivity().getSupportFragmentManager().findFragmentByTag(tag1);

A: I managed to get it to work with a small addition to my MainActivity class outside the onCreate method. Whenever you need to switch to another fragment in your pager, simply call this function with the item index and true/false depending if you want it to smooth scroll or not.
public void setCurrentItem (int item, boolean smoothScroll) {
        mViewPager.setCurrentItem(item, smoothScroll);
    }


text:
Q: Removing in app purchases from a new version of the application(iOS) I have an application that is live on iTunes. The app contains lots of in app purchases(non consummable). I wish to delete supoort for some in app purchases from the new version. Can I do it ? Will it lead to rejection because the user wont be able to restore those in app purchases? What would be the best way to go about it ?

A: From the iTunes Connect Developer Guide, you need to first set the "Cleared for sale" to NO, then delete the product.

Deleting In-App Purchases You can delete in-app purchases after they
  are created, but not if they are in review. Before you delete an
  approved in-app purchase, you should first remove it from sale.
Important: After you delete an in-app purchase, it is no longer
  searchable on iTunes Connect and it cannot be restored. The product ID
  for the in-app purchase can no longer be used for another in-app
  purchase after the in-app purchase is deleted.

A: Yes, it is possible to delete an in-app purchase while it is in Approved state.
1 - Log in to iTunes Connect & navigate to "Manage Your Apps section"; chose your app in there.
2- Navigate to "Manage In-App Purchases"
3- Now you need to mark the approved in-app purchased to "NOT clear for sale". Click the first "Edit" button that lets you change the summary/details of the in-app purchase. A new form/page will open. Search for "Clear For Sale" option and select "No" against it. Save your change.
4- A "delete" button will now appear at the top left corner of in-app details page. Just click that button and the in-app will be deleted.


text:
Q: C# observable collection Does anyone know can i retrieve the first element of an observation collection?
I have already added elements to my collection:
 _fetchingWords.Add(new Words { English = "abc", French = "dcb", Spanish = "mez"});

I need to retrieve the first element ,ie , abc .

A: You can use linq,
var firstElement = _fetchingWords.First();

A: ObservableCollection has an index
It is as simple as
I take it English is a property
_fetchingWords[_fetchingWords.Count - 1].English;


text:
Q: Is it possible to prevent users from modifying the code in an HTML plugin? I want to write an HTML plugin widget for users to include in their own websites. But given the way it works, it would be very easy to "game the system" by modifying the code.
In a nutshell, the widget would include instructions on how to use it, and a few POST links that lead to my site. The system is based on fair play, and it would be easy for somebody to alter the instructions, thereby altering the outcome.
Are there any techniques to prevent people from altering the content of plugins? I envision some way to keep the links from working if the instructions and styling aren't in place.
This is a simplified version of what the plugin might look like:

  Are you satisfied with this website?
  Yes

A: The short answer is no, there's no real way to prevent people from modifying your code.
Most web savvy users that are building with your plugin will eventually pull it apart and make changes. You can certainly add comments in there to ask people to be reasonable and not alter the credits on your plugin, but what you're sort of asking about is DRM in html which is being fought against at present.


text:
Q: Exporting old logs efficiently As part of cloud migration effort, in order establish an archive of old logs, I'd like to export all existing logs from Stackdriver.
I know it is possible to export old logs via entries.list as noted in the documentation:

Use the entries.list API method to retrieve your older log entries and use the destination service's API to write the log entries to the export destination.

It appears that gcloud logging read relies on exactly this call, so I can pull all my logs via the following command:
gcloud logging read "logName=projects/my-project/logs/my-entity" --order asc | pv > production-my-entity.logs

However, this is super slow.
Is there a way to download older logs faster, like in bulk or something?

A: I think at the moment there's no tools for your purpose, and this feature it's only available to store the logs in Cloud Storage, BigQuery, or Cloud Pub/Sub. You can open a feature request in this link:


text:
Q: Firefox Build Error: old-configure failed I'm trying to build Firefox(60.esr) from source. I followed the steps mentioned in Build Firefox on Windows. But it fails.
Method #1:
I followed all the steps mentioned in the Windows Build Instruction.
The Build process failed with error.
 0:24.36 ERROR: Could not find LLVM/Clang installation for compiling stylo build-time
 0:24.36 bindgen.  Please specify the 'LLVM_CONFIG' environment variable
 0:24.36 (recommended), pass the '--with-libclang-path' and '--with-clang-path'
 0:24.36 options to configure, or put 'llvm-config' in your PATH.  Altering your
 0:24.36 PATH may expose 'clang' as well, potentially altering your compiler,
 0:24.36 which may not be what you intended.

So, I tried method 2.
Method #2:
Since it was expecting LLVM/clang, I installed LLVM/Clang 6.0 and added 'LLVM_CONFIG' to the environment variable.
And then I executed mach build. Adding LLVM_CONFIG fixed the error which was caused in Method 1.
But the build failed again with error.
 0:16.24 c:/Users/n182s826/mozilla/mozilla-central/old-configure: fork: Resource temporarily unavailable
 0:18.59 m.AllocationBase 0x0, m.BaseAddress 0x607A0000, m.RegionSize 0x240000, m.State 0x10000
 0:18.59 C:\mozilla-build\msys\bin\sh.exe: *** Couldn't reserve space for cygwin's heap (0x607A0000 <0xB80000>) in child, Win32 error 0
 0:18.59       0 [main] sh 13328 sync_with_child: child 14220(0x3B8) died before initialization with status code 0x1
 0:18.59      51 [main] sh 13328 sync_with_child: *** child state waiting for longjmp
 0:18.59 c:/Users/n182s826/mozilla/mozilla-central/old-configure: fork: Resource temporarily unavailable
 0:18.61 ERROR: old-configure failed
 0:18.65 *** Fix above errors and then restart with\
 0:18.65                "c:/mozilla-build/mozmake/mozmake.EXE -f client.mk build"

I even raised a request at Bugzilla. But I haven't found any solution.


text:
Q: Tensorflow Serving Docker Image Installation Error curl: (56) GnuTLS recv error (-54): Error in the pull function I am trying to create a docker image using the following command
docker build --pull -t $USER/tensorflow-serving-devel -f tensorflow_serving/tools/docker/Dockerfile.devel .

But  when it runs the following command ,
Step 13/19 : RUN mkdir /bazel &&     cd /bazel &&     curl -H "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36" -fSsL -O https://github.com/bazelbuild/bazel/releases/download/$BAZEL_VERSION/bazel-$BAZEL_VERSION-installer-linux-x86_64.sh &&     curl -H "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36" -fSsL -o /bazel/LICENSE.txt https://raw.githubusercontent.com/bazelbuild/bazel/master/LICENSE &&     chmod +x bazel-*.sh &&     ./bazel-$BAZEL_VERSION-installer-linux-x86_64.sh &&     cd / &&     rm -f /bazel/bazel-$BAZEL_VERSION-installer-linux-x86_64.sh

it shows the exception
curl: (56) GnuTLS recv error (-54): Error in the pull function.
it shows the following exception

A: It usually would be a network issue. I remember getting such error. Also refer the given links stating that this is a network issue:

*

*https://github.com/curl/curl/issues/1707

*git error: RPC failed; curl 56 GnuTLS recv error (-54): Error in the pull function
Hope this helps!


text:
Q: Usage of "be cut out for" I found that the phrase "be cut out for" is used only in negative sentences (for example, "He's not cut out for teaching"). Is it true? Or can I make a statement like "I feel like I'm cut out for this job"?

A: The idiom be cut out for means

"[USUALLY WITH NEGATIVE] have exactly the right qualities for a particular role, task, or job" (Oxford Dictionaries).

As you see, the dictionary notes that it is usually used in a negative formation. The example sentence is, in fact, negative: "I'm just not cut out to be a policeman."
Most native speakers would probably agree that the negative variation is the more standard one. They might even cringe at the positive variation (or at least raise an eyebrow).
But still, the positive variation is perfectly acceptable. In other words, it is perfectly fine to say: "He is cut out to be a policeman."
To see this, just consult the results here. But note that some of these results contain another idiomatic construction: "We have our work cut out for us", which means (roughly) "We're going to have a tough time with this work" (here). Although this idiom is mixed in with the results, the positive use of be cut out for is nonetheless present.


text:
Q: How to provide System Priviliges to Android App I am working on a google-glass project, where i have to install/update an app programmatically, in my Research i have following complication:

*

* Getting System Dialog actions, to perform click programmatically
In order to install programmatically, the intent leads to System Dialog for user permission, but its not possible to stimulate the action of System Dialog programmatically. This solution is no possible link

* Using EMM Solution (WSO2 IOT)
 I used WSO2-IOT, but since there is no device policy manager available for google-glass, so even installing the agent apk wont help, as i can not avail any service provided by the EMM (WSO2 IOT), (to install or update my app)

*Getting System Privileges without Root
In order to use the following permissions:

*
*<uses-permission android:name="android.permission.INSTALL_PACKAGES"/>
*<uses-permission android:name="android.permission.DELETE_PACKAGES"/>
My app would require System Privileges, to silently install/delete/update the app.

According to my knowledge and research so far the only current solution is the third solution, that is to get the System Privileges. In order to get it, i also tried Sigined the APK with the system certificate.
Still i get the error:java.lang.SecurityException: Neither user 10056 nor current process has android.permission.INSTALL_PACKAGES.
Also i have tried adding the android:sharedUserId="android.uid.system to the manifest as described here
So far there is no success with achieving it. I would like to know how can i achieve installing an app silently in the background, with out rooting the device.
Any suggetions that will help will highly be appretiated.
Thank you.

A: When you need to install/update an app in the device, you have to trigger the Package Manager with the relevant details. But for triggering the Package Manager you must have the above permissions (android.permission.INSTALL_PACKAGES & android.permission.DELETE_PACKAGES) thus the device admin privileges. As you said, it is impossible to automate actions for System Dialog which is prompted for getting admin privileges.
The Device Owner concept is also available on if there exists the device policy manager. Therefore you will have to find an alternative.
I can provide you a light-weight version of an agent which successfully enroll with the IoT server without any hassle in your google-glass. But I'm afraid it is not possible to do any tasks that will need device policy manager from it.
Please find the source here: https://github.com/milanperera/android-glass-agent


text:
Q: Can I send alert message to MSN messenger or Yahoo! messenger from servers? There is a server changing a batch to add up data on the date and time, but I want to send the end states (normal end or abnormal termination) of this batch to Yahoo! Messenger or one's ID of the MSN messenger as a message, but a page and the document which I am useful for are not found.
Can I send alert message to MSN messenger or Yahoo! messenger from servers?

A: If I got it right you want to receive notifications from your server application using msn or yahoo IM protocol. The only way to archieve this is to write an msn or yahoo bot. You can use libpurple for those purposes since it supports msn, yahoo, irc, gtalk and many other protocols. In my opinion this is an overkill.
Msn messanger and Yahoo! messanger show notifications about new e-mail messages so you could send e-mails from your server application instead of IM messages.

A: Check out pymsn.  You should be able to call that lib from a script to send out alerts.  Someone did something similar and posted the python code over here.  Not sure if it still works. MSN has a habit of updating the MSNP protocol without notice.

A: There is also a .Net library called MSMP-Sharp that you can use.


text:
Q: On a relation between functions that both vanish on the same hypersurface Say I have a differentiable manifold $M$ and a smooth function $f$ on $M$. Assume that the locus of points in $M$ satisfying $f = 0$ defines a submanifold $\Sigma$, and that there is another smooth function $h$ on $M$ which also vanishes on $\Sigma$. Further assume that the gradient of $f$ nowhere vanishes on $\Sigma$.
My question is the following. Is it always true that, on a vicinity around $\Sigma$, there is another (possibly not unique) smooth function $g$ such that, locally, one can write $h = g.f$?

A: Your original claim is correct. The proof is a variant of a standard technique at the beginning of a differentiable manifolds course.
As I suggested, we choose local coordinates $x=(x^1,\dots,x^{n-1},x^n)$ so that $f(x)=x^n$. Let's write $x=(\bar x,t)$ with $\bar x = (x^1,\dots,x^{n-1})$ and $t=x^n$. Using the fundamental theorem of calculus, write
$$h(\bar x,t) - h(\bar x, 0) = \int_0^1 \frac d{du} h(\bar x,tu)\,du = t\int_0^1\frac{\partial h}{\partial x^n}(\bar x,tu)\,du.$$
Since $h(\bar x,0) = 0$ identically and $t=x^n=f(x)$, we set
$$g(\bar x,t) = \int_0^1\frac{\partial h}{\partial x^n}(\bar x,tu)\,du,$$
and we have $h=gf$, as desired.


text:
Q: Combining columns of two different datasets I have a UDF that needs to always return the same dataset structure, columns a, b, c and d.
It needs to return a UNION ALL from more than one datasource, including other UDF:s.
Let's say I have another function (myOtherUDF) that returns column a and b.
I also have a table (myTable) with the column names a, b, c and d.
What I want to do is to UNION ALL on myOtherUDF and myTable in a way that the columns c and d are added to myOtherUDF.
i.e. I want this to work although myOtherUDF lacks the columns c and d:
CREATE FUNCTION myUDF (@param INT)
RETURNS @tbl TABLE
(
    a int NOT NULL,
    b int NOT NULL,
    c int NOT NULL,
    d int NOT NULL
)
AS
BEGIN
    INSERT INTO @tbl
    SELECT * FROM myTable
    UNION ALL // this will obviously not work
    SELECT * FROM myOtherUDF(@param)
    RETURN
END

I cannot use a process to preload a table and I cannot use a view since I need the parameter @param.

A: If you explicitly list your columns - which is best practice - you immediately solve this problem, well after adding defaults for c and d from myOtherUDF;
INSERT INTO @tbl (a, b, c, d)
    SELECT a, b, c, d
    FROM myTable
    UNION ALL
    SELECT a, b, 0, 0
    FROM myOtherUDF(@param);

RETURN;

To be clear you should pretty much never select * and never insert into table without listing the columns. It saves so many issues down the line.
And for performance reasons its nearly always better to use an inline table valued function e.g.
CREATE FUNCTION myUDF
(
    @param INT
)
RETURNS TABLE
RETURN
    SELECT a, b, c, d
    FROM myTable
    UNION ALL
    SELECT a, b, 0, 0
    FROM myOtherUDF(@param);


text:
Q: does single step interrupt(01H interrupt) clear TF flag after every instruction? i want to use single step interrupt and i understand that for make this interrupt work for every instruction the TF flag should be 1 (TF=1).
and in my code i see single step interrupt work but after some instructions(maybe after every output) it stop and i should make TF=1 again to continue code and continue display outputs).
does that mean after every instruction or after special instructions cause TF=0 again ?
this code i used to set TF=1
 asm{
            PUSHF
            MOV BP,SP
            OR WORD PTR[BP+0],0100H
            POPF
        }


text:
Q: How to register inherited sub class in admin.py file in django?
*

*Project Name : fusion

*App Name : admin_lte

*Python 3.7

*Django 2

*MySql

Question is "I want to register sub model in django admin-panel",when i write code for model registration in admin.py file that time occurred below error.

django.core.exceptions.ImproperlyConfigured: The model Device is abstract, so it cannot be registered with admin.
NOTE : I used multiple separated model file.

device.py (Model File)
from django.db import models

class Device(models.Model):
device_type = models.CharField(max_length=100,blank=False)
price = models.IntegerField()
status =  models.CharField(max_length=10, default="SOLD")
issues = models.CharField(max_length=100, default="No Issues")

class Meta:
    abstract = True

def __str__(self):
    return 'Device_type:{0} Price:{1}'.format(self.device_type,self.price)

#Inheritance Concept
class Laptop(Device):
   pass
   class Meta:
       db_table = "laptop"

class Desktop(Device):
   pass
   class Meta:
       db_table = "Desktop"

class Mobile(Device):
    pass
    class Meta:
        db_table = "Mobile"

__init__.py File
from django_adminlte.models.employee import Employee
from django_adminlte.models.device import Device

admin.py
from django.contrib import admin
from.models import Employee
from.models import Device

admin.site.register (Employee)
admin.site.register (Device)

I want to show sub model (Desktop,Laptop,Mobile) in admin panel so admin can add some data from admin panel.

Project Structure Image :

A: I can see in your code Device is a abstract model. So, we should not register it because abstract models do not have associated tables in databases.
from django.contrib import admin
from .models import Employee, Laptop, Mobile, Desktop

admin.site.register(Employee)
admin.site.register(Laptop)
admin.site.register(Mobile)
admin.site.register(Desktop)

A: I also got a problem when trying to generate an admin CRUD for a class inheriting from an abstract class. But the cause was different so I'll leave my case here in case it helps someone else.
In my case, the problem was that I forgot to make the abstract class inherit from django's models.Model.
Example Code:
time.py
from django.db import models

from applications.utils import UniqueNameMixin

class Month(UniqueNameMixin):
    starting_date = models.DateField()
    ending_date = models.DateField()

class TimeSensible(models.Model):  # Here '(models.Model)' was missing.
    class Meta:
        abstract = True

    month = models.ForeignKey(Month, models.PROTECT)

transaction.py
from django.db import models

from applications.core.models.cash_flow import Concept
from applications.core.models.financial_position import Account
from applications.core.models.time import TimeSensible

class Transaction(models.Model, TimeSensible):
    concept = models.ForeignKey(Concept, models.PROTECT, blank=True, null=True)
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    account = models.ForeignKey(Account, models.PROTECT)
    detail = models.CharField(max_length=100, blank=True, null=True)

    def __str__(self):
        return '{} - {} - {} - {}'.format(self.month, self.concept, self.amount, self.account)

The error I got:
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: The model Transaction is abstract, so it cannot be registered with admin.


text:
Q: Laravel Faker lowercase This sounds very trivial but I can't seem to figure it out...
I normally have my db columns like so;
Table Name: City
**id** - 1
**name** - Cityx
**value** - cityx

as you can see value is exactly like name but in lowercase.
Now I'm trying to use $faker for php and wondering how I would do this
$factory->define(App\City::class, function ($faker) {
    return [
        'city' => $faker->city,
        'value' => , // make this lower case of $faker->city
    ];
});

A: $factory->define(App\City::class, function ($faker) {

    $city = $faker->city;

    return [
        'city' => $city,
        'value' => strtolower($city)
    ];
});


text:
Q: With Linqtosql, How to get a collection of Users based on an array of UserID's Using linqtosql, how would I get a colleciton of User objects, if I have an array of UserID's that I want to fetch?

A: You can use Contains to check if each UserID is in the array that you have.
int[] userIDs = ...
var users = db.Users.Where( u => userIDs.Contains( u.UserID ) );

A: If you want to avoid a SET operation and user chained ORs instead, you can use the PredicateBuilder to help you with that.
It goes something like this:
var userIDs = new[] { 1, 2, 3, 4, 5 };

// build multiple OR expressions
var filter = PredicateBuilder.False<User>();

foreach (var id in userIDs) {
    filter = filter.Or(x => x.UserID == id);
}

// fetch data
using (var db = new TheDataContext()) {

    var users = db.Users.Where(filter);

    // wham! - we have users now.

}

Take a look at the blog post to understand how it works. This basically creates a long chaining ORs for each user id in the list before passing it to a WHERE clauses.

A: Try this:
using(var db=new MyDataContext())
{
    var users=db.Users.Where(u=>userIds.Contains(u.Id));
}


text:
Q: React js component not listen to Jquery plugin I want to collaborate react with jquery as below
suppose I have this textarea that produce by react
var textarea = React.createClass({
   render : function(){
       return <textarea id="mytextarea"></textarea>;
   }
});

I want this textarea autosize by applying a plugin called "autosize", so I did this;
$("#mytextarea").autosize();

ReactDOM.render(<textarea/>, document.getElementById('form'));

note : If I make normal textarea (not by react DOM compoenent), the plugin work.
but not with react component.

A: The textarea is not rendered at the time you are calling $("#mytextarea").autosize();, so it doesn't actually exist yet. You might be successful in calling .autosize() in React's componentDidMount() method, which will be called after your component is rendered.
var textarea = React.createClass({
  componentDidMount: function() {
    $("#mytextarea").autosize();
  },
  render : function(){
    return <textarea id="mytextarea"></textarea>;
  }
});


text:
Q: Can you compare a combined string with a normal string? I made a form script with captcha, here is a part of it:
<?php
$captcha1 = rand(0,9);
$captcha2 = rand(0,9);
$captcha3 = rand(0,9);
$captcha4 = rand(0,9);
$captcha5 = rand(0,9);
$captchafinal = $captcha1.$captcha2.$captcha3.$captcha4.$captcha5;
$captchaimageholder = array("captcha0.png", "captcha1.png", "captcha2.png", "captcha3.png", "captcha4.png", "captcha5.png", "captcha6.png", "captcha7.png", "captcha8.png", "captcha9.png");

print_r($captchafinal);

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    if (!empty($_POST['afzender']) && !empty($_POST['subject']) && !empty($_POST['inhoud']) && !empty($_POST['captcha']) )
    {
        echo $_POST['captcha'];
        if ($captchafinal == $_POST['captcha'])
        {
            echo "
Succesvol verstuurd.
";
        }
    }
    else
    {
        echo "
Één of meer velden zijn niet correct ingevuld.
";
    }
}

The statement if ($captchafinal == $_POST['captcha']) evaluates to false, but I don't know why.

A: You probably have problem with following. You call php script, choose random 5 number and show this 5 pictures to client. Client type what they see and call php again. php AGAIN choose 5 random numbers and compare it with user input. But script not compare numbers displayed to client but new generated set.


text:
Q: Are reluctant and hesitant interchangeable? I kind of have an idea that "reluctant" and "hesitant" both have similar meanings, but I do not know the actual difference in the nuances they have. Could someone please teach me?

A: They have similar meanings, but they are not totally synonymous. In other words, they are not always interchangeable.
According to Online Etymology Dictionary, the noun form of reluctant "reluctance" comes from obsolete verb reluct which means "to struggle or rebel against" from Latin reluctari which means:

to struggle against, resist, make opposition

When you are reluctant to do something, it basically means you are not willing to do it (you are against it) or you don't want to do it.
However, when you are hesitant to do something, it could be either you don't like it or there is something that makes you wonder or pause for a while. The reason could be you are worried about consequences of your action, or you are not 100% sure about whether it is the right thing to do. That's why you have not made a decision yet and are hesitating.
You need to find example sentences on the internet and try to get yourself familiarized with them.


text:
Q: Why does this incorrect memoized fibonacci function work? Here's an incorrect implementation of memoized fibonacci:
long int fib(int n) {
    long int memo[100];
    if(n<2) {
        return n;
    }
    if(memo[n] != 0) {
        return memo[n];
    }
    else {
        memo[n] = fib(n - 1) + fib(n - 2);
        return memo[n];
    }
}

It is incorrect because the array memo is a brand new array each call and no memoization is occuring. The easiest fix is to make memo static. But, lo and behold, the code works!
I stepped through it in the debugger and memo is behaving as if it was static! It appears that the compiler generated code that is placing memo in the same memory space at every call as opposed to new fresh memory. Why is that?
Compiler used is Apple clang version 11.0.0 (clang-1100.0.33.12).

A: It is UB, but if we assume that stack of a fresh thread contains only zeroes,
then all values in memo[100] can be zeroes or remains of previous call of the function.
The effective algorithm might work like the following:
long int memo[100] = {0};

long int fib(int n) {
    if(n<2) {
        return n;
    }
    if(memo[n] != 0) {
        return memo[n];
    }
    else {
        memo[n] = fib(n - 1) + fib(n - 2);
        return memo[n];
    }
}

Except each layer of recursion have own 'memo[100]'.


text:
Q: Drag & Drop : Cursor in Chrome My problem is that in Chrome the cursor doesn't move with the draggable item. It works fine in IE.
I have jquery and jquery-ui 1.11.1 and this the script I am using
function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.target.innerHTML += ' '; // Add space so that there is no kerning...
    ev.dataTransfer.setData("Text", ev.target.id);
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("Text");
    ev.target.parentNode.replaceChild(document.getElementById(data), ev.target);
    document.getElementById(data).className = " ";
}

function drop(ev)
    {
      ev.preventDefault();
      var data=ev.dataTransfer.getData("Text");

      if(ev.target.getAttribute('data-drop') == data)
        ev.target.appendChild(document.getElementById(data));

    }

Maybe something is missing. Help would really be appreciated

A: The problem is the drag image ('shadow') being moved to the corner of the #word, correct?
It looks like Chrome is calculating the position wrong, may be because the <span> and <center> tags, I guess...
You can fix that using the setDragImage method, set the DragImage to be the target of the event and set the offset according to the click position, this will force Chrome to render it right:
function drag(ev) {
    ev.target.innerHTML += ' '; // Add space so that there is no kerning...
    ev.dataTransfer.setData("Text", ev.target.id);

    ev.dataTransfer.setDragImage(ev.target, ev.layerX - ev.target.offsetLeft, ev.layerY - ev.target.offsetTop);
}

It's working here http://jsfiddle.net/wv19zzsd/5/
(In my fiddle I changed the Type to 'text/plain' only to test if that was the cause of the issue, but it is not)


text:
Q: Updating EJS Include Methodology I should preface this by saying that I have never contributed to open source, and am very excited to start with ejs.
So I decided it was high time to update EJS's include methodology.
I decided to start by first adding the ability to include files from a relative or a absolute path, but I'm a little stuck because I am unsure how to access the app engine's (in this case express's) view root (in case it is different from "/views/"
So far, I have edited the resolveInclude function near line 280 in node_modules/ejs/lib/ejs.js and added 2 other functions. One that splits the path at the view root, which is currently only static, at "/views/"... obviously this needs to be dynamic, and set to the app engine's view root. Hence, my predicament...
/**
 * Resolve include `name` relative to `filename`.
 *
 * @param {String} name
 * @param {String} filename
 * @return {String}
 * @api private
 */
function resolveInclude(name, filename) {
    var path;
    if (0 == name.trim().indexOf('./')) path = dirname(filename);
    else path = resolveFromViewsRoot(dirname(filename), '/views/');
    path = join(path, name);
    return addExtension(path);
}
/**
 * Resolve include `name` relative to `root in '/views/ folder'`.
 *
 * @param {String} path
 * @param {String} root
 * @return {String}
 * @api private
 */
function resolveFromViewsRoot(path, root) {
    path = path.split(root);
    var nuPath = path.shift();
    nuPath = nuPath + root;
    return nuPath;
}
/**
 * Add ejs extension to file name
 *
 * @param {String} path
 * @return {String}
 * @api private
 */
function addExtension(path) {
    if (!extname(path)) return path + '.ejs';
}

any help would be greatly appreciated.


text:
Q: Azure Synapse Pipeline Execution based on file copy in DataLake I want to execute Azure Synapse Pipeline whenever a file is copied into a folder in data lake.
Can we do that and how can we achieve that?
Thanks,
Pavan.

A: You can trigger a pipeline (start pipeline execution) based on a file copied to datalake folder using storage event triggers. The storage event triggers can start the execution of pipeline based on a selected action.
You can follow the steps specified below to create a storage event trigger.

*

*Assuming you have a pipeline named 'pipeline1' in azure synapse which you want to execute based on file copied to datalake folder, click on trigger and select New/Edit.

*Choose a new trigger. Select trigger type as storage events and specify the datalake storage details on which you want to start trigger when a file is copied into it. Specify container name, blob path begins with and blob path ends with according to your datalake directory structure and type of files.

*Since you need to start pipeline when a blob file appears in datalake folder, check Blob Created event. Check start trigger on action, complete creating the trigger and publish it.
These steps allow you to create a storage event trigger for your pipeline based on the datalake storage. As soon as files are uploaded or copied to the specific directory of the datalake container, the pipeline execution will be started, and you can work on further steps. You can refer to the following document to understand more about event triggers.
https://learn.microsoft.com/en-us/azure/data-factory/how-to-create-event-trigger?tabs=data-factory


text:
Q: Why is the base type of an open generic type not open? Consider a piece of the code below:
public class A<T> { }

public class B<T> : A<T> { }

In such case:
var a = typeof(A<>).GenericTypeArguments.Length;

a has the value 0, which is not surprising. This, however, is somehow unexpected for me:
var b = typeof(B<>).BaseType.GenericTypeArguments.Length;

where b has the value 1. So it is closed using a non-existing type of name "T" and only doing GetGenericTypeDefinition on it makes it open again. Why is that?

A:
So it is closed using a non-existing type of name "T" and only doing GetGenericTypeArgument on it makes it open again. Why is that?

Because there is one type argument provided - the type parameter to B.
Look at how you're specifying the base class:
public class B<T> : A<T>

What's the T in A<T> if it's not a type argument? Just because the type argument is itself a type parameter doesn't mean it's not being specified as a type argument.
Consider this:
public class A<T1, T2> { }

public class B<T> : A<T, int> { }

Here, the base class of B<T> is A<T, int> - and you can determine that the int has been specified by asking for the type arguments. You can also show where the T comes from:
using System;
using System.Reflection;
using System.Collections.Generic;

public class A<T1, T2> { }

public class B<T> : A<T, int> { }

class Program
{
    static void Main()
    {
        var bT = typeof(B<>).GetTypeInfo().GenericTypeParameters[0];
        var listT = typeof(List<>).GetTypeInfo().GenericTypeParameters[0];
        var bBaseArguments = typeof(B<>).BaseType.GenericTypeArguments;
        Console.WriteLine(bBaseArguments[0] == bT); // True
        // Shows that the T from B<T> isn't the same as the T from List<T>
        Console.WriteLine(bBaseArguments[0] == listT); // False
        Console.WriteLine(bBaseArguments[1] == typeof(int)); // True
    }
}

A: The Type.GenericTypeArguments property returns the types used as generic parameters for a closed generic type, for open generic types, it returns an emtpy array.
The reason typeof(B<>).BaseType.GenericTypeArguments does not return an empty array is because it's not a open generic type.
To illustrate this behaviour, I used Type.MetadataToken to identify types.
Console.WriteLine(typeof(A<>).GetGenericArguments()[0].MetadataToken);
Console.WriteLine(typeof(B<>).GetGenericArguments()[0].MetadataToken);
Console.WriteLine(typeof(B<>).BaseType.GetGenericArguments()[0].MetadataToken);

This prints the following on the screen (numbers will vary, but equality will stay the same):
704643073
704643074
704643074

This indicates that the BaseType of type B<> is indeed a closed type having its generic parameter the 'virtual' generic type of class A<>.


text:
Q: Character encoding issues - Oracle SQL I made a simple query to a remote database. The table where I make query has all fields with VARCHAR2. However, some fields returns "?" in characters like º, £. I checked enconding and get:
NLS_CHARACTERSET: AL32UTF8
NLS_NCHAR_CHARACTERSET:AL16UTF16

Checking my /etc/default/locale file. These are the results:
LANG="en_US.UTF-8"
LC_NUMERIC="pt_BR.UTF-8"
LC_TIME="pt_BR.UTF-8"
LC_MONETARY="pt_BR.UTF-8"
LC_PAPER="pt_BR.UTF-8"
LC_NAME="pt_BR.UTF-8"
LC_ADDRESS="pt_BR.UTF-8"
LC_TELEPHONE="pt_BR.UTF-8"
LC_MEASUREMENT="pt_BR.UTF-8"
LC_IDENTIFICATION="pt_BR.UTF-8"

The enconding from both edges are UTF-8. Is there another configuration that I missing?

A: When you say 'some fields return "?" in characters like ...' I assume that is shown on your screen, right? You don't know what is REALLY returned, you only know what's on your screen.
To see what is REALLY returned, you could do something like
select dump('£500') from dual;

DUMP('£500')
--------------------------
Typ=96 Len=4: 163,53,48,48

EDIT: As discussed in the comments below, if you type EXACTLY that command at your terminal and you do, in fact, have a display problem, you will see garbage on the way in. Rather, to see what is stored in the database, you must refer to an actual table, and a column that has those string values in it. For example if the column name is COL1 in the table TBL, and there is also an ID column and for ID = 1000 you have a COL1 value with the pound sign in it, run
select dump(COL1) from TBL where ID = 1000;

Obviously, there are no issues with the INPUT since the input no longer has a pound sign in it (like my first example did). But on the way out, the DUMP may show the proper character is there - however your display is not able to show it correctly.
END EDIT
If you see the code 163 in the DUMP, that means the pound sign is stored correctly in the database, and the issue is just how it is displayed on your screen. In that case, you may have an issue with your NLS_LANG setting. There is excellent information here:
http://www.oracle.com/technetwork/products/globalization/nls-lang-099431.html
If you find that you have to work with different character sets often, you may benefit from reading this article carefully. It will show you how to find out what your current character set is, how to change it, and why the "obvious" things one would look at are in fact not very helpful. The issue is not too complicated, but not trivial either.